Professional Documents
Culture Documents
GTK+ & Gnome Application Development
GTK+ & Gnome Application Development
GTK+ & Gnome Application Development
Development
Havoc Pennington
Red Hat Advanced Development Labs
Table of Contents
I. Overview...........................................................................................................................24
1. Introduction ............................................................................................................24
What is Gnome?................................................................................................24
The Gnome Development Framework..........................................................24
Non-Gnome Libraries.............................................................................25
glib ...................................................................................................25
GTK+ ...............................................................................................25
ORBit ...............................................................................................25
Imlib ................................................................................................26
Gnome Libraries......................................................................................26
libgnome .........................................................................................26
libgnomeui ....................................................................................26
libgnorba ......................................................................................27
libzvt .............................................................................................27
libart_lgpl ..................................................................................27
Other Libraries ........................................................................................27
gnome-print ..................................................................................27
gnome-xml ......................................................................................27
Guile ................................................................................................28
Bonobo ............................................................................................28
A Word About Header Files ..................................................................28
Structure of the Book........................................................................................28
2. glib: Portability and Utility ...................................................................................30
Basics ..................................................................................................................30
Type Definitions ......................................................................................30
Frequently Used Macros ........................................................................30
Debugging Macros..................................................................................31
Memory ....................................................................................................33
String Handling.......................................................................................34
Data Structures..................................................................................................37
Lists ...........................................................................................................37
Trees ..........................................................................................................41
GTree ...............................................................................................41
GNode .............................................................................................43
Hash Tables ..............................................................................................46
Other Features...................................................................................................48
3. GTK+ Basics ............................................................................................................50
Whirlwind Tour of GTK+ ................................................................................50
A Complete Hello, World ......................................................................50
Compiling Hello, World ...............................................................51
How It Works...........................................................................................52
Initialization ...................................................................................52
Widgets ...........................................................................................52
Signals .............................................................................................53
Entering the Main Loop................................................................53
More on Signals and Callbacks ...................................................54
Containers And Widget Layout .....................................................................55
Size Allocation .........................................................................................56
Requisition......................................................................................56
Allocation........................................................................................56
GtkBox.......................................................................................................57
GtkBox Layout Details ..................................................................58
Non-Homogeneous Box Packing Patterns ................................59
Homogeneous Box Packing Patterns..........................................60
Widgets.............................................................................................................299
GtkWidget ..............................................................................................299
Library...........................................................................................299
Header File ...................................................................................299
Description ...................................................................................299
GtkContainer........................................................................................299
Library...........................................................................................299
Header File ...................................................................................299
Description ...................................................................................300
GtkBin.....................................................................................................300
Library...........................................................................................300
Header File ...................................................................................300
Description ...................................................................................300
GtkWindow ..............................................................................................300
Library...........................................................................................300
Header File ...................................................................................300
Description ...................................................................................300
GnomeDialog ..........................................................................................301
Library...........................................................................................301
Header File ...................................................................................301
Description ...................................................................................301
GnomeAbout ............................................................................................301
Library...........................................................................................301
Header File ...................................................................................301
Description ...................................................................................301
GnomeMessageBox .................................................................................301
Library...........................................................................................302
Header File ...................................................................................301
Description ...................................................................................302
GnomePropertyBox ...............................................................................302
Library...........................................................................................302
Header File ...................................................................................302
Description ...................................................................................302
GnomeScores ..........................................................................................302
Library...........................................................................................302
Header File ...................................................................................302
Description ...................................................................................302
GnomeApp ................................................................................................303
Library...........................................................................................303
Header File ...................................................................................303
Description ...................................................................................303
GtkDialog ..............................................................................................303
Library...........................................................................................303
Header File ...................................................................................303
Description ...................................................................................303
GnomeFontSelector .............................................................................303
Library...........................................................................................303
Header File ...................................................................................304
Description ...................................................................................304
GtkInputDialog ...................................................................................304
Library...........................................................................................304
Header File ...................................................................................304
Description ...................................................................................304
GtkColorSelectionDialog ................................................................304
Library...........................................................................................304
Header File ...................................................................................304
Description ...................................................................................304
GtkFileSelection ...............................................................................305
Library...........................................................................................305
Header File ...................................................................................305
Description ...................................................................................305
GtkFontSelectionDialog ..................................................................306
Library...........................................................................................306
Header File ...................................................................................306
Description ...................................................................................306
GtkPlug ..................................................................................................306
Library...........................................................................................307
Header File ...................................................................................306
Description ...................................................................................307
GtkButton ..............................................................................................307
Library...........................................................................................307
Header File ...................................................................................307
Description ...................................................................................307
GnomeColorPicker ...............................................................................307
Library...........................................................................................308
Header File ...................................................................................308
Description ...................................................................................308
GnomeFontPicker .................................................................................308
Library...........................................................................................308
Header File ...................................................................................308
Description ...................................................................................308
GnomeHRef ..............................................................................................308
Library...........................................................................................308
Header File ...................................................................................308
Description ...................................................................................308
GtkToggleButton .................................................................................309
Library...........................................................................................309
Header File ...................................................................................309
Description ...................................................................................309
GtkCheckButton ...................................................................................309
Library...........................................................................................309
Header File ...................................................................................309
Description ...................................................................................309
GtkRadioButton ...................................................................................310
Library...........................................................................................310
Header File ...................................................................................310
Description ...................................................................................310
GtkOptionMenu .....................................................................................311
Library...........................................................................................311
Header File ...................................................................................311
Description ...................................................................................311
GnomeDockItem .....................................................................................311
Library...........................................................................................311
Header File ...................................................................................312
Description ...................................................................................312
GtkAlignment........................................................................................312
Library...........................................................................................312
Header File ...................................................................................312
Description ...................................................................................312
GtkFrame ................................................................................................312
Library...........................................................................................312
Header File ...................................................................................312
Description ...................................................................................312
GtkAspectFrame ...................................................................................313
Library...........................................................................................313
Header File ...................................................................................313
Description ...................................................................................313
GtkItem ..................................................................................................314
Library...........................................................................................314
Header File ...................................................................................314
Description ...................................................................................314
GtkMenuItem ..........................................................................................314
Library...........................................................................................314
Header File ...................................................................................314
Description ...................................................................................314
GtkCheckMenuItem ...............................................................................314
Library...........................................................................................314
Header File ...................................................................................314
Description ...................................................................................314
GtkRadioMenuItem ...............................................................................315
Library...........................................................................................315
Header File ...................................................................................315
Description ...................................................................................315
GtkPixmapMenuItem .............................................................................315
Library...........................................................................................315
Header File ...................................................................................315
Description ...................................................................................315
GtkTearoffMenuItem ...........................................................................316
Library...........................................................................................316
Header File ...................................................................................316
Description ...................................................................................316
GtkListItem ..........................................................................................316
Library...........................................................................................316
Header File ...................................................................................316
Description ...................................................................................316
GtkTreeItem ..........................................................................................316
Library...........................................................................................317
Header File ...................................................................................317
Description ...................................................................................317
GtkEventBox ..........................................................................................317
Library...........................................................................................317
Header File ...................................................................................317
Description ...................................................................................317
GtkHandleBox........................................................................................317
Library...........................................................................................317
Header File ...................................................................................317
Description ...................................................................................317
GtkScrolledWindow .............................................................................318
Library...........................................................................................318
Header File ...................................................................................318
Description ...................................................................................318
GtkViewport ..........................................................................................318
Library...........................................................................................319
Header File ...................................................................................318
Description ...................................................................................319
GtkBox.....................................................................................................319
Library...........................................................................................319
Header File ...................................................................................319
10
Description ...................................................................................319
GtkHBox ..................................................................................................319
Library...........................................................................................319
Header File ...................................................................................319
Description ...................................................................................319
GnomeAppBar ..........................................................................................320
Library...........................................................................................320
Header File ...................................................................................320
Description ...................................................................................320
GnomeDateEdit .....................................................................................320
Library...........................................................................................320
Header File ...................................................................................320
Description ...................................................................................320
GtkCombo ................................................................................................321
Library...........................................................................................321
Header File ...................................................................................321
Description ...................................................................................321
GnomeEntry ............................................................................................321
Library...........................................................................................321
Header File ...................................................................................321
Description ...................................................................................321
GnomeFileEntry ...................................................................................322
Library...........................................................................................322
Header File ...................................................................................322
Description ...................................................................................322
GnomeNumberEntry ...............................................................................322
Library...........................................................................................322
Header File ...................................................................................322
Description ...................................................................................322
GnomeProcBar........................................................................................322
Library...........................................................................................322
Header File ...................................................................................323
Description ...................................................................................323
GtkStatusbar........................................................................................323
Library...........................................................................................323
Header File ...................................................................................323
Description ...................................................................................323
GtkVBox ..................................................................................................323
Library...........................................................................................323
Header File ...................................................................................323
Description ...................................................................................323
GnomeCalculator .................................................................................323
Library...........................................................................................324
Header File ...................................................................................323
Description ...................................................................................324
GnomeGuru ..............................................................................................324
Library...........................................................................................324
Header File ...................................................................................324
Description ...................................................................................324
GnomeIconEntry ...................................................................................324
Library...........................................................................................324
Header File ...................................................................................324
Description ...................................................................................324
GnomeIconSelection ...........................................................................325
Library...........................................................................................325
Header File ...................................................................................325
11
Description ...................................................................................325
GnomeLess ..............................................................................................326
Library...........................................................................................326
Header File ...................................................................................326
Description ...................................................................................326
GnomePaperSelector ...........................................................................326
Library...........................................................................................326
Header File ...................................................................................326
Description ...................................................................................326
GnomePixmapEntry ...............................................................................327
Library...........................................................................................327
Header File ...................................................................................327
Description ...................................................................................327
GnomeSpell ............................................................................................327
Library...........................................................................................327
Header File ...................................................................................327
Description ...................................................................................327
GtkColorSelection .............................................................................327
Library...........................................................................................328
Header File ...................................................................................327
Description ...................................................................................328
GtkGammaCurve .....................................................................................328
Library...........................................................................................328
Header File ...................................................................................328
Description ...................................................................................328
GtkButtonBox........................................................................................328
Library...........................................................................................329
Header File ...................................................................................328
Description ...................................................................................329
GtkHButtonBox .....................................................................................329
Library...........................................................................................329
Header File ...................................................................................329
Description ...................................................................................329
GtkVButtonBox .....................................................................................329
Library...........................................................................................329
Header File ...................................................................................329
Description ...................................................................................329
GtkLayout ..............................................................................................329
Library...........................................................................................330
Header File ...................................................................................330
Description ...................................................................................330
GnomeCanvas ..........................................................................................330
Library...........................................................................................330
Header File ...................................................................................330
Description ...................................................................................330
GnomeIconList .....................................................................................331
Library...........................................................................................331
Header File ...................................................................................331
Description ...................................................................................331
GnomeDockBand .....................................................................................332
Library...........................................................................................332
Header File ...................................................................................332
Description ...................................................................................332
GnomeDock ..............................................................................................332
Library...........................................................................................333
Header File ...................................................................................332
12
Description ...................................................................................333
GtkCList ................................................................................................333
Library...........................................................................................333
Header File ...................................................................................333
Description ...................................................................................333
GtkCTree ................................................................................................334
Library...........................................................................................334
Header File ...................................................................................334
Description ...................................................................................334
GtkFixed ................................................................................................335
Library...........................................................................................335
Header File ...................................................................................335
Description ...................................................................................335
GtkNotebook ..........................................................................................335
Library...........................................................................................336
Header File ...................................................................................335
Description ...................................................................................336
GtkFontSelection ...............................................................................336
Library...........................................................................................336
Header File ...................................................................................336
Description ...................................................................................336
GtkPaned ................................................................................................337
Library...........................................................................................337
Header File ...................................................................................337
Description ...................................................................................337
GtkHPaned ..............................................................................................337
Library...........................................................................................337
Header File ...................................................................................337
Description ...................................................................................337
GtkVPaned ..............................................................................................337
Library...........................................................................................338
Header File ...................................................................................338
Description ...................................................................................338
GtkList ..................................................................................................338
Library...........................................................................................338
Header File ...................................................................................338
Description ...................................................................................338
GtkMenuShell........................................................................................338
Library...........................................................................................338
Header File ...................................................................................338
Description ...................................................................................338
GtkMenuBar ............................................................................................339
Library...........................................................................................339
Header File ...................................................................................339
Description ...................................................................................339
GtkMenu ..................................................................................................339
Library...........................................................................................339
Header File ...................................................................................339
Description ...................................................................................339
GtkPacker ..............................................................................................339
Library...........................................................................................339
Header File ...................................................................................340
Description ...................................................................................340
GtkSocket ..............................................................................................340
Library...........................................................................................340
Header File ...................................................................................340
13
Description ...................................................................................340
GtkTable ................................................................................................340
Library...........................................................................................340
Header File ...................................................................................340
Description ...................................................................................340
GtkTed.....................................................................................................340
Library...........................................................................................341
Header File ...................................................................................340
Description ...................................................................................341
GtkToolbar ............................................................................................341
Library...........................................................................................341
Header File ...................................................................................341
Description ...................................................................................341
GtkTree ..................................................................................................341
Library...........................................................................................341
Header File ...................................................................................341
Description ...................................................................................341
GnomeAnimator .....................................................................................342
Library...........................................................................................342
Header File ...................................................................................342
Description ...................................................................................342
GnomePixmap ..........................................................................................342
Library...........................................................................................343
Header File ...................................................................................342
Description ...................................................................................343
GnomeStock ............................................................................................343
Library...........................................................................................343
Header File ...................................................................................343
Description ...................................................................................343
GtkMisc ..................................................................................................343
Library...........................................................................................343
Header File ...................................................................................343
Description ...................................................................................343
GtkLabel ................................................................................................344
Library...........................................................................................344
Header File ...................................................................................344
Description ...................................................................................344
GtkAccelLabel .....................................................................................344
Library...........................................................................................344
Header File ...................................................................................344
Description ...................................................................................344
GtkClock ................................................................................................345
Library...........................................................................................345
Header File ...................................................................................345
Description ...................................................................................345
GtkTipsQuery........................................................................................345
Library...........................................................................................345
Header File ...................................................................................345
Description ...................................................................................345
GtkArrow ................................................................................................346
Library...........................................................................................346
Header File ...................................................................................346
Description ...................................................................................346
GtkImage ................................................................................................346
Library...........................................................................................346
Header File ...................................................................................346
14
Description ...................................................................................346
GtkPixmap ..............................................................................................346
Library...........................................................................................346
Header File ...................................................................................346
Description ...................................................................................346
GtkCalendar ..........................................................................................347
Library...........................................................................................347
Header File ...................................................................................347
Description ...................................................................................347
GtkDrawingArea ...................................................................................347
Library...........................................................................................347
Header File ...................................................................................347
Description ...................................................................................347
GtkCurve ................................................................................................348
Library...........................................................................................348
Header File ...................................................................................348
Description ...................................................................................348
GtkDial ..................................................................................................348
Library...........................................................................................348
Header File ...................................................................................348
Description ...................................................................................348
GtkEditable ..........................................................................................349
Library...........................................................................................349
Header File ...................................................................................349
Description ...................................................................................349
GtkEntry ................................................................................................349
Library...........................................................................................349
Header File ...................................................................................349
Description ...................................................................................349
GtkSpinButton .....................................................................................350
Library...........................................................................................350
Header File ...................................................................................350
Description ...................................................................................350
GtkText ..................................................................................................350
Library...........................................................................................350
Header File ...................................................................................350
Description ...................................................................................350
GtkRuler ................................................................................................351
Library...........................................................................................351
Header File ...................................................................................351
Description ...................................................................................351
GtkHRuler ..............................................................................................352
Library...........................................................................................352
Header File ...................................................................................352
Description ...................................................................................352
GtkVRuler ..............................................................................................352
Library...........................................................................................352
Header File ...................................................................................352
Description ...................................................................................352
GtkRange ................................................................................................353
Library...........................................................................................353
Header File ...................................................................................353
Description ...................................................................................353
GtkScale ................................................................................................353
Library...........................................................................................353
Header File ...................................................................................353
15
Description ...................................................................................353
GtkHScale ..............................................................................................353
Library...........................................................................................354
Header File ...................................................................................354
Description ...................................................................................354
GtkVScale ..............................................................................................354
Library...........................................................................................354
Header File ...................................................................................354
Description ...................................................................................354
GtkScrollbar........................................................................................354
Library...........................................................................................354
Header File ...................................................................................354
Description ...................................................................................354
GtkHScrollbar .....................................................................................355
Library...........................................................................................355
Header File ...................................................................................355
Description ...................................................................................355
GtkVScrollbar .....................................................................................355
Library...........................................................................................355
Header File ...................................................................................355
Description ...................................................................................355
GtkSeparator........................................................................................355
Library...........................................................................................355
Header File ...................................................................................355
Description ...................................................................................355
GtkHSeparator .....................................................................................355
Library...........................................................................................356
Header File ...................................................................................356
Description ...................................................................................356
GtkVSeparator .....................................................................................356
Library...........................................................................................356
Header File ...................................................................................356
Description ...................................................................................356
GtkPreview ............................................................................................356
Library...........................................................................................356
Header File ...................................................................................356
Description ...................................................................................356
GtkProgress ..........................................................................................357
Library...........................................................................................357
Header File ...................................................................................357
Description ...................................................................................357
GtkProgressBar ...................................................................................357
Library...........................................................................................357
Header File ...................................................................................357
Description ...................................................................................357
ZvtTerm ..................................................................................................357
Library...........................................................................................358
Header File ...................................................................................357
Description ...................................................................................358
Canvas Items ...................................................................................................358
GnomeCanvasItem ...............................................................................359
Library...........................................................................................359
Header File ...................................................................................358
Description ...................................................................................359
GnomeCanvasRE ..................................................................................359
Library...........................................................................................359
16
17
Library...........................................................................................365
Header File ...................................................................................365
Description ...................................................................................365
GnomeMDI ............................................................................................365
Library...........................................................................................365
Header File ...................................................................................365
Description ...................................................................................365
GtkData...................................................................................................365
Library...........................................................................................366
Header File ...................................................................................365
Description ...................................................................................366
GtkAdjustment ......................................................................................366
Library...........................................................................................366
Header File ...................................................................................366
Description ...................................................................................366
GtkTooltips.............................................................................................366
Library...........................................................................................366
Header File ...................................................................................366
Description ...................................................................................366
GtkItemFactory......................................................................................367
Library...........................................................................................367
Header File ...................................................................................367
Description ...................................................................................367
15. Table of Header Files .........................................................................................368
16. Frequently Asked Questions ............................................................................375
Questions, with Answers ..............................................................................375
How do I make my application beep? ...............................................375
When do I need to destroy my widgets? ...........................................375
When I turn on memory profiling in glib, my application becomes
unstable. What gives? .................................................................375
To create a custom display, I want to place widgets in arbitrary
locations, or move them around rapidly, or draw to them
directly. How? ..............................................................................375
Why does my memory debugging tool show memory leaks in glib?
375
I get a bunch of "assertion failed" warnings from GTK+. What
causes these? ................................................................................376
Why are some things in Gnome rather than GTK+? .......................376
How can I center a window on the screen?.......................................376
Is there a widget that does printing?..................................................377
When I fork(), I get a bunch of warnings and my program crashes.
Whats going on? .........................................................................377
When do I need to call gtk_widget_realize() vs.
gtk_widget_show()? .................................................................377
When creating a pixmap, I get the warning: Creating pixmap
from xpm with NULL window and colormap. Whats
wrong?...........................................................................................378
How can I separate the GUI from the rest of my application?.......378
I dont like the default appearance of [some widget]. How do I
change its appearance? ...............................................................379
Thanks for the lecture, but I have a really good reason to change the
appearance of a widget. How do I override the theme? .......380
Why are signals specified as strings rather than integers or some
sort of macro?...............................................................................380
Why is GTK+ written in C? .................................................................380
My motion event handler is only invoked once; why is that? .......380
18
19
List of Tables
4-1. Standard make targets ..................................................................................................82
6-1. GnomeUIInfoType Values .........................................................................................107
9-1. The GTK+ Fundamental Types ................................................................................136
10-1. GdkWindowAttr Fields ...........................................................................................166
10-2. GdkEventType Values..............................................................................................174
10-3. Event Masks ..............................................................................................................175
10-4. GtkWidget Events.....................................................................................................177
10-5. Modifier Masks for Key and Button Events .........................................................180
10-6. GC Attributes ............................................................................................................202
12-1. GnomeCanvasRE Arguments.................................................................................268
12-2. GnomeCanvasLine Arguments ..............................................................................270
12-3. GnomeCanvasPolygon Arguments .......................................................................271
12-4. GnomeCanvasImage Arguments...........................................................................272
12-5. GnomeCanvasText Arguments ..............................................................................273
12-6. GnomeCanvasWidget Arguments .........................................................................275
15-1. glib, GTK+, and Gnome Header Files ...................................................................368
List of Figures
2-1. Familiar C Macros ........................................................................................................31
2-2. Macros for storing integers in pointers .....................................................................31
2-3. Precondition Checks ....................................................................................................32
2-4. Assertions ......................................................................................................................32
2-5. glib memory allocation ................................................................................................34
2-6. Allocation macros.........................................................................................................34
2-7. Portability Wrappers ....................................................................................................35
2-8. In-place string modifications ......................................................................................35
2-9. String Conversions .......................................................................................................36
2-10. Allocating Strings .......................................................................................................36
2-11. Concatenating strings.................................................................................................37
2-12. Manipulating NULL-terminated string vectors.....................................................37
2-13. Changing linked list contents ...................................................................................39
2-14. Accessing data in a linked list ..................................................................................40
2-15. Manipulating a linked list .........................................................................................40
2-16. Sorted lists ...................................................................................................................41
2-17. Creating and destroying balanced binary trees .....................................................42
2-18. Manipulating GTree contents ...................................................................................42
2-19. Determining the size of a GTree ...............................................................................42
2-20. Traversing GTree.........................................................................................................43
2-21. Accessing GNode members ......................................................................................43
2-22. Creating a GNode.......................................................................................................43
2-23. Building a GNode tree ...............................................................................................44
2-24. Building a GNode.......................................................................................................44
2-25. Destroying a GNode ..................................................................................................44
2-26. Predicates for GNode.................................................................................................45
2-27. GNode Properties .......................................................................................................45
2-28. Accessing a GNode ....................................................................................................46
2-29. GHashTable .................................................................................................................47
2-30. Pre-written hashes/comparisons .............................................................................47
2-31. Manipulating GHashTable ........................................................................................47
2-32. Freezing and thawing GHashTable .........................................................................48
3-1. Hello, World ..................................................................................................................50
20
21
22
23
Chapter 1. Introduction
This chapter gives you an overview of the technologies described in this book.
What is Gnome?
Gnome is a free (or "open source") software development project started in 1997 by
Miguel de Icaza of the Mexican Autonomous National University and a small team
of programmers from around the world. Inspired by the success of the similar K
Desktop Environment (KDE) project, the burgeoning popularity of the GNU/Linux
operating system, and and the power of the GTK+ graphical toolkit, Gnome grew
quickly within a year, hundreds of programmers were involved and many thousands of lines of code had been written. Gnome has become a powerful framework
for GUI application development which runs on any modern variety of UNIX.
"Gnome" is actually an acronym: GNU Network Object Model Environment. Originally, the project was intended to create a framework for application objects, similar
to Microsofts OLE and COM technologies. However, the scope of the project rapidly
expanded; it became clear that substantial groundwork was required before the "network object" part of the name could become reality. The latest development versions
of Gnome include an object embedding architecture called Bonobo, and Gnome 1.0
included a fast, light CORBA 2.2 ORB called ORBit.
Gnome is a part of the GNU Project, whose overall goal is developing a free operating system (named GNU) plus applications to go with it. GNU stands for "GNUs
Not UNIX", a humorous way of saying that the GNU operating system is UNIXcompatible. You can learn more about GNU at http://www.gnu.org.
Gnome has two important faces. From the users perspective, it is an integrated desktop environment and application suite. From the programmers perspective, it is an
application development framework (made up of numerous useful libraries). Applications written with the Gnome libraries run fine even if the user isnt running the
desktop environment, but they integrate nicely with the Gnome desktop if its available.
The desktop environment includes a file manager, a "panel" for task switching, launching programs, and docking applets, a "control center" for configuration, and several
smaller bells and whistles. These programs hide the traditional UNIX shell behind
an easy-to-use graphical interface.
Gnomes development framework makes it possible to write consistent, easy-to-use,
interoperable applications. The X Window System designers made a deliberate decision not to impose any user interface policy on developers; Gnome adds a "policy
layer," creating a consistent look-and-feel. Finished Gnome applications work well
with the Gnome desktop, but can also be used "standalone" users only need to install Gnomes shared libraries. Its even possible to write Gnome applications which
do not rely on the X Window System; you might want to provide a non-graphical
CORBA service, for example.
This book is about Gnome from a developers point of view; it describes how to write
a Gnome application using the Gnome libraries and tools.
24
Chapter 1. Introduction
Non-Gnome Libraries
Taking full advantage of the free software tradition, Gnome didnt start from scratch.
It uses several libraries which are maintained separately from the Gnome project.
These are a part of the Gnome application development framework, and you can
count on their presence in a Gnome environment.
glib
glib is the base of the Gnome infrastructure. Its a C utility library, providing routines
to create and manipulate common data structures. It also addresses portability issues;
for example, many systems lack the snprintf() function, but glib contains an implementation called g_snprintf() which is both guaranteed to exist on all platforms
and slightly safer than snprintf() (it always NULL-terminates the target buffer).
Gnome 1.0 uses glib version 1.2 and works with any glib in the 1.2 series (1.2.1, 1.2.2,
etc.). All glib versions beginning with 1.2 are compatible bug-fix releases.
GTK+
GTK+, or the Gimp Tool Kit, is the GUI toolkit used in Gnome applications. GTK+
was originally written for the Gimp (GNU Image Manipulation Program http://www.gimp.org),
but has become a general-purpose library. GTK+ depends on glib.
The GTK+ package includes GDK, the Gimp Drawing Kit, which is a simplification
and abstraction of the low-level X Window System libraries. Since GTK+ uses GDK
rather than calling X directly, a port of GDK permits GTK+ to run on windowing
systems other than X with relatively few modifications. GTK+ and the Gimp have
already been ported to the Win32 platform in this way.
GTK+ provides several features for Gnome applications:
A GtkWidget object written using the object system, which defines the interface
GTK+s graphical components implement.
25
Chapter 1. Introduction
Gnome 1.0 is based on GTK+ version 1.2. All GTK+ versions beginning with 1.2 are
compatible bug-fix releases; 1.2.1, for example.
ORBit
ORBit is a CORBA 2.2 ORB written in C. It was designed to be small and fast compared to other ORBs, and supports the C language mapping. ORBit is implemented
as a suite of libraries.
CORBA, or Common Object Request Broker Architecture, is a specification for Object
Request Brokers, or ORBs. An ORB is much like a dynamic linker, but it works with
objects, rather than subroutines. At runtime, a program can request the services of a
particular object; the ORB locates the object and creates a connection between it and
the program. For example, an email program might request an addressbook object,
and use it to look up a persons name. Unlike dynamic linking, CORBA works fine
across a network, and even allows different programming languages and operating
systems to interact with one another. If youre familiar with DCOM on the Windows
operating system, CORBA is analagous.
Imlib
Imlib ("Image Library") provides routines for loading, saving, displaying, and scaling images in a variety of popular formats (including GIF, JPEG, PNG, and TIFF). It
comes in two versions; an Xlib-only version, and a GDK-based version. Gnome uses
the GDK version.
Gnome Libraries
The libraries in this section are a part of the gnome-libs package and were developed
specifically for the Gnome Project.
libgnome
libgnome is a collection of non-GUI-related routines for use by Gnome applications.
It includes code to parse configuration files, for example. It also includes interfaces to
some external facilities, such as internationalization (via the GNU gettext package),
argument parsing (via the popt package), and sound (via the Enlightenment Sound
Daemon, esound). The gnome-libs package takes care of interacting with these external libraries, so the programmer does not need to concern herself with their implementation or availability.
libgnomeui
libgnomeui collects GUI-related Gnome code. It consists primarily of widgets de-
signed to enhance and extend GTK+. Gnome widgets generally impose user interface
policy, which permits a more convenient API (since there is less for the programmer
to specify). It also results in applications with more consistent interfaces, of course.
Highlights of libgnomeui include:
26
Chapter 1. Introduction
The GnomeApp widget, which makes it easy to create a nice main window for your
application. It uses another widget called GnomeDock which enables users to rearrange and "undock" toolbars.
The GnomeCanvas widget which makes it easy to write intricate, flicker-free custom displays.
The Gnome stock pixmaps (icons for open, close, save, and other operations).
libgnorba
libgnorba provides CORBA-related facilities, including a security mechanism and
libzvt
This small library contains a terminal widget (ZvtTerm) you can use in your Gnome
programs.
libart_lgpl
This library contains graphics rendering routines by Raph Levien. The routines included here are released under the GNU Library General Public License and used
in the GnomeCanvas widget; Raph Levien also sells an enhanced proprietary version. libart_lgpl provides antialiasing, microtile refresh regions, and other magic.
In essence it is a vector graphics rasterization library, functionally analogous to the
PostScript language.
Other Libraries
These libraries are commonly used in Gnome applications, but are not a part of
gnome-libs proper.
gnome-print
gnome-print is still somewhat experimental, but very promising. It uses libart_lgpl
and works nicely with GnomeCanvas. It provides virtual output devices (called "print
gnome-xml
gnome-xml is a non-validating XML engine written by Daniel Veillard of the World
Wide Web Consortium. It can parse XML into a tree structure, and output a tree struc-
27
Chapter 1. Introduction
ture as XML. Its useful for any application that needs to load and save structured
data; many Gnome applications use it as a file format. This library does not depend
on any of the others, not even glib so it is tied to Gnome in name only. However,
you can expect most Gnome users to have it installed, so it should not inconvenience
your users if your application uses this library.
Guile
Guile is an implementation of the Scheme programming language in a library, so that
any application can have an embedded Scheme interpreter. It is the official extension
language of the GNU Project, and is used by several Gnome applications. Adding
an extension language to your application might sound complex, but Guile makes
it almost trivial. (Several Gnome applications support Perl and Python as well; it is
usually easy to support several languages once you implement the first. But Guile
has a special place in the Gnome developers hearts.)
Bonobo
At press time, the Gnome hackers were putting the finishing touches on Bonobo.
Bonobo is a compound document architecture in the tradition of Microsofts OLE; it
allows you to embed charts in spreadsheets, for example. It will be used pervasively
throughout Gnome; any application will be able to display MIME-typed data such
as plain text, HTML, or images by asking the Gnome libraries for an appropriate
Bonobo component. Look for Bonobo technology in the next major Gnome release.
28
Right now youre reading Part 1. This chapter gives you an overview of the Gnome
application development framework. The following two chapters quickly introduce glib and GTK+ if youre already familiar with GTK+ programming, you
may want to move directly to Part 2.
Chapter 1. Introduction
Part 3 describes some advanced topics, including the internals of the GTK+ object
and type system, writing a custom GtkWidget subclass, and using the GnomeCanvas widget. It also covers GDK.
The appendices include a map of the GTK+ and Gnome object hierarchy, with a
short description of each object; a map of the GTK+ and Gnome header files; and
some pointers to online programming resources.
This book assumes some knowledge of GTK+ programming; chapters 2 and 3 will
give you a quick overview if your knowledge is minimal, but they move very quickly.
Most of the specific widgets in GTK+ are not covered. The book is intended to introduce Gnome programming, and some advanced GTK+ topics; it is a supplement to
an introductory GTK+ book.
Due to time and space limitations, only the central Gnome libraries are covered; in
particular, CORBA, printing, XML, plugins, and scripting are not covered. Most large
applications will use these features in addition to the core libraries.
29
Basics
glib provides substitutes for many standard and commonly-used C language constructs. This section describes glibs fundamental type definitions, macros, memory
allocation routines, and string utility functions.
Type Definitions
Rather than using Cs standard types (int, long, etc.) glib defines its own. These serve
a variety of purposes. For example, gint32 is guaranteed to be 32 bits wide, something
no standard C type can ensure. guint is simply easier to type than unsigned. A few
of the typedefs exist only for consistency; for example, gchar is always equivalent to
the standard char.
The following primitive types are defined by glib:
gint8, guint8, gint16, guint16, gint32, guint32, gint64, guint64these give you integers of a guaranteed size. Not all platforms provide 64-bit integers; if a platform
has them, glib will define G_HAVE_GINT64. (If it isnt obvious, the guint types are
unsigned, the gint types are signed.)
gboolean is useful to make your code more readable, since C has no bool type.
gpointer may be more convenient to type than void *. gconstpointer gives you
const void*. (const gpointer will not do what you typically mean it to; spend some
time with a good book on C if you dont see why.)
30
#include <glib.h>
MAX( a
MIN( a
ABS( x
CLAMP(
, b );
, b );
);
x , low ,
high );
Be careful, though; these macros allow you to store an integer in a pointer, but storing
a pointer in an integer will not work. To do that portably, you must store the pointer
in a long. (Its undoubtedly a bad idea to do so, however.)
#include <glib.h>
GINT_TO_POINTER(p);
GPOINTER_TO_INT(p);
GUINT_TO_POINTER(p);
GPOINTER_TO_UINT(p);
Debugging Macros
glib has a nice set of macros you can use to enforce invariants and preconditions in
your code. GTK+ uses these liberallyone of the reasons its so stable and easy to
use. They all disappear when you define G_DISABLE_CHECKS or G_DISABLE_ASSERT,
so theres no performance penalty in production code. Using these liberally is a very,
very good idea. Youll find bugs much faster if you do. You can even add assertions
and checks whenever you find a bug to be sure the bug doesnt reappear in future
versionsthis complements a regression suite. Checks are especially useful when
the code youre writing will be used as a black box by other programmers; users will
immediately know when and how theyve misused your code.
31
Of course you should be very careful to ensure your code isnt subtly dependent on
debug-only statements to function correctly. Statements that will disappear in production code should never have side effects.
#include <glib.h>
g_return_if_fail(condition);
g_return_val_if_fail(condition, retval);
Without the checks, passing NULL as a parameter to this function would result in
a mysterious segmentation fault. The person using the library would have to figure
out where the error occurred with a debugger, and maybe even dig in to the glib code
to see what was wrong. With the checks, theyll get a nice error message telling them
that NULL arguments are not allowed.
#include <glib.h>
g_assert(condition);
g_assert_not_reached(void);
32
an assertion which always fails. Assertions call abort() to exit the program and (if
your environment supports it) dump a core file for debugging purposes.
Fatal assertions should be used to check internal consistency of a function or library,
while g_return_if_fail() is intended to ensure sane values are passed to the public interfaces of a program module. That is, if an assertion fails, you typically look for
a bug in the module containing the assertion; if a g_return_if_fail() check fails,
you typically look for the bug in the code which invokes the module.
This code from glibs calendrical calculations module shows the difference:
GDate*
g_date_new_dmy (GDateDay day, GDateMonth m, GDateYear y)
{
GDate *d;
g_return_val_if_fail (g_date_valid_dmy (day, m, y), NULL);
d = g_new (GDate, 1);
d->julian = FALSE;
d->dmy
= TRUE;
d->month = m;
d->day
= day;
d->year = y;
g_assert (g_date_valid (d));
return d;
}
The precondition check at the beginning ensures the user passes in reasonable values
for the day, month and year; the assertion at the end ensures that glib constructed a
sane object, given sane values.
g_assert_not_reached() should be used to mark "impossible" situations; a com-
mon use is to detect switch statements that dont handle all possible values of an
enumeration:
switch (val)
{
case FOO_ONE:
break;
case FOO_TWO:
break;
default:
/* Invalid enumeration value */
g_assert_not_reached();
break;
}
All of the debugging macros print a warning using glibs g_log() facility, which
means the warning includes the name of the originating application or library, and
you can optionally install a replacement warning-printing routine. For example, you
might send all warnings to a dialog box or log file instead of printing them on the
console.
33
Memory
glib wraps the standard malloc() and free() with its own g_ variants, g_malloc()
and g_free(), shown in Figure 2-5. These are nice in several small ways:
g_malloc() always returns a gpointer, never a char*, so theres no need to cast the
return value.
g_malloc() aborts the program if the underlying malloc() fails, so you dont
have to check for a NULL return value.
g_malloc()
g_free()
In addition to these minor conveniences, g_malloc() and g_free() can support various kinds of memory debugging and profiling. If you pass the -enable-mem-check
option to glibs configure script, the compiled g_free() will warn you whenever you
free the same pointer twice. The -enable-mem-profile option enables code which
keeps memory use statistics; when you call g_mem_profile() they are printed to
the console. Finally, you can define USE_DMALLOC and the glib memory wrappers
will use the MALLOC(), etc. debugging macros available in dmalloc.h on some platforms.
#include <glib.h>
gpointer g_malloc(gulong size);
void g_free(gpointer mem);
gpointer g_realloc(gpointer mem, gulong size);
gpointer g_memdup(gconstpointer mem, guint bytesize);
#include <glib.h>
34
g_new(type, count);
g_new0(type, count);
g_renew(type, mem, count);
String Handling
glib provides a number of functions for string handling; some are unique to glib, and
some solve portability concerns. They all interoperate nicely with the glib memory
allocation routines.
For those interested in a better string than gchar*, theres also a GString type. It isnt
covered in this book, but documentation is available at http://www.gtk.org/.
#include <glib.h>
gint g_snprintf(gchar* buf, gulong n, const gchar* format, ...);
gint g_strcasecmp(const gchar* s1, const gchar* s2);
gint g_strncasecmp(const gchar* s1, const gchar* s2, guint n);
The functions in Figure 2-8 modify a string in-place: the first two convert the string
to lowercase or uppercase, respectively, while g_strreverse() reverses its characters. g_strchug() and g_strchomp() "chug" the string (remove leading spaces), or
"chomp" it (remove trailing spaces). These last two return the string, in addition to
modifying it in-place; in some cases it may be convenient to use the return value.
There is a macro, g_strstrip(), which combines both functions to remove both
leading and trailing spaces; it is used just as the individual functions are.
#include <glib.h>
35
#include <glib.h>
gdouble g_strtod(const gchar* nptr, gchar** endptr);
gchar* g_strerror(gint errnum);
gchar* g_strsignal(gint signum);
Instead you could say this, and avoid having to figure out the proper length of the
buffer to boot:
gchar* str = g_strdup_printf("%d printf-style %s", 1, "format");
#include <glib.h>
36
gchar*
gchar*
gchar*
gchar*
gchar*
gchar*
#include <glib.h>
gchar* g_strconcat(const gchar* string1,
gchar* g_strjoin(const gchar* separator,
...);
...);
#include <glib.h>
gchar** g_strsplit(const gchar* string, const gchar* delimiter, gint max_tokens);
gchar* g_strjoinv(const gchar* separator, gchar** str_array);
void g_strfreev(gchar** str_array);
Data Structures
glib implements many common data structures, so you dont have to reinvent the
wheel every time you want a linked list. This section covers glibs implementation of
linked lists, sorted binary trees, N-ary trees, and hash tables.
Lists
glib provides generic single and doubly linked lists, GSList and GList, respectively.
These are implemented as lists of gpointer; you can use them to hold integers with the
GINT_TO_POINTER and GPOINTER_TO_INT macros. GSList and GList have identical
37
glib lists have a noticeable Lisp influence; the empty list is a special "nil" value for that
reason. g_slist_prepend() works much like consits a constant-time operation
that adds a new cell to the front of the list.
Notice that you must replace the list passed to list-modifying functions with their
return value, in case the head of the list changes. glib will handle memory issues,
deallocating and allocating list links as needed.
For example, the following code would remove the above-added element and empty
the list:
list = g_slist_remove(list, element);
list is now NULL. You still have to free element yourself, of course. To clear an entire
list, use g_slist_free(), which removes all the links in one fell swoop. g_slist_free()
has no return value because it would always be NULL, and you can simply assign
that value to your list if you like. Obviously, g_slist_free() frees only the list cells;
it has no way of knowing what to do with the list contents.
To access a list element, you refer to the GSList struct directly:
gchar* my_data = list->data;
To iterate over the list, you might write code like this:
GSList* tmp = list;
while (tmp != NULL)
{
printf("List data: %p\n", tmp->data);
tmp = g_slist_next(tmp);
}
Figure 2-13 shows the basic functions for changing GSList contents. For all of these,
you must assign the return value to your list pointer in case the head of the list
changes. Note that glib does not store a pointer to the tail of the list, so prepending is a constant-time operation, while append, insert, and remove are proportional
to the lists size.
In particular, this means that constructing a list using g_slist_append() is a terrible
idea; use g_slist_prepend() and then call g_slist_reverse() if you need items in
a particular order. If you anticipate frequently appending to a list, you can also keep
a pointer to the last element. The following code can be used to perform efficient
appends:
38
void
efficient_append(GSList** list, GSList** list_end, gpointer data)
{
g_return_if_fail(list != NULL);
g_return_if_fail(list_end != NULL);
if (*list == NULL)
{
g_assert(*list_end == NULL);
*list = g_slist_append(*list, data);
*list_end = *list;
}
else
{
*list_end = g_slist_append(*list_end, data)->next;
}
}
To use this function, you would store the list and its end somewhere, and pass their
address to efficient_append():
GSList* list = NULL;
GSList* list_end = NULL;
efficient_append(&list, &list_end, g_strdup("Foo"));
efficient_append(&list, &list_end, g_strdup("Bar"));
efficient_append(&list, &list_end, g_strdup("Baz"));
Of course you have to be careful not to use any list functions that might change the
end of the list without updating list_end.
#include <glib.h>
GSList*
GSList*
GSList*
GSList*
39
For example, you might have a list of strings, and you might want to be able to create
a parallel list with some transformation applied to the strings. Here is some code,
using the efficient_append() function from an earlier example:
typedef struct _AppendContext AppendContext;
struct _AppendContext {
GSList* list;
GSList* list_end;
const gchar* append;
};
static void
append_foreach(gpointer data, gpointer user_data)
{
AppendContext* ac = (AppendContext*) user_data;
gchar* oldstring = (gchar*) data;
efficient_append(&ac->list, &ac->list_end,
g_strconcat(oldstring, ac->append, NULL));
}
GSList*
copy_with_append(GSList* list_of_strings, const gchar* append)
{
AppendContext ac;
ac.list = NULL;
ac.list_end = NULL;
ac.append = append;
g_slist_foreach(list_of_strings, append_foreach, &ac);
return ac.list;
}
glib and GTK+ use the "function pointer and user data" idiom heavily. If you have
functional programming experience, this is much like using lambda expressions to
create a closure. (A closure combines a function with an environmenta set of namevalue bindings. In this case the "environment" is the user data you pass to append_foreach(),
and the "closure" is the combination of the function pointer and the user data.)
#include <glib.h>
GSList* g_slist_find(GSList* list, gpointer data);
GSList* g_slist_nth(GSList* list, guint n);
gpointer g_slist_nth_data(GSList* list, guint n);
GSList* g_slist_last(GSList* list);
gint g_slist_index(GSList* list, gpointer data);
void g_slist_foreach(GSList* list, GFunc func, gpointer user_data);
40
#include <glib.h>
guint g_slist_length(GSList* list);
GSList* g_slist_concat(GSList* list1, GSList* list2);
GSList* g_slist_reverse(GSList* list);
GSList* g_slist_copy(GSList* list);
If a < b, the function should return a negative value; if a > b a positive value; if a ==
b it should return 0.
Once you have a comparison function, you can insert an element into an alreadysorted list, or sort an entire list. Lists are sorted in ascending order. You can even
recycle your GCompareFunc to find list elements, using g_slist_find_custom().
(A word of caution: GCompareFunc is used inconsistently in glib; sometimes it glib
expects an equality predicate instead of a qsort()-style function. However, the usage
is consistent within the list API.)
Be careful with sorted lists; misusing them can rapidly become very inefficient. For
example, g_slist_insert_sorted() is an O(n) operation, but if you use it in a loop
to insert multiple elements the loop runs in exponential time. Its better to simply
prepend all your elements, then call g_slist_sort().
#include <glib.h>
GSList* g_slist_insert_sorted(GSList* list, gpointer data, GCompareFunc
func);
GSList* g_slist_sort(GSList* list, GCompareFunc func);
GSList* g_slist_find_custom(GSList* list, gpointer data, GCompareFunc func);
Trees
There are two different kinds of tree in glib; GTree is your basic balanced binary tree,
useful to store key-value pairs sorted by key; GNode stores arbitrary tree-structured
data, such as a parse tree or taxonomy.
41
GTree
To create and destroy a GTree, use the constructor-destructor pair displayed in Figure
2-17. GCompareFunc is the same qsort()-style comparison function described for
GSList; in this case its used to compare keys in the tree.
#include <glib.h>
GTree* g_tree_new(GCompareFunc key_compare_func);
void g_tree_destroy(GTree* tree);
#include <glib.h>
void g_tree_insert(GTree* tree, gpointer key, gpointer value);
void g_tree_remove(GTree* tree, gpointer key);
gpointer g_tree_lookup(GTree* tree, gpointer key);
#include <glib.h>
gint g_tree_nnodes(GTree* tree);
gint g_tree_height(GTree* tree);
GTraverseType is an enumeration; there are four possible values. Here are their meanings with respect to GTree.
42
G_IN_ORDER first recurses the left child of the node (the "lower" key according to
your GCompareFunc), then calls the traversal function on the key-value pair of the
current node, then recurses the right child. This traversal is in order from lowest to
highest, according to your GCompareFunc.
G_PRE_ORDER calls the traversal function on the key-value pair of the current
node, then recurses the left child, then recurses the right child.
G_POST_ORDER recurses the left child, then recurses the right child, and finally
calls the traversal function on the current nodes key-value pair.
#include <glib.h>
void g_tree_traverse(GTree* tree, GTraverseFunc traverse_func, GTraverseType traverse_type, gpointer data);
GNode
A GNode is an N-way tree, implemented as a doubly linked list with parent and
child lists. Thus, most list operations have analogues in the GNode API. You can also
walk the tree in various ways. Heres the declaration for a node:
typedef struct _GNode GNode;
struct _GNode
{
gpointer data;
GNode
*next;
GNode
*prev;
GNode
*parent;
GNode
*children;
};
There are macros to access GNode members, shown in Figure 2-21. As with GList,
the data member is intended to be used directly. These macros return the next, prev,
and children members respectively; they also check whether their argument is NULL
before dereferencing it, and return NULL if it is.
#include <glib.h>
g_node_prev_sibling(node);
g_node_next_sibling(node);
g_node_first_child(node);
43
used only to create the root node; convenience macros are provided which automatically create new nodes as needed.
#include <glib.h>
GNode* g_node_new(gpointer data);
#include <glib.h>
GNode* g_node_insert(GNode* parent, gint position, GNode* node);
GNode* g_node_insert_before(GNode* parent, GNode* sibling, GNode* node);
GNode* g_node_prepend(GNode* parent, GNode* node);
#include <glib.h>
g_node_append(parent, node);
g_node_insert_data(parent, position, data);
g_node_insert_data_before(parent, sibling, data);
g_node_prepend_data(parent, data);
g_node_append_data(parent, data);
#include <glib.h>
void g_node_destroy(GNode* root);
void g_node_unlink(GNode* node);
44
There are two macros for detecting the top and bottom of a GNode tree, shown in
Figure 2-26. A root node is defined as a node with no parent or siblings. A leaf node
has no children.
#include <glib.h>
G_NODE_IS_ROOT(node);
G_NODE_IS_LEAF(node);
G_IN_ORDER first recurses the leftmost child of the node, then visits the node
itself, then recurses the rest of the nodes children. This isnt very useful; mostly it
is intended for use with GTree.
G_PRE_ORDER visits the current node, then recurses each child in turn.
G_POST_ORDER recurses each child in order, then visits the current node.
G_LEVEL_ORDER first visits the node itself; then each of the nodes children; then
the children of the children; then the children of the children of the children; and
so on. That is, it visits each node of depth 0, then each node of depth 1, then each
node of depth 2, etc.
#include <glib.h>
guint g_node_n_nodes(GNode* root, GTraverseFlags flags);
GNode* g_node_get_root(GNode* node);
gboolean g_node_is_ancestor(GNode* node, GNode* descendant);
guint g_node_depth(GNode* node);
GNode* g_node_find(GNode* root, GTraverseType order, GTraverseFlags flags,
gpointer data);
45
These are called with a pointer to the node being visited, and the user data you
provide. A GNodeTraverseFunc can return TRUE to stop whatever traversal is in
progress; thus you can use GNodeTraverseFunc in combination with g_node_traverse()
to search the tree by value.
#include <glib.h>
void g_node_traverse(GNode* root, GTraverseType order, GTraverseFlags flags,
gint max_depth, GNodeTraverseFunc func, gpointer data);
guint g_node_max_height(GNode* root);
void g_node_children_foreach(GNode* node, GTraverseFlags flags, GNodeForeachFunc func, gpointer data);
void g_node_reverse_children(GNode* node);
guint g_node_n_children(GNode* node);
GNode* g_node_nth_child(GNode* node, guint n);
GNode* g_node_last_child(GNode* node);
GNode* g_node_find_child(GNode* node, GTraverseFlags flags, gpointer data);
gint g_node_child_position(GNode* node, GNode* child);
gint g_node_child_index(GNode* node, gpointer data);
GNode* g_node_first_sibling(GNode* node);
GNode* g_node_last_sibling(GNode* node);
Hash Tables
GHashTable is a simple hash table implementation, providing an associative array
with constant-time lookups. To use the hash table, you must provide a GHashFunc,
which should return a positive integer when passed a hash key:
typedef guint (*GHashFunc) (gconstpointer key);
Each returned guint (modulus the size of the table) corresponds to a "slot" or "bucket"
in the hash; GHashTable handles collisions by storing a linked list of key-value pairs
in each slot. Thus, the guint values returned by your GHashFunc must be fairly
evenly distributed over the set of possible guint values, or the hash table will degenerate into a linked list. Your GHashFunc must also be fast, since it is used for
every lookup.
In addition to GHashFunc, a GCompareFunc is required to test keys for equality.
Somewhat unpleasantly, GHashTable does not use GCompareFunc in the same way
GSList and GTree do, although the function signature is the same. Here GCompareFunc is expected to be an equality operator, returning TRUE if its arguments are
equal. It should not be a qsort()-style comparison function. The key comparison function is used to find the correct key-value pair when hash collisions result in more
than one pair in the same hash slot.
46
To create and destroy a GHashTable, use the constructor and destructor listed in Figure 2-29. Remember that glib has no way of knowing how to destroy the data contained in your hash table; it only destroys the table itself.
#include <glib.h>
GHashTable* g_hash_table_new(GHashFunc hash_func, GCompareFunc key_compare_func);
void g_hash_table_destroy(GHashTable* hash_table);
#include <glib.h>
guint g_int_hash(gconstpointer v);
gint g_int_equal(gconstpointer v1, gconstpointer v2);
guint g_direct_hash(gconstpointer v);
gint g_direct_equal(gconstpointer v1, gconstpointer v2);
guint g_str_hash(gconstpointer v);
gint g_str_equal(gconstpointer v1, gconstpointer v2);
#include <glib.h>
47
#include <glib.h>
void g_hash_table_freeze(GHashTable* hash_table);
void g_hash_table_thaw(GHashTable* hash_table);
Other Features
There simply isnt space to cover all of glibs features in this book. Its worth looking at glib whenever you find yourself thinking, "There really should be a function
that..."glib.h and the glib documentation on http://www.gtk.org/ are excellent
resources.
Heres a brief list of features not already mentioned:
Byte-order conversions.
g_memmove()
48
Numerous macros to permit the use of compiler extensions (especially gcc extensions) in a portable way.
The g_log() facility, allows you to print warnings, messages, etc. with configurable log levels and pluggable print routines.
GMemChunk facility allows you to allocate a large pool of small memory chunks,
for efficiency gains compared to g_malloc(). Used in the GList implementation,
for example.
A timer facility.
Convenience/portability routines to get the users home directory, get the name
of a /tmp directory, and similar tasks.
Bitfield manipulation.
A lexical scanner.
Tab completions.
Calendrical/date-arithmetic functions.
If you need some generally-useful routine thats not in glib already, consider writing it in glib style and contributing it to the library! You get free assistance with design, debugging, and maintenance, and other programmers benefit from the facility
youve written. By the time you read this, its also possible that the feature you want
is already in the latest version of glib.
49
= gtk_label_new("Hello, World!");
gtk_container_add(GTK_CONTAINER(button), label);
gtk_container_add(GTK_CONTAINER(window), button);
gtk_window_set_title(GTK_WINDOW(window), "Hello");
gtk_container_set_border_width(GTK_CONTAINER(button), 10);
50
gtk_signal_connect(GTK_OBJECT(window),
"delete_event",
GTK_SIGNAL_FUNC(delete_event_cb),
NULL);
gtk_signal_connect(GTK_OBJECT(button),
"clicked",
GTK_SIGNAL_FUNC(button_click_cb),
label);
gtk_widget_show_all(window);
gtk_main();
return 0;
}
static gint
delete_event_cb(GtkWidget* window, GdkEventAny* e, gpointer data)
{
gtk_main_quit();
return FALSE;
}
static void
button_click_cb(GtkWidget* w, gpointer data)
{
GtkWidget* label;
gchar* text;
gchar* tmp;
label = GTK_WIDGET(data);
gtk_label_get(GTK_LABEL(label), &text);
tmp = g_strdup(text);
g_strreverse(tmp);
gtk_label_set_text(GTK_LABEL(label), tmp);
g_free(tmp);
}
51
If youre using a Bourne shell variant, such as bash, you can use backticks (not single
quotes!) to execute gtk-config and substitute its output. A simple Makefile for
compiling Hello, World might look like this:
CC=gcc
all: hello.c
$(CC) gtk-config -libs gtk-config -cflags -o hello hello.c
clean:
/bin/rm -f *.o *~
Of course, this Makefile is far too simple for real-world applications; Chapter 4 describes how to set up a more realistic build using automake and autoconf.
gtk-config allows you to locate GTK+ on the users system, instead of hard-coding
a location in your Makefile. It also comes in handy if you have two versions of GTK+
on your own system; if you install them each in a dedicated directory tree, you can
choose one or the other by placing the correct gtk-config in your shells search path.
How It Works
This simple program contains all the essential elements of a GTK+ application. It
doesnt contain any Gnome features; but since Gnome builds on GTK+, the same
concepts will apply.
Initialization
First, GTK+ must be initialized:
gtk_init(&argc, &argv);
This call connects to an X server, and parses some default arguments understood by
all GTK+ programs. Parsed arguments are removed from argv, and argc is decremented accordingly. gtk_init() also registers a "cleanup function" using atexit().
In practice, this is only important when you fork(); the child process must exit with
_exit() rather than exit() to avoid shutting down GTK+ in the parent.
Widgets
Next, any program will have some user interface elements. In the X tradition, these
are called widgets. All widgets are subclasses of the GtkWidget base class, so you
can use a GtkWidget* to refer to them. (Since C has no native support for object
inheritance, GTK+ has its own mechanismChapter 9 describes this.)
window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
52
button = gtk_button_new();
label
= gtk_label_new("Hello, World!");
gtk_container_add(GTK_CONTAINER(button), label);
gtk_container_add(GTK_CONTAINER(window), button);
gtk_window_set_title(GTK_WINDOW(window), "Hello");
gtk_container_set_border_width(GTK_CONTAINER(button), 10);
Each widget has a function called gtk_widgetname_new(), analagous to a constructor in C++ or Java. This function allocates a new object, initializes it, and returns a
pointer to it. All of the _new() routines return a GtkWidget*, even though they allocate a subclass; this is for convenience.
Once you have a GtkWidget* representing an object, you can manipulate the object
using its methods. All GTK+ widget functions begin with the name of the type they
operate on, and accept a pointer to that type as the first argument. In the above code,
gtk_container_add() accepts a GtkContainer* as the first argument. The macro
GTK_CONTAINER() casts the GtkWidget*, and also performs a runtime type check.
Casting is required because C does not understand the inheritance relationship.
As you might imagine, GtkButton and GtkWindow are both subclasses of GtkContainer. A GtkContainer can hold any other widget inside. The code creates a toplevel
window, places a button inside it, and places a label (line of text) inside the button.
Then it sets the window title, and adds a small cosmetic border around the button.
Signals
Next, youll want to arrange to respond when users manipulate the widgets. In this
simple application, there are two interesting things that can happen: the user can
click the button, or close the window using a window manager decoration. Widgets
(actually, all GtkObjects) emit signals when something interesting happens a program
might want to respond to. To respond to a signal, you "connect a callback" to iti.e.,
register a function to be called when the signal is emitted. Heres that code again:
gtk_signal_connect(GTK_OBJECT(window),
"delete_event",
GTK_SIGNAL_FUNC(delete_event_cb),
NULL);
gtk_signal_connect(GTK_OBJECT(button),
"clicked",
GTK_SIGNAL_FUNC(button_click_cb),
label);
gtk_signal_connect() specifies the GtkObject to monitor, which signal to connect
53
its children. The following code would have the same effect in this case:
gtk_widget_show(label);
gtk_widget_show(button);
gtk_widget_show(window);
Its necessary to show each and every widget that you want to appear on the screen.
The opposite operation is called gtk_widget_hide(); widgets start their life hidden,
and can be re-hidden/re-shown any number of times. Its good practice to show all
child widgets before showing the outermost container; otherwise, the user will see
the container appear first, followed by its children. Widgets are not actually visible
on the screen until their parent container is shownthe exception to the rule is GtkWindow, since it has no parent.
Once your widgets have been shown, you want to wait for the user to do something
with them. gtk_main() enters the GTK+ main loop; the main loop is event-driven.
That is, user actions trigger events which generally result in signals being emitted
and your callbacks being called. gtk_main() blocks indefinitely, waiting for and responding to user input. The main loop is described in more detail in the section called
The Main Loop. Events and their relation to the main loop are described in the section
called Events in Chapter 10.
54
Widget header files are the best quick reference for callback signatures. The "class
structure" for the widget will have a space for a default signal handler; your handler should be modeled on the default one. For example, in gtk/gtkbutton.h the
GtkButton class struct looks like this:
struct _GtkButtonClass
{
GtkBinClass
parent_class;
void
void
void
void
void
(*
(*
(*
(*
(*
pressed)
released)
clicked)
enter)
leave)
(GtkButton
(GtkButton
(GtkButton
(GtkButton
(GtkButton
*button);
*button);
*button);
*button);
*button);
};
Chapter 9 explains exactly what a class struct is for; for now, just pay attention to the
function pointers, and note that they correspond to signals. To get from this:
void (* clicked)
(GtkButton *button);
to this:
static void button_click_cb(GtkWidget* w, gpointer data);
simply add a gpointer data to the class struct functions signature. In Hello, World
Ive also changed the type from GtkButton* to GtkWidget*; this is common, since
it can be more convenient to have a GtkWidget*. The argument will always be the
GtkButton emitting the signal.
Another example may be useful; here is "delete_event" from gtk/gtkwidget.h:
gint (* delete_event)
(GtkWidget
GdkEventAny
*widget,
*event);
Thats all there is to it. You can write simple GTK+ applications using only the information presented in this section. GTK+ and Gnome are powerful application development tools because you can think about real functionality, instead of struggling to
get a window on the screen.
55
is a GtkBin which draws a relieved border around the child. GtkWindow allows the
child to appear in a toplevel window.
The second type of container widget often has GtkContainer as its immediate parent. These containers can have more than one child, and their purpose is to manage
layout. "Manage layout" means that these containers assign sizes and positions to the
widgets they contain. For example, GtkVBox arranges its children in a vertical stack.
GtkFixed allows you to position children at arbitrary coordinates. GtkPacker gives
you Tk-style layout management.
This chapter is about the second kind of container. To produce the layout you want
without hard-coding any sizes, youll need to understand how to use these. The goal
is to avoid making assumptions about window size, screen size, widget appearance,
fonts, and so on. Your application should automatically adapt if these factors change.
Size Allocation
To understand layout containers, you first have to understand how GTK+ widgets
negotiate their size. Its quite simple really; there are only two concepts, requisition
and allocation. These correspond to the two phases of layout.
Requisition
A widgets requisition consists of a width and a heightthe size the widget would
like to be. This is represented by a GtkRequisition struct:
typedef struct _GtkRequisition
GtkRequisition;
struct _GtkRequisition
{
gint16 width;
gint16 height;
};
Different widgets choose what size to request in different ways. GtkLabel, for example, requests enough size to display all the text in the label. Most container widgets
base their size request on the size requests of their children. For example, if you place
several buttons in a box, the box will ask to be large enough to hold all the buttons.
The first phase of layout starts with a toplevel widget such as GtkWindow. Since its
a container, GtkWindow asks its child widget for a size request; that child might ask
its own children; and so on recursively. When all child widgets have been queried,
GtkWindow will finally get a GtkRequisition back from its child. Depending on how
it was configured, GtkWindow may or may not be able to expand to accomodate the
size request.
Allocation
Phase two of layout begins at this point. GtkWindow makes a decision about how
much space is actually available for its child, and communicates its decision to the
child. This is known as the childs allocation, represented by the following struct:
typedef struct _GtkAllocation
struct _GtkAllocation
{
56
GtkAllocation;
gint16 x;
gint16 y;
guint16 width;
guint16 height;
};
The width and height elements are identical to GtkRequisition; they represent the size
of the widget. A GtkAllocation also includes the coordinates of the child with respect
to its parent. GtkAllocations are assigned to children by their parent container.
Widgets are required to honor the GtkAllocation given to them. GtkRequisition is
only a request; widgets must be able to cope with any size.
Given the layout process, its easy to see what role containers play. Their job is to
assemble each childs requisition into a single requisition to be passed up the widget
tree; then to divide the allocation they receive between their children. Exactly how
this happens depends on the particular container.
GtkBox
A GtkBox manages a row (GtkHBox) or column (GtkVBox) of widgets. For GtkHBox,
all the widgets are assigned the same height; the boxs job is to distribute the available
width between them. GtkHBox optionally uses some of the available width to leave
gaps (called "spacing") between widgets. GtkVBox is identical, but in the opposite
direction (i.e., it distributes available height rather than width). GtkBox is an abstract
base class; GtkVBox and GtkHBox can be used almost entirely via its interface. Boxes
are the most useful container widget.
To create a GtkBox, you use one of the constructors shown in Figure 3-2 and Figure 33. The box constructor functions take two parameters. If TRUE, homogeneous means
that all children of the box will be allocated the same amount of space. spacing specifies the amount of space between each child. There are functions to change spacing
and toggle homogeneity after the box is created.
#include <gtk/gtkhbox.h>
GtkWidget* gtk_hbox_new(gboolean homogeneous, gint spacing);
#include <gtk/gtkvbox.h>
GtkWidget* gtk_vbox_new(gboolean homogeneous, gint spacing);
57
#include <gtk/gtkbox.h>
void gtk_box_pack_start(GtkBox* box, GtkWidget* child, gboolean expand,
gboolean fill, gint padding);
void gtk_box_pack_end(GtkBox* box, GtkWidget* child, gboolean expand, gboolean
fill, gint padding);
58
4. The box-wide spacing setting determines how much blank space to leave between children; so this value is multiplied by the number of chilren minus one,
and added to the base size request. Note that spacing does not belong to a child;
it is blank space between children and is unaffected by the expand and fill parameters. Padding, on the other hand, is the space around each child and is affected by the childs packing parameters.
5. All containers have a "border width" setting; two times the border width is
added to the request, representing a border on either side. Thus, the total size
requested by a GtkBox is: (Sum of Child Sizes) + Spacing*(Number of Children
- 1) + 2*(Border Width).
After computing its size request and delivering it to its parent container, GtkBox will
receive its size allocation and distribute it among its children as follows:
1. Enough space for the border width and inter-child spacing is subtracted from
the allocation; the remainder is the available space for children themselves. This
space is divided into two chunks: the amount actually requested by the children
(child requisitions and padding), and the "extra." Extra = (Allocation Size) (Sum of Child Sizes).
2. If the box is not homogeneous, the "extra" space is divided among those children with the expand parameter set to TRUE. These children can expand to fit
available space. If no child can expand, the extra is used to add more space
in the center of the box, between the start-packed widgets and the end-packed
widgets.
3. If the box is homogeneous, the extra is distributed according to need; those
children who requested more space get less extra, so that everyone ends up with
the same amount of space. The expand parameter is ignored for homogeneous
boxesextra is distributed to all children, not just the expandable ones.
4. When a child gets some extra space, there are two possibilities. More padding
can be added around the child, or the child widget itself can be expanded. The
fill parameter determines which will happen. If TRUE, the child widget expands to fill the spacethat is, the entire space becomes the childs allocation;
if fill is FALSE, the childs padding is increased to fill the space, and the child is
allocated only the space it requested. Note that fill has no effect if expand is set
to FALSE and the box is not homogeneous, because the child will never receive
any extra space to fill.
Whew! Who wants to think about all that? Fortunately, there are some common patterns of usage, so you dont need to solve a multivariate equation to figure out how
to use the widget. The authors of the GTK+ Tutorial boil things down nicely to five
cases that occur in practice; well follow in their footsteps here.
The result is shown in Figure 3-6. The expand parameter is the only one that matters
in this case; no children are receiving extra space, so they wouldnt be able to fill it
even if fill were TRUE.
59
60
GtkTable
The second most common layout container is GtkTable. GtkTable divides a region
into cells; you can assign each child widget to a rectangle made up of one or more
61
cells. You can think of GtkTable as a sheet of graph paper (with more flexibilitythe
grid lines do not have to be equidistant, though they can be).
GtkTable comes with the usual constructor, and some functions to attach children
to it; these are shown in Figure 3-12. When creating a table, you specify the number of cells you plan to use; this is purely for efficiency. The table will automatically
grow if you place children in cells outside its current area. Like boxes, tables can be
homogeneous or not.
#include <gtk/gtktable.h>
GtkWidget* gtk_table_new(guint rows, guint columns, gboolean homogeneous);
GtkWidget* gtk_table_attach(GtkTable* table, GtkWidget* child, guint left_side,
guint right_side, guint top_side, guint bottom_side, GtkAttachOptions
xoptions, GtkAttachOptions yoptions, guint xpadding, guint ypadding);
GTK_EXPAND specifies that this section of the table will expand to fit available
space, much like the expand option when packing boxes.
GTK_FILL specifies that the child widget will expand to fill available space. Important only if GTK_EXPAND is set, because GTK_EXPAND permits extra space
to exist.
Its possible to set spacing between rows and columns, in addition to padding around
particular children; the terms "spacing" and "padding" mean the same thing with respect to tables and boxes. See gtk/gtktable.h for a complete list of available GtkTable functions.
GtkTable Example
The following code creates a table with four cells and three children; one child covers
two cells. The children are packed using different parameters:
GtkWidget* window;
GtkWidget* button;
GtkWidget* container;
62
window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
container = gtk_table_new(2, 2, FALSE);
gtk_container_add(GTK_CONTAINER(window), container);
gtk_window_set_title(GTK_WINDOW(window), "Table Attaching");
gtk_container_set_border_width(GTK_CONTAINER(container), 10);
/* This would be a bad idea in real code; but it lets us
* experiment with window resizing.
*/
gtk_window_set_policy(GTK_WINDOW(window), TRUE, TRUE, TRUE);
gtk_signal_connect(GTK_OBJECT(window),
"delete_event",
GTK_SIGNAL_FUNC(delete_event_cb),
NULL);
button = gtk_button_new_with_label("1. Doesnt shrink\nor expand");
gtk_table_attach(GTK_TABLE(container),
button,
0, 1,
0, 1,
GTK_FILL,
GTK_FILL,
0,
0);
button = gtk_button_new_with_label("2. Expands and shrinks\nvertically");
gtk_table_attach(GTK_TABLE(container),
button,
0, 1,
1, 2,
GTK_FILL,
GTK_FILL | GTK_EXPAND | GTK_SHRINK,
0,
0);
button = gtk_button_new_with_label("3. Expands and shrinks\nin both directions");
gtk_table_attach(GTK_TABLE(container),
button,
1, 2,
0, 2,
GTK_FILL | GTK_EXPAND | GTK_SHRINK,
GTK_FILL | GTK_EXPAND | GTK_SHRINK,
0,
0);
Its instructive to observe the resulting table as the window is resized. First, a quick
summary of how the children are attached:
1. The first child will always receive its requested size; it neither expands nor
shrinks.
2. The second child can expand and shrink only in the Y direction.
3. The third child can expand and shrink in either direction.
The windows natural size is shown in Figure 3-13; notice that some cells are given
more space than the widgets inside them requested because table cells have to remain
63
aligned. (Recall that a button with a label will request only enough space to display
the entire label.) The GTK_FILL flag causes GtkTable to allocate extra space to the
widgets themselves, instead of leaving blank padding around them.
64
gets shortchanged, while child number one gets all the vertical space it needs.
Using gtk_table_attach_defaults()
Since gtk_table_attach() is somewhat cumbersome, theres a simpler version called
gtk_table_attach_defaults(), shown in Figure 3-18. This version attaches the
child with the options GTK_EXPAND and GTK_FILL, and no padding.
Its tempting to use gtk_table_attach_defaults() all the time to save typing, but
really you shouldnt; in fact, its probably fair to say that its rarely used. The function
is only useful if the defaults happen to be exactly the settings you want. Most of the
time, you need to carefully tweak your table attachment parameters to get really nice
behavior when your window is resized. Always try resizing your window to be sure
youve designed your layout well.
#include <gtk/gtktable.h>
GtkWidget* gtk_table_attach_defaults(GtkTable* table, GtkWidget* child, guint
left_side, guint right_side, guint top_side, guint bottom_side);
65
GtkLayout
GtkFixed
nonsensical for other widgets, and will most likely cause bad things to happen. Its
primarily used to honor a -geometry command line argument.
All three of these functions can accept -1 for the x, y, width, or height argument.
The functions ignore any -1 argument; this allows you to set only one of the two
arguments, leaving the default value for the other.
#include <gtk/gtkwidget.h>
void gtk_widget_set_uposition(GtkWidget* widget, gint x, gint y);
void gtk_widget_set_usize(GtkWidget* widget, gint width, gint height);
#include <gtk/gtkwindow.h>
66
Widget Concepts
This section discusses concepts that apply to all widgets, including memory management and certain special states widgets can be in. Its a "conceptual" section; however,
the concepts are very important to practical topics covered later in the book.
#include <gtk/gtkwidget.h>
void gtk_widget_destroy(GtkWidget* widget);
67
#include <gtk/gtkobject.h>
void gtk_object_ref(GtkObject* object);
void gtk_object_unref(GtkObject* object);
void gtk_object_sink(GtkObject* object);
etc.) but the object and widget versions are completely synonymous. The widgetspecific versions are leftovers from earlier versions of GTK+.
So to safely remove a widget from a container, you might do this:
gtk_widget_ref(widget);
gtk_container_remove(container, widget);
The widget now has one reference, held by your code. At some point youll need
to release the reference, destroying the widget. (It would make sense to do so after
re-adding the widget to some other container, for example.)
Its worth pointing out that removing widgets from containers is uncommon; in general its faster to simply hide the widget with gtk_widget_hide(), then gtk_widget_show()
it at some later time.
gtk_object_sink() is used almost exclusively in widget implementations, when
This code adds one reference to the widget; if the widget was "floating," it also subtracts one reference. If the widget was not floating, gtk_widget_sink() has no effect.
Its important to understand the details because in some cases they can be important.
But most of the time, you can get by with a few simple rules:
You must destroy any toplevel widgets when you are done with them, but child
widgets are destroyed automatically.
If you want to remove a widget from a container without destroying it, you must
first add a reference to the widget.
If you add a reference to a widget, you are responsible for unreferencing the widget again when youre done with it.
68
In typical user code, you only need to call gtk_widget_show(); this implies realizing
and mapping the widget as soon as its parent is realized and mapped. Its important
to understand that gtk_widget_show() has no immediate effect, it merely schedules
the widget to be shown. This means you dont have to worry about showing widgets
in any particular order; it also means that you cant immediately access the GdkWindow of a widget. Sometimes you need to access the GdkWindow; in those cases youll
want to manually call gtk_widget_realize() to create it. gtk_widget_realize()
will also realize a widgets parents, if appropriate. Its uncommon to need gtk_widget_realize();
if you find that you do, perhaps you are approaching the problem incorrectly.
Destroying a widget automatically reverses the entire sequence of events, recursively
unrealizing the widgets children and the widget itself.
Figure 3-23 summarizes the functions discussed in this section.
69
#include <gtk/gtkwidget.h>
void
void
void
void
void
void
gtk_widget_realize(GtkWidget* widget);
gtk_widget_unrealize(GtkWidget* widget);
gtk_widget_map(GtkWidget* widget);
gtk_widget_unmap(GtkWidget* widget);
gtk_widget_show(GtkWidget* widget);
gtk_widget_hide(GtkWidget* widget);
#include <gtk/gtkwidget.h>
GTK_WIDGET_NO_WINDOW(widget);
GTK_WIDGET_REALIZED(widget);
GTK_WIDGET_MAPPED(widget);
GTK_WIDGET_VISIBLE(widget);
Sensitivity
Widgets can be sensitive or insensitive; insensitive widgets do not respond to input.
(On other platforms, this is termed "ghosted" or "inactive").
gtk_widget_set_sensitive() (Figure 3-25) changes a widgets sensitivity.
#include <gtk/gtkwidget.h>
void gtk_widget_set_sensitive(GtkWidget* widget, gboolean setting);
#include <gtk/gtkwidget.h>
70
GTK_WIDGET_IS_SENSITIVE(widget);
GTK_WIDGET_SENSITIVE(widget);
Focus
Within each toplevel window, one widget at a time may have the keyboard focus. Any
key events received by the toplevel window are forwarded to the focused widget.
This is important because typing something on the keyboard should have only one
effectchanging only one text entry field, for example.
Most widgets will give some visual indication that they have the current focus. Using
the default GTK+ theme, the focused widget is typically surrounded by a thin black
frame. The user can move the focus between widgets, using the arrow keys or the
Tab key. Focus can also move to a widget if the user clicks it.
The concept of focus is important for keyboard navigation. For example, pressing
Enter or the space bar "activates" many widgets if they have the focus; you can move
between buttons with the Tab key, and press one with Space, for example.
Grabs
Widgets can grab the pointer and keyboard away from other widgets. This essentially
means that the widget becomes "modal"; input goes only to that widget, and the
focus cant be changed to another widget. A typical reason to grab input is to create a
modal dialog; if a window has the grab, interaction with other windows is blocked.
Note that there is another, GDK-level "grab"; a GDK keyboard or pointer grab occurs
on an X-server-wide basisthat is, other applications are unable to receive keyboard
or mouse events. A widget grab is a GTK+ concept; it only grabs events away from
other widgets in the same application.
Default
Each window may have at most one default widget. For example, dialogs typically
have a default button which is activated when the user presses the Enter key.
Widget States
Widgets have states which determine their appearance:
Active: a button is currently pressed in, or a check box is currently checked, for
example.
Prelight: the mouse is over the widget (and typically clicking would have some
effect). Buttons "highlight" when you move over them, for example.
Selected: the widget is in a list or other set of alternatives, and is the currently
selected option.
71
The exact meaning and visual representation of a given state depends on the particular widget and the current theme. You can access the state of the widget GTK_WIDGET_STATE()
(Figure 3-27). This macro returns one of the constants GTK_STATE_NORMAL, GTK_STATE_ACTIVE,
GTK_STATE_PRELIGHT, GTK_STATE_SELECTED, or GTK_STATE_INSENSITIVE.
#include <gtk/gtkwidget.h>
GTK_WIDGET_STATE(widget);
All instances of gtk_main() are functionally identical; they are all watching the same
connection to the X server and working from the same event queue. gtk_main()
instances are used to block, halting a functions flow of control until some conditions
are met. All GTK+ programs use this technique to keep main() from exiting while
the application is running. The gnome_dialog_run() function (see the section called
Modal Dialogs in Chapter 7) uses a recursive main loop, so it doesnt return until the
user clicks a dialog button.
Sometimes you want to process a few events, without handing the flow of control to gtk_main(). You can perform a single iteration of the main loop by calling
gtk_main_iteration(). This might process a single event, for example; it depends
on what tasks are pending. You can check whether any events need to be processed
by calling the gtk_events_pending() predicate. Together, these two functions allow
you to temporarily return control to GTK+, so the GUI can "catch up." For example,
during a long computation, you will want to display a progress bar; you must allow
the GTK+ main loop to run periodically, so GTK+ can redraw the progress bar. Use
this code:
72
while (gtk_events_pending())
gtk_main_iteration();
#include <gtk/gtkmain.h>
void gtk_main(void);
void gtk_main_quit(void);
void gtk_main_iteration(void);
gint gtk_events_pending(void);
guint gtk_main_level(void);
Quit Functions
A quit function is a callback to be invoked when gtk_main_quit() is called. In other
words, the callback runs just before gtk_main() returns. The callback should be a
GtkFunction, defined as follows:
typedef gint (*GtkFunction) (gpointer data);
Quit functions are added with gtk_quit_add() (Figure 3-29). When adding a quit
function, you must specify a main loop level, as returned by gtk_main_level().
The second and third arguments specify a callback and callback data.
The callbacks return value indicates whether the callback should be invoked again.
As long as the callback returns TRUE, it will be repeatedly invoked. As soon as it
returns FALSE, it is disconnected. When all quit functions have returned FALSE,
gtk_main() can return.
gtk_quit_add() returns an ID number that can be used to remove the quit function
with gtk_quit_remove(). You can also remove a quit function by passing its callback
data to gtk_quit_remove_by_data().
#include <gtk/gtkmain.h>
guint gtk_quit_add(guint main_level, GtkFunction function, gpointer data);
void gtk_quit_remove(guint quit_handler_id);
void gtk_quit_remove_by_data(gpointer data);
73
Timeout Functions
Timeout functions are connected and disconnected exactly as quit functions are; the expected callback is the same. gtk_timeout_add() expects an interval argument; the
callback is invoked every interval milliseconds. If the callback ever returns FALSE, it
is removed from the list of timeout functions, just as if youd called gtk_timeout_remove().
It is not safe to call gtk_timeout_remove() from within a timeout function; this modifies the timeout list while GTK+ is iterating over it, causing a crash. Instead, return
FALSE to remove a function.
#include <gtk/gtkmain.h>
guint gtk_timeout_add(guint32 interval, GtkFunction function, gpointer data);
void gtk_timeout_remove(guint timeout_handler_id);
Idle Functions
Idle functions run continuously while the GTK+ main loop has nothing else to do.
Idle functions run only when the event queue is empty and the main loop would
normally sit idly, waiting for something to happen. As long as they return TRUE
they are invoked over and over; when they return FALSE, they are removed, just as
if gtk_idle_remove() had been called.
The idle function API, shown in Figure 3-31, is identical to the timeout and quit function APIs. Again, gtk_idle_remove() should not be called from within an idle function, because it will corrupt GTK+s idle function list. Return FALSE to remove the
idle function.
Idle functions are mostly useful to queue "one-shot" code, which is run after all events
have been handled. Relatively expensive operations such as GTK+ size negotiation
and GnomeCanvas repaints take place in idle functions that return FALSE. This ensures that expensive operations are performed only once, even though multiple consecutive events independently request the recalculation.
The GTK+ main loop contains a simple scheduler; idle functions actually have priorities assigned to them, just as UNIX processes do. You can assign a non-default
priority to your idle functions, but its a complicated topic outside the scope of this
book.
#include <gtk/gtkmain.h>
guint gtk_idle_add(GtkFunction function, gpointer data);
void gtk_idle_remove(guint idle_handler_id);
void gtk_idle_remove_by_data(gpointer data);
74
Input Functions
Input functions are handled on the GDK level. They are invoked when a given file
descriptor is ready for reading or writing. Theyre especially useful for networked
applications.
To add an input function, you specify the file descriptor to monitor, the state you want
to wait for (ready for reading or writing), and a callback/data pair. Figure 3-32 shows
the API. Functions can be removed using the tag returned by gdk_input_add(). Unlike quit, timeout, and idle functions, it should be safe to call gdk_input_remove()
from inside the input function; GTK+ will not be in the midst of iterating over the list
of input functions.
To specify the condition(s) to wait for, use the GdkInputCondition flags: GDK_INPUT_READ,
GDK_INPUT_WRITE, and GDK_INPUT_EXCEPTION. You can OR one or more flags
together. These correspond to the three file descriptor sets passed to the select()
system call; consult a good UNIX programming book for details. If any condition is
met, the input function is invoked.
The callback should look like this:
typedef void (*GdkInputFunction) (gpointer data,
gint source_fd,
GdkInputCondition condition);
It receives your callback data, the file descriptor being watched, and the conditions
that were met (possibly a subset of those you were watching for).
#include <gdk/gdk.h>
gint gdk_input_add(gint source_fd, GdkInputCondition condition, GdkInputFunction function, gpointer data);
void gdk_input_remove(gint tag);
75
76
The libtool package is the third important GNU tool; its purpose is to abstract
the idiosyncracies of shared libraries (static library behavior is fairly uniform across
UNIX-like systems, but shared libraries present major portability issues).
Informally, here are some of characteristics most Gnome packages have in common:
A file called INSTALL that explains how to compile and install the package.
A script called configure that automatically adapts the program to platformspecific features (or the lack thereof). configure is expected to take an argument
-prefix, specifying where to install the package.
Tar files are traditionally compressed with gzip and their name includes the package version (for example, foo-0.2.1.tar.gz). They should unpack into a single
directory, named with package and versionfoo-0.2.1.
77
8. Run the gettextize program that comes with the gettext package. This creates the intl and po directories, needed for internationalization (gettextize
is documented in the gettext manual). The intl contains the GNU gettext
source code; if users compiling the program do not have gettext, they can pass
the -with-included-gettext option to configure to automatically compile a
static version in the intl directory. The po directory holds the translation files;
gettextize will also create a file called po/Makefile.in.in, used to build the
translations.
9. Create a file called po/POTFILES.in listing source files which should be scanned
for strings to translate. POTFILES.in can be empty at first.
10. Copy autogen.sh and the macros directory from another Gnome module. You
must modify autogen.sh to reflect the name of your package. Running autogen.sh will invoke libtoolize, aclocal, autoheader, automake, and autoconf.
11. autogen.sh invokes automake with the -add-missing argument. This will
add some files, such as INSTALL with generic installation instructions. You can
(and should) edit INSTALL to include any specific instructions for your application. autogen.sh will also create a Makefile in each directory.
configure.in
autoconf processes configure.in to produce a configure script. configure is a
portable shell script which examines the build environment to determine which libraries are available, which features the platform has, where libraries and headers
are located, and so on. Based on this information, it modifies compiler flags, generates makefiles, and/or outputs the file config.h with appropriate preprocessor
symbols defined. Again, configure does not require autoconf to run; you generate
it before distributing your software, so users do not have to have autoconf.
Your job is to write configure.in. The file is basically a series of m4 macros, which
expand to snippets of shell script according to the parameters you pass them. You can
also write shell code manually. Really understanding how to write a configure.in
requires some knowledge of m4 (which is pretty simple) and some knowledge of the
Bourne shell (which is a black art). Fortunately, you can cheat: start with an existing
configure.in and modify it slightly to suit your application. Theres also an extensive autoconf manual, which describes the many pre-written macros shipped with
autoconf.
The GTK+ and Gnome developers have simplified things still further, by providing
macros to locate GTK+ and Gnome on the users system.
Here is a sample configure.in, from a Gnome version of "Hello, World":
AC_INIT(src/hello.c)
AM_CONFIG_HEADER(config.h)
AM_INIT_AUTOMAKE(GnomeHello, 0.1)
AM_MAINTAINER_MODE
AM_ACLOCAL_INCLUDE(macros)
GNOME_INIT
AC_PROG_CC
78
AC_ISC_POSIX
AC_HEADER_STDC
AC_ARG_PROGRAM
AM_PROG_LIBTOOL
GNOME_COMPILE_WARNINGS
ALL_LINGUAS="da de es fr gl nl no pl ru sv fi uk"
AM_GNU_GETTEXT
AC_SUBST(CFLAGS)
AC_SUBST(CPPFLAGS)
AC_SUBST(LDFLAGS)
AC_OUTPUT([
Makefile
macros/Makefile
src/Makefile
intl/Makefile
po/Makefile.in
pixmaps/Makefile
doc/Makefile
doc/C/Makefile
doc/es/Makefile
])
Before describing each macro, some general points should be made. First, those macros
that begin with AC come with autoconf, and those that begin with AM usually come
with automake. (This is useful when youre trying to find documentation for them.)
The macros that begin with GNOME come in the Gnome macros directory. These macros
are written in m4; the standard ones from autoconf/automake reside in /usr/share/aclocal,
if you installed autoconf/automake under /usr. (An aside: the macros directory is
not a good thing; each Gnome package should install its own m4 files to /usr/share/aclocal.
Newer Gnome versions attempt to fix the problem.)
AC_INIT is always the first macro in configure.in. It expands to a lot of boilerplate code shared by all configure scripts; this code parses the command line
arguments to configure. The macros one argument is a file that should be present
in the source directory; this is used as a sanity check, to be sure configure has correctly located the source directory.
79
to shoot themselves in the foot. Note, however, that the autogen.sh script used
in Gnome automatically passes -enable-maintainer-mode to configure, since
autogen.sh is intended for developers to use.
AC_ISC_POSIX adds some flags needed for POSIX compatibility on certain platforms.
AC_HEADER_STDC checks whether the present system has the standard ANSI
header files, and defines STDC_HEADERS if so.
ALL_LINGUAS="es" is not a macro, just a bit of shell code. It contains a spaceseparated list of language abbreviations, corresponding to .po files in the po subdirectory. (.po files contain translations into other languages, so ALL_LINGUAS should
list all languages your program has been translated into.)
AC_OUTPUT lists the files to be created by the configure script. These will be
created from a file with the same name, with .in appended. For example, the output file src/Makefile is generated from src/Makefile.in, and config.h comes
from config.h.in.
In the AC_OUTPUT stage, configure processes files containing variables marked with
two @ symbols; for example, @PACKAGE@. It recognizes such variables only if AC_SUBST
was used to "export" the variable (many of the pre-written macros discussed above
use AC_SUBST to define variables). Most commonly, this features is used to convert a Makefile.in to a Makefile. Makefile.in is typically generated by automake
from Makefile.am. (However, you can use autoconf without automake, and write
Makefile.in yourself.)
Makefile.am
automake processes Makefile.am to produce a standards-compliant Makefile.in.
80
automake does a lot of work for you: it keeps up with dependencies between source
files, for example. It creates all the standard targets, such as install and clean.
It also creates more complex targets: simply typing make dist creates a standard
.tar.gz file if your Makefile.am is correct.
The Makefile.am in the top source directory is generally very simple; here is an
example:
SUBDIRS = macros po intl src pixmaps doc
## We dist autogen.sh since this is an example program
## Real-world programs do not need to distribute autogen.sh
EXTRA_DIST = \
gnome-hello.desktop \
autogen.sh
Applicationsdir = $(datadir)/gnome/apps/Applications
Applications_DATA = gnome-hello.desktop
The SUBDIRS line instructs automake to recursively look for Makefile.am files in the
given subdirectories. (the section called .desktop Entries describes the remainder
of the file, ignore it for now.) The Makefile.am in the src directory is a little more
interesting:
INCLUDES = -I$(top_srcdir) -I$(includedir) $(GNOME_INCLUDEDIR) \
-DG_LOG_DOMAIN=\"GnomeHello\" -DGNOMELOCALEDIR=\""$(datadir)/locale"\" \
-I../intl -I$(top_srcdir)/intl
bin_PROGRAMS = gnome-hello
gnome_hello_SOURCES =
app.c
hello.c
menus.c \
app.h \
hello.h \
menus.h
\
\
\
automake understands a number of "magic variables" and can use them to create
Makefile.in. In the small example above, the following variables are used:
INCLUDES specifies flags to pass to the C compiler during the compile phase (as
opposed to the link phase). The variables used in this line come from the configure.in shown in the previous section.
bin_PROGRAMS
hello_SOURCES lists the files to be compiled and linked to create the program
called hello; hello must be listed in bin_PROGRAMS. All files in this variable are
automatically included in the distribution.
hello_LDADD lists flags to be passed to the linker. In this case, Gnome library flags
determined by configure.
81
Several elements of the INCLUDES line should be used in all Gnome programs. G_LOG_DOMAIN
should always be defined; error messages from checks and assertions will report this
value, so you can determine where the error occurred (in your code, or in a library).
GNOMELOCALEDIR is used to locate translation files. The intl directory is added to the
header search path so the application can find the intl headers.
There are many more complex things one can do in Makefile.am; in particular, you
can add @-bounded variables to be substituted by configure, you can conditionally
include portions of the Makefile based on configure checks, and you can build
libraries. The automake manual gives more details.
Table 4-1 summarizes the most interesting targets generated by automake. Of course
the default target is all, which compiles the program. The GNU Coding Standards
(http://www.gnu.org/prep/standards_toc.html) have more information about these
targets and GNU makefiles in general.
Table 4-1. Standard make targets
Target
dist
Description
Builds a tarball (.tar.gz) for
distribution
distcheck
clean
install
uninstall
distclean
mostlyclean
maintainer-clean
TAGS
check
82
The libtool manual explains the intermediate .lo and .la files created while
The autoconf manual explains how to write configure.in and its associated
files.
The automake manual explains how to write a Makefile.am.
The gettext manual has sections titled "Programmers" and "Maintainers"; you
should read these to learn how the intl and po subdirectories work.
The GNU coding standards describe how GNU packages should behave; autoconf and automake try to implement these standards.
The GNU hello package is intended to demonstrate the GNU packaging standards, and is an excellent source of examples. "GnomeHello" and other Gnome
packages are a good source of Gnome-specific examples, of course.
The manuals for make, the Bourne shell, and m4 are essential if you need to write
custom configure checks or add Makefile targets outside of automakes capabilities.
Pixmaps
To install datafiles from your Makefile.am you simply come up with a name for
the install targetpixmap seems goodthen create a variable for the directory and a
corresponding variable for the files to install there. For example:
EXTRA_DIST = gnome-hello-logo.png
pixmapdir = $(datadir)/pixmaps
pixmap_DATA = gnome-hello-logo.png
The "pixmap" string connects the pixmapdir variable with the pixmap_DATA variable. automake interprets the _DATA suffix and generates appropriate rules in Makefile.in. This Makefile.am segment installs gnome-hello-logo.png into $(datadir)/pixmaps;
$(datadir) is a variable filled in by configure. Typically $(datadir) is /usr/local/share
(more precisely, $(prefix)/share), which is the standard location for architectureindependent data files (that is, files which can be shared between several systems
with different binary file formats).
83
Documentation
Installing documentation uses the same principles, with a little more complication.
Gnome documentation is typically written in DocBook. DocBook is an SGML DTD
("Document Type Definition") just as HTML is. However, DocBooks tags are designed for technical documentation. Documentation written in DocBook can be converted to several other formats, including PostScript and HTML. Standardly, you
want to install the HTML format so users can read it with their web browser or the
Gnome help browser.
The Gnome libraries and help browser understand a file called topic.dat, which is
simply a list of help topics with corresponding URLs. It serves as an index of help
topics for your application. Heres an example, with only two entries:
gnome-hello.html
advanced.html
GnomeHello manual
Advanced Topics
URLs are relative to the directory where you install your help files.
You should consider in advance that your documentation will be translated into other
languages. It is nice to make a subdirectory in your source tree for each locale; for
example, the default C locale or the es (Spanish) locale. That way translations dont
cause clutter. Gnome expects help to be installed in a directory named after the locale,
so this arrangement is convenient from that point of view as well. Your documentation directory might look like this one from the GnomeHello example application:
doc/
Makefile.am
C/
Makefile.am
gnome-hello.sgml
topic.dat
es/
Makefile.am
gnome-hello.sgml
topic.dat
Here is doc/C/Makefile.am:
gnome_hello_helpdir = $(datadir)/gnome/help/gnome-hello/C
gnome_hello_help_DATA =
gnome-hello.html
topic.dat
\
\
SGML_FILES =
gnome-hello.sgml
84
topic.dat
$(SGML_FILES)
In particular notice the install directory for the generated HTML files: $(datadir)/gnome/help/gnomehello/C. The Gnome libraries look for help here. Each applications help goes in
its own directory under $(datadir)/gnome/help. Each locales documentation is
installed in its own subdirectory of the application directory. Other rules in Makefile.am run the DocBook-to-HTML converter, include HTML in the distribution tarball, and create PostScript and Rich Text Format targets. (Users can create PostScript
by typing make gnome-hello.ps explicitly.)
.desktop Entries
Gnome programs come with ".desktop entries," which are simply small files describing how the application should appear in menus. Installing a .desktop entry causes your application to show up in the Gnome panel menu. Here is gnomehello.desktop:
[Desktop Entry]
Name=Gnome Hello
Name[es]=Gnome Hola
Name[fi]=GNOME-hei
Name[gl]=Ola GNOME
Name[no]=Gnome hallo
Name[sv]=Gnome Hej
85
Name[pl]=Halo GNOME
Comment=Hello World
Comment[es]=Hola Mundo
Comment[fi]=Hei, maailma
Comment[gl]=Ola Mundo
Comment[sv]=Hej Vrlden
Comment[no]=Hallo verden
Comment[pl]=Witaj wiecie
Exec=gnome-hello
Icon=gnome-hello-logo.png
Terminal=0
Type=Application
The file consists of key-value pairs. The Name key specifies the name of your application in the default (C) locale; any key can have translations with a locale appended
in brackets, such as Name[es]. The Comment key is a "tooltip" or hint describing the
application in more detail. Exec is the command line to use to execute the program.
Terminal is a boolean value; if non-zero, the program will be run inside a terminal.
Type should always be "Application" in this context.
Installing a .desktop entry is simple; here is the toplevel Makefile.am from GnomeHello again:
SUBDIRS = macros po intl src pixmaps doc
## We dist autogen.sh since this is an example program
## Real-world programs do not need to distribute autogen.sh
EXTRA_DIST = \
gnome-hello.desktop \
autogen.sh
Applicationsdir = $(datadir)/gnome/apps/Applications
Applications_DATA = gnome-hello.desktop
Notice that there is a directory tree under $(datadir)/gnome/apps/ with subdirectories that arrange programs into categories. GnomeHello installs itself in the "Applications" category; other programs might choose "Games," "Graphics," "Internet,"
or whatever is appropriate. Try to choose a category that already exists, rather than
inventing your own.
EXTRA_DIST
The EXTRA_DIST variable in a Makefile.am lists files to be included in the distribution (tarball). Most important files are automatically included; for example, all files
listed as source files for binaries or libraries. However, automake does not know
about .desktop files, or SGML documentation; so these files must be listed in EXTRA_DIST. make distchecks attempt to build the distribution will normally fail if
you leave files out of EXTRA_DIST.
86
#include <libgnomeui/gnome-init.h>
int gnome_init(const char* app_id, const char* app_version, int argc, char**
argv);
Internationalization
All user-visible strings in a Gnome application should be marked for translation.
Translation is achieved using the GNU gettext facility. gettext is simply a message
catalog; it stores key-value pairs, where the key is the string hard-coded into the
program, and the value is a translated string (if appropriate) or simply the key (if
theres no translation, or the key is already in the correct language).
As a programmer, its not your responsibility to provide translations. However, you
must make sure strings are marked for translationso that gettexts scripts can
extract a list of strings to be translatedand you must call a special function on each
string when the catalog lookup should take place.
87
#include <libgnome/gnome-i18n.h>
_(string);
N_(string);
Notice that the string literals "Translate Me" and "Me Too" are marked so that gettext
can find them and produce a list of strings to be translated. Translators will use this
list to create the actual translations. Later, _() includes a function call to perform the
tranlation lookup on each member of the array. Since a function call is allowed when
the string literal "Translated String" is introduced, everything can happen in a single
step.
At the beginning of your program, you have to call bindtextdomain() and textdomain() as shown in the above example. In the above code, PACKAGE is a string representing the package the program is found in, typically defined in config.h (see
Chapter 4). You must arrange to define GNOMELOCALEDIR, typically in your Makefile.am ($(prefix)/share/locale, or $(datadir)/locale, is the standard value).
Translations are stored in GNOMELOCALEDIR.
When marking strings for translation, you must make sure your strings are translatable. Avoid constructing a string at runtime via concatenation. For example, do not
do this:
gchar* message = g_strconcat(_("There is an error on device "),
device, NULL);
The problem is that in some languages it may be correct to put the name of the device
first (or in the middle). If you use g_snprintf() or g_strdup_printf() instead of
88
concatenation, the translator can change the word order. Heres the right way to do
it:
gchar* message = g_strdup_printf(_("There is an error on device %s"),
device);
However, as the gettext manual points out, even this will not always work; some
languages will distinguish more categories than "exactly one" and "more than one"
(that is, they might have a word form for "exactly two" in addition to Englishs singular and plural forms). That manual suggests that a lookup table indexed by the
number you plan to use might work in some cases:
static const char* ndogs_phrases[] = {
N_("There were no dogs.\n"),
N_("There was one dog.\n"),
N_("There were two dogs.\n"),
N_("There were three dogs.\n")
};
As you can see, this rapidly becomes unpleasant to deal with. Avoid it if you can. The
gettext documentation has more examples, if you find yourself in a hairy situation.
Internationalization must also be considered when parsing or displaying certain kinds
of data, including dates and decimal numbers. In general, the C library provides sufficient facilities to deal with this; use strftime(), strcoll(), and so on to handle
these cases; a good C or POSIX book will explain them. The glib GDate facility handles dates using strftime() internally.
One common mistake to avoid: dont use locale-dependent functions when reading
and writing files. For example, printf() and scanf() adjust their decimal number
format for the locale, so you cant use this format in files. Users in Europe wont be
able to read files created in the United States.
89
#include <libgnomeui/gnome-init.h>
int gnome_init_with_popt_table(const char* app_id, const char* app_version,
int argc, char** argv, const struct poptOption* options, int flags, poptContext* return_ctx);
The first two components are the long and short names for the option; for example,
"help" and h would correspond to command-line options -help and -h. These can
be NULL and \0 respectively, if you want only one name for the option.
The arginfo member tells what kind of table entry this is. Here are the possible values:
POPT_ARG_INCLUDE_TABLE means that this struct poptOption does not specify an option, but rather another popt table to be included.
POPT_ARG_INTL_DOMAIN means that this struct poptOption specifies the translation domain for this table and any subtables.
The meaning of arg depends on the arginfo member. For options that take an argument, arg should point to a variable of the argument type. popt will fill the pointed-to
variable with the argument. For POPT_ARG_NONE, *arg is set to TRUE if the option
is found on the command line. In all cases, arg may be NULL, causing popt to ignore
it.
90
X display to use
Here argDescrip is "DISPLAY" and descrip is "X display to use." Remember to mark
these two strings for translation.
descrip has a slightly different meaning for POPT_ARG_INCLUDE_TABLE; in this
case it titles a "group" of options in the help output. For example, "Help options" in
the following output:
Help options
-?, -help
-usage
The opaque poptContext object contains all of popts state. This makes it possible to
use popt more than once in the same program, or parse more than one set of options
simultaneously. You can also extract information about the current parsing state from
the poptContext, using functions provided by popt.
Possible poptCallbackReason values are:
POPT_CALLBACK_REASON_PRE
POPT_CALLBACK_REASON_POST
POPT_CALLBACK_REASON_OPTION
Your callback is called once for each option found on the command line with POPT_CALLBACK_REASON_
as the reason argument. If you request, it can also be called before and after argument parsing. In these cases reason will be POPT_CALLBACK_REASON_PRE or
POPT_CALLBACK_REASON_POST. To specify that you want your callback to be
called before or after parsing, you have to combine a pair of flags with POPT_ARG_CALLBACK.
For example, the following struct poptOption initializer specifies a callback to be invoked both before and after argument parsing:
91
The opt argument to the callback is the struct poptOption corresponding to the most
recently-seen command line option (you can access the val member of this struct
to determine which option you are looking at). The arg argument is the text of any
argument passed to the command line option; the data argument is the callback data,
given as the descrip member of the struct poptOption which specified the callback.
The flags argument to gnome_init_with_popt_table() can basically be ignored in
a Gnome context; the available flags are not very useful.
If you pass a non-NULL pointer for return_ctx, the final argument to gnome_init_with_popt_table(),
the current context will be returned; you can use this to extract the non-option components of the command line, such as filenames. This is done with the function poptGetArgs()heres an example:
char** args;
poptContext ctx;
int i;
bindtextdomain (PACKAGE, GNOMELOCALEDIR);
textdomain (PACKAGE);
gnome_init_with_popt_table(APPNAME, VERSION, argc, argv,
options, 0, &ctx);
args = poptGetArgs(ctx);
if (args != NULL)
{
i = 0;
while (args[i] != NULL)
{
/* Do something with each argument */
++i;
}
}
poptFreeContext(ctx);
Notice that you must free the poptContext if you ask for it; however, if you pass
NULL for return_ctx the library will free it for you. Also keep in mind that poptGetArgs() will return NULL if there are no arguments on the command line.
92
-espeaker=HOSTNAME:PORT
Help options
-?, -help
-usage
GTK options
-gdk-debug=FLAGS
-gdk-no-debug=FLAGS
-display=DISPLAY
-sync
-no-xshm
-name=NAME
-class=CLASS
-gxid_host=HOST
-gxid_port=PORT
-xim-preedit=STYLE
-xim-status=STYLE
-gtk-debug=FLAGS
-gtk-no-debug=FLAGS
-g-fatal-warnings
-gtk-module=MODULE
Gtk+
Gtk+
Make
Load
GnomeHello options
-g, -greet
-m, -message=MESSAGE
-geometry=GEOMETRY
Almost all of these options are common to all Gnome applications; only the last three,
labelled "GnomeHello options," are specific to GnomeHello. The -greet or -g option
turns on "greet mode"; GnomeHello will expect a list of names on the command line,
and create a dialog to say hello to each person named. The -message option expects
a string argument which replaces the usual "Hello, World!" message; the -geometry
option expects a standard X geometry string, specifying the position and size of the
main application window.
Here are the variables and popt table GnomeHello uses to do its argument parsing:
static int greet_mode = FALSE;
static char* message = NULL;
static char* geometry = NULL;
struct poptOption options[] = {
{
"greet",
93
g,
POPT_ARG_NONE,
&greet_mode,
0,
N_("Say hello to specific people listed on the command line"),
NULL
},
{
"message",
m,
POPT_ARG_STRING,
&message,
0,
N_("Specify a message other than \"Hello, World!\""),
N_("MESSAGE")
},
{
"geometry",
\0,
POPT_ARG_STRING,
&geometry,
0,
N_("Specify the geometry of the main window"),
N_("GEOMETRY")
},
{
NULL,
\0,
0,
NULL,
0,
NULL,
NULL
}
};
And heres the first part of main(), where GnomeHello checks that the arguments
are properly combined and assembles a list of people to greet:
GtkWidget* app;
poptContext pctx;
char** args;
int i;
GSList* greet = NULL;
GnomeClient* client;
bindtextdomain(PACKAGE, GNOMELOCALEDIR);
textdomain(PACKAGE);
gnome_init_with_popt_table(PACKAGE, VERSION, argc, argv,
options, 0, &pctx);
/* Argument parsing */
args = poptGetArgs(pctx);
if (greet_mode && args)
94
{
i = 0;
while (args[i] != NULL)
{
greet = g_slist_prepend(greet, args[i]);
++i;
}
/* Put them in order */
greet = g_slist_reverse(greet);
}
else if (greet_mode && args == NULL)
{
g_error(_("You must specify someone to greet."));
}
else if (args != NULL)
{
g_error(_("Command line arguments are only allowed with -greet."));
}
else
{
g_assert(!greet_mode && args == NULL);
}
poptFreeContext(pctx);
ration files. Convenience routines are provided for numeric and boolean types which
transparently convert to and from a text representation of each type. The standard
location for Gnome configuration files is ~/.gnome, and the library will use that location by default. However, the library can be used with any file. There are also variants
of each function which save to ~/.gnome_private, a directory with user permissions
only. The basic functions to store and retrieve data are listed in Figure 5-4 and Figure
5-5. This module of libgnome is often referred to as gnome-config. Dont confuse
this usage of "gnome-config" with the gnome-config script that reports the compile
and link flags for Gnome programs.
The gnome-config functions work with a path. A path has three components:
95
may also be a better choice for storing some kinds of configuration information; the
primary advantage of the libgnome configuration library is its simplicity.
gnome-config has a long history; it was first written for the WINE Windows emu-
lator project, then used in the GNU Midnight Commander file manager, and finally
migrated into the Gnome libraries. The plan is to replace gnome-config with something more powerful in the next version of Gnome; we want to support per-host configuration, backends such as LDAP, and other features. However, the gnome-config
API will almost certainly be supported even if the underlying engine changes dramatically.
If the config file doesnt exist yet, or there is no key matching the path you provide,
these functions return 0, FALSE, or NULL. The functions that return a string return
allocated memory; you should g_free() the returned string. The string vector functions return an allocated vector full of allocated strings (g_strfreev() is the easiest
way to free this vector).
You can specify a default value to be returned if the key does not exist; to do so,
append an "=value" to the path. For example:
gboolean show_dialog;
show_dialog =
gnome_config_get_bool("/myapp/General/dialog=true");
Each function has a with_default variant; these tell you whether the return value was
taken from a config file or from the default you specified. For example:
gboolean show_dialog;
gboolean used_default;
show_dialog =
gnome_config_get_bool_with_default("/myapp/General/dialog=true",
&used_default);
if (used_default)
printf("Default value used for show_dialog\n");
be used to avoid specifying the entire path each time. For example:
96
gboolean show_dialog;
gnome_config_push_prefix("/myapp/General/");
show_dialog =
gnome_config_get_bool("dialog=true");
gnome_config_pop_prefix();
#include <libgnome/gnome-config.h>
gchar* gnome_config_get_string(const gchar* path);
gchar* gnome_config_get_translated_string(const gchar* path);
gint gnome_config_get_int(const gchar* path);
gdouble gnome_config_get_float(const gchar* path);
gboolean gnome_config_get_bool(const gchar* path);
void gnome_config_get_vector(const gchar* path, gint* argcp, gchar*** argvp);
gchar* gnome_config_private_get_string(const gchar* path);
gchar* gnome_config_private_get_translated_string(const gchar* path);
gint gnome_config_private_get_int(const gchar* path);
gdouble gnome_config_private_get_float(const gchar* path);
gboolean gnome_config_private_get_bool(const gchar* path);
void gnome_config_private_get_vector(const gchar* path, gint* argcp, gchar***
argvp);
gchar* gnome_config_get_string_with_default(const gchar* path, gboolean* was_default);
gchar* gnome_config_get_translated_string_with_default(const gchar* path, gboolean*
was_default);
gint gnome_config_get_int_with_default(const gchar* path, gboolean* was_default);
gdouble gnome_config_get_float_with_default(const gchar* path, gboolean* was_default);
gboolean gnome_config_get_bool_with_default(const gchar* path, gboolean* was_default);
void gnome_config_get_vector_with_default(const gchar* path, gint* argcp,
gchar*** argvp, gboolean* was_default);
gchar* gnome_config_private_get_string_with_default(const gchar* path, gboolean*
was_default);
gchar* gnome_config_private_get_translated_string_with_default(const gchar*
path, gboolean* was_default);
gint gnome_config_private_get_int_with_default(const gchar* path, gboolean*
was_default);
gdouble gnome_config_private_get_float_with_default(const gchar* path, gboolean*
was_default);
gboolean gnome_config_private_get_bool_with_default(const gchar* path, gboolean*
was_default);
void gnome_config_private_get_vector_with_default(const gchar* path, gint*
argcp, gchar*** argvp, gboolean* was_default);
97
#include <libgnome/gnome-config.h>
void gnome_config_set_string(const gchar* path, const gchar* value);
void gnome_config_set_translated_string(const gchar* path, const gchar* value);
void gnome_config_set_int(const gchar* path, gint value);
void gnome_config_set_float(const gchar* path, gdouble value);
void gnome_config_set_bool(const gchar* path, gboolean value);
void gnome_config_set_vector(const gchar* path, gint argc, const gchar* const
argv[]);
void gnome_config_private_set_string(const gchar* path, const gchar* value);
void gnome_config_private_set_translated_string(const gchar* path, const gchar*
value);
void gnome_config_private_set_int(const gchar* path, gint value);
void gnome_config_private_set_float(const gchar* path, gdouble value);
void gnome_config_private_set_bool(const gchar* path, gboolean value);
void gnome_config_private_set_vector(const gchar* path, gint argc, const
gchar* const argv[]);
98
config_iterator = gnome_config_init_iterator("/gnome-apt/ColumnOrder");
if (config_iterator != 0)
{
gchar * col, * pos;
columns.reserve(GAptPkgTree::ColumnTypeEnd);
loaded = 0;
while ((config_iterator =
gnome_config_iterator_next(config_iterator,
&col, &pos)))
{
// shouldnt happen, but Im paranoid
if (pos == 0 || col == 0)
{
if (pos) g_free(pos);
if (col) g_free(col);
continue;
}
GAptPkgTree::ColumnType ct = string_to_column(col);
gint index = atoi(pos);
g_free(pos); pos = 0;
g_free(col); col = 0;
// the user could mangle the config file to make this happen
if (static_cast<guint>(index) >= columns.size())
continue;
columns[index] = ct;
++loaded;
}
}
if (loaded != static_cast<guint>(GAptPkgTree::ColumnTypeEnd))
{
// Either there was no saved order, or something is busted - use
// default order
columns.clear();
int i = 0;
while (i < GAptPkgTree::ColumnTypeEnd)
{
columns.push_back(static_cast<GAptPkgTree::ColumnType>(i));
++i;
}
// Clean the section - otherwise an old entry could
// remain forever and keep screwing us up in the future.
gnome_config_clean_section("/gnome-apt/ColumnOrder");
gnome_config_sync();
}
g_return_if_fail(columns.size() ==
static_cast<guint>(GAptPkgTree::ColumnTypeEnd));
}
99
It might be helpful to see the function that saves the column positions:
static void
save_column_order(const vector<GAptPkgTree::ColumnType> & columns)
{
g_return_if_fail(columns.size() ==
static_cast<guint>(GAptPkgTree::ColumnTypeEnd));
int position = 0;
vector<GAptPkgTree::ColumnType>::const_iterator i = columns.begin();
while (i != columns.end())
{
gchar key[256];
g_snprintf(key, 255, "/gnome-apt/ColumnOrder/%s", column_to_string(*i));
gchar val[30];
g_snprintf(val, 29, "%d", position);
gnome_config_set_string(key, val);
++position;
++i;
}
gnome_config_sync();
}
When writing this code, the decision was made to store enumeration values as strings
rather than integers. The column_to_string() and string_to_column() functions
use a simple array of column names indexed by the enumeration values to convert
back and forth. There are two reasons to do this: it will not break when the enumeration is altered in future versions of the program, and it keeps the configuration file
human-editable.
You may also notice that the column positions are stored with gnome_config_set_string()
instead of gnome_config_set_int(). This is because gnome_config_iterator_next()
returns a string representation of the stored information, as found in the file. Most
likely, gnome_config_set_int() stores integers as strings atoi() would understand
(in fact it does), but it is technically not guaranteed by the API. If the code used
gnome_config_set_int(), it would have to obtain only the key from gnome_config_iterator_next()
and then call gnome_config_get_int() to obtain the integer value. Using atoi() on
the string value would make unwarranted assumptions about gnome-configs implementation.
Section Iterators
ignores its value argument and places the section name in the key argument.
#include <libgnome/gnome-config.h>
100
Functions are also provided to get the "real" (filesystem) path of a configuration file
from a gnome-config path. These are unlikely to be useful in application code.
#include <libgnome/gnome-config.h>
gboolean gnome_config_has_section(const gchar* path);
gboolean gnome_config_private_has_section(const gchar* path);
void gnome_config_drop_all(void);
void gnome_config_sync(void);
void gnome_config_sync_file(const gchar* path);
void gnome_config_private_sync_file(const gchar* path);
void gnome_config_drop_file(const gchar* path);
void gnome_config_private_drop_file(const gchar* path);
void gnome_config_clean_file(const gchar* path);
void gnome_config_private_clean_file(const gchar* path);
void gnome_config_clean_section(const gchar* path);
void gnome_config_private_clean_section(const gchar* path);
void gnome_config_clean_key(const gchar* path);
void gnome_config_private_clean_key(const gchar* path);
gchar* gnome_config_get_real_path(const gchar* path);
gchar* gnome_config_private_get_real_path(const gchar* path);
void gnome_config_push_prefix(const gchar* path);
void gnome_config_pop_prefix(void);
101
Session Management
The term session refers to a snapshot of the state of a users desktop: what applications
are open, where their windows are located, what windows each application has open,
what size those windows are, what documents are open, current cursor position,
and so on. Users should be able to save their session before logging out, and have it
automatically restored as closely as possible next time they log in. For this to work,
applications must cooperate by having the ability to record and restore those aspects
of their state not controlled by the window manager.
A special program called the session manager notifies applications when they should
save their state. The Gnome desktop environment comes with a session manager
called gnome-session, but Gnome uses the X session management specification,
which is several years old. CDE uses the same specification, and at press time, KDE
was planning to adopt it as well; an application that implements session management
via the Gnome interfaces should work on any session-managed desktop. Gnome
does implement some extensions to the basic specification (notably, startup "priorities") but these should not break other session managers and will likely be implemented in KDE as well.
Its worthwhile to read the session management documentation that comes with X;
its a good introduction to whats going on "behind the scenes." The Gnome libraries
also come with a useful document, called session-management.txt; have a look at
it, and the heavily-commented gnome-client.h header file, for additional details not
covered in this section.
When a session is saved, the session manager will ask each client to save enough
information to restore its state the next time the user logs in. Your application
should save as much interesting state as possible: the current open documents,
cursor position, command histories, and so on. Applications should not save their
current window geometries; the window manager is responsible for that.
Sometimes the session manager will ask your client to shut down and exit (typically when the user logs out). When you receive this request you should do whatever is necessary to exit the application.
When the session manager requests action from your application, a the GnomeClient
object emits an appropriate signal. The two important signals are "save_yourself"
and "die". "save_yourself" is emitted when an application should save its state, and
"die" is emitted when an application should exit. A "save_yourself" callback is fairly
complex and has quite a few arguments; a "die" callback is trivial.
GnomeHello obtains a pointer to the GnomeClient object and connects to its signals
as follows:
client = gnome_master_client ();
gtk_signal_connect (GTK_OBJECT (client), "save_yourself",
GTK_SIGNAL_FUNC (save_session), argv[0]);
gtk_signal_connect (GTK_OBJECT (client), "die",
GTK_SIGNAL_FUNC (session_die), NULL);
102
This is a bit more complex. A "save_yourself" must tell the session manager how
to restart and "clone" (create a new instance of) the application. The restarted application should remember as much state as possible; in GnomeHellos case, it will
remember the message being displayed. The simplest way to store application state
is to generate a command line, as GnomeHello does. Its also possible to ask GnomeClient for a prefix to be used with the gnome-config API; you can then save information to a per-session configuration file. Applications with significant state will need
to use this method.
103
Menu and toolbars can be detached from the window, or rearranged in relation to
one another and the main window contents.
Users can elect to disable detachable bars for all Gnome applications.
Users can choose whether to have small icons in the applications menus.
Figure 6-1. The Gnumeric spreadsheet, which uses the GnomeApp widget
104
GnomeApp has the usual constructor function, shown in Figure 6-2. The first argument,
app_id, is an internal name Gnome can use to work with this application. It should
be the same as the app_id passed to gnome_init(); the name of the executable is a
good choice. The second argument is simply a title for the application window; if you
use NULL here, the title will not be set.
#include <libgnomeui/gnome-app.h>
GtkWidget* gnome_app_new(gchar* app_id, gchar* title);
ality of your application. On all four sides of this central area, you can add toolbars,
menubars, and statusbars. Figure 6-3 lists the relevant functions.
These functions should be self-explanatory. They simply install the widget you give
them in the appropriate place on the GnomeApp. There are easy ways to create the
menubar, toolbar, and statusbar; the remainder of this chapter describes them.
#include <libgnomeui/gnome-app.h>
void gnome_app_set_contents(GnomeApp* app, GtkWidget* contents);
void gnome_app_set_menus(GnomeApp* app, GtkMenuBar* menubar);
void gnome_app_set_toolbar(GnomeApp* app, GtkToolbar* toolbar);
void gnome_app_set_statusbar(GnomeApp* app, GtkWidget* statusbar);
105
A static initializer is the most convenient way to fill in the struct (but of course
you can create it dynamically if you prefer). Gnomes routines accept an array of
GnomeUIInfo, and macros are provided to simplify and standardize the most common static initializers. Heres a typical example, a File menu:
static GnomeUIInfo file_menu[] = {
GNOMEUIINFO_MENU_NEW_ITEM(N_("_New Window"),
N_("Create a new text viewer window"),
new_app_cb, NULL),
GNOMEUIINFO_MENU_OPEN_ITEM(open_cb,NULL),
GNOMEUIINFO_MENU_SAVE_AS_ITEM(save_as_cb,NULL),
GNOMEUIINFO_SEPARATOR,
GNOMEUIINFO_MENU_CLOSE_ITEM(close_cb,NULL),
GNOMEUIINFO_MENU_EXIT_ITEM(exit_cb,NULL),
GNOMEUIINFO_END
};
There isnt always a nice macro for the menu item you want, so sometimes you must
manually specify each element of the struct:
{
GNOME_APP_UI_ITEM, N_("_Select All"),
N_("Select all cells in the spreadsheet"),
select_all_cb, NULL,
NULL, 0, 0, a, GDK_CONTROL_MASK
}
By now youre probably wondering what the struct members mean. Simple enough.
Heres a breakdown:
label is the text of the menu or toolbar button. It should be marked for internationalization with the N_() macro.
hint is a long description of the items function. For toolbar buttons, it will appear
in a tooltip; for menus, it can be made to appear in the statusbar.
user_data will be passed to your callback function, if this item type has a callback.
unused_data should be set to NULL, and is not used yet. It may be used in future
versions of Gnome.
pixmap_info can be raw pixmap data, a filename, or the name of a Gnome stock
pixmap.
accelerator_key is the key to be used as an accelerator for this item . You can use a
character such as a, or a value from gdk/gdkkeysyms.h.
106
type is a type marker from the GnomeUIInfoType enumeration. See Table 6-1.
You might also be wondering why the menu item names contain an underscore. The
underscore is used to mark the key shortcut for the menu item; translators can move
it around as needed to make it intuitive in their language. Gnome will parse the menu
item name to obtain the accelerator, then remove the underscore.
Table 6-1 summarizes the possible values for the type field of a GnomeUIInfo struct.
See libgnomeui/gnome-app-helper.h for more details. There are actually a few
more possible values, but the others are used internally by the library. The values
in Table 6-1 should be sufficient for application code.
Table 6-1. GnomeUIInfoType Values
GnomeUIInfoType
Description
Terminates a table of
GNOME_APP_UI_ENDOFINFO
GnomeUIInfo
moreinfo Field
None
GNOME_APP_UI_ITEM
Submenu
GNOME_APP_UI_SUBTREE
Array of GnomeUIInfo in
the subtree
Separator
GNOME_APP_UI_SEPARATOR
None
GNOME_APP_UI_HELP
Help item
To create an entire menu tree, you include pointers to previous menu tables using the
GNOMEUIINFO_SUBTREE() macro:
static GnomeUIInfo main_menu[] = {
GNOMEUIINFO_SUBTREE(N_("_File"), file_menu),
GNOMEUIINFO_END
};
The main advantage of this macro is standardization; it ensures that all Gnome file
menus use the same key shortcut and have the same name. There are quite a few
analagous macros; see libgnomeui/gnome-app-helper.h for the complete list.
107
#include <libgnomeui/gnome-app-helper.h>
void gnome_app_create_menus(GnomeApp* app, GnomeUIInfo* uiinfo);
void gnome_app_create_menus_with_data(GnomeApp* app, GnomeUIInfo* uiinfo,
gpointer user_data);
void gnome_app_create_toolbar(GnomeApp* app, GnomeUIInfo* uiinfo);
void gnome_app_create_toolbar_with_data(GnomeApp* app, GnomeUIInfo* uiinfo,
gpointer user_data);
void gnome_app_fill_toolbar(GtkToolbar* toolbar, GnomeUIInfo* uiinfo, GtkAccelGroup* accel_group);
void gnome_app_fill_toolbar_with_data(GtkToolbar* toolbar, GnomeUIInfo* uiinfo, GtkAccelGroup* accel_group, gpointer data);
void gnome_app_fill_menu(GtkMenuShell* menushell, GnomeUIInfo* uiinfo, GtkAccelGroup* accel_group, gboolean uline_accels, gint pos);
void gnome_app_fill_menu_with_data(GtkMenuShell* menushell, GnomeUIInfo*
uiinfo, GtkAccelGroup* accel_group, gboolean uline_accels, gint pos, gpointer
user_data);
GnomeHello: An Example
The GnomeHello application has menus and a toolbar created using the GnomeUIInfo method; the relevant code is in a separate file, menus.c. Appendix E lists this file
108
in its entirety.
#include <libgnomeui/gnome-app.h>
void gnome_app_set_statusbar(GnomeApp* app, GtkWidget* statusbar);
GnomeAppBar
Theres no real reason to prefer GnomeAppBar or GtkStatusbar; they simply have different APIs. The GnomeAppBar widget was written later, with several goals in mind:
To support an optional progress bar next to the status bar, similar to Netscapes.
Eventual support for "interactive" use in the tradition of the Emacs "minibuffer."
This is unfinished in Gnome 1.0, however.
109
#include <libgnomeui/gnome-appbar.h>
GtkWidget* gnome_appbar_new(gboolean has_progress, gboolean has_status,
GnomePreferencesType interactivity);
#include <libgnomeui/gnome-appbar.h>
GtkProgress* gnome_appbar_get_progress(GnomeAppBar* appbar);
#include <libgnomeui/gnome-appbar.h>
void
void
void
void
void
void
110
GtkStatusbar
GtkStatusbar has no default text or "transient" text, as in GnomeAppBar; it only has
#include <gtk/gtkstatusbar.h>
GtkWidget* gtk_statusbar_new(void);
guint gtk_statusbar_get_context_id(GtkStatusbar* statusbar, const gchar*
context_description);
guint gtk_statusbar_push(GtkStatusbar* statusbar, guint context_id, const
gchar* text);
void gtk_statusbar_pop(GtkStatusbar* statusbar, guint context_id);
void gtk_statusbar_remove(GtkStatusbar* statusbar, guint context_id, guint
message_id);
Online Help
Finished applications should provide online help and documentation. Of course, the
first "line of defense" is to have an intuitive interface in the first place. But you should
111
By writing documentation, and providing buttons and menu items that jump to
relevant sections. For example, the "Help" button in a properties dialog should
bring up a help window describing the dialog.
By adding "tooltips," explanatory text that appears if the mouse remains motionless over a widget for a short time. For menu items, explanatory text appears in the
windows status bar as the user moves over the item.
112
g_free(helpfile);
}
else
{
gnome_error_dialog(_("Couldnt find the GnomeHello manual!"));
}
"file:" to a path to make it a valid URL before calling this function. The first argument
to gnome_help_goto() is ignored; this makes it convenient to connect gnome_help_goto()
as a callback function, for example to a buttons "clicked" signal.
libgnome/gnome-help.h contains a few other variants of gnome_help_goto() suited
#include <libgnome/gnome-help.h>
gchar* gnome_help_file_find_file(const gchar* app, const gchar* filename);
void gnome_help_goto(void* ignore, const gchar* url);
Menu Hints
As the user moves over your application menus, a short description of each menu
item should appear in the statusbar. Gnome makes this very easy; just call the gnome_app_install_menu_hi
(Figure 6-11) after you create your menus and statusbar. The GnomeUIInfo struct
passed to this function must have its widget fields filled in by one of the menucreation functions, and the GnomeApp must have a GnomeAppBar or GtkStatusbar
in its statusbar slot.
#include <libgnomeui/gnome-app-helper.h>
void gnome_app_install_menu_hints(GnomeApp* app, GnomeUIInfo* uiinfo);
113
Tooltips
GTK+ provides tooltip functionality; you simply create a GtkTooltips and attach it to
a widget. I like to use the following convenience function in my applications:
void
set_tooltip(GtkWidget* w, const gchar* tip)
{
GtkTooltips* t = gtk_tooltips_new();
gtk_tooltips_set_tip (t, w, tip, NULL);
}
The GtkTooltips will be destroyed along with the widget. Make your tooltips long
rather than short; theres no reason to skimp on the amount of information you provide here. You should get in the habit of calling set_tooltip() every time you create
a button or other widget that could benefit from it.
Note that toolbars created from a GnomeUIInfo template will have tooltips installed
automatically.
Finishing Touches
Really polished application windows behave well on small screens, and set hints so
the window manager can keep track of them.
#include <gdk/gdk.h>
gint gdk_screen_width(void);
gint gdk_screen_height(void);
114
#include <gtk/gtkwindow.h>
void gtk_window_set_wmclass(GtkWindow* window, const gchar* wmclass_name,
const gchar* wmclass_class);
115
Creating a Dialog
A GnomeDialog is easy to create. Heres a summary of the basic steps, more detail
follows:
1. Read the section called Special Dialog Types and decide whether one of the special dialog subclasses is appropriate. If so, skip the below steps and create that
subclass instead.
2. Create the widget with gnome_dialog_new(). Pass this function the title of the
dialog (displayed by the window manager) and the name of each button youd
like to have.
3. Populate GNOME_DIALOG(dialog)->vbox with the contents of your dialog.
4. Plan how your dialog will work. You can connect to the "close" or "clicked"
signals, as appropriate. You can have the dialog hide or destroy itself when
closed. You can also have the dialog automatically close when clicked, or handle
this yourself. There are a number of ways the user can interact with a dialog, so
its important to be sure the combination of settings you choose will work no
matter what the user does.
To create a dialog, use gnome_dialog_new(), shown in Figure 7-1. The argument list
is a NULL-terminated list of buttons to insert in the dialog. For example, you might
say:
GtkWidget* dialog;
dialog = gnome_dialog_new(_("My Dialog Title"),
_("OK"),
_("Cancel"),
NULL);
116
This creates a dialog titled "My Dialog Title" with an OK and a Cancel button; the
strings are marked for translation with the _() macro. The OK button will be the
leftmost button in the dialog.
#include <libgnomeui/gnome-dialog.h>
GtkWidget* gnome_dialog_new(const gchar* title,
...);
Gnome includes many stock buttons, stock menu items, and stock pixmapsits a
good idea to check these out so you dont reinvent the wheel. Theres a complete list
in libgnomeui/gnome-stock.h.
117
Of course you can pack the contents of dialog->vbox using the packing options of
your choice. The above code is just an example.
Figure 7-2 shows a dialog from the Gnumeric spreadsheet, with its components labelled.
If the dialog is not modal, interacting with other parts of the application
GnomeDialog emits two signals in addition to those it inherits from parent classes. If
the user clicks one of the dialogs buttons, a "clicked" signal is emitted. (This is not
the "clicked" signal from GtkButton; its a different signal, emitted by GnomeDialog.)
A GnomeDialog"clicked" handler should have three arguments: the dialog emitting
the signal, the number of the button clicked, and your callback data.
GnomeDialog also has a "close" signal. It is emitted when gnome_dialog_close() is
called; all the built-in event handlers (e.g. for the Escape shortcut) call this function to
close the dialog. GnomeDialogs default handler for "close" has two possible behaviors: it can call either gtk_widget_hide() or gtk_widget_destroy() on the dialog.
The behavior is configurable by calling gnome_dialog_close_hides(), shown in
Figure 7-3.
#include <libgnomeui/gnome-dialog.h>
118
Finishing Touches
The difference between a good dialog and a great dialog is in the details. GnomeDialog comes with a number of features to make that final polish easy. Figure 7-4 sums
them up.
#include <libgnomeui/gnome-dialog.h>
void gnome_dialog_set_parent(GnomeDialog* dialog, GtkWindow* parent);
void gnome_dialog_set_default(GnomeDialog* dialog, gint button);
void gnome_dialog_editable_enters(GnomeDialog* dialog, GtkEditable* editable);
void gnome_dialog_set_sensitive(GnomeDialog* dialog, gint button, gboolean
setting);
119
/* Arguments elided. */
gtk_signal_connect(GTK_OBJECT(dialog),
"destroy",
GTK_SIGNAL_FUNC(gtk_widget_destroyed),
&dialog);
/* Show the dialog, connect callbacks, etc. here */
}
120
}
gtk_widget_destroyed() is defined in gtk/gtkwidget.h, and simply assigns NULL
to its second argument. The code resets the dialog variable each time the user closes
the dialog, and raises/deiconifies the dialog if the user tries to open it while another one is active. Note that the window manager has some say in whether the
raise/deiconify is successful, so it is not guaranteed to happen.
Modal Dialogs
Sometimes you need to prevent interaction with the rest of your application while
the user manipulates a dialog. Dialogs that freeze the rest of the application in this
way are called modal dialogs.
There is a lot of debate about when to use modal dialogs; some users hate them passionately, but there are times when they are necessary. Unfortunately, it is a little bit
easier to write code using modal dialogs, because you can stop in the middle of a
function, wait for a user response, then continue. With nonmodal dialogs, you have
to return the flow of control to the main application, and arrange callbacks to pick
up where you left off when the user finally deals with the dialog. With a complex sequence of dialogs, the result is ugly spaghetti code. This tempts many programmers
to use modal dialogs all the time, or at least a little too often. Avoid the temptation,
and your users will thank you.
Avoid modal dialogs if users might want to refer back to information in the main application as they use the dialog, or if they might want to cut-and-paste between the
application and the dialog. "Properties" dialogs should usually be nonmodal; because
users will want to experiment with the effects of the changes they make, without having to close the dialog. And theres no reason to make trivial message boxes modal,
since clicking on them has no effect on the rest of the application.
Do not be afraid to use a modal dialog if it makes sense, however. For example, I
wrote a frontend for the Debian package manager, called gnome-apt. The main application allows the user to select software packages for installation and removal; then
there are a series of dialogs which ask for confirmation and perform the requested
changes. These dialogs are modal, because it would make no sense to change a request in the middle of performing it. Changing the request should imply restarting
the request-fulfillment process and asking for confirmation a second time. Another
example: the "File Properties" dialog for the Gnome file manager is modal, because
otherwise the user could delete the file while its properties were being editeda
strange situation. There are no hard and fast rules; youll have to use your judgment
on a dialog-by-dialog basis.
All that said, it is very easy to create a modal dialog. In GTK+, any window can be
made modal with gtk_window_set_modal() (Figure 7-5).
#include <gtk/gtkwindow.h>
gtk_window_set_modal(GtkWindow* window, gboolean modality);
121
Since GnomeDialog is a GtkWindow subclass, this function works fine. It simply blocks
all interaction with windows other than the modal one.
Typically you want to go a step further, and wait for the user to click one of the dialog
buttons without setting up a lot of callbacks. In GTK+ this is done by running a second instance of gtk_main(), entering another, nested event loop. When the second
loop exits, the flow of control returns to just after your gtk_main() call. However
there are a host of complications and race conditions, due to the large number of
ways to close a dialog; the resulting code is somewhat unpleasant and error-prone.
The two functions in Figure 7-6 are provided to save your from the mess.
#include <libgnomeui/gnome-dialog.h>
gint gnome_dialog_run(GnomeDialog* dialog);
gint gnome_dialog_run_and_close(GnomeDialog* dialog);
nals, and closes the dialog if and only if it does not close "naturally" in response to
user clicks or keystrokes. Using this function guarantees that gnome_dialog_close()
will be called exactly once before it returns, unless you connect truly malicious callbacks to sabotage the process. gnome_dialog_run_and_close() is not very useful in
my opinion; it is little more than a way to avoid thinking about how the dialog will
be closed.
A Dialog Example
Heres a piece of code from the Gnome plot and chart component, Guppi. This is
used for an "Open file" dialog. Future versions of Gnome will have a GnomeFileSelection widget, which would be more appropriate for this particular task than a
custom dialog; but the example is nonetheless instructive.
122
GtkWidget * dialog;
dialog = gnome_dialog_new(_("Guppi: Open"),
GNOME_STOCK_BUTTON_OK,
GNOME_STOCK_BUTTON_CANCEL,
NULL);
gnome_dialog_set_close(GNOME_DIALOG(dialog), TRUE);
gnome_dialog_close_hides(GNOME_DIALOG(dialog), TRUE);
guppi_setup_dialog(dialog);
GtkWidget* fileentry =
gnome_file_entry_new("guppi:guppi_loadsave_history",
_("Guppi: Browse Files For Open"));
gnome_dialog_editable_enters(GNOME_DIALOG(dialog),
GTK_EDITABLE(gnome_file_entry_gtk_entry(GNOME_FILE_ENTRY
gnome_dialog_set_default(GNOME_DIALOG(dialog), GNOME_OK);
gtk_box_pack_start(GTK_BOX(GNOME_DIALOG(dialog)->vbox),
fileentry,
TRUE, TRUE, GNOME_PAD);
gtk_widget_show_all(dialog);
int reply = gnome_dialog_run(GNOME_DIALOG(dialog));
if (reply == GNOME_OK)
{
gchar* s =
gnome_file_entry_get_full_path(GNOME_FILE_ENTRY(fileentry),
TRUE);
/* Application-specific details of actually
* loading the file omitted.
*/
}
gtk_widget_destroy(dialog);
gnome_dialog_set_close() is called, so this dialog will close if any of its buttons are
clicked. However, closing the dialog only calls gtk_widget_hide(), rather than destroying it; gnome_dialog_close_hides() configures this behavior. guppi_setup_dialog()
is a wrapper function that calls gnome_dialog_set_parent() to set the main appli-
123
GnomeAbout
Gnome applications should have an "About Foo" menu item which displays this widget (where "Foo" is the name of your application). Using it is ridiculously easy; theres
only one function involved, gnome_about_new() (Figure 7-7). The arguments are, respectively: the title of your application, the version of your application, a one-line
copyright notice, a NULL-terminated vector of authors names, a short paragraph
saying anything you want to say, and an image filename to display as your applications logo. Only the authors argument is required; the others can be NULL, but your
dialog will look fairly strange if all of them are.
#include <libgnomeui/gnome-about.h>
GtkWidget* gnome_about_new(const gchar* title, const gchar* version, const
gchar* copyright, const gchar** authors, const gchar* comments, const
gchar* logo);
about it; just create and show the dialog. Remember to ensure only one instance exists
at any given time, as explained in the section called Finishing Touches.
Heres a menu item callback to show an about dialog, from the Gnome calendar application:
static void
about_calendar_cmd (GtkWidget *widget, void *data)
{
GtkWidget *about;
const gchar *authors[] = {
"Miguel de Icaza <miguel@kernel.org>",
"Federico Mena <federico@gimp.org>",
"Arturo Espinosa <arturo@nuclecu.unam.mx>",
NULL
};
about = gnome_about_new (_("Gnome Calendar"), VERSION,
"(C) 1998 the Free Software Foundation",
authors,
_("The GNOME personal calendar and schedule manager."),
NULL);
gtk_window_set_modal (GTK_WINDOW (about), TRUE);
gtk_widget_show (about);
}
124
Note that the authors give both their name and email address; that way people can
use the dialog to decide where to send hate mail and bug reports. (Or thank you
notes!) The VERSION macro comes from config.h, and is defined by configure. The
Gnome Calendar authors chose to prevent multiple dialog instances by making the
dialog modalthe user cant re-select the menu item while the dialog is open. It is
probably better to use the technique described in the section called Finishing Touches,
so the dialog is deiconified and raised if the user reselects the menu item.
GnomePropertyBox
GnomePropertyBox is used for application preferences, or to edit the properties of a
user-visible object. Its a dialog with a GtkNotebook inside, and four buttons: "OK,"
"Apply," "Close," and "Help." The "OK" button is equivalent in all respects to clicking "Apply" followed by "Close." "Apply" should immediately make any changes the
user has requested using the widgets youve placed in the GnomePropertyBox. Unsurprisingly, "Help" should display help. "OK" and "Close" are handled automatically
by the property box, so you can ignore them.
You dont need to deal with the property boxs buttons directly; instead GnomePropertyBox emits "apply" and "help" signals. Handlers for these should look like:
void handler(GtkWidget* propertybox, gint page_num, gpointer data);
page_num is the currently-active page of the GtkNotebook inside the dialog. (GtkNotebook pages are numbered from front to back, starting with 0; the front page is
the first one you add to the notebook.) For "help", the page number lets you provide
context-sensitive help. When the user clicks the "Apply" or "OK" button, the "apply"
signal is emitted once per page, then emitted a final time with -1 as the page_num
value. The multiple emissions of "apply" are something of an anachronism, because
it has become de facto standard behavior to simply apply all pages when the -1 page
number is received.
To create a property box, you first create the dialog, then create each page and add
it. Creating a GnomePropertyBox is straightforward; gnome_property_box_new()
takes no arguments.
#include <libgnomeui/gnome-propertybox.h>
GtkWidget* gnome_property_box_new(void);
gint gnome_property_box_append_page(GnomePropertyBox* pb, GtkWidget* page,
GtkWidget* tab);
125
information to set the "Apply" and "OK" buttons sensitive if and only if there are
unapplied changes. The relevant routines are in Figure 7-9.
#include <libgnomeui/gnome-propertybox.h>
void gnome_property_box_changed(GnomePropertyBox* pb);
void gnome_property_box_set_state(GnomePropertyBox* pb, gboolean setting);
box will automatically unset its internal "changes pending" flag when "apply" is emitted. If you need to change that internal flag for some reason (unlikely), you can use
gnome_property_box_set_state().
GnomeMessageBox
A GnomeMessageBox is a GnomeDialog subclass that conveys a short message or asks
a simple question. Gnome provides several "types" of message box; they have different icons next to the text, and corresponding titles. The icons look nice, and allow
users to quickly classify the message being presented.
The API is very simple; there are no functions specific to GnomeMessageBox other
than the constructor, in Figure 7-10. The first argument is the message to display;
the second is a string encoding the message box type. Then you can list any buttons,
just as you would with gnome_dialog_new(). Unlike the unadorned GnomeDialog,
GnomeMessageBox closes on any button click by default. Of course you can change
this behavior using gnome_dialog_set_close().
#include <libgnomeui/gnome-messagebox.h>
GtkWidget* gnome_message_box_new (const gchar* message, const gchar* messagebox_type, ...);
GNOME_MESSAGE_BOX_WARNING
GNOME_MESSAGE_BOX_ERROR
GNOME_MESSAGE_BOX_QUESTION
GNOME_MESSAGE_BOX_GENERIC
126
GNOME_STOCK_BUTTON_OK,
NULL);
gtk_widget_show (mbox);
Notice that GnomeMessageBox, like most GnomeDialog subclasses but not GnomeDialog itself, automatically closes when clicked. So there is no need to destroy it by
hand.
Convenience Routines
Since message boxes almost always have the same button (a single "OK"), there
are convenience routines covering that case. Each routine has a _parented() variant
which calls gnome_dialog_set_parent(). The three function pairs in Figure 7-11
display an info box, a warning box, and an error box, respectively; they create and
show the widget, so you can ignore the return value if you like.
The only purpose of these functions is to save you typing. They are pure syntactic
sugar. I find it much easier to remember them than to use gnome_message_box_new(),
though; I always forget the order of the arguments to gnome_message_box_new().
#include
GtkWidget*
GtkWidget*
ent);
GtkWidget*
GtkWidget*
parent);
GtkWidget*
GtkWidget*
ent);
<libgnomeui/gnome-dialog-util.h>
gnome_ok_dialog(const gchar* message);
gnome_ok_dialog_parented(const gchar* message, GtkWindow* pargnome_warning_dialog(const gchar* warning);
gnome_warning_dialog_parented(const gchar* warning, GtkWindow*
gnome_error_dialog(const gchar* error);
gnome_error_dialog_parented(const gchar* error, GtkWindow* par-
127
Internationalize your application with GNU gettext and the standard C library
functions.
Include the intl directory with your application, so users can build the application without having gettext. Include intl in your header file search path.
Define the G_LOG_DOMAIN preprocessor symbol to identify the origin of glib error
messages.
Install a .desktop file so your application will appear on the Gnome desktops
menus.
Install help files along with topic.dat files so the Gnome help browser can locate
them.
Be sure the make distcheck target works; this is will catch many common makefile errors.
Set up a popt argument parser; at a minimum, you will probably want to support
a -geometry option.
All configuration should be possible via the GUI; the easiest way to achieve this is
with the Gnome configuration library.
If appropriate, use the GnomeApp for your main document windows; this widget
gives Gnome applications a consistent look-and-feel.
Use GnomeUIInfo to create menus and toolbars; when appropriate, use the Gnome
macros for standard menu items.
Add a status bar to display hints for the menu items, and any other status your
application has to report.
128
Keep a ChangeLog detailing changes to your source code. This will help other
people understand the evolution of the application, and help you understand why
you made certain changes years later.
129
GtkButton;
GtkButtonClass;
struct _GtkButton
{
GtkBin bin;
GtkWidget *child;
guint in_button : 1;
guint button_down : 1;
guint relief : 2;
};
struct _GtkButtonClass
{
GtkBinClass
parent_class;
void (* pressed) (GtkButton *button);
void (* released) (GtkButton *button);
130
void (* clicked)
void (* enter)
void (* leave)
(GtkButton *button);
(GtkButton *button);
(GtkButton *button);
};
Notice that the first member of struct _GtkButton is GtkBinthats because GtkButton is a subclass of GtkBin. (GtkBin is a GtkContainer that can hold one child.)
Since GtkBin is the first member, we can safely cast a GtkButton to GtkBin. In struct
_GtkButtonClass, the same principle applies, and GtkBinClass is the first member.
The first time this function is invoked, it will register a GtkButton type with the object
system, and in the process obtain a type identifier. On subsequent calls, the type
identifier is simply returned. GtkType is a typedef (unsigned int is the actual type of
GTK+s type identifiers).
The type system allows GTK+ to check the validity of casts. To facilitate this, objects
customarily provide macros like these in their header file:
#define GTK_TYPE_BUTTON
#define GTK_BUTTON(obj)
(gtk_button_get_type ())
(GTK_CHECK_CAST ((obj), \
GTK_TYPE_BUTTON, GtkButton))
#define GTK_BUTTON_CLASS(klass)
(GTK_CHECK_CLASS_CAST ((klass), \
GTK_TYPE_BUTTON, GtkButtonClass))
#define GTK_IS_BUTTON(obj)
(GTK_CHECK_TYPE ((obj), \
GTK_TYPE_BUTTON))
#define GTK_IS_BUTTON_CLASS(klass) (GTK_CHECK_CLASS_TYPE ((klass), \
GTK_TYPE_BUTTON))
Instead of simply casting an object, you can use the GTK_BUTTON() macro. If GTK_NO_CHECK_CASTS
is defined, these macros are equivalent to simple casts. Otherwise, they retrieve the
type of the object and compare it to the type youre attempting to cast to.
GTK+ also provides convenient runtime type checking, with the GTK_IS_BUTTON()
macro. This is often used in preconditions; for example, a function expecting a button
as an argument might have this check at the beginning:
g_return_if_fail(GTK_IS_BUTTON(widget));
The GTK+ and Gnome library functions have many such checks. You can also use
the macro to make certain code conditional on an objects type, though this is most
likely a poor idea from a design standpoint.
To give you an idea what sort of information GTK+ stores about each object type,
heres the implementation of gtk_button_get_type():
131
GtkType
gtk_button_get_type (void)
{
static GtkType button_type = 0;
if (!button_type)
{
static const GtkTypeInfo button_info =
{
"GtkButton",
sizeof (GtkButton),
sizeof (GtkButtonClass),
(GtkClassInitFunc) gtk_button_class_init,
(GtkObjectInitFunc) gtk_button_init,
/* reserved_1 */ NULL,
/* reserved_2 */ NULL,
(GtkClassInitFunc) NULL,
};
button_type = gtk_type_unique (GTK_TYPE_BIN, &button_info);
gtk_type_set_chunk_alloc (button_type, 16);
}
return button_type;
}
The code fills in a struct with information about the class, then hands that struct to
GTK+ to get a type identifier (GtkType). Only six components of the GtkTypeInfo
struct are important. GtkButton gives GTK+ a human-readable name for the class,
used in error messages and the like; the size of the instance and class structs; then a
function to initialize the class struct and another to initialize each new instance. The
sixth and seventh members of the struct (reserved_1 and reserved_2) are obsolete
and preserved only for compatibility. The final member is a pointer to a base class
initialization function, used to initialize the class struct of any subclasses.
gtk_type_unique() registers the new type and obtains a type identifier. The GTK_TYPE_BIN
argument is a macro containing the type of GtkButtons parent class, GtkBin. The
call to gtk_type_set_chunk_alloc() optimizes memory allocation for this type; it
is never required, and should only be used for frequently-allocated types like GtkButton.
Given a registered GtkButton type, the following code creates a type instance:
GtkWidget*
gtk_button_new (void)
{
return GTK_WIDGET (gtk_type_new (gtk_button_get_type ()));
}
The newborn GtkButton will be initialized by its instance initializer. The instance
initialization function is called each time an instance of the type is created; it gives
the objects data members reasonable default values:
static void
gtk_button_init (GtkButton *button)
{
GTK_WIDGET_SET_FLAGS (button, GTK_CAN_FOCUS);
132
133
Here is the GtkButton class initialization function, just to give you an initial sense of
things; read on to learn what this code does.
static void
gtk_button_class_init (GtkButtonClass *klass)
{
GtkObjectClass *object_class;
GtkWidgetClass *widget_class;
GtkContainerClass *container_class;
object_class = (GtkObjectClass*) klass;
widget_class = (GtkWidgetClass*) klass;
container_class = (GtkContainerClass*) klass;
parent_class = gtk_type_class (GTK_TYPE_BIN);
gtk_object_add_arg_type ("GtkButton::label",
GTK_TYPE_STRING,
GTK_ARG_READWRITE,
ARG_LABEL);
gtk_object_add_arg_type ("GtkButton::relief",
GTK_TYPE_RELIEF_STYLE,
GTK_ARG_READWRITE,
ARG_RELIEF);
button_signals[PRESSED] =
gtk_signal_new ("pressed",
GTK_RUN_FIRST,
object_class->type,
GTK_SIGNAL_OFFSET (GtkButtonClass, pressed),
gtk_marshal_NONE__NONE,
GTK_TYPE_NONE, 0);
button_signals[RELEASED] =
gtk_signal_new ("released",
134
GTK_RUN_FIRST,
object_class->type,
GTK_SIGNAL_OFFSET (GtkButtonClass,
gtk_marshal_NONE__NONE,
GTK_TYPE_NONE, 0);
button_signals[CLICKED] =
gtk_signal_new ("clicked",
GTK_RUN_FIRST | GTK_RUN_ACTION,
object_class->type,
GTK_SIGNAL_OFFSET (GtkButtonClass,
gtk_marshal_NONE__NONE,
GTK_TYPE_NONE, 0);
button_signals[ENTER] =
gtk_signal_new ("enter",
GTK_RUN_FIRST,
object_class->type,
GTK_SIGNAL_OFFSET (GtkButtonClass,
gtk_marshal_NONE__NONE,
GTK_TYPE_NONE, 0);
button_signals[LEAVE] =
gtk_signal_new ("leave",
GTK_RUN_FIRST,
object_class->type,
GTK_SIGNAL_OFFSET (GtkButtonClass,
gtk_marshal_NONE__NONE,
GTK_TYPE_NONE, 0);
released),
clicked),
enter),
leave),
object_class->set_arg = gtk_button_set_arg;
object_class->get_arg = gtk_button_get_arg;
widget_class->activate_signal = button_signals[CLICKED];
widget_class->realize = gtk_button_realize;
widget_class->draw = gtk_button_draw;
widget_class->draw_focus = gtk_button_draw_focus;
widget_class->draw_default = gtk_button_draw_default;
widget_class->size_request = gtk_button_size_request;
widget_class->size_allocate = gtk_button_size_allocate;
widget_class->expose_event = gtk_button_expose;
widget_class->button_press_event = gtk_button_button_press;
widget_class->button_release_event = gtk_button_button_release;
widget_class->enter_notify_event = gtk_button_enter_notify;
widget_class->leave_notify_event = gtk_button_leave_notify;
widget_class->focus_in_event = gtk_button_focus_in;
widget_class->focus_out_event = gtk_button_focus_out;
container_class->add = gtk_button_add;
container_class->remove = gtk_button_remove;
container_class->child_type = gtk_button_child_type;
klass->pressed = gtk_real_button_pressed;
klass->released = gtk_real_button_released;
klass->clicked = NULL;
klass->enter = gtk_real_button_enter;
klass->leave = gtk_real_button_leave;
}
135
It allows object attributes (values that you can "get" or "set") to be dynamically
queried and manipulated.
It is possible to identify types at runtime and traverse the object class hierarchy.
Because of its type system, GTK+ is particularly easy to manipulate from dynamicallytyped, interactive languages. There are bindings available for nearly all popular languages, and the bindings can be lightweight (since GTK+ already includes much of
the needed functionality, and types can be handled generically so the amount of glue
code is reduced). You can find a complete list of functions for querying and using
GTK+s type system in gtk/gtktypeutils.h; most of these are not useful in applications. Only the functions of general interest are described in this book.
GTK+ has a number of so-called fundamental types which are automatically registered
during gtk_init() (or gnome_init()). The fundamental types include all the primitive C types, some GTK+ types such as GTK_TYPE_SIGNAL, and GTK_TYPE_OBJECT.
Fundamental types are essentially the "base classes" understood by the GTK+ type
system; for example, the fundamental type of any enumeration is GTK_TYPE_ENUM,
and the fundamental type of any GtkObject subclass is GTK_TYPE_OBJECT. Fundamental types are supposed to cover all the "special cases" in the GTK+ type system;
all types ultimately derive from some fundamental type. A types fundamental type
is extracted from a GtkType with the GTK_FUNDAMENTAL_TYPE() macro. The fundamental types are shown in Table 9-1.
There is a second category of GtkType values: builtin types are registered by GTK+
and libgnomeui during library initialization and are thus always available. Builtin
types include enumerations, flags, and some structs (GdkWindow, or GdkImlibImage, for example). Builtin types are distinct from fundamental types because the
GTK+ object system does not have to understand them; for the purposes of getting
and setting argument values, they can be treated as fundamental types. They are
somewhat arbitrarily distinguished from user-registered enumeration or flag types.
(The difference between builtin types and user types is the time of registration.)
Builtin types are all accessible via macros that come with GTK+ and Gnome. These
begin with GTK_TYPE_, as in: GTK_TYPE_WINDOW, GTK_TYPE_GDK_WINDOW,
GTK_TYPE_RELIEF_STYLE, GTK_TYPE_GNOME_DIALOG. As you can see, the name
of the type macro is derived from the name of the GtkObject, struct, or enumeration;
if the object name begins with "Gtk," the "Gtk" is dropped. The above examples map
to the GtkWindow widget, GdkWindow struct, GtkReliefStyle enumeration, and GnomeDialog widget, respectively.
The final major category of GtkType values consists of the registered GtkObject types.
These are registered the first time the _get_type() routine for each object is called.
Table 9-1. The GTK+ Fundamental Types
GtkType Constant
GTK_TYPE_INVALID
136
Corresponding C Type
None
GtkType Constant
GTK_TYPE_NONE
GTK_TYPE_CHAR
GTK_TYPE_UCHAR
GTK_TYPE_BOOL
GTK_TYPE_INT
GTK_TYPE_UINT
GTK_TYPE_LONG
GTK_TYPE_ULONG
GTK_TYPE_FLOAT
GTK_TYPE_DOUBLE
GTK_TYPE_STRING
GTK_TYPE_ENUM
GTK_TYPE_FLAGS
GTK_TYPE_BOXED
GTK_TYPE_POINTER
GTK_TYPE_SIGNAL
GTK_TYPE_ARGS
GTK_TYPE_CALLBACK
GTK_TYPE_C_CALLBACK
GTK_TYPE_FOREIGN
GTK_TYPE_OBJECT
Corresponding C Type
void
gchar
guchar
gboolean
gint
guint
glong
gulong
gfloat
gdouble
gchar*
Any enumeration
guint
gpointer
gpointer
GtkSignalFunc, gpointer
gint, GtkArg*
GtkCallbackMarshal, gpointer,
GtkDestroyNotify
GtkFunction, gpointer
gpointer, GtkDestroyNotify
GtkObject*
GTK_TYPE_NONE: used to indicate a void return value when specifying the signature of a signal.
GTK_TYPE_CALLBACK: interpreted language bindings can use this to pass signal callbacks around.
A fundamental type describes not only describe the data layout but also how memory is managed. For values passed in as arguments, the called function is not allowed to retain the pointer beyond the duration of the call. For returned values, the
137
138
The type field contains the values GtkType, as you might expect. The name field is
an object argument namemore on arguments in a moment. The final union stores a
value of the appropriate type; there is one union member for each fundamental type.
This value field should be accessed using a special set of macros provided for the
purpose, listed in Figure 9-2; each macro corresponds to a fundamental type. These
macros are defined so that you can use the & operator on them; e.g. >K_VALUE_CHAR(arg).
To print a GtkArgs value, you might write code like this:
GtkArg arg;
/* ... */
switch (GTK_FUNDAMENTAL_TYPE (arg.type))
{
case GTK_TYPE_INT:
printf("arg: %d\n", GTK_VALUE_INT(arg));
break;
/* ... case for each type ... */
}
#include <gtk/gtktypeutils.h>
GTK_VALUE_CHAR(arg);
GTK_VALUE_UCHAR(arg);
GTK_VALUE_BOOL(arg);
GTK_VALUE_INT(arg);
GTK_VALUE_UINT(arg);
GTK_VALUE_LONG(arg);
GTK_VALUE_ULONG(arg);
GTK_VALUE_FLOAT(arg);
GTK_VALUE_DOUBLE(arg);
GTK_VALUE_STRING(arg);
GTK_VALUE_ENUM(arg);
GTK_VALUE_FLAGS(arg);
GTK_VALUE_BOXED(arg);
GTK_VALUE_POINTER(arg);
GTK_VALUE_OBJECT(arg);
GTK_VALUE_SIGNAL(arg);
GTK_VALUE_ARGS(arg);
GTK_VALUE_CALLBACK(arg);
GTK_VALUE_C_CALLBACK(arg);
GTK_VALUE_FOREIGN(arg);
139
Object Arguments
Arguments are one of the most interesting features of GtkObject. Arguments are a
mechanism for handling what CORBAs Interface Definition Language (IDL) calls an
attribute: a value with a "getter" and a "setter." In concrete terms, object arguments
pair a key (which is a string) with a value (represented as a GtkArg). Each GtkObject
subclass can register permissible keys and the GtkTypes of their associated values.
Using object arguments, one can discover at runtime what attributes an object has,
and then get or set their values. This is very useful for people implementing GUI
builders, since some of the widget configuration dialogs can be automated. Similarly,
it makes it much easier to write GTK+ bindings for scripting languages. It can also
be convenient for programmers, since they can avoid writing all the get/set functionsthe GnomeCanvas, for example, uses object arguments for almost all of its API.
Finally, object arguments may be configurable via the gtkrc configuration mechanism in a future version of GTK+, making it possible for users to extensively customize GTK+ software.
Its up to you which to use; it depends on the context. Typically, you would use the argument mechanism if you have a reason to, i.e. if you are using its dynamic, runtimeoriented features. However, if you are setting several attributes, it may be easier to
type and read.
gtk_object_set() takes a GtkObject as the first argument, followed by any number
of key-value pairs. If a key is not defined for the object you pass in, a runtime error
will be triggered. The list of key-value pairs must be terminated with a NULL key.
When a GtkObject registers itself with GTK+, it tells GTK+ what type of value to
expect after each key. For the aggregate fundamental types gtk_object_set() will
expect more than one C function argument after the key. For example, first a signal
function and then a user data pointer will be expected after GTK_TYPE_SIGNAL
arguments. (Table 9-1 gives the types of the expected arguments.)
It is permissible to leave off the object class portion of an argument name"GtkContainer::border_width"
can be simply "border_width":
gtk_object_set(GTK_OBJECT(vbox),
"border_width", (gulong) 10,
NULL);
140
If you do not specify the class name as part of the argument name, GTK+ will start
with the real type of the object and look up the argument name in the argument table
for each superclass until it finds the right one (GtkContainer in this case). If you do
specify the class name, GTK+ will only look for the argument in the specified classs
argument table.
Since gtk_object_set() uses C variable argument lists, it has limited type safety.
This can be a real problem in your code. You may have noticed the cast to gulong
in the sample call to gtk_object_set(). The argument GtkContainer::border_width
has type GTK_TYPE_ULONG. GTK+ will extract sizeof(gulong) bytes from the argument list when it encounters this argument. If you leave out the cast, C will probably pass only sizeof(gint) bytes to the function. As you might imagine, this causes
memory corruption on many platforms. A similar problem arises with arguments
of type GTK_TYPE_DOUBLE; if you type 5 instead of 5.0, C will pass an integer to
gtk_object_set(). These bugs are very hard to find, once you introduce them.
gtk_object_set() is syntactic sugar for a more fundamental function call, gtk_object_setv().
gtk_object_setv() takes a vector of GtkArg (gtk_object_set() converts each
141
gtk_object_getv(GTK_OBJECT(button),
2,
args);
g_assert(args[0].type == GTK_TYPE_ULONG);
g_assert(args[1].type == GTK_TYPE_RESIZE_MODE);
g_assert(GTK_FUNDAMENTAL_TYPE(args[1].type) == GTK_TYPE_ENUM);
printf("Border width: %lu Resize mode: %d\n",
GTK_VALUE_ULONG(args[0]), GTK_VALUE_ENUM(args[1]));
The first argument must be a static string constant, because GTK+ does not copy
it. It must also begin with the name of your new class, separated from the name of
the argument by two colons (reminiscent of the C++ scope operator). The second
argument should be the type of the argument; this can be any GtkType GTK+ knows
about.
The third argument contains one or more flags, defined in gtk/gtkobject.h. The
available flags are:
GTK_ARG_CONSTRUCT means the argument should be initialized with a default value. This applies to numeric and pointer types; they are set to 0 or NULL, respectively. (This happens within gtk_object_new() or gtk_widget_new(), which
call gtk_object_default_construct().)
GTK_ARG_CONSTRUCT_ONLY means the argument is only used for object construction; it cannot be read or written later. That is, you cant use these arguments
with gtk_object_set().
142
GTK_ARG_CHILD_ARG should not be used outside of container-style object implementations; it is used internally by the GtkContainer child argument functions.
struct:
object_class->get_arg = gtk_container_get_arg;
object_class->set_arg = gtk_container_set_arg;
143
like this:
static void
gtk_container_set_arg (GtkObject
GtkArg
guint
{
GtkContainer *container;
*object,
*arg,
arg_id)
*object,
*arg,
arg_id)
Notice that the type must be set to GTK_TYPE_INVALID if your subclass doesnt understand the argument ID. This is used as an error indicator; users who call gtk_object_getv()
will check for it.
If you flip back to page XXXX and have another look at the GtkButton class initialization function, you should now understand what is going on with respect to object
arguments.
144
Notice that a types parent type can be obtained using the gtk_type_parent() function, and that you can extract the GtkType tag from a GtkObject using the GTK_OBJECT_TYPE()
macro. GTK_OBJECT_TYPE() is defined as follows:
#define GTK_OBJECT_TYPE(obj) (GTK_OBJECT (obj)->klass->type)
An objects type is stored in its class structure, and a pointer to an objects class structure is stored in each instance of the object. (The class structure pointer is called klass
rather than class to avoid confusing C++ compilers.)
Figure 9-3 summarizes the functions for reading, writing, and querying object arguments.
145
#include <gtk/gtkobject.h>
void gtk_object_getv(GtkObject* object, guint n_args, GtkArg* args);
void gtk_object_set(GtkObject* object, const gchar* first_arg_name, ...);
void gtk_object_setv(GtkObjec* object, guint n_args, GtkArg* args);
void gtk_object_add_arg_type(const gchar* arg_name, GtkType arg_type, guint
arg_flags, guint arg_id);
GtkArg* gtk_object_query_args(GtkType class_type, guint32** arg_flags, guint*
n_args);
Signals
A GtkObject can emit a signal. Signals are stored in a global table by GTK+. Handlers or callbacks can be connected to signals; when a signal is emitted, its callbacks are
invoked. The process of invoking all handlers for a signal is called emission.
Abstractly, a signal is a kind of message that an object wants to broadcast; the kind of
message is associated with certain conditions (such as the user selecting a list item)
and with message-specific parameter types which are passed to connected callbacks
(such as the index of the row the user selected). User callbacks are connected to a particular signal and to a particular object instance. That is, you do not connect callbacks
to the "clicked" signal of all buttons; rather, you connect to the "clicked" signal of a
particular one. (However, there is a way to monitor all emissions of a signalthese
callbacks are called "emission hooks.")
Signals are typically associated with a class function pointer which is invoked every
time the signal is emitted; if non-NULL, the pointed-to class function serves as a default handler for the signal. It is up to the author of each GtkObject subclass whether
to provide a space in the class struct for a default handler, and whether to implement
the default handler in the base class. Conventionally, signals have the same name as
the class function they are associated with.
For example, the GtkButtonClass struct has a member called clicked; this member
is registered as the default handler for the "clicked" signal. However, the GtkButton base class does not implement a default handler, and leaves the clicked member
set to NULL. Subclasses of GtkButton could optionally fill it in with an appropriate
function. If GtkButton did implement a default clicked handler, subclasses could still
override it with a different one.
Note that GTK+ signals have nothing to do with UNIX signals. Sometimes new GTK+
users confuse the two.
146
GTK_TYPE_NONE, 0);
button_signals[RELEASED] =
gtk_signal_new ("released",
GTK_RUN_FIRST,
object_class->type,
GTK_SIGNAL_OFFSET (GtkButtonClass,
gtk_marshal_NONE__NONE,
GTK_TYPE_NONE, 0);
button_signals[CLICKED] =
gtk_signal_new ("clicked",
GTK_RUN_FIRST | GTK_RUN_ACTION,
object_class->type,
GTK_SIGNAL_OFFSET (GtkButtonClass,
gtk_marshal_NONE__NONE,
GTK_TYPE_NONE, 0);
button_signals[ENTER] =
gtk_signal_new ("enter",
GTK_RUN_FIRST,
object_class->type,
GTK_SIGNAL_OFFSET (GtkButtonClass,
gtk_marshal_NONE__NONE,
GTK_TYPE_NONE, 0);
button_signals[LEAVE] =
gtk_signal_new ("leave",
GTK_RUN_FIRST,
object_class->type,
GTK_SIGNAL_OFFSET (GtkButtonClass,
gtk_marshal_NONE__NONE,
GTK_TYPE_NONE, 0);
released),
clicked),
enter),
leave),
It tells GTK+ where to find the default handler in the class struct, if any.
It registers a marshaller, a function which invokes the signals callbacks in an appropriate way.
147
It generates an integer identifier which can be used to refer to the signal. (If you
refer to the symbol by name, GTK+ will find the ID associated with the name and
then use the ID.)
struct, so the signals for a given class can be rapidly located. Conventionally, the
argument to this function is an enumeration-indexed static array, as shown for GtkButton. The static array is also useful when implementing the functionality of the
class (the signal identifiers are used to emit the signals).
The first argument to gtk_signal_new() is a name for the signal; you refer to the
signal by name when you call gtk_signal_connect(), for example. The third argument is the GtkType of the object type emitting the signal, and the fourth is the location of the associated class function in the types class struct. A macro is provided to
compute the offset. If you specify an offset of 0, no class function will be associated
with the signal. Note that giving a zero offset is distinct from giving a valid offset but
setting the function member in the struct to NULL; in the latter case, subclasses of
the object can fill in a value for the default handler.
The second argument is a bitfield. Here are the associated flags:
GTK_RUN_FIRST means that the default handler in the class struct, if any, will
run before user-connected callbacks. If this flag is set, signal handlers should not
return a value.
GTK_RUN_LAST means the opposite, the default handler will run last. (Caveat:
user callbacks connected with gtk_signal_connect_after() run after a GTK_RUN_LAST
default handler. There is no way to ensure a default handler is always run last.
GTK_RUN_FIRST handlers are always first, however.)
GTK_RUN_ACTION means the signal can be "bound" and invoked by the user. In
other words, no special setup or shutdown is required in order to emit it. Among
other things, GTK+ will allow users to bind keyboard accelerators to these signals
using statements in the .gtkrc configuration file.
GTK_RUN_NO_HOOKS means that emission hooks are not allowed (you cant
monitor this signal for an entire object type, only for particular object instances). It
is used for GtkObjects "destroy" signal because hooks are not invoked on objects
with the GTK_DESTROYED flag set and that flag is set before emitting "destroy".
Its probably not good for anything else.
The last few arguments to gtk_signal_new() provide a marshaller, and tell GTK+
the marshallers type. A marshaller invokes a callback function, based on an array of
GtkArg it receives from GTK+. Marshallers are needed because C function argument
lists cannot be constructed at runtime. GTK+ comes with a number of prewritten
marshallers; here is the one used for all GtkButton signals:
148
As you can see, the NONE__NONE refers to the fact that the expected callback type
returns no value and has no "special" arguments. GTK+ automatically passes the object emitting the signal and a user_data field to all callbacks; special signal arguments
are inserted in between these two. Since there are no signal-specific arguments in this
case, the array of GtkArg is ignored.
The naming convention for marshallers places a double underscore between the return value and the special arguments, if any. Heres a more complex example:
typedef gint (*GtkSignal_INT__POINTER) (GtkObject * object,
gpointer arg1,
gpointer user_data);
void
gtk_marshal_INT__POINTER (GtkObject * object,
GtkSignalFunc func,
gpointer func_data,
GtkArg * args)
{
GtkSignal_INT__POINTER rfunc;
gint *return_val;
return_val = GTK_RETLOC_INT (args[1]);
rfunc = (GtkSignal_INT__POINTER) func;
*return_val = (*rfunc) (object,
GTK_VALUE_POINTER (args[0]),
func_data);
}
Notice that the last element of the array of GtkArg is a space for the return value;
if there is no return value, this element will have type GTK_TYPE_NONE and can
be ignored. GTK+ provides macros such as GTK_RETLOC_INT() to extract a "return
location" from a GtkArg. Similar GTK_RETLOC_ macros exist for all the fundamental
types.
The function pointer signatures in the class structure for an object will correspond to
the type of the signal. This is a convenient way to find out what signature the callbacks connected to a signal should have, if the GTK+ header files are readily available
on your system.
The last arguments to gtk_signal_new() give the type of the signals marshaller.
First a return value type is given, then the number of special arguments, then a variable argument list containing that many GtkType values in the appropriate order.
Since GtkButton has no examples of signals with arguments, here is one from GtkWidget:
149
widget_signals[BUTTON_PRESS_EVENT] =
gtk_signal_new("button_press_event",
GTK_RUN_LAST,
object_class->type,
GTK_SIGNAL_OFFSET (GtkWidgetClass, button_press_event),
gtk_marshal_BOOL__POINTER,
GTK_TYPE_BOOL, 1,
GTK_TYPE_GDK_EVENT);
"button_press_event" returns a boolean value, and has a GdkEvent* argument. Notice that the marshaller works with any GTK_TYPE_POINTER, but the signal requires the more-specific boxed type GTK_TYPE_GDK_EVENT, allowing language
bindings to query the correct kind of pointer.
Signals can have many arguments; here is one from GtkCList:
clist_signals[SELECT_ROW] =
gtk_signal_new ("select_row",
GTK_RUN_FIRST,
object_class->type,
GTK_SIGNAL_OFFSET (GtkCListClass, select_row),
gtk_marshal_NONE__INT_INT_POINTER,
GTK_TYPE_NONE, 3,
GTK_TYPE_INT,
GTK_TYPE_INT,
GTK_TYPE_GDK_EVENT);
The "select_row" signal returns no value, but has three arguments (the selected row
and column number, and the event that caused the selection).
You may not be aware that gtk_signal_connect() returns a "handler ID" which
can be used to refer to the connection it creates. Using the handler ID, you can
unregister the callback with gtk_signal_disconnect(). You can also temporarily
"block" the callback by calling gtk_signal_handler_block(). This increments a
"block count"; the callback will not be invoked until the block count returns to 0.
gtk_signal_handler_unblock() decrements the block count. Both gtk_signal_disconnect()
and gtk_signal_handler_unblock() have variants that search for the handler ID
150
given a callback function or user data pointer; these are possibly more convenient,
with some loss of efficiency.
It can be useful to block signal handlers if youll be changing some aspect of an object
yourself, and thus dont need to run the callbacks you use to respond to user actions.
For example, you normally change some boolean variable if the user clicks a toggle
button, in a callback to the "toggled" signal. If you update the toggle button programmatically because the flag was changed via some mechanism other than the button,
"toggled" will still be emitted; but you want to block your callback, since the flag is
already correct.
gtk_signal_connect() is not the only way to connect to a signal. You can also
use gtk_signal_connect_object(); this simply swaps the signal-emitting object
pointer and the user data pointer in the arguments passed to the callback. Normally,
the object comes first, then any arguments unique to the signal, and finally the user
data pointer; with gtk_signal_connect_object(), the object is last and user data
is first. This function is useful when you want to use a pre-existing function as a
callback without writing a wrapper to move its arguments. For example:
gtk_signal_connect_object(GTK_OBJECT(button),
"clicked",
GTK_SIGNAL_FUNC(gtk_widget_destroy),
GTK_OBJECT(dialog));
Because the user data and the button are swapped, the first argument to gtk_widget_destroy()
will be the dialog rather than the button, closing the dialog. When using gtk_signal_connect_object(),
your callback data must be a GtkObject to avoid confusing marshallers that expect
an object as their first argument.
gtk_signal_connect_after() asks GTK+ to run the callback after the objects de-
fault signal handler, rather than before it. This only works with certain signals, those
with the GTK_RUN_LAST flag set; the section called Adding a New Signal explains
this flag.
gtk_signal_connect_object_after() combines the effects of gtk_signal_connect_object()
and gtk_signal_connect_after().
gtk_signal_connect_full() gives you complete control over the connection and
is mostly useful in language bindings. The object_signal and after arguments can be
TRUE or FALSE, toggling argument order and time of callback invocation. The functions we just mentioned also let you change this, so gtk_signal_connect_full()
adds little. Its unique features are the ability to specify a callback marshaller, and the
ability to specify a GtkDestroyNotify function. Notice that gtk_signal_connect_full()
does not expect the same kind of marshaller described in the section called Adding
a New Signal; it expects a more general marshaller appropriate for marshalling functions written in languages other than C. If you give a non-NULLGtkDestroyNotify
function, it will be invoked on the user data pointer when this handler is disconnected or the GtkObject is destroyed. Here is the proper signature for the function:
typedef void (*GtkDestroyNotify)
(gpointer
data);
Conveniently, you can use g_free() or gtk_object_destroy() as a GtkDestroyNotify. Of course, if these arent appropriate you can write a custom function.
gtk_signal_connect_while_alive() is a variant on gtk_signal_connect(); its
151
(emits the "destroy" signal), the handler will be disconnected. That is, handlers connected with this function are automatically disconnected when a specified object no
longer exists.
Theres rarely a need to do so, but you can look up a signals ID number given the
signal name and the object type that emits it. This function is gtk_signal_lookup().
Note that names are not globally unique, but they are unique with respect to a particular object type. On the other hand, signal IDs are globally unique.
During the emission of a signal (that is, during the process of invoking its handlers),
you can call gtk_signal_emit_stop() (or its _by_name() variant) to halt the emission. These functions are only useful from within signal handlers, because they must
be called during the emission process or they wont have anything to stop. They
do not take effect immediately; instead, they set a variable that GTK+ checks at key
points during emission. the section called What Happens When A Signal Is Emitted describes this in detail.
Emission hooks can be used to monitor all emissions of a given signal (regardless of
the object instance doing the emitting). Emission hooks have the following signature:
typedef gboolean (*GtkEmissionHook) (GtkObject
guint
guint
GtkArg
gpointer
*object,
signal_id,
n_params,
*params,
data);
They are passed the same parameters GTK+ would normally pass to callback marshallers (see the section called Adding a New Signal). You can connect an emission
hook with a destroy notify function to be invoked on the user data pointer when the
hook is removed. When you add an emission hook, an integer identify is returned.
You can remove emission hooks with this ID number.
Emission hooks are rarely useful, but sometimes they are the only way to do something. For example, Gnome optionally plays sound effects when certain signals are
emitted (such as button clicks).
Finally, you can ask everything you ever wanted to know about a signal using gtk_signal_query().
This function is intended for GUI builders and language bindings to use; it is probably not useful in application code. It returns a GtkSignalQuery structure filled with
information about the signal. The return value should be freed with g_free() but
not modified in any way (it contains pointers to internal data which isnt copied).
Here is the definition of GtkSignalQuery:
typedef struct _GtkSignalQuery GtkSignalQuery;
struct _GtkSignalQuery
{
GtkType
object_type;
guint
signal_id;
const gchar
*signal_name;
guint
is_user_signal : 1;
GtkSignalRunType signal_flags;
GtkType
return_val;
guint
nparams;
const GtkType
*params;
};
152
#include <gtk/gtksignal.h>
guint gtk_signal_lookup(const gchar* name, GtkType object_type);
gchar* gtk_signal_name(guint signal_id);
void gtk_signal_emit_stop(GtkObject* object, guint signal_id);
void gtk_signal_emit_stop_by_name(GtkObject* object, const gchar* name);
guint gtk_signal_connect(GtkObject* object, const gchar* name, GtkSignalFunc func, gpointer func_data);
guint gtk_signal_connect_after(GtkObject* object, const gchar* name, GtkSignalFunc func, gpointer func_data);
guint gtk_signal_connect_object(GtkObject* object, const gchar* name, GtkSignalFunc func, GtkObject* slot_object);
guint gtk_signal_connect_object_after(GtkObject* object, const gchar* name,
GtkSignalFunc func, GtkObject* slot_object);
guint gtk_signal_connect_full(GtkObject* object, const gchar* name, GtkSignalFunc func, GtkCallbackMarshal marshal, gpointer data, GtkDestroyNotify destroy_func, gint object_signal, gint after);
void gtk_signal_connect_object_while_alive(GtkObject* object, const gchar*
signal, GtkSignalFunc func, GtkObject* alive_object);
void gtk_signal_connect_while_alive(GtkObject* object, const gchar* signal, GtkSignalFunc func, gpointer func_data, GtkObject * alive_object);
void gtk_signal_disconnect(GtkObject* object, guint handler_id);
void gtk_signal_disconnect_by_func(GtkObject* object, GtkSignalFunc func,
gpointer func_data);
void gtk_signal_disconnect_by_data(GtkObject * object, gpointer func_data);
void gtk_signal_handler_block(GtkObject* object, guint handler_id);
void gtk_signal_handler_block_by_func(GtkObject* object, GtkSignalFunc func,
gpointer func_data);
void gtk_signal_handler_block_by_data(GtkObject* object, gpointer func_data);
void gtk_signal_handler_unblock(GtkObject* object, guint handler_id);
void gtk_signal_handler_unblock_by_func(GtkObject* object, GtkSignalFunc func,
gpointer func_data);
void gtk_signal_handler_unblock_by_data(GtkObject* object, gpointer func_data);
guint gtk_signal_add_emission_hook(guint signal_id, GtkEmissionHook hook_func,
gpointer data);
guint gtk_signal_add_emission_hook_full(guint signal_id, GtkEmissionHook hook_func,
gpointer data, GDestroyNotify destroy);
void gtk_signal_remove_emission_hook(guint signal_id, guint hook_id);
GtkSignalQuery* gtk_signal_query(guint signal_id);
Emitting A Signal
Its your objects responsibility to emit its signals at appropriate times. This is very
simple; if youve saved the return value from gtk_signal_new(), that identifier can
be used to emit the signal. Otherwise, you can emit the signal by name (with some
cost in execution speed, since GTK+ will have to look up the identifier in a hash
table).
Here is code from gtk/gtkbutton.c which is used to emit the "button_pressed" signal:
void
gtk_button_pressed (GtkButton *button)
{
g_return_if_fail (button != NULL);
g_return_if_fail (GTK_IS_BUTTON (button));
153
If a signal has arguments (other than the standard two), you must specify those as a
variable argument list:
gtk_signal_emit (GTK_OBJECT (widget), widget_signals[SIZE_REQUEST],
&widget->requisition);
If a signal returns a value, you must pass a location for the returned value as the final
argument:
gint return_val;
return_val = FALSE;
gtk_signal_emit (GTK_OBJECT (widget), widget_signals[EVENT], event,
&return_val);
Notice that return_val is initialized to something sane; if there are no signal handlers,
none of them will assign a value to return_val. So you must initialize the variable.
Each signal handlers return value will be assigned to the same location, so the final
value of return_val is determined by the last signal handler to run. Note that certain
return values (such as strings) must be freed by the signal emitter.
gtk_signal_emit_by_name() is the same as gtk_signal_emit(), except that the
second argument is a signal name rather than a signal ID number. There are also
variants of both emission functions that take a vector of GtkArg instead of a variable argument list. These variants expect arrays of n+1GtkArg structs, where n is the
number of signal arguments and there is an additional GtkArg for the return value.
The GtkArg structs should be initialized with sane values. If the function returns no
value, the return value GtkArg will have GTK_TYPE_NONE.
All four signal emission functions are summarized in Figure 9-5.
#include <gtk/gtksignal.h>
void gtk_signal_emit(GtkObject* object, guint signal_id, ...);
void gtk_signal_emit_by_name(GtkObject* object, const gchar* name, ...);
void gtk_signal_emitv(GtkObject* object, guint signal_id, GtkArg* params);
void gtk_signal_emitv_by_name(GtkObject* object, const gchar* name, GtkArg*
params);
154
gtk_widget_size_request (GtkWidget
*widget,
GtkRequisition *requisition)
{
g_return_if_fail (widget != NULL);
g_return_if_fail (GTK_IS_WIDGET (widget));
gtk_widget_ref (widget);
gtk_widget_ensure_style (widget);
gtk_signal_emit (GTK_OBJECT (widget), widget_signals[SIZE_REQUEST],
&widget->requisition);
if (requisition)
gtk_widget_get_child_requisition (widget, requisition);
gtk_widget_unref (widget);
}
As you can see, particular actions are required before and after emitting the signal;
thus it should only be emitted via the gtk_widget_size_request() function.
155
Within each step the handlers are invoked in the order they were connected. The
order of the steps is fixed: GTK_RUN_FIRST default handler, emission hooks, normal
connections, GTK_RUN_LAST default handler, "after" connections.
Object Finalization
To write a GtkObject, you must implement the methods provided by the GtkObject
interface, or at least be sure you are happy with the default implementations. There
are only five GtkObject methods; two of them are get_arg and set_arg, described in
the section called Using Object Arguments in Your Own GtkObject Subclass. The other
three implement object destruction; here are the fields in GtkObjectClass:
void (* shutdown) (GtkObject *object);
void (* destroy) (GtkObject *object);
void (* finalize) (GtkObject *object);
As you might guess from this, objects are destroyed in a three-stage process. Each
method represents one stage in the process; if your object subclass overrides any of
them, it must "chain up" to the corresponding method in the parent class (see the
section called Chaining Up). The three methods do the following:
The shutdown method allows objects to perform actions before destruction begins.
Most subclasses do not override this method; the default shutdown method emits
the "destroy" signal to start the next phase. (The default implementation will always
be invoked, even if overridden, because subclasses are required to "chain up.")
The destroy method marks the object "useless" and cleans up associated resources,
but does not free the object itself. Typically a destroy method would free data,
strings, and so on stored in the instance struct, and set the struct members to NULL.
This is the method most subclasses override.
The finalize method is invoked only when the objects reference count reaches 0. The
default implementation frees the object instance struct, so that further attempts to
use the object result in a segmentation fault. The finalize method must also consider that user code could have been invoked after the destroy method, and free
any data that user code could have allocated.
Note: Objects can be destroyed regardless of their reference count. This means that the
shutdown method is invoked and the destroy signal is emitted. However, as long as
the reference count is greater than 0, the object will not be finalized.
The shutdown method has no defined role; its purpose depends on the particular
object. For example, the GtkWidget shutdown implementation removes the widget
from its parent container, and unrealizes the widget. This is especially important for
containers: their destroy method destroys all children of the container. If the container
was not unrealized before destruction, it would still be visible and the user would see
each child disappear, followed by the container. With the shutdown method, everything disappears at once.
The destroy method frees as many resources as possible without rendering the object
"unsafe." If your object has invariants describing its integrity, a destroy method will
not violate them. All public functions exported by an object implementation should
gracefully handle destroyed objects (they should not crashremember that an object
156
can be destroyed while references to it persist). The finalize method actually frees the
object, meaning that attempts to use the object become dangerous bugs.
The statement that "public functions exported by an object implementation should
gracefully handle destroyed objects" requires some qualification. This is the intended
behavior; otherwise, code could not ensure the sanity of an object by increasing its
reference count. However, the implementation does not yet live up to the guarantee
in all cases. Some public functions in GTK+ and Gnome still assume data structures
freed in the destroy method exist, or re-allocate data structures the destroy method
already freed. Unless the finalize method re-frees those data structures, they will be
leaked. To avoid these bugs, it is best to avoid calling functions on destroyed objects
(in practice, it would be uncommon to do so).
You can count on being able to check the type and object flags of a destroyed object,
however; and it is certainly safe to call gtk_object_unref() on a destroyed object.
In your own object implementations, be sure you implement each public function
correctly; check whether the object is destroyed with GTK_OBJECT_DESTROYED(), and
keep in mind that user code can run between the destroy method and the finalize
method.
Notice that the destroy method is the default handler for a "destroy" signal, but the
shutdown and finalize methods are class functions only. This reduces the complexity
and increases the speed of the finalization process. Also, because finalize destroys
the integrity of an object, it would be unsafe to emit as a signal (GTK+ does have a
facility called "weak references" that allows you to invoke a callback when an object
is finalizedweak references do not assume that the GtkObject is in a sane state).
To make things more concrete, lets look at the functions you would use to destroy
an object. First, gtk_object_destroy():
void
gtk_object_destroy
{
g_return_if_fail
g_return_if_fail
g_return_if_fail
(GtkObject *object)
(object != NULL);
(GTK_IS_OBJECT (object));
(GTK_OBJECT_CONSTRUCTED (object));
if (!GTK_OBJECT_DESTROYED (object))
{
gtk_object_ref (object);
object->klass->shutdown (object);
gtk_object_unref (object);
}
}
Notice that destroyed-but-not-finalized objects are flagged, and this flag can be checked
with the GTK_OBJECT_DESTROYED() macro. gtk_object_destroy() ensures that objects are not destroyed twice by ignoring any already-destroyed objects. If an object has not been destroyed, gtk_object_destroy() references it to prevent finalization during the destroy process and invokes the shutdown method; by default, that
method looks like this:
static void
gtk_object_shutdown (GtkObject *object)
{
GTK_OBJECT_SET_FLAGS (object, GTK_DESTROYED);
gtk_signal_emit (object, object_signals[DESTROY]);
}
157
This method sets the destroyed flag, to ensure that any recursive gtk_object_destroy()
calls have no effect; then it emits the "destroy" signal. gtk_object_shutdown() seems
pointless by itself; however, subclasses may override this method with something
more substantial, chaining up to the GtkObject default method (see the section called
Chaining Up).
It may be unclear that gtk_object_shutdown() is a method implementation, while
gtk_object_destroy() is a public function. Note that gtk_object_shutdown() is
the internal function that implements the shutdown method for the GtkObject class,
while gtk_object_destroy() is part of the public API. The GtkObject implementation of the destroy method is called gtk_object_real_destroy():
static void
gtk_object_real_destroy (GtkObject *object)
{
if (GTK_OBJECT_CONNECTED (object))
gtk_signal_handlers_destroy (object);
}
This code simply cleans up any signal handlers associated with the object. gtk_object_real_destroy()
is the default handler invoked when the "destroy" signal is emitted. gtk_object_destroy()
invokes the (possibly overridden) class function shutdown; the default shutdown
method emits the "destroy" signal.
Finalization is initiated by gtk_object_unref(), if and only if the reference count
has reached 0. gtk_object_unref() can be invoked directly by a user, but often
gtk_object_destroy() invokes it. Here it is:
void
gtk_object_unref (GtkObject *object)
{
g_return_if_fail (object != NULL);
g_return_if_fail (GTK_IS_OBJECT (object));
g_return_if_fail (object->ref_count > 0);
if (object->ref_count == 1)
{
gtk_object_destroy (object);
g_return_if_fail (object->ref_count > 0);
}
object->ref_count -= 1;
if (object->ref_count == 0)
{
object->klass->finalize (object);
}
}
If an object has a reference count of 1, calling gtk_object_unref() invokes the shutdown and destroy methods (via gtk_object_destroy()) and then finalizes the object (unless the reference count was incremented sometime during the shutdown/destroy
process; this is allowed and will prevent finalization). If an objects reference count
is greater than 1 at the start of gtk_object_unref(), the reference count is simply
decremented.
158
Again, notice that an object can be destroyed while the reference count is greater than
1 if the user calls gtk_object_destroy(); if this happens, finalization does not take
place until the holders of the remaining references call gtk_object_unref(). In the
most common case, the gtk_object_destroy() implementation holds the last reference count have another look at the gtk_object_destroy() code with this in
mind.
For completeness, here is GtkObjects default finalize method:
static void
gtk_object_finalize (GtkObject *object)
{
gtk_object_notify_weaks (object);
g_datalist_clear (&object->object_data);
gtk_type_free (GTK_OBJECT_TYPE (object), object);
}
Invoke "weak references," which are callbacks invoked on object finalization. This
is a little-used GtkObject feature not described in this book (usually connecting to
the "destroy" signal is more appropriate).
Clear any object data (described in the section called Attaching Data to Objects).
the section called Widget Life Cycle in Chapter 3 has more to say about reference counting and destruction with respect to widgets.
Chaining Up
If an object overrides the shutdown, destroy, or finalize methods, it should chain up
to the default implementation, to ensure that each parent class has a chance to clean
up. Here is an example of chaining up:
static void
gtk_widget_real_destroy (GtkObject *object)
{
/* ... */
if (parent_class->destroy)
parent_class->destroy (object);
};
159
Of course, if parent_class is not a GtkObjectClass*, you will need to cast it with the
GTK_OBJECT_CLASS() macro.
An aside: notice that you should not chain up when implementing get_arg and set_arg
GTK+ special-cases these methods in gtk_object_set() and gtk_object_get().
Recall that the GtkObject base class initializer zeroes these two methods, rather than
leaving the default implementation. When setting or getting an argument value,
GTK+ uses the information provided on argument registration to jump directly to
the correct class struct and invoke only the correct get_arg or set_arg method. Chaining up would be a much slower way to implement the same thing (and would require
unique argument IDs within the same class ancestry).
Later, when you have a pointer to the button but not the label (perhaps in a callback
connected to the buttons "clicked" signal), you can do this:
GtkWidget* label = gtk_object_get_data(GTK_OBJECT(button),
"my_label_key");
/* If no data is found for the key, NULL is returned. */
160
if (label == NULL)
{
g_warning("No data was associated with my_label_key!");
}
A pair of convenience functions use a predetermined key and thus save typing (and
remembering) the object data key. These are gtk_object_set_user_data() and gtk_object_get_user_da
You can also register a function to free the data when the data is removed or replaced,
or the GtkObject is destroyed; This function should be of type GtkDestroyNotify:
typedef void (*GtkDestroyNotify) (gpointer data);
#include <gtk/gtkobject.h>
void gtk_object_set_data(GtkObject* object, const gchar* key, gpointer data);
void gtk_object_set_data_full(GtkObject* object, const gchar* key, gpointer
data, GtkDestroyNotify destroy);
void gtk_object_remove_data(GtkObject* object, const gchar* key);
gpointer gtk_object_get_data(GtkObject* object, const gchar* key);
void gtk_object_remove_no_notify(GtkObject* object, const gchar* key);
void gtk_object_set_user_data(GtkObject* object, gpointer data);
gpointer gtk_object_get_user_data(GtkObject* object);
161
Each data structure is cast to its "private" version, which contains information relating to the particular window system GDK is being used on; this is to keep windowsystem-specific declarations out of the gdk/gdk.h header file. The private version of
each data structure contains a wrapped Xlib data structure, which is passed to XDrawPoint(). So the XDrawPoint() documentation will also apply to gdk_draw_point().
162
GdkWindow
GdkWindow is a wrapper around Xlibs Window object. (It was discussed briefly in
the section called Realizing, Mapping, and Showing in Chapter 3.) A GdkWindow represents a region on the screen. It can be shown or hidden (called mapping and unmapping
the window in Xlib). You can capture events received by a GdkWindow, draw graphics inside it, and move or resize it. GdkWindows are arranged in a tree structure; that
is, each window can have child windows. Child windows are positioned relative to
their parent window, and move when the parent moves. Child windows dont draw
outside of their parents bounds (i.e. they are clipped by the parent window).
The tree of GdkWindows is not specific to each application; there is a global tree of
windows controlled by the X server and the window manager. The root window has
no parent; all windows derive from it. All or part of it is visible as your desktop background. Each window can be owned by a different UNIX process; some windows
will be created by the window manager, some will come from user applications.
GdkWindow and GtkWindow are very different things; GtkWindow is a GTK+ widget
used to represent toplevel windows (toplevel windows are the highest applicationcontrolled windows in the window hierarchy). Window managers typically create
decorations for toplevel windows; decorations include title bars, close buttons, and
the like.
Its important to understand that an X window is primarily an object on the X server.
X clients receive a unique integer ID for each window, and refer to windows by ID.
Thus, all window operations take place on the server; all functions that deal with X
windows go across the network.
GdkWindow is a wrapper around the integer ID returned by X. It does keep local
copies of some information (such as the windows dimensions), so some GDK operations are more efficient than the corresponding Xlib operations. Still, GdkWindow
is essentially a handle for a server-side object. Many GDK objects are similar; fonts,
pixmaps, cursors, and so on are also handles for server-side objects.
GdkWindow Attributes
gdk_window_new() (shown in Figure 10-1) allows you to specify all of a windows
attributes when you create it; many of them can be changed later as well. To specify
163
a block of attributes, you pass in a GdkWindowAttr object; its contents will give you
an idea what attributes a GdkWindow can have:
typedef struct _GdkWindowAttr GdkWindowAttr;
struct _GdkWindowAttr
{
gchar *title;
gint event_mask;
gint16 x, y;
gint16 width;
gint16 height;
GdkWindowClass wclass;
GdkVisual *visual;
GdkColormap *colormap;
GdkWindowType window_type;
GdkCursor *cursor;
gchar *wmclass_name;
gchar *wmclass_class;
gboolean override_redirect;
};
destroys a window when you are done with it. Windows are also reference counted;
be sure to read the section called GDK Resource Management for more details on this.
#include <gdk/gdk.h>
GdkWindow* gdk_window_new(GdkWindow* parent, GdkWindowAttr* attributes,
gint attributes_mask);
void gdk_window_destroy(GdkWindow* window);
164
GDK_WINDOW_ROOT is the type of the GDK wrapper for the root window,
created at initialization time.
GDK_WINDOW_TEMP is used for popup menus and the like; its a window that
will exist only briefly. Its a toplevel window, so its parent should be NULL. These
windows are always override redirect and their cursor is always the same as their
parents. So they will ignore those elements of the attributes struct.
165
dows to behave according to the window managers layout policy. You can override
this behavior by setting override_redirect to TRUE. Since window managers can not
move windows with this flag set, they will normally not put a title bar or other decorations on them. Note that all GDK_WINDOW_TEMP windows use TRUE for this
field; recall that GDK_WINDOW_TEMP is often used for popup menus, which are
not controlled by the window manager.
Typically you should not change the override_redirect field; the default is almost
always right, if you specify the correct GdkWindowType. However, there are some
exceptions; the Gnome panel application sets this field, for example.
Table 10-1. GdkWindowAttr Fields
Field
title
Type
gchar*
event_mask
gint
none
none
gint16
GDK_WA_X
gint16
GDK_WA_Y
width
gint16
none
none
height
gint16
none
none
none
none
wclass
GdkWindowClass
Events to
receive on this
window
X position
relative to
parent window
Y position
relative to
parent window
Width of
window
Height of
window
GDK_INPUT_ONLY
vs.
GDK_INPUT_OUTPUT
visual
GdkVisual*
Xs "default
GDK_WA_VISUAL
visual"
colormap
GdkColormap*
Xs "default
GDK_WA_COLORMAP
colormap"
[PD]footnote!
none
none
Colormap for
this window
Parent
GDK_WA_CURSOR
windows
cursor
none (doesnt
GDK_WA_WMCLASS
set hint)
Mouse pointer
for this window
window_type
cursor
GdkWindowType
GdkCursor*
wmclass_name gchar*
wmclass_class
166
Flag
gchar*
none (doesnt
GDK_WA_WMCLASS
set hint)
Window type
(see text)
Field
override_redirect
Type
gboolean
Flag
GdkVisual
Xlib can report a list of all available visuals and information about each; GDK keeps
a client-side copy of this information in a struct called GdkVisual. GDK can report
the available visuals, and rank them in different ways. Most of the time you will only
use gdk_visual_get_system(), which returns a pointer to the default visual (Figure
167
#include <gdk/gdk.h>
GdkVisual* gdk_visual_get_system(void);
Types of Visual
Visuals differ along several dimensions. They can be grayscale or RGB, colormaps
can be modifiable or fixed, and the pixel value can either index a single colormap or
contain packed red, green, and blue indexes. Here are the possible values for GdkVisualType:
168
blue. The display is almost certainly 12-bit or less (a 24-bit display using a single
colormap would need a colormap with 2^24 entries, occupying close to half a gigabytenot very practical!). This is an annoying visual, because relatively few colors
are available and you cant change which colors they are.
GDK_VISUAL_PSEUDO_COLOR is the most common visual on low-end PC hardware from several years ago. If you have a one-megabyte 256-color video card, this
is most likely your X servers visual. It represents a color display with a read/write
colormap. Pixels index a single colormap.
In Xlib, this is an enormously complicated process, because it has to be done differently for every kind of visual. GDK conceals things fairly well. You simply call
gdk_colormap_alloc_color() to fill in the pixel value and add the color to the colormap (Figure 10-3). Here is an example; it assumes a preexisting GdkColormap*
colormap, which should be the colormap of the drawable you are targetting:
GdkColor color;
/* Describe
color.red
color.green
color.blue
a
=
=
=
pure red */
65535;
0;
0;
169
When youre finished with a color, you can remove it from the colormap with gdk_colormap_free_colors(
This is only really important for pseudo color and grayscale visuals, where colors are
in short supply and the colormap can be modified by clients. GDK will automatically
do the right thing for each visual type, so always call this function.
A convenient way to obtain RGB values is the gdk_color_parse() function. This
takes an X color specification, and fills in the red, green, and blue fields of a GdkColor.
An X color specification can have many forms; one possibility is an RGB string:
RGB:FF/FF/FF
This specifies white (red, green, and blue are all at full intensity). The RGB: specifies a
"color space," and determines the meaning of the numbers after it. X also understands
several more obscure color spaces. If the color specification string doesnt begin with
a recognized color space, X assumes its a color name and looks it up in a database of
names. So you can write code like this:
GdkColor color;
if (gdk_color_parse("orange", &color))
{
if (gdk_colormap_alloc_color(colormap, &color, FALSE, TRUE))
{
/* We have orange! */
}
}
170
As you can see, gdk_color_parse() returns TRUE if it figures out the string you
pass it. There is no way to know exactly what will be in the color database, so always
check this return value.
#include <gdk/gdk.h>
gboolean gdk_colormap_alloc_color(GdkColormap* colormap, GdkColor* color,
gboolean writeable, gboolean best_match);
void gdk_colormap_free_colors(GdkColormap* colormap, GdkColor* colors, gint
ncolors);
gint gdk_color_parse(gchar* spec, GdkColor* color);
Obtaining a Colormap
If youre writing a GtkWidget subclass, the correct way to obtain a colormap is with
gtk_widget_get_colormap() (see Chapter 11). Otherwise, the system (default) colormap is usually what you want; call gdk_colormap_get_system(), which takes no
arguments and returns the default colormap.
The GdkRGB module (see the section called RGB Buffers) is another way to deal with
colors; among other capabilities, it can set the foreground and background colors of a
graphics context from an RGB value. The relevant functions are gdk_rgb_gc_set_foreground()
and gdk_rgb_gc_set_background(). GdkRGB has a pre-allocated colormap that it
uses to pick a best-match color; using it means that your application can share limited
colormap resources with other applications using GdkRGB (such as the Gimp). You
can also obtain GdkRGBs colormap and use it directly (see the section called RGB
Buffers).
171
On the client side, pixmaps and bitmaps are just GdkWindows with type GDK_WINDOW_PIXMAP.
GdkDrawable is used in function declarations when either a window or a pixmap is
an acceptable argument. Functions that draw graphics take either type; functions that
move windows around or set window manager hints accept only windows. Only
windows can receive events. GDK_INPUT_ONLY windows are a special case; they
are not drawables and you cant draw on them.
Three of the four logical combinations of "window features" and drawability actually
exist:
Window Features
No Window Features
Drawable
Normal Window
Pixmap/Bitmap
Not Drawable
Input Only Window
--
Unfortunately, all three of these logically distinct cases appear the same from a typechecking point of view. So be careful not to use the wrong one. Also keep in mind
that a normal window is not drawable until it actually appears on the screen; you
should wait until you receive an expose event before you draw. Expose events are
covered in the section called Expose Events.
Like GdkWindow, a GdkPixmap is merely a client-side handle for an object located
on the X server. Because of this, some things are entirely infeasible from a performance point of view; notably, if you are doing anything which requires significant
manipulation of individual pixels, drawables will be far too slow. On the other hand,
copying a pixmap to a window is not as slow as you might think, because both objects
are on the same machine.
Creating a pixmap is much easier than creating a window, because most of the window attributes are not relevant to pixmaps. The function is gdk_pixmap_new() (Figure 10-4). It accepts an initial size, and a bit depth. If a depth of -1 is given, the depth
is copied from its GdkWindow argument. You cant choose an arbitrary number for
the depththe server will not support all depths, and the pixmaps depth must
match the depth of any windows you plan to copy it to. To destroy a pixmap, call
gdk_pixmap_unref().
The GdkWindow argument to gdk_pixmap_new() may not seem strictly necessary.
However, the function wraps XCreatePixmap(), which takes an X window as an
argument. It uses this argument to determine which screen to create the window on;
some X servers have multiple displays. Screens are an Xlib concept totally concealed
by GDK; GDK supports only one screen at a time. Thus the window argument to
gdk_pixmap_new() seems mysterious from a GDK point of view.
#include <gdk/gdk.h>
GdkPixmap* gdk_pixmap_new(GdkWindow* window, gint width, gint height, gint
depth);
void gdk_pixmap_unref(GdkPixmap* pixmap);
172
Events
Events are sent to your application to indicate changes in a GdkWindow or user actions you might be interested in. All events are associated with a GdkWindow. They
also come to be associated with a GtkWidget; the GTK+ main loop passes events from
GDK to the GTK+ widget tree.
Types of Event
There are many kinds of events; the GdkEvent union can represent any of them. A
special event type, GdkEventAny, contains the three fields common to all events; any
event can be cast to GdkEventAny. The first field in GdkEventAny is a type marker,
GdkEventType; GdkEventType is also included in the GdkEvent union. Confused
yet? Seeing the code should help. Here is GdkEventAny:
struct _GdkEventAny
{
GdkEventType type;
GdkWindow *window;
gint8 send_event;
};
and GdkEvent:
union _GdkEvent
{
GdkEventType
GdkEventAny
GdkEventExpose
GdkEventNoExpose
GdkEventVisibility
GdkEventMotion
GdkEventButton
GdkEventKey
GdkEventCrossing
GdkEventFocus
GdkEventConfigure
GdkEventProperty
GdkEventSelection
GdkEventProximity
GdkEventClient
GdkEventDND
};
type;
any;
expose;
no_expose;
visibility;
motion;
button;
key;
crossing;
focus_change;
configure;
property;
selection;
proximity;
client;
dnd;
Every event type has the three members of GdkEventAny as its first three members.
Thus, the type of an event can be referred to in many ways (assume a GdkEvent*
called event):
event->type
event->any.type
event->button.type
((GdkEventAny*)event)->type
173
((GdkEventButton*)event)->type
Youll probably see all these in GTK+ source code. Of course, each event subtype has
its own unique members; the type field tells you which subtype is valid.
The window field of GdkEventAny is the GdkWindow the event was sent to. If
the send_event flag is TRUE, then the event was synthesized by another (or your
own) application; if FALSE, it originated with the X server. GDK does not export
the X interface for sending events (XSendEvent()). However, GTK+ often "makes
up" an event by declaring a static event struct, filling it in, then emitting the events
corresponding widget signal. These synthesized events will have send_event set to
TRUE. the section called Receiving GDK Events in GTK+ explains how GTK+ associates events with widget signals.
There are more possible values for GdkEventType than there are members in the GdkEvent union. Many event types share the same data; for example, GDK_BUTTON_PRESS
and GDK_BUTTON_RELEASE both use the button member of GdkEvent, since the
same information is conveyed when mouse buttons are pressed and released. Table 10-2 shows all possible values of the GdkEventType enumeration, and the corresponding GdkEvent member. The meaning of each event type is described later in
this section.
Table 10-2. GdkEventType Values
Value
GDK_NOTHING
GDK_DELETE
GDK_DESTROY
GDK_EXPOSE
GDK_MOTION_NOTIFY
GDK_BUTTON_PRESS
GDK_2BUTTON_PRESS
GDK_3BUTTON_PRESS
GDK_BUTTON_RELEASE
GDK_KEY_PRESS
GDK_KEY_RELEASE
GDK_ENTER_NOTIFY
GDK_LEAVE_NOTIFY
GDK_FOCUS_CHANGE
GDK_CONFIGURE
GDK_MAP
GDK_UNMAP
GDK_PROPERTY_NOTIFY
GDK_SELECTION_CLEAR
GDK_SELECTION_REQUEST
GDK_SELECTION_NOTIFY
GDK_PROXIMITY_IN
GDK_PROXIMITY_OUT
GDK_DRAG_ENTER
GDK_DRAG_LEAVE
174
GdkEvent Member
none [PD] footnote!
GdkEventAny
GdkEventAny
GdkEventExpose
GdkEventMotion
GdkEventButton
GdkEventButton
GdkEventButton
GdkEventButton
GdkEventKey
GdkEventKey
GdkEventCrossing
GdkEventCrossing
GdkEventFocus
GdkEventConfigure
GdkEventAny
GdkEventAny
GdkEventProperty
GdkEventSelection
GdkEventSelection
GdkEventSelection
GdkEventProximity
GdkEventProximity
GdkEventDND
GdkEventDND
Value
GDK_DRAG_MOTION
GDK_DRAG_STATUS
GDK_DROP_START
GDK_DROP_FINISHED
GDK_CLIENT_EVENT
GDK_VISIBILITY_NOTIFY
GDK_NO_EXPOSE
GdkEvent Member
GdkEventDND
GdkEventDND
GdkEventDND
GdkEventDND
GdkEventClient
GdkEventVisibility
GdkEventNoExpose
#include <gdk/gdk.h>
GdkEventMask gdk_window_get_events(GdkWindow* window);
void gdk_window_set_events(GdkWindow* window, GdkEventMask event_mask);
#include <gtk/gtkwidget.h>
gint gdk_widget_get_events(GtkWidget* widget);
void gtk_widget_add_events(GtkWidget* widget, gint event_mask);
void gtk_widget_set_events(GtkWidget* widget, gint event_mask);
Map, unmap, destroy, and configure events are selected with GDK_STRUCTURE_MASK,
but GDK automatically selects them on any new window. (Xlib programmers beware; Xlib does not do this.)
Selection, client, drag-and-drop, and delete events have no masks, because they
are automatically selected (Xlib selects them for all windows).
175
Event Type
GDK_EXPOSE
GDK_MOTION_NOTIFY
N/A (see the section called Mouse
GDK_POINTER_MOTION_HINT_MASK Movement Events)
GDK_BUTTON_MOTION_MASK
GDK_BUTTON1_MOTION_MASK
GDK_BUTTON2_MOTION_MASK
GDK_BUTTON3_MOTION_MASK
GDK_BUTTON_PRESS_MASK
GDK_BUTTON_RELEASE_MASK
GDK_KEY_PRESS_MASK
GDK_KEY_RELEASE_MASK
GDK_ENTER_NOTIFY_MASK
GDK_LEAVE_NOTIFY_MASK
GDK_FOCUS_CHANGE_MASK
GDK_STRUCTURE_MASK
GDK_PROPERTY_CHANGE_MASK
GDK_VISIBILITY_NOTIFY_MASK
GDK_PROXIMITY_IN_MASK
GDK_PROXIMITY_OUT_MASK
GDK_SUBSTRUCTURE_MASK
GDK_ALL_EVENTS_MASK
GDK_MOTION_NOTIFY (while a
button is pressed)
GDK_MOTION_NOTIFY (while button
1 is pressed)
GDK_MOTION_NOTIFY (while button
2 is pressed)
GDK_MOTION_NOTIFY (while button
3 is pressed)
GDK_BUTTON_PRESS,
GDK_2BUTTON_PRESS,
GDK_3BUTTON_PRESS
GDK_BUTTON_RELEASE
GDK_KEY_PRESS
GDK_KEY_RELEASE
GDK_ENTER_NOTIFY
GDK_LEAVE_NOTIFY
GDK_FOCUS_IN, GDK_FOCUS_OUT
GDK_CONFIGURE, GDK_DESTROY,
GDK_MAP, GDK_UNMAP
GDK_PROPERTY_NOTIFY
GDK_VISIBILITY_NOTIFY
GDK_PROXIMITY_IN
GDK_PROXIMITY_OUT
Receive GDK_STRUCTURE_MASK
events for child windows
All events
176
signals.
In general, events go to the widget owning the GdkWindow the event occurred on.
However, there are certain special cases.
if a widget has the grab (i.e., if gtk_grab_add() was called, see the section called
Grabs in Chapter 3), certain events will only be forwarded to the widget with the
grab, or the children of that widget. Events that occur on other widgets are ignored.
Only certain user-initiated events such as button events and key events are affected
by a grab.
Widget sensitivity (see the section called Sensitivity in Chapter 3) also affects where
events are sent. Events representing user interaction are not forwarded to insensitive
widgets.
As you might expect, widgets with no associated GdkWindow do not originate events;
X only sends events to windows. There is one exception: containers synthesize expose
events for their windowless children.
The GTK+ main loop propagates certain events from child widgets to their parent
containers. That is, for each event, a signal is emitted first from a child widget, then
from its immediate parent, then from the parents parent, and so on. For example, if
you click a GtkMenuItem, it ignores the button press and lets the menu its a part of
handle it. Some events are not propagated; Table 10-4 gives details.
Event propagation ends once a widget "handles" the event. This ensures that only one
user-visible change results from any user action. Handlers for GtkWidgets event signals must return a gint value. Recall that the last signal handler to run determines the
return value of a signal emissionsee the section called Emitting A Signal in Chapter
9. All event signals are GTK_RUN_LAST, so the return value will come from:
If the emission of an event signal returns TRUE, the GTK+ main loop will stop
propagating the current event. If it returns FALSE, the main loop will propagate
the event to the widgets parent. Recall that each event results in two signal emissions: a generic "event" signal and a specific signal (such as "button_press_event"
or "key_press_event"). If either emission returns TRUE, event propagation ends. The
return value from the generic "event" signal has one additional effect: if TRUE, the
second, more specific signal will not be emitted.
Table 10-4 summarizes how GtkWidget signals correspond to event types, which
events are affected by an active grab, and which events are propagated from parent to child. Signal handlers for all event signals should return a gint and take three
arguments: the widget emitting the signal, the event which triggered the signal, and
a user data pointer.
Table 10-4. GtkWidget Events
Event Type
GDK_DELETE
GDK_DESTROY
GDK_EXPOSE
"delete_event"
"destroy_event"
"expose_event"
No
No
No
Grabbed?
No
No
No
177
Event Type
"moGDK_MOTION_NOTIFY
tion_notify_event"
Yes
Grabbed?
Yes
"butGDK_BUTTON_PRESS
ton_press_event"
Yes
Yes
"butGDK_2BUTTON_PRESS
ton_press_event"
Yes
Yes
"butGDK_3BUTTON_PRESS
ton_press_event"
Yes
Yes
"butGDK_BUTTON_RELEASE
ton_release_event"
Yes
Yes
"key_press_event" Yes
"key_release_event" Yes
GDK_KEY_RELEASE
Yes
Yes
No
Yes
No
"focus_in_event",
GDK_FOCUS_CHANGE
"focus_out_event"
No
No
GDK_CONFIGURE "configure_event"
No
No
GDK_MAP
GDK_UNMAP
"map_event"
"unmap_event"
"propGDK_PROPERTY_NOTIFY
erty_notify_event"
No
No
No
No
No
No
"selecGDK_SELECTION_CLEAR
tion_clear_event"
No
No
"selecNo
GDK_SELECTION_REQUEST
tion_request_event"
No
"selecGDK_SELECTION_NOTIFY
tion_notify_event"
No
No
"proximGDK_PROXIMITY_IN
ity_in_event"
Yes
Yes
"proximGDK_PROXIMITY_OUT
ity_out_event"
Yes
Yes
"client_event"
GDK_CLIENT_EVENT
No
No
GDK_KEY_PRESS
GDK_ENTER_NOTIFY
"enter_notify_event"
GDK_LEAVE_NOTIFY
"leave_notify_event"
178
Event Type
"visibilGDK_VISIBILITY_NOTIFY
ity_notify_event"
No
GDK_NO_EXPOSE "no_expose_event" No
Grabbed?
No
No
Button Events
Four different event types result in a GdkEventButton:
If you click three times quickly, on the same GdkWindow, the following events are
received in order:
1. GDK_BUTTON_PRESS
2. GDK_BUTTON_RELEASE
3. GDK_BUTTON_PRESS
4. GDK_2BUTTON_PRESS
5. GDK_BUTTON_RELEASE
6. GDK_BUTTON_PRESS
7. GDK_3BUTTON_PRESS
8. GDK_BUTTON_RELEASE
The X server automatically causes a pointer grab when a button is pressed, and releases it when it is released. This means that the button release event always goes
to the same window that received the button press event. Xlib allows you to change
this behavior, but GDK does not. (In the Xlib documentation, this automatic grab
is referred to as a "passive" grab. Its distinct from an "active" grab initiated with
gdk_pointer_grab(), described in the section called Grabbing the Pointer.)
A button event is defined as follows:
typedef struct _GdkEventButton GdkEventButton;
struct _GdkEventButton
{
GdkEventType type;
GdkWindow *window;
gint8 send_event;
guint32 time;
gdouble x;
gdouble y;
179
gdouble pressure;
gdouble xtilt;
gdouble ytilt;
guint state;
guint button;
GdkInputSource source;
guint32 deviceid;
gdouble x_root, y_root;
};
Button events are marked with a time stamp (time) by the X server. The time is given
in milliseconds of "server time"; every few weeks the integer overflows and timestamps begin again at 0. Thus, you should not rely on the value as an absolute measure
of time; it is intended only to determine relative time between events.
The mouse pointers X and Y coordinates (relative to the window the event occurred
in) are included in GdkEventButton. Keep in mind that the pointer may be outside
the window (if a pointer grab is in effect; see the section called The Mouse Pointer). If
the pointer is outside the window, its coordinates could be negative or larger than the
windows size. Coordinates are given as doubles rather than integers, because some
input devices such as graphics tablets have sub-pixel resolution. For most purposes,
you will want to cast the doubles to integers. pressure, xtilt, and ytilt are also special
features of some input devices; they can be ignored almost all the time.
The state member of GdkEventButton indicates which modifier keys or mouse buttons were held down an instant before the button was pressed. It is a bitfield, with
one or more of the flags in Table 10-5 set. Since the modifiers are read just before the
button press, it follows that button press events do not have the pressed button in
state, but button release events do have it.
Be careful to check for the presence of certain bit masks, rather than the exact value
of state. That is, prefer this:
if ( (state & GDK_SHIFT_MASK) == GDK_SHIFT_MASK )
If you check the exact value of state, your application will mysteriously stop working
if the user has Num Lock or some other obscure modifier turned on.
Table 10-5. Modifier Masks for Key and Button Events
Modifier Mask
GDK_SHIFT_MASK
GDK_LOCK_MASK
GDK_CONTROL_MASK
GDK_MOD1_MASK
GDK_MOD2_MASK
GDK_MOD3_MASK
GDK_MOD4_MASK
180
Meaning
Shift
Caps Lock
Control
Mod1 (often Meta or Alt)
Mod2
Mod3
Mod4
Modifier Mask
GDK_MOD5_MASK
GDK_BUTTON1_MASK
GDK_BUTTON2_MASK
GDK_BUTTON3_MASK
GDK_BUTTON4_MASK
GDK_BUTTON5_MASK
GDK_RELEASE_MASK
Meaning
Mod5
Button 1
Button 2
Button 3
Button 4
Button 5
Key releases
The button member of GdkEventButton indicates which button triggered the event
(i.e., the button which was pressed or released). Buttons are numbered from one to
five; most of the time, button one is the left button, button two is the middle button,
and button three is the right button. Left-handed users might reverse these. Button
four and five events are generated by some scroll wheel mice when you spin the scroll
wheel; GTK+ attempts to send capture these events and move nearby scroll bars. You
should probably ignore any events you receive for buttons four or five.
The three standard mouse buttons have conventional meanings in Gnome. Button
one is used for selection, drag and drop, and operating widgets: the most common
tasks. Button three typically activates a pop-up menu. Button two is traditionally
used to move objects, such as the panel. Sometimes button one moves objects also;
for example, desktop icons can be moved with either button one or two. It is a good
idea to be consistent with other applications whenever possible.
The source and deviceid members are used to determine which device triggered the
event; the user may have a graphics tablet and a mouse connected simultaneously,
for example. You can ignore these fields unless you are writing an application that
can take advantage of non-mouse devices.
The last two members of GdkEventButton, x_root and y_root, are the x and y coordinates translated to be relative to the root window rather than the window receiving
the event. You can use these as "absolute" coordinates to compare events from two
different windows.
Keyboard Events
There are only two types of key event: GDK_KEY_PRESS and GDK_KEY_RELEASE.
Some hardware does not generate key release events; you should not write code that
depends on GDK_KEY_RELEASE events, though your code should respond sanely
if one is received.
Here are the contents of a key event:
typedef struct _GdkEventKey GdkEventKey;
struct _GdkEventKey
{
GdkEventType type;
GdkWindow *window;
gint8 send_event;
guint32 time;
guint state;
guint keyval;
gint length;
gchar *string;
};
181
The first three members are the standard members from GdkEventAny; the time and
state members are identical to those found in GdkEventButton.
keyval contains a keysym. The X server keeps a global translation table which converts combinations of physical keys and modifiers to keysyms. For example, the
key marked "A" on the keyboard typically generates the keysym GDK_a with no
modifiers, and GDK_A with shift held down. Users can change the physical-keyto-keysym mapping; for example, they may rearrange their keys to create a Dvorak
keyboard (more commonly, they might swap Control and Caps Lock, or use the Alt
key as a Meta key). Keysyms are defined in gdk/gdkkeysyms.h. You will need to
include this file to use the keyval field.
Keysyms are matched with a string representation. For example, the GDK_a keysym
typically maps to the string "a". (However, X allows the keysym-to-string mapping
to be modified.) The string member of GdkEventKey contains a keysyms string representation, and the length member contains the strings length. Keep in mind that
the length may be 0 (many non-alphanumeric keys have no string representation by
default). (If youre familiar with Xlib, the string field is simply the result of XLookupString() or XmbLookupString(). Even if you arent familiar with Xlib, the man
pages for these functions may be helpful.)
In general, if you are reading key events in order to create a textual representation
of what the user is typing, you should use the string field of GdkEventKey. GtkEntry and GtkText use the string field, for example. A word processor would also read
this field. If youre reading key events for some other reason (such as keyboard shortcuts), or if you are interested in keys with no string representation by default (such as
function keys or arrow keys), you will need to use the keyval field and the keysyms
defined in gdk/gdkkeysyms.h.
Here is a sample key event callback demonstrating how to extract information from a
key event. It would be suitable for connection to the "key_press_event" signal of any
GtkWidget:
static gint
key_press_cb(GtkWidget* widget, GdkEventKey* event, gpointer data)
{
if (event->length > 0)
printf("The key events string is %s\n", event->string);
printf("The name of this keysym is %s\n",
gdk_keyval_name(event->keyval));
switch (event->keyval)
{
case GDK_Home:
printf("The Home key was pressed.\n");
break;
case GDK_Up:
printf("The Up arrow key was pressed.\n");
break;
default:
break;
}
if (gdk_keyval_is_lower(event->keyval))
{
printf("A non-uppercase key was pressed.\n");
}
182
else if (gdk_keyval_is_upper(event->keyval))
{
printf("An uppercase letter was pressed.\n");
}
}
gdk_keyval_name() is useful for debugging; it returns the name of the keysym with-
out the GDK_ prefix. For example, it returns "Home" if passed the value GDK_Home.
The string is statically allocated. gdk_keyval_is_lower() returns FALSE if the keysym
has an uppercase equivalent. Thus it returns TRUE for lowercase letters, numbers,
and all non-alphanumeric characters. It returns FALSE only for uppercase letters.
gdk_keyval_is_upper() returns the opposite values.
Which mode you choose depends on the application. If you need to trace the exact
trajectory of the pointer, you will want to get all motion events. If you only care about
the most recent pointer position, you will want to include GDK_POINTER_MOTION_HINT_MASK
in your windows event mask to minimize network traffic and maximize responsiveness. One caveat: gdk_window_get_pointer() requires a server round-trip to obtain
the pointer position; so it does place some maximum limit on your applications responsiveness. If you can handle motion events quickly enough to keep them from
backlogging, your application will probably seem faster without GDK_POINTER_MOTION_HINT_MASK.
Motion events are unlikely to come more often than a couple hundred per second
so if you can handle them in less than 5 milliseconds, you should be OK.
You can ask to receive motion events only while one or more mouse buttons are held
down. To receive motion events while any button is down, use GDK_BUTTON_MOTION_MASK
in place of GDK_POINTER_MOTION_MASK. You can use GDK_POINTER_MOTION_HINT_MASK
with GDK_BUTTON_MOTION_MASK to limit the number of events received, just
as you can use it with GDK_POINTER_MOTION_MASK. If you are only interested
in motion events while a certain button is pressed, you can use the more specific
GDK_BUTTON1_MOTION_MASK, GDK_BUTTON2_MOTION_MASK, and GDK_BUTTON3_MOTION_
Any combination of these three is allowed. They can also be combined with GDK_POINTER_MOTION_HIN
to limit the number of events.
In sum, you can select which motion events to receive along the "button state" dimension using these five masks:
183
By default, you are deluged with events as quickly as the X server can generate them;
adding GDK_POINTER_MOTION_HINT_MASK to the event mask enables one-ata-time behavior.
Motion events are represented by GdkEventMotion:
typedef struct _GdkEventMotion GdkEventMotion;
struct _GdkEventMotion
{
GdkEventType type;
GdkWindow *window;
gint8 send_event;
guint32 time;
gdouble x;
gdouble y;
gdouble pressure;
gdouble xtilt;
gdouble ytilt;
guint state;
gint16 is_hint;
GdkInputSource source;
guint32 deviceid;
gdouble x_root, y_root;
};
Most of these fields should be familiar to you from GdkEventButton; in fact, the only
field unique to GdkEventMotion is the is_hint flag. If this field is TRUE, GDK_POINTER_MOTION_HINT_M
was selected. You might use this flag if you are writing a widget for other people to
use, and you want to let them choose how to receive motion events. In your motion
event handler, you could do this:
double x, y;
x = event->motion.x;
y = event->motion.y;
if (event->motion.is_hint)
gdk_window_get_pointer(event->window, &x, &y, NULL);
That is, you call gdk_window_get_pointer() only if necessary. If you are using
GDK_POINTER_MOTION_HINT_MASK, you should prefer the results from gdk_window_get_pointer()
to the coordinates given in the event, because they are more recent. (If you are receiving every event, it makes no sense to call gdk_window_get_pointer() because it is
relatively slow and will worsen the backlogyoure getting every event eventually
anyway.)
Crossing events occur when the mouse pointer enters or leaves a window. If you
move the mouse pointer rapidly across your application, GDK generates these events
for every window you pass through. However, GTK+ will try to remove the events
184
"in the middle" and forward only the first leave event and the last enter event to
widgets. If you feel you should be getting enter/leave events when you arent, this
optimization is a likely cause.
Here is GdkEventCrossing:
typedef struct _GdkEventCrossing GdkEventCrossing;
struct _GdkEventCrossing
{
GdkEventType type;
GdkWindow *window;
gint8 send_event;
GdkWindow *subwindow;
guint32 time;
gdouble x;
gdouble y;
gdouble x_root;
gdouble y_root;
GdkCrossingMode mode;
GdkNotifyType detail;
gboolean focus;
guint state;
};
Again, many of the fields should be familiar; coordinates relative to the event window and the root window, a time stamp, a state bitfield indicating which buttons
and modifiers are active, and the standard three fields from GdkEventAny. However,
there are several new fields.
The standard window field contains a pointer to the window the pointer is entering
or leaving; x and y are relative to this window. However, the pointer may have been
in a child of the window receiving the event before a leave event occurred; the pointer
may end up in a child window when an enter event occurs. In these cases, subwindow is set to the child window. Otherwise subwindow is NULL. Note that the child
window will receive its own enter and leave events, if it GDK_ENTER_NOTIFY_MASK
or GDK_LEAVE_NOTIFY_MASK are in its event mask.
The mode field indicates whether the event occurred normally, or as part of a pointer
grab. When the pointer is grabbed or ungrabbed (see the section called The Mouse
Pointer), the pointer may be moved; crossing events caused by a grab have the GDK_CROSSING_GRAB
mode, those caused by an ungrab have GDK_CROSSING_UNGRAB, and all others
have GDK_CROSSING_NORMAL. This field appears to be completely useless; some
quick greps through GTK+ and Gnome reveal no examples of its use.
The detail field is rarely used. It gives information about the relative tree positions of
the window being left and the window being entered. It has two simple and useful
values:
185
Keyboard Focus
The focus field in GdkEventCrossing indicates whether the event window or one of
its ancestors has the keyboard input focus. Keyboard focus is an X concept, used to
determine which window should receive key events. The window manager decides
which toplevel window has the focus (usually the focused window is highlighted
and brought to the top; most window managers let you choose between "focus follows mouse" and "click to focus" modes). When an application has the focus, it is
free to move it among its subwindowsperhaps different text entry fields. However,
GTK+ does not use the X focus mechanism for subwindows. Toplevel GtkWindow
widgets are the only ones which receive the X focus. Thus, they receive all raw key
events from X (by way of GDK). GTK+ implements its own concept of widget focus, which is analagous to Xs window focus, but in reality entirely distinct. When a
toplevel GtkWindow widget receives key events, it forwards them to the widget with
GTK+s focus.
In short, this means the focus flag will be TRUE if the toplevel GtkWindow containing
the event window currently has the X focus. The focus flag is unrelated to GTK+s
widget focus concept.
186
Expose Events
Expose events are received when a previously-obscured region of a window becomes
visible. GdkWindow contents are not recorded; that is, if you draw to a GdkWindow,
then the X server places another window on top of it, the graphics in the bottom
window will be lost. When the top window is moved away, the bottom window
will receive an expose event indicating the region that needs to be re-drawn. Expose
events are also sent when a window first appears on-screen. (Incidentally, you should
not draw into a GdkWindow until you receive the first expose event. The first expose
event is your signal that the window is actually on-screen.)
Expose events have a unique feature: GTK+ synthesizes them for windowless widgets. This is the only kind of event GTK_NO_WINDOW widgets will receive.
Expose events are very simple:
typedef struct _GdkEventExpose GdkEventExpose;
struct _GdkEventExpose
{
GdkEventType type;
GdkWindow *window;
gint8 send_event;
GdkRectangle area;
gint count;
};
area is the area that has been exposed and should be redrawn. count is the number of
expose events that follow this one; conceivably you might want to compress successive events into a single redraw. However, GDK already makes a reasonable effort to
do this, so adding another pass is unlikely to gain much. GdkRectangle is defined as
follows:
typedef struct _GdkRectangle GdkRectangle;
struct _GdkRectangle
{
gint16 x;
gint16 y;
guint16 width;
guint16 height;
};
There is one other time you will receive expose events. If you call gdk_window_copy_area()
to copy part of one window into another, the source window region may be partially
or completely obscured. If it is, X will be unable to copy something sensible from the
obscured region. By default, expose events will be generated for the areas of the destination window X was unable to copy something to. Your programs standard redraw
routine can then refresh these areas of the destination window by hand. You can turn
this behavior off by calling gdk_gc_set_exposures() on the graphics context passed
to gdk_window_copy_area(). (Graphics contexts are discussed in the section called
Graphics Contexts.)
If the source window region is not obscured, gdk_window_copy_area() can successfully draw the entire destination region. In this case, no expose events are generated;
a single "no expose" event is generated instead. This event contains no information
beyond the standard event fields:
187
188
GDK_DELETE means that the window manager has asked the application to destroy this window. If a widget receives the signal corresponding to this event, and
the signal emission returns FALSE, the widget is automatically destroyed by the
GTK+ main loop. Because FALSE is the default return value, you must connect a
signal handler which returns TRUE to prevent users from destroying GtkWindow
widgets.
GDK_DESTROY means the window has been destroyed. Widgets normally destroy their own windows when they are unrealized. If a widget is not destroyed
after a destroy event on its window, the GTK+ main loop destroys it.
GDK_MAP means the window has been shown on the screen. You should wait
for the first expose event before you draw to the window, however.
GDK_UNMAP means the window has been hidden; perhaps it was iconified, or
perhaps you called gtk_widget_hide().
Little-used Events
There are a few other event types that arent very useful, so this book does not cover
them in detail. This section gives a brief description of each one, for completeness.
You can safely skip this section.
Visibility Events
Visibility events occur when a window is obscured or unobscured. They are not very
useful, because other events already give you the information you need. In particular,
when a window is unobscured you receive expose events indicating which newlyvisible areas should be redrawn. Here is the event:
typedef struct _GdkEventVisibility GdkEventVisibility;
struct _GdkEventVisibility
{
GdkEventType type;
GdkWindow *window;
gint8 send_event;
GdkVisibilityState state;
};
state is an enumeration value indicating whether the window was obscured or unobscured.
Property Events
X associates properties with windows. These are basically key-value pairs used for
interclient communication; most commonly, they relay some information about a
toplevel window to the window manager. GTK+ provides a high-level interface for
all the important properties, so you should not need to deal with them directly. Property events are sent when a propertys value changes.
typedef struct _GdkEventProperty GdkEventProperty;
struct _GdkEventProperty
{
GdkEventType type;
GdkWindow *window;
gint8 send_event;
GdkAtom atom;
guint32 time;
guint state;
};
189
Selection Events
X has a simple cut-and-paste mechanism (typically, you select some text with button
1 and paste with button 2). The current contents of the "clipboard" are called the
selection. You only need to know about this if you are writing a widget like GtkText
or GtkEntry that allows you to cut and paste text. Selection events indicate that the
current selection has changed, and look like this:
typedef struct _GdkEventSelection GdkEventSelection;
struct _GdkEventSelection
{
GdkEventType type;
GdkWindow *window;
gint8 send_event;
GdkAtom selection;
GdkAtom target;
GdkAtom property;
guint32 requestor;
guint32 time;
};
Most GTK+ widgets deal with the selection using a higher-level interface, found in
gtk/gtkselection.h. If youre interested in writing selection-handling code, have a
look at this header.
Client Events
Client events are an arbitrary chunk of data sent from one application to another.
However, there are some conventional "messages" that can be sent, mostly defined
in the Inter-Client Communication Conventions Manual (ICCCM). The ICCCM is
free with the X Window System distribution from the Open Group. Client events
are mostly used for communication between applications and the window manager.
(The Xlib event being wrapped is called ClientMessage, so look for ClientMessage in
the ICCCM.) An important ClientMessage event is sent from the window manager
to applications, asking for windows to be deleted. However, GDK converts these
events to a GdkEventAny with type GDK_DELETE, so a GdkEventClient will not be
received. Some events involved in drag-and-drop are also ClientMessage events, but
GDK translates these to GdkEventDND, so a GdkEventClient will not be received
for them either. GdkEventClient will only be received if some other client sends your
application an unconventional message GDK and GTK+ are not prepared to understand. Most of the common messages are nicely wrapped in a high-level interface.
Just for reference, here is the event:
typedef struct _GdkEventClient GdkEventClient;
struct _GdkEventClient
{
GdkEventType type;
GdkWindow *window;
gint8 send_event;
GdkAtom message_type;
gushort data_format;
union {
char b[20];
short s[10];
long l[5];
190
} data;
};
The union at the end is used to hold the contents of the message. send_event is always
TRUE, since this event is always sent from one client to another and does not come
from the X server.
Proximity Events
Proximity events are generated when using GDKs wrapper for the XInput extension. The XInput extension is an add-on for standard X that allows you to use nonstandard devices such as graphics tablets. A proximity event indicates that the stylus
has moved in or out of contact with the tablet, or perhaps that the users finger has
moved in or out of contact with a touch screen. The X distribution comes with some
documentation for the XInput extension, and Owen Taylors gsumi application contains example GDK code.
typedef struct _GdkEventProximity GdkEventProximity;
struct _GdkEventProximity
{
GdkEventType type;
GdkWindow *window;
gint8 send_event;
guint32 time;
GdkInputSource source;
guint32 deviceid;
};
191
Pointer Location
You can query the pointers location with gdk_window_get_pointer() (Figure 10-7).
This function requests the X and Y coordinates of the pointer relative to the window
passed as its first argument. It also requests the currently active modifiers (including
modifier keys and buttons; this field is identical to the state field in several events,
such as button events). If NULL is passed for the x, y, or state arguments, that argument will be ignored.
#include <gdk/gdk.h>
GdkWindow* gdk_window_get_pointer(GdkWindow* window, gint* x, gint* y, GdkModifierMask* state);
grab window or confine_to window is hidden, another client has the grab already,
192
or any of the arguments are invalid. Regrettably few applications check this return
value, which is a bug (granted, a difficult-to-trigger one).
To ungrab the pointer, call gdk_pointer_ungrab(); the time argument is identical
to the one in gdk_pointer_grab(). You can find out if the pointer is grabbed using gdk_pointer_is_grabbed(). You must ungrab the pointer when youre finished
with it, because the user will be unable to use other applications while the pointer is
grabbed.
Note that the GDK-level concept of grabbing the pointer is distinct from the GTK+level grab concept. A GTK+ grab redirects certain events to a grabbing widget, creating a "modal" widget such as a dialog (see the section called Grabs in Chapter 3).
GTK+s grab only affects the current application; only events that occur on one of
the current applications widgets are redirected. The scope of a GDK grab is wider,
encompassing the entire X server, not just your application.
#include <gdk/gdk.h>
gint gdk_pointer_grab(GdkWindow* window, gint owner_events, GdkWindow* confine_to, GdkCursor* cursor, guint32 time);
void gdk_pointer_ungrab(guint32 time);
gint gdk_pointer_is_grabbed(void);
Notice that you can destroy the cursor as soon as you attach it to a window; GdkCursor is a client-side handle for a server-side resource, and X will keep the server-side
resource around as long as its in use.
If none of the cursors in the cursor font are appropriate, you can create a custom
cursor from a bitmap. Two bitmaps, actually: the source pixmap, and the mask. Since
these are bitmaps, every pixel is either on or off (0 or 1). If a pixel is 0 in the mask, that
pixel will be transparent. If a pixel is 1 in both pixmaps, it will be displayed in the fg
(foreground) color passed to gdk_cursor_new_from_pixmap(). If a pixel is 1 in the
193
mask but 0 in the source pixmap, it will be displayed in the bg (background) color.
The source and mask pixmaps must be the same size, and they must have a depth of
one.
The foreground and background colors should be contrasting, so the cursor will be
visible against any background. Most cursors are drawn in the foreground color
and outlined in the background color. (To see this, move an X cursor over a dark
background; you will notice a white outline around its edges.) To achieve this, mask
should be slightly larger than source, but the same shape.
The final two arguments to gdk_cursor_new_from_pixmap() are the coordinates of
the cursors hot spot. This is the point drawn at the mouse pointers locationthe tip
of an arrow cursor, or the center of a crosshair cursor. gdk_cursor_new_from_pixmap()
will fail if the hot spot is not within the bitmap.
#include <gdk/gdk.h>
GdkCursor* gdk_cursor_new(GdkCursorType cursor_type);
GdkCursor* gdk_cursor_new_from_pixmap(GdkPixmap* source, GdkPixmap* mask,
GdkColor* fg, GdkColor* bg, gint x, gint y);
void gdk_cursor_destroy(GdkCursor* cursor);
void gdk_window_set_cursor(GdkWindow* window, GdkCursor* cursor);
Fonts
An X font is (yet another) a server-side resource. In essence, a font is a collection
of bitmaps representing characters. The bitmaps in a single font will have a similar
size and style. GDK allows you to manipulate fonts with a client-side handle called
GdkFont.
To obtain a GdkFont, call gdk_font_load() (or use the font from a preexisting GtkStyle; more on this in the section called GtkStyle and Themes). Fonts are loaded by
name; font names are a fairly involved topic. Names follow a convention called the
"X Logical Font Description," or XLFD. The best way to get a feel for XLFD is to play
with the xfontsel program that comes with X. You can also get a list of font names
on your X server with the xlsfonts program. The standard X distribution includes
a 30-page XLFD manual, but the basics arent too complicated.
A font name is a string made up of hyphen-separated fields. Each field describes
some aspect of the font. For example:
-misc-fixed-medium-r-normal-0-0-75-75-c-0-iso8859-1
or
-adobe-new century schoolbook-bold-i-normal-11-80-100-100-p-66-iso88591
194
Foundry: the vendor who created the font, such as Adobe or Sony. misc is used for
some generic fonts that come with X.
Set Width: the "proportionate width" of the font; possible values include normal,
condensed, semicondensed, etc.
"Add Style": any additional information about the font can go in this field; it is
used to distinguish two fonts that otherwise have the same name. There are no
constraints on the string.
Points: the point size of the font, in tenths of a point. A point is 1/72 of an inch;
the relationship of point size to pixel size is determined by the resolution (dots per
inch) the X server thinks the display has. Typically people do not configure their X
server to match their monitor, so the X servers idea of the current resolution may
be wildly inaccurate.
Horizontal Resolution: horizontal display resolution in dots per inch (dpi) the font
is designed for.
Average Width: the mean width of all characters in the font, in tenths of a pixel.
Character Set Registry: the organization or standard defining the character set.
Character Set Encoding: specifies the specific character set encoding. These last
two fields in combination specify the character set. For European languages iso88591 will almost always be used. This is the "Latin-1" character set, which is an 8-bit
encoding including ASCII as a subset.
It is not necessary to specify all 14 fields when requesting a font. "Wild cards" are
allowed: * matches any number of characters, and ? matches a single character. For
example, a 160 point Bold Roman Helvetica font can be requested like this:
-*-helvetica-bold-r-*-*-*-160-*-*-*-*-*-*
When you pass a font name to gdk_font_load(), you should consider it a default
choice only. Users in other countries will certainly want to use a font appropriate to
their language; US and European users might want to customize fonts too. Also, there
are no fonts guaranteed to exist on all servers. Thus you should provide a way to
customize any fonts you use. The easiest way is to use fonts from a widgets GtkStyle
(again, see the section called GtkStyle and Themes).
gdk_font_load() returns NULL if it fails to find a font matching the supplied name.
When you are done with a font, you should release it by calling gdk_font_unref().
195
italic font, which is unlikely to be what you want. The Xlib Programming Manual suggests that you always specify the font size in points, so that users with different monitors will get the right effect; however, X servers do not reliably know the display
resolution, so this is more theory than reality. Perhaps its better to specify pixels, because you do know the pixel size of other elements of your display. Neither is perfect;
be sure you make your applications fonts configurable.
#include <gdk/gdk.h>
GdkFont* gdk_font_load(const gchar* font_name);
void gdk_font_unref(GdkFont* font);
Font Metrics
To use a font, you typically need detailed information about its metrics. Font metrics are used to position characters with respect to one another, and to determine the
size of strings rendered in the font. The most fundamental metrics are the ascent and
descent of the font. Text is placed on a baseline; the baseline is like a rule on a sheet
of notebook paper. The bottom of each character touches the baseline. Some characters (such as lowercase "p" and "y") extend below the baseline. A fonts descent is
the maximum distance below the baseline reached by its characters. Its ascent is the
maximum distance above the baseline. The height of a font is the sum of the ascent
and the descent. When rendering multiple lines of text, you should leave at least the
fonts height between each baseline.
Ascent and descent are available as members of the GdkFont struct:
typedef struct _GdkFont GdkFont;
struct _GdkFont
{
GdkFontType type;
gint ascent;
gint descent;
};
The type field distinguishes fonts from fontsets; fontsets are used to display nonEuropean languages.
Individual characters in a font have their own ascent and descent; a characters ascent and descent will always be less than or equal to the fonts ascent and descent.
GDK can calculate the sum of the maximum ascent and descent for a particular
string, rather than an entire font; this height will be less than or equal to the fonts
height. The relevant functions are gdk_string_height(), gdk_text_height(), and
gdk_char_height(). gdk_text_height() is different from gdk_string_height()
because it accepts the length of the string as an argument; gdk_string_height()
calls strlen() for you. Thus gdk_text_height() is preferred if you already know a
strings length.
In addition to its vertical metrics, each character in a font has three metrics describing
its horizontal dimensions. The width of a character is the distance from the left origin
of the character to the start of the next character. Note: the width is not the distance to
the furthest-right pixel in a character; in some fonts, especially italic fonts, characters
196
may lean over past the start of the next character. The left-side-bearing or lbearing is the
distance from the left origin to the leftmost pixel in the character; the right-side-bearing
or rbearing is the distance from the origin to the rightmost pixel in the character. Thus
the rbearing can be larger than the width, in the case of italic fonts that lean over past
the start of the next character.
GDK functions that return a character or string width return the width of the character, or the sum of the character widths in the string. If the rbearing of the rightmost
character is greater than its width, a string may require more space than gdk_string_width(),
gdk_text_width(), or gdk_char_width() will return. Like the height-measurement
functions, the _string_ variant computes the length of the string for you, and the
_text_ variant accepts a precomputed length as an argument.
The functions ending in _measure are more often what you want. For a string with
N characters, these return the sum of the widths of the first N-1 characters, plus the
rbearing of the final character. That is, they take into account the fact that rbearing
may be greater than width. If youre trying to decide how much space to leave for rendering a string, you probably want the gdk_string_measure(), gdk_text_measure(),
or gdk_char_measure() functions. Sometimes you dont want to consider the rbearing, however; for example, if youre centering a string, it may look nicer to use the
width (because a small italic flourish extending past the width wont "fill" the space
and the string will look slightly left of center).
gdk_text_extents() and gdk_string_extents() return all the metrics for a string,
including both bearings, the width, ascent, and descent. The returned left-side-bearing
is the leftmost pixel in the string; the right-side-bearing is the rightmost pixel as returned by gdk_text_measure(). The width is the sum of character widths, as returned by gdk_text_width().
Figure 10-11 depicts the various font metrics. Figure 10-12 summarizes the API for
querying font metrics. All font metrics are computed on the client side, so these functions are not expensive compared to most of the drawing API.
#include <gdk/gdk.h>
gint
gint
gint
gint
gint
gint
gint
gint
gint
void
ing,
void
197
gint* lbearing, gint* rbearing, gint* width, gint* ascent, gint* descent);
Graphics Contexts
A graphics context, or GC, is simply a set of parameters to be used when drawing (such
as color, clip mask, font, and so on). It is a server-side resource, just as pixmaps and
windows are. GCs reduce the number of arguments to the GDK drawing functions,
and also reduce the number of parameters passed from client to server with each
drawing request.
A graphics context can be created with a GdkGCValues struct, analagous to GdkWindowAttr; the struct contains all the interesting features of a graphics context,
and you pass gdk_gc_new_with_values() flags indicating which fields are valid.
The other fields retain their default value. You can also create an all-default GC with
gdk_gc_new() (this is usually easier). Functions are provided to change GC settings
after the GC is created as wellbut remember that each change requires a message
to the X server. These functions are summarized in Figure 10-16. The attributes of
a GC, and the flags used as the final argument to gdk_gc_new_with_values(), are
summarized in Table 10-6.
All GCs are not interchangeable; they are tied to a particular depth and visual. The
GCs depth and visual must match the depth and visual of the drawable you are
drawing to. A GCs depth and visual are taken from the GdkWindow* argument to
gdk_gc_new(), so the easiest way to handle this issue is to create the GC with the
window you plan to draw on.
GdkGCValues is a nice summary of a GCs attributes:
typedef struct _GdkGCValues GdkGCValues;
struct _GdkGCValues
{
GdkColor
foreground;
GdkColor
background;
GdkFont
*font;
GdkFunction
function;
GdkFill
fill;
GdkPixmap
*tile;
GdkPixmap
*stipple;
GdkPixmap
*clip_mask;
GdkSubwindowMode subwindow_mode;
gint
ts_x_origin;
gint
ts_y_origin;
gint
clip_x_origin;
gint
clip_y_origin;
gint
graphics_exposures;
gint
line_width;
GdkLineStyle
line_style;
GdkCapStyle
cap_style;
GdkJoinStyle
join_style;
};
198
The foreground color is the "pen color" used to draw lines, circles, and other shapes.
The purpose of the background color depends on the particular drawing operation.
These colors must be allocated in the current colormap with gdk_color_alloc().
The font field is unused: in Xlib, it specifies the font to use when drawing text. In
GDK, it used to have the same purpose; but now the GDK routines for drawing text
all require a GdkFont* argument instead. An Xlib graphics context can only store
plain fonts, but a GdkFont can also represent a fontset (used to render some foreign
languages). GDK should probably store a font field in its GdkGC instead of requiring
a font argument to the text-drawing functions, but it doesnt.
The function field specifies how each pixel being drawn is combined with the pixel
that already exists in the drawable. There are many possible values, but only two are
ever used:
GDK_COPY is the default. It ignores the existing pixel (just writes the new pixel
over it).
GDK_XOR combines the old and new pixels in an invertable way. That is, if you
perform exactly the same GDK_XOR operation twice, the first draw is undone by
the second. GDK_XOR is often used for "rubberbanding," since it makes it easy to
restore the original contents of the drawable once rubberbanding is complete.
The fill field determines how the tile and stipple fields are used. A tile is a pixmap
with the same depth as the destination drawable; it is copied over and over into the
destination drawablethe origin of the first tile is (ts_x_origin, ts_y_origin). A stipple is a bitmap (pixmap with depth 1); stipples are also tiled starting at (ts_x_origin,
ts_y_origin). Possible fill values are:
GDK_SOLID means to ignore the tile and stipple. Shapes are drawn in the foreground and background colors.
GDK_TILED means that shapes are drawn with the tile, instead of the foreground
and background colors. Imagine a tiled surface underneath your drawable; drawing in GDK_TILED mode will scratch away the contents of the drawable, revealing
the tiled surface underneath.
GDK_OPAQUE_STIPPLED draws bits set in the stipple with the foreground color,
and bits not set in the stipple with the background color.
Some X servers do not implement the more obscure function and fill modes very
efficiently. Dont be surprised if using them noticeably slows down drawing.
The optional clip_mask is a bitmap; only bits set in this bitmap will be drawn. The
mapping from the clip mask to the drawable is determined by clip_x_origin and
clip_y_origin; these define the drawable coordinates corresponding to (0,0) in the clip
mask. It is also possible to set a clip rectangle (the most common and useful form of
clipping) or a clip region (a region is an arbitrary area on the screen, typically a polygon or list of rectangles). To set a clip rectangle, use gdk_gc_set_clip_rectangle():
GdkRectangle clip_rect;
clip_rect.x = 10;
clip_rect.y = 20;
clip_rect.width = 200;
clip_rect.height = 100;
gdk_gc_set_clip_rectangle(gc, &clip_rect);
To turn off clipping, set the clip rectangle, clip region, or clip mask to NULL.
199
GDK_LINE_ON_OFF_DASH draws a dashed line with the foreground color, leaving the "off" parts of the dash blank.
dash_list is an array of dash lengths. Even-indexed lengths are "on" dashes; these
are drawn in the foreground color. Odd-indexed lengths are "off" dashes; they are
not drawn or drawn in the background color, depending on line_style. 0 is not a
permitted value; all lengths must be positive.
dash_offset is the index of the first pixel to use in the dash list. That is, if the dash
list specifies 5 pixels "on" and 5 "off", and the offset is 3, the line will begin in the
middle of the "on" dash.
You might set a whimsical dash pattern this way, for example:
gchar dash_list[] = { 5, 5, 3, 3, 1, 1, 3, 3 };
gdk_gc_set_dashes(gc, 0, dash_list, sizeof(dash_list));
200
GDK_CAP_BUTT is the default; it means that lines have square ends (as you might
expect).
201
GDK_CAP_NOT_LAST specifies that the last pixel is skipped for one-pixel lines.
It is otherwise the same as GDK_CAP_BUTT.
GDK_CAP_ROUND draws a small arc on the end of the line, extending beyond
the lines endpoint. The center of the arc is on the endpoint, and the radius of the
arc is one-half the width of the line. For one-pixel lines, it has no effect (since there
is no way to draw a one-pixel-wide arc).
GDK_CAP_PROJECTING extends the line past its endpoint by one-half its width.
It has no effect on one-pixel lines.
The join_style parameter affects how lines are connected to one another, when drawing a polygon or drawing multiple lines in one function call. If you think of lines as
long, thin rectangles, it is clear that they do not connect smoothly; there is a "notch"
where the two endpoints come together. The three join styles fill in this notch:
GDK_JOIN_MITER is the default; it draws a sharp angle where the lines intersect.
GDK_JOIN_BEVEL creates a flat corner, filling the notch with the smallest possible
shape.
#include <gdk/gdk.h>
GdkGC* gdk_gc_new(GdkWindow* window);
GdkGC* gdk_gc_new_with_values(GdkWindow* window, GdkGCValues* values, GdkGCValuesMask values_mask);
void gdk_gc_set_dashes(GdkGC* gc, gint dash_offset, gchar dash_list, gint
n);
void gdk_gc_unref(GdkGC* gc);
Modifying
GdkGCValuesMask Function
Default Value
GdkColor
foreground
black
GDK_GC_FOREGROUND
gdk_gc_set_foreground()
GdkColor
background
white
GDK_GC_BACKGROUND
gdk_gc_set_background()
GdkFont *font
GdkFunction
function
GdkFill fill
GDK_GC_FONT
gdk_gc_set_font
depends on X
server
GDK_COPY
GDK_GC_FUNCTION
gdk_gc_set_function()
GDK_GC_FILL
GDK_SOLID
gdk_gc_set_fill()
GdkPixmap *tile
GDK_GC_TILE
effectively none)
202
Attribute
Modifying
GdkGCValuesMask Function
Default Value
all-bits-on bitmap
gdk_gc_set_stipple()
(i.e. effectively none)
GdkPixmap
*clip_mask
GdkSubwindowMode
subwindow_mode
gint ts_x_origin
none
GDK_GC_CLIP_MASK
gdk_gc_set_clip_mask()
GDK_GC_SUBWINDOW
gdk_gc_set_subwindow()
GDK_CLIP_BY_CHILDREN
0
GDK_GC_TS_X_ORIGIN
gdk_gc_set_ts_origin()
gint ts_y_origin
0
GDK_GC_TS_Y_ORIGIN
gdk_gc_set_ts_origin()
gint clip_x_origin
0
GDK_GC_CLIP_X_ORIGIN
gdk_gc_set_clip_origin()
gint clip_y_origin
0
GDK_GC_CLIP_Y_ORIGIN
gdk_gc_set_clip_origin()
gint
TRUE
graphics_exposures GDK_GC_EXPOSURES
gdk_gc_set_exposures()
gint line_width
0
GDK_GC_LINE_WIDTH
gdk_gc_set_line_attributes()
GdkLineStyle
line_style
GDK_LINE_SOLID
GDK_GC_LINE_STYLE
gdk_gc_set_line_attributes()
GdkCapStyle
cap_style
GDK_CAP_BUTT
GDK_GC_CAP_STYLE
gdk_gc_set_line_attributes()
GdkJoinStyle
join_style
GDK_JOIN_MITER
GDK_GC_JOIN_STYLE
gdk_gc_set_line_attributes()
gchar dash_list[]
none
{4, 4}
gdk_gc_set_dashes()
gint dash_offset
none
0
gdk_gc_set_dashes()
Drawing
Once you understand drawables, colors, visuals, graphics contexts, and fonts, actually drawing is very simple. This section is a quick summary of the GDK drawing
routines. Remember that drawing is a server-side operation; for example, if you ask
to draw a line, Xlib will send the lines endpoints to the server, and the server will
do the actual drawing using the specified GC (the GC is also a server-side resource).
Often this is an important performance consideration.
203
Points
You can draw a single point with gdk_draw_point(), or multiple points with gdk_draw_points()
(Figure 10-17). The point is drawn in the current foreground color. Multiple points are
given as an array. A GdkPoint looks like this:
typedef struct _GdkPoint GdkPoint;
struct _GdkPoint
{
gint16 x;
gint16 y;
};
Remember that X coordinates start in the top left corner, are relative to the drawable,
and may not overflow a signed sixteen-bit integer.
#include <gdk/gdk.h>
void gdk_draw_point(GdkDrawable* drawable, GdkGC* gc, gint x, gint y);
void gdk_draw_points(GdkDrawable* drawable, GdkGC* gc, GdkPoint* points,
gint npoints);
Lines
To draw a single line, pass its endpoints as arguments to gdk_draw_line() (Figure
10-18). To draw connected lines, you pass a list of points to gdk_draw_lines(); GDK
will "connect the dots." To draw multiple lines that arent necessarily connected, pass
a list of segments to gdk_draw_segments(); a GdkSegment is:
typedef struct _GdkSegment GdkSegment;
struct _GdkSegment
{
gint16 x1;
gint16 y1;
gint16 x2;
gint16 y2;
};
If lines or segments drawn in the same request meet at their endpoints, they are joined
with the join style from the GC.
#include <gdk/gdk.h>
204
void gdk_draw_line(GdkDrawable* drawable, GdkGC* gc, gint x1, gint y1, gint
x2, gint y2);
void gdk_draw_lines(GdkDrawable* drawable, GdkGC* gc, GdkPoint* points,
gint npoints);
void gdk_draw_segments(GdkDrawable* drawable, GdkGC* gc, GdkSegment* segments, gint nsegments);
Rectangles
Rectangles are drawn with gdk_draw_rectangle() (Figure 10-19). The filled argument indicates whether to fill the rectangle; TRUE means to fill it.
#include <gdk/gdk.h>
void gdk_draw_rectangle(GdkDrawable* drawable, GdkGC* gc, gint filled, gint
x, gint y, gint width, gint height);
Arcs
gdk_draw_arc() draws an ellipse or a portion of one. (Figure 10-20). The arc can be
filled or unfilled; the third argument to the function toggles fill. The fourth through
seventh arguments describe a rectangle; the ellipse is inscribed in this rectangle. angle1 is the angle at which to start drawing; it is relative to the 3 oclock position (that
is, 0 radians). angle2 is the distance to travel around the arc; if positive, travel is counterclockwise, otherwise travel is clockwise. Both angle1 and angle2 are specified in
sixty-fourths of a degree; so, 360 degrees is given as 360*64. This allows more precise specification of the arcs size and shape, without using floating point numbers.
angle2 should not exceed 360 degrees, since it is nonsensical to move more than 360
degrees around the ellipse.
To draw a circle, draw from 0 to 360*64 inside a square:
gdk_draw_arc(drawable, gc, TRUE,
0, 0,
50, 50,
0, 360*64);
To draw half an ellipse, change the aspect ratio and halve the span of the arc:
gdk_draw_arc(drawable, gc, TRUE,
0, 0,
100, 50,
0, 180*64);
205
Many X servers draw the edges of filled arcs in an aesthetically unpleasing way; in
particular, very small circles may not look very circular. You can work around this by
also drawing the circles outline.
#include <gdk/gdk.h>
void gdk_draw_arc(GdkDrawable* drawable, GdkGC* gc, gint filled, gint x,
gint y, gint width, gint height, gint angle1, gint angle2);
Polygons
gdk_draw_polygon() draws a filled or unfilled polygon (Figure 10-21). Notice that
gdk_draw_lines() can also be used to draw an unfilled polygon (there is no reason
to prefer one or the other). The arguments to gdk_draw_polygon() are the same as
those to gdk_draw_lines(). The polygon does not have to be convex. It may also
#include <gdk/gdk.h>
void gdk_draw_polygon(GdkDrawable* drawable, GdkGC* gc, gint filled, GdkPoint* points, gint npoints);
Text
There are two functions to draw strings; as an optimization, gdk_draw_text() takes
the length of the string to draw as an argument. gdk_draw_string() uses strlen()
to compute the string length for you. Otherwise the two are identical. The x and y
coordinates specify the location of the left side of the texts baseline. See the section
called Fonts for more information on fonts and font metrics. Text is drawn in the
foreground color.
There is no way to draw scaled or rotated text with GDK. GnomeCanvasText offers
a slow and low-quality way to render scaled and rotated text (see the section called
Text Item in Chapter 12). If you need high-quality scaling and rotating, you will need
to use additional libraries, such as t1lib for Type 1 fonts or FreeType for True Type
fonts. Another possibility is the Display Postscript extension to X (XDPS); the GNU
Project is working on a free implementation of XDPS. The Gnome project also has a
text solution in development, as part of the gnome-print library.
#include <gdk/gdk.h>
206
Pixmaps
gdk_draw_pixmap() copies a region from a pixmap to another drawable (pixmap
or window). The source and destination drawables must have the same depth and
visual. If you pass -1 for the width or height, the full size of the source pixmap
is substituted. The source can actually be any drawable, including a window, but
gdk_window_copy_area() will make your code clearer if the source is a window.
Figure 10-23 shows gdk_draw_pixmap().
#include <gdk/gdk.h>
void gdk_draw_pixmap(GdkDrawable* drawable, GdkGC* gc, GdkDrawable* src,
gint xsrc, gint ysrc, gint xdest, gint ydest, gint width, gint height);
RGB Buffers
GDKs GdkRGB module allows you to copy a client-side buffer of image data to a
drawable. If you need to manipulate images extensively, or copy image data to the
server, this is the correct way to do it. You cant directly manipulate a GdkPixmap
because a pixmap is a server-side object. Copying image data to the server with
gdk_draw_point() would be unbelievably slow, since each point would require a
server request (probably more than one, since you will need to change the GC for
each point).
Internally, GdkRGB uses an object called GdkImage to rapidly copy image data to
the server in a single request. This is still somewhat slowsizeable data does have
to be copiedbut GdkRGB is highly tuned and uses shared memory if the client
and server happen to be on the same machine. So its the fastest way to perform this
task, given the X architecture. It will also handle some tricky issues for you (such as
adapting to the colormaps and visuals available on a given X server).
The GdkRGB functions are in a separate header, gdk/gdkrgb.h. Before using any
GdkRGB functions, you must initialize the module with gdk_rgb_init() (Figure
10-24); this sets up the visual and colormap GdkRGB will use, and some internal
data structures.
The drawable you intend to copy the RGB buffer to must use GdkRGBs visual and
colormap. If the drawable is a part of a widget, the easiest way to ensure this is to
push the GdkRGB visual and colormap when you create the widget:
GtkWidget* widget;
gtk_widget_push_visual(gdk_rgb_get_visual());
207
gtk_widget_push_colormap(gdk_rgb_get_cmap());
widget = gtk_whatever_new();
gtk_widget_pop_visual();
gtk_widget_pop_colormap();
The current version of GTK+ will be better-behaved if you do this when creating the
toplevel window containing the drawable, instead of when creating the drawable
itself. However, in principle you can do it for only the drawable.
GdkRGB understands several kinds of image data, including 24- and 32-bit RGB data,
8-bit grayscale, and 8-bit indexes into an array of RGB values (a client-side GdkRgbCmap). This section describes only the simplest, 24-bit RGB data; this kind of buffer
is rendered with gdk_draw_rgb_image(). There are separate functions to render the
other buffer types, but all of them work in essentially the same way.
A 24-bit RGB buffer is a one-dimensional array of bytes; every byte triplet makes up
a pixel (byte 0 is red, byte 1 is green, byte 2 is blue). Three numbers describe the size
of the array and the location of bytes within it:
The width is the number of pixels (byte triplets) per row of the image.
The rowstride is the number of bytes between rows. That is, for a buffer with rowstride r, if row n starts at array index i row n+1 starts at array index i+r. The rowstride is not necessarily three times the buffers width; GdkRGB is faster if both
the source pointer and the rowstride are aligned to a 4-byte boundary. Specifying
a rowstride allows you to use padding to achieve this.
GDK_RGB_DITHER_NONE specifies that no dithering will be done. Its appropriate for text or line drawings with few colors, but inappropriate for photographic
images.
GDK_RGB_DITHER_NORMAL specifies dithering on 8-bit displays, but not 16bit displays. This is usually the best quality/performance tradeoff.
#include <gdk/gdkrgb.h>
208
void gdk_rgb_init(void);
GdkColormap* gdk_rgb_get_cmap(void);
GdkVisual* gdk_rgb_get_visual(void);
void gdk_draw_rgb_image(GdkDrawable* drawable, GdkGC* gc, gint x, gint y,
gint width, gint height, GdkRGBDither dither, guchar* rgb_buf, gint rowstride);
209
fg[5];
bg[5];
light[5];
dark[5];
mid[5];
text[5];
base[5];
GdkColor black;
GdkColor white;
GdkFont *font;
GdkGC
GdkGC
GdkGC
GdkGC
GdkGC
GdkGC
GdkGC
GdkGC
GdkGC
*fg_gc[5];
*bg_gc[5];
*light_gc[5];
*dark_gc[5];
*mid_gc[5];
*text_gc[5];
*base_gc[5];
*black_gc;
*white_gc;
GdkPixmap *bg_pixmap[5];
/* private */
gint ref_count;
gint attach_count;
gint depth;
GdkColormap *colormap;
GtkThemeEngine *engine;
gpointer
engine_data;
GtkRcStyle
*rc_style;
GSList
*styles;
};
The private fields should be ignored. The public fields contain GDK resources for
widget rendering. The first group of fields contains arrays of colors; these arrays
are indexed by the widget state enumeration (GTK_STATE_ACTIVE, etc.). A widget
might use widget->style->fg[GTK_STATE_NORMAL] to render text, for example.
Each widget has an associated style, stored in the style field of GtkWidget.
Widgets should use the font stored in their associated GtkStyle; they should use the
styles graphics contexts when drawing in the styles colors.
GtkStyle also contains a virtual table, GtkStyleClass, which can be implemented by
a dynamically-loaded theme engine. The virtual table is quite large, so it isnt reproduced here. Have a look at gtk/gtkstyle.h.
210
gtk/gtkstyle.h contains drawing functions that use a styles virtual table to draw
various GUI elements. There are two variants of each drawing function. One variant,
prefixed with gtk_draw_, renders to any drawable; the other variant, prefixed with
gtk_paint_, renders part of a widget. For example, gtk_draw_shadow() looks like
this:
void gtk_draw_shadow
(GtkStyle
*style,
GdkWindow
*window,
GtkStateType
state_type,
GtkShadowType shadow_type,
gint
x,
gint
y,
gint
width,
gint
height);
(GtkStyle
*style,
GdkWindow
*window,
GtkStateType state_type,
GtkShadowType shadow_type,
GdkRectangle *area,
GtkWidget
*widget,
gchar
*detail,
gint
x,
gint
y,
gint
width,
gint
height);
Here the area argument is NULL, specifying that no clipping should be used.
Because there are a couple dozen functions in GtkStyleClass, and there are numerous
examples in the GTK+ source code, this book wont describe them in detail. When
writing your own widgets, simply locate a GTK+ widget that draws a similar graphical element, and use the same gtk_paint_ function it uses.
211
Overview
This section gives a brief overview, including the different kinds of widget you might
encounter, and the general functionality a GtkWidget is required to have.
Kinds of Widget
The term "widget" is really very broad, since it encompasses any object that implements the GtkWidget interface. There are many ways to classify widgets:
Containers are widgets that store other widgets inside, such as the boxes and tables
described in Chapter 3. As Chapter 3 discussed, containers can be subdivided into
those that add functionality to a single child (GtkButton, GtkFrame, GtkEventBox,
etc.), and those that manage layout for multiple children (GtkBox, GtkTable, etc.).
Container widgets are harder to implement than "plain" widgets because the GtkContainer interface must be implemented in addition to the GtkWidget interface.
Composite widgets are containers that already contain a useful collection of child
widgets in a nice package. For example, the GtkFileSelection widget is a subclass
of GtkWindow that already contains a list widget to show files, dialog buttons,
and so on. Widgets like this are easy to write, and are a convenient way to code
applications. You could write a "MainWindow" widget for your main application
window, for example, and then create a new instance of the widget whenever the
user opens a new document. GnomeApp and GnomeDialog are two important composite widgets in Gnome.
Non-container widgets can be actual controls (buttons, scroll bars, etc.), information displays (GtkLabel), or decorative flourishes (GtkSeparator, for example).
As Chapter 3 briefly mentioned, there are two major ways to implement widgets:
most widgets (those that need to receive events or draw their own background)
have an associated GdkWindow; "no window" widgets draw on their parent container. Widgets without windows are implemented slightly differently. All con-
212
tainers have a GdkWindow (since widgets without one might need to draw on it,
among other reasons).
This chapter presents several widgets as examples, including a GtkEv widget written
especially for this book, GtkVBox from GTK+, and GnomeAppBar from libgnomeui.
Creation and destruction; this means the usual GtkObject boilerplate (instance
and class initializers, shutdown, destroy and finalize methods). See Chapter 9, especially the section called Object and Class Structures in Chapter 9 and the section
called Object Finalization in Chapter 9. Also see the section called Widget Life Cycle
in Chapter 3.
Drawing; widgets must be able to draw themselves on the screen. For container
widgets, the widget itself may be invisible but it must ensure child widgets are
drawn.
213
GtkStyle *style;
GtkRequisition requisition;
GtkAllocation allocation;
GdkWindow *window;
GtkWidget *parent;
};
The private_flags, state, and saved_state fields should all be accessed with macros,
if at all. Some of these macros will come up as we discuss widget implementations.
The state field stores the widgets state as described in the section called Widget States
in Chapter 3. saved_state is used to save the widgets previous state when the current state is GTK_STATE_INSENSITIVE; when the widget is re-sensitized, its original
state is restored. As the section called Widget States in Chapter 3 explains, the current
state can be accessed with the GTK_WIDGET_STATE() macro.
The name of a widget is used in a gtkrc file to group widgets together for customization purposes. By default, the name of a widget is the type name registered
with the object system (in GTK+, this type name is always the name of the instance
struct, such as "GtkLabel"). Particular widgets can be given a different name with
gtk_widget_set_name(); for example, if you want a particular label to appear in
a different font, you can give it a name like "FunkyFontLabel" and then specify a
different font for that name in a gtkrc shipped with your application.
The requisition and allocation fields store the last requested and allocated size of the
widget, respectively. the section called Size Negotiation will have more to say about
this.
The window field stores the widgets GdkWindow, or the widgets parents GdkWindow if the widget has none. The parent field is a pointer to the widgets parent container; it will be NULL if the widget is not inside a container.
214
(GtkWidget
(GtkWidget
(GtkWidget
(GtkWidget
(GtkWidget
(GtkWidget
(GtkWidget
*widget);
*widget);
*widget);
*widget);
*widget);
*widget);
*widget);
void (* unrealize)
void (* draw)
void (* draw_focus)
void (* draw_default)
void (* size_request)
void (* size_allocate)
void (* state_changed)
void (* parent_set)
void (* style_set)
/* Accelerators */
gint (* add_accelerator)
void (* remove_accelerator)
/* Explicit focus */
void (* grab_focus)
/* Events */
gint (* event)
gint (* button_press_event)
gint (* button_release_event)
gint (* motion_notify_event)
gint (* delete_event)
gint (* destroy_event)
gint (* expose_event)
gint (* key_press_event)
gint (* key_release_event)
gint (* enter_notify_event)
gint (* leave_notify_event)
gint (* configure_event)
gint (* focus_in_event)
gint (* focus_out_event)
gint (* map_event)
gint (* unmap_event)
(GtkWidget
(GtkWidget
GdkRectangle
(GtkWidget
(GtkWidget
(GtkWidget
GtkRequisition
(GtkWidget
GtkAllocation
(GtkWidget
GtkStateType
(GtkWidget
GtkWidget
(GtkWidget
GtkStyle
*widget);
*widget,
*area);
*widget);
*widget);
*widget,
*requisition);
*widget,
*allocation);
*widget,
previous_state);
*widget,
*previous_parent);
*widget,
*previous_style);
(GtkWidget
*widget,
guint
accel_signal_id,
GtkAccelGroup *accel_group,
guint
accel_key,
GdkModifierType accel_mods,
GtkAccelFlags
accel_flags);
(GtkWidget
*widget,
GtkAccelGroup *accel_group,
guint
accel_key,
GdkModifierType accel_mods);
(GtkWidget
*widget);
(GtkWidget
GdkEvent
(GtkWidget
GdkEventButton
(GtkWidget
GdkEventButton
(GtkWidget
GdkEventMotion
(GtkWidget
GdkEventAny
(GtkWidget
GdkEventAny
(GtkWidget
GdkEventExpose
(GtkWidget
GdkEventKey
(GtkWidget
GdkEventKey
(GtkWidget
GdkEventCrossing
(GtkWidget
GdkEventCrossing
(GtkWidget
GdkEventConfigure
(GtkWidget
GdkEventFocus
(GtkWidget
GdkEventFocus
(GtkWidget
GdkEventAny
(GtkWidget
*widget,
*event);
*widget,
*event);
*widget,
*event);
*widget,
*event);
*widget,
*event);
*widget,
*event);
*widget,
*event);
*widget,
*event);
*widget,
*event);
*widget,
*event);
*widget,
*event);
*widget,
*event);
*widget,
*event);
*widget,
*event);
*widget,
*event);
*widget,
215
GdkEventAny
*event);
(GtkWidget
*widget,
GdkEventProperty
*event);
gint (* selection_clear_event)
(GtkWidget
*widget,
GdkEventSelection *event);
gint (* selection_request_event) (GtkWidget
*widget,
GdkEventSelection *event);
gint (* selection_notify_event) (GtkWidget
*widget,
GdkEventSelection *event);
gint (* proximity_in_event)
(GtkWidget
*widget,
GdkEventProximity *event);
gint (* proximity_out_event)
(GtkWidget
*widget,
GdkEventProximity *event);
gint (* visibility_notify_event) (GtkWidget
*widget,
GdkEventVisibility *event);
gint (* client_event)
(GtkWidget
*widget,
GdkEventClient
*event);
gint (* no_expose_event)
(GtkWidget
*widget,
GdkEventAny
*event);
gint (* property_notify_event)
/* Selection */
void (* selection_get)
void (* selection_received)
void (* drag_data_delete)
gboolean (* drag_motion)
gboolean (* drag_drop)
void (* drag_data_received)
216
(GtkWidget
GtkSelectionData
guint
guint
(GtkWidget
GtkSelectionData
guint
*widget,
*selection_data,
info,
time);
*widget,
*selection_data,
time);
(GtkWidget
GdkDragContext
(GtkWidget
GdkDragContext
(GtkWidget
GdkDragContext
GtkSelectionData
guint
guint
(GtkWidget
GdkDragContext
*widget,
*context);
*widget,
*context);
*widget,
*context,
*selection_data,
info,
time);
*widget,
*context);
(GtkWidget
GdkDragContext
guint
(GtkWidget
GdkDragContext
gint
gint
guint
(GtkWidget
GdkDragContext
gint
gint
guint
(GtkWidget
GdkDragContext
gint
gint
GtkSelectionData
guint
guint
*widget,
*context,
time);
*widget,
*context,
x,
y,
time);
*widget,
*context,
x,
y,
time);
*widget,
*context,
x,
y,
*selection_data,
info,
time);
/* Action signals */
void (* debug_msg)
(GtkWidget
const gchar
*widget,
*string);
Most of the functions in GtkWidgetClass are registered as default handlers for signals. The exceptions are show_all and hide_all, which are class functions only. Of
course, GtkWidgetClass inherits the five class functions and single signal ("destroy")
from GtkObjectClass. This chapter will describe the important methods in more detail; also, the section called Events in Chapter 10 is important for understanding the
event methods. the section called GtkWidget In Detail describes the default implementation of each method in some detail.
Overridable Signals
You may notice that GtkWidgetClass contains two signal identifiers in addition to
function pointers. These are 0 by default; otherwise, they indicate the signal to emit
to "activate" the widget, or to set its scroll adjustments.
The activate_signal is emitted when the user presses the space bar or Enter key while
the widget is focused; for buttons, it will be the "clicked" signal, for menu items, the
"activate" signal.
The set_scroll_adjustments_signal is used by GtkScrolledWindow to set the scroll
adjustments used by the widget. GtkLayout, GtkCList, and others have a signal to
set the scroll adjustments.
These two hacks are necessary because GTK+ 1.2 does not support interfaces or multiple inheritance. (A future version of GTK+ may support interfaces similar in spirit to
Javas interfaces.) Ideally, there would be "GtkActivatable" and "GtkScrollable" base
classes or interfaces, and all widgets supporting these actions would derive from
them. Including the two signal IDs in GtkWidgetClass is a short-term workaround.
217
Figure 11-1. The GtkEv widget. Events are reported for the white subwindow.
Overview
GtkEv uses two GdkWindows; the larger one, GtkEvs widget->window, has a gray
background and is used to render text describing each event. The smaller one is a
child of the primary window, and is the window the widget reports events for.
GtkEv;
GtkEvClass;
struct _GtkEv
{
GtkWidget widget;
GdkWindow*
event_window;
GdkRectangle
event_window_rect;
GdkRectangle
description_rect;
GList*
GList*
gint
buffer;
buffer_end;
buffer_size;
};
struct _GtkEvClass
{
GtkWidgetClass parent_class;
218
};
As you can see, GtkEv has no class functions or signals of its own. Each instance
stores a pointer to the small event window in event_window. Two rectangles cache
the area covered by the event window, and the area covered by the event description
text. The widgets allocation is divided between these two areas. Finally, GtkEv stores
a list of string vectors describing events; it caches the end of the list and the length of
the list. As events are received, text describing them is pushed on to the front of the
buffer. When the list becomes too long to fit on the screen, GtkEv removes an event
from the back of the buffer each time it adds a new event to the front, keeping the
buffer size constant.
GtkObject Features
Like all GtkObjects, GtkEv provides for its creation and destruction.
Creation
GtkEvs init, class init, and constructor functions are pure boilerplate and should re-
219
=
=
=
=
NULL;
NULL;
NULL;
0;
ev->event_window_rect.x = ev->event_window_rect.y = 0;
ev->event_window_rect.width = ev->event_window_rect.height = 0;
ev->description_rect.x = ev->description_rect.y = 0;
ev->description_rect.width = ev->description_rect.height = 0;
}
GtkWidget*
gtk_ev_new (void)
{
GtkEv *ev;
ev = gtk_type_new (gtk_ev_get_type ());
return GTK_WIDGET (ev);
}
Destruction
GtkEv overrides only the destroy method from GtkObject, to clean up the event description buffer. The widgets windows will be destroyed in GtkWidgets shutdown
method, which unrealizes the widget. GtkWidgets finalize method cleans up some
GtkWidget resources and then chains to the GtkObject method which frees the in-
stance struct. (Refer to the section called Object Finalization in Chapter 9 for more
details on these methods.)
220
Because GtkEv has no object arguments, it does not need to implement get_arg or
set_arg methods.
Here is its destroy method implementation:
static void
gtk_ev_destroy
{
GtkEv* ev;
GList* tmp;
(GtkObject
*object)
g_return_if_fail(object != NULL);
g_return_if_fail(GTK_IS_EV(object));
ev = GTK_EV(object);
tmp = ev->buffer;
while (tmp != NULL)
{
g_strfreev((gchar**)tmp->data);
tmp = g_list_next(tmp);
}
g_list_free(ev->buffer);
ev->buffer = NULL;
ev->buffer_end = NULL;
ev->buffer_size = 0;
/* Chain up */
if (GTK_OBJECT_CLASS(parent_class)->destroy)
(* GTK_OBJECT_CLASS(parent_class)->destroy) (object);
}
The only detail worthy of note is that freed pointers are set to NULL, because a
destroyed object should remain "sane," unlike a finalized object. The GtkEv code
depends on the fact that destroyed widgets are always unrealized; otherwise, text
could be re-added to the buffer after destruction but before finalization, and a finalize method would be required.
Any widget with a GdkWindow that has GtkWidget as its immediate parent will
need to override the realize method; the default is only suitable for windowless widgets. GtkEv is no exception. GtkEv also overrides the unrealize method, in order to
destroy the event window.
Here is GtkEvs realize method:
static void
gtk_ev_realize
(GtkWidget
*widget)
221
{
GdkWindowAttr attributes;
gint attributes_mask;
GtkEv* ev;
GdkCursor* cursor;
g_return_if_fail(widget != NULL);
g_return_if_fail(GTK_IS_EV(widget));
ev = GTK_EV(widget);
/* Set realized flag */
GTK_WIDGET_SET_FLAGS (widget, GTK_REALIZED);
/* Main widget window */
attributes.window_type = GDK_WINDOW_CHILD;
attributes.x = widget->allocation.x;
attributes.y = widget->allocation.y;
attributes.width = widget->allocation.width;
attributes.height = widget->allocation.height;
attributes.wclass = GDK_INPUT_OUTPUT;
attributes.visual = gtk_widget_get_visual (widget);
attributes.colormap = gtk_widget_get_colormap (widget);
attributes.event_mask = gtk_widget_get_events (widget) | GDK_EXPOSURE_MASK;
attributes_mask = GDK_WA_X | GDK_WA_Y | GDK_WA_VISUAL | GDK_WA_COLORMAP;
widget->window = gdk_window_new (gtk_widget_get_parent_window (widget),
&attributes, attributes_mask);
gdk_window_set_user_data (widget->window, widget);
/* Event window */
cursor = gdk_cursor_new(GDK_CROSSHAIR);
attributes.window_type = GDK_WINDOW_CHILD;
attributes.x = ev->event_window_rect.x;
attributes.y = ev->event_window_rect.y;
attributes.width = ev->event_window_rect.width;
attributes.height = ev->event_window_rect.height;
attributes.wclass = GDK_INPUT_OUTPUT;
attributes.visual = gtk_widget_get_visual (widget);
attributes.colormap = gtk_widget_get_colormap (widget);
attributes.event_mask = GDK_ALL_EVENTS_MASK;
attributes.cursor = cursor;
attributes_mask = GDK_WA_X | GDK_WA_Y | GDK_WA_VISUAL |
GDK_WA_COLORMAP | GDK_WA_CURSOR;
ev->event_window = gdk_window_new (widget->window,
&attributes, attributes_mask);
gdk_window_set_user_data (ev->event_window, widget);
gdk_window_show(ev->event_window);
gdk_cursor_destroy(cursor);
/* Style */
widget->style = gtk_style_attach (widget->style, widget->window);
222
The first step in any realize method is to set the GTK_REALIZED flag; this is a small
but important detail. After that, most of the realize method is concerned with creating the two GdkWindows, as described in the section called GdkWindow in Chapter
10. widget->window should be created as a subwindow of the widgets parents GdkWindow; the parent window is obtained with gtk_widget_get_parent_window().
Notice that all events are requested on the event window, for obvious reasons. Also,
the event window has a special cursor, to give the user visual feedback when the
pointer moves into it. The client-side cursor handle is destroyed immediately after
attaching the cursor to the window; the X server will keep it around as long as its in
use.
After creating each GdkWindow, a pointer to the GtkEv is stored in the GdkWindows "user data" field. GTK+ uses the contents of this field to determine which widget should receive events that occur on the window. Recall that GTK+ receives a
stream of events from GDK, and that each GdkEvent has a window field indicating
the GdkWindow that received it. GTK+ forwards each event to the widget owning
the events GdkWindow. (the section called Events in Chapter 10 details this process
if you dont remember.)
The code calls gdk_window_show() on the event window but not widget->window;
widget->window should not be shown until the widget is mapped. Because the
event window is a child of widget->window, it will remain offscreen until its parent
is shown. Alternatively, GtkEv could implement a map method to show the child, but
this way seems simpler.
All widgets must take create their associated GtkStyle in their realize method, because a style contains X resources. (See the section called GtkStyle and Themes in Chapter 10 for more information about GtkStyle.) Recall from the section called Realizing,
Mapping, and Showing in Chapter 3 that widgets allocate all X resources in their realize
method. GTK+ provides a simple function to create a widgets style:
widget->style = gtk_style_attach (widget->style, widget->window);
After filling in widget->style, GtkEv uses colors from the style to set window backgrounds. It sets the main windows background using gtk_style_set_background(),
which could do almost anything (it might invoke a routine from a dynamically loaded
theme module). If the default theme is running, it simply sets the windows background to an appropriate color or pixmap tile. There is no special style function to
set the background of the event window, so we set it to the "base" color (the base
color is white by default; its the background color for lists and text entries). Selecting
a color from the style means that users will be able to customize the widgets color.
Its also convenient to avoid allocating and deallocating a custom color.
Notice that the realize method does not chain up to the default realize method, because the default isnt appropriate for GtkEv.
Unrealizing GtkEv is relatively simple:
static void
gtk_ev_unrealize (GtkWidget
{
*widget)
223
GtkEv* ev;
g_return_if_fail(widget != NULL);
g_return_if_fail(GTK_IS_EV(widget));
ev = GTK_EV(widget);
/* Hide all windows */
if (GTK_WIDGET_MAPPED (widget))
gtk_widget_unmap (widget);
GTK_WIDGET_UNSET_FLAGS (widget, GTK_MAPPED);
/* Destroy our child window */
if (ev->event_window)
{
gdk_window_set_user_data(ev->event_window, NULL);
gdk_window_destroy(ev->event_window);
ev->event_window = NULL;
}
/* This destroys widget->window and unsets the realized flag
*/
if (GTK_WIDGET_CLASS(parent_class)->unrealize)
(* GTK_WIDGET_CLASS(parent_class)->unrealize) (widget);
}
First, the unrealize method ensures that the widget is unmapped. This is essential:
GTK+ maintains the invariant that mapped widgets are also realized. Next, the unrealize method destroys the event window. It sets the windows user data to NULL
before destroying it; otherwise GtkEv would receive a useless destroy event. Finally,
GtkEv chains up to the default unrealize method, which unsets the GTK_WIDGET_REALIZED
flag and destroys widget->window. Unrealize implemenations are required to chain
up to their base classs implementation.
When writing your realize and unrealize methods, keep in mind that they can be
called multiple times, but they are always paired. That is, a widget can be unrealized and re-realized over and over, but it will never be realized twice without an
intervening unrealize. The pairing is guaranteed; that is, if a widget is realized it will
definitely be unrealized sooner or later, unless the program exits.
Size Negotiation
the section called Size Allocation in Chapter 3 describes the size negotiation process;
be sure youre familiar with it before reading this section.
Theres no obvious "right" size for GtkEv, so the size request method requests an
arbitrary size that looks nice:
static void
gtk_ev_size_request
(GtkWidget
GtkRequisition
{
g_return_if_fail(widget != NULL);
g_return_if_fail(GTK_IS_EV(widget));
/*
224
*widget,
*requisition)
Assign the new allocation to widget->allocation; this does not happen automatically, as it does for widget->requisition.
Perform any widget-specific tasks; for example, GtkEv updates the two GdkRectangles representing its internal layout.
(GtkWidget
GtkAllocation
*widget,
*allocation)
{
static const gint spacing = 10;
GtkEv* ev;
g_return_if_fail(widget != NULL);
g_return_if_fail(GTK_IS_EV(widget));
ev = GTK_EV(widget);
widget->allocation = *allocation;
ev->event_window_rect.width =
MAX(allocation->width - spacing*2, 0);
ev->event_window_rect.height =
MAX(allocation->height / 5 - spacing / 2, 0);
ev->event_window_rect.x =
(allocation->width - ev->event_window_rect.width)/2;
ev->event_window_rect.y =
MIN(spacing, allocation->height);
ev->description_rect.x = ev->event_window_rect.x;
ev->description_rect.y =
ev->event_window_rect.y + ev->event_window_rect.height + spacing;
ev->description_rect.width =
ev->event_window_rect.width;
ev->description_rect.height =
MAX((allocation->height - ev->event_window_rect.height - spacing*3), 0);
225
if (GTK_WIDGET_REALIZED (widget))
{
gdk_window_move_resize (widget->window,
allocation->x,
allocation->y,
allocation->width,
allocation->height);
gdk_window_move_resize (ev->event_window,
ev->event_window_rect.x,
ev->event_window_rect.y,
ev->event_window_rect.width,
ev->event_window_rect.height);
}
}
Drawing
There are three common situations that require a widget to redraw all or part of itself:
1. Expose events signal that all or part of a widgets GdkWindow has just become
visible on the screen and needs repainting (see the section called Expose Events
in Chapter 10). A widgets expose_event method performs these redraws.
2. GTK+ sometimes determines that a widget should be redrawn. This might happen when a widget receives a new size allocation different from its previous size
allocation, or when a new theme is loaded. A widgets draw method, usually
invoked via gtk_widget_queue_draw() or gtk_widget_queue_clear(), handles this case.
3. Widgets sometimes decide to redraw themselves. For example, if you change
the text of a GtkLabel, the label will redraw itself to reflect the new text. Widget
implementations are free to handle this case however they like, but most will
use the draw method.
There are two special cases of the second situation. The first occurs when a widget
receives or loses the keyboard focus; the second occurs when the widget becomes (or
unbecomes) the "default" widget. Widgets should indicate these states visually, but
they can often do so without a complete redraw. Thus, there are special draw_focus
and draw_default signals to handle them. These signals only have to be implemented
if a widget can meaningfully receive the focus or default.
Because there is typically little difference between a widgets draw and expose methods, a common convention is to write a static function to handle both of them. This
function is standardly called gtk_whatever_paint(). Its also possible to avoid implementing the draw method, because the default draw method synthesizes an expose event covering the widgets entire allocation and invokes the expose method.
(Remember that a synthetic expose event will have its send_event flag set to TRUE;
you can use this to distinguish synthetic events.)
The primary reason for distinguishing expose events from other draws is that expose
events are marked with the window they occurred on; for widgets with multiple
windows such as GtkEv, this can increase efficiency. GtkEv implements two private
functions, gtk_ev_paint() and gtk_ev_paint_event_window(), which it uses to
implement the expose and draw methods.
Here is the draw method:
226
static void
gtk_ev_draw
(GtkWidget
GdkRectangle
*widget,
*area)
{
GdkRectangle event_window_area;
GdkRectangle intersection;
GtkEv* ev;
g_return_if_fail(widget != NULL);
g_return_if_fail(GTK_IS_EV(widget));
ev = GTK_EV(widget);
gtk_ev_paint(ev, area);
event_window_area = *area;
if (gdk_rectangle_intersect(area, &ev->event_window_rect, &intersection))
{
/* Make the intersection relative to the event window */
intersection.x -= ev->event_window_rect.x;
intersection.y -= ev->event_window_rect.y;
gtk_ev_paint_event_window(ev, &intersection);
}
}
(GtkWidget
GdkEventExpose
*widget,
*event)
{
if (event->window == widget->window)
gtk_ev_paint(GTK_EV(widget), &event->area);
else if (event->window == GTK_EV(widget)->event_window)
gtk_ev_paint_event_window(GTK_EV(widget), &event->area);
else
g_assert_not_reached();
return TRUE;
}
Both the draw and expose methods should be self-explanatory. All the work is done
in the two paint functions. Here is gtk_ev_paint(), which renders the main widget
window:
static void
gtk_ev_paint
(GtkEv
GdkRectangle
*ev,
*area)
{
GtkWidget* widget;
g_return_if_fail(ev != NULL);
g_return_if_fail(GTK_IS_EV(ev));
widget = GTK_WIDGET(ev);
if (!GTK_WIDGET_DRAWABLE (widget))
return;
227
gdk_window_clear_area (widget->window,
area->x,
area->y,
area->width,
area->height);
gdk_gc_set_clip_rectangle(widget->style->black_gc, area);
/* Draw a black rectangle around the event window */
gdk_draw_rectangle(widget->window,
widget->style->black_gc,
FALSE,
ev->event_window_rect.x - 1,
ev->event_window_rect.y - 1,
ev->event_window_rect.width + 2,
ev->event_window_rect.height + 2);
gdk_gc_set_clip_rectangle(widget->style->black_gc, NULL);
/* Draw text in the description area, if applicable */
if (ev->buffer)
{
GdkRectangle intersection;
if (gdk_rectangle_intersect(area,
&ev->description_rect,
&intersection))
{
static const gint space = 2;
gint line;
gint step;
gint first_baseline;
GList* tmp;
step = widget->style->font->ascent +
widget->style->font->descent + space;
first_baseline = ev->description_rect.y +
widget->style->font->ascent + space;
line = 0;
tmp = ev->buffer;
while (tmp != NULL)
{
gchar** this_event = tmp->data;
gint i = 0;
while (this_event[i])
{
gtk_paint_string (widget->style,
widget->window,
widget->state,
&intersection, widget, "ev",
ev->description_rect.x,
first_baseline + line*step,
this_event[i]);
++i;
++line;
}
228
Most of gtk_ev_paint() is GtkEv-specific; it simply draws the contents of the window. Notice that it checks GTK_WIDGET_DRAWABLE() at the beginning; this is required
because the draw method may invoke the function. Unsynthesized expose events
guarantee that a widgets X window is on-screen and thus this check is not really
necessary when responding to expose events.
gtk_ev_paint_event_window() paints the small subwindow; its a very simple func-
tion:
static void
gtk_ev_paint_event_window
(GtkEv
GdkRectangle
*ev,
*area)
{
GtkWidget* widget;
gint width;
gint x, y;
const char* title;
g_return_if_fail(ev != NULL);
g_return_if_fail(GTK_IS_EV(ev));
widget = GTK_WIDGET(ev);
if (!GTK_WIDGET_DRAWABLE (widget))
return;
title = _("Event Window");
gdk_window_clear_area (ev->event_window,
area->x,
area->y,
area->width,
area->height);
gdk_gc_set_clip_rectangle(widget->style->black_gc, area);
229
Handling Focus
GtkEv wants to receive key press events so it can report information about them.
As discussed in the section called Focus in Chapter 3 and the section called Keyboard
Focus in Chapter 10, only toplevel windows receive key events from GDK. GtkWindow
keeps track of a current focus widget and forwards key events to it.
If a widget wants to receive key events, it must:
Set its GTK_CAN_FOCUS flag, so GTK+ will consider it as a possible focus widget.
(GtkWidget
GdkEventFocus
*widget,
*event)
{
g_return_val_if_fail(widget != NULL, FALSE);
g_return_val_if_fail(GTK_IS_EV(widget), FALSE);
GTK_WIDGET_SET_FLAGS (widget, GTK_HAS_FOCUS);
gtk_widget_draw_focus (widget);
return FALSE;
}
static gint
gtk_ev_focus_out
(GtkWidget
GdkEventFocus
*widget,
*event)
{
g_return_val_if_fail(widget != NULL, FALSE);
g_return_val_if_fail(GTK_IS_EV(widget), FALSE);
GTK_WIDGET_UNSET_FLAGS (widget, GTK_HAS_FOCUS);
gtk_widget_draw_focus (widget);
230
return FALSE;
}
These implementations are the minimal ones; all focusable widgets must set or unset
the GTK_HAS_FOCUS flag when they gain or lose the focus, and they must emit the
"draw_focus" signal.
GtkEv has a lazy implementation of the "draw_focus" signal; it just calls the same
gtk_ev_paint() used to respond to expose events and redraw requests. Recall that
gtk_ev_paint() checks whether the GtkEv has the focus and draws a focus frame if
(GtkWidget
*widget)
g_return_if_fail(widget != NULL);
g_return_if_fail(GTK_IS_EV(widget));
ev = GTK_EV(widget);
rect.x = 0;
rect.y = 0;
rect.width = widget->allocation.width;
rect.height = widget->allocation.height;
if (GTK_WIDGET_DRAWABLE (ev))
gtk_ev_paint(ev, &rect);
}
Notice that widget implementations are responsible for emitting the "draw_focus"
signal themselves; GTK+ does not emit it as the focus moves. Contrast this with the
"draw_default" signal, which GTK+ automatically emits whenever a widget gains or
loses the default. GtkEv cannot be the default widget, so it does not implement this
signal.
GtkEvs Functionality
All the code presented so far implements the GtkWidget and GtkObject interfaces.
GtkEv does have some unique functionality; namely, it responds to events on its event
window by adding text describing the event to its buffer, and queueing a redraw. To
do this, it overrides the default "event" signal handler.
Here is GtkEvs event method:
static gint
gtk_ev_event (GtkWidget
GdkEvent
{
GtkEv* ev;
*widget,
*event)
231
if (event->any.window == widget->window)
{
if (GTK_WIDGET_CLASS(parent_class)->event)
return (* GTK_WIDGET_CLASS(parent_class)->event) (widget, event);
else
return FALSE;
}
else
{
gchar* text;
/* The event is either on ev->event_window, or it is a key event
* passed down to us from the toplevel GtkWindow
*/
text = event_to_text(event);
gtk_ev_push_text(ev, text);
g_free(text);
/* If it was a motion event, make sure we get more */
if (event->type == GDK_MOTION_NOTIFY)
{
gdk_window_get_pointer(ev->event_window, NULL, NULL, NULL);
}
/* We didnt "handle" the event, just listened in on it. */
return FALSE;
}
}
Notice that the window method of the event is used to distinguish events that occur
on widget->window from events that occur on the event subwindow. Some events
will be received from a different window entirely; for example, key events actually
occur on a toplevel window, and are passed to GtkEv if GtkEv has the focus.
event_to_text() is a lengthy but trivial function that creates a string describing the
event; gtk_ev_push_text() pushes the text onto the front of the buffer and queues
a redraw. The implementation of these functions is part of the complete GtkEv code
listing, in Appendix E.
GtkWidget In Detail
This section catalogs the functions in GtkWidgetClass more rigorously, and describes
the default implementation of each.
Destruction
Widget destruction is not significantly different from object destruction in general, as
described in the section called Object Finalization in Chapter 9. As always, there are
three phases: shutdown, destroy, and finalize. Only the destroy method is a signal;
the others are class functions only. If you override any of the three, you must "chain
up" to the parent class implementation.
GtkWidget has default implementations of all three; you should know what they do:
232
In its shutdown method, a GtkWidget removes itself from its parent container (if
any), and then unrealizes itself. This implies that widgets are always unrealized inside their destroy methods. It chains up to the GtkObject shutdown method which
emits the "destroy" signal.
In its destroy method, a GtkWidget releases the grab if it has it, unreferences its
style and sets widget->style to NULL, and gives up any connections it had to the
current selection. (GtkEntry and other editable-text widgets allow you to select
and paste text.) It chains up to the GtkObject destroy method which disconnects
any signal handlers for the object.
233
its layout.
does the same, since a newly-invisible widget implies recalculating the layout just as a newly-visible one does.
gtk_widget_hide()
gtk_widget_show_all() and gtk_widget_hide_all() dont do anything special, they simply invoke the corresponding class function.
gtk_widget_map() realizes the widget before emitting the "map" signal, if the
widget is not realized. This maintains an important invariant (all mapped widgets
are also realized). After emitting the signal, gtk_widget_map() queues a draw for
windowless widgets; widgets with windows will receive an expose event when
the window appears on the screen, so queueing a draw is not necessary.
Realization
The realize and unrealize class functions are registered as signals. Realization is the
process of creating GDK resources associated with the widget; including but not limited to widget->window and widget->style.
A realize method should do the following:
234
Unmaps the widget if the widget is mapped; remember the GTK+ invariant that
all mapped widgets are realized.
Unrealizes all child widgets, if the widget is a container; this maintains the invariant that widgets cannot be realized unless their parents are also realized.
Unreferences widget->style.
Widgets are required to chain up if they override their base classs unrealize method.
This ensures that all resources are freed. Overriding the default method may be necessary if a widget has more than one GdkWindow or other special needs. All windows should be destroyed just as GtkEv destroys its event_window, that is, the windows user data field should be set to NULL before destruction:
gdk_window_set_user_data(ev->event_window, NULL);
gdk_window_destroy(ev->event_window);
ev->event_window = NULL;
This keeps GTK+ from sending a useless GDK_DESTROY event for the window.
The "unrealize" signal is emitted via gtk_widget_unrealize(). gtk_widget_unrealize()
does some internal bookkeeping which is important but not very interesting; just be
careful to use this function rather than emitting the signal directly.
Drawing
The relationship between draw, draw_focus, draw_default, and expose_event was
discussed in the section called Drawing. All four class functions are registered as default handlers for a signal of the same name. The "draw" signal redraws a portion of
the widget; it is emitted by GTK+ or by widget implementations.
Widget implementations should emit the "draw_focus" signal themselves, generally
in response to focus events; the signal draws or undraws a frame indicating that the
widget is focused. gtk_window_set_default() emits the "draw_default" signal for
both the widget losing default status and the widget gaining it. (gtk_widget_grab_default()
calls gtk_window_set_default().) Only widgets with the GTK_CAN_FOCUS or
GTK_CAN_DEFAULT flag set need to worry about the draw_focus and draw_default
methods. These flags should be set in a widgets instance initialization function.
Only the draw method has a default implementation in GtkWidget; the default implementation synthesizes an expose event covering the widgets entire allocation.
This allows you to write an expose event handler that also handles the draw signal.
GTK+ normally emits the "draw" signal in an idle function. That is, it keeps a list of
widgets (and regions of them) that need to be redrawn; when no events are pending,
the GTK+ main loop runs an idle function that traverses the list and emits the "draw"
signal for each widget. Redraw areas are merged as much as possible to avoid multiple redraws, and the idle function is removed after it runs once. This arrangement
minimizes the number of redraws and reduces flicker.
Size Negotiation
The size negotiation process has already been described in the section called Size Allocation in Chapter 3 and the section called Size Negotiation. The two signals/methods
235
involved are size_request and size_allocate. GtkWidget provides default implementations of each.
Here is the default size_request method:
static void
gtk_widget_real_size_request (GtkWidget
GtkRequisition
{
g_return_if_fail (widget != NULL);
g_return_if_fail (GTK_IS_WIDGET (widget));
*widget,
*requisition)
requisition->width = widget->requisition.width;
requisition->height = widget->requisition.height;
}
This implementation is appropriate for widgets that always request the same size;
GtkArrow and GtkDrawingArea, for example, use this default. Widgets using the default must initialize widget->requisition with their fixed request; GtkArrow does this
in gtk_arrow_init(). GtkDrawingArea begins with a default size, but allows users
to change the request with gtk_drawing_area_set_size().
Widgets whose request depends on their children, or the amount of text they contain,
or some other factor, should override the default size request method with a method
that calculates the size they want.
Size allocation is mildly more complicated; here is its default implementation:
static void
gtk_widget_real_size_allocate (GtkWidget
*widget,
GtkAllocation *allocation)
{
g_return_if_fail (widget != NULL);
g_return_if_fail (GTK_IS_WIDGET (widget));
widget->allocation = *allocation;
if (GTK_WIDGET_REALIZED (widget) &&
!GTK_WIDGET_NO_WINDOW (widget))
{
gdk_window_move_resize (widget->window,
allocation->x, allocation->y,
allocation->width, allocation->height);
}
}
This should suffice for most simple widgets. Widgets like GtkEv, or any container,
need to update internal data structures or distribute the allocation they receive among
child widgets; these widgets will override size_allocate. It is possible but not required
to chain up to the default implementation.
The wrapper function which emits the "size_allocate" signal is significantly more involved than the signal handlers. gtk_widget_size_allocate() takes into account
gtk_widget_set_usize() and ensures widgets are redrawn if their size changes.
(Unsurprisingly, gtk_widget_size_request() also exists and should be used instead of emitting "size_request" directly.)
236
GtkContainer
GtkContainer is the base class for all widgets that contain one or more other widgets.
GtkBin is a subclass of GtkContainer, and is the base class for widgets with a single
child.
GtkContainer;
struct _GtkContainer
{
GtkWidget widget;
GtkWidget *focus_child;
guint border_width : 16;
guint need_resize : 1;
guint resize_mode : 2;
GSList *resize_widgets;
};
The focus_child member is the child in the container with the keyboard focus; it can
be NULL if no child has the focus. The GtkContainer implementation handles setting and unsetting this field. The border_width member is a width in pixels to add
to the containers size request on all sides; the container will also subtract this value
from its allocation. (In other words, the border_width is a blank space around the container.) Library users set the border_width field with gtk_container_set_border_width();
GtkContainer subclasses must honor its value in their size_request and size_allocate
implementations.
The need_resize, resize_mode, and resize_widgets fields are implementation details
that subclasses should not have to read or modify. These fields are used to implement
gtk_widget_queue_resize(); when a resize is queued for a widget, the GtkContainer implementation ensures that the size negotiation process (requisition/allocation)
will take place a in a one-shot idle handler. Subclasses of GtkContainer simply implement size_request and size_allocate, and everything works.
GtkContainerClass;
struct _GtkContainerClass
{
GtkWidgetClass parent_class;
guint
n_child_args;
void (* add)
void (* remove)
void (* check_resize)
void (* forall)
(GtkContainer
GtkWidget
(GtkContainer
GtkWidget
(GtkContainer
(GtkContainer
gboolean
GtkCallback
*container,
*widget);
*container,
*widget);
*container);
*container,
include_internals,
callback,
237
gint (* focus)
void (* set_focus_child)
GtkType (*child_type)
void
(*set_child_arg)
void
(*get_child_arg)
gchar*
(*composite_name)
gpointer
callbabck_data);
(GtkContainer
*container,
GtkDirectionType direction);
(GtkContainer
*container,
GtkWidget
*widget);
(GtkContainer
*container);
(GtkContainer
*container,
GtkWidget
*child,
GtkArg
*arg,
guint
arg_id);
(GtkContainer
*container,
GtkWidget
*child,
GtkArg
*arg,
guint
arg_id);
(GtkContainer
*container,
GtkWidget
*child);
Many of these class functions do not have corresponding signals. add, remove, check_resize,
focus, and set_focus_child methods are default handlers for signals with the same
name. The others are just methods.
The check_resize method recalculates layout if necessary; it is invoked by the idle
handler installed by gtk_widget_queue_resize(). As the previous section mentioned, subclasses should not have to concern themselves with this process.
The focus and set_focus_child methods handle moving focus around a GtkWindow.
Users can move the focus with the arrow keys and the tab key. This results in emissions of the "focus" signal, with the direction argument indicating which way the focus should move. The possible directions are: GTK_DIR_TAB_FORWARD, GTK_DIR_TAB_BACKWARD,
GTK_DIR_UP, GTK_DIR_DOWN, GTK_DIR_LEFT, and GTK_DIR_RIGHT. GtkContainer provides a default implementation based on the geometric location of child
widgets; it works fine for most standard layout containers, such as GtkBox and GtkTable. It should also work for GtkBin subclasses. More elaborate or unusual containers, such as the tree and list widgets, or GtkNotebook, override this method. The
focus method should return TRUE if an appropriate child was found and the focus
was moved (using gtk_widget_grab_focus()).
The set_focus_child method is used by gtk_widget_grab_focus() to set the focus
child of a container. gtk_widget_grab_focus() can be invoked by the focus method
of a container, or by a widget implementation (for example, GtkEntry grabs the focus
if the user clicks on it). The default implementation simply sets the focus_child field
of the container, and increments the childs reference count.
composite_name returns a special name for a child when its a part of a particular
container. For example, the composite names of the two GtkScrollbar widgets in
a GtkScrolledWindow are "hscrollbar" and "vscrollbar." These names allow themes
to specify widget attributes precisely. The default implementation of this method
should always work fine; it returns the name set with gtk_widget_set_composite_name().
n_child_args, set_child_arg, and get_child_arg are exactly analagous to the n_args,
get_arg, and set_arg fields of GtkObjectClass. the section called Using Object Arguments in Your Own GtkObject Subclass in Chapter 9 mentions this briefly. Child arguments are used to get and set attributes of the container-child unit, such as the packing parameters for GtkBox or the attachment parameters for GtkTable. In contrast,
normal object arguments set the characteristics of a single object in isolation. Though
238
the implementation differs, child arguments work almost exactly like the object arguments described in Chapter 9. The only visible difference is that the get and set
functions take a container and a widget as arguments, instead of a single object.
The following section introduces the remaining functions in GtkContainer by describing their implementation in GtkBin.
container instance for storing a single child, and provides default implementations
for the container methods that operate on this one child. GtkBin implements the add,
remove, forall, and child_type methods from GtkContainer; combined with GtkContainers default implementations, simple subclasses of GtkBin (such as GtkEventBox, GtkAlignment, and GtkFrame) do not need to override any GtkContainer methods. Heres the instance struct:
typedef struct _GtkBin
GtkBin;
struct _GtkBin
{
GtkContainer container;
GtkWidget *child;
};
GtkBinClass;
struct _GtkBinClass
{
GtkContainerClass parent_class;
};
239
g_return_if_fail
g_return_if_fail
g_return_if_fail
g_return_if_fail
(container != NULL);
(GTK_IS_BIN (container));
(child != NULL);
(GTK_IS_WIDGET (child));
>parent and handles reference counting and some other internal details.
The container saves a pointer to the child; this is easy for GtkBin, since there is
only one child and it goes in bin->child.
If the container has been shown (i.e., if its GTK_VISIBLE flag is set), parent and
childs GTK_REALIZED and GTK_MAPPED states are synchronized. That is, the
child is realized and mapped if the parent is realized and mapped.
If both parent and child have been shown, a resize is queued. That is, layout will
be recalculated in light of the new child.
(container != NULL);
(GTK_IS_BIN (container));
(child != NULL);
(GTK_IS_WIDGET (child));
240
if (widget_was_visible)
gtk_widget_queue_resize (GTK_WIDGET (container));
}
A remove method is little more than a wrapper for gtk_widget_unparent that queues
a resize if necessary. Most remove methods would check the containers GTK_VISIBLE
flag before queueing a resize, just as gtk_bin_add() does; GtkBin does not because
toplevel widgets like GtkWindow derive from it, and those widgets always queue a
resize, regardless of visibility.
You may notice that GtkBin ignores the include_internals argument. Some containers have "incidental" child widgets in addition to the user-provided children they are
primarily designed to hold. For example, GtkNotebook has a widget labelling each of
its tabs; GtkCList uses buttons to title each column in the list. These internal widgets
must be included in the iteration in many cases; for example, when drawing each
child in a container, or destroying each child in a container. However, some operations only operate on the "primary" children, such as the pages in GtkNotebook. The
include_internals flag indicates whether to invoke the callback on incidental widgets.
Convenience functions are provided that invoke the forall method; these are used by
application authors as well as GtkContainer internals. gtk_container_foreach()
iterates over only the primary children of a container, while gtk_container_forall()
iterates over all the children.
Child Type
The child_type method returns the type of children a container can hold. For example, a GtkMenuShell (parent class of GtkMenu and GtkMenuBar) can only hold children of type GTK_TYPE_MENU_ITEM. The child_type method allows GUI builders
and scripting languages to determine at runtime what sort of children a container
241
will accept. GTK_TYPE_NONE indicates that a container will not accept children at
this time, for whatever reason.
The GtkBin implementation accepts GTK_TYPE_WIDGET if the bin is empty, and
GTK_TYPE_NONE if the bin already contains a child:
static GtkType
gtk_bin_child_type (GtkContainer *container)
{
if (!GTK_BIN (container)->child)
return GTK_TYPE_WIDGET;
else
return GTK_TYPE_NONE;
}
242
gtk_widget_queue_clear (widget);
else
gdk_window_hide (widget->window);
if (bin->child && GTK_WIDGET_MAPPED (bin->child))
gtk_widget_unmap (bin->child);
}
GtkBins draw and expose implementations simply redraw the child widget; most
subclasses will need to override these methods in order to draw themselves, then
chain up to draw the child. The code:
static void
gtk_bin_draw (GtkWidget
*widget,
GdkRectangle *area)
{
GtkBin *bin;
GdkRectangle child_area;
g_return_if_fail (widget != NULL);
g_return_if_fail (GTK_IS_BIN (widget));
bin = GTK_BIN (widget);
if (GTK_WIDGET_DRAWABLE (bin))
{
if (bin->child && GTK_WIDGET_DRAWABLE (bin->child) &&
gtk_widget_intersect (bin->child, area, &child_area))
gtk_widget_draw (bin->child, &child_area);
}
}
static gint
gtk_bin_expose (GtkWidget
*widget,
GdkEventExpose *event)
{
GtkBin *bin;
GdkEventExpose child_event;
g_return_val_if_fail (widget != NULL, FALSE);
g_return_val_if_fail (GTK_IS_BIN (widget), FALSE);
g_return_val_if_fail (event != NULL, FALSE);
if (GTK_WIDGET_DRAWABLE (widget))
{
bin = GTK_BIN (widget);
child_event = *event;
if (bin->child && GTK_WIDGET_DRAWABLE (bin->child) &&
GTK_WIDGET_NO_WINDOW (bin->child) &&
gtk_widget_intersect (bin->child, &event->area, &child_event.area))
gtk_widget_event (bin->child, (GdkEvent*) &child_event);
}
return FALSE;
}
Notice that expose events are only generated for windowless widgets; widgets with
windows will receive their own expose events. Containers are required to generate
expose events for windowless children.
243
GtkBox;
struct _GtkBox
{
GtkContainer container;
GList *children;
gint16 spacing;
guint homogeneous : 1;
};
GtkBoxClass adds nothing to GtkContainerClass, and GtkVBox adds nothing to
GtkBox.
244
identical to GtkBins draw and expose implementations, except that theres a list of
children to iterate over.
A GTK_NO_WINDOW widget that isnt invisible, such as GtkLabel, should be careful not to draw a background; the parent widgets background is used.
Size Negotiation
GtkVBoxs purpose in life is size negotiation; it passes size requests up from its chil-
dren, and then divides a size allocation among them. This leads to the layout behavior
described in the section called GtkBox in Chapter 3.
Here is the size request implementation:
static void
gtk_vbox_size_request (GtkWidget
*widget,
GtkRequisition *requisition)
{
GtkBox *box;
GtkBoxChild *child;
GtkRequisition child_requisition;
GList *children;
gint nvis_children;
gint height;
g_return_if_fail (widget != NULL);
g_return_if_fail (GTK_IS_VBOX (widget));
g_return_if_fail (requisition != NULL);
box = GTK_BOX (widget);
requisition->width = 0;
requisition->height = 0;
nvis_children = 0;
children = box->children;
while (children)
{
child = children->data;
children = children->next;
if (GTK_WIDGET_VISIBLE (child->widget))
{
gtk_widget_size_request (child->widget, &child_requisition);
if (box->homogeneous)
{
height = child_requisition.height + child->padding * 2;
requisition->height = MAX (requisition->height, height);
}
else
{
requisition->height += child_requisition.height + child>padding * 2;
}
requisition->width = MAX (requisition->width, child_requisition.width);
nvis_children += 1;
}
}
245
if (nvis_children > 0)
{
if (box->homogeneous)
requisition->height *= nvis_children;
requisition->height += (nvis_children - 1) * box->spacing;
}
requisition->width += GTK_CONTAINER (box)->border_width * 2;
requisition->height += GTK_CONTAINER (box)->border_width * 2;
}
If the box is homogenous, it multiplies the maximum child requisition times the number of children; otherwise, it sums the child requisitions. Then it adds padding, spacing, and border width, as appropriate. Recall that all containers must honor their
border width, set with gtk_container_set_border_width() and available as the
border_width field in the GtkContainer instance struct.
When reading this code, it may help to know that GtkBox stores a small struct for
each child widget in its children field. The struct looks like this:
typedef struct _GtkBoxChild
GtkBoxChild;
struct _GtkBoxChild
{
GtkWidget *widget;
guint16 padding;
guint expand : 1;
guint fill : 1;
guint pack : 1;
};
Size allocation is more complex; here, all the box-packing flags come into play. It will
probably take you a while to fully understand this function, but there is no need to;
the important thing is to see how layout takes place via size allocation.
static void
gtk_vbox_size_allocate (GtkWidget
*widget,
GtkAllocation *allocation)
{
GtkBox *box;
GtkBoxChild *child;
GList *children;
GtkAllocation child_allocation;
gint nvis_children;
gint nexpand_children;
gint child_height;
gint height;
gint extra;
gint y;
g_return_if_fail (widget != NULL);
g_return_if_fail (GTK_IS_VBOX (widget));
g_return_if_fail (allocation != NULL);
box = GTK_BOX (widget);
widget->allocation = *allocation;
nvis_children = 0;
nexpand_children = 0;
children = box->children;
246
while (children)
{
child = children->data;
children = children->next;
if (GTK_WIDGET_VISIBLE (child->widget))
{
nvis_children += 1;
if (child->expand)
nexpand_children += 1;
}
}
if (nvis_children > 0)
{
if (box->homogeneous)
{
height = (allocation->height GTK_CONTAINER (box)->border_width * 2 (nvis_children - 1) * box->spacing);
extra = height / nvis_children;
}
else if (nexpand_children > 0)
{
height = (gint) allocation->height - (gint) widget->requisition.height;
extra = height / nexpand_children;
}
else
{
height = 0;
extra = 0;
}
y = allocation->y + GTK_CONTAINER (box)->border_width;
child_allocation.x = allocation->x + GTK_CONTAINER (box)->border_width;
child_allocation.width = MAX (1, (gint) allocation->width - (gint) GTK_CONTAINER
>border_width * 2);
children = box->children;
while (children)
{
child = children->data;
children = children->next;
if ((child->pack == GTK_PACK_START) && GTK_WIDGET_VISIBLE (child>widget))
{
if (box->homogeneous)
{
if (nvis_children == 1)
child_height = height;
else
child_height = extra;
nvis_children -= 1;
height -= extra;
}
else
{
GtkRequisition child_requisition;
247
248
if (child->expand)
{
if (nexpand_children == 1)
child_height += height;
else
child_height += extra;
nexpand_children -= 1;
height -= extra;
}
}
if (child->fill)
{
child_allocation.height = MAX (1, child_height - (gint)child>padding * 2);
child_allocation.y = y + child->padding - child_height;
}
else
{
child_allocation.height = child_requisition.height;
child_allocation.y = y + (child_height - child_allocation.height) / 2
child_height;
}
gtk_widget_size_allocate (child->widget, &child_allocation);
y -= (child_height + box->spacing);
}
}
}
}
Child Arguments
GtkBox implements child arguments, which were briefly described in the section called
Using Object Arguments in Your Own GtkObject Subclass in Chapter 9. Child arguments
represent a property of a pair of objects. In this case, the box-packing flags for each
child can be read and written using the object argument system.
Heres how GtkBox registers its child arguments, in gtk_box_class_init():
gtk_container_add_child_arg_type
gtk_container_add_child_arg_type
gtk_container_add_child_arg_type
gtk_container_add_child_arg_type
gtk_container_add_child_arg_type
GtkBox then implements the get_child_arg and set_child_arg methods from GtkContainerClass. Heres gtk_box_get_child_arg(); the gtk_box_set_child_arg() is
analagous.
static void
gtk_box_get_child_arg (GtkContainer
GtkWidget
GtkArg
guint
*container,
*child,
*arg,
arg_id)
249
{
gboolean expand = 0;
gboolean fill = 0;
guint padding = 0;
GtkPackType pack_type = 0;
GList *list;
if (arg_id != CHILD_ARG_POSITION)
gtk_box_query_child_packing (GTK_BOX (container),
child,
&expand,
&fill,
&padding,
&pack_type);
switch (arg_id)
{
case CHILD_ARG_EXPAND:
GTK_VALUE_BOOL (*arg) = expand;
break;
case CHILD_ARG_FILL:
GTK_VALUE_BOOL (*arg) = fill;
break;
case CHILD_ARG_PADDING:
GTK_VALUE_ULONG (*arg) = padding;
break;
case CHILD_ARG_PACK_TYPE:
GTK_VALUE_ENUM (*arg) = pack_type;
break;
case CHILD_ARG_POSITION:
GTK_VALUE_LONG (*arg) = 0;
for (list = GTK_BOX (container)->children; list; list = list->next)
{
GtkBoxChild *child_entry;
child_entry = list->data;
if (child_entry->widget == child)
break;
GTK_VALUE_LONG (*arg)++;
}
if (!list)
GTK_VALUE_LONG (*arg) = -1;
break;
default:
arg->type = GTK_TYPE_INVALID;
break;
}
}
250
A composite widget derives from some kind of container, then adds child widgets
and sets up callbacks to implement some sort of functionality. GnomeAppBar derives
from GtkHBox; the box is packed with a progress bar and/or a status line. GnomeAppBar has members in its instance struct to store a stack of status messages, and it adds
some signals to the class struct for use with its "interactive" mode.
As an aside, GnomeAppBar does not follow the GTK+/Gnome naming conventions;
because Bar is capitalized, the functions and macros should have an underscore, i.e.
app_bar rather than appbar. Dont copy this aspect of the widget.
Heres the implementation of gnome_appbar_new():
GtkWidget*
gnome_appbar_new (gboolean has_progress,
gboolean has_status,
GnomePreferencesType interactivity)
{
GnomeAppBar * ab = gtk_type_new (gnome_appbar_get_type ());
gnome_appbar_construct(ab, has_progress, has_status, interactivity);
return GTK_WIDGET(ab);
}
void
gnome_appbar_construct(GnomeAppBar * ab,
gboolean has_progress,
gboolean has_status,
GnomePreferencesType interactivity)
{
GtkBox *box;
251
GTK_SIGNAL_FUNC(entry_delete_text_cb),
ab);
gtk_signal_connect (GTK_OBJECT(ab->status), "insert_text",
GTK_SIGNAL_FUNC(entry_insert_text_cb),
ab);
gtk_signal_connect_after(GTK_OBJECT(ab->status), "key_press_event",
GTK_SIGNAL_FUNC(entry_key_press_cb),
ab);
gtk_signal_connect(GTK_OBJECT(ab->status), "activate",
GTK_SIGNAL_FUNC(entry_activate_cb),
ab);
/* no prompt now */
gtk_entry_set_editable(GTK_ENTRY(ab->status), FALSE);
gtk_box_pack_start (box, ab->status, TRUE, TRUE, 0);
}
else {
GtkWidget * frame;
ab->interactive = FALSE;
frame = gtk_frame_new (NULL);
gtk_frame_set_shadow_type (GTK_FRAME(frame), GTK_SHADOW_IN);
ab->status = gtk_label_new ("");
gtk_misc_set_alignment (GTK_MISC (ab->status), 0.0, 0.0);
gtk_box_pack_start (box, frame, TRUE, TRUE, 0);
gtk_container_add (GTK_CONTAINER(frame), ab->status);
gtk_widget_show (frame);
}
}
else {
ab->status = NULL;
ab->interactive = FALSE;
}
if (has_progress && gnome_preferences_get_statusbar_meter_on_right ())
gtk_box_pack_start (box, ab->progress, FALSE, FALSE, 0);
if (ab->status) gtk_widget_show (ab->status);
if (ab->progress) gtk_widget_show(ab->progress);
}
Most of this code could be in the instance initializer; its in the constructor instead because its dependent on the arguments passed to gnome_appbar_new(). Theres not
much to explain here; the code is straightforward. Do notice that gtk_widget_show()
is called for each child widget; this ensures that the right thing happens when the user
calls gtk_widget_show() on GnomeAppBar. Another approach would be to override
the map method and map all children (normally, containers such as GtkBox only map
children that have been shown). When youre writing a composite container, keep
the gtk_widget_show_all() function in mind; never rely on hiding child widgets,
because the user might accidentally show them.
A composite widget is just a special case of extending a base widget with additional
functionality. You can extend widgets without adding new children to them; for example, GtkClock extends GtkLabel by constantly changing the label to reflect the
time.
252
Other Examples
Here are some other widgets you might look at for inspiration and code; of course,
these are only a few of the many widgets in GTK+ and Gnome. Appendix A gives a
more comprehensive list of the available widgets, and a brief description of each one.
Toplevel: GtkWindow
253
canvas items render directly to a GdkPixmap buffer using the GDK drawing primitives. The canvas copies the buffer to the screen once all items are rendered. In antialiased or "AA" mode, the canvas items write RGB pixels to a vector of bytes; after
all the items have drawn on the RGB buffer, the canvas copies it to the screen. This
RGB buffer mode is called "antialiased" mode because all the standard canvas items
draw to the RGB buffer using the high-quality antialiased routines in libart_lgpl.
This results in smooth lines and very high display quality, with some cost in speed.
GnomeCanvasGroup
Canvas items are arranged in a tree structure. You can group items together, to be
moved as a unit; canvas architect Federico Mena Quintero likes to use a circuit diagram editor as an example. You might group together the shapes representing each
logic gate, so you could manipulate the logic gate as a unit. You could also collect
several logic gates into a single component; that is, groups can contain subgroups.
Within each group, the canvas maintains a stacking order; objects higher in the stacking order obscure objects lower in the stacking order.
To implement this, the canvas comes with a special kind of canvas item called GnomeCanvasGroup. As the name suggests, a canvas group groups a number canvas items
together so you can manipulate the child items as a single item. A GnomeCanvasGroup is invisible; to render itself, it simply recurses its children, rendering each of
them in turn. When you create a new GnomeCanvas, a default group called the "root"
is created for you. All canvas items are added somewhere below the root group. The
canvas widget only deals with the root canvas item directly; all other canvas items
are managed by their parent group.
254
An accessor function is provided to access the root canvas group, shown in Figure
12-1.
#include <libgnomeui/gnome-canvas.h>
GnomeCanvasGroup* gnome_canvas_root(GnomeCanvas* canvas);
Coordinates
Many of the features of the canvas are implemented via translations between different coordinate systems. Canvas items can be moved, rotated, or scaled via affine transformations, described in more detail below. (Short version: an affine transformation is
a way to convert from one coordinate system to another.) Here are the important coordinate systems which come up when using the canvas and writing custom canvas
items:
World coordinates are an absolute coordinate system; i.e., the same world coordinate refers to the same place on the canvas in all cases. World coordinates are conceptually infinite and are represented by a double. World coordinates are the real,
toplevel, untransformed, canonical coordinate system. Consistent with the X Window System and GDK, Y coordinates increase as they move downward, so lower Y
coordinates are toward the top of the canvas.
Item coordinates are the coordinates used by a particular canvas item. Item coordinates exist because each canvas item has an affine transformation associated with
it. In the case of GnomeCanvasGroup, this transformation is applied to the groups
children. To convert from world coordinates to item coordinates for some particular item, you apply the transform for each canvas group in the items ancestry,
starting with the root canvas group; then you apply the items own transform.
(Dont worry, Gnome comes with a function to do this for you.) Like world coordinates, item coordinates are conceptually infinite.
Canvas coordinates are pixel coordinates. While item and world coordinates are
floating-point numbers, canvas pixel coordinates are integers. To use the canvas,
you must specify a "scroll region," which is the rectangle in world coordinate space
you want the user to be able to see. Canvas pixel coordinates are relative to this
rectangle. Canvas pixel coordinates also take into account a scaling factor representing the number of pixels per world coordinate unit. To convert from world
coordinates to canvas coordinates, the canvas subtracts the X and Y coordinates of
the scroll region, multiplies by the scaling factor, and then rounds to an integer.
Thus, (0,0) in canvas coordinates will be the top left corner of the scroll region.
Buffer coordinates are canvas coordinates modified by some offset. Item implementations use these during rendering. The canvas passes the item implementation a
buffer (which is either a GdkDrawable or an RGB buffer, depending on the canvas mode). The canvas tells the item implementation which region of the screen
255
Window coordinates are rarely used. The canvas eventually copies each temporary
buffer to a GdkWindow (to be precise,it copies them to GTK_LAYOUT(canvas)>bin_window). Window coordinates are relative to this GdkWindow. In some rare
cases you might want to draw to the window directly rather than using a canvas
item, or you might want to respond to an event on the window (such as a dragand-drop). Then you need to convert from window coordinates to one of the other
coordinate systems.
When using preexisting canvas items, you will mostly be interested in world and
item coordinates. When writing your own items, you will also need to use canvas
and buffer coordinates.
There are two ways to convert between the various coordinate systems; one way is
to obtain and use affines directlythis is described in the next section. The easy way
is to use one of the convenience functions provided for the purpose, shown in Figure
12-2. Conversion between canvas and item coordinates requires you to convert to
world coordinates first as an intermediate step. There is no function to convert to
or from buffer coordinates, because this is a simple matter of subtracting the buffer
offsets from the canvas coordinates (canvas to buffer), or adding the buffer offsets to
the buffer coordinates (buffer to canvas).
#include <libgnomeui/gnome-canvas.h>
void gnome_canvas_w2c(GnomeCanvas* canvas, double wx, double wy, int* cx,
int* cy);
void gnome_canvas_w2c_d(GnomeCanvas* canvas, double wx, double wy, double* cx, double* cy);
void gnome_canvas_c2w(GnomeCanvas* canvas, int cx, int cy, double* wx, double* wy);
void gnome_canvas_item_w2i(GnomeCanvasItem* item, double* x, double* y);
void gnome_canvas_item_i2w(GnomeCanvasItem* item, double* x, double* y);
void gnome_canvas_window_to_world(GnomeCanvas* canvas, double winx, double winy, double* worldx, double* worldy);
void gnome_canvas_world_to_window(GnomeCanvas* canvas, double worldx, double worldy, double* winx, double* winy);
Affine Transformations
An affine is a transformation matrix made up of six real numbers that can be applied
to an ordered pair. Depending on the contents of the affine, the point it is applied to
can be:
256
array of six doubles. Its affine functions are shown in Figure 12-3.
#include <libart_lgpl/art_affine.h>
void art_affine_point(ArtPoint* dst, const ArtPoint* src, const double affine[6]);
void art_affine_invert(double dst_affine[6], const double src_affine[6]);
void art_affine_multiply(double dst[6], const double src1[6], const double src2[6]);
void art_affine_identity(double dst[6]);
void art_affine_scale(double dst[6], double sx, double sy);
void art_affine_rotate(double dst[6], double theta);
void art_affine_translate(double dst[6], double tx, double ty);
int art_affine_rectilinear(const double src[6]);
argument (src) and the result is copied into the first argument (dst). An ArtPoint is
simply:
typedef struct _ArtPoint ArtPoint;
struct _ArtPoint {
double x, y;
};
Affines can be inverted. If an affine converts points in coordinate system A into points
in coordinate system B, its inverse converts points in coordinate system B into points
in coordinate system A. art_affine_invert() fills its first argument with the inverse of its second.
art_affine_multiply() composes two affines as described earlier in this section,
257
art_affine_scale() gives an affine which scales the plane by the given factors
(a factor of 1.0 does no scaling, less than 1.0 shrinks, greater than 1.0 expands).
the axes in such a way that they remain aligned to the axes. That is, it returns TRUE
if the rotation is 0, 90, 180, or 270 degrees.
You can ask the canvas widget to compute affines which convert between its various
coordinate systems. These functions are shown in Figure 12-4; each of them fills an
array you pass in with the affine being requested.
#include <libgnomeui/gnome-canvas.h>
void gnome_canvas_item_i2w_affine(GnomeCanvasItem* item, double affine[6]);
void gnome_canvas_item_i2c_affine(GnomeCanvasItem* item, double affine[6]);
void gnome_canvas_w2c_affine(GnomeCanvas* canvas, double affine[6]);
other low-level approach. This section describes how to create a canvas, and work
with canvas items. It ends with a programming example.
In GDK mode, if you want to use the GnomeCanvasImage item to display images, you must use Imlibs visual and colormap. GnomeCanvasImage uses Imlib
to render images.
In antialiased mode, GDKs RGB buffer rendering facilities (see the section called
RGB Buffers in Chapter 10) are used to copy the RGB buffer to the screen. You must
use the visual and colormap from the GDK RGB module.
258
#include <libgnomeui/gnome-canvas.h>
GtkWidget* gnome_canvas_new(void);
GtkWidget* gnome_canvas_new_aa(void);
Scroll Region
The canvas is practically infinite from a programmers standpoint; however, in reality
your application probably uses only a small area. When using the canvas you must
specify which region is interesting to the user with gnome_canvas_set_scroll_region()
(Figure 12-6). The scroll region is given in world coordinates. You can query the scroll
region with gnome_canvas_get_scroll_region().
To add scroll bars to the canvas, simply create a GtkScrolledWindow and add the
canvas to it:
GtkWidget* sw;
sw = gtk_scrolled_window_new(NULL, NULL);
gtk_container_add(GTK_CONTAINER(sw), canvas);
If you want to implement scrolling via some mechanism other than the scroll bars,
you can get and set the "scroll offsets." The scroll offsets are in canvas pixel coordinates; they specify the top left visible pixel. Remember that canvas pixel coordinates
are relative to the scroll region.
#include <libgnomeui/gnome-canvas.h>
void gnome_canvas_set_scroll_region(GnomeCanvas* canvas, double x1, double y1, double x2, double y2);
void gnome_canvas_get_scroll_region(GnomeCanvas* canvas, double* x1, double* y1, double* x2, double* y2);
void gnome_canvas_scroll_to(GnomeCanvas* canvas, gint cx, gint cy);
void gnome_canvas_get_scroll_offsets(GnomeCanvas* canvas, gint* cx, gint*
cy);
259
Zooming
The canvas gives you zooming "for free"; it is included in the world-to-canvas and
canvas-to-world coordinate system conversions. You can set the zoom factor with
gnome_canvas_set_pixels_per_unit() (Figure 12-7). By default, there ratio of pixels to canvas units is 1.0, meaning no zoom. Specifying a value less than 1.0 means
reduced size; greater than 1.0 means increased size.
In antialiased mode, you could achieve the same visual effect by applying a scaling
affine transformation to the root canvas group. The pixels_per_unit member of the
GnomeCanvas struct predates the canvass use of affines. Still, gnome_canvas_set_pixels_per_unit()
is a bit more convenient than the affine transform method, and it does work in GDK
mode. (Because GDK mode uses Xlib primitives, its nontrivial to implement arbitrary affine transformations; a future version of Gnome may do so, however.)
#include <libgnomeui/gnome-canvas.h>
void gnome_canvas_set_pixels_per_unit(GnomeCanvas* canvas, double ppu);
Canvas Items
Most of the time you will be interested in canvas items rather than the canvas itself.
Canvas items are typically very easy to use, compared to widgets; none of the standard items have any unique signals, since they are not interactive. (Since GnomeCanvasItem is a subclass of GtkObject, however, you could certainly have an item
with signals if you wanted to.) The GnomeCanvasItem base class has a single signal,
"event", which is used to convey all types of event. The "event" signal has no default
handler; canvas items do not respond to events unless you connect handlers of your
own. Figure 12-8 lists all the useful functions for working with the GnomeCanvasItem base class.
To create a canvas item, you use the generic gnome_canvas_item_new() (or gnome_canvas_item_newv()).
This function accepts the group to place the item in, the GtkType of the GnomeCanvasItem subclass to create, and finally a NULL-terminated list of arguments to set. The
argument list is purely for convenience, so you dont have to call gnome_canvas_item_set()
immediately. gnome_canvas_item_new() creates a new instance of the type with
gtk_type_new(), adds the item to its GnomeCanvasGroup, and schedules it to be
redrawn.
To destroy an item and remove it from the canvas, simply call gtk_object_destroy().
You can also use the standard reference counting mechanism with canvas items.
You can set an items affine using gnome_canvas_item_affine_absolute(), or compose a new affine with the items existing affine using gnome_canvas_item_affine_relative().
These functions can be used to translate, scale, or rotate a canvas item (however, scaling and rotation only work in antialiased mode).
Items in a group are normally stacked in the order you add them, with the most
recently-added item "on top" and the oldest item on the bottom. You can manipulate
the stacking order with gnome_canvas_item_raise() and gnome_canvas_item_lower().
These move an item up or down by the given number of positions. It is safe to pass
in a too-large value for positions; the item will be moved as far as possible and no
260
more. You can also request that an item is moved to one extreme or the other, using
gnome_canvas_item_raise_to_top() and gnome_canvas_item_lower_to_bottom.
Items can be shown and hidden; hidden items are not rendered by the canvas and do
not receive events. All items are visible by default. The routines are gnome_canvas_item_show()
and gnome_canvas_item_hide().
Reparenting a canvas item is straightforward; the only rule is that the new group
must be on the same canvas as the old group.
gnome_canvas_item_grab_focus() is analagous to gtk_widget_grab_focus(); it
sends all key events to the item with the grab. It also sends focus change events to
the item (when the item gains or loses the focus).
Canvas items can grab and ungrab the mouse pointer just as a GdkWindow can; the
arguments to gnome_canvas_item_grab() are exactly analagous to those of gdk_pointer_grab()
(see Chapter 10). While a canvas item has the pointer grabbed, no other item receives
events. Behind the scenes, GnomeCanvas uses gdk_pointer_grab() to implement
gnome_canvas_item_grab(), so an item grabbing the mouse away from other items
implies the canvas grabbing the mouse away from other widgets.
The visual properties of canvas items are manipulated almost entirely via object arguments. If you skipped Chapter 9, go back and read the section on object arguments
now. Two functions are used to set canvas item properties: gnome_canvas_item_set()
and gnome_canvas_item_setv(). These are almost but not quite equivalent to gtk_object_set()
and gtk_object_setv()they set object arguments in the same way, but they also
mark the canvas item to be redrawn. So you should prefer them to the GtkObject
variants. (This is something of a design bug, and future canvas versions will most
likely allow you to use gtk_object_set().)
gnome_canvas_item_request_update() marks the canvas item as "dirty" and queues
it to be redrawn. Internally, the canvas uses a one-shot idle function to perform redraws; that is, it waits until no more GTK+ events are pending, then redraws itself
a single time. It does this by installing an idle function with gtk_idle_add() and
removing it after it runs once. Thus gnome_canvas_item_request_update() can be
called many times without creating an efficiency problemit pretty much does nothing at all if an update is already pending.
#include <libgnomeui/gnome-canvas.h>
GnomeCanvasItem* gnome_canvas_item_new(GnomeCanvasGroup* parent, GtkType
type, const gchar* first_arg_name, ...);
GnomeCanvasItem* gnome_canvas_item_newv(GnomeCanvasGroup* parent, GtkType
type, guint nargs, GtkArg* args);
void gnome_canvas_item_set(GnomeCanvasItem* item, const gchar* first_arg_name,
...);
void gnome_canvas_item_setv(GnomeCanvasItem* item, guint nargs, GtkArg* args);
void gnome_canvas_item_affine_relative(GnomeCanvasItem* item, const double
affine[6]);
void gnome_canvas_item_affine_absolute(GnomeCanvasItem* item, const double
affine[6]);
void gnome_canvas_item_raise(GnomeCanvasItem* item, int positions);
void gnome_canvas_item_lower(GnomeCanvasItem* item, int positions);
void gnome_canvas_item_raise_to_top(GnomeCanvasItem* item);
void gnome_canvas_item_lower_to_bottom(GnomeCanvasItem* item);
void gnome_canvas_item_show(GnomeCanvasItem* item);
void gnome_canvas_item_hide(GnomeCanvasItem* item);
void gnome_canvas_item_reparent(GnomeCanvasItem* item, GnomeCanvasGroup*
261
new_group);
void gnome_canvas_item_grab_focus(GnomeCanvasItem* item);
int gnome_canvas_item_grab(GnomeCanvasItem* item, unsigned int event_mask,
GdkCursor* cursor, guint32 etime);
void gnome_canvas_item_ungrab(GnomeCanvasItem* item, guint32 etime);
void gnome_canvas_item_get_bounds(GnomeCanvasItem* item, double* x1, double* y1, double* x2, double* y2);
void gnome_canvas_item_request_update(GnomeCanvasItem* item);
Coordinates are automatically converted to canvas world coordinates. For example, if a canvas item receives an event of type GDK_BUTTON_PRESS, the x and y
fields of the event will be in world coordinates. (The raw event was received on the
canvass GdkWindow and thus had window coordinates.)
Enter/leave events are synthesized for canvas items as the mouse pointer moves
across the canvas.
Events are propagated up the canvas item hierarchy, until some items "event"
signal handler returns TRUE. This works just as it does with GtkWidget; events
are first sent to the bottommost or leaf canvas item, and eventually make it up to
the root item.
Only user-generated events are sent to canvas items; many events you might expect to receive on a GdkWindow, such as expose and configure events, are not
forwarded to canvas items.
The canvas does this work behind the scenes, so item events work intuitively and
much like normal GDK events.
A canvas item event callback looks like this:
static gint
item_event_callback(GnomeCanvasItem* item,
GdkEvent* event,
gpointer data)
{
switch (event->type) {
case GDK_BUTTON_PRESS:
break;
case GDK_MOTION_NOTIFY:
break;
case GDK_BUTTON_RELEASE:
break;
default:
break;
262
}
/* Returning FALSE propagates the event to parent items;
* returning TRUE ends event propagation.
*/
return FALSE;
}
Of course, a real callback would probably examine the contents of the event and take
some action in response to some of them.
A Canvas Example
This section gives a brief example program, demonstrating the user of the canvas.
It does not explain the particulars of the canvas items being created; see the section
called Standard Canvas Item Reference for that. Figure 12-9 shows the example program
in action. You can drag canvas items around the screen with the left mouse button;
clicking an item with the Shift key held down destroys it.
263
gtk_widget_push_visual(gdk_rgb_get_visual());
gtk_widget_push_colormap(gdk_rgb_get_cmap());
canvas = gnome_canvas_new_aa();
gtk_widget_pop_colormap();
gtk_widget_pop_visual();
gnome_canvas_set_scroll_region(GNOME_CANVAS(canvas), 0, 0, 600, 450);
create_canvas_items(canvas);
gtk_container_add(GTK_CONTAINER(sw), canvas);
gtk_container_add(GTK_CONTAINER(window), sw);
gtk_window_set_default_size(GTK_WINDOW(window), 300, 300);
gtk_widget_show_all(window);
gtk_main();
return 0;
}
static gint
delete_event_cb(GtkWidget* window, GdkEventAny* e, gpointer data)
{
gtk_main_quit();
return FALSE;
}
Once the canvas has been created, the program adds some items to it, and connects a
simple callback to the items "event" signal. Heres the code:
static gint
item_event(GnomeCanvasItem *item, GdkEvent *event, gpointer data)
{
static double x, y;
double new_x, new_y;
GdkCursor *fleur;
264
265
setup_item(GnomeCanvasItem *item)
{
gtk_signal_connect(GTK_OBJECT(item), "event",
(GtkSignalFunc) item_event,
NULL);
}
static void
create_canvas_items(GtkWidget* canvas)
{
GnomeCanvasPoints* points;
GnomeCanvasGroup* group;
GnomeCanvasItem* item;
double affine[6];
group = gnome_canvas_root(GNOME_CANVAS(canvas));
/* A polygon */
points = gnome_canvas_points_new(14);
points->coords[0] = 270.0;
points->coords[1] = 330.0;
points->coords[2] = 270.0;
points->coords[3] = 430.0;
points->coords[4] = 390.0;
points->coords[5] = 430.0;
points->coords[6] = 390.0;
points->coords[7] = 330.0;
points->coords[8] = 310.0;
points->coords[9] = 330.0;
points->coords[10] = 310.0;
points->coords[11] = 390.0;
points->coords[12] = 350.0;
points->coords[13] = 390.0;
points->coords[14] = 350.0;
points->coords[15] = 370.0;
points->coords[16] = 330.0;
points->coords[17] = 370.0;
points->coords[18] = 330.0;
points->coords[19] = 350.0;
points->coords[20] = 370.0;
points->coords[21] = 350.0;
points->coords[22] = 370.0;
points->coords[23] = 410.0;
points->coords[24] = 290.0;
points->coords[25] = 410.0;
points->coords[26] = 290.0;
points->coords[27] = 330.0;
item = gnome_canvas_item_new(group,
gnome_canvas_polygon_get_type (),
"points", points,
"fill_color", "tan",
"outline_color", "black",
"width_units", 3.0,
NULL);
setup_item(item);
gnome_canvas_points_unref(points);
/* Translate the polygon */
266
267
Type
double
Read/Write
Both
Description
Leftmost coordinate
y1
double
Both
Topmost coordinate
x2
double
Both
y2
double
Both
fill_color
gchar*
Write-only
Rightmost
coordinate
Bottommost
coordinate
Fill color; string for
gdk_color_parse(),
or NULL for
transparent
fill_color_gdk
GdkColor*
Both
fill_color_rgba
guint32
Both
outline_color
gchar*
Write-only
268
Name
outline_color_gdk
Type
GdkColor*
Read/Write
Both
outline_color_rgba
guint32
Both
fill_stipple
GdkBitmap*
Both
outline_stipple
GdkBitmap*
Both
width_pixels
guint
Write-only
width_units
double
Write-only
Description
Outline color;
specified as
already-allocated
GdkColor
Outline color;
specified as 32-bit
value packing red,
green, blue, and
alpha into bytes 1, 2,
3, and 4; alpha of 255
is opaque, 0 is
invisible
Stipple to use when
drawing fill; GDK
mode only
Stipple to use when
drawing outline;
GDK mode only
Width of the
outline, in pixels
(independent of
zoom)
Width of the
outline, in canvas
units; pixel width
changes with zoom
factor (pixels per
unit)
Line Item
GnomeCanvasLine represents one or more line segments joined at their endpoints.
You can use it to represent an unfilled polygon as well. GnomeCanvasPolygon is
used for filled polygons.
A line is specified using a GnomeCanvasPoints structure, which looks like this:
typedef struct {
int num_points;
double *coords;
int ref_count;
} GnomeCanvasPoints;
The coords field contains an array of points, alternating X and Y coordinates. You fill
the coords array directly, after creating a GnomeCanvasPoints with gnome_canvas_points_new();
the structure should be destroyed with gnome_canvas_points_unref().
Lines can have arrowheads on either end; the arrowhead shape is specified via three
parameters, arbitrarily named A, B, and C. Parameter A (specified with the arrow_shape_a
argument) specifies the distance from the base of the arrowhead to the tip. B specifies
the distance from the tip of the arrowhead to one of the trailing points; C specifies
the distance of a trailing point from the outer edge of the line.
269
Type
GnomeCanvasPoints*
Read/Write
Both
fill_color
gchar*
Write-only
Description
Points in the line
Fill color; string for
gdk_color_parse()
270
fill_color_gdk
GdkColor*
Both
fill_color_rgba
guint32
Both
fill_stipple
GdkBitmap*
Both
width_pixels
guint
Write-only
width_units
double
Write-only
cap_style
GdkCapStyle
Both
join_style
GdkJoinStyle
Both
line_style
GdkLineStyle
Both
first_arrowhead
gboolean
Both
last_arrowhead
gboolean
Both
smooth
gboolean
Both
spline_steps
guint
Both
arrow_shape_a
double
Both
Name
arrow_shape_b
Type
double
Read/Write
Both
arrow_shape_c
double
Both
Description
Length of
arrowhead edges
(tip to trailing
points)
Width of arrowhead
Polygon Item
GnomeCanvasPolygon represents a filled polygon; it can be filled or only an outline. Unlike GnomeCanvasRE, an unfilled GnomeCanvasPolygon is not "hollow";
the transparent portion in the center is part of the canvas item. GnomeCanvasLine
is used for "hollow" polygons.
Table 12-3. GnomeCanvasPolygon Arguments
Name
points
fill_color
Type
GnomeCanvasPoints*
gchar*
Read/Write
Both
Write-only
Description
Points in the
polygon
Fill color; string for
gdk_color_parse(),
or NULL for
transparent
fill_color_gdk
GdkColor*
Both
fill_color_rgba
guint32
Both
outline_color
gchar*
Write-only
outline_color_gdk
GdkColor*
Both
Outline color;
specified as
already-allocated
GdkColor
271
Name
outline_color_rgba
Type
guint32
Read/Write
Both
fill_stipple
GdkBitmap*
Both
outline_stipple
GdkBitmap*
Both
width_pixels
guint
Write-only
width_units
double
Write-only
Description
Outline color;
specified as 32-bit
value packing red,
green, blue, and
alpha into bytes 1, 2,
3, and 4; alpha of 255
is opaque, 0 is
invisible
Stipple to use when
drawing fill; GDK
mode only
Stipple to use when
drawing outline;
GDK mode only
Width of the
outline, in pixels
(independent of
zoom)
Width of the
outline, in canvas
units; pixel width
changes with zoom
factor (pixels per
unit)
Image Item
GnomeCanvasImage places an image on the canvas; you pass it a GdkImlibImage,
loaded using one of the Imlib routines. If the image has transparent areas, they will
be properly handled (they wont be considered part of the item, and will not receive
events). To use GnomeCanvasImage with a GDK canvas, you must push the Imlib
visual and colormap before creating the canvas; see the section called Preparing the
GnomeCanvas Widget.
Table 12-4. GnomeCanvasImage Arguments
272
Name
image
Type
GdkImlibImage*
Read/Write
Both
double
Both
double
Both
anchor
GtkAnchorType
Both
width
double
Both
Description
GdkImlibImage to
display
X coordinate of the
anchor point
Y coordinate of the
anchor point
Location of anchor
point
Width in canvas
units (image will be
scaled)
Name
height
Type
double
Read/Write
Both
Description
Height in canvas
units (image will be
scaled)
Text Item
GnomeCanvasText displays a text string. You can specify the coordinates of the string
as an ordered pair; these coordinates will represent the location of the texts anchor.
For example, if the "anchor" argument is set to GTK_ANCHOR_NORTH, the text
items coordinates will represent the location of the top-center of the item. That is,
the text will be centered around the X position and begin just below the Y position.
Possible anchor values are:
GTK_ANCHOR_CENTER
GTK_ANCHOR_NORTH
GTK_ANCHOR_NORTH_WEST
GTK_ANCHOR_NORTH_EAST
GTK_ANCHOR_SOUTH
GTK_ANCHOR_SOUTH_WEST
GTK_ANCHOR_SOUTH_EAST
GTK_ANCHOR_WEST
GTK_ANCHOR_EAST
273
Type
gchar*
double
Read/Write
Both
Both
double
Both
anchor
GtkAnchorType
Both
font
gchar*
Write-only
Description
String to display
X coordinate of the
anchor point
Y coordinate of the
anchor point
Location of anchor
point
Font name for
gdk_font_load()
fontset
gchar*
Write-only
font_gdk
GdkFont*
Both
justification
GtkJustification
Both
fill_color
gchar*
Write-only
274
fill_color_gdk
GdkColor*
Both
fill_color_rgba
guint32
Both
fill_stipple
GdkBitmap*
Both
clip_width
double
Both
clip_height
double
Both
clip
gboolean
Both
x_offset
double
Both
y_offset
double
Both
text_width
double
Read-only
Name
text_height
Type
double
Read/Write
Read-only
Description
Height of rendered
text
Widget Item
The GnomeCanvasWidget item places a widget on the canvas. The canvas item emulates a container widget, passing a size allocation to the widget it holds. You can
specify an anchor point for the widget item, just as you can for GnomeCanvasText.
Table 12-6. GnomeCanvasWidget Arguments
Name
widget
x
Type
GtkWidget*
double
Read/Write
Both
Both
double
Both
anchor
GtkAnchorType
Both
width
height
size_pixels
double
double
gboolean
Both
Both
Both
Description
Widget to display
X coordinate of the
anchor point
Y coordinate of the
anchor point
Location of anchor
point
Width of widget
Height of widget
Specifies how to
interpret the width
and height
argument; if TRUE,
they are in pixels; if
FALSE, they are in
canvas units
275
Overview
To write a GnomeCanvasItem, you create a concrete implemenation of the GnomeCanvasItem abstract base class. This chapter assumes youve read Chapter 9 and understand how a GtkObject works; you will need to understand objects to write your
own.
Canvas items can support GDK mode, antialiased mode, or both. The canvas has a
flag indicating which kind of canvas it is; items can check this flag at runtime:
if (item->canvas->aa)
{
/* antialiased mode */
}
else
{
/* Gdk mode */
}
However, most code will be the same for both canvas types. The only real difference
is in the drawing process: GDK mode draws to a pixmap, antialiased mode draws to
an RGB buffer. You do not have to support both kinds of canvas, just be careful not
to use your item with the unsupported canvas type.
Here is the GnomeCanvasItem type you will be subclassing:
typedef struct _GnomeCanvasItem
typedef struct _GnomeCanvasItemClass
GnomeCanvasItem;
GnomeCanvasItemClass;
struct _GnomeCanvasItem {
GtkObject object;
/* Canvas we are on */
GnomeCanvas *canvas;
/* Parent group */
GnomeCanvasItem *parent;
/* Bounding box for this item */
double x1, y1, x2, y2;
/* If NULL, the identity transform */
double *xform;
};
struct _GnomeCanvasItemClass {
GtkObjectClass parent_class;
void (* update) (GnomeCanvasItem *item, double *affine,
ArtSVP *clip_path, int flags);
276
GnomeCanvasRect
GnomeCanvasRect and GnomeCanvasEllipse have almost identical implementations;
in fact, all but three of GnomeCanvasItems methods are implemented by the GnomeCanvasRE base class. GnomeCanvasRE handles their user-visible interface, as discussed in the previous chapter.
To understand the implementation of GnomeCanvasRect presented in this chapter,
you should first read the previous chapters discussion of the object arguments it
supports. Youll also want to see the object itself:
typedef struct _GnomeCanvasRE GnomeCanvasRE;
struct _GnomeCanvasRE {
GnomeCanvasItem item;
double x1, y1, x2, y2;
double width;
guint fill_color;
guint outline_color;
gulong fill_pixel;
/* Fill color */
277
gulong outline_pixel;
/* Outline color */
GdkBitmap *fill_stipple;
GdkBitmap *outline_stipple;
GdkGC *fill_gc;
GdkGC *outline_gc;
/* GC for filling */
/* GC for outline */
/* Configuration flags */
unsigned int fill_set : 1;
/* Is fill color set? */
unsigned int outline_set : 1; /* Is outline color set? */
unsigned int width_pixels : 1;/* Is outline width specified in pixels or units? */
};
Drawing Methods
The most important task of any canvas item is rendering itself onto the canvas. Rendering is a two-stage process for efficiency reasons. The first stage, implemented in a
GnomeCanvasItems update method, is guaranteed to happen only once per item per
rendering cycle; the idea is to do any expensive affine transformations or other calculations in the update method. In the second stage, the canvas item renders itself to
some region on the screen. The render method implements stage two for antialiased
items, while the draw method implements stage two for GDK items. An items render or draw method may be invoked multiple times during a canvas repaint.
Rendering occurs in a one-shot idle function. That is, whenever the canvas receives
an expose event or otherwise determines that a redraw is needed, it adds an idle
function which removes itself after a single invocation. (An idle function runs when
no GTK+ events are pending and the flow of execution is in the GTK+ main loopsee
the section called The Main Loop in Chapter 3 for details.) The canvas maintains a list
of redraw regions and adds to it whenever a redraw request is received, so it knows
which areas to repaint when the idle handler is finally invoked.
Canvas items carry a flag indicating whether they need to be updated. Whenever a
canvas item "changes" (for example, if you set a new fill color for GnomeCanvasRect),
it will call gnome_canvas_item_request_update() to set the "update needed" flag
for itself and the groups that contain it, up to and including the root canvas group.
(The GnomeCanvas widget is only aware of a single canvas item, the root groupall
other items are handled recursively when methods are invoked on the root group.) In
its one-shot idle function, the canvas invokes the update method of the root canvas
item if its update flag is set, then clears the flag so the update method will not be run
278
next time. The GnomeCanvasGroup update method does the same for each child
item.
Once all canvas items have been updated, the rendering process begins. The canvas
creates an RGB or GdkPixmap buffer, converts its list of redraw regions into a list of
buffer-sized rectangles, then invokes the render or draw method of the root canvas
group once per rectangle. After each rectangle is rendered, the buffer is copied to the
screen.
279
ART_MOVETO;
- halfwidth;
- halfwidth;
ART_LINETO;
- halfwidth;
+ halfwidth;
ART_LINETO;
+ halfwidth;
+ halfwidth;
ART_LINETO;
+ halfwidth;
- halfwidth;
ART_LINETO;
- halfwidth;
- halfwidth;
280
vpath[i].x = 0;
vpath[i].y = 0;
vpath2 = art_vpath_affine_transform (vpath, affine);
As you can see, the first thing this function does is invoke an update function shared
by GnomeCanvasRect and GnomeCanvasEllipse; here is that function:
static void
gnome_canvas_re_update_shared (GnomeCanvasItem *item, double *affine,
ArtSVP *clip_path, int flags)
{
GnomeCanvasRE *re;
re = GNOME_CANVAS_RE (item);
if (re_parent_class->update)
(* re_parent_class->update) (item, affine, clip_path, flags);
if (!item->canvas->aa) {
set_gc_foreground (re->fill_gc, re->fill_pixel);
set_gc_foreground (re->outline_gc, re->outline_pixel);
set_stipple (re->fill_gc, &re->fill_stipple,
re->fill_stipple, TRUE);
set_stipple (re->outline_gc, &re->outline_stipple,
re->outline_stipple, TRUE);
set_outline_gc_width (re);
}
}
There is a lot of code involved here; the update method is almost always the most
complicated one, since it does all the work of preparing to render a canvas item.
Also, the update method is different for GDK and antialiased mode; notice the code
which depends on the item->canvas->aa flag.
The first thing GnomeCanvasRE does during an update is invoke the update method
of its parent class. The GnomeCanvasItem default update method does nothing whatsoever in Gnome 1.0, but it is good practice to chain up for future robustness. Then,
GnomeCanvasRE calls a series of utility routines to fill in its graphics contexts with
their correct values. These are straightforward functions, so their implementations
are omitted here.
Next gnome_canvas_rect_update() continues with GnomeCanvasRect-specific details. Several tasks are accomplished:
The bounding box of the canvas item is updated. Every canvas item has an associated bounding box; the GnomeCanvasGroup draw and render methods use this
281
box to determine which items are in the redraw region. The bounding box must be
updated in both GDK and antialiased mode.
In antialiased mode, a sorted vector path is created. A sorted vector path is simply
a series of drawing instructions, similar to primitive PostScript operations, that
libart_lgpl can render to an RGB buffer.
In antialiased mode, the affine and clip_path arguments to the update method are
used to transform the sorted vector path; thus the affine and clip path are implicitly
stored for use in the render method. If you do not use libart_lgpls sorted vector
paths in your own canvas items, you must arrange some other way to ensure the
affine and clip are taken into account when you render.
In both modes, a redraw is requested for both the region the item used to occupy,
and the region the item will now occupy.
Much of this work takes place behind the scenes in utility functions from libgnomeui/gnomecanvas-util.h. gnome_canvas_update_bbox() sets the items new bounding box
and requests a redraw on both the old and new bounding boxes; it is used in GDK
mode. (gnome_canvas_update_bbox() expects canvas pixel coordinates; get_bounds()
is a trivial function which computes the rectangles bounds in canvas pixel coordinates.)
So you know whats happening behind the scenes, here is the implementation of
gnome_canvas_update_bbox():
void
gnome_canvas_update_bbox (GnomeCanvasItem *item,
int x1, int y1,
int x2, int y2)
{
gnome_canvas_request_redraw (item->canvas,
item->x1, item->y1,
item->x2, item->y2);
item->x1 = x1;
item->y1 = y1;
item->x2 = x2;
item->y2 = y2;
gnome_canvas_request_redraw (item->canvas,
item->x1, item->y1,
item->x2, item->y2);
}
Of course youre free to do the equivalent yourself, this is merely a convenience function.
In GDK mode, thats about all that happens; we update the bounds and then return.
Antialiased mode is a bit more complex, but essentially the same tasks are performed.
First, gnome_canvas_item_reset_bounds() sets the items bounds back to an empty
rectangle. Then, two sorted vector paths are prepared; one for the solid part of the
rectangle (if any), and one for the rectangles outline (if any). The same procedure
is followed each time. First, a vector path for libart_lgpl is prepared; next, the
path is affine transformed; then gnome_canvas_item_update_svp_clip() is used
to request a redraw on the old path, free the old path, clip the new path, request a
redraw on the new one, and save the new one for use in rendering. If the rectangles
fill or outline has been turned off, a redraw is requested on the old vector path, but
no new path is created.
To give you a clearer idea what is happening, here is the implementation of gnome_canvas_item_update_sv
void
282
and gnome_canvas_item_update_svp():
void
gnome_canvas_item_update_svp (GnomeCanvasItem *item,
ArtSVP **p_svp, ArtSVP *new_svp)
{
ArtDRect bbox;
gnome_canvas_update_svp (item->canvas, p_svp, new_svp);
if (new_svp)
{
bbox.x0 = item->x1;
bbox.y0 = item->y1;
bbox.x1 = item->x2;
bbox.y1 = item->y2;
art_drect_svp_union (&bbox, new_svp);
item->x1 = bbox.x0;
item->y1 = bbox.y0;
item->x2 = bbox.x1;
item->y2 = bbox.y1;
}
}
283
}
else if (old_svp != NULL)
{
repaint_uta = art_uta_from_svp (old_svp);
art_svp_free (old_svp);
gnome_canvas_request_redraw_uta (canvas, repaint_uta);
}
*p_svp = new_svp;
}
Requesting Updates
It is the canvas items responsibility to request an update or redraw when the properties of the item are changed and the screen should be refreshed. This is straightforward. For example, here is a snippet of code from gnome_canvas_re_set_arg(),
which sets the "y2" argument:
case ARG_Y2:
re->y2 = GTK_VALUE_DOUBLE (*arg);
gnome_canvas_item_request_update (item);
break;
Since "y2" modifies the shape of the rectangle, the path must be recreated and an
update is necessary. Note that gnome_canvas_item_request_update() simply sets
a flag and installs an idle handler if none is pending, so it can be called many times
without a performance penalty.
Not all changes require an update; a redraw may be sufficient, or perhaps the argument is unrelated to the display. It depends on the canvas item and what exactly is
being changed.
284
if (re->fill_svp != NULL) {
gnome_canvas_render_svp (buf, re->fill_svp, re->fill_color);
}
if (re->outline_svp != NULL) {
gnome_canvas_render_svp (buf, re->outline_svp, re->outline_color);
}
}
As you can see, most of the work takes place in gnome_canvas_render_svp(), another function from libgnomeui/gnome-canvas-util.h; here is its implementation:
void
gnome_canvas_render_svp (GnomeCanvasBuf *buf, ArtSVP *svp, guint32 rgba)
{
guint32 fg_color, bg_color;
if (buf->is_bg) {
bg_color = buf->bg_color;
fg_color = rgba >> 8;
art_rgb_svp_aa (svp,
buf->rect.x0, buf->rect.y0, buf->rect.x1, buf->rect.y1,
fg_color, bg_color,
buf->buf, buf->buf_rowstride,
NULL);
buf->is_bg = 0;
buf->is_buf = 1;
} else {
art_rgb_svp_alpha (svp,
buf->rect.x0, buf->rect.y0, buf->rect.x1, buf>rect.y1,
rgba,
buf->buf, buf->buf_rowstride,
NULL);
}
}
To understand gnome_canvas_render_svp(), or to do your own RGB buffer drawing (without using libart_lgpl), you will need to know what a GnomeCanvasBuf
is:
typedef struct {
guchar *buf;
int buf_rowstride;
ArtIRect rect;
guint32 bg_color;
unsigned int is_bg : 1;
unsigned int is_buf : 1;
} GnomeCanvasBuf;
The buf member is an RGB buffer, as explained in the section called RGB Buffers in
Chapter 10. The buf_rowstride is the buffers rowstride, also explained in the section
called RGB Buffers in Chapter 10. An ArtIRect is an integer rectangle; rect defines
285
the redraw region in canvas pixel coordinates that this buffer represents. rect.x0 and
rect.y0 are the buffer offsets and correspond to row 0, column 0 in the RGB buffer; you
can convert from canvas pixel coordinates to RGB buffer coordinates by subtracting
these values. rect.x1 and rect.y1 are not part of the redraw area, but rather its
bounds. That is, the X coordinates in the rectangle are greater than or equal to rect.x0
and less than rect.x1.
As an optimization, the canvas does not initialize the RGB buffer with the background color, because the first canvas item might cover the entire background anyway. Thus, if your canvas item is the first one to render, you must put some pixel
value in every pixel of the redraw region defined by the buffers rect. If your item
does not cover a pixel, you should fill that pixel with the bg_color; bg_color is a
packed RGB value (no alpha). If you do this manually, unpack an RGB value rgb like
this:
guchar r, g, b;
r = (rgb >> 16) & 0xff;
g = (rgb >> 8) & 0xff;
b = rgb & 0xff;
286
287
The draw method receives a drawable (the buffer), the buffer offsets (x and ythe
canvas pixel coordinates of the buffer), and the buffers size (width and height).
GnomeCanvasRects draw method obtains the item-to-world and world-to-canvas
affines, then composes (multiplies) them to create an item-to-canvas affine. (See the
section called Affine Transformations in Chapter 12 for more on affines.) Using this
affine, it converts the rectangles corner points to canvas pixel coordinates; then it
draws the rectangle, converting the canvas coordinates to buffer coordinates by subtracting the buffer offsets.
Other Methods
This section describes the remaining GnomeCanvasItem methods, including event,
point, bounds, realize, unrealize, map, and unmap.
288
Events
The GnomeCanvasItem class has a slot in its vtable called event; this is the only
GnomeCanvasItem class function associated with a signal. None of the stock canvas items implement a default handler for event, but of course your own canvas item
could.
The return value of event works just like the GtkWidget "event" signal; if the last
signal handler returns FALSE, the event is propagated to the items parent item (by
emitting the event signal on the parent), if TRUE propagation ends.
Point
The point method is used to determine which canvas item is located at a given point.
The canvas uses this information to decide which item should receive events. A point
method calculates the distance from some point to the canvas item. Canvas items
must correctly report a distance of 0 if the point is on the canvas item, or they will not
receive events; they must report non-zero if the point is not on the item, or they will
receive too many events. The exact value returned is not nearly as important as the
zero/non-zero distinction.
For convenience, the point method receives the same point pre-translated into both
item and canvas pixel coordinates.
The point method also receives a pointer to a pointer to a GnomeCanvasItem; nongroup canvas items should store a pointer to themselves in this space. Groups store
the *actual_item received from the topmost child which returns 0 from its point
method. If you think about it for a while, you will see the implication: the root canvas groups point method stores a pointer to the deepest child in the item tree at the
point in question. The canvas sends events occurring at that point to this most-junior
child. Note that the canvas item tree corresponds to the item stacking order (i.e. the
root group is on the bottom), so events go to the topmost items, as you might expect.
Remember that events are then propagated up the item tree hierarchy.
Here is the point method for GnomeCanvasRect:
static double
gnome_canvas_rect_point (GnomeCanvasItem *item,
double x, double y, int cx, int cy,
GnomeCanvasItem **actual_item)
{
GnomeCanvasRE *re;
double x1, y1, x2, y2;
double hwidth;
double dx, dy;
double tmp;
re = GNOME_CANVAS_RE (item);
*actual_item = item;
/* Find the bounds for the rectangle plus its outline width */
x1
y1
x2
y2
=
=
=
=
re->x1;
re->y1;
re->x2;
re->y2;
if (re->outline_set) {
if (re->width_pixels)
289
It should be obvious how this function works; it is simple geometry. Again, notice
the line:
290
*actual_item = item;
If your item isnt receiving any events, make sure you included a similar statement.
Bounds
The bounds method computes the approximate bounding box of a canvas item. In
Gnome 1.0, this method is only used in gnome_canvas_item_get_bounds(), a uservisible function to return the bounds of a canvas item. The canvas does not use it at
all internally, and most likely you could get away without implementing it, though
all the stock items do.
The function should return an items bounding box in item coordinates; here is the
GnomeCanvasRE version:
static void
gnome_canvas_re_bounds (GnomeCanvasItem *item,
double *x1, double *y1,
double *x2, double *y2)
{
GnomeCanvasRE *re;
double hwidth;
re = GNOME_CANVAS_RE (item);
if (re->width_pixels)
hwidth = (re->width / item->canvas->pixels_per_unit) / 2.0;
else
hwidth = re->width / 2.0;
*x1
*y1
*x2
*y2
=
=
=
=
re->x1
re->y1
re->x2
re->y2
+
+
hwidth;
hwidth;
hwidth;
hwidth;
291
if (re_parent_class->realize)
(* re_parent_class->realize) (item);
if (!item->canvas->aa) {
re->fill_gc = gdk_gc_new (item->canvas->layout.bin_window);
re->outline_gc = gdk_gc_new (item->canvas->layout.bin_window);
}
}
And unrealize:
static void
gnome_canvas_re_unrealize (GnomeCanvasItem *item)
{
GnomeCanvasRE *re;
re = GNOME_CANVAS_RE (item);
if (!item->canvas->aa) {
gdk_gc_unref (re->fill_gc);
gdk_gc_unref (re->outline_gc);
}
if (re_parent_class->unrealize)
(* re_parent_class->unrealize) (item);
}
Note that your realize and unrealize methods are unlikely to have anything to do in
antialiased mode, since there wont be any GDK resources to worry about.
GtkObject Methods
Of course, any canvas item subclass must implement the usual GtkObject methods, including destroy if the object allocates resources that need cleaning up, and
a get_arg/set_arg pair if the object defines any arguments. The only canvas-itemspecific concern is that you must schedule an update or redraw as needed if set_arg
changes the properties of the canvas item. These functions are quite long due to the
number of arguments, but not very interesting, so they are omitted here. See the full
GnomeCanvasRect source code if youre curious.
292
Hierarchy Summary
GtkBin
|
+GtkButton
|
+GnomeColorPicker
|
+GnomeFontPicker
|
+GnomeHRef
|
+GtkToggleButton
|
+GtkOptionMenu
This would be for GtkButton. The parent of the object (if any) is shown, then the
object itself (possibly highlighted or in bold), then the immediate children of the object,
if any. The second element that might be nice: some of the objects are "immature" or
"unstable", which is a sort of mild warning suggesting to programmers that they may
not want to use the object. It might be nice to have some sort of icon or margin text
used to mark those objects.
GtkObject
|
+GtkWidget
| |
293
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
294
+GtkContainer
| |
| +GtkBin
| | |
| | +GtkWindow
| | | |
| | | +GnomeDialog
| | | | |
| | | | +GnomeAbout
| | | | |
| | | | +GnomeMessageBox
| | | | |
| | | | +GnomePropertyBox
| | | | |
| | | | GnomeScores
| | | |
| | | +GnomeApp
| | | |
| | | +GtkDialog
| | | | |
| | | | +GnomeFontSelector
| | | | |
| | | | GtkInputDialog
| | | |
| | | +GtkColorSelectionDialog
| | | |
| | | +GtkFileSelection
| | | |
| | | +GtkFontSelectionDialog
| | | |
| | | GtkPlug
| | |
| | +GtkButton
| | | |
| | | +GnomeColorPicker
| | | |
| | | +GnomeFontPicker
| | | |
| | | +GnomeHRef
| | | |
| | | +GtkToggleButton
| | | | |
| | | | GtkCheckButton
| | | |
|
| | | |
GtkRadioButton
| | | |
| | | GtkOptionMenu
| | |
| | +GnomeDockItem
| | |
| | +GtkAlignment
| | |
| | +GtkFrame
| | | |
| | | GtkAspectFrame
| | |
| | +GtkItem
| | | |
| | | +GtkMenuItem
| | | | |
| | | | +GtkCheckMenuItem
| | | | | |
| | | | | GtkRadioMenuItem
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| | | |
| | | +GtkPixmapMenuItem
| | | |
| | | GtkTearoffMenuItem
| | |
| | +GtkListItem
| | |
| | GtkTreeItem
| |
| +GtkEventBox
| |
| +GtkHandleBox
| |
| +GtkScrolledWindow
| |
| GtkViewport
|
+GtkBox
| |
| +GtkHBox
| | |
| | +GnomeAppBar
| | |
| | +GnomeDateEdit
| | |
| | +GtkCombo
| | | |
| | | GnomeEntry
| | |
| | +GnomeFileEntry
| | |
| | +GnomeNumberEntry
| | |
| | +GnomeProcBar
| | |
| | GtkStatusbar
| |
| +GtkVBox
| | |
| | +GnomeCalculator
| | |
| | +GnomeGuru
| | |
| | +GnomeIconEntry
| | |
| | +GnomeIconSelection
| | |
| | +GnomeLess
| | |
| | +GnomePaperSelector
| | |
| | +GnomePixmapEntry
| | |
| | +GnomeSpell
| | |
| | +GtkColorSelection
| | |
| | GtkGammaCurve
| |
| GtkButtonBox
|
|
|
+GtkHButtonBox
|
|
295
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
296
| |
GtkVButtonBox
| |
| +GtkLayout
| | |
| | GnomeCanvas
| |
|
| |
GnomeIconList
| |
| +GnomeDockBand
| |
| +GnomeDock
| |
| +GtkCList
| | |
| | GtkCTree
| |
| +GtkFixed
| |
| +GtkNotebook
| | |
| | GtkFontSelection
| |
| +GtkPaned
| | |
| | +GtkHPaned
| | |
| | GtkVPaned
| |
| +GtkList
| |
| +GtkMenuShell
| | |
| | +GtkMenuBar
| | |
| | GtkMenu
| |
| +GtkPacker
| |
| +GtkSocket
| |
| +GtkTable
| | |
| | GtkTed
| |
| +GtkToolbar
| |
| GtkTree
|
+GnomeAnimator
|
+GnomePixmap
| |
| GnomeStock
|
+GtkMisc
| |
| +GtkLabel
| | |
| | +GtkAccelLabel
| | |
| | +GtkClock
| | |
| | GtkTipsQuery
| | |
| | +GtkArrow
| | |
| | +GtkImage
| | |
| | GtkPixmap
| |
| +GtkCalendar
| |
| +GtkDrawingArea
| | |
| | GtkCurve
| |
| +GtkDial
| |
| +GtkEditable
| | |
| | +GtkEntry
| | | |
| | | GtkSpinButton
| | |
| | GtkText
| |
| +GtkRuler
| | |
| | +GtkHRuler
| | |
| | GtkVRuler
| |
| +GtkRange
| | |
| | +GtkScale
| | | |
| | | +GtkHScale
| | | |
| | | GtkVScale
| | |
| | GtkScrollbar
| |
|
| |
+GtkHScrollbar
| |
|
| |
GtkVScrollbar
| |
| +GtkSeparator
| | |
| | +GtkHSeparator
| | |
| | GtkVSeparator
| |
| +GtkPreview
| |
| +GtkProgress
| | |
| | GtkProgressBar
| |
| ZvtTerm
|
+GnomeCanvasItem
| |
| +GnomeCanvasRE
| | |
| | +GnomeCanvasEllipse
| | |
297
| | GnomeCanvasRect
| |
| +GnomeCanvasGroup
| |
| +GnomeCanvasImage
| |
| +GnomeCanvasLine
| |
| +GnomeCanvasPolygon
| |
| +GnomeCanvasText
| |
| +GnomeCanvasWidget
| |
| GnomeIconTextItem
|
+GnomeClient
|
+GnomeDEntryEdit
|
+GnomeDockLayout
|
+GnomeMDIChild
| |
| GnomeMDIGenericChild
|
+GnomeMDI
|
+GtkData
| |
| +GtkAdjustment
| |
| GtkTooltips
|
GtkItemFactory
GtkObject
GtkObject
Library
GTK+
Header File
gtk/gtkobject.h
298
Description
GtkObject is the base of GTK+s object hierarchy. It is not a graphical component; it
implements interfaces for reference counting, attaching key-value pairs to objects and
object destruction ("virtual destructors" in C++ terms). GtkObject itself makes heavy
use of the GTK+ type system. The signal/callback infrastructure of GTK+ works in
terms of GtkObjectthat is, signals are emitted from a particular GtkObject, and callbacks are connected to a particular object and signal.
Chapter 9 covers GtkObject in detail.
Widgets
Widgets are the reason for GTK+s existence. Widgets are subclasses of GtkWidget,
which is in turn a subclass of GtkObject. A widget represents a rectangular region
on the screen, and may be purely decorative, an interactive control, or a container
controlling the arrangement of child widgets. Chapter 3 introduces GTK+ and thus
widgets; Chapter 11 covers widget implementation and concepts in more detail.
GtkWidget
Library
GTK+
Header File
gtk/gtkwidget.h
Description
GtkWidget is the parent class of all widgets. Chapters Chapter 3 and Chapter 11 de-
GtkContainer
Library
GTK+
Header File
gtk/gtkcontainer.h
299
Description
GtkContainer is the abstract base class for widgets that can contain other widgets.
the section called Containers And Widget Layout in Chapter 3 describes containers in
some detail; Chapter 11 includes information on container widget implementation.
GtkBin
Library
GTK+
Header File
gtk/gtkbin.h
Description
GtkBin is an abstract base class for containers with one child. It provides default
implementions of the GtkContainer interface, so it is very easy to subclass. Chapter
11 describes how to implement a GtkBin subclass.
GtkWindow
Library
GTK+
Header File
gtk/gtkwindow.h
Description
GtkWindow represents a toplevel dialog or application window. As the primary toplevel
widget in GTK+, it has many special responsibilities; for example, it maintains the
current keyboard focus and determines its own size allocation (rather than receiving
one from a parent widget).
Gnome applications typically use GnomeApp for main application windows, to take
advantage of its added features; for dialogs, you should use GnomeDialog with Gnome
and GtkDialog with GTK+. Of course there are several specialized dialog subclasses
available as well. If none of GtkWindows subclasses seem appropriate to your application, GtkWindow can also be used directly.
A danger worthy of note: GtkWindow is automatically destroyed if it receives a "delete_event"
signal. To prevent this, you must install the last signal handler to run, and your signal
300
handler must return TRUE. This is a very common GTK+ programming mistake; see
the section called Window Change Events in Chapter 10 for details. GnomeDialog will
help you handle this situation; see Chapter 7.
It is a good idea to make GtkWindow the last container you call gtk_widget_show()
on. Most widgets are not actually mapped (placed onscreen) until their parent container is; but GtkWindow has no parent, and appears immediately. So if you show its
children after youve shown the window, you will see some flicker.
GnomeDialog
Library
Gnome
Header File
libgnomeui/gnome-dialog.h
Description
GnomeDialog (or a subclass) should be used for all dialogs in a Gnome program.
Chapter 7 describes the GnomeDialog interface.
If you arent using Gnome, GnomeDialog is still useful because it implements all
the basic features a dialog really must have. Studying the GnomeDialog source is
highly recommended (you can even cut-and-paste if your application is under the
GPL).
GnomeAbout
Library
Gnome
Header File
libgnomeui/gnome-about.h
Description
GnomeAbout is an about dialog, giving Gnome about dialogs a consistent look-andfeel. the section called GnomeAbout in Chapter 7 covers the interface.
301
GnomeMessageBox
Library
Gnome
Header File
libgnomeui/gnome-messagebox.h
Description
GnomeMessageBox is simply a GnomeDialog with a label and a small icon pre-packed
inside. The icon corresponds to a "message box type," such as a warning message,
an error, or a question. This helps users rapidly determine the dialogs purpose. the
section called GnomeMessageBox in Chapter 7 explains the use of this widget.
GnomePropertyBox
Library
Gnome
Header File
libgnomeui/gnome-propertybox.h
Description
GnomePropertyBox is a dialog for application preferences or the properties of some
user-visible object in your program. It has "apply", "OK", "close", and "help" buttons;
"OK" is equivalent to "apply" followed by "close." the section called GnomePropertyBox in Chapter 7 describes it in more detail.
GnomeScores
Library
Gnome
Header File
libgnomeui/gnome-scores.h
302
Description
GnomeScores keeps track of and displays a high scores list. Most Gnome games use
it.
GnomeApp
Library
Gnome
Header File
libgnomeui/gnome-app.h
Description
GnomeApp is a GtkWidget subclass specialized for main application windows. It has
spaces for an optional toolbar, menubar, and statusbar. The applications "document"
goes in a special slot in the center of the widget. the section called The GnomeApp
Widget in Chapter 6 describes this widget.
GtkDialog
Library
GTK+
Header File
gtk/gtkdialog.h
Description
GtkDialog is a GtkWindow with three widgets pre-packed: a GtkVBox for the dialog
contents, a GtkSeparator, and a GtkHBox for the dialogs buttons. GtkDialog is not
very useful; all Gnome programs should use GnomeDialog instead.
GnomeFontSelector
Library
Gnome
303
Header File
libgnomeui/gnome-font-selector.h
Description
GnomeFontSelector is an obsolete font selection dialog, replaced by GtkFontSelectionDialog. GtkFontSelectionDialog contains a GtkFontSelection. Gnome
programs should really use a GtkFontSelection inside a GnomeDialog, because
GtkFontSelectionDialog does not use GnomeDialog and thus its look-and-feel is
slightly wrong. GnomeFontSelector should not be used.
GtkInputDialog
Library
GTK+
Header File
gtk/gtkinputdialog.h
Description
GtkInputDialog is a dialog for selecting and setting up devices that use the X Input
Extension (such as drawing tablets). It predates Gnome and is not a GnomeDialog so
GtkColorSelectionDialog
Library
GTK+
Header File
gtk/gtkcolorsel.h
Description
GtkColorSelectionDialog is a dialog containing a GtkColorSelection. Gnome
applications should manually place the GtkColorSelection in a GnomeDialog, or
use GnomeColorPicker.
304
GtkFileSelection
Library
GTK+
Header File
gtk/gtkfilesel.h
Description
GtkFileSelection is a file selection dialog (unlike most of the other widgets ending
in "Selection", which are composite widgets meant to be placed inside a dialog).
305
GtkFontSelectionDialog
Library
GTK+
Header File
gtk/gtkfontsel.h
Description
GtkFontSelectionDialog is a dialog containing a GtkFontSelection. Gnome applications should use a GnomeDialog containing a GtkFontSelection instead.
306
GtkPlug
Library
GTK+
Header File
gtk/gtkplug.h
Description
GtkPlug is a toplevel window that can be embedded in a GtkSocket widget running
in a separate application. In other words, GtkSocket is a "hole" in one process that
can contain a GtkPlug widget from another.
GtkButton
Library
GTK+
Header File
gtk/gtkbutton.h
Description
GtkButton is a simple rectangular button. Its a container with one child; usually it
307
GnomeColorPicker
Library
Gnome
Header File
libgnomeui/gnome-color-picker.h
Description
GnomeColorPicker is a button containing a small colored square indicating the cur-
rently selected color. When clicked, it creates a color selection dialog to change the
selected color.
GnomeFontPicker
Library
Gnome
Header File
libgnomeui/gnome-font-picker.h
Description
GnomeFontPicker is analagous to GnomeColorPicker; its a button showing the cur-
rently selected font, which pops up a font selection dialog when clicked.
GnomeHRef
Library
Gnome
Header File
libgnomeui/gnome-href.h
308
Description
GnomeHRef is a borderless button with a hyperlink displayed on it. When the button is
clicked, Gnome points the users browser at the hyperlinks target URL, or launches
a new browser instance. The command used to go to the URL is globally configurable
from the Gnome control center.
GtkToggleButton
Library
GTK+
Header File
gtk/gtktogglebutton.h
Description
GtkToggleButton looks much like a regular GtkButton. However, it is intended to
reflect a toggleable state; when the toggle is "active," the button appears to be depressed. GtkCheckButton should often be used instead of the toggle button; the
check button usually looks nicer than GtkToggleButton, and gives the user a better idea that the button represents a toggleable state.
GtkCheckButton
Library
GTK+
309
Header File
gtk/gtkcheckbutton.h
Description
The GtkCheckButton widget works just like the GtkToggleButton, but looks different (it looks like a label with a small button to the left). In most cases, the check button
is a better choice than the toggle button, because the toggle button does not give the
user a visual hint that it represents a toggleable state.
GtkRadioButton
Library
GTK+
Header File
gtk/gtkradiobutton.h
Description
A radio button represents one of several mutually-exclusive options. Radio buttons
are placed in "groups"; only one button in a group can be active at a given time.
GtkOptionMenu can also be used to represent mutually exclusive options; an option
menu is typically a better choice if there are more than a few options. A GtkList or
GtkCList might be appropriate if there are a truly large number of options.
310
GtkOptionMenu
Library
GTK+
Header File
gtk/gtkoptionmenu.h
Description
GtkOptionMenu displays the currently active item from among a number of options;
when clicked, it pops up a menu to allow the user to make a new item active. The
option menu is slightly broken; it does not take the size of the menu items into account when requesting its size. If you have menu items containing labels in the option
menu, the labels will often be truncated. The best workaround is to give the option
menu more space than it requests, by setting appropriate options on its parent container.
GnomeDockItem
Library
Gnome
311
Header File
libgnomeui/gnome-dock-item.h
Description
GnomeDockItem is a container that allows its child to appear on a GnomeDock. Dock
items can be detached from their parent window and placed anywhere on the desktop; they can also be moved around within the dock. GnomeDock lets users rearrange Gnome toolbars. GnomeDockItem provides the "handle" for dragging its child.
GnomeApp uses GnomeDock internally, so Gnome toolbars are all repositionable.
GtkAlignment
Library
GTK+
Header File
gtk/gtkalignment.h
Description
GtkAlignment is an invisible container used to align a child widget within some
space. It lets you set two factors, each in both the X and Y direction; the alignment is 0.0
for left-justified (or top-justified) and 1.0 for right-justified (or bottom-justified). An
alignment of 0.5 centers the child in that direction. The scale factor determines how
the child fills extra space it did not request; if 0.0, the child fills only its requisition. A
scale of 1.0 means that the child always expands to fill all the available space. (Clearly,
a 1.0 scale factor makes the alignment factor irrelevant.)
GtkFrame
Library
GTK+
312
Header File
gtk/gtkframe.h
Description
The frame widget draws a decorative frame around its child. It has an optional title describing the contents of the frame. To turn off the title, set it to NULL. It also
has a configurable shadow style; the four possibilities are shown in Figure 14-10.
GTK_SHADOW_NONE is a fifth acceptable value for the shadow type; it turns the
shadow off.
GtkAspectFrame
Library
GTK+
Header File
gtk/gtkaspectframe.h
Description
GtkAspectFrame is used to control the aspect ratio of its child. It also allows you
313
to justify the child in both directions, similar to GtkAlignment. You can specify an
aspect ratio, or require that the ratio of the childs size request be preserved. Visually,
GtkAspectFrame looks exactly like GtkFrame.
GtkItem
Library
GTK+
Header File
gtk/gtkitem.h
Description
GtkItem is an abstract base class for list items, tree items, and menu items. Items are
GtkMenuItem
Library
GTK+
Header File
gtk/gtkmenuitem.h
Description
A menu item is an invisible container; it is the only kind of widget that can appear
in a GtkMenu. Typically, a label or a label and a pixmap are placed in the menu item
to indicate its function. If a menu item has no child widget, it draws a separator line
instead. This saves the overhead of adding a GtkSeparator to the menu item.
GtkCheckMenuItem
Library
GTK+
314
Header File
gtk/gtkcheckmenuitem.h
Description
GtkCheckMenuItem is a menu item that works like a GtkCheckButton; it has a small
button next to its child widget, which is either "active" or "inactive." Because its a
subclass of GtkMenuItem, it can appear in menus.
GtkRadioMenuItem
Library
GTK+
Header File
gtk/gtkradiomenuitem.h
Description
A radio menu item works like GtkRadioButton; it allows the user to choose from
a set of mutually exclusive options. Because its a subclass of GtkMenuItem, it can
appear in menus.
GtkPixmapMenuItem
Library
Gnome
Header File
libgnomeui/gtkpixmapmenuitem.h
Description
GtkPixmapMenuItem is a Gnome widget despite its name. This widget solves a very
specific problem: namely, if a menu contains check or radio menu items, GTK+ indents the child widget of all the menu items in the menu to make room for the check
or radio buttons. Gnome uses pixmaps next to some menu items; GtkPixmapMenuItem indents pixmaps in the same way GTK+ indents check or radio buttons. If you
simply added a pixmap and a label to a GtkMenuItem, the pixmap would be incorrectly aligned with the plain labels in other menu items. This widget is not really
315
pixmap-specific; any widget can be placed in the unindented "pixmap" slot. Usually
GtkPixmapMenuItem is created implicitly with the Gnome menu creation functions.
GtkTearoffMenuItem
Library
GTK+
Header File
gtk/gtktearoffmenuitem.h
Description
GtkTearoffMenuItem is a "perforation" representing a spot where a menu can be
"torn off" (kept visible in a toplevel window for easy access). Gnome menus all include a tearoff menu item by default, but users can globally disable them using the
Gnome control center.
GtkListItem
Library
GTK+
Header File
gtk/gtklistitem.h
Description
GtkListItem is an invisible container that allows its child to appear in a GtkList.
That is, only list items can appear in a list.
316
GtkTreeItem
Library
GTK+
Header File
gtk/gtktreeitem.h
Description
GtkTreeItem is an invisible container that gives its child the ability to appear in a
GtkTree. Only tree items can be placed in the tree widget.
GtkEventBox
Library
GTK+
Header File
gtk/gtkeventbox.h
Description
The event box widget may be the simplest container in GTK+; its only purpose is to
have a GdkWindow. Certain operations only work on widgets with windows (such
as setting the background color, or capturing events); if you want to perform these
operations on a windowless widget, you can place the widget in an event box and
perform the operations on the event box, achieving much the same effect.
GtkHandleBox
Library
GTK+
Header File
gtk/gtkhandlebox.h
317
Description
The handle box widget can be adds a handle to a child widget; by dragging on the
handle, the child can be removed from the window and positioned elsewhere on the
users desktop. The handle box is often used for toolbars. GnomeDock and GnomeDockItem offer a more flexible (but more elaborate) alternative.
GtkScrolledWindow
Library
GTK+
Header File
gtk/gtkscrolledwindow.h
Description
GtkScrolledWindow provides horizontal and vertical scrollbars for its child widget.
Optionally, the scrollbars are hidden when the entire child is visible. If a child widget has a set_scroll_adjustments_signal in its GtkWidgetClas (see the section called
Overridable Signals in Chapter 11), the scrolled window uses them as the adjustments
for the scrollbars. Otherwise, the scrolled window scrolls the entire widget using a
GtkViewport. (Consider GtkCList for example; the column titles arent scrolled, only
the list contents. Thus GtkCList provides scroll adjustment signals.)
318
GtkViewport
Library
GTK+
Header File
gtk/gtkviewport.h
Description
GtkViewport is more or less an implementation detail of GtkScrolledWindow. It con-
GtkBox
Library
GTK+
Header File
gtk/gtkbox.h
Description
GtkBox is an abstract base class for GtkVBox, GtkHBox, and GtkButtonBox. Its an
GtkHBox
Library
GTK+
Header File
gtk/gtkhbox.h
319
Description
GtkHBox is a GtkBox that packs widgets from left to right. The left side is considered
GnomeAppBar
Library
Gnome
Header File
libgnomeui/gnome-appbar.h
Description
GnomeAppBar is a simple status bar with an optional progress meter. It does not have
"contexts" like GtkStatusbar. the section called GnomeAppBar in Chapter 6 gives
more details.
Figure 14-13. GnomeAppBar with the optional progress bar turned on.
GnomeDateEdit
Library
Gnome
Header File
libgnomeui/gnome-dateedit.h
Description
GnomeDateEdit allows the user to edit a date and time. The time-editing part can be
320
GtkCombo
Library
GTK+
Header File
gtk/gtkcombo.h
Description
GtkCombo is a text entry box with a drop-down menu "quick choices." If you want
to limit the user to a fixed set of options, a GtkOptionMenu is more appropriate.
GtkCombo allows the user to type in anything, but offers some suggestions as well.
GnomeEntry is a combo box that adds items the user types in to the list of choices in
the drop-down menu, and automatically remembers the list from session to session.
GnomeEntry
Library
Gnome
Header File
libgnomeui/gnome-entry.h
321
Description
GnomeEntry is a GtkCombo extension that uses the drop-down menu as a history. If
the user types something which isnt in the history already, GnomeEntry adds it and
saves it in a configuration file to be loaded next time the application starts up.
GnomeFileEntry
Library
Gnome
Header File
libgnomeui/gnome-file-entry.h
Description
GnomeFileEntry is a GnomeEntry that keeps file names in its history. It also has
a "Browse" button which pops up a GtkFileSelection. It has a "directories only"
mode as well.
GnomeNumberEntry
Library
Gnome
Header File
libgnomeui/gnome-number-entry.h
Description
GnomeNumberEntry allows the user to enter a number; it keeps a history of numbers
entered in its drop-down menu. It also has a "Calculator" button to pop up a GnomeCalculator.
GnomeProcBar
Library
Gnome
322
Header File
libgnomeui/gnome-procbar.h
Description
GnomeProcBar is used in a Gnome panel applet that displays CPU and memory load,
and in the GTop application (a graphical top clone). It displays a colored bar that can
GtkStatusbar
Library
GTK+
Header File
gtk/gtk.h
Description
GtkStatusbar is described in the section called GtkStatusbar in Chapter 6. Its a
GtkVBox
Library
GTK+
Header File
gtk/gtkvbox.h
Description
GtkVBox is a GtkBox that packs widgets from top to bottom. The top is considered
323
GnomeCalculator
Library
Gnome
Header File
libgnomeui/gnome-calculator.h
Description
GnomeCalculator is a simple calculator, implemented as a GtkWidget.
GnomeGuru
Library
Gnome
Header File
libgnomeui/gnome-guru.h
Description
GnomeGuru was an attempt to implement a "wizard" widget (a series of pages rep-
resenting steps in a task that the user can step through). It is an immature interface
and should not be used; at press time, it appears that a new widget called GnomeDruid will replace it in the next version of Gnome. GnomeDruide will most likely be
available as an add-on module before that, so look for it if you need a wizard widget.
GnomeIconEntry
Library
Gnome
324
Header File
libgnomeui/gnome-icon-entry.h
Description
GnomeIconEntry is similar to GnomeColorPicker and GnomeFontPicker. Its a but-
ton displaying a currently-selected icon; when the button is clicked, an icon browser
dialog allows the user to set a new icon. The widget used to have a text entry for typing an icon filename, thus it is called GnomeIconEntry rather than GnomeIconPicker.
GnomeIconSelection
Library
Gnome
Header File
libgnomeui/gnome-icon-sel.h
Description
GnomeIconSelection browses icon files; its used by GnomeIconEntry but can also
be used directly.
325
GnomeLess
Library
Gnome
Header File
libgnomeui/gnome-less.h
Description
GnomeLess is a simple extension of GtkText that loads text from a file or file descrip-
tor and displays it. It is probably a good idea to avoid this widget; because it isnt
very useful, it is likely to disappear from future versions of Gnome.
GnomePaperSelector
Library
Gnome
326
Header File
libgnomeui/gnome-paper-selector.h
Description
GnomePaperSelector is another widget worth avoiding; in the 1.0 release, it is strictly
experimental. It allows the user to select the paper size for printing.
GnomePixmapEntry
Library
Gnome
Header File
libgnomeui/gnome-pixmap-entry.h
Description
GnomePixmapEntry has essentially the same purpose as GnomeIconEntry; it allows
the user to select a pixmap. The only reason you might prefer one to the other is that
GnomeIconEntry scales images to the standard Gnome icon size.
GnomeSpell
Library
Gnome
Header File
libgnomeui/gnome-spell.h
Description
GnomeSpell is a spell-checker interface; it uses the ispell program internally. This
327
GtkColorSelection
Library
GTK+
Header File
gtk/gtkcolorsel.h
Description
GtkColorSelection allows the user to specify a color, using a color wheel or sliders.
It makes up the contents of GtkColorSelectionDialog (Figure 14-1).
GtkGammaCurve
Library
GTK+
Header File
gtk/gtkgamma.h
Description
GtkGammaCurve allows the user to edit a curve; its a very specialized widget used in
328
GtkButtonBox
Library
GTK+
Header File
gtk/gtkbbox.h
Description
GtkButtonBox is a special kind of GtkBox designed to store the buttons of a dialog.
It has horizontal and vertical variants. GnomeDialog creates a button box for you, so
there is no need to use this widget directly when programming with Gnome.
GtkHButtonBox
Library
GTK+
Header File
gtk/gtkhbbox.h
Description
GtkHButtonBox is the horizontal variant of GtkButtonBox.
GtkVButtonBox
Library
GTK+
Header File
gtk/gtk.h
Description
GtkVButtonBox is the vertical variant of GtkButtonBox.
329
GtkLayout
Library
GTK+
Header File
gtk/gtklayout.h
Description
GtkLayout creates the illusion of a container with infinite size. Because X windows
are limited to 32,768 pixels in size (2^15), most widgets also have a 32,768-pixel size
limit (and child widgets must be positioned within the parents X window). Naive
widgets scroll by simply moving their GdkWindow. GtkLayout is more intelligent
about this.
GnomeCanvas
Library
Gnome
Header File
libgnomeui/gnome-canvas.h
Description
GnomeCanvas is extensively discussed in Chapter 12. It renders flicker-free structured
330
GnomeIconList
Library
Gnome
Header File
libgnomeui/gnome-icon-list.h
Description
GnomeIconList is used in the Gnome file manager. It displays icons and their names;
331
GnomeDockBand
Library
Gnome
Header File
libgnomeui/gnome-dock-band.h
Description
GnomeDockBand contains one row or column of GnomeDockItems; a GnomeDock in turn
contains one or more GnomeDockBands. See the GnomeDockItem entry for details and
a screenshot.
332
GnomeDock
Library
Gnome
Header File
libgnomeui/gnome-dock.h
Description
GnomeDock collects GnomeDockBands which in turn hold GnomeDockItems. GnomeDock allows users to reposition toolbars and other application components. See the
GnomeDockItem entry for details and a screenshot.
GtkCList
Library
GTK+
Header File
gtk/gtkclist.h
Description
GtkCList is a list-with-columns widget; it is also the base class for GtkCTree. GtkCList displays text and/or a pixmap in each cell; it cannot hold child widgets in its
cells. GtkCList is only a container because it uses widgets for the column headings.
You may prefer GtkList, which can have child widgets as list items, but is less effi-
333
Figure 14-21. The Gnome file managers list view uses GtkCList
GtkCTree
Library
GTK+
Header File
gtk/gtkctree.h
Description
GtkCTree is similar to GtkCList, but (unsurprisingly) displays a tree with expandable nodes instead of a simple list. GtkTree is a more flexible tree widget (it can have
arbitrary widgets in the tree cells), but it is less efficient and limited to 32,768 pixels.
334
GtkFixed
Library
GTK+
Header File
gtk/gtkfixed.h
Description
The GtkFixed container allows you to position child widgets at absolute coordinates, and always gives child widgets exactly their requested size. This widget is for
masochists; it doesnt do anything automatically. You should almost always use another layout widget instead (if you think you need the fixed widget, consider asking
for help; most likely a real layout widget can be made to work better).
335
GtkNotebook
Library
GTK+
Header File
gtk/gtknotebook.h
Description
A notebook widget presents the user with several "pages"; the user can move a page
to the top by selecting its "tab." Each child added to GtkNotebook becomes a page;
you can also specify widgets to use for the tab labels. It is generally considered bad
practice to have more than a single row of tabs, but GtkNotebook does allow it. It is
also possible to position the tabs on the left, right, or bottom of the notebook, but you
should always leave them on top for interface consistency.
GtkFontSelection
Library
GTK+
Header File
gtk/gtkfontsel.h
Description
GtkFontSelection is a composite widget that allows the user to select a font from
among the fonts available on the system. GtkFontSelectionDialog contains an in-
336
GtkPaned
Library
GTK+
Header File
gtk/gtkpaned.h
Description
The GtkPaned widget divides an area into two user-resizable sections. It has horizontal and vertical variants.
GtkHPaned
Library
GTK+
Header File
gtk/gtkhpaned.h
Description
GtkHPaned is the horizontal variant of GtkPaned; it allows the user to divide a horizontal space between the GtkHPaneds two child widgets.
337
GtkVPaned
Library
GTK+
Header File
gtk/gtkvpaned.h
Description
GtkVPaned is the vertical variant of GtkPaned; it allows the user to divide a vertical
space between the GtkVPaneds two child widgets.
GtkList
Library
GTK+
Header File
gtk/gtklist.h
Description
GtkList displays a list of items. Each item is a GtkListItem; GtkListItem is a container that can hold any kind of widget. The size of a GtkList is limited, because
list items are placed at fixed coordinates in the lists GdkWindow, and scrolling is
achieved by moving the GdkWindow; GdkWindow has a maximum size of 32,768
pixels, and any list item positioned outside that range is invisible. GtkCList overcomes this limitation, but is unable to contain arbitrary widgets.
GtkMenuShell
Library
GTK+
Header File
gtk/gtkmenushell.h
338
Description
GtkMenuShell is an abstract base class for widgets that contain GtkMenuItems. Its
two subclasses are GtkMenu and GtkMenuBar.
GtkMenuBar
Library
GTK+
Header File
gtk/gtkmenubar.h
Description
GtkMenuBar is a menu bar. It contains one or more menu items; normally, each menu
item will have a submenu (i.e., a GtkMenu with more menu items). For example, the
menu bar might have a menu item called "File," with a submenu containing the menu
items "Open" and "Quit."
GtkMenu
Library
GTK+
Header File
gtk/gtkmenu.h
Description
GtkMenu contains menu items. GtkMenu is unique because it should not be shown
(with gtk_widget_show()) by the programmer; menus are popped up in response
to user actions.
GtkPacker
Library
GTK+
339
Header File
gtk/gtkpacker.h
Description
GtkPacker is a layout container inspired by the Tk toolkit. If youre familiar with that
toolkit, you may find it easier to use than the standard GTK+ layout containers.
GtkSocket
Library
GTK+
Header File
gtk/gtksocket.h
Description
GtkSocket is a "hole" in one application that allows a GtkPlug from a second appli-
cation to be embedded.
GtkTable
Library
GTK+
Header File
gtk/gtktable.h
Description
the section called GtkTable in Chapter 3 desribes GtkTable in some detail. Its one
of the most important GTK+ layout widgets.
340
GtkTed
Library
Gnome
Header File
libgnomeui/gtk-ted.h
Description
GtkTed is a relic from the early days of Gnome; "ted" stands for "table editor." Its a
kind of primitive GUI builder. There are at least two advanced projects to write good
GUI builders (Glade and GLE), so this widget should be ignored and will disappear
in a future version of libgnomeui.
GtkToolbar
Library
GTK+
Header File
gtk/gtktoolbar.h
Description
No surprises here: GtkToolbar is a toolbar widget. Gnome applications will usually
use the Gnome helper functions instead of creating a toolbar directly, as described in
Chapter 6.
GtkTree
Library
GTK+
Header File
gtk/gtktree.h
341
Description
GtkTree is to GtkCTree as GtkList is to GtkCList. That is, GtkTree is more flexible
than GtkCTreetree items can contain any widget but its also a bit slower than
GtkCTree and holds only a limited number of items. The maximum number of items
depends on the height of the rows; the total row height must fit inside a GdkWindow,
which means 32,768 pixels.
GnomeAnimator
Library
Gnome
Header File
libgnomeui/gnome-animator.h
Description
GnomeAnimator displays a series of images, creating an animation. It has a "loop
mode" and a "play once" mode. The GnomeAnimator API is marked "immature" in
Gnome 1.0 and may change incompatibly in future versions; this is an experimental
widget.
342
GnomePixmap
Library
Gnome
Header File
libgnomeui/gnome-pixmap.h
Description
GnomePixmap should be preferred to GtkPixmap, though it has the same purpose.
GnomePixmap is a bit smarter about visuals. It can also load images from many differ-
GnomeStock
Library
Gnome
Header File
libgnomeui/gnome-stock.h
Description
GnomeStock is a container that wraps a GnomePixmap; it automatically creates "insen-
sitive" and "focused" copies of the pixmap to reflect the widget state. It can be set to
one of the Gnome stock pixmap macros, such as GNOME_STOCK_PIXMAP_CUT (small
picture of scissors), GNOME_STOCK_PIXMAP_PRINT (a little printer), etc. You can also
register new stock pixmaps specific to your application at runtime. Gnome uses this
widget internally when creating menus and toolbars using a GnomeUIInfo template
(see the section called Menus and Toolbars with GnomeUIInfo in Chapter 6).
GtkMisc
Library
GTK+
343
Header File
gtk/gtkmisc.h
Description
The descriptively-named (or not) GtkMisc abstract base class allows you to set the
"alignment" and "padding" of its subclasses. Alignment is a float between 0.0 and
1.0, where 0.0 is left-justified, 0.5 is centered, and 1.0 is right-justified. Alignment
only matters if a GtkMisc receives a size allocation larger than its size request; the
alignment locates the natural bounding box of the widget within its actual bounding
box. Padding is a number of pixels to add to the widgets size request. The widget will
then leave those pixels blank.
Widgets that do not derive from GtkMisc can be made "alignable" in the same way
by placing them in a GtkAlignment container.
GtkLabel
Library
GTK+
Header File
gtk/gtklabel.h
Description
GtkLabel simply displays a text string. If the text string contains newlines, GtkLabel displays multiple lines. Labels honor the alignment parameter from their parent
class (GtkMisc); you can use this to center the text, or move it to the left or right.
Alignment is not the same as justification. Justification defines the position of multiple lines with respect to each other. Left-justified means each line starts in the same
place, right-justified means each ends in the same place, center-justified means each
is centered around the same imaginary line. Justification has no meaning for one-line
labels. Alignment set with gtk_misc_set_alignment() positions the entire block
of text within its size allocation; alignment only matters if the label receives more
space than it requested (it will request just enough to hold the text block). Labels are
GTK_NO_WINDOW widgets (which means they dont receive events and draw on
their parents background).
GtkAccelLabel
Library
GTK+
344
Header File
gtk/gtkaccellabel.h
Description
GtkAccelLabel is associated with some other widget, and displays the accelerator
GtkClock
Library
Gnome
Header File
libgnomeui/gtk-clock.h
Description
GtkClock is a label that displays a time. It can optionally update the time periodically
GtkTipsQuery
Library
GTK+
Header File
gtk/gtktipsquery.h
Description
GtkTipsQuery is a label that displays tooltips. It also has "Whats This?" functionality. You call gtk_tips_query_start() to switch to "query mode." In query mode,
the cursor is changed to a question mark; as the mouse moves over widgets in the
application, the GtkTipsQuery displays their tooltips. GtkTipsQuery emits a "widget_selected" signal if the user clicks on a widget; you can use this to display more
extensive help for that widget. You might store the more extensive help as the "private" component of a GtkTooltip, or you might use gtk_object_set_data() to store
some kind of application-specific help information.
345
GtkArrow
Library
GTK+
Header File
gtk/gtkarrow.h
Description
GtkArrow displays an arrow. Its a very simple GTK_NO_WINDOW widget and
doesnt even receive events. In the default theme, an arrow is simply a triangle.
GtkImage
Library
GTK+
Header File
gtk/gtkimage.h
Description
GtkImage displays a GdkImage in a widget. Its only useful if you already have a
GdkImage; to display a fixed image you usually want GnomePixmap.
GtkPixmap
Library
GTK+
Header File
gtk/gtkpixmap.h
346
Description
GtkPixmap displays a GdkPixmap. If youre using Gnome, prefer GnomePixmap for
GtkCalendar
Library
GTK+
Header File
gtk/gtkcalendar.h
Description
GtkCalendar displays a calendar page (one month). It allows users to select a date.
GnomeDateEdit uses GtkCalendar in a popup menu.
GtkDrawingArea
Library
GTK+
Header File
gtk/gtkdrawingarea.h
347
Description
GtkDrawingArea is a thin wrapper around GdkWindow; it gives you a blank area
to draw on. Normally, you would connect to its "configure_event" signal to catch
changes in the size of the area, and do your drawing in an "expose_event" handler.
To eliminate flicker, you might keep a GdkPixmap equal in size to the drawing area,
and draw to the pixmap; in your "expose_event" handler, simply copy the exposed
region from the pixamp to the drawing area.
For high-level graphics, GnomeCanvas can be much more convenient to use.
GtkCurve
Library
GTK+
Header File
gtk/gtkcurve.h
Description
GtkCurve is used to display the curve in the GtkGammaCurve widget. Its a drawing
area extension with curve-drawing abilities. Most likely you wont find a use for this
widget.
GtkDial
Library
GTK+
Header File
gtk/gtkdial.h
Description
GtkDial is a "speedometer" display. By default, the user can drag the "needle" around,
changing the dials value. GtkDial also has a "view only" mode.
348
GtkEditable
Library
GTK+
Header File
gtk/gtkeditable.h
Description
GtkEditable is an abstract base class for widgets that allow the user to edit text. The
base class interface allows cursor positioning, retrieving characters, and so on. It also
includes the "changed" signal, which you can use to detect user input.
GtkEntry
Library
GTK+
Header File
gtk/gtkentry.h
Description
GtkEntry allows the user to enter a single line of text. It has a "password" mode; in
349
GtkSpinButton
Library
GTK+
Header File
gtk/gtkspinbutton.h
Description
GtkSpinButton is a GtkEntry customized to allow the user to enter a number. Spin
buttons add up and down arrows to the entry, so the user can rapidly spin through
the possible values.
GtkText
Library
GTK+
Header File
gtk/gtktext.h
Description
GtkText is a text widget. It can display text, and offers simple text-editing facilities.
350
Two questions about the text widget are very frequently asked on the GTK+ mailing
lists. These are:
The text widget doesnt seem to be very powerful. Are there plans to replace it?
The text widget does not support horizontal scrolling; instead, it wraps lines. It is not
very powerful, and the code is difficult to maintain; it will most likely be replaced in
Gtk 1.4 as part of the move to Unicode.
GtkRuler
Library
GTK+
Header File
gtk/gtkruler.h
Description
GtkRuler is an abstract base class for the horizontal and vertical ruler widgets. The
351
GtkHRuler
Library
GTK+
Header File
gtk/gtkhruler.h
Description
Horizontal variant of GtkRuler.
GtkVRuler
Library
GTK+
Header File
gtk/gtkvruler.h
352
Description
Vertical variant of GtkRuler.
GtkRange
Library
GTK+
Header File
gtk/gtkrange.h
Description
GtkRange is an abstract base class for "slider" widgets. These widgets modify some
numeric value as a "slider" is moved in a "trough." The two subclasses of GtkRange
are GtkScale, used to allow the user to enter a numeric value, and GtkScrollbar,
GtkScale
Library
GTK+
Header File
gtk/gtkscale.h
Description
GtkScale allows the user to enter a numeric value by moving a slider. It can display
the current value above the slider; you can turn this off if the exact value isnt relevant, or you want to provide feedback in some other way. GtkScale is an abstract
base class; you must instantiate its vertical or horizontal variant.
353
GtkHScale
Library
GTK+
Header File
gtk/gtkhscale.h
Description
GtkHScale is the horizontal variant of GtkScale.
GtkVScale
Library
GTK+
Header File
gtk/gtkvscale.h
Description
GtkVScale is the vertical variant of GtkScale.
GtkScrollbar
Library
GTK+
Header File
gtk/gtkscrollbar.h
Description
GtkScrollbar is an abstract base class, giving horizontal and vertical scrollbars a
common interface.
354
GtkHScrollbar
Library
GTK+
Header File
gtk/gtkhscrollbar.h
Description
A horizontal scrollbar.
GtkVScrollbar
Library
GTK+
Header File
gtk/gtkvscrollbar.h
Description
A vertical scrollbar.
GtkSeparator
Library
GTK+
Header File
gtk/gtkseparator.h
Description
The GtkSeparator widget is a divider line you can use to make your interface more
attractive. For example, a GtkHSeparator is used to divide the contents of a GnomeDialog from its buttons.
355
GtkHSeparator
Library
GTK+
Header File
gtk/gtkhseparator.h
Description
Horizontal GtkSeparator.
GtkVSeparator
Library
GTK+
Header File
gtk/gtkvseparator.h
Description
Vertical GtkSeparator.
GtkPreview
Library
GTK+
Header File
gtk/gtkpreview.h
Description
GtkPreview displays an RGB image; the GIMP uses it to display a preview of the
356
GtkProgress
Library
GTK+
Header File
gtk/gtkprogress.h
Description
GtkProgress is an abstract base class for progress displays. In GTK+ 1.2 only one
concrete subclass exists (GtkProgressBar). Future versions of GTK+ may add addi-
GtkProgressBar
Library
GTK+
Header File
gtk/gtkprogressbar.h
Description
GtkProgressBar is a flexible progress bar widget. It can display text over the progress
bar, and has an "activity" mode to indicate "activity, but unknown total task size." In
"activity" mode a small block moves back and forth. GtkProgressBar is probably excessively configurable; you should try to use its default look-and-feel, for consistency
with other applications.
357
ZvtTerm
Library
Zvt
Header File
zvt/zvtterm.h
Description
ZvtTerm comes with gnome-libs but is not in libgnomeui. Its in a separate libzvt.
ZvtTerm is simply a terminal emulator; you can spawn a child process to run inside
the widget and interact with the user. ZvtTerm provides all the functionality of the
gnome-terminal program that comes with the Gnome desktop environment.
358
Canvas Items
GnomeCanvasItem
Library
Gnome
Header File
libgnomeui/gnome-canvas.h
Description
GnomeCanvasItem is the abstract base class for canvas items. Chapter 12 and Chapter 13 describe it in detail.
GnomeCanvasRE
Library
Gnome
Header File
libgnomeui/gnome-canvas-rect-ellipse.h
Description
GnomeCanvasRE is the base class for the rectangle and ellipse canvas items. In the
future, it may also be the base class for a GnomeCanvasArc item. the section called
Rectangle and Ellipse Items in Chapter 12 details this canvas item.
GnomeCanvasEllipse
Library
Gnome
Header File
libgnomeui/gnome-canvas-rect-ellipse.h
359
Description
GnomeCanvasEllipse renders an ellipse on the canvas; see the section called Rectangle
and Ellipse Items in Chapter 12 for more details.
GnomeCanvasRect
Library
Gnome
Header File
libgnomeui/gnome.h
Description
GnomeCanvasRect renders a rectangle on the canvas; see the section called Rectangle
and Ellipse Items in Chapter 12 for more details.
GnomeCanvasGroup
Library
Gnome
Header File
libgnomeui/gnome-canvas.h
Description
GnomeCanvasGroup is a GnomeCanvasItem that contains other GnomeCanvasItems.
It creates the hierarchical tree structure of the items on a GnomeCanvas. The GnomeCanvas creates a special GnomeCanvasGroup, called the root; all user-created canvas
items must be added below the root group. See Chapter 12 for more details.
GnomeCanvasImage
Library
Gnome
360
Header File
libgnomeui/gnome-canvas-image.h
Description
GnomeCanvasImage displays an image on the canvas (specifically, a GdkImlibImage). See the section called Image Item in Chapter 12 for details.
GnomeCanvasLine
Library
Gnome
Header File
libgnomeui/gnome.h
Description
GnomeCanvasLine displays a line segment or series of line segments on the canvas; it
can also be used to display an unfilled polygon, by joining the end of the last segment
to the start of the first. Optionally, the line can have arrowheads at either end. See the
section called Line Item in Chapter 12.
GnomeCanvasPolygon
Library
Gnome
Header File
libgnomeui/gnome-canvas-polygon.h
Description
GnomeCanvasPolygon displays a filled polygon. Use GnomeCanvasLine for hollow
polygons. See the section called Polygon Item in Chapter 12 for more details.
361
GnomeCanvasText
Library
Gnome
Header File
libgnomeui/gnome-canvas-text.h
Description
GnomeCanvasText displays some text on the canvas; see the section called Text Item
in Chapter 12 for more information.
GnomeCanvasWidget
Library
Gnome
Header File
libgnomeui/gnome-canvas-widget.h
Description
GnomeCanvasWidget emulates a GtkContainer; it holds a child widget and displays
it on the canvas. See the section called Widget Item in Chapter 12 for details.
GnomeCanvasTextItem
Library
Gnome
Header File
libgnomeui/gnome-icon-item.h
362
Description
GnomeCanvasTextItem is used internally by the GnomeIconList widget. You should
never use it directly; its considered an implementation detail and subject to change
in future versions of the library.
Miscellaneous Objects
GnomeClient
Library
Gnome
Header File
libgnomeui/gnome-client.h
Description
GnomeClient is a GtkObject which conceals the details of session management and
provides a nice session management API for Gnome applications. See the section
called Session Management in Chapter 5 for more information.
GnomeDEntryEdit
Library
Gnome
Header File
libgnomeui/gnome-dentry-edit.h
Description
GnomeDEntryEdit is a very specialized object; it is a sort of "widget manager" that
creates and keeps track of two child widgets, an "easy" and an "advanced" page. The
two pages combine to let the user edit a Gnome .desktop entry, as described in the
section called .desktop Entries in Chapter 4. GnomeDEntryEdit is intended to be
used in conjunction with a preexisting GtkNotebook. It isnt a GtkNotebook subclass
itself, because you might want to use the GtkNotebook in a GnomePropertyBox. The
Gnome panel and the Gnome menu editor use this widget.
363
Figure 14-35. The GnomeDEntryEdit object created the two widgets in this notebook
GnomeDockLayout
Library
Gnome
Header File
libgnomeui/gnome-dock-layout.h
Description
GnomeDockLayout maintains information about the current position of items in a
GnomeDock. It can load and save this information; GnomeDock uses this functionality
to save and load toolbar positions. Recall that GnomeApp uses the GnomeDock widget
for its layout.
GnomeMDIChild
Library
Gnome
Header File
libgnomeui/gnome-mdi-child.h
364
Description
GnomeMDIChild is an abstract interface; you must derive your own subclass or
use GnomeMDIGenericChild in order to take advantage of the GnomeMDI object.
GnomeMDI is a "multiple document interface" manager.
GnomeMDIGenericChild
Library
Gnome
Header File
libgnomeui/gnome-mdi-generic-child.h
Description
A generic implementation of GnomeMDIChild. For complex applications, you may
need to write a custom implementation.
GnomeMDI
Library
Gnome
Header File
libgnomeui/gnome-mdi.h
Description
GnomeMDI keeps track of multiple documents. Users can configure how the documents are arranged in the application; they might be placed in a GtkNotebook in the
same GtkWindow, or each document might have its own GtkWindow. Also, users can
drag the notebook pages out of the GtkWindow, and they will be reparented into their
own toplevel window.
365
GtkData
Library
GTK+
Header File
gtk/gtkdata.h
Description
GtkData is an abstract base class for a piece of data that might be shared between
multiple objects. Right now its interface is empty; in the future, there may be generic
operations for all GtkData objects.
GtkAdjustment
Library
GTK+
Header File
gtk/gtkadjustment.h
Description
GtkAdjustment represents a numeric value. It can also store a maximum and minimum value, a "step increment," a "page increment," and a "page size." Some objects
dont use all the fields in the adjustment, and some interpret them slightly differently. A GtkRange (including its GtkScale and GtkScrollbar subclasses) will allow
the user to move the slider between the minimum and maximum values. Clicking
the arrows on the end of a GtkScrollbar nudges the scroll bar by one "step increment"; clicking them with the middle button moves one "page increment." The "page
size" determines the size of the scrollbar slider (its the length of the "visible" page
in the same units as the overall range). GtkAdjustment emits signals when its values
change.
GtkTooltips
Library
GTK+
366
Header File
gtk/gtktooltips.h
Description
GtkTooltips associates some help text with a widget. If the user holds the mouse
pointer still over the widget for a short time, a tooltip will appear displaying the
help text. GtkTooltips can also store some "private" text; you might use this with a
GtkTipsQuery to display more extensive help. the section called Tooltips in Chapter 6
has more information on tooltips.
GtkItemFactory
Library
GTK+
Header File
gtk/gtkitemfactory.h
Description
GtkItemFactory is intended to simplify menu creation; Gnome applications should
use GnomeUIInfo templates instead (see the section called Menus and Toolbars with
GnomeUIInfo in Chapter 6).
367
Description
Affine operations
Alphagamma tables
Bezier paths
"Filter levels" for image rendering
Rendering sorted vector paths to a
grayscale buffer
Miscellaneous libart declarations
Path operators (moveto, lineto, etc.)
Pixel buffers
Point data types (i.e. X,Y coordinate
pairs)
Rectangle data types
Bounding box computation for sorted
vector paths
Bounding rectangles from a microtile
array
Basic RGB drawing primitives
(run-filling)
Affine transformation of RGB buffers
Affine transformation of bitmaps
Affine transformation of generic pixel
buffers
Affine transformation of RGBA buffers
Rendering sorted vector paths to RGB
buffers
Sorted vector path data type
Sorted vector path set operations (union,
intersection, etc.)
Antialiased sorted vector path rendering
Sorting an unsorted vector path
"Strokes" a vector path yielding a sorted
vector path
Winding rules for sorted vector paths
Microtile array data type
Microtile array set operations (union,
etc.)
Conversion from a rectangle to a
microtile array
368
Header
art_uta_svp.h
art_uta_vpath.h
art_vpath.h
art_vpath_bpath.h
art_vpath_svp.h
gdk.h
gdkcursors.h
gdki18n.h
Description
Conversion from a sorted vector path to
a microtile array
Conversion from a vector path to a
microtile array
Vector path data type
Bezier path to vector path conversion
Sorted vector path to vector path
conversion
GDK function declarations
GDK builtin cursor IDs
Portability wrappers for iswalnum()
and iswspace()
gdkkeysyms.h
gdkprivate.h
gdkrgb.h
gdktypes.h
gdkx.h
glib.h
gnome-about.h
GnomeAbout widget
gnome-animator.h
GnomeAnimator widget
gnome-app-helper.h
gnome-app-util.h
gnome-app.h
GnomeApp widget
gnome-appbar.h
GnomeAppBar widget
gnome-calculator.h
GnomeCalculator widget
gnome-canvas-image.h
gnome-canvas-line.h
gnome-canvas-load.h
gnome-canvas-polygon.h
gnome-canvas-rect-ellipse.h
gnome-canvas-text.h
gnome-canvas-util.h
gnome-canvas-widget.h
gnome-canvas.h
GnomeCanvas widget,
GnomeCanvasItem base class and
GnomeCanvasGroup item
gnome-client.h
gnome-color-picker.h
gnome-config.h
gnome-dateedit.h
369
Header
gnome-dialog-util.h
Description
Miscellaneous libgnome macros
GnomeDEntryEdit object
.desktop file handling
Dialog convenience functions
gnome-dialog.h
GnomeDialog widget
gnome-dns.h
gnome-dock-band.h
GnomeDockBand widget
gnome-dock-item.h
GnomeDockItem widget
gnome-dock-layout.h
GnomeDockLayout object
gnome-dock.h
GnomeDock widget
gnome-entry.h
GnomeEntry widget
gnome-defs.h
gnome-dentry-edit.h
gnome-dentry.h
gnome-exec.h
gnome-file-entry.h
gnome-fileconvert.h
GnomeFileEntry widget
gnome-font-picker.h
GnomeFontPicker widget
gnome-font-selector.h
GnomeFontSelector widget
gnome-guru.h
gnome-help.h
gnome-history.h
Recently-used-file history
gnome-href.h
GnomeHRef widget
gnome-geometry.h
gnome-i18n.h
gnome-i18nP.h
gnome-ice.h
gnome-icon-entry.h
gnome-icon-item.h
gnome-icon-list.h
GnomeIconList widget
gnome-icon-sel.h
GnomeIconSelection widget
gnome-init.h
gnome-less.h
GnomeLess widget
gnome-mdi-child.h
gnome-mdi-generic-child.h
gnome-mdi-session.h
gnome-mdi.h
gnome-messagebox.h
gnome-metadata.h
gnome-mime-info.h
gnome-mime.h
370
GnomeMDIChild object
GnomeMDIGenericChild object
Session management support for
GnomeMDI
GnomeMDI object
GnomeMessageBox widget
Header
Description
gnome-number-entry.h
GnomeNumberEntry widget
gnome-paper-selector.h
GnomePaperSelector widget
gnome-paper.h
gnome-pixmap-entry.h
GnomePixmapEntry widget
gnome-pixmap.h
GnomePixmap widget
gnome-popt.h
gnome-popup-help.h
gnome-popup-menu.h
gnome-preferences.h
gnome-procbar.h
gnome-properties.h
gnome-property-entries.h
Argument-parsing-related declarations
Routine to add popup help to a widget
Convenience routines to create
right-click popup menus
Routines to load and save certain
Gnome-wide preferences
GnomeProcBar widget
gnome-propertybox.h
GnomePropertyBox widget
gnome-regex.h
gnome-remote.h
gnome-score.h
gnome-scores.h
GnomeScores widget
gnome-sound.h
gnome-spell.h
GnomeSpell widget
gnome-startup.h
gnome-stock.h
gnome-triggers.h
gnome-types.h
gnome-uidefs.h
gnome-url.h
gnome-util.h
gnome-winhints.h
gnome.h
gnorba.h
gtk-clock.h
GtkClock widget
gtk-ted.h
GtkTed widget
371
Header
gtk.h
Description
Includes the public GTK+ headers and
gdk.h
gtkaccelgroup.h
gtkaccellabel.h
GtkAccelLabel widget
gtkadjustment.h
GtkAdjustment object
gtkalignment.h
GtkAlignment widget
gtkarg.h
GtkArg type
gtkarrow.h
GtkArrow widget
gtkaspectframe.h
GtkAspectFrame widget
gtkbbox.h
GtkButtonBox widget
gtkbin.h
GtkBin widget
gtkbindings.h
gtkbox.h
GtkBox widget
gtkbutton.h
GtkButton widget
gtkcalendar.h
GtkCalendar widget
gtkcauldron.h
gtkcheckbutton.h
GtkCheckButton widget
gtkcheckmenuitem.h
GtkCheckMenuItem widget
gtkclist.h
GtkCList widget
gtkcolorsel.h
GtkColorSelection widget
gtkcombo.h
GtkCombo widget
gtkcompat.h
372
gtkcontainer.h
GtkContainer widget
gtkctree.h
GtkCTree widget
gtkcurve.h
GtkCurve widget
gtkdata.h
GtkData object
gtkdial.h
GtkDial widget
gtkdialog.h
GtkDialog widget
gtkdnd.h
gtkdrawingarea.h
GtkDrawingArea widget
gtkeditable.h
GtkEditable widget
gtkentry.h
GtkEntry widget
gtkenums.h
gtkeventbox.h
GtkEventBox widget
gtkfeatures.h
gtkfilesel.h
GtkFileSelection widget
gtkfixed.h
GtkFixed widget
gtkfontsel.h
GtkFontSelection widget
gtkframe.h
GtkFrame widget
gtkgamma.h
GtkGammaCurve widget
gtkgc.h
gtkhandlebox.h
GtkHandleBox widget
Header
Description
gtkhbbox.h
GtkHButtonBox widget
gtkhbox.h
GtkHBox widget
gtkhpaned.h
GtkHPaned widget
gtkhruler.h
GtkHRuler widget
gtkhscale.h
GtkHScale widget
gtkhscrollbar.h
GtkHScrollbar widget
gtkhseparator.h
GtkHSeparator widget
gtkimage.h
GtkImage widget
gtkinputdialog.h
GtkInputDialog widget
gtkintl.h
GTK+ internationalization
gtkitem.h
GtkItem widget
gtkitemfactory.h
GtkItemFactory object
gtklabel.h
GtkLabel widget
gtklayout.h
GtkLayout widget
gtklist.h
GtkList widget
gtklistitem.h
GtkListItem widget
gtkmain.h
gtkmarshal.h
gtkmenu.h
GtkMenu widget
gtkmenubar.h
GtkMenuBar widget
gtkmenufactory.h
gtkmenuitem.h
GtkMenuItem widget
gtkmenushell.h
GtkMenuShell widget
gtkmisc.h
GtkMisc widget
gtknotebook.h
GtkNotebook widget
gtkobject.h
gtkoptionmenu.h
GtkOptionMenu widget
gtkpacker.h
GtkPacker widget
gtkpaned.h
GtkPaned widget
gtkpixmap.h
GtkPixmap widget
gtkpixmapmenuitem.h
GtkPixmapMenuItem widget
gtkplug.h
GtkPlug widget
gtkpreview.h
GtkPreview widget
gtkprogress.h
GtkProgress widget
gtkprogressbar.h
GtkProgressBar widget
gtkradiobutton.h
GtkRadioButton widget
gtkradiomenuitem.h
GtkRadioMenuItem widget
gtkrange.h
GtkRange widget
gtkrc.h
gtkruler.h
GtkRuler widget
gtkscale.h
GtkScale widget
gtkscrollbar.h
GtkScrollbar widget
373
Header
Description
gtkscrolledwindow.h
GtkScrolledWindow widget
gtkselection.h
Selection-handling routines
gtkseparator.h
GtkSeparator widget
gtksignal.h
Signal-related declarations
gtksocket.h
GtkSocket widget
gtkspinbutton.h
GtkSpinButton widget
gtkstatusbar.h
GtkStatusbar widget
gtkstyle.h
374
gtktable.h
GtkTable widget
gtktearoffmenuitem.h
GtkTearoffMenuItem widget
gtktext.h
GtkText widget
gtkthemes.h
gtktipsquery.h
GtkTipsQuery widget
gtktogglebutton.h
GtkToggleButton widget
gtktoolbar.h
GtkToolbar widget
gtktooltips.h
GtkTooltips object
gtktree.h
GtkTree widget
gtktreeitem.h
GtkTreeItem widget
gtktypebuiltins.h
gtktypeutils.h
gtkvbbox.h
GtkVButtonBox widget
gtkvbox.h
GtkVBox widget
gtkviewport.h
GtkViewport widget
gtkvpaned.h
GtkVPaned widget
gtkvruler.h
GtkVRuler widget
gtkvscale.h
GtkVScale widget
gtkvscrollbar.h
GtkVScrollbar widget
gtkvseparator.h
GtkVSeparator widget
gtkwidget.h
gtkwindow.h
GtkWindow widget
libgnome.h
libgnomeui.h
zvtterm.h
ZvtTerm widget
375
#include <glib.h>
void g_list_push_allocator(GAllocator* allocator);
void g_list_pop_allocator(void);
GAllocator* g_allocator_new(gchar* name, guint n_preallocs);
void g_allocator_free(GAllocator* allocator);
376
You should do this before calling gtk_widget_show(), because the function affects
where the window appears when it is first placed on-screen.
377
Theres one exception, however. To realize a widget means to allocate X server resources for it, most notably a GdkWindow. Some things you might want to do require the GdkWindow to exist, so you might want to force a widget to be realized
immediately. gtk_widget_realize() does this. Since parent widgets must be realized before their children, gtk_widget_realize() will immediately realize all of a
widgets parents as well. One of these parents must be a toplevel window, or realization will not be possible.
If you force-realize a widget, you still have to call gtk_widget_show() since realization does not map the widget.
A good but not foolproof rule of thumb: if you are using GTK_WIDGET(widget)>window, you will need widget to be realized.
However, it should be noted that force-realizing a widget is always a mildly bad idea;
it is inefficient and uncomfortably low-level. In many cases you can work around the
need to do so.
378
Write the backend as a library; if this becomes undesirable for any reason, you can
always statically link.
Write at least two frontends from the start; one or both can be ugly prototypes,
you just want to get an idea how to structure the backend. Remember, frontends
should be easy; the backend has the hard parts.
If one of your frontends is Gnome- or GTK+- based, an excellent choice for the other
is an interactive Guile terminal. Your non-expert end users probably wont use it, but
its a great debugging tool; you can prototype and test the backend using easy-towrite Guile bindings, and add the graphical controls only when things are working.
When youre done, youll have a scriptable application almost for free.
If your application can potentially be run in batch mode, command line and web
interfaces are also relatively easy to write, useful for debugging, and will keep you
disciplined.
Finally, if your project is large enough to justify the bother and complexity, consider
using a cross-platform frontend layer to share code between GUI frontends on different platforms. This approach is taken by Mozilla (http://www.mozilla.org), and the
AbiSource office suite (http://www.abisource.com). It might be interesting to have a
look at their code.
379
in your application. Thus GnomeDialog loads a user preference for the dialogs initial
position. This preference can be set from the Gnome control center.
The original authors wanted to write it in C, and now many C-only applications
are based on it. The current authors enjoy C.
GTK+ handles types and objects much more flexibly than C++; it is runtimeoriented, more like Java or Objective C than C++ system. This is convenient for
GUI builders and language bindings.
C is the lingua franca of UNIX development; most people know how to code in it.
There are already nice toolkits for languages such as Java and Objective C. There
are C++ wrappers for GTK+; several, in fact.
C is more portable than C++; ANSI C++ is not yet widely implemented, so only
an ill-defined subset of C++ can actually be used.
When GTK+ development first started, there was no free, working C++ compiler.
Again: do not ask this question on any mailing lists, because people will not be
amused.
380
location. See the section called Mouse Movement Events in Chapter 10.
381
tainers background. If you want to set the background, place the label in a GtkEventBox. The same answer applies to other windowless widgets, such as GtkImage.
ing care of any necessary details before and after emission (remember that only
GTK_RUN_ACTION signals can be emitted without special actions before and after). gtk_whatever_real_foo() will be the default handler for the signal, installed
in the objects class struct. Chapter 11 has many examples of this.
The event youre trying to monitor isnt in the event mask for the widgets GdkWindow. Use gtk_widget_add_events() to add more events to the mask.
The widget is a container, and some child widget is "handling" the event by returning TRUE from the event signal emission. Only "unhandled" events are propagated
from child to parent.
See the section called Receiving GDK Events in GTK+ in Chapter 10 for more details
on events and how they are passed to widgets.
382
If theres a focus widget, the key event signal is emitted on the focus widget. If this
emission returns TRUE, as described in the section called Receiving GDK Events in
GTK+ in Chapter 10, processing stops.
If the key event hasnt been handled yet, there are some default bindings; the
arrow keys move the focus around, for example.
Thus, to override the arrow key behavior, you can return TRUE from the focus widgets signal emission, install an accelerator for the arrow keys, or connect to "key_press_event"
on the toplevel window and use gtk_signal_emit_stop_by_name() to end the signal emission before the GtkWindow default handler runs.
This code will handle all pending events, then return control to you. You can also run
nested instances of gtk_main(); each call to gtk_main_quit() exits one instance.
gnome_dialog_run() uses this technique to block waiting for user input.
The GTK+ coding style is basically the GNU coding style (http://www.gnu.org/prep/standards_toc.html).
The Gnome libraries are less consistent, but lean toward the Linux kernel coding style
383
It also leaves a space between identifiers and opening parentheses. To make Emacs
use the Gnome style, add a line like this to the top of your source files:
/* -*- Mode: C; indent-tabs-mode: nil; c-basic-offset: 8 c-style: "K&R" *- */
When preparing a patch for any piece of free software, its polite the style of the
preexisting code. Its customary to include a file called HACKING in source code distributions addressing this and similar issues; read it if it exists.
384
You should have the source code around, to learn from and to refer to when documentation is lacking.
You should compile with debugging switched on, so preconditions and assertions
will be triggered if you try to use the library incorrectly. Most prebuilt binaries will
turn these checks off for efficiency.
You will probably want unstripped libraries, so you can see function names and
so on in your debugger.
Web sites
GTK+ and Gnome each have home pages; http://www.gtk.org/ and http://www.gnome.org,
respectively.
On the GTK+ site, take special note of these pages:
http://www.gtk.org/faq/ has the GTK+ FAQ; asking these questions on the mailing list is discouraged. Appendix C of this book supplements the official GTK+
FAQ with still more questions; check it out as well.
http://developer.gnome.org was not yet live at press time, but will be available
soon. It will contain comprehensive resources for Gnome developers.
385
Mailing Lists
Here are some of the mailing lists that cover GTK+ and Gnome development topics:
application development. Most things appropriate for this list are also appropriate
for gtk-list, but gtk-app-devel-list has less traffic if youre concerned about
that.
is for discussion of developing the glib, GDK, and
GTK+ libraries. It is not for discussion of using the libraries to develop applications.
gtk-devel-list@redhat.com
gnome-announce-list@gnome.org
To subscribe to any of these mailing lists, append -request to the list name and
send a message with subscribe my-address@wherever.net in the subject. For example, I would subscribe to gtk-list@redhat.com by sending a message to gtklist-request@redhat.com with subscribe hp@pobox.com in the subject line.
Please, ask any and all questions about GTK+ and Gnome development on one of
the mailing lists or on IRC. It is inappropriate to mail the developers privately, unless
you have reason to believe they have special knowledge of some particular section
of code. Youll almost certainly get a faster and better response from the list anyway.
This Book
This book is available online at http://developer.gnome.org/doc/GGAD
386
hello.c
#include <config.h>
#include <gnome.h>
#include "app.h"
387
{
NULL,
\0,
0,
NULL,
0,
NULL,
NULL
}
};
int
main(int argc, char* argv[])
{
GtkWidget* app;
poptContext pctx;
char** args;
int i;
GSList* greet = NULL;
GnomeClient* client;
bindtextdomain(PACKAGE, GNOMELOCALEDIR);
textdomain(PACKAGE);
gnome_init_with_popt_table(PACKAGE, VERSION, argc, argv,
options, 0, &pctx);
/* Argument parsing */
args = poptGetArgs(pctx);
if (greet_mode && args)
{
i = 0;
while (args[i] != NULL)
{
greet = g_slist_prepend(greet, args[i]);
++i;
}
/* Put them in order */
greet = g_slist_reverse(greet);
}
else if (greet_mode && args == NULL)
{
g_error(_("You must specify someone to greet."));
}
else if (args != NULL)
{
g_error(_("Command line arguments are only allowed with -greet."));
}
else
{
g_assert(!greet_mode && args == NULL);
}
poptFreeContext(pctx);
/* Session Management */
388
/* Main app */
app = hello_app_new(message, geometry, greet);
g_slist_free(greet);
gtk_widget_show_all(app);
gtk_main();
return 0;
}
static gint
save_session (GnomeClient *client, gint phase, GnomeSaveStyle save_style,
gint is_shutdown, GnomeInteractStyle interact_style,
gint is_fast, gpointer client_data)
{
gchar** argv;
guint argc;
/* allocate 0-filled, so it will be NULL-terminated */
argv = g_malloc0(sizeof(gchar*)*4);
argc = 1;
argv[0] = client_data;
if (message)
{
argv[1] = "-message";
argv[2] = message;
argc = 3;
}
gnome_client_set_clone_command (client, argc, argv);
gnome_client_set_restart_command (client, argc, argv);
return TRUE;
}
static void
session_die(GnomeClient* client, gpointer client_data)
{
gtk_main_quit ();
}
app.h
#ifndef GNOMEHELLO_APP_H
#define GNOMEHELLO_APP_H
389
#include <gnome.h>
GtkWidget* hello_app_new(const gchar* message,
const gchar* geometry,
GSList* greet);
void
hello_app_close(GtkWidget* app);
#endif
app.c
#include <config.h>
#include "app.h"
#include "menus.h"
/* Keep a list of all open application windows */
static GSList* app_list = NULL;
static gint delete_event_cb(GtkWidget* w, GdkEventAny* e, gpointer data);
static void button_click_cb(GtkWidget* w, gpointer data);
GtkWidget*
hello_app_new(const gchar* message,
const gchar* geometry,
GSList* greet)
{
GtkWidget* app;
GtkWidget* button;
GtkWidget* label;
GtkWidget* status;
GtkWidget* frame;
app = gnome_app_new(PACKAGE, _("Gnome Hello"));
frame = gtk_frame_new(NULL);
button = gtk_button_new();
label
390
gnome_app_set_statusbar(GNOME_APP(app), status);
hello_install_menus_and_toolbar(app);
gtk_signal_connect(GTK_OBJECT(app),
"delete_event",
GTK_SIGNAL_FUNC(delete_event_cb),
NULL);
gtk_signal_connect(GTK_OBJECT(button),
"clicked",
GTK_SIGNAL_FUNC(button_click_cb),
label);
if (geometry != NULL)
{
gint x, y, w, h;
if ( gnome_parse_geometry( geometry,
&x, &y, &w, &h ) )
{
if (x != -1)
{
gtk_widget_set_uposition(app, x, y);
}
if (w != -1)
{
gtk_window_set_default_size(GTK_WINDOW(app), w, h);
}
}
else
{
g_error(_("Could not parse geometry string %s"), geometry);
}
}
if (greet != NULL)
{
GtkWidget* dialog;
gchar* greetings = g_strdup(_("Special Greetings to:\n"));
GSList* tmp = greet;
while (tmp != NULL)
{
gchar* old = greetings;
greetings = g_strconcat(old,
(gchar*) tmp->data,
"\n",
NULL);
g_free(old);
tmp = g_slist_next(tmp);
}
dialog = gnome_ok_dialog(greetings);
g_free(greetings);
gnome_dialog_set_parent(GNOME_DIALOG(dialog), GTK_WINDOW(app));
}
391
menus.h
#ifndef GNOMEHELLO_MENUS_H
#define GNOMEHELLO_MENUS_H
392
#include <gnome.h>
void hello_install_menus_and_toolbar(GtkWidget* app);
#endif
menus.c
#include <config.h>
#include "menus.h"
#include "app.h"
static
static
static
static
static
void
void
void
void
void
nothing_cb(GtkWidget*
new_app_cb(GtkWidget*
close_cb (GtkWidget*
exit_cb
(GtkWidget*
about_cb (GtkWidget*
widget,
widget,
widget,
widget,
widget,
gpointer
gpointer
gpointer
gpointer
gpointer
data);
data);
data);
data);
data);
393
GNOMEUIINFO_END
};
static GnomeUIInfo menu [] = {
GNOMEUIINFO_MENU_FILE_TREE(file_menu),
GNOMEUIINFO_MENU_EDIT_TREE(edit_menu),
GNOMEUIINFO_MENU_HELP_TREE(help_menu),
GNOMEUIINFO_END
};
void
hello_install_menus_and_toolbar(GtkWidget* app)
{
gnome_app_create_toolbar_with_data(GNOME_APP(app), toolbar, app);
gnome_app_create_menus_with_data(GNOME_APP(app), menu, app);
gnome_app_install_menu_hints(GNOME_APP(app), menu);
}
static void
nothing_cb(GtkWidget* widget, gpointer data)
{
GtkWidget* dialog;
GtkWidget* app;
app = (GtkWidget*) data;
dialog = gnome_ok_dialog_parented(
_("This does nothing; it is only a demonstration."),
GTK_WINDOW(app));
}
static void
new_app_cb(GtkWidget* widget, gpointer data)
{
GtkWidget* app;
app = hello_app_new(_("Hello, World!"), NULL, NULL);
gtk_widget_show_all(app);
}
static void
close_cb(GtkWidget* widget, gpointer data)
{
GtkWidget* app;
app = (GtkWidget*) data;
hello_app_close(app);
}
394
static void
exit_cb(GtkWidget* widget, gpointer data)
{
gtk_main_quit();
}
static void
about_cb(GtkWidget* widget, gpointer data)
{
static GtkWidget* dialog = NULL;
GtkWidget* app;
app = (GtkWidget*) data;
if (dialog != NULL)
{
g_assert(GTK_WIDGET_REALIZED(dialog));
gdk_window_show(dialog->window);
gdk_window_raise(dialog->window);
}
else
{
const gchar *authors[] = {
"Havoc Pennington <hp@pobox.com>",
NULL
};
gchar* logo = gnome_pixmap_file("gnome-hello-logo.png");
dialog = gnome_about_new (_("GnomeHello"), VERSION,
"(C) 1999 Havoc Pennington",
authors,
_("A sample GNOME application."),
logo);
g_free(logo);
gtk_signal_connect(GTK_OBJECT(dialog),
"destroy",
GTK_SIGNAL_FUNC(gtk_widget_destroyed),
&dialog);
gnome_dialog_set_parent(GNOME_DIALOG(dialog), GTK_WINDOW(app));
gtk_widget_show(dialog);
}
}
395
gtkev.h
#ifndef INC_GTK_EV_H
#define INC_GTK_EV_H
#include <gtk/gtkwidget.h>
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
#define GTK_EV(obj)
#define GTK_EV_CLASS(klass)
#define GTK_IS_EV(obj)
typedef struct _GtkEv
typedef struct _GtkEvClass
struct _GtkEv
{
GtkWidget widget;
GdkWindow*
event_window;
GdkRectangle
event_window_rect;
GdkRectangle
description_rect;
GList*
GList*
gint
buffer;
buffer_end;
buffer_size;
};
struct _GtkEvClass
{
GtkWidgetClass parent_class;
};
guint
GtkWidget*
gtk_ev_get_type
gtk_ev_new
(void);
(void);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* __GTK_EV_H__ */
gtkev.c
#include "gtkev.h"
static void
static void
396
gtk_ev_class_init
gtk_ev_init
(GtkEvClass
(GtkEv
*klass);
*ev);
/* GtkObject functions */
static void
gtk_ev_destroy
(GtkObject
*object);
/* GtkWidget functions */
static gint
gtk_ev_event (GtkWidget
GdkEvent
*widget,
*event);
(GtkWidget
(GtkWidget
(GtkWidget
GtkRequisition
(GtkWidget
GtkAllocation
*widget);
*widget);
*widget,
*requisition);
*widget,
*allocation);
(GtkWidget
GdkRectangle
(GtkWidget
*widget,
*area);
*widget);
(GtkWidget
GdkEventExpose
(GtkWidget
GdkEventFocus
(GtkWidget
GdkEventFocus
*widget,
*event);
*widget,
*event);
*widget,
*event);
(GtkEv
GdkRectangle
*ev,
*area);
/* GtkEv-specific functions */
static void gtk_ev_paint
(GtkEv
GdkRectangle
(GtkEv
const gchar*
*ev,
*area);
*ev,
text);
/* Utility Functions */
static gchar* event_to_text (GdkEvent* event);
static GtkWidgetClass *parent_class = NULL;
guint
gtk_ev_get_type (void)
{
static guint ev_type = 0;
if (!ev_type)
{
static const GtkTypeInfo ev_info =
{
"GtkEv",
sizeof (GtkEv),
sizeof (GtkEvClass),
(GtkClassInitFunc) gtk_ev_class_init,
(GtkObjectInitFunc) gtk_ev_init,
/* reserved_1 */ NULL,
/* reserved_2 */ NULL,
(GtkClassInitFunc) NULL,
397
};
ev_type = gtk_type_unique (gtk_widget_get_type (), &ev_info);
}
return ev_type;
}
static void
gtk_ev_class_init (GtkEvClass *klass)
{
GtkObjectClass *object_class;
GtkWidgetClass *widget_class;
object_class = (GtkObjectClass*) klass;
widget_class = (GtkWidgetClass*) klass;
parent_class = gtk_type_class (gtk_widget_get_type ());
object_class->destroy = gtk_ev_destroy;
widget_class->realize = gtk_ev_realize;
widget_class->unrealize = gtk_ev_unrealize;
widget_class->size_request = gtk_ev_size_request;
widget_class->size_allocate = gtk_ev_size_allocate;
widget_class->draw = gtk_ev_draw;
widget_class->event = gtk_ev_event;
widget_class->draw_focus = gtk_ev_draw_focus;
widget_class->expose_event = gtk_ev_expose;
widget_class->focus_in_event = gtk_ev_focus_in;
widget_class->focus_out_event = gtk_ev_focus_out;
}
static void
gtk_ev_init (GtkEv *ev)
{
GTK_WIDGET_SET_FLAGS (GTK_WIDGET(ev), GTK_CAN_FOCUS);
ev->event_window
ev->buffer
ev->buffer_end
ev->buffer_size
=
=
=
=
NULL;
NULL;
NULL;
0;
ev->event_window_rect.x = ev->event_window_rect.y = 0;
ev->event_window_rect.width = ev->event_window_rect.height = 0;
ev->description_rect.x = ev->description_rect.y = 0;
ev->description_rect.width = ev->description_rect.height = 0;
}
GtkWidget*
gtk_ev_new (void)
{
GtkEv *ev;
ev = gtk_type_new (gtk_ev_get_type ());
398
*object)
g_return_if_fail(object != NULL);
g_return_if_fail(GTK_IS_EV(object));
ev = GTK_EV(object);
tmp = ev->buffer;
while (tmp != NULL)
{
g_strfreev((gchar**)tmp->data);
tmp = g_list_next(tmp);
}
g_list_free(ev->buffer);
ev->buffer = NULL;
ev->buffer_end = NULL;
ev->buffer_size = 0;
/* Chain up */
if (GTK_OBJECT_CLASS(parent_class)->destroy)
(* GTK_OBJECT_CLASS(parent_class)->destroy) (object);
}
/* GtkWidget functions */
static gint
gtk_ev_event (GtkWidget
GdkEvent
{
GtkEv* ev;
*widget,
*event)
399
text = event_to_text(event);
gtk_ev_push_text(ev, text);
g_free(text);
/* If it was a motion event, make sure we get more */
if (event->type == GDK_MOTION_NOTIFY)
{
gdk_window_get_pointer(ev->event_window, NULL, NULL, NULL);
}
/* We didnt "handle" the event, just listened in on it. */
return FALSE;
}
}
static void
gtk_ev_realize
(GtkWidget
{
GdkWindowAttr attributes;
gint attributes_mask;
GtkEv* ev;
GdkCursor* cursor;
*widget)
g_return_if_fail(widget != NULL);
g_return_if_fail(GTK_IS_EV(widget));
ev = GTK_EV(widget);
/* Set realized flag */
GTK_WIDGET_SET_FLAGS (widget, GTK_REALIZED);
/* Main widget window */
attributes.window_type = GDK_WINDOW_CHILD;
attributes.x = widget->allocation.x;
attributes.y = widget->allocation.y;
attributes.width = widget->allocation.width;
attributes.height = widget->allocation.height;
attributes.wclass = GDK_INPUT_OUTPUT;
attributes.visual = gtk_widget_get_visual (widget);
attributes.colormap = gtk_widget_get_colormap (widget);
attributes.event_mask = gtk_widget_get_events (widget) | GDK_EXPOSURE_MASK;
attributes_mask = GDK_WA_X | GDK_WA_Y | GDK_WA_VISUAL | GDK_WA_COLORMAP;
widget->window = gdk_window_new (gtk_widget_get_parent_window (widget),
&attributes, attributes_mask);
gdk_window_set_user_data (widget->window, widget);
/* Event window */
cursor = gdk_cursor_new(GDK_CROSSHAIR);
attributes.window_type = GDK_WINDOW_CHILD;
attributes.x = ev->event_window_rect.x;
attributes.y = ev->event_window_rect.y;
attributes.width = ev->event_window_rect.width;
attributes.height = ev->event_window_rect.height;
attributes.wclass = GDK_INPUT_OUTPUT;
attributes.visual = gtk_widget_get_visual (widget);
400
*widget)
g_return_if_fail(widget != NULL);
g_return_if_fail(GTK_IS_EV(widget));
ev = GTK_EV(widget);
/* Hide all windows */
if (GTK_WIDGET_MAPPED (widget))
gtk_widget_unmap (widget);
GTK_WIDGET_UNSET_FLAGS (widget, GTK_MAPPED);
/* Destroy our child window */
if (ev->event_window)
{
gdk_window_set_user_data(ev->event_window, NULL);
gdk_window_destroy(ev->event_window);
ev->event_window = NULL;
}
/* This destroys widget->window and unsets the realized flag
*/
if (GTK_WIDGET_CLASS(parent_class)->unrealize)
(* GTK_WIDGET_CLASS(parent_class)->unrealize) (widget);
}
static void
gtk_ev_size_request
(GtkWidget
GtkRequisition
*widget,
*requisition)
{
g_return_if_fail(widget != NULL);
g_return_if_fail(GTK_IS_EV(widget));
401
/*
* GtkEv always wants to be the same fixed size.
*/
requisition->width = 450;
requisition->height = 300;
}
static void
gtk_ev_size_allocate
(GtkWidget
GtkAllocation
*widget,
*allocation)
{
static const gint spacing = 10;
GtkEv* ev;
g_return_if_fail(widget != NULL);
g_return_if_fail(GTK_IS_EV(widget));
ev = GTK_EV(widget);
widget->allocation = *allocation;
ev->event_window_rect.width =
MAX(allocation->width - spacing*2, 0);
ev->event_window_rect.height =
MAX(allocation->height / 5 - spacing / 2, 0);
ev->event_window_rect.x =
(allocation->width - ev->event_window_rect.width)/2;
ev->event_window_rect.y =
MIN(spacing, allocation->height);
ev->description_rect.x = ev->event_window_rect.x;
ev->description_rect.y =
ev->event_window_rect.y + ev->event_window_rect.height + spacing;
ev->description_rect.width =
ev->event_window_rect.width;
ev->description_rect.height =
MAX((allocation->height - ev->event_window_rect.height - spacing*3), 0);
if (GTK_WIDGET_REALIZED (widget))
{
gdk_window_move_resize (widget->window,
allocation->x,
allocation->y,
allocation->width,
allocation->height);
gdk_window_move_resize (ev->event_window,
ev->event_window_rect.x,
ev->event_window_rect.y,
ev->event_window_rect.width,
ev->event_window_rect.height);
}
}
static void
gtk_ev_draw
(GtkWidget
GdkRectangle
{
GdkRectangle event_window_area;
GdkRectangle intersection;
402
*widget,
*area)
GtkEv* ev;
g_return_if_fail(widget != NULL);
g_return_if_fail(GTK_IS_EV(widget));
ev = GTK_EV(widget);
gtk_ev_paint(ev, area);
event_window_area = *area;
if (gdk_rectangle_intersect(area, &ev->event_window_rect, &intersection))
{
/* Make the intersection relative to the event window */
intersection.x -= ev->event_window_rect.x;
intersection.y -= ev->event_window_rect.y;
gtk_ev_paint_event_window(ev, &intersection);
}
}
static void
gtk_ev_draw_focus
{
GdkRectangle rect;
GtkEv* ev;
(GtkWidget
*widget)
g_return_if_fail(widget != NULL);
g_return_if_fail(GTK_IS_EV(widget));
ev = GTK_EV(widget);
rect.x = 0;
rect.y = 0;
rect.width = widget->allocation.width;
rect.height = widget->allocation.height;
if (GTK_WIDGET_DRAWABLE (ev))
gtk_ev_paint(ev, &rect);
}
static gint
gtk_ev_expose
(GtkWidget
GdkEventExpose
*widget,
*event)
{
if (event->window == widget->window)
gtk_ev_paint(GTK_EV(widget), &event->area);
else if (event->window == GTK_EV(widget)->event_window)
gtk_ev_paint_event_window(GTK_EV(widget), &event->area);
else
g_assert_not_reached();
return TRUE;
}
static gint
gtk_ev_focus_in
(GtkWidget
GdkEventFocus
*widget,
*event)
{
g_return_val_if_fail(widget != NULL, FALSE);
g_return_val_if_fail(GTK_IS_EV(widget), FALSE);
GTK_WIDGET_SET_FLAGS (widget, GTK_HAS_FOCUS);
403
gtk_widget_draw_focus (widget);
return FALSE;
}
static gint
gtk_ev_focus_out
(GtkWidget
GdkEventFocus
*widget,
*event)
{
g_return_val_if_fail(widget != NULL, FALSE);
g_return_val_if_fail(GTK_IS_EV(widget), FALSE);
GTK_WIDGET_UNSET_FLAGS (widget, GTK_HAS_FOCUS);
gtk_widget_draw_focus (widget);
return FALSE;
}
/* GtkEv-specific functions */
static void
gtk_ev_paint
(GtkEv
GdkRectangle
*ev,
*area)
{
GtkWidget* widget;
g_return_if_fail(ev != NULL);
g_return_if_fail(GTK_IS_EV(ev));
widget = GTK_WIDGET(ev);
if (!GTK_WIDGET_DRAWABLE (widget))
return;
gdk_window_clear_area (widget->window,
area->x,
area->y,
area->width,
area->height);
gdk_gc_set_clip_rectangle(widget->style->black_gc, area);
/* Draw a black rectangle around the event window */
gdk_draw_rectangle(widget->window,
widget->style->black_gc,
FALSE,
ev->event_window_rect.x - 1,
ev->event_window_rect.y - 1,
ev->event_window_rect.width + 2,
ev->event_window_rect.height + 2);
gdk_gc_set_clip_rectangle(widget->style->black_gc, NULL);
/* Draw text in the description area, if applicable */
if (ev->buffer)
{
GdkRectangle intersection;
if (gdk_rectangle_intersect(area,
&ev->description_rect,
&intersection))
404
{
static const gint space = 2;
gint line;
gint step;
gint first_baseline;
GList* tmp;
step = widget->style->font->ascent +
widget->style->font->descent + space;
first_baseline = ev->description_rect.y +
widget->style->font->ascent + space;
line = 0;
tmp = ev->buffer;
while (tmp != NULL)
{
gchar** this_event = tmp->data;
gint i = 0;
while (this_event[i])
{
gtk_paint_string (widget->style,
widget->window,
widget->state,
&intersection, widget, "ev",
ev->description_rect.x,
first_baseline + line*step,
this_event[i]);
++i;
++line;
}
/* Bail out if were off the bottom; the "- 2*step" is
* needed because the next baseline may be outside the
* redraw area but we are interested in the whole row of
* text, not the baseline. The 2* is because line is one
* larger than weve actually drawn.
*/
if ((first_baseline + line*step - 2*step) >
(intersection.y + intersection.height))
break;
tmp = g_list_next(tmp);
}
}
}
if (GTK_WIDGET_HAS_FOCUS (widget))
{
gtk_paint_focus (widget->style, widget->window,
area, widget, "ev",
widget->allocation.x, widget->allocation.y,
widget->allocation.width-1, widget->allocation.height1);
}
}
static void
gtk_ev_paint_event_window
(GtkEv
GdkRectangle
*ev,
*area)
405
GtkWidget* widget;
gint width;
gint x, y;
const char* title;
g_return_if_fail(ev != NULL);
g_return_if_fail(GTK_IS_EV(ev));
widget = GTK_WIDGET(ev);
if (!GTK_WIDGET_DRAWABLE (widget))
return;
title = _("Event Window");
gdk_window_clear_area (ev->event_window,
area->x,
area->y,
area->width,
area->height);
gdk_gc_set_clip_rectangle(widget->style->black_gc, area);
/* Clearly it would be better to cache this */
width = gdk_string_width(widget->style->font,
title);
x = (ev->event_window_rect.width - width)/2;
y = widget->style->font->ascent + 2;
gdk_draw_string(ev->event_window,
widget->style->font,
widget->style->black_gc,
x, y,
title);
gdk_gc_set_clip_rectangle(widget->style->black_gc, NULL);
}
static void
gtk_ev_push_text (GtkEv
*ev,
const gchar*
text)
{
if (text)
{
gchar** event;
event = g_strsplit(text, "\n", 10);
ev->buffer = g_list_prepend(ev->buffer, event);
ev->buffer_size += 1;
/* See if this was the first one we added */
if (ev->buffer_end == NULL)
{
ev->buffer_end = ev->buffer;
}
/* See if we have too many to possibly fit on-screen */
if (ev->buffer_size > 100)
{
GList* prev = ev->buffer_end->prev;
prev->next = NULL;
406
g_strfreev(ev->buffer_end->data);
g_list_free_1(ev->buffer_end);
ev->buffer_end = prev;
ev->buffer_size -= 1;
}
}
if (GTK_WIDGET_DRAWABLE (ev))
gtk_widget_queue_draw_area(GTK_WIDGET(ev),
ev->description_rect.x,
ev->description_rect.y,
ev->description_rect.width,
ev->description_rect.height);
}
static gchar*
event_name_line(GdkEvent* event)
{
switch (event->type)
{
case GDK_NOTHING:
return g_strdup(_("Invalid event!\n"));
break;
case GDK_DELETE:
return g_strdup(_("Delete\n"));
break;
case GDK_DESTROY:
return g_strdup(_("Destroy\n"));
break;
case GDK_EXPOSE:
return g_strdup(_("Expose\n"));
break;
case GDK_MOTION_NOTIFY:
return g_strdup(_("Motion Notify\n"));
break;
case GDK_BUTTON_PRESS:
return g_strdup(_("Button Press\n"));
break;
case GDK_2BUTTON_PRESS:
return g_strdup(_("2 Button Press\n"));
break;
case GDK_3BUTTON_PRESS:
return g_strdup(_("3 Button Press\n"));
break;
case GDK_BUTTON_RELEASE:
return g_strdup(_("Button Release\n"));
break;
case GDK_KEY_PRESS:
return g_strdup(_("Key Press\n"));
break;
407
case GDK_KEY_RELEASE:
return g_strdup(_("Key Release\n"));
break;
case GDK_ENTER_NOTIFY:
return g_strdup(_("Enter Notify\n"));
break;
case GDK_LEAVE_NOTIFY:
return g_strdup(_("Leave Notify\n"));
break;
case GDK_FOCUS_CHANGE:
return g_strdup(_("Focus Change\n"));
break;
case GDK_CONFIGURE:
return g_strdup(_("Configure\n"));
break;
case GDK_MAP:
return g_strdup(_("Map\n"));
break;
case GDK_UNMAP:
return g_strdup(_("Unmap\n"));
break;
case GDK_PROPERTY_NOTIFY:
return g_strdup(_("Property Notify\n"));
break;
case GDK_SELECTION_CLEAR:
return g_strdup(_("Selection Clear\n"));
break;
case GDK_SELECTION_REQUEST:
return g_strdup(_("Selection Request\n"));
break;
case GDK_SELECTION_NOTIFY:
return g_strdup(_("Selection Notify\n"));
break;
case GDK_PROXIMITY_IN:
return g_strdup(_("Proximity In\n"));
break;
case GDK_PROXIMITY_OUT:
return g_strdup(_("Proximity Out\n"));
break;
case GDK_DRAG_ENTER:
return g_strdup(_("Drag Enter\n"));
break;
case GDK_DRAG_LEAVE:
return g_strdup(_("Drag Leave\n"));
break;
case GDK_DRAG_MOTION:
return g_strdup(_("Drag Motion\n"));
break;
408
case GDK_DRAG_STATUS:
return g_strdup(_("Drag Status\n"));
break;
case GDK_DROP_START:
return g_strdup(_("Drop Start\n"));
break;
case GDK_DROP_FINISHED:
return g_strdup(_("Drop Finished\n"));
break;
case GDK_CLIENT_EVENT:
return g_strdup(_("Client Event\n"));
break;
case GDK_VISIBILITY_NOTIFY:
return g_strdup(_("Visibility Notify\n"));
break;
case GDK_NO_EXPOSE:
return g_strdup(_("No Expose\n"));
break;
default:
g_assert_not_reached();
return NULL;
break;
}
}
static gchar*
any_event_line(GdkEvent* event)
{
guint32 event_time;
event_time = gdk_event_get_time(event);
if (event_time != GDK_CURRENT_TIME)
return g_strdup_printf(_("Window: %p Time: %u send_event: %s\n"),
event->any.window,
event_time,
event->any.send_event ? _("True") : _("False"));
else
return g_strdup_printf(_("Window: %p send_event: %s\n"),
event->any.window,
event->any.send_event ? _("True") : _("False"));
}
#define MAX_STATES 30
static gchar*
event_state_line(GdkModifierType state)
{
gchar** states;
gint n_active;
states = g_new(gchar*, MAX_STATES);
n_active = 0;
if (state & GDK_SHIFT_MASK)
409
{
states[n_active] = _("Shift");
++n_active;
}
if (state & GDK_LOCK_MASK)
{
states[n_active] = _("Lock");
++n_active;
}
if (state & GDK_CONTROL_MASK)
{
states[n_active] = _("Ctrl");
++n_active;
}
if (state & GDK_MOD1_MASK)
{
states[n_active] = _("Mod1");
++n_active;
}
if (state & GDK_MOD2_MASK)
{
states[n_active] = _("Mod2");
++n_active;
}
if (state & GDK_MOD3_MASK)
{
states[n_active] = _("Mod3");
++n_active;
}
if (state & GDK_MOD4_MASK)
{
states[n_active] = _("Mod4");
++n_active;
}
if (state & GDK_MOD5_MASK)
{
states[n_active] = _("Mod5");
++n_active;
}
if (state & GDK_BUTTON1_MASK)
{
states[n_active] = _("Button1");
++n_active;
}
if (state & GDK_BUTTON2_MASK)
{
states[n_active] = _("Button2");
++n_active;
}
if (state & GDK_BUTTON3_MASK)
{
states[n_active] = _("Button3");
++n_active;
}
if (state & GDK_BUTTON4_MASK)
{
states[n_active] = _("Button4");
++n_active;
}
if (state & GDK_BUTTON5_MASK)
{
states[n_active] = _("Button4");
++n_active;
410
}
if (state & GDK_RELEASE_MASK)
{
states[n_active] = _("Release");
++n_active;
}
if (n_active == 0)
return NULL;
else
{
/* Not efficient, but not important */
gchar* str = NULL;
gchar* tmp = NULL;
guint i = 0;
while (i < n_active)
{
if (str)
{
tmp = str;
str = g_strconcat(str, " | ", states[i], NULL);
g_free(tmp);
}
else
{
str = g_strdup(states[i]);
}
++i;
}
tmp = str;
str = g_strconcat(str, "\n", NULL);
g_free(tmp);
return str;
}
}
static gchar*
event_to_text (GdkEvent* event)
{
gchar* any_line;
gchar* name_line;
gchar* entire_line;
gchar* detail;
gchar* state;
name_line = event_name_line(event);
any_line = any_event_line(event);
entire_line = NULL;
detail = NULL;
state = NULL;
switch (event->type)
{
case GDK_NOTHING:
break;
411
case GDK_DELETE:
break;
case GDK_DESTROY:
break;
case GDK_EXPOSE:
detail = g_strdup_printf(_("Area: %d,%d %dx%d Count: %d\n"),
event->expose.area.x,
event->expose.area.y,
event->expose.area.width,
event->expose.area.height,
event->expose.count);
break;
case GDK_MOTION_NOTIFY:
detail = g_strdup_printf(_("x: %g y: %g\n"),
event->motion.x,
event->motion.y);
state = event_state_line(event->motion.state);
break;
case GDK_BUTTON_PRESS:
case GDK_2BUTTON_PRESS:
case GDK_3BUTTON_PRESS:
case GDK_BUTTON_RELEASE:
detail = g_strdup_printf(_("Button: %d\n"),
event->button.button);
state = event_state_line(event->button.state);
break;
case GDK_KEY_PRESS:
case GDK_KEY_RELEASE:
detail = g_strdup_printf(_("Keyval: GDK_%s Text: %s\n"),
gdk_keyval_name(event->key.keyval),
event->key.string);
state = event_state_line(event->key.state);
break;
case GDK_ENTER_NOTIFY:
break;
case GDK_LEAVE_NOTIFY:
break;
case GDK_FOCUS_CHANGE:
break;
case GDK_CONFIGURE:
break;
case GDK_MAP:
break;
case GDK_UNMAP:
break;
case GDK_PROPERTY_NOTIFY:
break;
case GDK_SELECTION_CLEAR:
break;
412
case GDK_SELECTION_REQUEST:
break;
case GDK_SELECTION_NOTIFY:
break;
case GDK_PROXIMITY_IN:
break;
case GDK_PROXIMITY_OUT:
break;
case GDK_DRAG_ENTER:
break;
case GDK_DRAG_LEAVE:
break;
case GDK_DRAG_MOTION:
break;
case GDK_DRAG_STATUS:
break;
case GDK_DROP_START:
break;
case GDK_DROP_FINISHED:
break;
case GDK_CLIENT_EVENT:
break;
case GDK_VISIBILITY_NOTIFY:
break;
case GDK_NO_EXPOSE:
break;
default:
g_assert_not_reached();
break;
}
if (entire_line == NULL)
{
/* Assumes we always have a detail if we have a state */
entire_line = g_strconcat(name_line,
" ", any_line,
detail ? " " : NULL, detail,
state ? " " : NULL, state,
NULL);
}
g_free(name_line);
g_free(any_line);
g_free(detail);
g_free(state);
return entire_line;
}
413