Libx11 PDF
Libx11 PDF
X Consortium Standard
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Except as contained in this notice, the name of The Open Group shall not be used in advertising or otherwise to
promote the sale, use or other dealings in this Software without prior written authorization from The Open Group.
Copyright © 1985, 1986, 1987, 1988, 1989, 1991 Digital Equipment Corporation
Permission to use, copy, modify and distribute this documentation for any purpose and without fee is hereby granted,
provided that the above copyright notice appears in all copies and that both that copyright notice and this permission
notice appear in supporting documentation, and that the names of Digital and Tetronix not be used in in advertising
or publicity pertaining to distribution of the software without specific, written prior permission. Digital and Tetronix
make no representations about the suitability of the software described herein for any purpose. It is provided “as
is” without express or implied warranty.
iii
Xlib - C Language X Interface
iv
Xlib - C Language X Interface
v
Xlib - C Language X Interface
vi
Xlib - C Language X Interface
vii
Xlib - C Language X Interface
viii
List of Tables
A.1. Protocol requests made by each Xlib function ........................................... 394
A.2. Xlib functions which use each Protocol Request ........................................ 400
ix
Acknowledgments
The design and implementation of the first 10 versions of X were primarily the work
of three individuals: Robert Scheifler of the MIT Laboratory for Computer Science
and Jim Gettys of Digital Equipment Corporation and Ron Newman of MIT, both at
MIT Project Athena. X version 11, however, is the result of the efforts of dozens of
individuals at almost as many locations and organizations. At the risk of offending
some of the players by exclusion, we would like to acknowledge some of the people
who deserve special credit and recognition for their work on Xlib. Our apologies to
anyone inadvertently overlooked.
Release 1
Our thanks does to Ron Newman (MIT Project Athena), who contributed
substantially to the design and implementation of the Version 11 Xlib interface.
Our thanks also goes to Ralph Swick (Project Athena and Digital) who kept it all
together for us during the early releases. He handled literally thousands of requests
from people everywhere and saved the sanity of at least one of us. His calm good
cheer was a foundation on which we could build.
Our thanks also goes to Todd Brunhoff (Tektronix) who was ``loaned'' to Project
Athena at exactly the right moment to provide very capable and much-needed
assistance during the alpha and beta releases. He was responsible for the successful
integration of sources from multiple sites; we would not have had a release without
him.
Our thanks also goes to Al Mento and Al Wojtas of Digital's ULTRIX Documentation
Group. With good humor and cheer, they took a rough draft and made it an
infinitely better and more useful document. The work they have done will help
many everywhere. We also would like to thank Hal Murray (Digital SRC) and Peter
George (Digital VMS) who contributed much by proofreading the early drafts of this
document.
Our thanks also goes to Jeff Dike (Digital UEG), Tom Benson, Jackie Granfield, and
Vince Orgovan (Digital VMS) who helped with the library utilities implementation;
to Hania Gajewska (Digital UEG-WSL) who, along with Ellis Cohen (CMU and
Siemens), was instrumental in the semantic design of the window manager
properties; and to Dave Rosenthal (Sun Microsystems) who also contributed to
the protocol and provided the sample generic color frame buffer device-dependent
code.
The alpha and beta test participants deserve special recognition and thanks as
well. It is significant that the bug reports (and many fixes) during alpha and
beta test came almost exclusively from just a few of the alpha testers, mostly
hardware vendors working on product implementations of X. The continued public
contribution of vendors and universities is certainly to the benefit of the entire X
community.
x
Acknowledgments
in order to make version 11 a reality. Many of the people mentioned here are part
of the Western Software Laboratory (Digital UEG-WSL) of the ULTRIX Engineering
group and work for Smokey Wallace, who has been vital to the project's success.
Others not mentioned here worked on the toolkit and are acknowledged in the X
Toolkit documentation.
Finally, our thanks goes to MIT, Digital Equipment Corporation, and IBM for
providing the environment where it could happen.
Release 4
Our thanks go to Jim Fulton (MIT X Consortium) for designing and specifying the
new Xlib functions for Inter-Client Communication Conventions (ICCCM) support.
We also thank Al Mento of Digital for his continued effort in maintaining this
document and Jim Fulton and Donna Converse (MIT X Consortium) for their much-
appreciated efforts in reviewing the changes.
Release 5
The principal authors of the Input Method facilities are Vania Joloboff (Open
Software Foundation) and Bill McMahon (Hewlett-Packard). The principal author
of the rest of the internationalization facilities is Glenn Widener (Tektronix). Our
thanks to them for keeping their sense of humor through a long and sometimes
difficult design process. Although the words and much of the design are due to
them, many others have contributed substantially to the design and implementation.
Tom McFarland (HP) and Frank Rojas (IBM) deserve particular recognition for their
contributions. Other contributors were: Tim Anderson (Motorola), Alka Badshah
(OSF), Gabe Beged-Dov (HP), Chih-Chung Ko (III), Vera Cheng (III), Michael Collins
(Digital), Walt Daniels (IBM), Noritoshi Demizu (OMRON), Keisuke Fukui (Fujitsu),
Hitoshoi Fukumoto (Nihon Sun), Tim Greenwood (Digital), John Harvey (IBM),
Hideki Hiura (Sun), Fred Horman (AT&T), Norikazu Kaiya (Fujitsu), Yuji Kamata
(IBM), Yutaka Kataoka (Waseda University), Ranee Khubchandani (Sun), Akira
Kon (NEC), Hiroshi Kuribayashi (OMRON), Teruhiko Kurosaka (Sun), Seiji Kuwari
(OMRON), Sandra Martin (OSF), Narita Masahiko (Fujitsu), Masato Morisaki (NTT),
Nelson Ng (Sun), Takashi Nishimura (NTT America), Makato Nishino (IBM), Akira
Ohsone (Nihon Sun), Chris Peterson (MIT), Sam Shteingart (AT&T), Manish Sheth
(AT&T), Muneiyoshi Suzuki (NTT), Cori Mehring (Digital), Shoji Sugiyama (IBM),
and Eiji Tosa (IBM).
xi
Acknowledgments
The principal authors (design and implementation) of the Xcms color management
facilities are Al Tabayoyon (Tektronix) and Chuck Adams (Tektronix). Joann Taylor
(Tektronix), Bob Toole (Tektronix), and Keith Packard (MIT X Consortium) also
contributed significantly to the design. Others who contributed are: Harold
Boll (Kodak), Ken Bronstein (HP), Nancy Cam (SGI), Donna Converse (MIT X
Consortium), Elias Israel (ISC), Deron Johnson (Sun), Jim King (Adobe), Ricardo
Motta (HP), Chuck Peek (IBM), Wil Plouffe (IBM), Dave Sternlicht (MIT X
Consortium), Kumar Talluri (AT&T), and Richard Verberg (IBM).
We also once again thank Al Mento of Digital for his work in formatting and
reformatting text for this manual, and for producing man pages. Thanks also to Clive
Feather (IXI) for proof-reading and finding a number of small errors.
Release 6
Stephen Gildea (X Consortium) authored the threads support. Ovais Ashraf (Sun)
and Greg Olsen (Sun) contributed substantially by testing the facilities and
reporting bugs in a timely fashion.
Others who have contributed to the architectural design or testing of the sample
implementation of the internationalization facilities are: Hector Chan (Digital),
Michael Kung (IBM), Joseph Kwok (Digital), Hiroyuki Machida (Sony), Nelson Ng
(SunSoft), Frank Rojas (IBM), Yoshiyuki Segawa (Fujitsu OSSI), Makiko Shimamura
(Fujitsu), Shoji Sugiyama (IBM), Lining Sun (SGI), Masaki Takeuchi (Sony), Jinsoo
Yoon (KAIST) and Akiyasu Zen (HP).
Jim Gettys
Cambridge Research Laboratory
Digital Equipment Corporation
Robert W. Scheifler
xii
Acknowledgments
Release 7
This document is made available to you in modern formats such as HTML and
PDF thanks to the efforts of Matt Dew, who converted the original troff sources
to DocBook/XML and edited them into shape; along with Gaetan Nadon and
Alan Coopersmith, who set up the formatting machinery in the libX11 builds and
performed further editing of the DocBook markup.
xiii
Chapter 1. Introduction to Xlib
The X Window System is a network-transparent window system that was designed
at MIT. X display servers run on computers with either monochrome or color bitmap
display hardware. The server distributes user input to and accepts output requests
from various client programs located either on the same machine or elsewhere in
the network. Xlib is a C subroutine library that application programs (clients) use
to interface with the window system by means of a stream connection. Although a
client usually runs on the same machine as the X server it is talking to, this need
not be the case.
• Errors
• Programming considerations
• Formatting conventions
1
Introduction to Xlib
All the windows in an X server are arranged in strict hierarchies. At the top of each
hierarchy is a root window, which covers each of the display screens. Each root
window is partially or completely covered by child windows. All windows, except
for root windows, have parents. There is usually at least one window for each
application program. Child windows may in turn have their own children. In this
way, an application program can create an arbitrarily deep tree on each screen. X
provides graphics, text, and raster operations for windows.
A child window can be larger than its parent. That is, part or all of the child window
can extend beyond the boundaries of the parent, but all output to a window is clipped
by its parent. If several children of a window have overlapping locations, one of the
children is considered to be on top of or raised over the others, thus obscuring them.
Output to areas covered by other windows is suppressed by the window system
unless the window has backing store. If a window is obscured by a second window,
the second window obscures only those ancestors of the second window that are
also ancestors of the first window.
A window has a border zero or more pixels in width, which can be any pattern
(pixmap) or solid color you like. A window usually but not always has a background
pattern, which will be repainted by the window system when uncovered. Child
windows obscure their parents, and graphic operations in the parent window
usually are clipped by the children.
Each window and pixmap has its own coordinate system. The coordinate system has
the X axis horizontal and the Y axis vertical with the origin [0, 0] at the upper-left
corner. Coordinates are integral, in terms of pixels, and coincide with pixel centers.
For a window, the origin is inside the border at the inside, upper-left corner.
X does not guarantee to preserve the contents of windows. When part or all of a
window is hidden and then brought back onto the screen, its contents may be lost.
The server then sends the client program an Expose event to notify it that part or
all of the window needs to be repainted. Programs must be prepared to regenerate
the contents of windows on demand.
Most of the functions in Xlib just add requests to an output buffer. These requests
later execute asynchronously on the X server. Functions that return values of
information stored in the server do not return (that is, they block) until an explicit
reply is received or an error occurs. You can provide an error handler, which will
be called when the error is reported.
If a client does not want a request to execute asynchronously, it can follow the
request with a call to XSync, which blocks until all previously buffered asynchronous
events have been sent and acted on. As an important side effect, the output buffer in
Xlib is always flushed by a call to any function that returns a value from the server
or waits for input.
Many Xlib functions will return an integer resource ID, which allows you
to refer to objects stored on the X server. These can be of type Window, Font,
Pixmap, Colormap, Cursor, and GContext, as defined in the file <X11/X.h>. These
2
Introduction to Xlib
resources are created by requests and are destroyed (or freed) by requests or
when connections are closed. Most of these resources are potentially sharable
between applications, and in fact, windows are manipulated explicitly by window
manager programs. Fonts and cursors are shared automatically across multiple
screens. Fonts are loaded and unloaded as needed and are shared by multiple
clients. Fonts are often cached in the server. Xlib provides no support for sharing
graphics contexts between applications.
Client programs are informed of events. Events may either be side effects of a
request (for example, restacking windows generates Expose events) or completely
asynchronous (for example, from the keyboard). A client program asks to be
informed of events. Because other applications can send events to your application,
programs must be prepared to handle (or ignore) events of all types.
Input events (for example, a key pressed or the pointer moved) arrive
asynchronously from the server and are queued until they are requested by an
explicit call (for example, XNextEvent or XWindowEvent). In addition, some library
functions (for example, XRaiseWindow) generate Expose and ConfigureRequest
events. These events also arrive asynchronously, but the client may wish to explicitly
wait for them by calling XSync after calling a function that can cause the server to
generate events.
Errors
Some functions return Status, an integer error indication. If the function fails, it
returns a zero. If the function returns a status of zero, it has not updated the return
arguments. Because C does not provide multiple return values, many functions
must return their results by writing into client-passed storage. By default, errors are
handled either by a standard library function or by one that you provide. Functions
that return pointers to strings return NULL pointers if the string does not exist.
The X server reports protocol errors at the time that it detects them. If more than
one error could be generated for a given request, the server can report any of them.
Because Xlib usually does not transmit requests to the server immediately (that is,
it buffers them), errors can be reported much later than they actually occur. For
debugging purposes, however, Xlib provides a mechanism for forcing synchronous
behavior (see section 11.8.1). When synchronization is enabled, errors are reported
as they are generated.
When Xlib detects an error, it calls an error handler, which your program can
provide. If you do not provide an error handler, the error is printed, and your
program terminates.
<X11/Xlib.h>
<X11/X.h>
<X11/Xcms.h>
<X11/Xutil.h>
<X11/Xresource.h> 3
<X11/Xatom.h>
Introduction to Xlib
<X11/cursorfont.h>
<X11/keysymdef.h>
<X11/keysym.h>
<X11/Xlibint.h>
<X11/Xproto.h>
<X11/Xprotostr.h>
<X11/X10.h>
• Xlib defines the type Bool and the Boolean values True and False.
• The type XPointer is defined to be char* and is used as a generic opaque pointer
to data.
• To differentiate the X symbols from the other symbols, the library uses mixed case
for external symbols. It leaves lowercase for variables and all uppercase for user
macros, as per existing convention.
• All user-visible data structures begin with a capital X. More generally, anything
that a user might dereference begins with a capital X.
• Macros and other symbols do not begin with a capital X. To distinguish them from
all user symbols, each word in the macro is capitalized.
• The display argument, where used, is always first in the argument list.
• All resource objects, where used, occur at the beginning of the argument list
immediately after the display argument.
• The width argument always precedes the height argument in the argument list.
• Where the x, y, width, and height arguments are used together, the x and y
arguments always precede the width and height arguments.
• Where a mask is accompanied with a structure, the mask always precedes the
pointer to the structure in the argument list.
Programming Considerations
The major programming considerations are:
• Coordinates and sizes in X are actually 16-bit quantities. This decision was made
to minimize the bandwidth required for a given level of performance. Coordinates
usually are declared as an int in the interface. Values larger than 16 bits are
truncated silently. Sizes (width and height) are declared as unsigned quantities.
• Many display systems have limited amounts of off-screen memory. If you can, you
should minimize use of pixmaps and backing store.
• The user should have control of their screen real estate. Therefore, you should
write your applications to react to window management rather than presume
control of the entire screen. What you do inside of your top-level window, however,
is up to your application. For further information, see chapter 14 and the Inter-
Client Communication Conventions Manual.
5
Introduction to Xlib
Latin Portable Character The encoding of the X Portable Character Set using
Encoding the Latin-1 codepoints plus ASCII control characters.
If a string is said to be in the Latin Portable Character
Encoding, then it only contains characters from the
X Portable Character Set, not all of Latin-1.
Formatting Conventions
Xlib − C Language X Interface uses the following conventions:
• Global symbols are printed in this special font. These can be either function
names, symbols defined in include files, or structure names. When declared and
defined, function arguments are printed in italics. In the explanatory text that
follows, they usually are printed in regular type.
• To eliminate any ambiguity between those arguments that you pass and those that
a function returns to you, the explanations for all arguments that you pass start
with the word specifies or, in the case of multiple arguments, the word specify.
The explanations for all arguments that are returned to you start with the word
returns or, in the case of multiple arguments, the word return. The explanations
for all arguments that you can pass and are returned start with the words specifies
and returns.
6
Chapter 2. Display Functions
Before your program can use a display, you must establish a connection to the X
server. Once you have established a connection, you then can use the Xlib macros
and functions discussed in this chapter to return information about the display. This
chapter discusses how to:
Display *XOpenDisplay(display_name);
protocol/hostname:number.screen_number
7
Display Functions
For example, the following would specify screen 1 of display 0 on the machine named
``dual-headed'':
dual-headed:0.1
X servers may implement various types of access control mechanisms (see section
9.8).
8
Display Functions
• Display macros
All other members of the Display structure (that is, those for which no
macros are defined) are private to Xlib and must not be used. Applications
must never directly modify or inspect these private members of the Display
structure. The XDisplayWidth, XDisplayHeight, XDisplayCells, XDisplayPlanes,
XDisplayWidthMM, and XDisplayHeightMM functions in the next sections are
misnamed. These functions really should be named Screenwhatever and
XScreenwhatever, not Displaywhatever or XDisplaywhatever. Our apologies for the
resulting confusion.
Display Macros
Applications should not directly modify any part of the Display and Screen
structures. The members should be considered read-only, although they may change
as the result of other operations on the display.
The following lists the C language macros, their corresponding function equivalents
that are for other language bindings, and what data both can return.
AllPlanes
Both return a value with all bits set to 1 suitable for use in a plane argument to
a procedure.
BlackPixel(display, screen_number);
Both return the black pixel value for the specified screen.
WhitePixel(display, screen_number);
9
Display Functions
Both return the white pixel value for the specified screen.
ConnectionNumber(display);
int XConnectionNumber(display);
DefaultColormap(display, screen_number);
Both return the default colormap ID for allocation on the specified screen. Most
routine allocations of color should be made out of this colormap.
DefaultDepth(display, screen_number);
Both return the depth (number of planes) of the default root window for
the specified screen. Other depths may also be supported on this screen (see
XMatchVisualInfo).
To determine the number of depths that are available on a given screen, use
XListDepths.
The XListDepths function returns the array of depths that are available on the
specified screen. If the specified screen_number is valid and sufficient memory
for the array can be allocated, XListDepths sets count_return to the number of
available depths. Otherwise, it does not set count_return and returns NULL. To
release the memory allocated for the array of depths, use XFree.
DefaultGC(display, screen_number);
10
Display Functions
GC XDefaultGC(display, screen_number);
Both return the default graphics context for the root window of the specified
screen. This GC is created for the convenience of simple applications and contains
the default GC components with the foreground and background pixel values
initialized to the black and white pixels for the screen, respectively. You can modify
its contents freely because it is not used in any Xlib function. This GC should never
be freed.
DefaultRootWindow(display);
Window XDefaultRootWindow(display);
DefaultScreenOfDisplay(display);
Screen *XDefaultScreenOfDisplay(display);
ScreenOfDisplay(display, screen_number);
DefaultScreen(display);
int XDefaultScreen(display);
Both return the default screen number referenced by the XOpenDisplay function.
This macro or function should be used to retrieve the screen number in applications
that will use only a single screen.
DefaultVisual(display, screen_number);
11
Display Functions
Both return the default visual type for the specified screen. For further information
about visual types, see section 3.1.
DisplayCells(display, screen_number);
DisplayPlanes(display, screen_number);
Both return the depth of the root window of the specified screen. For an explanation
of depth, see the glossary.
DisplayString(display);
char *XDisplayString(display);
Both return the string that was passed to XOpenDisplay when the current display
was opened. On POSIX-conformant systems, if the passed string was NULL, these
return the value of the DISPLAY environment variable when the current display was
opened. These are useful to applications that invoke the fork system call and want
to open a new connection to the same display from the child process as well as for
printing error messages.
long XExtendedMaxRequestSize(display);
12
Display Functions
long XMaxRequestSize(display);
The XMaxRequestSize function returns the maximum request size (in 4-byte units)
supported by the server without using an extended-length protocol encoding. Single
protocol requests to the server can be no larger than this size unless an extended-
length protocol encoding is supported by the server. The protocol guarantees the
size to be no smaller than 4096 units (16384 bytes). Xlib automatically breaks
data up into multiple protocol requests as necessary for the following functions:
XDrawPoints, XDrawRectangles, XDrawSegments, XFillArcs, XFillRectangles,
and XPutImage.
LastKnownRequestProcessed(display);
Both extract the full serial number of the last request known by Xlib to have been
processed by the X server. Xlib automatically sets this number when replies, events,
and errors are received.
NextRequest(display);
Both extract the full serial number that is to be used for the next request. Serial
numbers are maintained separately for each display connection.
ProtocolVersion(display);
int XProtocolVersion(display);
Both return the major version number (11) of the X protocol associated with the
connected display.
ProtocolRevision(display);
int XProtocolRevision(display);
13
Display Functions
QLength(display);
int XQLength(display);
Both return the length of the event queue for the connected display. Note that there
may be more events that have not been read into the queue yet (see XEventsQueued).
RootWindow(display, screen_number);
Both return the root window. These are useful with functions that need a drawable
of a particular screen and for creating top-level windows.
ScreenCount(display);
int XScreenCount(display);
ServerVendor(display);
char *XServerVendor(display);
VendorRelease(display);
int XVendorRelease(display);
14
Display Functions
typedef struct {
int depth;
int bits_per_pixel;
int scanline_pad;
} XPixmapFormatValues;
The following lists the C language macros, their corresponding function equivalents
that are for other language bindings, and what data they both return for the
specified server and screen. These are often used by toolkits as well as by simple
applications.
ImageByteOrder(display);
int XImageByteOrder(display);
Both specify the required byte order for images for each scanline unit in XY format
(bitmap) or for each pixel value in Z format. The macro or function can return either
LSBFirst or MSBFirst.
XBitmapUnit(display);
int XBitmapUnit(display);
Both return the size of a bitmap's scanline unit in bits. The scanline is calculated
in multiples of this value.
BitmapBitOrder(display);
int XBitmapBitOrder(display);
15
Display Functions
Within each bitmap unit, the left-most bit in the bitmap as displayed on the screen is
either the least significant or most significant bit in the unit. This macro or function
can return LSBFirst or MSBFirst.
BitmapPad(display);
int XBitmapPad(display);
DisplayHeight(display, screen_number);
Both return an integer that describes the height of the screen in pixels.
DisplayHeightMM(display, screen_number);
DisplayWidth(display, screen_number);
DisplayWidthMM(display, screen_number);
16
Display Functions
BlackPixelOfScreen(screen);
XWhitePixelOfScreen(screen);
CellsOfScreen(screen);
int XCellsOfScreen(screen);
Both return the number of colormap cells in the default colormap of the specified
screen.
DefaultColormapOfScreen(screen);
Colormap XDefaultColormapOfScreen(screen);
DefaultDepthOfScreen(screen);
int XDefaultDepthOfScreen(screen);
DefaultGCOfScreen(screen);
GC XDefaultGCOfScreen(screen);
17
Display Functions
Both return a default graphics context (GC) of the specified screen, which has the
same depth as the root window of the screen. The GC must never be freed.
XDefaultVisualOfScreen(screen);
Visual *XDefaultVisualOfScreen(screen);
Both return the default visual of the specified screen. For information on visual
types, see section 3.1.
DoesBackingStore(screen);
int XDoesBackingStore(screen);
Both return a value indicating whether the screen supports backing stores. The
value returned can be one of WhenMapped, NotUseful, or Always (see section 3.2.4).
DoesSaveUnders(screen);
Bool XDoesSaveUnders(screen);
Both return a Boolean value indicating whether the screen supports save unders.
If True, the screen supports save unders. If False, the screen does not support save
unders (see section 3.2.5).
DisplayOfScreen(screen);
Display *XDisplayOfScreen(screen);
ScreenNumberOfScreen(screen);
long XScreenNumberOfScreen(screen);
EventMaskOfScreen(screen);
18
Display Functions
long XEventMaskOfScreen(screen);
Both return the event mask of the root window for the specified screen at
connection setup time.
WidthOfScreen(screen);
int XWidthOfScreen(screen);
HeightOfScreen(screen);
int XHeightOfScreen(screen);
WidthMMOfScreen(screen);
int XWidthMMOfScreen(screen);
HeightMMOfScreen(screen);
int XHeightMMOfScreen(screen);
MaxCmapsOfScreen(screen);
int XMaxCmapsOfScreen(screen);
Both return the maximum number of installed colormaps supported by the specified
screen (see section 9.3).
MinCmapsOfScreen(screen);
int XMinCmapsOfScreen(screen);
19
Display Functions
Both return the minimum number of installed colormaps supported by the specified
screen (see section 9.3).
PlanesOfScreen(screen);
int XPlanesOfScreen(screen);
RootWindowOfScreen(screen);
Window XRootWindowOfScreen(screen);
XNoOp(display);
The XNoOp function sends a NoOperation protocol request to the X server, thereby
exercising the connection.
XFree(data);
The XFree function is a general-purpose Xlib routine that frees the specified data.
You must use it to free any objects that were allocated by Xlib, unless an alternate
function is explicitly specified for the object. A NULL pointer cannot be passed to
this function.
XCloseDisplay(display);
The XCloseDisplay function closes the connection to the X server for the display
specified in the Display structure and destroys all windows, resource IDs (Window,
20
Display Functions
Font, Pixmap, Colormap, Cursor, and GContext), or other resources that the client
has created on this display, unless the close-down mode of the client has been
changed (see XSetCloseDownMode). Therefore, these windows, resource IDs, and
other resources should never be referenced again or an error will be generated.
Before exiting, you should call XCloseDisplay explicitly so that any pending errors
are reported as XCloseDisplay performs a final XSync operation.
XSetCloseDownMode(display, close_mode);
The XSetCloseDownMode function defines what will happen to the client's resources
at connection close. A connection starts in DestroyAll mode. For information
on what happens to the client's resources when the close_mode argument is
RetainPermanent or RetainTemporary, see section 2.6.
• It marks all resources (including colormap entries) allocated by the client either
as permanent or temporary, depending on whether the close-down mode is
RetainPermanent or RetainTemporary. However, this does not prevent other client
applications from explicitly destroying the resources (see XSetCloseDownMode).
When the close-down mode is DestroyAll, the X server destroys all of a client's
resources as follows:
21
Display Functions
unchanged the absolute coordinates (with respect to the root window) of the
upper-left outer corner of the save-set window.
Additional processing occurs when the last connection to the X server closes. An X
server goes through a cycle of having no connections and having some connections.
When the last connection to the X server closes as a result of a connection closing
with the close_mode of DestroyAll, the X server does the following:
• It resets its state as if it had just been started. The X server begins by destroying
all lingering resources from clients that have terminated in RetainPermanent or
RetainTemporary mode.
• It resets all device maps and attributes (for example, key click, bell volume, and
acceleration) as well as the access control list.
However, the X server does not reset if you close a connection with a close-down
mode set to RetainPermanent or RetainTemporary.
Status XInitThreads();
The XInitThreads function initializes Xlib support for concurrent threads. This
function must be the first Xlib function a multi-threaded program calls, and it must
complete before any other Xlib call is made. This function returns a nonzero status
if initialization was successful; otherwise, it returns zero. On systems that do not
support threads, this function always returns zero.
It is only necessary to call this function if multiple threads might use Xlib
concurrently. If all calls to Xlib functions are protected by some other access
22
Display Functions
XLockDisplay(display);
The XLockDisplay function locks out all other threads from using the specified
display. Other threads attempting to use the display will block until the display is
unlocked by this thread. Nested calls to XLockDisplay work correctly; the display
will not actually be unlocked until XUnlockDisplay has been called the same
number of times as XLockDisplay. This function has no effect unless Xlib was
successfully initialized for threads using XInitThreads.
XUnlockDisplay(display);
The XUnlockDisplay function allows other threads to use the specified display
again. Any threads that have blocked on the display are allowed to continue. Nested
locking works correctly; if XLockDisplay has been called multiple times by a thread,
then XUnlockDisplay must be called an equal number of times before the display is
actually unlocked. This function has no effect unless Xlib was successfully initialized
for threads using XInitThreads.
23
Display Functions
This function can be called at any time after a display is opened. If internal
connections already exist, the registered procedure will immediately be called for
each of them, before XAddConnectionWatch returns. XAddConnectionWatch returns
a nonzero status if the procedure is successfully registered; otherwise, it returns
zero.
The registered procedure should not call any Xlib functions. If the procedure
directly or indirectly causes the state of internal connections or watch procedures
to change, the result is not defined. If Xlib has been initialized for threads, the
procedure is called with the display locked and the result of a call by the procedure
to any Xlib function that locks the display is not defined unless the executing thread
has externally locked the display using XLockDisplay.
24
Display Functions
25
Chapter 3. Window Functions
Visual Types
On some display hardware, it may be possible to deal with color resources in more
than one way. For example, you may be able to deal with a screen of either 12-bit
depth with arbitrary mapping of pixel to color (pseudo-color) or 24-bit depth with 8
bits of the pixel dedicated to each of red, green, and blue. These different ways of
dealing with the visual aspects of the screen are called visuals. For each screen of
the display, there may be a list of valid visual types supported at different depths of
the screen. Because default windows and visual types are defined for each screen,
most simple applications need not deal with this complexity. Xlib provides macros
and functions that return the default root window, the default depth of the default
root window, and the default visual type (see sections 2.2.1 and 16.7).
Xlib uses an opaque Visual structure that contains information about the possible
color mapping. The visual utility functions (see section 16.7) use an XVisualInfo
structure to return this information to an application. The members of this
structure pertinent to this discussion are class, red_mask, green_mask, blue_mask,
bits_per_rgb, and colormap_size. The class member specifies one of the possible
visual classes of the screen and can be StaticGray, StaticColor, TrueColor,
GrayScale, PseudoColor, or DirectColor.
The following concepts may serve to make the explanation of visual types clearer.
The screen can be color or grayscale, can have a colormap that is writable or read-
only, and can also have a colormap whose indices are decomposed into separate
RGB pieces, provided one is not on a grayscale screen. This leads to the following
diagram:
Color Gray-Scale
R/O R/W R/O R/W
----------------------------------------------
Undecomposed Static Pseudo Static Gray
Colormap Color Color Gray Scale
Conceptually, as each pixel is read out of video memory for display on the screen,
it goes through a look-up stage by indexing into a colormap. Colormaps can be
manipulated arbitrarily on some hardware, in limited ways on other hardware, and
not at all on other hardware. The visual types affect the colormap and the RGB
values in the following ways:
• GrayScale is treated the same way as PseudoColor except that the primary that
drives the screen is undefined. Thus, the client should always store the same value
for red, green, and blue in the colormaps.
26
Window Functions
• For DirectColor, a pixel value is decomposed into separate RGB subfields, and
each subfield separately indexes the colormap for the corresponding value. The
RGB values can be changed dynamically.
• TrueColor is treated the same way as DirectColor except that the colormap has
predefined, read-only RGB values. These RGB values are server dependent but
provide linear or near-linear ramps in each primary.
• StaticColor is treated the same way as PseudoColor except that the colormap has
predefined, read-only, server-dependent RGB values.
• StaticGray is treated the same way as StaticColor except that the RGB values are
equal for any single pixel value, thus resulting in shades of gray. StaticGray with
a two-entry colormap can be thought of as monochrome.
The red_mask, green_mask, and blue_mask members are only defined for
DirectColor and TrueColor. Each has one contiguous set of bits with no
intersections. The bits_per_rgb member specifies the log base 2 of the number
of distinct color values (individually) of red, green, and blue. Actual RGB values
are unsigned 16-bit numbers. The colormap_size member defines the number
of available colormap entries in a newly created colormap. For DirectColor and
TrueColor, this is the size of an individual pixel subfield.
VisualID XVisualIDFromVisual(visual);
The XVisualIDFromVisual function returns the visual ID for the specified visual
type.
Window Attributes
All InputOutput windows have a border width of zero or more pixels, an optional
background, an event suppression mask (which suppresses propagation of events
from children), and a property list (see section 4.3). The window border and
background can be a solid color or a pattern, called a tile. All windows except the
root have a parent and are clipped by their parent. If a window is stacked on top of
another window, it obscures that other window for the purpose of input. If a window
has a background (almost all do), it obscures the other window for purposes of
output. Attempts to output to the obscured area do nothing, and no input events
(for example, pointer motion) are generated for the obscured area.
Both InputOutput and InputOnly windows have the following common attributes,
which are the only attributes of an InputOnly window:
• win-gravity
• event-mask
• do-not-propagate-mask
27
Window Functions
• override-redirect
• cursor
If you specify any other attributes for an InputOnly window, a BadMatch error
results.
InputOnly windows are used for controlling input events in situations where
InputOutput windows are unnecessary. InputOnly windows are invisible; can only
be used to control such things as cursors, input event generation, and grabbing;
and cannot be used in any graphics requests. Note that InputOnly windows cannot
have InputOutput windows as inferiors.
When windows are first created, they are not visible (not mapped) on the screen. Any
output to a window that is not visible on the screen and that does not have backing
store will be discarded. An application may wish to create a window long before it
is mapped to the screen. When a window is eventually mapped to the screen (using
XMapWindow), the X server generates an Expose event for the window if backing
store has not been maintained.
A window manager can override your choice of size, border width, and position
for a top-level window. Your program must be prepared to use the actual size and
position of the top window. It is not acceptable for a client application to resize
itself unless in direct response to a human command to do so. Instead, either your
program should use the space given to it, or if the space is too small for any useful
work, your program might ask the user to resize the window. The border of your
top-level window is considered fair game for window managers.
28
Window Functions
/* Values */
typedef struct {
Pixmap background_pixmap; /* background, None, or ParentRelative */
unsigned long background_pixel; /* background pixel */
Pixmap border_pixmap; /* border of the window or CopyFromParent */
unsigned long border_pixel; /* border pixel value */
int bit_gravity; /* one of bit gravity values */
int win_gravity; /* one of the window gravity values */
int backing_store; /* NotUseful, WhenMapped, Always */
unsigned long backing_planes; /* planes to be preserved if possible */
unsigned long backing_pixel; /* value to use in restoring planes */
Bool save_under; /* should bits under be saved? (popups) */
long event_mask; /* set of events that should be saved */
long do_not_propagate_mask; /* set of events that should not propagate */
Bool override_redirect; /* boolean value for override_redirect */
Colormap colormap; /* color map to be associated with window */
Cursor cursor; /* cursor to be displayed (or None) */
} XSetWindowAttributes;
The following lists the defaults for each window attribute and indicates whether the
attribute is applicable to InputOutput and InputOnly windows:
29
Window Functions
Background Attribute
Only InputOutput windows can have a background. You can set the background of
an InputOutput window by using a pixel or a pixmap.
• If the parent window has a background-pixmap of None, the window also has a
background-pixmap of None.
• The background tile origin always aligns with the parent window's background
tile origin. If the background-pixmap is not ParentRelative, the background tile
origin is the child window's origin.
When no valid contents are available for regions of a window and either the regions
are visible or the server is maintaining backing store, the server automatically tiles
the regions with the window's background unless the window has a background of
None. If the background is None, the previous screen contents from other windows
30
Window Functions
of the same depth as the window are simply left in place as long as the contents come
from the parent of the window or an inferior of the parent. Otherwise, the initial
contents of the exposed regions are undefined. Expose events are then generated
for the regions, even if the background-pixmap is None (see section 10.9).
Border Attribute
Only InputOutput windows can have a border. You can set the border of an
InputOutput window by using a pixel or a pixmap.
You can also set the border-pixmap to a pixmap of any size (some may be faster
than others) or to CopyFromParent (default). You can set the border-pixel to any
pixel value (no default).
If you set a border-pixmap, it overrides the default. The border-pixmap and the
window must have the same depth, or a BadMatch error results. If you set the
border-pixmap to CopyFromParent, the parent window's border-pixmap is copied.
Subsequent changes to the parent window's border attribute do not affect the child
window. However, the child window must have the same depth as the parent window,
or a BadMatch error results.
Gravity Attributes
The bit gravity of a window defines which region of the window should be retained
when an InputOutput window is resized. The default value for the bit-gravity
attribute is ForgetGravity. The window gravity of a window allows you to define how
the InputOutput or InputOnly window should be repositioned if its parent is resized.
The default value for the win-gravity attribute is NorthWestGravity.
If the inside width or height of a window is not changed and if the window is moved
or its border is changed, then the contents of the window are not lost but move with
the window. Changing the inside width or height of the window causes its contents
to be moved or lost (depending on the bit-gravity of the window) and causes children
to be reconfigured (depending on their win-gravity). For a change of width and
height, the (x, y) pairs are defined:
31
Window Functions
When a window with one of these bit-gravity values is resized, the corresponding
pair defines the change in position of each pixel in the window. When a window with
one of these win-gravities has its parent window resized, the corresponding pair
defines the change in position of the window within the parent. When a window is
so repositioned, a GravityNotify event is generated (see section 10.10.5).
A bit-gravity of StaticGravity indicates that the contents or origin should not move
relative to the origin of the root window. If the change in size of the window is
coupled with a change in position (x, y), then for bit-gravity the change in position of
each pixel is (−x, −y), and for win-gravity the change in position of a child when its
parent is so resized is (−x, −y). Note that StaticGravity still only takes effect when
the width or height of the window is changed, not when the window is moved.
The contents and borders of inferiors are not affected by their parent's bit-gravity.
A server is permitted to ignore the specified bit-gravity and use Forget instead.
32
Window Functions
the server may generate an Expose event when the window is created. A backing-
store attribute of Always advises the X server that maintaining contents even when
the window is unmapped would be beneficial. Even if the window is larger than
its parent, this is a request to the X server to maintain complete contents, not just
the region within the parent window boundaries. While the X server maintains the
window's contents, Expose events normally are not generated, but the X server may
stop maintaining contents at any time.
When the contents of obscured regions of a window are being maintained, regions
obscured by noninferior windows are included in the destination of graphics
requests (and source, when the window is the source). However, regions obscured
by inferior windows are not included.
You can set the save-under flag to True or False (default). If save-under is True,
the X server is advised that, when this window is mapped, saving the contents of
windows it obscures would be beneficial.
33
Window Functions
The override-redirect flag specifies whether map and configure requests on this
window should override a SubstructureRedirectMask on the parent. You can set
the override-redirect flag to True or False (default). Window managers use this
information to avoid tampering with pop-up windows (see also chapter 14).
Colormap Attribute
The colormap attribute specifies which colormap best reflects the true colors of
the InputOutput window. The colormap must have the same visual type as the
window, or a BadMatch error results. X servers capable of supporting multiple
hardware colormaps can use this information, and window managers can use it for
calls to XInstallColormap. You can set the colormap attribute to a colormap or to
CopyFromParent (default).
If you set the colormap to CopyFromParent, the parent window's colormap is copied
and used by its child. However, the child window must have the same visual type
as the parent, or a BadMatch error results. The parent window must not have a
colormap of None, or a BadMatch error results. The colormap is copied by sharing
the colormap object between the child and parent, not by making a complete copy
of the colormap contents. Subsequent changes to the parent window's colormap
attribute do not affect the child window.
Cursor Attribute
The cursor attribute specifies which cursor is to be used when the pointer is in
the InputOutput or InputOnly window. You can set the cursor to a cursor or None
(default).
If you set the cursor to None, the parent's cursor is used when the pointer is in the
InputOutput or InputOnly window, and any change in the parent's cursor will cause
an immediate change in the displayed cursor. By calling XFreeCursor, the cursor
can be freed immediately as long as no further explicit reference to it is made.
Creating Windows
Xlib provides basic ways for creating windows, and toolkits often supply higher-
level functions specifically for creating and placing top-level windows, which are
discussed in the appropriate toolkit documentation. If you do not use a toolkit,
however, you must provide some standard information or hints for the window
manager by using the Xlib inter-client communication functions (see chapter 14).
If you use Xlib to create your own top-level windows (direct children of the root
window), you must observe the following rules so that all applications interact
reasonably across the different styles of window management:
34
Window Functions
• You must never fight with the window manager for the size or placement of your
top-level window.
• You must be able to deal with whatever size window you get, even if this means
that your application just prints a message like ``Please make me bigger'' in its
window.
• You should only attempt to resize or move top-level windows in direct response to
a user request. If a request to change the size of a top-level window fails, you must
be prepared to live with what you get. You are free to resize or move the children
of top-level windows as necessary. (Toolkits often have facilities for automatic
relayout.)
• If you do not use a toolkit that automatically sets standard window properties,
you should set these properties for top-level windows before mapping them.
XCreateWindow is the more general function that allows you to set specific window
attributes when you create a window. XCreateSimpleWindow creates a window that
inherits its attributes from its parent window.
The X server acts as if InputOnly windows do not exist for the purposes of graphics
requests, exposure processing, and VisibilityNotify events. An InputOnly window
cannot be used as a drawable (that is, as a source or destination for graphics
requests). InputOnly and InputOutput windows act identically in other respects
(properties, grabs, input control, and so on). Extension packages can define other
classes of windows.
To create an unmapped window and set its window attributes, use XCreateWindow.
width
height Specify the width and height, which are the created
window's inside dimensions and do not include the
created window's borders. The dimensions must be
nonzero, or a BadValue error results.
35
Window Functions
The coordinate system has the X axis horizontal and the Y axis vertical with the
origin [0, 0] at the upper-left corner. Coordinates are integral, in terms of pixels,
and coincide with pixel centers. Each window and pixmap has its own coordinate
system. For a window, the origin is inside the border at the inside, upper-left corner.
The created window is not yet displayed (mapped) on the user's display. To display
the window, call XMapWindow. The new window initially uses the same cursor as its
parent. A new cursor can be defined for the new window by calling XDefineCursor.
The window will not be visible on the screen unless it and all of its ancestors are
mapped and it is not obscured by any of its ancestors.
36
Window Functions
width
height Specify the width and height, which are the created
window's inside dimensions and do not include the
created window's borders. The dimensions must be
nonzero, or a BadValue error results.
Destroying Windows
Xlib provides functions that you can use to destroy a window or destroy all
subwindows of a window.
XDestroyWindow(display, w);
The XDestroyWindow function destroys the specified window as well as all of its
subwindows and causes the X server to generate a DestroyNotify event for each
window. The window should never be referenced again. If the window specified
by the w argument is mapped, it is unmapped automatically. The ordering of
the DestroyNotify events is such that for any given window being destroyed,
DestroyNotify is generated on any inferiors of the window before being generated
on the window itself. The ordering among siblings and across subhierarchies is not
otherwise constrained. If the window you specified is a root window, no windows
37
Window Functions
are destroyed. Destroying a mapped window will generate Expose events on other
windows that were obscured by the window being destroyed.
XDestroySubwindows(display, w);
Mapping Windows
A window is considered mapped if an XMapWindow call has been made on it. It may
not be visible on the screen for one of the following reasons:
Expose events are generated for the window when part or all of it becomes visible
on the screen. A client receives the Expose events only if it has asked for them.
Windows retain their position in the stacking order when they are unmapped.
A tiling window manager might decide to reposition and resize other clients'
windows and then decide to map the window to its final location. A window manager
that wants to provide decoration might reparent the child into a frame first. For
further information, see sections 3.2.8 and 10.10. Only a single client at a time can
select for SubstructureRedirectMask.
38
Window Functions
XMapWindow(display, w);
The XMapWindow function maps the window and all of its subwindows that have had
map requests. Mapping a window that has an unmapped ancestor does not display
the window but marks it as eligible for display when the ancestor becomes mapped.
Such a window is called unviewable. When all its ancestors are mapped, the window
becomes viewable and will be visible on the screen if it is not obscured by another
window. This function has no effect if the window is already mapped.
If the override-redirect of the window is False and if some other client has selected
SubstructureRedirectMask on the parent window, then the X server generates
a MapRequest event, and the XMapWindow function does not map the window.
Otherwise, the window is mapped, and the X server generates a MapNotify event.
If the window becomes viewable and no earlier contents for it are remembered,
the X server tiles the window with its background. If the window's background is
undefined, the existing screen contents are not altered, and the X server generates
zero or more Expose events. If backing-store was maintained while the window
was unmapped, no Expose events are generated. If backing-store will now be
maintained, a full-window exposure is always generated. Otherwise, only visible
regions may be reported. Similar tiling and exposure take place for any newly
viewable inferiors.
XMapRaised(display, w);
XMapSubwindows(display, w);
39
Window Functions
The XMapSubwindows function maps all subwindows for a specified window in top-
to-bottom stacking order. The X server generates Expose events on each newly
displayed window. This may be much more efficient than mapping many windows
one at a time because the server needs to perform much of the work only once, for
all of the windows, rather than for each window.
Unmapping Windows
Xlib provides functions that you can use to unmap a window or all subwindows.
XUnmapWindow(display, w);
The XUnmapWindow function unmaps the specified window and causes the X server
to generate an UnmapNotify event. If the specified window is already unmapped,
XUnmapWindow has no effect. Normal exposure processing on formerly obscured
windows is performed. Any child window will no longer be visible until another map
call is made on the parent. In other words, the subwindows are still mapped but are
not visible until the parent is mapped. Unmapping a window will generate Expose
events on windows that were formerly obscured by it.
XUnmapSubwindows(display, w);
The XUnmapSubwindows function unmaps all subwindows for the specified window
in bottom-to-top stacking order. It causes the X server to generate an UnmapNotify
event on each subwindow and Expose events on formerly obscured windows. Using
this function is much more efficient than unmapping multiple windows one at a time
because the server needs to perform much of the work only once, for all of the
windows, rather than for each window.
Configuring Windows
Xlib provides functions that you can use to move a window, resize a window, move
and resize a window, or change a window's border width. To change one of these
40
Window Functions
/* Values */
typedef struct {
int x, y;
int width, height;
int border_width;
Window sibling;
int stack_mode;
} XWindowChanges;
The x and y members are used to set the window's x and y coordinates, which are
relative to the parent's origin and indicate the position of the upper-left outer corner
of the window. The width and height members are used to set the inside size of the
window, not including the border, and must be nonzero, or a BadValue error results.
Attempts to configure a root window have no effect.
The border_width member is used to set the width of the border in pixels. Note that
setting just the border width leaves the outer-left corner of the window in a fixed
position but moves the absolute position of the window's origin. If you attempt to
set the border-width attribute of an InputOnly window nonzero, a BadMatch error
results.
The sibling member is used to set the sibling window for stacking operations. The
stack_mode member is used to set how the window is to be restacked and can be
set to Above, Below, TopIf, BottomIf, or Opposite.
If the override-redirect flag of the window is False and if some other client
has selected SubstructureRedirectMask on the parent, the X server generates
a ConfigureRequest event, and no further processing is performed. Otherwise,
if some other client has selected ResizeRedirectMask on the window and the
inside width or height of the window is being changed, a ResizeRequest event is
generated, and the current inside width and height are used instead. Note that the
override-redirect flag of the window has no effect on ResizeRedirectMask and that
SubstructureRedirectMask on the parent has precedence over ResizeRedirectMask
on the window.
When the geometry of the window is changed as specified, the window is restacked
among siblings, and a ConfigureNotify event is generated if the state of the window
41
Window Functions
If regions of the window were obscured but now are not, exposure processing is
performed on these formerly obscured windows, including the window itself and
its inferiors. As a result of increasing the width or height, exposure processing is
also performed on any new regions of the window and any regions where window
contents are lost.
The restack check (specifically, the computation for BottomIf, TopIf, and Opposite)
is performed with respect to the window's final size and position (as controlled by
the other arguments of the request), not its initial position. If a sibling is specified
without a stack_mode, a BadMatch error results.
42
Window Functions
XMoveWindow(display, w, x, y);
The XMoveWindow function moves the specified window to the specified x and y
coordinates, but it does not change the window's size, raise the window, or change
the mapping state of the window. Moving a mapped window may or may not lose the
window's contents depending on if the window is obscured by nonchildren and if no
backing store exists. If the contents of the window are lost, the X server generates
Expose events. Moving a mapped window generates Expose events on any formerly
obscured windows.
If the override-redirect flag of the window is False and some other client has
selected SubstructureRedirectMask on the parent, the X server generates a
ConfigureRequest event, and no further processing is performed. Otherwise, the
window is moved.
43
Window Functions
width
height Specify the width and height, which are the interior
dimensions of the window after the call completes.
The XResizeWindow function changes the inside dimensions of the specified window,
not including its borders. This function does not change the window's upper-left
coordinate or the origin and does not restack the window. Changing the size of a
mapped window may lose its contents and generate Expose events. If a mapped
window is made smaller, changing its size generates Expose events on windows that
the mapped window formerly obscured.
If the override-redirect flag of the window is False and some other client has
selected SubstructureRedirectMask on the parent, the X server generates a
ConfigureRequest event, and no further processing is performed. If either width or
height is zero, a BadValue error results.
width
height Specify the width and height, which define the interior size
of the window.
The XMoveResizeWindow function changes the size and location of the specified
window without raising it. Moving and resizing a mapped window may generate an
Expose event on the window. Depending on the new size and location parameters,
moving and resizing a window may generate Expose events on windows that the
window formerly obscured.
If the override-redirect flag of the window is False and some other client has
selected SubstructureRedirectMask on the parent, the X server generates a
ConfigureRequest event, and no further processing is performed. Otherwise, the
window size and location are changed.
XSetWindowBorderWidth(display, w, width);
44
Window Functions
XRaiseWindow(display, w);
The XRaiseWindow function raises the specified window to the top of the stack so
that no sibling window obscures it. If the windows are regarded as overlapping
sheets of paper stacked on a desk, then raising a window is analogous to moving the
sheet to the top of the stack but leaving its x and y location on the desk constant.
Raising a mapped window may generate Expose events for the window and any
mapped subwindows that were formerly obscured.
If the override-redirect attribute of the window is False and some other client
has selected SubstructureRedirectMask on the parent, the X server generates a
ConfigureRequest event, and no processing is performed. Otherwise, the window
is raised.
To lower a window so that it does not obscure any sibling windows, use
XLowerWindow.
XLowerWindow(display, w);
The XLowerWindow function lowers the specified window to the bottom of the stack
so that it does not obscure any sibling windows. If the windows are regarded as
overlapping sheets of paper stacked on a desk, then lowering a window is analogous
to moving the sheet to the bottom of the stack but leaving its x and y location on
the desk constant. Lowering a mapped window will generate Expose events on any
windows it formerly obscured.
If the override-redirect attribute of the window is False and some other client
has selected SubstructureRedirectMask on the parent, the X server generates a
ConfigureRequest event, and no processing is performed. Otherwise, the window
is lowered to the bottom of the stack.
45
Window Functions
XCirculateSubwindows(display, w, direction);
To raise the lowest mapped child of a window that is partially or completely occluded
by another child, use XCirculateSubwindowsUp.
XCirculateSubwindowsUp(display, w);
To lower the highest mapped child of a window that partially or completely occludes
another child, use XCirculateSubwindowsDown.
XCirculateSubwindowsDown(display, w);
46
Window Functions
The XRestackWindows function restacks the windows in the order specified, from top
to bottom. The stacking order of the first window in the windows array is unaffected,
but the other windows in the array are stacked underneath the first window, in the
order of the array. The stacking order of the other windows is not affected. For each
window in the window array that is not a child of the specified window, a BadMatch
error results.
47
Window Functions
Multiple clients can select input on the same window. Their event masks are
maintained separately. When an event is generated, it is reported to all interested
clients. However, only one client at a time can select for SubstructureRedirectMask,
ResizeRedirectMask, and ButtonPressMask. If a client attempts to select any of
these event masks and some other client has already selected one, a BadAccess
error results. There is only one do-not-propagate-mask for a window, not one per
client.
XSetWindowBackground(display, w, background_pixel);
XSetWindowBackgroundPixmap(display, w, background_pixmap);
48
Window Functions
XSetWindowBorder(display, w, border_pixel);
The XSetWindowBorder function sets the border of the window to the pixel value
you specify. If you attempt to perform this on an InputOnly window, a BadMatch
error results.
XSetWindowBorderPixmap(display, w, border_pixmap);
XSetWindowColormap(display, w, colormap);
49
Window Functions
XDefineCursor(display, w, cursor);
If a cursor is set, it will be used when the pointer is in the window. If the cursor is
None, it is equivalent to XUndefineCursor.
XUndefineCursor(display, w);
50
Chapter 4. Window Information
Functions
After you connect the display to the X server and create a window, you can use the
Xlib window information functions to:
• Manipulate selections
To obtain the parent, a list of children, and number of children for a given window,
use XQueryTree.
The XQueryTree function returns the root ID, the parent window ID, a pointer to
the list of children windows (NULL when there are no children), and the number
of children in the list for the specified window. The children are listed in current
stacking order, from bottom-most (first) to top-most (last). XQueryTree returns zero
if it fails and nonzero if it succeeds. To free a non-NULL children list when it is no
longer needed, use XFree.
51
Window Information
Functions
The XGetWindowAttributes function returns the current attributes for the specified
window to an XWindowAttributes structure.
typedef struct {
int x, y; /* location of window */
int width, height; /* width and height of window */
int border_width; /* border width of window */
int depth; /* depth of window */
Visual *visual; /* the associated visual structure */
Window root; /* root of screen containing window */
int class; /* InputOutput, InputOnly*/
int bit_gravity; /* one of the bit gravity values */
int win_gravity; /* one of the window gravity values */
int backing_store; /* NotUseful, WhenMapped, Always */
unsigned long backing_planes; /* planes to be preserved if possible */
unsigned long backing_pixel; /* value to be used when restoring planes */
Bool save_under; /* boolean, should bits under be saved? */
Colormap colormap; /* color map to be associated with window */
Bool map_installed; /* boolean, is color map currently installed*/
int map_state; /* IsUnmapped, IsUnviewable, IsViewable */
long all_event_masks; /* set of events all people have interest in*/
long your_event_mask; /* my event mask */
long do_not_propagate_mask; /* set of events that should not propagate */
Bool override_redirect; /* boolean value for override-redirect */
Screen *screen; /* back pointer to correct screen */
} XWindowAttributes;
The x and y members are set to the upper-left outer corner relative to the parent
window's origin. The width and height members are set to the inside size of the
window, not including the border. The border_width member is set to the window's
border width in pixels. The depth member is set to the depth of the window (that
is, bits per pixel for the object). The visual member is a pointer to the screen's
associated Visual structure. The root member is set to the root window of the screen
containing the window. The class member is set to the window's class and can be
either InputOutput or InputOnly.
The bit_gravity member is set to the window's bit gravity and can be one of the
following:
ForgetGravity EastGravity
NorthWestGravity SouthWestGravity
NorthGravity SouthGravity
NorthEastGravity SouthEastGravity
52
Window Information
Functions
WestGravity StaticGravity
The win_gravity member is set to the window's window gravity and can be one of
the following:
UnmapGravity SouthWestGravity
NorthWestGravity SouthGravity
NorthGravity SouthEastGravity
NorthEastGravity StaticGravity
WestGravity CenterGravity
EastGravity
The backing_store member is set to indicate how the X server should maintain
the contents of a window and can be WhenMapped, Always, or NotUseful. The
backing_planes member is set to indicate (with bits set to 1) which bit planes of the
window hold dynamic data that must be preserved in backing_stores and during
save_unders. The backing_pixel member is set to indicate what values to use for
planes not set in backing_planes.
The save_under member is set to True or False. The colormap member is set to
the colormap for the specified window and can be a colormap ID or None. The
map_installed member is set to indicate whether the colormap is currently installed
and can be True or False. The map_state member is set to indicate the state of
the window and can be IsUnmapped, IsUnviewable, or IsViewable. IsUnviewable is
used if the window is mapped but some ancestor is unmapped.
The all_event_masks member is set to the bitwise inclusive OR of all event masks
selected on the window by all clients. The your_event_mask member is set to
the bitwise inclusive OR of all event masks selected by the querying client. The
do_not_propagate_mask member is set to the bitwise inclusive OR of the set of
events that should not propagate.
The screen member is set to a screen pointer that gives you a back pointer to the
correct screen. This makes it easier to obtain the screen information without having
to loop over the root window fields to see which field matches.
x_return
53
Window Information
Functions
width_return
depth_return Returns the depth of the drawable (bits per pixel for
the object).
The XGetGeometry function returns the root window and the current geometry of
the drawable. The geometry of the drawable includes the x and y coordinates, width
and height, border width, and depth. These are described in the argument list. It is
legal to pass to this function a window whose class is InputOnly.
src_x
dest_x_return
54
Window Information
Functions
root_x_return
win_x_return
The XQueryPointer function returns the root window the pointer is logically on
and the pointer coordinates relative to the root window's origin. If XQueryPointer
returns False, the pointer is not on the same screen as the specified window,
and XQueryPointer returns None to child_return and zero to win_x_return and
win_y_return. If XQueryPointer returns True, the pointer coordinates returned to
win_x_return and win_y_return are relative to the origin of the specified window. In
this case, XQueryPointer returns the child that contains the pointer, if any, or else
None to child_return.
XQueryPointer returns the current logical state of the keyboard buttons and the
modifier keys in mask_return. It sets mask_return to the bitwise inclusive OR of one
or more of the button or modifier key bitmasks to match the current state of the
mouse buttons and the modifier keys.
Note that the logical state of a device (as seen through Xlib) may lag the physical
state if device event processing is frozen (see section 12.1).
55
Window Information
Functions
A property is also stored in one of several possible formats. The X server can
store the information as 8-bit quantities, 16-bit quantities, or 32-bit quantities. This
permits the X server to present the data in the byte order that the client expects. If
you define further properties of complex type, you must encode and decode them
yourself. These functions must be carefully written if they are to be portable. For
further information about how to write a library extension, see appendix C. The
type of a property is defined by an atom, which allows for arbitrary extension in
this type scheme.
Certain property names are predefined in the server for commonly used functions.
The atoms for these properties are defined in <X11/Xatom.h>. To avoid name
clashes with user symbols, the #define name for each atom has the XA_ prefix. For
an explanation of the functions that let you get and set much of the information
stored in these predefined properties, see chapter 14.
The core protocol imposes no semantics on these property names, but semantics are
specified in other X Consortium standards, such as the Inter-Client Communication
Conventions Manual and the X Logical Font Description Conventions.
You can use properties to communicate other information between applications. The
functions described in this section let you define new properties and get the unique
atom IDs in your applications.
Although any particular atom can have some client interpretation within each of the
name spaces, atoms occur in five distinct name spaces within the protocol:
• Selections
• Property names
• Property types
• Font properties
PRIMARY SECONDARY
56
Window Information
Functions
CUT_BUFFER0 RESOURCE_MANAGER
CUT_BUFFER1 WM_CLASS
CUT_BUFFER2 WM_CLIENT_MACHINE
CUT_BUFFER3 WM_COLORMAP_WINDOWS
CUT_BUFFER4 WM_COMMAND
CUT_BUFFER5 WM_HINTS
CUT_BUFFER6 WM_ICON_NAME
CUT_BUFFER7 WM_ICON_SIZE
RGB_BEST_MAP WM_NAME
RGB_BLUE_MAP WM_NORMAL_HINTS
RGB_DEFAULT_MAP WM_PROTOCOLS
RGB_GRAY_MAP WM_STATE
RGB_GREEN_MAP WM_TRANSIENT_FOR
RGB_RED_MAP WM_ZOOM_HINTS
ARC PIXMAP
ATOM POINT
BITMAP RGB_COLOR_MAP
CARDINAL RECTANGLE
COLORMAP STRING
CURSOR VISUALID
DRAWABLE WINDOW
FONT WM_HINTS
INTEGER WM_SIZE_HINTS
MIN_SPACE STRIKEOUT_DESCENT
NORM_SPACE STRIKEOUT_ASCENT
MAX_SPACE ITALIC_ANGLE
END_SPACE X_HEIGHT
SUPERSCRIPT_X QUAD_WIDTH
SUPERSCRIPT_Y WEIGHT
SUBSCRIPT_X POINT_SIZE
SUBSCRIPT_Y RESOLUTION
UNDERLINE_POSITION COPYRIGHT
UNDERLINE_THICKNESS NOTICE
FONT_NAME FAMILY_NAME
FULL_NAME CAP_HEIGHT
57
Window Information
Functions
The XInternAtom function returns the atom identifier associated with the specified
atom_name string. If only_if_exists is False, the atom is created if it does not exist.
Therefore, XInternAtom can return None. If the atom name is not in the Host
Portable Character Encoding, the result is implementation-dependent. Uppercase
and lowercase matter; the strings ``thing'', ``Thing'', and ``thinG'' all designate
different atoms. The atom will remain defined even after the client's connection
closes. It will become undefined only when the last connection to the X server closes.
The XInternAtoms function returns the atom identifiers associated with the
specified names. The atoms are stored in the atoms_return array supplied by the
caller. Calling this function is equivalent to calling XInternAtom for each of the
names in turn with the specified value of only_if_exists, but this function minimizes
the number of round-trip protocol exchanges between the client and the X server.
This function returns a nonzero status if atoms are returned for all of the names;
otherwise, it returns zero.
atom Specifies the atom for the property name you want
returned.
The XGetAtomName function returns the name associated with the specified atom. If
the data returned by the server is in the Latin Portable Character Encoding, then the
returned string is in the Host Portable Character Encoding. Otherwise, the result
is implementation-dependent. To free the resulting string, call XFree.
58
Window Information
Functions
The XGetAtomNames function returns the names associated with the specified atoms.
The names are stored in the names_return array supplied by the caller. Calling this
function is equivalent to calling XGetAtomName for each of the atoms in turn, but
this function minimizes the number of round-trip protocol exchanges between the
client and the X server.
This function returns a nonzero status if names are returned for all of the atoms;
otherwise, it returns zero.
Xlib provides functions that you can use to obtain, change, update, or interchange
window properties. In addition, Xlib provides other utility functions for inter-client
communication (see chapter 14).
To obtain the type, format, and value of a property of a given window, use
XGetWindowProperty.
59
Window Information
Functions
The XGetWindowProperty function returns the actual type of the property; the actual
format of the property; the number of 8-bit, 16-bit, or 32-bit items transferred; the
number of bytes remaining to be read in the property; and a pointer to the data
actually returned. XGetWindowProperty sets the return arguments as follows:
• If the specified property does not exist for the specified window,
XGetWindowProperty returns None to actual_type_return and the value zero
to actual_format_return and bytes_after_return. The nitems_return argument is
empty. In this case, the delete argument is ignored.
• If the specified property exists but its type does not match the specified type,
XGetWindowProperty returns the actual property type to actual_type_return, the
actual property format (never zero) to actual_format_return, and the property
length in bytes (even if the actual_format_return is 16 or 32) to bytes_after_return.
It also ignores the delete argument. The nitems_return argument is empty.
• If the specified property exists and either you assign AnyPropertyType to the
req_type argument or the specified type matches the actual property type,
XGetWindowProperty returns the actual property type to actual_type_return and
the actual property format (never zero) to actual_format_return. It also returns a
value to bytes_after_return and nitems_return, by defining the following values:
• N = actual length of the stored property in bytes (even if the format is 16 or 32)
I = 4 * long_offset T = N - I L = MINIMUM(T, 4 * long_length) A = N - (I + L)
• The returned value starts at byte index I in the property (indexing from zero),
and its length in bytes is L. If the value for long_offset causes L to be negative,
a BadValue error results. The value of bytes_after_return is A, giving the number
of trailing unread bytes in the stored property.
If the returned format is 8, the returned data is represented as a char array. If the
returned format is 16, the returned data is represented as a short array and should
be cast to that type to obtain the elements. If the returned format is 32, the returned
data is represented as a long array and should be cast to that type to obtain the
elements.
The function returns Success if it executes successfully. To free the resulting data,
use XFree.
60
Window Information
Functions
The XChangeProperty function alters the property for the specified window
and causes the X server to generate a PropertyNotify event on that window.
XChangeProperty performs the following:
61
Window Information
Functions
If the specified format is 8, the property data must be a char array. If the specified
format is 16, the property data must be a short array. If the specified format is 32,
the property data must be a long array.
The lifetime of a property is not tied to the storing client. Properties remain until
explicitly deleted, until the window is destroyed, or until the server resets. For
a discussion of what happens when the connection to the X server is closed, see
section 2.6. The maximum size of a property is server dependent and can vary
dynamically depending on the amount of memory the server has available. (If there
is insufficient space, a BadAlloc error results.)
XDeleteProperty(display, w, property);
62
Window Information
Functions
The XDeleteProperty function deletes the specified property only if the property
was defined on the specified window and causes the X server to generate a
PropertyNotify event on the window unless the property does not exist.
Selections
Selections are one method used by applications to exchange data. By using the
property mechanism, applications can exchange data of arbitrary types and can
negotiate the type of the data. A selection can be thought of as an indirect property
with a dynamic type. That is, rather than having the property stored in the X server,
the property is maintained by some client (the owner). A selection is global in nature
(considered to belong to the user but be maintained by clients) rather than being
private to a particular window subhierarchy or a particular set of clients.
Xlib provides functions that you can use to set, get, or request conversion of
selections. This allows applications to implement the notion of current selection,
which requires that notification be sent to applications when they no longer own the
selection. Applications that support selection often highlight the current selection
and so must be informed when another application has acquired the selection so
that they can unhighlight the selection.
When a client asks for the contents of a selection, it specifies a selection target
type. This target type can be used to control the transmitted representation of the
contents. For example, if the selection is ``the last thing the user clicked on'' and
that is currently an image, then the target type might specify whether the contents
of the image should be sent in XY format or Z format.
The target type can also be used to control the class of contents transmitted, for
example, asking for the ``looks'' (fonts, line spacing, indentation, and so forth) of a
paragraph selection, not the text of the paragraph. The target type can also be used
for other purposes. The protocol does not constrain the semantics.
The XSetSelectionOwner function changes the owner and last-change time for the
specified selection and has no effect if the specified time is earlier than the current
last-change time of the specified selection or is later than the current X server
time. Otherwise, the last-change time is set to the specified time, with CurrentTime
63
Window Information
Functions
replaced by the current server time. If the owner window is specified as None, then
the owner of the selection becomes None (that is, no owner). Otherwise, the owner
of the selection becomes the client executing the request.
If the new owner (whether a client or None) is not the same as the current owner
of the selection and the current owner is not None, the current owner is sent a
SelectionClear event. If the client that is the owner of a selection is later terminated
(that is, its connection is closed) or if the owner window it has specified in the
request is later destroyed, the owner of the selection automatically reverts to None,
but the last-change time is not affected. The selection atom is uninterpreted by
the X server. XGetSelectionOwner returns the owner window, which is reported in
SelectionRequest and SelectionClear events. Selections are global to the X server.
property Specifies the property name. You also can pass None.
64
Window Information
Functions
The arguments are passed on unchanged in either of the events. There are two
predefined selection atoms: PRIMARY and SECONDARY.
65
Chapter 5. Pixmap and Cursor
Functions
Creating and Freeing Pixmaps
Pixmaps can only be used on the screen on which they were created. Pixmaps are
off-screen resources that are used for various operations, such as defining cursors
as tiling patterns or as the source for certain raster operations. Most graphics
requests can operate either on a window or on a pixmap. A bitmap is a single bit-
plane pixmap.
width
height Specify the width and height, which define the dimensions
of the pixmap.
The XCreatePixmap function creates a pixmap of the width, height, and depth
you specified and returns a pixmap ID that identifies it. It is valid to pass an
InputOnly window to the drawable argument. The width and height arguments must
be nonzero, or a BadValue error results. The depth argument must be one of the
depths supported by the screen of the specified drawable, or a BadValue error
results.
The server uses the specified drawable to determine on which screen to create the
pixmap. The pixmap can be used only on this screen and only with other drawables
of the same depth (see XCopyPlane for an exception to this rule). The initial contents
of the pixmap are undefined.
XFreePixmap(display, pixmap);
The XFreePixmap function first deletes the association between the pixmap ID
and the pixmap. Then, the X server frees the pixmap storage when there are no
references to it. The pixmap should never be referenced again.
66
Pixmap and Cursor Functions
From X's perspective, a cursor consists of a cursor source, mask, colors, and a
hotspot. The mask pixmap determines the shape of the cursor and must be a depth
of one. The source pixmap must have a depth of one, and the colors determine the
colors of the source. The hotspot defines the point on the cursor that is reported
when a pointer event occurs. There may be limitations imposed by the hardware
on cursors as to size and whether a mask is implemented. XQueryBestCursor can
be used to find out what sizes are possible. There is a standard font for creating
cursors, but Xlib provides functions that you can use to create cursors from an
arbitrary font or from bitmaps.
#include <X11/cursorfont.h>
The hotspot comes from the information stored in the cursor font. The initial colors
of a cursor are a black foreground and a white background (see XRecolorCursor).
For further information about cursor shapes, see appendix B.
67
Pixmap and Cursor Functions
For 2-byte matrix fonts, the 16-bit value should be formed with the byte1 member
in the most significant byte and the byte2 member in the least significant byte.
68
Pixmap and Cursor Functions
undefined effect on the cursor. The X server might or might not make a copy of the
pixmap.
width
height Specify the width and height of the cursor that you
want the size information for.
width_return
Some displays allow larger cursors than other displays. The XQueryBestCursor
function provides a way to find out what size cursors are actually possible on the
display. It returns the largest size that can be displayed. Applications should be
prepared to use smaller cursors on displays that cannot support large ones.
The XRecolorCursor function changes the color of the specified cursor, and if the
cursor is being displayed on a screen, the change is visible immediately. The pixel
members of the XColor structures are ignored; only the RGB values are used.
XFreeCursor(display, cursor);
69
Pixmap and Cursor Functions
The XFreeCursor function deletes the association between the cursor resource
ID and the specified cursor. The cursor storage is freed when no other resource
references it. The specified cursor ID should not be referred to again.
70
Chapter 6. Color Management
Functions
Each X window always has an associated colormap that provides a level of
indirection between pixel values and colors displayed on the screen. Xlib provides
functions that you can use to manipulate a colormap. The X protocol defines
colors using values in the RGB color space. The RGB color space is device
dependent; rendering an RGB value on differing output devices typically results in
different colors. Xlib also provides a means for clients to specify color using device-
independent color spaces for consistent results across devices. Xlib supports device-
independent color spaces derivable from the CIE XYZ color space. This includes the
CIE XYZ, xyY, L*u*v*, and L*a*b* color spaces as well as the TekHVC color space.
All functions, types, and symbols in this chapter with the prefix ``Xcms'' are defined
in <X11/Xcms.h>. The remaining functions and types are defined in <X11/Xlib.h>.
Functions in this chapter manipulate the representation of color on the screen. For
each possible value that a pixel can take in a window, there is a color cell in the
colormap. For example, if a window is 4 bits deep, pixel values 0 through 15 are
defined. A colormap is a collection of color cells. A color cell consists of a triple
of red, green, and blue (RGB) values. The hardware imposes limits on the number
of significant bits in these values. As each pixel is read out of display memory, the
pixel is looked up in a colormap. The RGB value of the cell determines what color
is displayed on the screen. On a grayscale display with a black-and-white monitor,
the values are combined to determine the brightness on the screen.
Typically, an application allocates color cells or sets of color cells to obtain the
desired colors. The client can allocate read-only cells. In which case, the pixel values
for these colors can be shared among multiple applications, and the RGB value of the
cell cannot be changed. If the client allocates read/write cells, they are exclusively
owned by the client, and the color associated with the pixel value can be changed
at will. Cells must be allocated (and, if read/write, initialized with an RGB value)
by a client to obtain desired colors. The use of pixel value for an unallocated cell
results in an undefined color.
71
Color Management Functions
Because colormaps are associated with windows, X supports displays with multiple
colormaps and, indeed, different types of colormaps. If there are insufficient
colormap resources in the display, some windows will display in their true colors,
and others will display with incorrect colors. A window manager usually controls
which windows are displayed in their true colors if more than one colormap is
required for the color resources the applications are using. At any time, there
is a set of installed colormaps for a screen. Windows using one of the installed
colormaps display with true colors, and windows using other colormaps generally
display with incorrect colors. You can control the set of installed colormaps by using
XInstallColormap and XUninstallColormap.
Colormaps are local to a particular screen. Screens always have a default colormap,
and programs typically allocate cells out of this colormap. Generally, you should
not write applications that monopolize color resources. Although some hardware
supports multiple colormaps installed at one time, many of the hardware displays
built today support only a single installed colormap, so the primitives are written to
encourage sharing of colormap entries between applications.
Color Structures
Functions that operate only on RGB color space values use an XColor structure,
which contains:
typedef struct {
unsigned long pixel; /* pixel value */
unsigned short red, green, blue; /* rgb values */
char flags; /* DoRed, DoGreen, DoBlue */
char pad;
} XColor;
The red, green, and blue values are always in the range 0 to 65535 inclusive,
independent of the number of bits actually used in the display hardware. The server
scales these values down to the range used by the hardware. Black is represented
by (0,0,0), and white is represented by (65535,65535,65535). In some functions,
the flags member controls which of the red, green, and blue members is used and
can be the inclusive OR of zero or more of DoRed, DoGreen, and DoBlue.
Functions that operate on all color space values use an XcmsColor structure. This
structure contains a union of substructures, each supporting color specification
encoding for a particular color space. Like the XColor structure, the XcmsColor
structure contains pixel and color specification information (the spec member in
the XcmsColor structure).
72
Color Management Functions
typedef struct {
union {
XcmsRGB RGB;
XcmsRGBi RGBi;
XcmsCIEXYZ CIEXYZ;
XcmsCIEuvY CIEuvY;
XcmsCIExyY CIExyY;
XcmsCIELab CIELab;
XcmsCIELuv CIELuv;
XcmsTekHVC TekHVC;
XcmsPad Pad;
} spec;
unsigned long pixel;
XcmsColorFormat format;
} XcmsColor; /* Xcms Color Structure */
Because the color specification can be encoded for the various color spaces,
encoding for the spec member is identified by the format member, which is of type
XcmsColorFormat. The following macros define standard formats.
Formats for device-independent color spaces are distinguishable from those for
device-dependent spaces by the 32nd bit. If this bit is set, it indicates that the color
specification is in a device-dependent form; otherwise, it is in a device-independent
form. If the 31st bit is set, this indicates that the color space has been added to
Xlib at run time (see section 6.12.4). The format value for a color space added
at run time may be different each time the program is executed. If references to
such a color space must be made outside the client (for example, storing a color
specification in a file), then reference should be made by color space string prefix
(see XcmsFormatOfPrefix and XcmsPrefixOfFormat).
Data types that describe the color specification encoding for the various color
spaces are defined as follows:
typedef struct {
unsigned short red; /* 0x0000 to 0xffff */
73
Color Management Functions
typedef struct {
XcmsFloat red; /* 0.0 to 1.0 */
XcmsFloat green; /* 0.0 to 1.0 */
XcmsFloat blue; /* 0.0 to 1.0 */
} XcmsRGBi; /* RGB Intensity */
typedef struct {
XcmsFloat X;
XcmsFloat Y; /* 0.0 to 1.0 */
XcmsFloat Z;
} XcmsCIEXYZ; /* CIE XYZ */
typedef struct {
XcmsFloat u_prime; /* 0.0 to ~0.6 */
XcmsFloat v_prime; /* 0.0 to ~0.6 */
XcmsFloat Y; /* 0.0 to 1.0 */
} XcmsCIEuvY; /* CIE u'v'Y */
typedef struct {
XcmsFloat x; /* 0.0 to ~.75 */
XcmsFloat y; /* 0.0 to ~.85 */
XcmsFloat Y; /* 0.0 to 1.0 */
} XcmsCIExyY; /* CIE xyY */
typedef struct {
XcmsFloat L_star; /* 0.0 to 100.0 */
74
Color Management Functions
XcmsFloat a_star;
XcmsFloat b_star;
} XcmsCIELab; /* CIE L*a*b* */
typedef struct {
XcmsFloat L_star; /* 0.0 to 100.0 */
XcmsFloat u_star;
XcmsFloat v_star;
} XcmsCIELuv; /* CIE L*u*v* */
typedef struct {
XcmsFloat H; /* 0.0 to 360.0 */
XcmsFloat V; /* 0.0 to 100.0 */
XcmsFloat C; /* 0.0 to 100.0 */
} XcmsTekHVC; /* TekHVC */
typedef struct {
XcmsFloat pad0;
XcmsFloat pad1;
XcmsFloat pad2;
XcmsFloat pad3;
} XcmsPad; /* four doubles */
• Red, green, and blue linear intensity values, floating-point values from 0.0 to 1.0,
where 1.0 indicates full intensity, 0.5 half intensity, and so on.
• Red, green, and blue values appropriate for the specified output device. XcmsRGB
values are of type unsigned short, scaled from 0 to 65535 inclusive, and are
interchangeable with the red, green, and blue values in an XColor structure.
It is important to note that RGB Intensity values are not gamma corrected values. In
contrast, RGB Device values generated as a result of converting color specifications
are always gamma corrected, and RGB Device values acquired as a result of
querying a colormap or passed in by the client are assumed by Xlib to be gamma
corrected. The term RGB value in this manual always refers to an RGB Device value.
75
Color Management Functions
Color Strings
Xlib provides a mechanism for using string names for colors. A color string may
either contain an abstract color name or a numerical color specification. Color
strings are case-insensitive.
• XAllocNamedColor
• XcmsAllocNamedColor
• XLookupColor
• XcmsLookupColor
• XParseColor
• XStoreNamedColor
Xlib supports the use of abstract color names, for example, red or blue. A value
for this abstract name is obtained by searching one or more color name databases.
Xlib first searches zero or more client-side databases; the number, location, and
content of these databases is implementation-dependent and might depend on the
current locale. If the name is not found, Xlib then looks for the color in the X server's
database. If the color name is not in the Host Portable Character Encoding, the
result is implementation-dependent.
A numerical color specification consists of a color space name and a set of values
in the following syntax:
<color_space_name>:<value>/.../<value>
"CIEXYZ:0.3227/0.28133/0.2493"
"RGBi:1.0/0.0/0.0"
"rgb:00/ff/00"
"CIELuv:50.0/0.0/0.0"
The syntax and semantics of numerical specifications are given for each standard
color space in the following sections.
rgb:<red>/<green>/<blue>
76
Color Management Functions
Note that h indicates the value scaled in 4 bits, hh the value scaled in 8 bits, hhh
the value scaled in 12 bits, and hhhh the value scaled in 16 bits, respectively.
Typical examples are the strings ``rgb:ea/75/52'' and ``rgb:ccc/320/320'', but mixed
numbers of hexadecimal digit strings (``rgb:ff/a5/0'' and ``rgb:ccc/32/0'') are also
allowed.
For backward compatibility, an older syntax for RGB Device is supported, but its
continued use is not encouraged. The syntax is an initial sharp sign character
followed by a numeric specification, in one of the following formats:
The R, G, and B represent single hexadecimal digits. When fewer than 16 bits each
are specified, they represent the most significant bits of the value (unlike the ``rgb:''
syntax, in which values are scaled). For example, the string ``#3a7'' is the same
as ``#3000a0007000''.
rgbi:<red>/<green>/<blue>
Note that red, green, and blue are floating-point values between 0.0 and 1.0,
inclusive. The input format for these values is an optional sign, a string of numbers
possibly containing a decimal point, and an optional exponent field containing an E
or e followed by a possibly signed integer string.
CIEXYZ:<X>/<Y>/<Z>
CIEuvY:<u>/<v>/<Y>
CIExyY:<x>/<y>/<Y>
CIELab:<L>/<a>/<b>
CIELuv:<L>/<u>/<v>
TekHVC:<H>/<V>/<C>
All of the values (C, H, V, X, Y, Z, a, b, u, v, y, x) are floating-point values. The syntax for
these values is an optional plus or minus sign, a string of digits possibly containing a
decimal point, and an optional exponent field consisting of an ``E'' or ``e'' followed
by an optional plus or minus followed by a string of digits.
77
Color Management Functions
Because a specified color may be outside the color gamut of the target screen and
the white point associated with the color specification may differ from the white
point inherent to the screen, Xlib applies gamut mapping when it encounters certain
conditions:
• White adjustment occurs when the inherent white point of the screen differs from
the white point assumed by the client.
Gamut handling methods are stored as callbacks in the CCC, which in turn are used
by the color space conversion routines. Client data is also stored in the CCC for each
callback. The CCC also contains the white point the client assumes to be associated
with color specifications (that is, the Client White Point). The client can specify
the gamut handling callbacks and client data as well as the Client White Point. Xlib
does not preclude the X client from performing other forms of gamut handling (for
example, gamut expansion); however, Xlib does not provide direct support for gamut
handling other than white adjustment and gamut compression.
Xcms functions in which gamut mapping can occur return Status and have specific
status values defined for them, as follows:
78
Color Management Functions
The XCreateColormap function creates a colormap of the specified visual type for
the screen on which the specified window resides and returns the colormap ID
associated with it. Note that the specified window is only used to determine the
screen.
The initial values of the colormap entries are undefined for the visual
classes GrayScale, PseudoColor, and DirectColor. For StaticGray, StaticColor, and
TrueColor, the entries have defined values, but those values are specific to the visual
and are not defined by X. For StaticGray, StaticColor, and TrueColor, alloc must
be AllocNone, or a BadMatch error results. For the other visual classes, if alloc is
AllocNone, the colormap initially has no allocated entries, and clients can allocate
them. For information about the visual types, see section 3.1.
If alloc is AllocAll, the entire colormap is allocated writable. The initial values of all
allocated entries are undefined. For GrayScale and PseudoColor, the effect is as if an
XAllocColorCells call returned all pixel values from zero to N - 1, where N is the
colormap entries value in the specified visual. For DirectColor, the effect is as if an
XAllocColorPlanes call returned a pixel value of zero and red_mask, green_mask,
and blue_mask values containing the same bits as the corresponding masks in the
specified visual. However, in all cases, none of these entries can be freed by using
XFreeColors.
To create a new colormap when the allocation out of a previously shared colormap
has failed because of resource exhaustion, use XCopyColormapAndFree.
79
Color Management Functions
with AllocAll, all color values for all entries are copied from the specified colormap,
and then all entries in the specified colormap are freed. If the specified colormap
was not created by the client with AllocAll, the allocations to be moved are all
those pixels and planes that have been allocated by the client using XAllocColor,
XAllocNamedColor, XAllocColorCells, or XAllocColorPlanes and that have not
been freed since they were allocated.
XFreeColormap(display, colormap);
The XFreeColormap function deletes the association between the colormap resource
ID and the colormap and frees the colormap storage. However, this function has
no effect on the default colormap for a screen. If the specified colormap is an
installed map for a screen, it is uninstalled (see XUninstallColormap). If the
specified colormap is defined as the colormap for a window (by XCreateWindow,
XSetWindowColormap, or XChangeWindowAttributes), XFreeColormap changes the
colormap associated with the window to None and generates a ColormapNotify
event. X does not define the colors displayed for a window with a colormap of None.
The XLookupColor function looks up the string name of a color with respect to
the screen associated with the specified colormap. It returns both the exact color
values and the closest values provided by the screen with respect to the visual type
of the specified colormap. If the color name is not in the Host Portable Character
Encoding, the result is implementation-dependent. Use of uppercase or lowercase
does not matter. XLookupColor returns nonzero if the name is resolved; otherwise,
it returns zero.
80
Color Management Functions
exact_def_return Returns the exact color value for later use and sets
the DoRed, DoGreen, and DoBlue flags.
The XParseColor function looks up the string name of a color with respect to the
screen associated with the specified colormap. It returns the exact color value.
If the color name is not in the Host Portable Character Encoding, the result
is implementation-dependent. Use of uppercase or lowercase does not matter.
XParseColor returns nonzero if the name is resolved; otherwise, it returns zero.
81
Color Management Functions
Read-only colormap cells are shared among clients. The server counts each
allocation and freeing of the cell by clients. When the last client frees a shared cell,
the cell is finally deallocated. If a single client allocates the same read-only cell
multiple times, the server counts each such allocation, not just the first one.
82
Color Management Functions
To allocate a read-only color cell using a color name and return the closest color
supported by the hardware in RGB format, use XAllocNamedColor.
The XAllocNamedColor function looks up the named color with respect to the
screen that is associated with the specified colormap. It returns both the exact
database definition and the closest color supported by the screen. The allocated
color cell is read-only. The pixel value is returned in screen_def_return. If the color
name is not in the Host Portable Character Encoding, the result is implementation-
dependent. Use of uppercase or lowercase does not matter. If screen_def_return
and exact_def_return point to the same structure, the pixel field will be set correctly,
but the color values are undefined. XAllocNamedColor returns nonzero if a cell is
allocated; otherwise, it returns zero.
To allocate a read-only color cell using a color name and return the closest color
supported by the hardware in an arbitrary format, use XcmsAllocNamedColor.
83
Color Management Functions
color_screen_return Returns the pixel value of the color cell and color
specification that actually is stored for that cell.
This function returns both the color specification as a result of parsing (exact
specification) and the actual color specification stored (screen specification).
This screen specification is the result of converting the RGB value returned
by XAllocColor into the format specified in result_format. If there is no
interest in a returned color specification, unnecessary computation can be
bypassed if result_format is set to XcmsRGBFormat. If color_screen_return and
color_exact_return point to the same structure, the pixel field will be set correctly,
but the color values are undefined.
To allocate read/write color cell and color plane combinations for a PseudoColor
model, use XAllocColorCells.
84
Color Management Functions
nreds
ngreens
rmask_return
gmask_return
bmask_return Return bit masks for the red, green, and blue planes.
The specified ncolors must be positive; and nreds, ngreens, and nblues must be
nonnegative, or a BadValue error results. If ncolors colors, nreds reds, ngreens
greens, and nblues blues are requested, ncolors pixels are returned; and the masks
have nreds, ngreens, and nblues bits set to 1, respectively. If contig is True, each
mask will have a contiguous set of bits set to 1. No mask will have any bits set
to 1 in common with any other mask or with any of the pixels. For DirectColor,
85
Color Management Functions
each mask will lie within the corresponding pixel subfield. By ORing together
(nreds+ngreens+nblues)
subsets of masks with each pixel value, ncolors × 2 distinct pixel
values can be produced. All of these are allocated by the request. However, in the
nreds ngreens
colormap, there are only ncolors × 2 independent red entries, ncolors × 2
nblues
independent green entries, and ncolors × 2 independent blue entries. This is
true even for PseudoColor. When the colormap entry of a pixel value is changed
(using XStoreColors, XStoreColor, or XStoreNamedColor), the pixel is decomposed
according to the masks, and the corresponding independent entries are updated.
XAllocColorPlanes returns nonzero if it succeeded or zero if it failed.
The XFreeColors function frees the cells represented by pixels whose values are
in the pixels array. The planes argument should not have any bits set to 1 in
common with any of the pixels. The set of all pixels is produced by ORing together
subsets of the planes argument with the pixels. The request frees all of these
pixels that were allocated by the client (using XAllocColor, XAllocNamedColor,
XAllocColorCells, and XAllocColorPlanes). Note that freeing an individual pixel
obtained from XAllocColorPlanes may not actually allow it to be reused until all
of its related pixels are also freed. Similarly, a read-only entry is not actually freed
until it has been freed by all clients, and if a client allocates the same read-only entry
multiple times, it must free the entry that many times before the entry is actually
freed.
All specified pixels that are allocated by the client in the colormap are freed, even
if one or more pixels produce an error. If a specified pixel is not a valid index into
the colormap, a BadValue error results. If a specified pixel is not allocated by the
client (that is, is unallocated or is only allocated by another client) or if the colormap
was created with all entries writable (by passing AllocAll to XCreateColormap), a
BadAccess error results. If more than one pixel is in error, the one that gets reported
is arbitrary.
86
Color Management Functions
The XStoreColor function changes the colormap entry of the pixel value specified
in the pixel member of the XColor structure. You specified this value in the pixel
member of the XColor structure. This pixel value must be a read/write cell and
a valid index into the colormap. If a specified pixel is not a valid index into the
colormap, a BadValue error results. XStoreColor also changes the red, green, and/
or blue color components. You specify which color components are to be changed
by setting DoRed, DoGreen, and/or DoBlue in the flags member of the XColor
structure. If the colormap is an installed map for its screen, the changes are visible
immediately.
The XStoreColors function changes the colormap entries of the pixel values
specified in the pixel members of the XColor structures. You specify which color
components are to be changed by setting DoRed, DoGreen, and/or DoBlue in the
flags member of the XColor structures. If the colormap is an installed map for its
screen, the changes are visible immediately. XStoreColors changes the specified
pixels if they are allocated writable in the colormap by any client, even if one or more
pixels generates an error. If a specified pixel is not a valid index into the colormap, a
BadValue error results. If a specified pixel either is unallocated or is allocated read-
only, a BadAccess error results. If more than one pixel is in error, the one that gets
reported is arbitrary.
color Specifies the color cell and the color to store. Values
specified in this XcmsColor structure remain unchanged
on return.
87
Color Management Functions
Note that XStoreColor has no return value; therefore, an XcmsSuccess return value
from this function indicates that the conversion to RGB succeeded and the call to
XStoreColor was made. To obtain the actual color stored, use XcmsQueryColor.
Because of the screen's hardware limitations or gamut compression, the color
stored in the colormap may not be identical to the color specified.
88
Color Management Functions
XStoreColors was made. To obtain the actual colors stored, use XcmsQueryColors.
Because of the screen's hardware limitations or gamut compression, the colors
stored in the colormap may not be identical to the colors specified.
flags Specifies which red, green, and blue components are set.
The XStoreNamedColor function looks up the named color with respect to the
screen associated with the colormap and stores the result in the specified colormap.
The pixel argument determines the entry in the colormap. The flags argument
determines which of the red, green, and blue components are set. You can set
this member to the bitwise inclusive OR of the bits DoRed, DoGreen, and DoBlue.
If the color name is not in the Host Portable Character Encoding, the result is
implementation-dependent. Use of uppercase or lowercase does not matter. If the
specified pixel is not a valid index into the colormap, a BadValue error results. If
the specified pixel either is unallocated or is allocated read-only, a BadAccess error
results.
The XQueryColor and XQueryColors functions take pixel values in the pixel member
of XColor structures and store in the structures the RGB values for those pixels from
the specified colormap. The values returned for an unallocated entry are undefined.
These functions also set the flags member in the XColor structure to all three colors.
If a pixel is not a valid index into the specified colormap, a BadValue error results.
If more than one pixel is in error, the one that gets reported is arbitrary.
def_in_out Specifies and returns the RGB values for the pixel
specified in the structure.
The XQueryColor function returns the current RGB value for the pixel in the XColor
structure and sets the DoRed, DoGreen, and DoBlue flags.
89
Color Management Functions
The XQueryColors function returns the RGB value for each pixel in each XColor
structure and sets the DoRed, DoGreen, and DoBlue flags in each structure.
The XcmsQueryColor function obtains the RGB value for the pixel value in the pixel
member of the specified XcmsColor structure and then converts the value to the
target format as specified by the result_format argument. If the pixel is not a valid
index in the specified colormap, a BadValue error results.
90
Color Management Functions
The XcmsQueryColors function obtains the RGB values for pixel values in the pixel
members of XcmsColor structures and then converts the values to the target format
as specified by the result_format argument. If a pixel is not a valid index into the
specified colormap, a BadValue error results. If more than one pixel is in error, the
one that gets reported is arbitrary.
The initial values for these attributes are implementation specific. The CCC
attributes for subsequently created CCCs can be defined by changing the CCC
attributes of the default CCC. There is a default CCC associated with each screen.
The XcmsCCCOfColormap function returns the CCC associated with the specified
colormap. Once obtained, the CCC attributes can be queried or modified.
Unless the CCC associated with the specified colormap is changed with
XcmsSetCCCOfColormap, this CCC is used when the specified colormap is used as
an argument to color functions.
91
Color Management Functions
The XcmsSetCCCOfColormap function changes the CCC associated with the specified
colormap. It returns the CCC previously associated with the colormap. If they are
not used again in the application, CCCs should be freed by calling XcmsFreeCCC.
Several colormaps may share the same CCC without restriction; this includes the
CCCs generated by Xlib with each colormap. Xlib, however, creates a new CCC with
each new colormap.
The XcmsDefaultCCC function returns the default CCC for the specified screen.
Its visual is the default visual of the screen. Its initial gamut compression and
white point adjustment procedures as well as the associated client data are
implementation specific.
DisplayOfCCC(ccc);
Display *XcmsDisplayOfCCC(ccc);
VisualOfCCC(ccc);
Visual *XcmsVisualOfCCC(ccc);
ScreenNumberOfCCC(ccc);
int XcmsScreenNumberOfCCC(ccc);
92
Color Management Functions
Both return the number of the screen associated with the specified CCC.
ScreenWhitePointOfCCC(ccc);
XcmsColor XcmsScreenWhitePointOfCCC(ccc);
Both return the white point of the screen associated with the specified CCC.
ClientWhitePointOfCCC(ccc);
XcmsColor *XcmsClientWhitePointOfCCC(ccc);
This function returns nonzero status if the format for the new white point is valid;
otherwise, it returns zero.
93
Color Management Functions
To set the white point adjustment procedure and corresponding client data in a
specified CCC, use XcmsSetWhiteAdjustProc.
94
Color Management Functions
white_adjust_client_data Specifies client data for use with the white point
adjustment procedure or NULL.
The XcmsCreateCCC function creates a CCC for the specified display, screen, and
visual.
void XcmsFreeCCC(ccc);
The XcmsFreeCCC function frees the memory used for the specified CCC. Note that
default CCCs and those currently associated with colormaps are ignored.
The array may contain a mixture of color specification formats (for example, 3
CIE XYZ, 2 CIE Luv, and so on). When the array contains both device-independent
95
Color Management Functions
Callback Functions
This section describes the gamut compression and white point adjustment
callbacks.
The gamut compression procedure specified in the CCC is called when an attempt
to convert a color specification from XcmsCIEXYZ to a device-dependent format
(typically XcmsRGBi) results in a color that lies outside the screen's color gamut. If
the gamut compression procedure requires client data, this data is passed via the
gamut compression client data in the CCC.
96
Color Management Functions
• When called, the element in the color specification array specified by the index
argument contains the color specification outside the screen's color gamut
encountered by the calling routine. In addition, this color specification can be
assumed to be in XcmsCIEXYZ. Upon return, this color specification must be in
XcmsCIEXYZ.
• When called, elements from index to ncolors - 1 in the color specification array
may or may not fall within the screen's color gamut. In addition, these color
specifications can be assumed to be in XcmsCIEXYZ. If any modifications are made
to these color specifications, they must be in XcmsCIEXYZ upon return.
• The color specifications passed to the gamut compression procedure have already
been adjusted to the Screen White Point. This means that at this point the color
specification's white point is the Screen White Point.
• XcmsCIELabClipL
• This brings the encountered out-of-gamut color specification into the screen's
color gamut by reducing or increasing CIE metric lightness (L*) in the CIE L*a*b*
color space until the color is within the gamut. If the Psychometric Chroma
of the color specification is beyond maximum for the Psychometric Hue Angle,
then while maintaining the same Psychometric Hue Angle, the color will be
clipped to the CIE L*a*b* coordinates of maximum Psychometric Chroma. See
XcmsCIELabQueryMaxC. No client data is necessary.
• XcmsCIELabClipab
• This brings the encountered out-of-gamut color specification into the screen's
color gamut by reducing Psychometric Chroma, while maintaining Psychometric
Hue Angle, until the color is within the gamut. No client data is necessary.
97
Color Management Functions
• XcmsCIELabClipLab
• This brings the encountered out-of-gamut color specification into the screen's
color gamut by replacing it with CIE L*a*b* coordinates that fall within the color
gamut while maintaining the original Psychometric Hue Angle and whose vector
to the original coordinates is the shortest attainable. No client data is necessary.
• XcmsCIELuvClipL
• This brings the encountered out-of-gamut color specification into the screen's
color gamut by reducing or increasing CIE metric lightness (L*) in the CIE L*u*v*
color space until the color is within the gamut. If the Psychometric Chroma
of the color specification is beyond maximum for the Psychometric Hue Angle,
then, while maintaining the same Psychometric Hue Angle, the color will be
clipped to the CIE L*u*v* coordinates of maximum Psychometric Chroma. See
XcmsCIELuvQueryMaxC. No client data is necessary.
• XcmsCIELuvClipuv
• This brings the encountered out-of-gamut color specification into the screen's
color gamut by reducing Psychometric Chroma, while maintaining Psychometric
Hue Angle, until the color is within the gamut. No client data is necessary.
• XcmsCIELuvClipLuv
• This brings the encountered out-of-gamut color specification into the screen's
color gamut by replacing it with CIE L*u*v* coordinates that fall within the color
gamut while maintaining the original Psychometric Hue Angle and whose vector
to the original coordinates is the shortest attainable. No client data is necessary.
• XcmsTekHVCClipV
• This brings the encountered out-of-gamut color specification into the screen's
color gamut by reducing or increasing the Value dimension in the TekHVC color
space until the color is within the gamut. If Chroma of the color specification is
beyond maximum for the particular Hue, then, while maintaining the same Hue,
the color will be clipped to the Value and Chroma coordinates that represent
maximum Chroma for that particular Hue. No client data is necessary.
• XcmsTekHVCClipC
• This brings the encountered out-of-gamut color specification into the screen's
color gamut by reducing the Chroma dimension in the TekHVC color space until
the color is within the gamut. No client data is necessary.
• XcmsTekHVCClipVC
• This brings the encountered out-of-gamut color specification into the screen's
color gamut by replacing it with TekHVC coordinates that fall within the color
gamut while maintaining the original Hue and whose vector to the original
coordinates is the shortest attainable. No client data is necessary.
98
Color Management Functions
• XcmsCIELabWhiteShiftColors
• This uses the CIE L*a*b* color space for adjusting the chromatic character of
colors to compensate for the chromatic differences between the source and
destination white points. This procedure simply converts the color specifications
to XcmsCIELab using the source white point and then converts to the target
specification format using the destination's white point. No client data is
necessary.
• XcmsCIELuvWhiteShiftColors
• This uses the CIE L*u*v* color space for adjusting the chromatic character of
colors to compensate for the chromatic differences between the source and
destination white points. This procedure simply converts the color specifications
to XcmsCIELuv using the source white point and then converts to the target
specification format using the destination's white point. No client data is
necessary.
• XcmsTekHVCWhiteShiftColors
• This uses the TekHVC color space for adjusting the chromatic character of
colors to compensate for the chromatic differences between the source and
destination white points. This procedure simply converts the color specifications
99
Color Management Functions
to XcmsTekHVC using the source white point and then converts to the target
specification format using the destination's white point. An advantage of this
procedure over those previously described is an attempt to minimize hue shift.
No client data is necessary.
As an example, if the CCC specifies a white point adjustment procedure and if the
Client White Point and Screen White Point differ, the XcmsAllocColor function will
use the white point adjustment procedure twice:
The resulting RGB specification is passed to XAllocColor, and the RGB specification
returned by XAllocColor is converted back to XcmsCIEuvY by reversing the color
conversion sequence.
100
Color Management Functions
The white point associated with color specifications passed to and returned from
these gamut querying functions is assumed to be the Screen White Point. This is
a reasonable assumption, because the client is trying to query the screen's color
gamut.
The following naming convention is used for the Max and Min functions:
Xcms<color_space>QueryMax<dimensions>
Xcms<color_space>QueryMin<dimensions>
The <dimensions> consists of a letter or letters that identify the dimensions of the
color space that are not fixed. For example, XcmsTekHVCQueryMaxC is given a fixed
Hue and Value for which maximum Chroma is found.
ccc Specifies the CCC. The CCC's Client White Point and
white point adjustment procedures are ignored.
The XcmsQueryBlack function returns the color specification in the specified target
format for zero-intensity red, green, and blue.
To obtain the color specification for blue (full-intensity blue while red and green are
zero), use XcmsQueryBlue.
ccc Specifies the CCC. The CCC's Client White Point and
white point adjustment procedures are ignored.
101
Color Management Functions
The XcmsQueryBlue function returns the color specification in the specified target
format for full-intensity blue while red and green are zero.
To obtain the color specification for green (full-intensity green while red and blue
are zero), use XcmsQueryGreen.
ccc Specifies the CCC. The CCC's Client White Point and
white point adjustment procedures are ignored.
The XcmsQueryGreen function returns the color specification in the specified target
format for full-intensity green while red and blue are zero.
To obtain the color specification for red (full-intensity red while green and blue are
zero), use XcmsQueryRed.
ccc Specifies the CCC. The CCC's Client White Point and
white point adjustment procedures are ignored.
The XcmsQueryRed function returns the color specification in the specified target
format for full-intensity red while green and blue are zero.
To obtain the color specification for white (full-intensity red, green, and blue), use
XcmsQueryWhite.
ccc Specifies the CCC. The CCC's Client White Point and
white point adjustment procedures are ignored.
102
Color Management Functions
The XcmsQueryWhite function returns the color specification in the specified target
format for full-intensity red, green, and blue.
CIELab Queries
The following equations are useful in describing the CIELab query functions: delim
%%
To obtain the CIE L*a*b* coordinates of maximum Psychometric Chroma for a given
Psychometric Hue Angle and CIE metric lightness (L*), use XcmsCIELabQueryMaxC.
ccc Specifies the CCC. The CCC's Client White Point and
white point adjustment procedures are ignored.
The XcmsCIELabQueryMaxC function, given a hue angle and lightness, finds the point
of maximum chroma displayable by the screen. It returns this point in CIE L*a*b*
coordinates.
ccc Specifies the CCC. The CCC's Client White Point and
white point adjustment procedures are ignored.
103
Color Management Functions
The XcmsCIELabQueryMaxL function, given a hue angle and chroma, finds the point
in CIE L*a*b* color space of maximum lightness (L*) displayable by the screen. It
returns this point in CIE L*a*b* coordinates. An XcmsFailure return value usually
indicates that the given chroma is beyond maximum for the given hue angle.
To obtain the CIE L*a*b* coordinates of maximum Psychometric Chroma for a given
Psychometric Hue Angle, use XcmsCIELabQueryMaxLC.
ccc Specifies the CCC. The CCC's Client White Point and
white point adjustment procedures are ignored.
The XcmsCIELabQueryMaxLC function, given a hue angle, finds the point of maximum
chroma displayable by the screen. It returns this point in CIE L*a*b* coordinates.
ccc Specifies the CCC. The CCC's Client White Point and
white point adjustment procedures are ignored.
104
Color Management Functions
The XcmsCIELabQueryMinL function, given a hue angle and chroma, finds the point
of minimum lightness (L*) displayable by the screen. It returns this point in CIE
L*a*b* coordinates. An XcmsFailure return value usually indicates that the given
chroma is beyond maximum for the given hue angle.
CIELuv Queries
The following equations are useful in describing the CIELuv query functions: delim
%%
To obtain the CIE L*u*v* coordinates of maximum Psychometric Chroma for a given
Psychometric Hue Angle and CIE metric lightness (L*), use XcmsCIELuvQueryMaxC.
ccc Specifies the CCC. The CCC's Client White Point and
white point adjustment procedures are ignored.
The XcmsCIELuvQueryMaxC function, given a hue angle and lightness, finds the point
of maximum chroma displayable by the screen. It returns this point in CIE L*u*v*
coordinates.
ccc Specifies the CCC. The CCC's Client White Point and
white point adjustment procedures are ignored.
105
Color Management Functions
The XcmsCIELuvQueryMaxL function, given a hue angle and chroma, finds the point
in CIE L*u*v* color space of maximum lightness (L*) displayable by the screen. It
returns this point in CIE L*u*v* coordinates. An XcmsFailure return value usually
indicates that the given chroma is beyond maximum for the given hue angle.
To obtain the CIE L*u*v* coordinates of maximum Psychometric Chroma for a given
Psychometric Hue Angle, use XcmsCIELuvQueryMaxLC.
ccc Specifies the CCC. The CCC's Client White Point and
white point adjustment procedures are ignored.
The XcmsCIELuvQueryMaxLC function, given a hue angle, finds the point of maximum
chroma displayable by the screen. It returns this point in CIE L*u*v* coordinates.
ccc Specifies the CCC. The CCC's Client White Point and
white point adjustment procedures are ignored.
The XcmsCIELuvQueryMinL function, given a hue angle and chroma, finds the point
of minimum lightness (L*) displayable by the screen. It returns this point in CIE
106
Color Management Functions
L*u*v* coordinates. An XcmsFailure return value usually indicates that the given
chroma is beyond maximum for the given hue angle.
TekHVC Queries
To obtain the maximum Chroma for a given Hue and Value, use
XcmsTekHVCQueryMaxC.
ccc Specifies the CCC. The CCC's Client White Point and
white point adjustment procedures are ignored.
To obtain the maximum Value for a given Hue and Chroma, use
XcmsTekHVCQueryMaxV.
ccc Specifies the CCC. The CCC's Client White Point and
white point adjustment procedures are ignored.
color_return Returns the maximum Value along with the Hue and
Chroma at which the maximum Value was found.
The white point associated with the returned color
specification is the Screen White Point. The value
returned in the pixel member is undefined.
To obtain the maximum Chroma and Value at which it is reached for a specified Hue,
use XcmsTekHVCQueryMaxVC.
107
Color Management Functions
ccc Specifies the CCC. The CCC's Client White Point and
white point adjustment procedures are ignored.
ccc Specifies the CCC. The CCC's Client White Point and
white point adjustment procedures are ignored.
To obtain the minimum Value for a given Hue and Chroma, use
XcmsTekHVCQueryMinV.
ccc Specifies the CCC. The CCC's Client White Point and
white point adjustment procedures are ignored.
108
Color Management Functions
color_return Returns the minimum Value and the actual Hue and
Chroma at which the minimum Value was found.
The white point associated with the returned color
specification is the Screen White Point. The value
returned in the pixel member is undefined.
• Device-independent color spaces that are derivable to CIE XYZ space can be
added using the XcmsAddColorSpace function.
Color Spaces
The CIE XYZ color space serves as the hub for all conversions between device-
independent and device-dependent color spaces. Therefore, the knowledge to
convert an XcmsColor structure to and from CIE XYZ format is associated with
each color space. For example, conversion from CIE L*u*v* to RGB requires the
knowledge to convert from CIE L*u*v* to CIE XYZ and from CIE XYZ to RGB.
This knowledge is stored as an array of functions that, when applied in series, will
convert the XcmsColor structure to or from CIE XYZ format. This color specification
conversion mechanism facilitates the addition of color spaces.
109
Color Management Functions
Status XcmsAddColorSpace(color_space);
XcmsColorFormat XcmsFormatOfPrefix(prefix);
prefix Specifies the string that contains the color space prefix.
The XcmsFormatOfPrefix function returns the format for the specified color space
prefix (for example, the string ``CIEXYZ''). The prefix is case-insensitive. If the
color space is not accessible in the color management system, XcmsFormatOfPrefix
returns XcmsUndefinedFormat.
To obtain the color string prefix associated with the color space specified by a color
format, use XcmsPrefixOfFormat.
char *XcmsPrefixOfFormat(format);
The XcmsPrefixOfFormat function returns the string prefix associated with the
color specification encoding specified by the format argument. Otherwise, if no
encoding is found, it returns NULL. The returned string must be treated as read-
only.
110
Color Management Functions
specifications in a file using the unregistered color space), then reference should be
made by color space prefix (see XcmsFormatOfPrefix and XcmsPrefixOfFormat).
typedef (*XcmsConversionProc)();
typedef XcmsConversionProc *XcmsFuncListPtr;
/* A NULL terminated list of function pointers*/
The prefix member specifies the prefix that indicates a color string is in this color
space's string format. For example, the strings ``ciexyz'' or ``CIEXYZ'' for CIE XYZ,
and ``rgb'' or ``RGB'' for RGB. The prefix is case insensitive. The format member
specifies the color specification format. Formats for unregistered color spaces are
assigned at run time. The parseString member contains a pointer to the function
that can parse a color string into an XcmsColor structure. This function returns
an integer (int): nonzero if it succeeded and zero otherwise. The to_CIEXYZ and
from_CIEXYZ members contain pointers, each to a NULL terminated list of function
pointers. When the list of functions is executed in series, it will convert the color
specified in an XcmsColor structure from/to the current color space format to/from
the CIE XYZ format. Each function returns an integer (int): nonzero if it succeeded
and zero otherwise. The white point to be associated with the colors is specified
explicitly, even though white points can be found in the CCC. The inverse_flag
member, if nonzero, specifies that for each function listed in to_CIEXYZ, its inverse
function can be found in from_CIEXYZ such that:
This allows Xlib to use the shortest conversion path, thus bypassing CIE XYZ if
possible (for example, TekHVC to CIE L*u*v*).
111
Color Management Functions
Conversion functions are available globally for use by other color spaces. The
conversion functions provided by Xlib are:
112
Color Management Functions
Function Sets
Functions to convert between device-dependent color spaces and CIE XYZ may
differ for different classes of output devices (for example, color versus gray
monitors). Therefore, the notion of a Color Characterization Function Set has
been developed. A function set consists of device-dependent color spaces and the
functions that convert color specifications between these device-dependent color
spaces and the CIE XYZ color space appropriate for a particular class of output
devices. The function set also contains a function that reads color characterization
data off root window properties. It is this characterization data that will differ
between devices within a class of output devices. For details about how color
characterization data is stored in root window properties, see the section on Device
Color Characterization in the Inter-Client Communication Conventions Manual. The
LINEAR_RGB function set is provided by Xlib and will support most color monitors.
Function sets may require data that differs from those needed for the LINEAR_RGB
function set. In that case, its corresponding data may be stored on different root
window properties.
Status XcmsAddFunctionSet(function_set);
Additional function sets should be added before any calls to other Xlib routines are
made. If not, the XcmsPerScrnInfo member of a previously created XcmsCCC does
not have the opportunity to initialize with the added function set.
113
Color Management Functions
The screen initialization callback must adhere to the following software interface
specification:
• It sets the screenData member to the address of the created device profile data
structure (contents known only by the function set).
114
Color Management Functions
If unsuccessful, the procedure sets the state member to XcmsInitFailure and returns
XcmsFailure.
The screenWhitePoint member specifies the white point inherent to the screen. The
functionSet member specifies the appropriate function set. The screenData member
specifies the device profile. The state member is set to one of the following:
The screen free callback must adhere to the following software interface
specification:
115
Chapter 7. Graphics Context Functions
A number of resources are used when performing graphics operations in X. Most
information about performing graphics (for example, foreground color, background
color, line style, and so on) is stored in resources called graphics contexts (GCs).
Most graphics operations (see chapter 8) take a GC as an argument. Although in
theory the X protocol permits sharing of GCs between applications, it is expected
that applications will use their own GCs when performing operations. Sharing of
GCs is highly discouraged because the library may cache GC state.
Xlib implements a write-back cache for all elements of a GC that are not resource
IDs to allow Xlib to implement the transparent coalescing of changes to GCs. For
example, a call to XSetForeground of a GC followed by a call to XSetLineAttributes
results in only a single-change GC protocol request to the server. GCs are neither
expected nor encouraged to be shared between client applications, so this write-
back caching should present no problems. Applications cannot share GCs without
external synchronization. Therefore, sharing GCs between applications is highly
discouraged.
To set an attribute of a GC, set the appropriate member of the XGCValues structure
and OR in the corresponding value bitmask in your subsequent calls to XCreateGC.
The symbols for the value mask bits and the XGCValues structure are:
116
Graphics Context Functions
/* Values */
typedef struct {
int function; /* logical operation */
unsigned long plane_mask; /* plane mask */
unsigned long foreground; /* foreground pixel */
unsigned long background; /* background pixel */
int line_width; /* line width (in pixels) */
int line_style; /* LineSolid, LineOnOffDash, LineDoubleDash */
int cap_style; /* CapNotLast, CapButt, CapRound, CapProjecting
int join_style; /* JoinMiter, JoinRound, JoinBevel */
int fill_style; /* FillSolid, FillTiled, FillStippled FillOpaque
int fill_rule; /* EvenOddRule, WindingRule */
int arc_mode; /* ArcChord, ArcPieSlice */
Pixmap tile; /* tile pixmap for tiling operations */
Pixmap stipple; /* stipple 1 plane pixmap for stippling */
int ts_x_origin; /* offset for tile or stipple operations */
int ts_y_origin
Font font; /* default text font for text operations */
int subwindow_mode; /* ClipByChildren, IncludeInferiors */
Bool graphics_exposures; /* boolean, should exposures be generated */
int clip_x_origin; /* origin for clipping */
int clip_y_origin;
Pixmap clip_mask; /* bitmap clipping; other calls for rects */
int dash_offset; /* patterned/dashed line information */
char dashes;
} XGCValues;
Component Default
function GXcopy
plane_mask All ones
foreground 0
117
Graphics Context Functions
Component Default
background 1
line_width 0
line_style LineSolid
cap_style CapButt
join_style JoinMiter
fill_style FillSolid
fill_rule EvenOddRule
arc_mode ArcPieSlice
tile Pixmap of unspecified size filled with
foreground pixel
Note that foreground and background are not set to any values likely to be useful
in a window.
The function attributes of a GC are used when you update a section of a drawable
(the destination) with bits from somewhere else (the source). The function in a GC
defines how the new destination bits are to be computed from the source bits and
the old destination bits. GXcopy is typically the most useful because it will work
on a color display, but special applications may use other functions, particularly in
concert with particular planes of a color display. The 16 GC functions, defined in
<X11/X.h>, are:
118
Graphics Context Functions
Many graphics operations depend on either pixel values or planes in a GC. The
planes attribute is of type long, and it specifies which planes of the destination are
to be modified, one bit per plane. A monochrome display has only one plane and will
be the least significant bit of the word. As planes are added to the display hardware,
they will occupy more significant bits in the plane mask.
In graphics operations, given a source and destination pixel, the result is computed
bitwise on corresponding bits of the pixels. That is, a Boolean operation is performed
in each bit plane. The plane_mask restricts the operation to a subset of planes.
A macro constant AllPlanes can be used to refer to all planes of the screen
simultaneously. The result is computed by the following:
Wide lines are drawn centered on the path described by the graphics request.
Unless otherwise specified by the join-style or cap-style, the bounding box of a wide
line with endpoints [x1, y1], [x2, y2] and width w is a rectangle with vertices at the
following real coordinates:
Here sn is the sine of the angle of the line, and cs is the cosine of the angle of the
line. A pixel is part of the line and so is drawn if the center of the pixel is fully inside
the bounding box (which is viewed as having infinitely thin edges). If the center
of the pixel is exactly on the bounding box, it is part of the line if and only if the
interior is immediately to its right (x increasing direction). Pixels with centers on a
horizontal edge are a special case and are part of the line if and only if the interior
119
Graphics Context Functions
Thin lines (zero line-width) are one-pixel-wide lines drawn using an unspecified,
device-dependent algorithm. There are only two constraints on this algorithm.
• If a line is drawn unclipped from [x1,y1] to [x2,y2] and if another line is drawn
unclipped from [x1+dx,y1+dy] to [x2+dx,y2+dy], a point [x,y] is touched by
drawing the first line if and only if the point [x+dx,y+dy] is touched by drawing
the second line.
• The effective set of points comprising a line cannot be affected by clipping. That
is, a point is touched in a clipped line if and only if the point lies inside the clipping
region and the point would be touched by the line when drawn unclipped.
A wide line drawn from [x1,y1] to [x2,y2] always draws the same pixels as a
wide line drawn from [x2,y2] to [x1,y1], not counting cap-style and join-style. It is
recommended that this property be true for thin lines, but this is not required. A
line-width of zero may differ from a line-width of one in which pixels are drawn.
This permits the use of many manufacturers' line drawing hardware, which may run
many times faster than the more precisely specified wide lines.
In general, drawing a thin line will be faster than drawing a wide line of width one.
However, because of their different drawing algorithms, thin lines may not mix well
aesthetically with wide lines. If it is desirable to obtain precise and uniform results
across all displays, a client should always use a line-width of one rather than a line-
width of zero.
LineDoubleDash The full path of the line is drawn, but the even dashes are filled
differently from the odd dashes (see fill-style) with CapButt style
used where even and odd dashes meet.
LineOnOffDash Only the even dashes are drawn, and cap-style applies to all
internal ends of the individual dashes, except CapNotLast is
treated as CapButt.
CapRound The line has a circular arc with the diameter equal to the line-
width, centered on the endpoint. (This is equivalent to CapButt for
line-width of zero).
CapProjecting The line is square at the end, but the path continues beyond
the endpoint for a distance equal to half the line-width. (This is
equivalent to CapButt for line-width of zero).
120
Graphics Context Functions
The join-style defines how corners are drawn for wide lines:
JoinMiter The outer edges of two lines extend to meet at an angle. However, if
the angle is less than 11 degrees, then a JoinBevel join-style is used
instead.
JoinRound The corner is a circular arc with the diameter equal to the line-width,
centered on the joinpoint.
JoinBevel The corner has CapButt endpoint styles with the triangular notch filled.
For a line with coincident endpoints (x1=x2, y1=y2), when the cap-style is applied
to both endpoints, the semantics depends on the line-width and the cap-style:
For a line with coincident endpoints (x1=x2, y1=y2), when the join-style is applied
at one or both endpoints, the effect is as if the line was removed from the overall
path. However, if the total path consists of or is reduced to a single point joined with
itself, the effect is the same as when the cap-style is applied at both endpoints.
The fill-style defines the contents of the source for line, text, and fill requests. For
all text and fill requests (for example, XDrawText, XDrawText16, XFillRectangle,
XFillPolygon, and XFillArc); for line requests with line-style LineSolid (for
example, XDrawLine, XDrawSegments, XDrawRectangle, XDrawArc); and for the even
dashes for line requests with line-style LineOnOffDash or LineDoubleDash, the
following apply:
121
Graphics Context Functions
FillSolid Foreground
FillTiled Tile
FillOpaqueStippled A tile with the same width and height as stipple, but
with background everywhere stipple has a zero and
with foreground everywhere stipple has a one
FillStippled Foreground masked by stipple
When drawing lines with line-style LineDoubleDash, the odd dashes are controlled
by the fill-style in the following manner:
FillSolid Background
FillTiled Same as for even dashes
FillOpaqueStippled Same as for even dashes
FillStippled Background masked by stipple
Storing a pixmap in a GC might or might not result in a copy being made. If the
pixmap is later used as the destination for a graphics request, the change might or
might not be reflected in the GC. If the pixmap is used simultaneously in a graphics
request both as a destination and as a tile or stipple, the results are undefined.
For optimum performance, you should draw as much as possible with the same
GC (without changing its components). The costs of changing GC components
relative to using different GCs depend on the display hardware and the server
implementation. It is quite likely that some amount of GC information will be cached
in display hardware and that such hardware can only cache a small number of GCs.
The dashes value is actually a simplified form of the more general patterns that
can be set with XSetDashes. Specifying a value of N is equivalent to specifying the
two-element list [N, N] in XSetDashes. The value must be nonzero, or a BadValue
error results.
The clip-mask restricts writes to the destination drawable. If the clip-mask is set to
a pixmap, it must have depth one and have the same root as the GC, or a BadMatch
error results. If clip-mask is set to None, the pixels are always drawn regardless of
the clip origin. The clip-mask also can be set by calling the XSetClipRectangles or
XSetRegion functions. Only pixels where the clip-mask has a bit set to 1 are drawn.
Pixels are not drawn outside the area covered by the clip-mask or where the clip-
mask has a bit set to 0. The clip-mask affects all graphics requests. The clip-mask
does not clip sources. The clip-mask origin is interpreted relative to the origin of
whatever destination drawable is specified in a graphics request.
The fill-rule defines what pixels are inside (drawn) for paths given in XFillPolygon
requests and can be set to EvenOddRule or WindingRule. For EvenOddRule, a point
is inside if an infinite ray with the point as origin crosses the path an odd number
of times. For WindingRule, a point is inside if an infinite ray with the point as
122
Graphics Context Functions
For both EvenOddRule and WindingRule, a point is infinitely small, and the path is
an infinitely thin line. A pixel is inside if the center point of the pixel is inside and the
center point is not on the boundary. If the center point is on the boundary, the pixel
is inside if and only if the polygon interior is immediately to its right (x increasing
direction). Pixels with centers on a horizontal edge are a special case and are inside
if and only if the polygon interior is immediately below (y increasing direction).
The arc-mode controls filling in the XFillArcs function and can be set to ArcPieSlice
or ArcChord. For ArcPieSlice, the arcs are pie-slice filled. For ArcChord, the arcs
are chord filled.
To create a new GC that is usable on a given screen with a depth of drawable, use
XCreateGC.
The XCreateGC function creates a graphics context and returns a GC. The GC can be
used with any destination drawable having the same root and depth as the specified
drawable. Use with other drawables results in a BadMatch error.
123
Graphics Context Functions
The XCopyGC function copies the specified components from the source GC to the
destination GC. The source and destination GCs must have the same root and depth,
or a BadMatch error results. The valuemask specifies which component to copy, as
for XCreateGC.
The XChangeGC function changes the components specified by valuemask for the
specified GC. The values argument contains the values to be set. The values and
restrictions are the same as for XCreateGC. Changing the clip-mask overrides any
previous XSetClipRectangles request on the context. Changing the dash-offset
or dash-list overrides any previous XSetDashes request on the context. The order
in which components are verified and altered is server dependent. If an error is
generated, a subset of the components may have been altered.
124
Graphics Context Functions
XFreeGC(display, gc);
The XFreeGC function destroys the specified GC as well as all the associated storage.
GContext XGContextFromGC(gc);
• Font component
125
Graphics Context Functions
function Specifies the function you want to set for the specified
GC.
126
Graphics Context Functions
function Specifies the function you want to set for the specified GC.
line_width Specifies the line-width you want to set for the specified
GC.
cap_style Specifies the line-style and cap-style you want to set for
the specified GC. You can pass CapNotLast, CapButt,
CapRound, or CapProjecting.
join_style Specifies the line join-style you want to set for the
specified GC. You can pass JoinMiter, JoinRound, or
JoinBevel.
To set the dash-offset and dash-list for dashed line styles of a given GC, use
XSetDashes.
dash_offset Specifies the phase of the pattern for the dashed line-
style you want to set for the specified GC.
127
Graphics Context Functions
The XSetDashes function sets the dash-offset and dash-list attributes for dashed
line styles in the specified GC. There must be at least one element in the specified
dash_list, or a BadValue error results. The initial and alternating elements (second,
fourth, and so on) of the dash_list are the even dashes, and the others are the odd
dashes. Each element specifies a dash length in pixels. All of the elements must be
nonzero, or a BadValue error results. Specifying an odd-length list is equivalent to
specifying the same list concatenated with itself to produce an even-length list.
The dash-offset defines the phase of the pattern, specifying how many pixels into the
dash-list the pattern should actually begin in any single graphics request. Dashing
is continuous through path elements combined with a join-style but is reset to the
dash-offset between each sequence of joined lines.
The unit of measure for dashes is the same for the ordinary coordinate system.
Ideally, a dash length is measured along the slope of the line, but implementations
are only required to match this ideal for horizontal and vertical lines. Failing the
ideal semantics, it is suggested that the length be measured along the major axis
of the line. The major axis is defined as the x axis for lines drawn at an angle of
between −45 and +45 degrees or between 135 and 225 degrees from the x axis.
For all other lines, the major axis is the y axis.
fill_style Specifies the fill-style you want to set for the specified
GC. You can pass FillSolid, FillTiled, FillStippled, or
FillOpaqueStippled.
fill_rule Specifies the fill-rule you want to set for the specified GC.
You can pass EvenOddRule or WindingRule.
128
Graphics Context Functions
class Specifies the class that you are interested in. You can
pass TileShape, CursorShape, or StippleShape.
width
width_return
The XQueryBestSize function returns the best or closest size to the specified
size. For CursorShape, this is the largest size that can be fully displayed on
the screen specified by which_screen. For TileShape, this is the size that can
be tiled fastest. For StippleShape, this is the size that can be stippled fastest.
For CursorShape, the drawable indicates the desired screen. For TileShape and
StippleShape, the drawable indicates the screen and possibly the window class
and depth. An InputOnly window cannot be used as the drawable for TileShape or
StippleShape, or a BadMatch error results.
width
width_return
129
Graphics Context Functions
The XQueryBestTile function returns the best or closest size, that is, the size that
can be tiled fastest on the screen specified by which_screen. The drawable indicates
the screen and possibly the window class and depth. If an InputOnly window is used
as the drawable, a BadMatch error results.
width
width_return
The XQueryBestStipple function returns the best or closest size, that is, the size
that can be stippled fastest on the screen specified by which_screen. The drawable
indicates the screen and possibly the window class and depth. If an InputOnly
window is used as the drawable, a BadMatch error results.
tile Specifies the fill tile you want to set for the specified GC.
The tile and GC must have the same depth, or a BadMatch error results.
stipple Specifies the stipple you want to set for the specified GC.
130
Graphics Context Functions
ts_x_origin
When graphics requests call for tiling or stippling, the parent's origin will be
interpreted relative to whatever destination drawable is specified in the graphics
request.
clip_x_origin
131
Graphics Context Functions
If the clip-mask is set to None, the pixels are always drawn (regardless of the clip-
origin).
clip_x_origin
If known by the client, ordering relations on the rectangles can be specified with the
ordering argument. This may provide faster operation by the server. If an incorrect
ordering is specified, the X server may generate a BadMatch error, but it is not
required to do so. If no error is generated, the graphics results are undefined.
Unsorted means the rectangles are in arbitrary order. YSorted means that the
rectangles are nondecreasing in their Y origin. YXSorted additionally constrains
YSorted order in that all rectangles with an equal Y origin are nondecreasing in
their X origin. YXBanded additionally constrains YXSorted by requiring that, for
every possible Y scanline, all rectangles that include that scanline have an identical
Y origins and Y extents.
132
Graphics Context Functions
Xlib provides a set of basic functions for performing region arithmetic. For
information about these functions, see section 16.5.
133
Chapter 8. Graphics Functions
Once you have established a connection to a display, you can use the Xlib graphics
functions to:
• Fill areas
• Manipulate fonts
• Draw text
If the same drawable and GC is used for each call, Xlib batches back-to-back calls to
XDrawPoint, XDrawLine, XDrawRectangle, XFillArc, and XFillRectangle. Note that
this reduces the total number of requests sent to the server.
Clearing Areas
Xlib provides functions that you can use to clear an area or the entire window.
Because pixmaps do not have defined backgrounds, they cannot be filled by
using the functions described in this section. Instead, to accomplish an analogous
operation on a pixmap, you should use XFillRectangle, which sets the pixmap to
a known value.
width
height Specify the width and height, which are the dimensions
of the rectangle.
134
Graphics Functions
replaced with the current height of the window minus y. If the window has a defined
background tile, the rectangle clipped by any children is filled with this tile. If
the window has background None, the contents of the window are not changed.
In either case, if exposures is True, one or more Expose events are generated for
regions of the rectangle that are either visible or are being retained in a backing
store. If you specify a window whose class is InputOnly, a BadMatch error results.
XClearWindow(display, w);
The XClearWindow function clears the entire area in the specified window and is
equivalent to XClearArea (display, w, 0, 0, 0, 0, False). If the window has a defined
background tile, the rectangle is tiled with a plane-mask of all ones and GXcopy
function. If the window has background None, the contents of the window are
not changed. If you specify a window whose class is InputOnly, a BadMatch error
results.
Copying Areas
Xlib provides functions that you can use to copy an area or a bit plane.
To copy an area between drawables of the same root and depth, use XCopyArea.
src
src_x
width
height Specify the width and height, which are the dimensions of
both the source and destination rectangles.
dest_x
135
Graphics Functions
The XCopyArea function combines the specified rectangle of src with the specified
rectangle of dest. The drawables must have the same root and depth, or a BadMatch
error results.
If regions of the source rectangle are obscured and have not been retained
in backing store or if regions outside the boundaries of the source drawable
are specified, those regions are not copied. Instead, the following occurs on
all corresponding destination regions that are either visible or are retained in
backing store. If the destination is a window with a background other than None,
corresponding regions of the destination are tiled with that background (with
plane-mask of all ones and GXcopy function). Regardless of tiling or whether
the destination is a window or a pixmap, if graphics-exposures is True, then
GraphicsExpose events for all corresponding destination regions are generated.
If graphics-exposures is True but no GraphicsExpose events are generated, a
NoExpose event is generated. Note that by default graphics-exposures is True in
new GCs.
src
src_x
width
height Specify the width and height, which are the dimensions of
both the source and destination rectangles.
dest_x
136
Graphics Functions
plane Specifies the bit plane. You must set exactly one bit to 1.
The XCopyPlane function uses a single bit plane of the specified source rectangle
combined with the specified GC to modify the specified rectangle of dest. The
drawables must have the same root but need not have the same depth. If the
drawables do not have the same root, a BadMatch error results. If plane does not
have exactly one bit set to 1 and the value of plane is not less than %2 sup n%,
where n is the depth of src, a BadValue error results.
Effectively, XCopyPlane forms a pixmap of the same depth as the rectangle of dest
and with a size specified by the source region. It uses the foreground/background
pixels in the GC (foreground everywhere the bit plane in src contains a bit set
to 1, background everywhere the bit plane in src contains a bit set to 0) and the
equivalent of a CopyArea protocol request is performed with all the same exposure
semantics. This can also be thought of as using the specified region of the source
bit plane as a stipple with a fill-style of FillOpaqueStippled for filling a rectangular
area of the destination.
Some of the functions described in the following sections use these structures:
typedef struct {
short x1, y1, x2, y2;
} XSegment;
typedef struct {
short x, y;
} XPoint;
137
Graphics Functions
typedef struct {
short x, y;
unsigned short width, height;
} XRectangle;
typedef struct {
short x, y;
unsigned short width, height;
short angle1, angle2; /* Degrees * 64 */
} XArc;
All x and y members are signed integers. The width and height members are 16-bit
unsigned integers. You should be careful not to generate coordinates and sizes out
of the 16-bit ranges, because the protocol only has 16-bit fields for these values.
138
Graphics Functions
The XDrawPoint function uses the foreground pixel and function components of the
GC to draw a single point into the specified drawable; XDrawPoints draws multiple
points this way. CoordModeOrigin treats all coordinates as relative to the origin, and
CoordModePrevious treats all coordinates after the first as relative to the previous
point. XDrawPoints draws the points in the order listed in the array.
To draw a single line between two points in a given drawable, use XDrawLine.
x1
y1
x2
139
Graphics Functions
The XDrawLine function uses the components of the specified GC to draw a line
between the specified set of points (x1, y1) and (x2, y2). It does not perform joining
at coincident endpoints. For any given line, XDrawLine does not draw a pixel more
than once. If lines intersect, the intersecting pixels are drawn multiple times.
The XDrawLines function uses the components of the specified GC to draw npoints-1
lines between each pair of points (point[i], point[i+1]) in the array of XPoint
structures. It draws the lines in the order listed in the array. The lines join correctly
at all intermediate points, and if the first and last points coincide, the first and
last lines also join correctly. For any given line, XDrawLines does not draw a
pixel more than once. If thin (zero line-width) lines intersect, the intersecting
pixels are drawn multiple times. If wide lines intersect, the intersecting pixels are
drawn only once, as though the entire PolyLine protocol request were a single,
filled shape. CoordModeOrigin treats all coordinates as relative to the origin, and
CoordModePrevious treats all coordinates after the first as relative to the previous
point.
The XDrawSegments function draws multiple, unconnected lines. For each segment,
XDrawSegments draws a line between (x1, y1) and (x2, y2). It draws the lines in the
order listed in the array of XSegment structures and does not perform joining at
coincident endpoints. For any given line, XDrawSegments does not draw a pixel more
than once. If lines intersect, the intersecting pixels are drawn multiple times.
140
Graphics Functions
width
height Specify the width and height, which specify the dimensions
of the rectangle.
For the specified rectangle or rectangles, these functions do not draw a pixel more
than once. XDrawRectangles draws the rectangles in the order listed in the array.
If rectangles intersect, the intersecting pixels are drawn multiple times.
141
Graphics Functions
width
height Specify the width and height, which are the major and
minor axes of the arc.
angle2 Specifies the path and extent of the arc relative to the start
of the arc, in units of degrees * 64.
delim %% XDrawArc draws a single circular or elliptical arc, and XDrawArcs draws
multiple circular or elliptical arcs. Each arc is specified by a rectangle and two
angles. The center of the circle or ellipse is the center of the rectangle, and the
major and minor axes are specified by the width and height. Positive angles indicate
counterclockwise motion, and negative angles indicate clockwise motion. If the
magnitude of angle2 is greater than 360 degrees, XDrawArc or XDrawArcs truncates
it to 360 degrees.
For an arc specified as %[ ~x, ~y, ~width , ~height, ~angle1, ~angle2 ]%, the origin
of the major and minor axes is at % [ x +^ {width over 2} , ~y +^ {height over
2} ]%, and the infinitely thin path describing the entire circle or ellipse intersects
the horizontal axis at % [ x, ~y +^ {height over 2} ]% and % [ x +^ width , ~y
+^ { height over 2 }] % and intersects the vertical axis at % [ x +^ { width over
2 } , ~y ]% and % [ x +^ { width over 2 }, ~y +^ height ]%. These coordinates
can be fractional and so are not truncated to discrete coordinates. The path should
be defined by the ideal mathematical path. For a wide line with line-width lw, the
bounding outlines for filling are given by the two infinitely thin paths consisting of
all points whose perpendicular distance from the path of the circle/ellipse is equal to
lw/2 (which may be a fractional value). The cap-style and join-style are applied the
same as for a line corresponding to the tangent of the circle/ellipse at the endpoint.
For an arc specified as % [ ~x, ~y, ~width, ~height, ~angle1, ~angle2 ]%, the angles
must be specified in the effectively skewed coordinate system of the ellipse (for a
circle, the angles and coordinate systems are identical). The relationship between
these angles and angles expressed in the normal coordinate system of the screen
(as measured with a protractor) is as follows:
142
Graphics Functions
For any given arc, XDrawArc and XDrawArcs do not draw a pixel more than once.
If two arcs join correctly and if the line-width is greater than zero and the arcs
intersect, XDrawArc and XDrawArcs do not draw a pixel more than once. Otherwise,
the intersecting pixels of intersecting arcs are drawn multiple times. Specifying an
arc with one endpoint and a clockwise extent draws the same pixels as specifying
the other endpoint and an equivalent counterclockwise extent, except as it affects
joins.
If the last point in one arc coincides with the first point in the following arc, the two
arcs will join correctly. If the first point in the first arc coincides with the last point
in the last arc, the two arcs will join correctly. By specifying one axis to be zero, a
horizontal or vertical line can be drawn. Angles are computed based solely on the
coordinate system and ignore the aspect ratio.
XDrawArc and XDrawArcs can generate BadDrawable, BadGC, and BadMatch errors.
Filling Areas
Xlib provides functions that you can use to fill:
• A single polygon
143
Graphics Functions
width
height Specify the width and height, which are the dimensions of
the rectangle to be filled.
Each function uses the x and y coordinates, width and height dimensions, and GC
you specify.
XFillRectangles fills the rectangles in the order listed in the array. For any given
rectangle, XFillRectangle and XFillRectangles do not draw a pixel more than
once. If rectangles intersect, the intersecting pixels are drawn multiple times.
144
Graphics Functions
XFillPolygon fills the region closed by the specified path. The path is closed
automatically if the last point in the list does not coincide with the first point.
XFillPolygon does not draw a pixel of the region more than once. CoordModeOrigin
treats all coordinates as relative to the origin, and CoordModePrevious treats all
coordinates after the first as relative to the previous point.
• If shape is Complex, the path may self-intersect. Note that contiguous coincident
points in the path are not treated as self-intersection.
• If shape is Convex, for every pair of points inside the polygon, the line segment
connecting them does not intersect the path. If known by the client, specifying
Convex can improve performance. If you specify Convex for a path that is not
convex, the graphics results are undefined.
• If shape is Nonconvex, the path does not self-intersect, but the shape is not wholly
convex. If known by the client, specifying Nonconvex instead of Complex may
improve performance. If you specify Nonconvex for a self-intersecting path, the
graphics results are undefined.
145
Graphics Functions
width
height Specify the width and height, which are the major and
minor axes of the arc.
angle2 Specifies the path and extent of the arc relative to the start
of the arc, in units of degrees * 64.
For each arc, XFillArc or XFillArcs fills the region closed by the infinitely thin
path described by the specified arc and, depending on the arc-mode specified in
the GC, one or two line segments. For ArcChord, the single line segment joining
the endpoints of the arc is used. For ArcPieSlice, the two line segments joining the
endpoints of the arc with the center point are used. XFillArcs fills the arcs in the
order listed in the array. For any given arc, XFillArc and XFillArcs do not draw a
pixel more than once. If regions intersect, the intersecting pixels are drawn multiple
times.
XFillArc and XFillArcs can generate BadDrawable, BadGC, and BadMatch errors.
Font Metrics
A font is a graphical description of a set of characters that are used to increase
efficiency whenever a set of small, similar sized patterns are repeatedly used.
146
Graphics Functions
The X server loads fonts whenever a program requests a new font. The server
can cache fonts for quick lookup. Fonts are global across all screens in a server.
Several levels are possible when dealing with fonts. Most applications simply use
XLoadQueryFont to load a font and query the font metrics.
Characters in fonts are regarded as masks. Except for image text requests, the only
pixels modified are those in which bits are set to 1 in the character. This means that
it makes sense to draw text using stipples or tiles (for example, many menus gray-
out unusable entries).
The XFontStruct structure contains all of the information for the font and consists
of the font-specific information as well as a pointer to an array of XCharStruct
structures for the characters contained in the font. The XFontStruct, XFontProp,
and XCharStruct structures contain:
typedef struct {
short lbearing; /* origin to left edge of raster */
short rbearing; /* origin to right edge of raster */
short width; /* advance to next char's origin */
short ascent; /* baseline to top edge of raster */
short descent; /* baseline to bottom edge of raster */
unsigned short attributes; /* per char flags (not predefined) */
} XCharStruct;
typedef struct {
Atom name;
unsigned long card32;
} XFontProp;
147
Graphics Functions
typedef struct {
XExtData *ext_data; /* hook for extension to hang data */
Font fid; /* Font id for this font */
unsigned direction; /* hint about the direction font is painted
unsigned min_char_or_byte2; /* first character */
unsigned max_char_or_byte2; /* last character */
unsigned min_byte1; /* first row that exists */
unsigned max_byte1; /* last row that exists */
Bool all_chars_exist; /* flag if all characters have nonzero size
unsigned default_char; /* char to print for undefined character */
int n_properties; /* how many properties there are */
XFontProp *properties; /* pointer to array of additional properties
XCharStruct min_bounds; /* minimum bounds over all existing char */
XCharStruct max_bounds; /* maximum bounds over all existing char */
XCharStruct *per_char; /* first_char to last_char information */
int ascent; /* logical extent above baseline for spacing
int descent; /* logical descent below baseline for spacin
} XFontStruct;
• where:
148
Graphics Functions
• If the per_char pointer is NULL, all glyphs between the first and last character
indexes inclusive have the same information, as given by both min_bounds and
max_bounds.
• The default_char member specifies the character that will be used when an
undefined or nonexistent character is printed. The default_char is a 16-bit
character (not a 2-byte character). For a font using 2-byte matrix format,
the default_char has byte1 in the most-significant byte and byte2 in the least
significant byte. If the default_char itself specifies an undefined or nonexistent
character, no printing is performed for an undefined or nonexistent character.
• The min_bounds and max_bounds members contain the most extreme values of
each individual XCharStruct component over all elements of this array (and ignore
nonexistent characters). The bounding box of the font (the smallest rectangle
enclosing the shape obtained by superimposing all of the characters at the same
origin [x,y]) has its upper-left coordinate at:
[x + min_bounds.lbearing, y - max_bounds.ascent]
max_bounds.rbearing - min_bounds.lbearing
max_bounds.ascent + max_bounds.descent
• The ascent member is the logical extent of the font above the baseline that is used
for determining line spacing. Specific characters may extend beyond this.
• The descent member is the logical extent of the font at or below the baseline that
is used for determining line spacing. Specific characters may extend beyond this.
For a character origin at [x,y], the bounding box of a character (that is, the smallest
rectangle that encloses the character's shape) described in terms of XCharStruct
components is a rectangle with its upper-left corner at:
[x + lbearing, y - ascent]
149
Graphics Functions
rbearing - lbearing
ascent + descent
[x + width, y]
The lbearing member defines the extent of the left edge of the character ink from the
origin. The rbearing member defines the extent of the right edge of the character
ink from the origin. The ascent member defines the extent of the top edge of the
character ink from the origin. The descent member defines the extent of the bottom
edge of the character ink from the origin. The width member defines the logical
width of the character.
Note that the baseline (the y position of the character origin) is logically viewed as
being the scanline just below nondescending characters. When descent is zero, only
pixels with Y-coordinates less than y are drawn, and the origin is logically viewed
as being coincident with the left edge of a nonkerned character. When lbearing is
zero, no pixels with X-coordinate less than x are drawn. Any of the XCharStruct
metric members could be negative. If the width is negative, the next character will
be placed to the left of the current origin.
The X protocol does not define the interpretation of the attributes member in the
XCharStruct structure. A nonexistent character is represented with all members of
its XCharStruct set to zero.
A font is not guaranteed to have any properties. The interpretation of the property
value (for example, long or unsigned long) must be derived from a priori knowledge
of the property. A basic set of font properties is specified in the X Consortium
standard X Logical Font Description Conventions.
The XLoadFont function loads the specified font and returns its associated font
ID. If the font name is not in the Host Portable Character Encoding, the result is
implementation-dependent. Use of uppercase or lowercase does not matter. When
the characters ``?'' and ``*'' are used in a font name, a pattern match is performed
and any matching font is used. In the pattern, the ``?'' character will match any
150
Graphics Functions
single character, and the ``*'' character will match any number of characters.
A structured format for font names is specified in the X Consortium standard X
Logical Font Description Conventions. If XLoadFont was unsuccessful at loading the
specified font, a BadName error results. Fonts are not associated with a particular
screen and can be stored as a component of any GC. When the font is no longer
needed, call XUnloadFont.
The XLoadQueryFont function provides the most common way for accessing a font.
XLoadQueryFont both opens (loads) the specified font and returns a pointer to the
appropriate XFontStruct structure. If the font name is not in the Host Portable
Character Encoding, the result is implementation-dependent. If the font does not
exist, XLoadQueryFont returns NULL.
To unload the font and free the storage used by the font structure that was allocated
by XQueryFont or XLoadQueryFont, use XFreeFont.
XFreeFont(display, font_struct);
The XFreeFont function deletes the association between the font resource ID and
the specified font and frees the XFontStruct structure. The font itself will be freed
when no other resource references it. The data and the font should not be referenced
again.
151
Graphics Functions
atom Specifies the atom for the property name you want
returned.
Given the atom for that property, the XGetFontProperty function returns the value
of the specified font property. XGetFontProperty also returns False if the property
was not defined or True if it was defined. A set of predefined atoms exists for font
properties, which can be found in <X11/Xatom.h>. This set contains the standard
properties associated with a font. Although it is not guaranteed, it is likely that the
predefined font properties will be present.
XUnloadFont(display, font);
The XUnloadFont function deletes the association between the font resource ID and
the specified font. The font itself will be freed when no other resource references
it. The font should not be referenced again.
The XListFonts function returns an array of available font names (as controlled by
the font search path; see XSetFontPath) that match the string you passed to the
pattern argument. The pattern string can contain any characters, but each asterisk
(*) is a wildcard for any number of characters, and each question mark (?) is a
wildcard for a single character. If the pattern string is not in the Host Portable
Character Encoding, the result is implementation-dependent. Use of uppercase or
lowercase does not matter. Each returned string is null-terminated. If the data
152
Graphics Functions
returned by the server is in the Latin Portable Character Encoding, then the
returned strings are in the Host Portable Character Encoding. Otherwise, the result
is implementation-dependent. If there are no matching font names, XListFonts
returns NULL. The client should call XFreeFontNames when finished with the result
to free the memory.
XFreeFontNames(list[]);
The XFreeFontNames function frees the array and strings returned by XListFonts
or XListFontsWithInfo.
The XListFontsWithInfo function returns a list of font names that match the
specified pattern and their associated font information. The list of names is limited
to size specified by maxnames. The information returned for each font is identical to
what XLoadQueryFont would return except that the per-character metrics are not
returned. The pattern string can contain any characters, but each asterisk (*) is a
wildcard for any number of characters, and each question mark (?) is a wildcard for a
single character. If the pattern string is not in the Host Portable Character Encoding,
the result is implementation-dependent. Use of uppercase or lowercase does not
matter. Each returned string is null-terminated. If the data returned by the server is
in the Latin Portable Character Encoding, then the returned strings are in the Host
Portable Character Encoding. Otherwise, the result is implementation-dependent.
If there are no matching font names, XListFontsWithInfo returns NULL.
To free only the allocated name array, the client should call XFreeFontNames. To
free both the name array and the font information array or to free just the font
information array, the client should call XFreeFontInfo.
153
Graphics Functions
The XFreeFontInfo function frees a font structure or an array of font structures and
optionally an array of font names. If NULL is passed for names, no font names are
freed. If a font structure for an open font (returned by XLoadQueryFont) is passed,
the structure is freed, but the font is not closed; use XUnloadFont to close the font.
154
Graphics Functions
To compute the bounding box of a 2-byte character string in a given font, use
XTextExtents16.
The ascent member is set to the maximum of the ascent metrics of all characters
in the string. The descent member is set to the maximum of the descent metrics.
The width member is set to the sum of the character-width metrics of all characters
in the string. For each character in the string, let W be the sum of the character-
width metrics of all characters preceding it in the string. Let L be the left-side-
bearing metric of the character plus W. Let R be the right-side-bearing metric of the
character plus W. The lbearing member is set to the minimum L of all characters in
the string. The rbearing member is set to the maximum R.
For fonts defined with linear indexing rather than 2-byte matrix indexing, each
XChar2b structure is interpreted as a 16-bit number with byte1 as the most
significant byte. If the font has no defined default character, undefined characters
in the string are taken to have all zero metrics.
155
Graphics Functions
To query the server for the bounding box of a 2-byte character string in a given font,
use XQueryTextExtents16.
The ascent member is set to the maximum of the ascent metrics of all characters
in the string. The descent member is set to the maximum of the descent metrics.
The width member is set to the sum of the character-width metrics of all characters
in the string. For each character in the string, let W be the sum of the character-
width metrics of all characters preceding it in the string. Let L be the left-side-
bearing metric of the character plus W. Let R be the right-side-bearing metric of the
character plus W. The lbearing member is set to the minimum L of all characters in
the string. The rbearing member is set to the maximum R.
156
Graphics Functions
For fonts defined with linear indexing rather than 2-byte matrix indexing, each
XChar2b structure is interpreted as a 16-bit number with byte1 as the most
significant byte. If the font has no defined default character, undefined characters
in the string are taken to have all zero metrics.
Characters with all zero metrics are ignored. If the font has no defined default_char,
the undefined characters in the string are also ignored.
Drawing Text
This section discusses how to draw:
• Complex text
• Text characters
The fundamental text functions XDrawText and XDrawText16 use the following
structures:
typedef struct {
char *chars; /* pointer to string */
int nchars; /* number of characters */
int delta; /* delta between strings */
Font font; /* Font to print it in, None don't change */
} XTextItem;
typedef struct {
XChar2b *chars; /* pointer to two-byte characters */
int nchars; /* number of characters */
int delta; /* delta between strings */
Font font; /* font to print it in, None don't change */
} XTextItem16;
If the font member is not None, the font is changed before printing and also is stored
in the GC. If an error was generated during text drawing, the previous items may
have been drawn. The baseline of the characters are drawn starting at the x and y
coordinates that you pass in the text drawing functions.
157
Graphics Functions
(x,y), pass the (x,y + ascent) as the baseline origin coordinates to the text functions.
The ascent is the font ascent, as given in the XFontStruct structure. If you want the
lower-left corner of the background rectangle to be at pixel coordinate (x,y), pass
the (x,y - descent + 1) as the baseline origin coordinates to the text functions. The
descent is the font descent, as given in the XFontStruct structure.
The XDrawText16 function is similar to XDrawText except that it uses 2-byte or 16-bit
characters. Both functions allow complex spacing and font shifts between counted
strings.
Each text item is processed in turn. A font member other than None in an item
causes the font to be stored in the GC and used for subsequent text. A text element
delta specifies an additional change in the position along the x axis before the string
is drawn. The delta is always added to the character origin and is not dependent
158
Graphics Functions
on any characteristics of the font. Each character image, as defined by the font in
the GC, is treated as an additional mask for a fill operation on the drawable. The
drawable is modified only where the font character has a bit set to 1. If a text item
generates a BadFont error, the previous text items may have been drawn.
For fonts defined with linear indexing rather than 2-byte matrix indexing, each
XChar2b structure is interpreted as a 16-bit number with byte1 as the most
significant byte.
159
Graphics Functions
Each character image, as defined by the font in the GC, is treated as an additional
mask for a fill operation on the drawable. The drawable is modified only where the
font character has a bit set to 1. For fonts defined with 2-byte matrix indexing and
used with XDrawString16, each byte is used as a byte2 with a byte1 of zero.
160
Graphics Functions
The effect is first to fill a destination rectangle with the background pixel defined in
the GC and then to paint the text with the foreground pixel. The upper-left corner
of the filled rectangle is at:
[x, y - font-ascent]
overall-width
font-ascent + font-descent
For fonts defined with 2-byte matrix indexing and used with XDrawImageString,
each byte is used as a byte2 with a byte1 of zero.
All the image manipulation functions discussed in this section make use of the
XImage structure, which describes an image as it exists in the client's memory.
161
Graphics Functions
Status XInitImage(image);
This function must be called for any image constructed by the client before passing
it to any other Xlib function. Image structures created or returned by Xlib do not
need to be initialized in this fashion.
162
Graphics Functions
image Specifies the image you want combined with the rectangle.
src_x Specifies the offset in X from the left edge of the image
defined by the XImage structure.
src_y Specifies the offset in Y from the top edge of the image
defined by the XImage structure.
dest_x
width
height Specify the width and height of the subimage, which define
the dimensions of the rectangle.
If the characteristics of the image (for example, byte_order and bitmap_unit) differ
from what the server requires, XPutImage automatically makes the appropriate
conversions.
163
Graphics Functions
width
format Specifies the format for the image. You can pass
XYPixmap or ZPixmap.
XGetImage returns the depth of the image to the depth member of the XImage
structure. The depth of the image is as specified when the drawable was created,
except when getting a subset of the planes in XYPixmap format, when the depth is
given by the number of bits set to 1 in plane_mask.
If the drawable is a pixmap, the given rectangle must be wholly contained within the
pixmap, or a BadMatch error results. If the drawable is a window, the window must
be viewable, and it must be the case that if there were no inferiors or overlapping
windows, the specified rectangle of the window would be fully visible on the screen
and wholly contained within the outside edges of the window, or a BadMatch error
results. Note that the borders of the window can be included and read with this
request. If the window has backing-store, the backing-store contents are returned
for regions of the window that are obscured by noninferior windows. If the window
does not have backing-store, the returned contents of such obscured regions are
undefined. The returned contents of visible regions of inferiors of a different depth
than the specified window's depth are also undefined. The pointer cursor image
is not included in the returned contents. If a problem occurs, XGetImage returns
NULL.
164
Graphics Functions
width
format Specifies the format for the image. You can pass
XYPixmap or ZPixmap.
dest_x
The XGetSubImage function updates dest_image with the specified subimage in the
same manner as XGetImage. If the format argument is XYPixmap, the image contains
only the bit planes you passed to the plane_mask argument. If the format argument
is ZPixmap, XGetSubImage returns as zero the bits in all planes not specified in the
plane_mask argument. The function performs no range checking on the values in
plane_mask and ignores extraneous bits. As a convenience, XGetSubImage returns
a pointer to the same XImage structure specified by dest_image.
The depth of the destination XImage structure must be the same as that of the
drawable. If the specified subimage does not fit at the specified location on the
destination image, the right and bottom edges are clipped. If the drawable is a
pixmap, the given rectangle must be wholly contained within the pixmap, or a
BadMatch error results. If the drawable is a window, the window must be viewable,
and it must be the case that if there were no inferiors or overlapping windows, the
specified rectangle of the window would be fully visible on the screen and wholly
contained within the outside edges of the window, or a BadMatch error results. If the
window has backing-store, then the backing-store contents are returned for regions
of the window that are obscured by noninferior windows. If the window does not
have backing-store, the returned contents of such obscured regions are undefined.
The returned contents of visible regions of inferiors of a different depth than the
specified window's depth are also undefined. If a problem occurs, XGetSubImage
returns NULL.
165
Chapter 9. Window and Session
Manager Functions
Although it is difficult to categorize functions as exclusively for an application, a
window manager, or a session manager, the functions in this chapter are most often
used by window managers and session managers. It is not expected that these
functions will be used by most application programs. Xlib provides management
functions to:
• Kill a client
166
Window and Session
Manager Functions
• The new parent window is not on the same screen as the old parent window.
• The new parent window is the specified window or an inferior of the specified
window.
• The specified window has a ParentRelative background, and the new parent
window is not the same depth as the specified window.
The X server automatically removes windows from the save-set when they are
destroyed.
XChangeSaveSet(display, w, change_mode);
167
Window and Session
Manager Functions
XAddToSaveSet(display, w);
The XAddToSaveSet function adds the specified window to the client's save-set. The
specified window must have been created by some other client, or a BadMatch error
results.
XRemoveFromSaveSet(display, w);
The XRemoveFromSaveSet function removes the specified window from the client's
save-set. The specified window must have been created by some other client, or a
BadMatch error results.
At any time, there is a subset of the installed maps that is viewed as an ordered list
and is called the required list. The length of the required list is at most M, where
M is the minimum number of installed colormaps specified for the screen in the
connection setup. The required list is maintained as follows. When a colormap is
specified to XInstallColormap, it is added to the head of the list; the list is truncated
at the tail, if necessary, to keep its length to at most M. When a colormap is specified
to XUninstallColormap and it is in the required list, it is removed from the list. A
colormap is not added to the required list when it is implicitly installed by the X
server, and the X server cannot implicitly uninstall a colormap that is in the required
list.
XInstallColormap(display, colormap);
The XInstallColormap function installs the specified colormap for its associated
screen. All windows associated with this colormap immediately display with true
168
Window and Session
Manager Functions
colors. You associated the windows with this colormap when you created them
by calling XCreateWindow, XCreateSimpleWindow, XChangeWindowAttributes, or
XSetWindowColormap.
If the specified colormap is not already an installed colormap, the X server generates
a ColormapNotify event on each window that has that colormap. In addition, for
every other colormap that is installed as a result of a call to XInstallColormap, the
X server generates a ColormapNotify event on each window that has that colormap.
XUninstallColormap(display, colormap);
To obtain a list of the currently installed colormaps for a given screen, use
XListInstalledColormaps.
169
Window and Session
Manager Functions
The XSetFontPath function defines the directory search path for font lookup.
There is only one search path per X server, not one per client. The encoding
and interpretation of the strings are implementation-dependent, but typically they
specify directories or font servers to be searched in the order listed. An X server
is permitted to cache font information internally; for example, it might cache an
entire font from a file and not check on subsequent opens of that font to see if the
underlying font file has changed. However, when the font path is changed, the X
server is guaranteed to flush all cached information about fonts for which there
currently are no explicit resource IDs allocated. The meaning of an error from this
request is implementation-dependent.
The XGetFontPath function allocates and returns an array of strings containing the
search path. The contents of these strings are implementation-dependent and are
not intended to be interpreted by client applications. When it is no longer needed,
the data in the font path should be freed by using XFreeFontPath.
XFreeFontPath(list);
170
Window and Session
Manager Functions
XGrabServer(display);
The XGrabServer function disables processing of requests and close downs on all
other connections than the one this request arrived on. You should not grab the X
server any more than is absolutely necessary.
XUngrabServer(display);
Killing Clients
Xlib provides a function to cause the connection to a client to be closed and its
resources to be destroyed. To destroy a client, use XKillClient.
XKillClient(display, resource);
resource Specifies any resource associated with the client that you
want to destroy or AllTemporary.
The XKillClient function forces a close down of the client that created the
resource if a valid resource is specified. If the client has already terminated in
either RetainPermanent or RetainTemporary mode, all of the client's resources
are destroyed. If AllTemporary is specified, the resources of all clients that have
terminated in RetainTemporary are destroyed (see section 2.5). This permits
implementation of window manager facilities that aid debugging. A client can set its
close-down mode to RetainTemporary. If the client then crashes, its windows would
not be destroyed. The programmer can then inspect the application's window tree
and use the window manager to destroy the zombie windows.
171
Window and Session
Manager Functions
Timeout and interval are specified in seconds. A timeout of 0 disables the screen
saver (but an activated screen saver is not deactivated), and a timeout of −1 restores
the default. Other negative values generate a BadValue error. If the timeout value
is nonzero, XSetScreenSaver enables the screen saver. An interval of 0 disables
the random-pattern motion. If no input from devices (keyboard, mouse, and so on)
is generated for the specified number of timeout seconds once the screen saver is
enabled, the screen saver is activated.
For each screen, if blanking is preferred and the hardware supports video blanking,
the screen simply goes blank. Otherwise, if either exposures are allowed or the
screen can be regenerated without sending Expose events to clients, the screen
is tiled with the root window background tile randomly re-origined each interval
seconds. Otherwise, the screens' state do not change, and the screen saver is not
activated. The screen saver is deactivated, and all screen states are restored at the
next keyboard or pointer input or at the next call to XForceScreenSaver with mode
ScreenSaverReset.
If the server-dependent screen saver method supports periodic change, the interval
argument serves as a hint about how long the change period should be, and zero
hints that no periodic change should be made. Examples of ways to change the
screen include scrambling the colormap periodically, moving an icon image around
the screen periodically, or tiling the screen with the root window background tile,
randomly re-origined periodically.
XForceScreenSaver(display, mode);
172
Window and Session
Manager Functions
XActivateScreenSaver(display);
XResetScreenSaver(display);
X does not provide any protection on a per-window basis. If you find out
the resource ID of a resource, you can manipulate it. To provide some minimal
level of protection, however, connections are permitted only from machines you
trust. This is adequate on single-user workstations but obviously breaks down
on timesharing machines. Although provisions exist in the X protocol for proper
connection authentication, the lack of a standard authentication server leaves host-
level access control as the only common mechanism.
The initial set of hosts allowed to open connections typically consists of:
173
Window and Session
Manager Functions
If a host is not in the access control list when the access control mechanism is
enabled and if the host attempts to establish a connection, the server refuses the
connection. To change the access list, the client must reside on the same host as
the server and/or must have been granted permission in the initial authorization at
connection setup.
Servers also can implement other access control policies in addition to or in place
of this host access facility. For further information about other access control
implementations, see X Window System Protocol.
typedef struct {
int family; /* for example FamilyInternet */
int length; /* length of address, in bytes */
char *address; /* pointer to where to find the address */
} XHostAddress;
The family member specifies which protocol address family to use (for
example, TCP/IP or DECnet) and can be FamilyInternet, FamilyInternet6,
FamilyServerInterpreted, FamilyDECnet, or FamilyChaos. The length member
specifies the length of the address in bytes. The address member specifies a pointer
to the address.
For TCP/IP, the address should be in network byte order. For IP version 4 addresses,
the family should be FamilyInternet and the length should be 4 bytes. For IP version
6 addresses, the family should be FamilyInternet6 and the length should be 16 bytes.
For the DECnet family, the server performs no automatic swapping on the address
bytes. A Phase IV address is 2 bytes long. The first byte contains the least significant
8 bits of the node number. The second byte contains the most significant 2 bits of
the node number in the least significant 2 bits of the byte and the area in the most
significant 6 bits of the byte.
For the ServerInterpreted family, the length is ignored and the address member is
a pointer to a XServerInterpretedAddress structure, which contains:
typedef struct {
int typelength; /* length of type string, in bytes */
int valuelength; /* length of value string, in bytes */
char *type; /* pointer to where to find the type string */
174
Window and Session
Manager Functions
The type and value members point to strings representing the type and value of the
server interpreted entry. These strings may not be NULL-terminated so care should
be used when accessing them. The typelength and valuelength members specify the
length in byte of the type and value strings.
XAddHost(display, host);
The XAddHost function adds the specified host to the access control list for that
display. The server must be on the same host as the client issuing the command,
or a BadAccess error results.
The XAddHosts function adds each specified host to the access control list for that
display. The server must be on the same host as the client issuing the command,
or a BadAccess error results.
The XListHosts function returns the current access control list as well as whether
the use of the list at connection setup was enabled or disabled. XListHosts allows a
program to find out what machines can make connections. It also returns a pointer
to a list of host structures that were allocated by the function. When no longer
needed, this memory should be freed by calling XFree.
XRemoveHost(display, host);
175
Window and Session
Manager Functions
The XRemoveHost function removes the specified host from the access control list
for that display. The server must be on the same host as the client process, or a
BadAccess error results. If you remove your machine from the access list, you can
no longer connect to that server, and this operation cannot be reversed unless you
reset the server.
The XRemoveHosts function removes each specified host from the access control list
for that display. The X server must be on the same host as the client process, or a
BadAccess error results. If you remove your machine from the access list, you can
no longer connect to that server, and this operation cannot be reversed unless you
reset the server.
For these functions to execute successfully, the client application must reside on
the same host as the X server and/or have been given permission in the initial
authorization at connection setup.
XSetAccessControl(display, mode);
The XSetAccessControl function either enables or disables the use of the access
control list at each connection setup.
XEnableAccessControl(display);
176
Window and Session
Manager Functions
The XEnableAccessControl function enables the use of the access control list at
each connection setup.
XDisableAccessControl(display);
The XDisableAccessControl function disables the use of the access control list at
each connection setup.
177
Chapter 10. Events
A client application communicates with the X server through the connection you
establish with the XOpenDisplay function. A client application sends requests to
the X server over this connection. These requests are made by the Xlib functions
that are called in the client application. Many Xlib functions cause the X server to
generate events, and the user’s typing or moving the pointer can generate events
asynchronously. The X server returns events to the client on the same connection.
• Event types
• Event structures
• Event masks
• Event processing
Functions for handling events are dealt with in the next chapter.
Event Types
An event is data generated asynchronously by the X server as a result of some
device activity or as side effects of a request sent by an Xlib function. Device-related
events propagate from the source window to ancestor windows until some client
application has selected that event type or until the event is explicitly discarded.
The X server generally sends an event to a client application only if the client has
specifically asked to be informed of that event type, typically by setting the event-
mask attribute of the window. The mask can also be set when you create a window
or by changing the window's event-mask. You can also mask out events that would
propagate to ancestor windows by manipulating the do-not-propagate mask of the
window's attributes. However, MappingNotify events are always sent to all clients.
An event type describes a specific event generated by the X server. For each event
type, a corresponding constant name is defined in <X11/X.h>, which is used
when referring to an event type. The following table lists the event category and
its associated event type or types. The processing associated with these events is
discussed in section 10.5.
178
Events
Event Structures
For each event type, a corresponding structure is declared in <X11/Xlib.h>. All
the event structures have the following common members:
typedef struct {
int type;
unsigned long serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request */
Display *display; /* Display the event was read from */
Window window;
} XAnyEvent;
The type member is set to the event type constant name that uniquely identifies
it. For example, when the X server reports a GraphicsExpose event to a client
application, it sends an XGraphicsExposeEvent structure with the type member
set to GraphicsExpose. The display member is set to a pointer to the display the
event was read on. The send_event member is set to True if the event came from
a SendEvent protocol request. The serial member is set from the serial number
179
Events
reported in the protocol but expanded from the 16-bit least-significant bits to a full
32-bit value. The window member is set to the window that is most useful to toolkit
dispatchers.
The X server can send events at any time in the input stream. Xlib stores any events
received while waiting for a reply in an event queue for later use. Xlib also provides
functions that allow you to check events in the event queue (see section 11.3).
In addition to the individual structures declared for each event type, the XEvent
structure is a union of the individual structures declared for each event type.
Depending on the type, you should access members of each event by using the
XEvent union.
180
Events
An XEvent structure's first entry always is the type member, which is set to the
event type. The second member always is the serial number of the protocol request
that generated the event. The third member always is send_event, which is a Bool
that indicates if the event was sent by a different client. The fourth member always
is a display, which is the display that the event was read from. Except for keymap
events, the fifth member always is a window, which has been carefully selected to
be useful to toolkit dispatchers. To avoid breaking toolkits, the order of these first
five entries is not to change. Most events also contain a time member, which is the
time at which an event occurred. In addition, a pointer to the generic event must
be cast before it is used to access any other information in the structure.
Event Masks
Clients select event reporting of most events relative to a window. To do this, pass an
event mask to an Xlib event-handling function that takes an event_mask argument.
The bits of the event mask are defined in <X11/X.h>. Each bit in the event mask
maps to an event mask name, which describes the event or events you want the X
server to return to a client application.
Unless the client has specifically asked for them, most events are not reported
to clients when they are generated. Unless the client suppresses them by
setting graphics-exposures in the GC to False, GraphicsExpose and NoExpose
are reported by default as a result of XCopyPlane and XCopyArea. SelectionClear,
SelectionRequest, SelectionNotify, or ClientMessage cannot be masked. Selection-
related events are only sent to clients cooperating with selections (see section 4.5).
When the keyboard or pointer mapping is changed, MappingNotify is always sent
to clients.
The following table lists the event mask constants you can pass to the event_mask
argument and the circumstances in which you would want to specify the event mask:
181
Events
In other cases, one event mask constant can map to several event type constants. For
example, if you pass the event mask SubstructureNotifyMask, the X server can send
back CirculateNotify, ConfigureNotify, CreateNotify, DestroyNotify, GravityNotify,
MapNotify, ReparentNotify, or UnmapNotify events.
In another case, two event masks can map to one event type. For example, if you
pass either PointerMotionMask or ButtonMotionMask, the X server sends back a
MotionNotify event.
The following table lists the event mask, its associated event type or types, and the
structure name associated with the event type. Some of these structures actually
are typedefs to a generic structure that is shared between two event types. Note
that N.A. appears in columns for which the information is not applicable.
Button1MotionMask
Button2MotionMask
Button3MotionMask
Button4MotionMask
Button5MotionMask
ButtonPressMask ButtonPress XButtonPressedEvent XButtonEvent
182
Events
183
Events
The sections that follow describe the processing that occurs when you select the
different event masks. The sections are organized according to these processing
categories:
• Exposure events
The X server searches the ancestors of w from the root down, looking for a passive
grab to activate. If no matching passive grab on the button exists, the X server
automatically starts an active grab for the client receiving the event and sets the
last-pointer-grab time to the current server time. The effect is essentially equivalent
to an XGrabButton with these client passed arguments:
184
Events
Argument Value
w The event window
event_mask The client's selected pointer events on the event window
pointer_mode GrabModeAsync
keyboard_mode GrabModeAsync
owner_events True, if the client has selected OwnerGrabButtonMask on the
event window, otherwise False
confine_to None
cursor None
The active grab is automatically terminated when the logical state of the pointer has
all buttons released. Clients can modify the active grab by calling XUngrabPointer
and XChangeActivePointerGrab.
The generation of the logical changes lags the physical changes if device event
processing is frozen.
To receive MotionNotify events, set one or more of the following event masks bits
in the event-mask attribute of the window.
• Button1MotionMask - Button5MotionMask
• The client application receives MotionNotify events only when one or more of the
specified buttons is pressed.
• ButtonMotionMask
• The client application receives MotionNotify events only when at least one button
is pressed.
185
Events
• PointerMotionMask
• PointerMotionHintMask
The source of the event is the viewable window that the pointer is in. The window
used by the X server to report these events depends on the window's position in the
window hierarchy and whether any intervening window prohibits the generation of
these events. Starting with the source window, the X server searches up the window
hierarchy until it locates the first window specified by a client as having an interest
in these events. If one of the intervening windows has its do-not-propagate-mask set
to prohibit generation of the event type, the events of those types will be suppressed.
Clients can modify the actual window used for reporting by performing active grabs
and, in the case of keyboard events, by using the focus window.
typedef struct {
int type; /* ButtonPress or ButtonRelease */
unsigned long serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request
Display *display; /* Display the event was read from */
Window window; /* ``event'' window it is reported relative to
Window root; /* root window that the event occurred on */
Window subwindow; /* child window */
Time time; /* milliseconds */
int x, y; /* pointer x, y coordinates in event window */
int x_root, y_root; /* coordinates relative to root */
unsigned int state; /* key or button mask */
unsigned int button; /* detail */
Bool same_screen; /* same screen flag */
} XButtonEvent;
typedef XButtonEvent XButtonPressedEvent;
typedef XButtonEvent XButtonReleasedEvent;
typedef struct {
int type; /* KeyPress or KeyRelease */
unsigned long serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request
Display *display; /* Display the event was read from */
Window window; /* ``event'' window it is reported relative to
Window root; /* root window that the event occurred on */
Window subwindow; /* child window */
Time time; /* milliseconds */
186
Events
typedef struct {
int type; /* MotionNotify */
unsigned long serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent reques
Display *display; /* Display the event was read from */
Window window; /* ``event'' window reported relative to */
Window root; /* root window that the event occurred on */
Window subwindow; /* child window */
Time time; /* milliseconds */
int x, y; /* pointer x, y coordinates in event window
int x_root, y_root; /* coordinates relative to root */
unsigned int state; /* key or button mask */
char is_hint; /* detail */
Bool same_screen; /* same screen flag */
} XMotionEvent;
typedef XMotionEvent XPointerMovedEvent;
These structures have the following common members: window, root, subwindow,
time, x, y, x_root, y_root, state, and same_screen. The window member is set to the
window on which the event was generated and is referred to as the event window.
As long as the conditions previously discussed are met, this is the window used by
the X server to report the event. The root member is set to the source window's root
window. The x_root and y_root members are set to the pointer's coordinates relative
to the root window's origin at the time of the event.
The same_screen member is set to indicate whether the event window is on the
same screen as the root window and can be either True or False. If True, the event
and root windows are on the same screen. If False, the event and root windows are
not on the same screen.
If the source window is an inferior of the event window, the subwindow member of
the structure is set to the child of the event window that is the source window or
the child of the event window that is an ancestor of the source window. Otherwise,
the X server sets the subwindow member to None. The time member is set to the
time when the event was generated and is expressed in milliseconds.
If the event window is on the same screen as the root window, the x and y members
are set to the coordinates relative to the event window's origin. Otherwise, these
members are set to zero.
The state member is set to indicate the logical state of the pointer buttons
and modifier keys just prior to the event, which is the bitwise inclusive OR of
one or more of the button or modifier key masks: Button1Mask, Button2Mask,
Button3Mask, Button4Mask, Button5Mask, ShiftMask, LockMask, ControlMask,
Mod1Mask, Mod2Mask, Mod3Mask, Mod4Mask, and Mod5Mask.
187
Events
Each of these structures also has a member that indicates the detail. For the
XKeyPressedEvent and XKeyReleasedEvent structures, this member is called a
keycode. It is set to a number that represents a physical key on the keyboard. The
keycode is an arbitrary representation for any key on the keyboard (see sections
12.7 and 16.1).
Some of the symbols mentioned in this section have fixed values, as follows:
Symbol Value
Button1MotionMask (1L<<8)
Button2MotionMask (1L<<9)
Button3MotionMask (1L<<10)
Button4MotionMask (1L<<11)
Button5MotionMask (1L<<12)
Button1Mask (1<<8)
Button2Mask (1<<9)
Button3Mask (1<<10)
Button4Mask (1<<11)
Button5Mask (1<<12)
ShiftMask (1<<0)
LockMask (1<<1)
ControlMask (1<<2)
Mod1Mask (1<<3)
Mod2Mask (1<<4)
Mod3Mask (1<<5)
Mod4Mask (1<<6)
Mod5Mask (1<<7)
Button1 1
Button2 2
Button3 3
Button4 4
Button5 5
188
Events
CirculateNotify) caused by that change; however, the X protocol does not constrain
the ordering of EnterNotify and LeaveNotify events with respect to FocusOut,
VisibilityNotify, and Expose events.
This contrasts with MotionNotify events, which are also generated when the pointer
moves but only when the pointer motion begins and ends in a single window.
An EnterNotify or LeaveNotify event also can be generated when some client
application calls XGrabPointer and XUngrabPointer.
typedef struct {
int type; /* EnterNotify or LeaveNotify */
unsigned long serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request */
Display *display; /* Display the event was read from */
Window window; /* ``event'' window reported relative to */
Window root; /* root window that the event occurred on */
Window subwindow; /* child window */
Time time; /* milliseconds */
int x, y; /* pointer x, y coordinates in event window */
int x_root, y_root; /* coordinates relative to root */
int mode; /* NotifyNormal, NotifyGrab, NotifyUngrab */
int detail;
/*
* NotifyAncestor, NotifyVirtual, NotifyInferior,
* NotifyNonlinear,NotifyNonlinearVirtual
*/
Bool same_screen; /* same screen flag */
Bool focus; /* boolean focus */
unsigned int state; /* key or button mask */
} XCrossingEvent;
typedef XCrossingEvent XEnterWindowEvent;
typedef XCrossingEvent XLeaveWindowEvent;
The window member is set to the window on which the EnterNotify or LeaveNotify
event was generated and is referred to as the event window. This is the window
used by the X server to report the event, and is relative to the root window on which
the event occurred. The root member is set to the root window of the screen on
which the event occurred.
For a LeaveNotify event, if a child of the event window contains the initial position of
the pointer, the subwindow component is set to that child. Otherwise, the X server
sets the subwindow member to None. For an EnterNotify event, if a child of the
event window contains the final pointer position, the subwindow component is set
to that child or None.
The time member is set to the time when the event was generated and is expressed
in milliseconds. The x and y members are set to the coordinates of the pointer
189
Events
position in the event window. This position is always the pointer's final position, not
its initial position. If the event window is on the same screen as the root window, x
and y are the pointer coordinates relative to the event window's origin. Otherwise,
x and y are set to zero. The x_root and y_root members are set to the pointer's
coordinates relative to the root window's origin at the time of the event.
The same_screen member is set to indicate whether the event window is on the
same screen as the root window and can be either True or False. If True, the event
and root windows are on the same screen. If False, the event and root windows are
not on the same screen.
The focus member is set to indicate whether the event window is the focus window
or an inferior of the focus window. The X server can set this member to either True
or False. If True, the event window is the focus window or an inferior of the focus
window. If False, the event window is not the focus window or an inferior of the
focus window.
The state member is set to indicate the state of the pointer buttons and modifier
keys just prior to the event. The X server can set this member to the bitwise
inclusive OR of one or more of the button or modifier key masks: Button1Mask,
Button2Mask, Button3Mask, Button4Mask, Button5Mask, ShiftMask, LockMask,
ControlMask, Mod1Mask, Mod2Mask, Mod3Mask, Mod4Mask, Mod5Mask.
The mode member is set to indicate whether the events are normal events,
pseudo-motion events when a grab activates, or pseudo-motion events when a grab
deactivates. The X server can set this member to NotifyNormal, NotifyGrab, or
NotifyUngrab.
The detail member is set to indicate the notify detail and can be NotifyAncestor,
NotifyVirtual, NotifyInferior, NotifyNonlinear, or NotifyNonlinearVirtual.
190
Events
• When the pointer moves from window A to window B and window C is their least
common ancestor, the X server does the following:
• When the pointer moves from window A to window B on different screens, the X
server does the following:
• When a pointer grab activates after any initial warp into a confine_to window and
before generating any actual ButtonPress event that activates the grab, G is the
grab_window for the grab, and P is the window the pointer is in, the X server does
the following:
191
Events
• It generates EnterNotify and LeaveNotify events (see section 10.6.1) with the
mode members of the XEnterWindowEvent and XLeaveWindowEvent structures
set to NotifyGrab. These events are generated as if the pointer were to suddenly
warp from its current position in P to some position in G. However, the pointer
does not warp, and the X server uses the pointer position as both the initial and
final positions for the events.
• When a pointer grab deactivates after generating any actual ButtonRelease event
that deactivates the grab, G is the grab_window for the grab, and P is the window
the pointer is in, the X server does the following:
• It generates EnterNotify and LeaveNotify events (see section 10.6.1) with the
mode members of the XEnterWindowEvent and XLeaveWindowEvent structures
set to NotifyUngrab. These events are generated as if the pointer were to suddenly
warp from some position in G to its current position in P. However, the pointer
does not warp, and the X server uses the current pointer position as both the
initial and final positions for the events.
To receive FocusIn or FocusOut events, set the FocusChangeMask bit in the event-
mask attribute of the window.
typedef struct {
int type; /* FocusIn or FocusOut */
unsigned long serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request */
Display *display; /* Display the event was read from */
Window window; /* window of event */
int mode; /* NotifyNormal, NotifyGrab, NotifyUngrab */
int detail;
/*
* NotifyAncestor, NotifyVirtual, NotifyInferior,
* NotifyNonlinear,NotifyNonlinearVirtual, NotifyPointer,
* NotifyPointerRoot, NotifyDetailNone
*/
} XFocusChangeEvent;
typedef XFocusChangeEvent XFocusInEvent;
typedef XFocusChangeEvent XFocusOutEvent;
The window member is set to the window on which the FocusIn or FocusOut event
was generated. This is the window used by the X server to report the event. The
192
Events
mode member is set to indicate whether the focus events are normal focus events,
focus events while grabbed, focus events when a grab activates, or focus events
when a grab deactivates. The X server can set the mode member to NotifyNormal,
NotifyWhileGrabbed, NotifyGrab, or NotifyUngrab.
All FocusOut events caused by a window unmap are generated after any
UnmapNotify event; however, the X protocol does not constrain the ordering
of FocusOut events with respect to generated EnterNotify, LeaveNotify,
VisibilityNotify, and Expose events.
Depending on the event mode, the detail member is set to indicate the notify
detail and can be NotifyAncestor, NotifyVirtual, NotifyInferior, NotifyNonlinear,
NotifyNonlinearVirtual, NotifyPointer, NotifyPointerRoot, or NotifyDetailNone.
• When the focus moves from window A to window B, A is an inferior of B, and the
pointer is in window P, the X server does the following:
• When the focus moves from window A to window B, B is an inferior of A, and the
pointer is in window P, the X server does the following:
193
Events
• When the focus moves from window A to window B, window C is their least
common ancestor, and the pointer is in window P, the X server does the following:
• It generates a FocusIn event on each window between C and B, exclusive, with the
detail member of each XFocusInEvent structure set to NotifyNonlinearVirtual.
• When the focus moves from window A to window B on different screens and the
pointer is in window P, the X server does the following:
• When the focus moves from window A to PointerRoot (events sent to the window
under the pointer) or None (discard), and the pointer is in window P, the X server
does the following:
194
Events
• It generates a FocusIn event on the root window of all screens, with the
detail member of each XFocusInEvent structure set to NotifyPointerRoot (or
NotifyDetailNone).
• If the new focus is PointerRoot, it generates a FocusIn event on each window from
window P's root down to and including window P, with the detail member of each
XFocusInEvent structure set to NotifyPointer.
• When the focus moves from PointerRoot (events sent to the window under the
pointer) or None to window A, and the pointer is in window P, the X server does
the following:
• It generates a FocusOut event on all root windows, with the detail member of each
XFocusOutEvent structure set to NotifyPointerRoot (or NotifyDetailNone).
• When the focus moves from PointerRoot (events sent to the window under the
pointer) to None (or vice versa), and the pointer is in window P, the X server does
the following:
• It generates a FocusOut event on all root windows, with the detail member of each
XFocusOutEvent structure set to either NotifyPointerRoot or NotifyDetailNone.
• It generates a FocusIn event on all root windows, with the detail member of each
XFocusInEvent structure set to NotifyDetailNone or NotifyPointerRoot.
• If the new focus is PointerRoot, it generates a FocusIn event on each window from
window P's root down to and including window P, with the detail member of each
XFocusInEvent structure set to NotifyPointer.
195
Events
• When a keyboard grab activates before generating any actual KeyPress event that
activates the grab, G is the grab_window, and F is the current focus, the X server
does the following:
• It generates FocusIn and FocusOut events, with the mode members of the
XFocusInEvent and XFocusOutEvent structures set to NotifyGrab. These events
are generated as if the focus were to change from F to G.
• When a keyboard grab deactivates after generating any actual KeyRelease event
that deactivates the grab, G is the grab_window, and F is the current focus, the
X server does the following:
• It generates FocusIn and FocusOut events, with the mode members of the
XFocusInEvent and XFocusOutEvent structures set to NotifyUngrab. These events
are generated as if the focus were to change from G to F.
The window member is not used but is present to aid some toolkits. The key_vector
member is set to the bit vector of the keyboard. Each bit set to 1 indicates that the
corresponding key is currently pressed. The vector is represented as 32 bytes. Byte
N (from 0) contains the bits for keys 8N to 8N + 7 with the least significant bit in
the byte representing key 8N.
196
Events
Exposure Events
The X protocol does not guarantee to preserve the contents of window regions when
the windows are obscured or reconfigured. Some implementations may preserve
the contents of windows. Other implementations are free to destroy the contents of
windows when exposed. X expects client applications to assume the responsibility
for restoring the contents of an exposed window region. (An exposed window region
describes a formerly obscured window whose region becomes visible.) Therefore,
the X server sends Expose events describing the window and the region of the
window that has been exposed. A naive client application usually redraws the entire
window. A more sophisticated client application redraws only the exposed region.
Expose Events
The X server can report Expose events to clients wanting information about when
the contents of window regions have been lost. The circumstances in which the
X server generates Expose events are not as definite as those for other events.
However, the X server never generates Expose events on windows whose class you
specified as InputOnly. The X server can generate Expose events when no valid
contents are available for regions of a window and either the regions are visible,
the regions are viewable and the server is (perhaps newly) maintaining backing
store on the window, or the window is not viewable but the server is (perhaps
newly) honoring the window's backing-store attribute of Always or WhenMapped.
The regions decompose into an (arbitrary) set of rectangles, and an Expose event
is generated for each rectangle. For any given window, the X server guarantees to
report contiguously all of the regions exposed by some action that causes Expose
events, such as raising a window.
To receive Expose events, set the ExposureMask bit in the event-mask attribute of
the window.
typedef struct {
int type; /* Expose */
unsigned long serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request */
Display *display; /* Display the event was read from */
Window window;
int x, y;
int width, height;
int count; /* if nonzero, at least this many more */
} XExposeEvent;
The window member is set to the exposed (damaged) window. The x and y members
are set to the coordinates relative to the window's origin and indicate the upper-left
corner of the rectangle. The width and height members are set to the size (extent)
of the rectangle. The count member is set to the number of Expose events that are
197
Events
to follow. If count is zero, no more Expose events follow for this window. However,
if count is nonzero, at least that number of Expose events (and possibly more)
follow for this window. Simple applications that do not want to optimize redisplay
by distinguishing between subareas of its window can just ignore all Expose events
with nonzero counts and perform full redisplays on events with zero counts.
The X server generates a NoExpose event whenever a graphics request that might
produce a GraphicsExpose event does not produce any. In other words, the client is
really asking for a GraphicsExpose event but instead receives a NoExpose event.
To receive GraphicsExpose or NoExpose events, you must first set the graphics-
exposure attribute of the graphics context to True. You also can set the graphics-
expose attribute when creating a graphics context using XCreateGC or by calling
XSetGraphicsExposures.
typedef struct {
int type; /* GraphicsExpose */
unsigned long serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request *
Display *display; /* Display the event was read from */
Drawable drawable;
int x, y;
int width, height;
int count; /* if nonzero, at least this many more */
int major_code; /* core is CopyArea or CopyPlane */
int minor_code; /* not defined in the core */
} XGraphicsExposeEvent;
typedef struct {
int type; /* NoExpose */
unsigned long serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request */
Display *display; /* Display the event was read from */
198
Events
Drawable drawable;
int major_code; /* core is CopyArea or CopyPlane */
int minor_code; /* not defined in the core */
} XNoExposeEvent;
• CirculateNotify events
• ConfigureNotify events
• CreateNotify events
• DestroyNotify events
• GravityNotify events
• MapNotify events
• MappingNotify events
• ReparentNotify events
• UnmapNotify events
• VisibilityNotify events
CirculateNotify Events
The X server can report CirculateNotify events to clients wanting information
about when a window changes its position in the stack. The X server generates
this event type whenever a window is actually restacked as a result of a
199
Events
typedef struct {
int type; /* CirculateNotify */
unsigned long serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request */
Display *display; /* Display the event was read from */
Window event;
Window window;
int place; /* PlaceOnTop, PlaceOnBottom */
} XCirculateEvent;
The event member is set either to the restacked window or to its parent, depending
on whether StructureNotify or SubstructureNotify was selected. The window
member is set to the window that was restacked. The place member is set
to the window's position after the restack occurs and is either PlaceOnTop or
PlaceOnBottom. If it is PlaceOnTop, the window is now on top of all siblings. If it is
PlaceOnBottom, the window is now below all siblings.
ConfigureNotify Events
The X server can report ConfigureNotify events to clients wanting information
about actual changes to a window's state, such as size, position, border, and
stacking order. The X server generates this event type whenever one of the following
configure window requests made by a client application actually completes:
• A window is mapped and its position in the stacking order is changed by calling
XMapRaised.
200
Events
typedef struct {
int type; /* ConfigureNotify */
unsigned long serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request */
Display *display; /* Display the event was read from */
Window event;
Window window;
int x, y;
int width, height;
int border_width;
Window above;
Bool override_redirect;
} XConfigureEvent;
The event member is set either to the reconfigured window or to its parent,
depending on whether StructureNotify or SubstructureNotify was selected. The
window member is set to the window whose size, position, border, and/or stacking
order was changed.
The x and y members are set to the coordinates relative to the parent window's
origin and indicate the position of the upper-left outside corner of the window. The
width and height members are set to the inside size of the window, not including
the border. The border_width member is set to the width of the window's border,
in pixels.
The above member is set to the sibling window and is used for stacking operations.
If the X server sets this member to None, the window whose state was changed is
on the bottom of the stack with respect to sibling windows. However, if this member
is set to a sibling window, the window whose state was changed is placed on top
of this sibling window.
CreateNotify Events
The X server can report CreateNotify events to clients wanting information
about creation of windows. The X server generates this event whenever a client
application creates a window by calling XCreateWindow or XCreateSimpleWindow.
201
Events
typedef struct {
int type; /* CreateNotify */
unsigned long serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent reques
Display *display; /* Display the event was read from */
Window parent; /* parent of the window */
Window window; /* window id of window created */
int x, y; /* window location */
int width, height; /* size of window */
int border_width; /* border width */
Bool override_redirect; /* creation should be overridden */
} XCreateWindowEvent;
The parent member is set to the created window's parent. The window member
specifies the created window. The x and y members are set to the created window's
coordinates relative to the parent window's origin and indicate the position of the
upper-left outside corner of the created window. The width and height members
are set to the inside size of the created window (not including the border) and
are always nonzero. The border_width member is set to the width of the created
window's border, in pixels. The override_redirect member is set to the override-
redirect attribute of the window. Window manager clients normally should ignore
this window if the override_redirect member is True.
DestroyNotify Events
The X server can report DestroyNotify events to clients wanting information about
which windows are destroyed. The X server generates this event whenever a client
application destroys a window by calling XDestroyWindow or XDestroySubwindows.
The ordering of the DestroyNotify events is such that for any given window,
DestroyNotify is generated on all inferiors of the window before being generated
on the window itself. The X protocol does not constrain the ordering among siblings
and across subhierarchies.
typedef struct {
int type; /* DestroyNotify */
unsigned long serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request */
202
Events
The event member is set either to the destroyed window or to its parent, depending
on whether StructureNotify or SubstructureNotify was selected. The window
member is set to the window that is destroyed.
GravityNotify Events
The X server can report GravityNotify events to clients wanting information about
when a window is moved because of a change in the size of its parent. The X server
generates this event whenever a client application actually moves a child window
as a result of resizing its parent by calling XConfigureWindow, XMoveResizeWindow,
or XResizeWindow.
typedef struct {
int type; /* GravityNotify */
unsigned long serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request */
Display *display; /* Display the event was read from */
Window event;
Window window;
int x, y;
} XGravityEvent;
The event member is set either to the window that was moved or to its parent,
depending on whether StructureNotify or SubstructureNotify was selected. The
window member is set to the child window that was moved. The x and y members
are set to the coordinates relative to the new parent window's origin and indicate
the position of the upper-left outside corner of the window.
MapNotify Events
The X server can report MapNotify events to clients wanting information about
which windows are mapped. The X server generates this event type whenever a
client application changes the window's state from unmapped to mapped by calling
XMapWindow, XMapRaised, XMapSubwindows, XReparentWindow, or as a result of save-
set processing.
203
Events
attribute of the parent window (in which case, mapping any child generates an
event).
typedef struct {
int type; /* MapNotify */
unsigned long serial; /* # of last request processed by server
Bool send_event; /* true if this came from a SendEvent req
Display *display; /* Display the event was read from */
Window event;
Window window;
Bool override_redirect; /* boolean, is override set... */
} XMapEvent;
The event member is set either to the window that was mapped or to its parent,
depending on whether StructureNotify or SubstructureNotify was selected. The
window member is set to the window that was mapped. The override_redirect
member is set to the override-redirect attribute of the window. Window manager
clients normally should ignore this window if the override-redirect attribute is True,
because these events usually are generated from pop-ups, which override structure
control.
MappingNotify Events
The X server reports MappingNotify events to all clients. There is no mechanism to
express disinterest in this event. The X server generates this event type whenever
a client application successfully calls:
typedef struct {
int type; /* MappingNotify */
unsigned long serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request */
Display *display; /* Display the event was read from */
Window window; /* unused */
int request; /* one of MappingModifier, MappingKeyboard,
MappingPointer */
204
Events
The request member is set to indicate the kind of mapping change that occurred
and can be MappingModifier, MappingKeyboard, or MappingPointer. If it is
MappingModifier, the modifier mapping was changed. If it is MappingKeyboard, the
keyboard mapping was changed. If it is MappingPointer, the pointer button mapping
was changed. The first_keycode and count members are set only if the request
member was set to MappingKeyboard. The number in first_keycode represents the
first number in the range of the altered mapping, and count represents the number
of keycodes altered.
To update the client application's knowledge of the keyboard, you should call
XRefreshKeyboardMapping.
ReparentNotify Events
The X server can report ReparentNotify events to clients wanting information about
changing a window's parent. The X server generates this event whenever a client
application calls XReparentWindow and the window is actually reparented.
typedef struct {
int type; /* ReparentNotify */
unsigned long serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request */
Display *display; /* Display the event was read from */
Window event;
Window window;
Window parent;
int x, y;
Bool override_redirect;
} XReparentEvent;
The event member is set either to the reparented window or to the old or the
new parent, depending on whether StructureNotify or SubstructureNotify was
selected. The window member is set to the window that was reparented. The parent
member is set to the new parent window. The x and y members are set to the
reparented window's coordinates relative to the new parent window's origin and
define the upper-left outer corner of the reparented window. The override_redirect
member is set to the override-redirect attribute of the window specified by the
window member. Window manager clients normally should ignore this window if
the override_redirect member is True.
205
Events
UnmapNotify Events
The X server can report UnmapNotify events to clients wanting information about
which windows are unmapped. The X server generates this event type whenever a
client application changes the window's state from mapped to unmapped.
typedef struct {
int type; /* UnmapNotify */
unsigned long serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request */
Display *display; /* Display the event was read from */
Window event;
Window window;
Bool from_configure;
} XUnmapEvent;
The event member is set either to the unmapped window or to its parent, depending
on whether StructureNotify or SubstructureNotify was selected. This is the
window used by the X server to report the event. The window member is set to the
window that was unmapped. The from_configure member is set to True if the event
was generated as a result of a resizing of the window's parent when the window
itself had a win_gravity of UnmapGravity.
VisibilityNotify Events
The X server can report VisibilityNotify events to clients wanting any change in the
visibility of the specified window. A region of a window is visible if someone looking
at the screen can actually see it. The X server generates this event whenever the
visibility changes state. However, this event is never generated for windows whose
class is InputOnly.
206
Events
typedef struct {
int type; /* VisibilityNotify */
unsigned long serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request */
Display *display; /* Display the event was read from */
Window window;
int state;
} XVisibilityEvent;
The window member is set to the window whose visibility state changes. The state
member is set to the state of the window's visibility and can be VisibilityUnobscured,
VisibilityPartiallyObscured, or VisibilityFullyObscured. The X server ignores all of
a window's subwindows when determining the visibility state of the window and
processes VisibilityNotify events according to the following:
• When the window changes state from partially obscured, fully obscured, or
not viewable to viewable and completely unobscured, the X server generates
the event with the state member of the XVisibilityEvent structure set to
VisibilityUnobscured.
• When the window changes state from viewable and completely unobscured
or not viewable to viewable and partially obscured, the X server generates
the event with the state member of the XVisibilityEvent structure set to
VisibilityPartiallyObscured.
• When the window changes state from viewable and completely unobscured,
viewable and partially obscured, or not viewable to viewable and fully obscured,
the X server generates the event with the state member of the XVisibilityEvent
structure set to VisibilityFullyObscured.
• CirculateRequest events
• ConfigureRequest events
• MapRequest events
• ResizeRequest events
CirculateRequest Events
The X server can report CirculateRequest events to clients wanting
information about when another client initiates a circulate window request
on a specified window. The X server generates this event type whenever a
client initiates a circulate window request on a window and a subwindow
actually needs to be restacked. The client initiates a circulate window request
207
Events
typedef struct {
int type; /* CirculateRequest */
unsigned long serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request */
Display *display; /* Display the event was read from */
Window parent;
Window window;
int place; /* PlaceOnTop, PlaceOnBottom */
} XCirculateRequestEvent;
The parent member is set to the parent window. The window member is set to the
subwindow to be restacked. The place member is set to what the new position in
the stacking order should be and is either PlaceOnTop or PlaceOnBottom. If it is
PlaceOnTop, the subwindow should be on top of all siblings. If it is PlaceOnBottom,
the subwindow should be below all siblings.
ConfigureRequest Events
The X server can report ConfigureRequest events to clients wanting
information about when a different client initiates a configure window request
on any child of a specified window. The configure window request attempts
to reconfigure a window's size, position, border, and stacking order. The X
server generates this event whenever a different client initiates a configure
window request on a window by calling XConfigureWindow, XLowerWindow,
XRaiseWindow, XMapRaised, XMoveResizeWindow, XMoveWindow, XResizeWindow,
XRestackWindows, or XSetWindowBorderWidth.
208
Events
typedef struct {
int type; /* ConfigureRequest */
unsigned long serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request */
Display *display; /* Display the event was read from */
Window parent;
Window window;
int x, y;
int width, height;
int border_width;
Window above;
int detail; /* Above, Below, TopIf, BottomIf, Opposite */
unsigned long value_mask;
} XConfigureRequestEvent;
The parent member is set to the parent window. The window member is set to
the window whose size, position, border width, and/or stacking order is to be
reconfigured. The value_mask member indicates which components were specified
in the ConfigureWindow protocol request. The corresponding values are reported as
given in the request. The remaining values are filled in from the current geometry
of the window, except in the case of above (sibling) and detail (stack-mode), which
are reported as None and Above, respectively, if they are not given in the request.
MapRequest Events
The X server can report MapRequest events to clients wanting information about
a different client's desire to map windows. A window is considered mapped when
a map window request completes. The X server generates this event whenever a
different client initiates a map window request on an unmapped window whose
override_redirect member is set to False. Clients initiate map window requests by
calling XMapWindow, XMapRaised, or XMapSubwindows.
209
Events
typedef struct {
int type; /* MapRequest */
unsigned long serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request */
Display *display; /* Display the event was read from */
Window parent;
Window window;
} XMapRequestEvent;
The parent member is set to the parent window. The window member is set to the
window to be mapped.
ResizeRequest Events
The X server can report ResizeRequest events to clients wanting information about
another client's attempts to change the size of a window. The X server generates
this event whenever some other client attempts to change the size of the specified
window by calling XConfigureWindow, XResizeWindow, or XMoveResizeWindow.
typedef struct {
int type; /* ResizeRequest */
unsigned long serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request */
Display *display; /* Display the event was read from */
Window window;
int width, height;
} XResizeRequestEvent;
The window member is set to the window whose size another client attempted to
change. The width and height members are set to the inside size of the window,
excluding the border.
210
Events
typedef struct {
int type; /* ColormapNotify */
unsigned long serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request */
Display *display; /* Display the event was read from */
Window window;
Colormap colormap; /* colormap or None */
Bool new;
int state; /* ColormapInstalled, ColormapUninstalled */
} XColormapEvent;
The window member is set to the window whose associated colormap is changed,
installed, or uninstalled. For a colormap that is changed, installed, or uninstalled,
the colormap member is set to the colormap associated with the window. For a
colormap that is changed by a call to XFreeColormap, the colormap member is set
to None. The new member is set to indicate whether the colormap for the specified
window was changed or installed or uninstalled and can be True or False. If it
is True, the colormap was changed. If it is False, the colormap was installed or
uninstalled. The state member is always set to indicate whether the colormap is
installed or uninstalled and can be ColormapInstalled or ColormapUninstalled.
• ClientMessage events
• PropertyNotify events
• SelectionClear events
• SelectionNotify events
• SelectionRequest events
ClientMessage Events
The X server generates ClientMessage events only when a client calls the function
XSendEvent.
211
Events
typedef struct {
int type; /* ClientMessage */
unsigned long serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request */
Display *display; /* Display the event was read from */
Window window;
Atom message_type;
int format;
union {
char b[20];
short s[10];
long l[5];
} data;
} XClientMessageEvent;
The message_type member is set to an atom that indicates how the data should
be interpreted by the receiving client. The format member is set to 8, 16, or 32
and specifies whether the data should be viewed as a list of bytes, shorts, or longs.
The data member is a union that contains the members b, s, and l. The b, s, and
l members represent data of twenty 8-bit values, ten 16-bit values, and five 32-
bit values. Particular message types might not make use of all these values. The X
server places no interpretation on the values in the window, message_type, or data
members.
PropertyNotify Events
The X server can report PropertyNotify events to clients wanting information about
property changes for a specified window.
typedef struct {
int type; /* PropertyNotify */
unsigned long serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request */
Display *display; /* Display the event was read from */
Window window;
Atom atom;
Time time;
int state; /* PropertyNewValue or PropertyDelete */
} XPropertyEvent;
The window member is set to the window whose associated property was changed.
The atom member is set to the property's atom and indicates which property was
changed or desired. The time member is set to the server time when the property
was changed. The state member is set to indicate whether the property was changed
212
Events
SelectionClear Events
The X server reports SelectionClear events to the client losing ownership of
a selection. The X server generates this event type when another client asserts
ownership of the selection by calling XSetSelectionOwner.
typedef struct {
int type; /* SelectionClear */
unsigned long serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request */
Display *display; /* Display the event was read from */
Window window;
Atom selection;
Time time;
} XSelectionClearEvent;
The selection member is set to the selection atom. The time member is set to the
last change time recorded for the selection. The window member is the window
that was specified by the current owner (the owner losing the selection) in its
XSetSelectionOwner call.
SelectionRequest Events
The X server reports SelectionRequest events to the owner of a selection. The X
server generates this event whenever a client requests a selection conversion by
calling XConvertSelection for the owned selection.
typedef struct {
int type; /* SelectionRequest */
unsigned long serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request */
Display *display; /* Display the event was read from */
Window owner;
213
Events
Window requestor;
Atom selection;
Atom target;
Atom property;
Time time;
} XSelectionRequestEvent;
The owner member is set to the window that was specified by the current owner in
its XSetSelectionOwner call. The requestor member is set to the window requesting
the selection. The selection member is set to the atom that names the selection. For
example, PRIMARY is used to indicate the primary selection. The target member
is set to the atom that indicates the type the selection is desired in. The property
member can be a property name or None. The time member is set to the timestamp
or CurrentTime value from the ConvertSelection request.
The owner should convert the selection based on the specified target type and
send a SelectionNotify event back to the requestor. A complete specification for
using selections is given in the X Consortium standard Inter-Client Communication
Conventions Manual.
SelectionNotify Events
This event is generated by the X server in response to a ConvertSelection protocol
request when there is no owner for the selection. When there is an owner, it should
be generated by the owner of the selection by using XSendEvent. The owner of a
selection should send this event to a requestor when a selection has been converted
and stored as a property or when a selection conversion could not be performed
(which is indicated by setting the property member to None).
typedef struct {
int type; /* SelectionNotify */
unsigned long serial; /* # of last request processed by server */
Bool send_event; /* true if this came from a SendEvent request */
Display *display; /* Display the event was read from */
Window requestor;
Atom selection;
Atom target;
Atom property; /* atom or None */
Time time;
} XSelectionEvent;
The requestor member is set to the window associated with the requestor of the
selection. The selection member is set to the atom that indicates the selection. For
214
Events
example, PRIMARY is used for the primary selection. The target member is set to the
atom that indicates the converted type. For example, PIXMAP is used for a pixmap.
The property member is set to the atom that indicates which property the result
was stored on. If the conversion failed, the property member is set to None. The
time member is set to the time the conversion took place and can be a timestamp
or CurrentTime.
215
Chapter 11. Event Handling Functions
This chapter discusses the Xlib functions you can use to:
• Select events
Note
Some toolkits use their own event-handling functions and do not allow you
to interchange these event-handling functions with those in Xlib. For further
information, see the documentation supplied with the toolkit.
Most applications simply are event loops: they wait for an event, decide what to
do with it, execute some amount of code that results in changes to the display, and
then wait for the next event.
Selecting Events
There are two ways to select the events you want reported to your client application.
One way is to set the event_mask member of the XSetWindowAttributes structure
when you call XCreateWindow and XChangeWindowAttributes. Another way is to
use XSelectInput.
XSelectInput(display, w, event_mask);
The XSelectInput function requests that the X server report the events associated
with the specified event mask. Initially, X will not report any of these events.
Events are reported relative to a window. If a window is not interested in a device
event, it usually propagates to the closest ancestor that is interested, unless the
do_not_propagate mask prohibits it.
Setting the event-mask attribute of a window overrides any previous call for the
same window but not for other clients. Multiple clients can select for the same
events on the same window with the following restrictions:
• Multiple clients can select events on the same window because their event masks
are disjoint. When the X server generates an event, it reports it to all interested
clients.
216
Event Handling Functions
• Only one client at a time can select a ResizeRequest event, which is associated
with the event mask ResizeRedirectMask.
• Only one client at a time can select a ButtonPress event, which is associated with
the event mask ButtonPressMask.
XFlush(display);
The XFlush function flushes the output buffer. Most client applications need not use
this function because the output buffer is automatically flushed as needed by calls
to XPending, XNextEvent, and XWindowEvent. Events generated by the server may
be enqueued into the library's event queue.
To flush the output buffer and then wait until all requests have been processed, use
XSync.
XSync(display, discard);
The XSync function flushes the output buffer and then waits until all requests have
been received and processed by the X server. Any errors generated must be handled
by the error handler. For each protocol error received by Xlib, XSync calls the client
application's error handling routine (see section 11.8.2). Any events generated by
the server are enqueued into the library's event queue.
Finally, if you passed False, XSync does not discard the events in the queue. If you
passed True, XSync discards all events in the queue, including those events that
were on the queue before XSync was called. Client applications seldom need to call
XSync.
217
Event Handling Functions
XEventsQueued always returns immediately without I/O if there are events already
in the queue. XEventsQueued with mode QueuedAfterFlush is identical in behavior
to XPending. XEventsQueued with mode QueuedAlready is identical to the XQLength
function.
int XPending(display);
The XPending function returns the number of events that have been received from
the X server but have not been removed from the event queue. XPending is identical
to XEventsQueued with the mode QueuedAfterFlush specified.
• Obtain events that match the event mask or the arbitrary predicate procedures
that you provide
XNextEvent(display, event_return);
218
Event Handling Functions
The XNextEvent function copies the first event from the event queue into the
specified XEvent structure and then removes it from the queue. If the event queue
is empty, XNextEvent flushes the output buffer and blocks until an event is received.
XPeekEvent(display, event_return);
The XPeekEvent function returns the first event from the event queue, but it does
not remove the event from the queue. If the queue is empty, XPeekEvent flushes the
output buffer and blocks until an event is received. It then copies the event into the
client-supplied XEvent structure without removing it from the event queue.
The predicate procedure is called once for each event in the queue until it finds a
match. After finding a match, the predicate procedure must return True. If it did
not find a match, it must return False.
To check the event queue for a matching event and, if found, remove the event from
the queue, use XIfEvent.
219
Event Handling Functions
The XIfEvent function completes only when the specified predicate procedure
returns True for an event, which indicates an event in the queue matches. XIfEvent
flushes the output buffer if it blocks waiting for additional events. XIfEvent removes
the matching event from the queue and copies the structure into the client-supplied
XEvent structure.
To check the event queue for a matching event without blocking, use
XCheckIfEvent.
When the predicate procedure finds a match, XCheckIfEvent copies the matched
event into the client-supplied XEvent structure and returns True. (This event
is removed from the queue.) If the predicate procedure finds no match,
XCheckIfEvent returns False, and the output buffer will have been flushed. All
earlier events stored in the queue are not discarded.
To check the event queue for a matching event without removing the event from
the queue, use XPeekIfEvent.
The XPeekIfEvent function returns only when the specified predicate procedure
returns True for an event. After the predicate procedure finds a match,
XPeekIfEvent copies the matched event into the client-supplied XEvent structure
without removing the event from the queue. XPeekIfEvent flushes the output buffer
if it blocks waiting for additional events.
220
Event Handling Functions
To remove the next event that matches both a window and an event mask, use
XWindowEvent.
The XWindowEvent function searches the event queue for an event that matches
both the specified window and event mask. When it finds a match, XWindowEvent
removes that event from the queue and copies it into the specified XEvent structure.
The other events stored in the queue are not discarded. If a matching event is not in
the queue, XWindowEvent flushes the output buffer and blocks until one is received.
To remove the next event that matches both a window and an event mask (if any),
use XCheckWindowEvent. This function is similar to XWindowEvent except that it
never blocks and it returns a Bool indicating if the event was returned.
The XCheckWindowEvent function searches the event queue and then the events
available on the server connection for the first event that matches the specified
window and event mask. If it finds a match, XCheckWindowEvent removes that event,
copies it into the specified XEvent structure, and returns True. The other events
stored in the queue are not discarded. If the event you requested is not available,
XCheckWindowEvent returns False, and the output buffer will have been flushed.
To remove the next event that matches an event mask, use XMaskEvent.
The XMaskEvent function searches the event queue for the events associated with
the specified mask. When it finds a match, XMaskEvent removes that event and
copies it into the specified XEvent structure. The other events stored in the queue
are not discarded. If the event you requested is not in the queue, XMaskEvent flushes
the output buffer and blocks until one is received.
221
Event Handling Functions
To return and remove the next event that matches an event mask (if any), use
XCheckMaskEvent. This function is similar to XMaskEvent except that it never blocks
and it returns a Bool indicating if the event was returned.
The XCheckMaskEvent function searches the event queue and then any events
available on the server connection for the first event that matches the specified
mask. If it finds a match, XCheckMaskEvent removes that event, copies it into the
specified XEvent structure, and returns True. The other events stored in the queue
are not discarded. If the event you requested is not available, XCheckMaskEvent
returns False, and the output buffer will have been flushed.
To return and remove the next event in the queue that matches an event type, use
XCheckTypedEvent.
The XCheckTypedEvent function searches the event queue and then any events
available on the server connection for the first event that matches the specified
type. If it finds a match, XCheckTypedEvent removes that event, copies it into the
specified XEvent structure, and returns True. The other events in the queue are not
discarded. If the event is not available, XCheckTypedEvent returns False, and the
output buffer will have been flushed.
To return and remove the next event in the queue that matches an event type and
a window, use XCheckTypedWindowEvent.
The XCheckTypedWindowEvent function searches the event queue and then any
events available on the server connection for the first event that matches the
specified type and window. If it finds a match, XCheckTypedWindowEvent removes
the event from the queue, copies it into the specified XEvent structure, and returns
True. The other events in the queue are not discarded. If the event is not available,
XCheckTypedWindowEvent returns False, and the output buffer will have been
flushed.
222
Event Handling Functions
XPutBackEvent(display, event);
The XPutBackEvent function pushes an event back onto the head of the display's
event queue by copying the event into the queue. This can be useful if you read an
event and then decide that you would rather deal with it later. There is no limit to
the number of times in succession that you can call XPutBackEvent.
• If w is InputFocus and if the focus window contains the pointer, the destination
window is the window that contains the pointer; otherwise, the destination
window is the focus window.
To determine which clients should receive the specified events, XSendEvent uses
the propagate argument as follows:
• If event_mask is the empty set, the event is sent to the client that created the
destination window. If that client no longer exists, no event is sent.
• If propagate is False, the event is sent to every client selecting on destination any
of the event types in the event_mask argument.
223
Event Handling Functions
• If propagate is True and no clients have selected on destination any of the event
types in event-mask, the destination is replaced with the closest ancestor of
destination for which some client has selected a type in event-mask and for which
no intervening window has that type in its do-not-propagate-mask. If no such
window exists or if the window is an ancestor of the focus window and InputFocus
was originally specified as the destination, the event is not sent to any clients.
Otherwise, the event is reported to every client selecting on the final destination
any of the types specified in event_mask.
The event in the XEvent structure must be one of the core events or one of the
events defined by an extension (or a BadValue error results) so that the X server
can correctly byte-swap the contents as necessary. The contents of the event are
otherwise unaltered and unchecked by the X server except to force send_event to
True in the forwarded event and to set the serial number in the event correctly;
therefore these fields and the display field are ignored by XSendEvent.
XSendEvent returns zero if the conversion to wire protocol format failed and returns
nonzero otherwise.
unsigned long(display);
The server may retain the recent history of the pointer motion and do so to a
finer granularity than is reported by MotionNotify events. The function makes this
history available.
To get the motion history for a specified window and time, use .
start
224
Event Handling Functions
The function returns all events in the motion history buffer that fall between the
specified start and stop times, inclusive, and that have coordinates that lie within
the specified window (including its borders) at its present placement. If the server
does not support motion history, if the start time is later than the stop time, or if the
start time is in the future, no events are returned; returns NULL. If the stop time
is in the future, it is equivalent to specifying CurrentTime. The return type for this
function is a structure defined as follows:
typedef struct {
Time time;
short x, y;
} XTimeCoord;
The time member is set to the time, in milliseconds. The x and y members are set to
the coordinates of the pointer and are reported relative to the origin of the specified
window. To free the data returned from this call, use XFree.
After completing their work, all Xlib functions that generate protocol requests call
what is known as an after function. sets which function is to be called.
int(display, (*procedure)());
The specified procedure is called with only a display pointer. returns the previous
after function.
int(display, onoff);
225
Event Handling Functions
The XSynchronize function returns the previous after function. If onoff is True,
XSynchronize turns on synchronous behavior. If onoff is False, XSynchronize turns
off synchronous behavior.
int *XSetErrorHandler(handler);
Xlib generally calls the program's supplied error handler whenever an error
is received. It is not called on BadName errors from OpenFont, LookupColor,
or AllocNamedColor protocol requests or on BadFont errors from a QueryFont
protocol request. These errors generally are reflected back to the program through
the procedural interface. Because this condition is not assumed to be fatal, it is
acceptable for your error handler to return; the returned value is ignored. However,
the error handler should not call any functions (directly or indirectly) on the display
that will generate protocol requests or that will look for input events. The previous
error handler is returned.
typedef struct {
int type;
Display *display; /* Display the event was read from */
unsigned long serial; /* serial number of failed request */
unsigned char error_code; /* error code of failed request */
unsigned char request_code; /* Major op-code of failed request */
unsigned char minor_code; /* Minor op-code of failed request */
XID resourceid; /* resource id */
} XErrorEvent;
The serial member is the number of requests, starting from one, sent over the
network connection since it was opened. It is the number that was the value
of NextRequest immediately before the failing call was made. The request_code
member is a protocol request of the procedure that failed, as defined in <X11/
Xproto.h>. The following error codes can be returned by the functions described
in this chapter:
226
Event Handling Functions
227
Event Handling Functions
Note
The BadAtom, BadColor, BadCursor, BadDrawable, BadFont, BadGC,
BadPixmap, and BadWindow errors are also used when the argument type
is extended by a set of fixed alternatives.
code Specifies the error code for which you want to obtain
a description.
228
Event Handling Functions
The name argument should generally be the name of your application. The message
argument should indicate which type of error message you want. If the name
and message are not in the Host Portable Character Encoding, the result is
implementation-dependent. Xlib uses three predefined ``application names'' to
report errors. In these names, uppercase and lowercase matter.
XlibMessage These are the message strings that are used internally
by the library.
To report an error to the user when the requested display does not exist, use
XDisplayName.
char *XDisplayName(string);
The XDisplayName function returns the name of the display that XOpenDisplay
would attempt to use. If a NULL string is specified, XDisplayName looks in the
environment for the display and returns the display name that XOpenDisplay would
attempt to use. This makes it easier to report to the user precisely which display
the program attempted to open when the initial connection attempt failed.
int());
229
Event Handling Functions
The XSetIOErrorHandler sets the fatal I/O error handler. Xlib calls the program's
supplied error handler if any sort of system call error occurs (for example, the
connection to the server was lost). This is assumed to be a fatal condition, and the
called routine should not return. If the I/O error handler does return, the client
process exits.
230
Chapter 12. Input Device Functions
You can use the Xlib input device functions to:
Pointer Grabbing
Xlib provides functions that you can use to control input from the pointer, which
usually is a mouse. Usually, as soon as keyboard and mouse events occur, the X
server delivers them to the appropriate client, which is determined by the window
and input focus. The X server provides sufficient control over event delivery to
allow window managers to support mouse ahead and various other styles of user
interface. Many of these user interfaces depend on synchronous delivery of events.
The delivery of pointer and keyboard events can be controlled independently.
When mouse buttons or keyboard keys are grabbed, events will be sent to the
grabbing client rather than the normal client who would have received the event.
If the keyboard or pointer is in asynchronous mode, further mouse and keyboard
events will continue to be processed. If the keyboard or pointer is in synchronous
mode, no further events are processed until the grabbing client allows them (see
XAllowEvents). The keyboard or pointer is considered frozen during this interval.
The event that triggered the grab can also be replayed.
Note that the logical state of a device (as seen by client applications) may lag the
physical state if device event processing is frozen.
There are two kinds of grabs: active and passive. An active grab occurs when a
single client grabs the keyboard and/or pointer explicitly (see XGrabPointer and
XGrabKeyboard). A passive grab occurs when clients grab a particular keyboard
key or pointer button in a window, and the grab will activate when the key or button
is actually pressed. Passive grabs are convenient for implementing reliable pop-up
menus. For example, you can guarantee that the pop-up is mapped before the up
pointer button event occurs by grabbing a button requesting synchronous behavior.
The down event will trigger the grab and freeze further processing of pointer events
until you have the chance to map the pop-up window. You can then allow further
event processing. The up event will then be correctly processed relative to the pop-
up window.
For many operations, there are functions that take a time argument. The X server
includes a timestamp in various events. One special time, called CurrentTime,
231
Input Device Functions
represents the current server time. The X server maintains the time when the input
focus was last changed, when the keyboard was last grabbed, when the pointer was
last grabbed, or when a selection was last changed. Your application may be slow
reacting to an event. You often need some way to specify that your request should
not occur if another application has in the meanwhile taken control of the keyboard,
pointer, or selection. By providing the timestamp from the event in the request, you
can arrange that the operation not take effect if someone else has performed an
operation in the meanwhile.
For many functions in this section, you pass pointer event mask
bits. The valid pointer event mask bits are: ButtonPressMask,
ButtonReleaseMask, EnterWindowMask, LeaveWindowMask, PointerMotionMask,
PointerMotionHintMask, Button1MotionMask, Button2MotionMask,
Button3MotionMask, Button4MotionMask, Button5MotionMask,
ButtonMotionMask, and KeymapStateMask. For other functions in this section, you
pass keymask bits. The valid keymask bits are: ShiftMask, LockMask, ControlMask,
Mod1Mask, Mod2Mask, Mod3Mask, Mod4Mask, and Mod5Mask.
232
Input Device Functions
The XGrabPointer function actively grabs control of the pointer and returns
GrabSuccess if the grab was successful. Further pointer events are reported only to
the grabbing client. XGrabPointer overrides any active pointer grab by this client.
If owner_events is False, all generated pointer events are reported with respect to
grab_window and are reported only if selected by event_mask. If owner_events is
True and if a generated pointer event would normally be reported to this client, it is
reported as usual. Otherwise, the event is reported with respect to the grab_window
and is reported only if selected by event_mask. For either value of owner_events,
unreported events are discarded.
The time argument allows you to avoid certain circumstances that come up if
applications take a long time to respond or if there are long network delays.
Consider a situation where you have two applications, both of which normally grab
the pointer when clicked on. If both applications specify the timestamp from the
event, the second application may wake up faster and successfully grab the pointer
before the first application. The first application then will get an indication that the
other application grabbed the pointer before its request was processed.
233
Input Device Functions
the last-pointer-grab time or later than the current X server time, it fails and returns
GrabInvalidTime. Otherwise, the last-pointer-grab time is set to the specified time
(CurrentTime is replaced by the current X server time).
XUngrabPointer(display, time);
The XUngrabPointer function releases the pointer and any queued events if this
client has actively grabbed the pointer from XGrabPointer, XGrabButton, or from a
normal button press. XUngrabPointer does not release the pointer if the specified
time is earlier than the last-pointer-grab time or is later than the current X server
time. It also generates EnterNotify and LeaveNotify events. The X server performs
an UngrabPointer request automatically if the event window or confine_to window
for an active pointer grab becomes not viewable or if window reconfiguration causes
the confine_to window to lie completely outside the boundaries of the root window.
234
Input Device Functions
The XGrabButton function establishes a passive grab. In the future, the pointer is
actively grabbed (as for XGrabPointer), the last-pointer-grab time is set to the time
at which the button was pressed (as transmitted in the ButtonPress event), and the
ButtonPress event is reported if all of the following conditions are true:
• The pointer is not grabbed, and the specified button is logically pressed when the
specified modifier keys are logically down, and no other buttons or modifier keys
are logically down.
• A passive grab on the same button/key combination does not exist on any ancestor
of grab_window.
Note that the logical state of a device (as seen by client applications) may lag the
physical state if device event processing is frozen.
This request overrides all previous grabs by the same client on the same button/
key combinations on the same window. A modifiers of AnyModifier is equivalent
to issuing the grab request for all possible modifier combinations (including the
combination of no modifiers). It is not required that all modifiers specified have
currently assigned KeyCodes. A button of AnyButton is equivalent to issuing the
request for all possible buttons. Otherwise, it is not required that the specified
button currently be assigned to a physical button.
235
Input Device Functions
If some other client has already issued an XGrabButton with the same button/
key combination on the same window, a BadAccess error results. When using
AnyModifier or AnyButton, the request fails completely, and a BadAccess error
results (no grabs are established) if there is a conflicting grab for any combination.
XGrabButton has no effect on an active grab.
Keyboard Grabbing
Xlib provides functions that you can use to grab or ungrab the keyboard as well as
allow events.
For many functions in this section, you pass keymask bits. The valid keymask
bits are: ShiftMask, LockMask, ControlMask, Mod1Mask, Mod2Mask, Mod3Mask,
Mod4Mask, and Mod5Mask.
236
Input Device Functions
The XGrabKeyboard function actively grabs control of the keyboard and generates
FocusIn and FocusOut events. Further key events are reported only to the
grabbing client. XGrabKeyboard overrides any active keyboard grab by this client.
If owner_events is False, all generated key events are reported with respect to
grab_window. If owner_events is True and if a generated key event would normally
be reported to this client, it is reported normally; otherwise, the event is reported
with respect to the grab_window. Both KeyPress and KeyRelease events are always
reported, independent of any event selection made by the client.
XUngrabKeyboard(display, time);
The XUngrabKeyboard function releases the keyboard and any queued events
if this client has it actively grabbed from either XGrabKeyboard or XGrabKey.
XUngrabKeyboard does not release the keyboard and any queued events if the
specified time is earlier than the last-keyboard-grab time or is later than the
current X server time. It also generates FocusIn and FocusOut events. The X server
237
Input Device Functions
The XGrabKey function establishes a passive grab on the keyboard. In the future, the
keyboard is actively grabbed (as for XGrabKeyboard), the last-keyboard-grab time is
set to the time at which the key was pressed (as transmitted in the KeyPress event),
and the KeyPress event is reported if all of the following conditions are true:
• The keyboard is not grabbed and the specified key (which can itself be a modifier
key) is logically pressed when the specified modifier keys are logically down, and
no other modifier keys are logically down.
• Either the grab_window is an ancestor of (or is) the focus window, or the
grab_window is a descendant of the focus window and contains the pointer.
• A passive grab on the same key combination does not exist on any ancestor of
grab_window.
Note that the logical state of a device (as seen by client applications) may lag the
physical state if device event processing is frozen.
238
Input Device Functions
If some other client has issued a XGrabKey with the same key combination on the
same window, a BadAccess error results. When using AnyModifier or AnyKey, the
request fails completely, and a BadAccess error results (no grabs are established)
if there is a conflicting grab for any combination.
The XUngrabKey function releases the key combination on the specified window
if it was grabbed by this client. It has no effect on an active grab. A modifiers
of AnyModifier is equivalent to issuing the request for all possible modifier
combinations (including the combination of no modifiers). A keycode argument of
AnyKey is equivalent to issuing the request for all possible key codes.
To allow further events to be processed when the device has been frozen, use
XAllowEvents.
The XAllowEvents function releases some queued events if the client has caused a
device to freeze. It has no effect if the specified time is earlier than the last-grab
time of the most recent active grab for the client or if the specified time is later than
the current X server time. Depending on the event_mode argument, the following
occurs:
239
Input Device Functions
src_x
src_y
src_width
dest_x
If dest_w is None, XWarpPointer moves the pointer by the offsets (dest_x, dest_y)
relative to the current position of the pointer. If dest_w is a window, XWarpPointer
moves the pointer to the offsets (dest_x, dest_y) relative to the origin of dest_w.
However, if src_w is a window, the move only takes place if the window src_w
contains the pointer and if the specified rectangle of src_w contains the pointer.
The src_x and src_y coordinates are relative to the origin of src_w. If src_height is
zero, it is replaced with the current height of src_w minus src_y. If src_width is zero,
it is replaced with the current width of src_w minus src_x.
There is seldom any reason for calling this function. The pointer should normally be
left to the user. If you do use this function, however, it generates events just as if the
user had instantaneously moved the pointer from one position to another. Note that
you cannot use XWarpPointer to move the pointer outside the confine_to window
241
Input Device Functions
of an active pointer grab. An attempt to do so will only move the pointer as far as
the closest edge of the confine_to window.
The XSetInputFocus function changes the input focus and the last-focus-change
time. It has no effect if the specified time is earlier than the current last-focus-
change time or is later than the current X server time. Otherwise, the last-focus-
change time is set to the specified time (CurrentTime is replaced by the current
X server time). XSetInputFocus causes the X server to generate FocusIn and
FocusOut events.
• If focus is None, all keyboard events are discarded until a new focus window is
set, and the revert_to argument is ignored.
The specified focus window must be viewable at the time XSetInputFocus is called,
or a BadMatch error results. If the focus window later becomes not viewable, the
X server evaluates the revert_to argument to determine the new focus window as
follows:
• If revert_to is RevertToParent, the focus reverts to the parent (or the closest
viewable ancestor), and the new revert_to value is taken to be RevertToNone.
242
Input Device Functions
The XGetInputFocus function returns the focus window and the current focus state.
This section discusses the user-preference options of bell, key click, pointer
behavior, and so on. The default values for many of these options are server
dependent. Not all implementations will actually be able to control all of these
parameters.
/* Values */
typedef struct {
int key_click_percent;
int bell_percent;
int bell_pitch;
243
Input Device Functions
int bell_duration;
int led;
int led_mode; /* LedModeOn, LedModeOff */
int key;
int auto_repeat_mode; /* AutoRepeatModeOff, AutoRepeatModeOn,
AutoRepeatModeDefault */
} XKeyboardControl;
The key_click_percent member sets the volume for key clicks between 0 (off) and
100 (loud) inclusive, if possible. A setting of -1 restores the default. Other negative
values generate a BadValue error.
The bell_percent sets the base volume for the bell between 0 (off) and 100 (loud)
inclusive, if possible. A setting of -1 restores the default. Other negative values
generate a BadValue error. The bell_pitch member sets the pitch (specified in Hz)
of the bell, if possible. A setting of -1 restores the default. Other negative values
generate a BadValue error. The bell_duration member sets the duration of the bell
specified in milliseconds, if possible. A setting of -1 restores the default. Other
negative values generate a BadValue error.
If both the led_mode and led members are specified, the state of that LED
is changed, if possible. The led_mode member can be set to LedModeOn or
LedModeOff. If only led_mode is specified, the state of all LEDs are changed,
if possible. At most 32 LEDs numbered from one are supported. No standard
interpretation of LEDs is defined. If led is specified without led_mode, a BadMatch
error results.
If both the auto_repeat_mode and key members are specified, the auto_repeat_mode
of that key is changed (according to AutoRepeatModeOn, AutoRepeatModeOff, or
AutoRepeatModeDefault), if possible. If only auto_repeat_mode is specified, the
global auto_repeat_mode for the entire keyboard is changed, if possible, and does
not affect the per-key settings. If a key is specified without an auto_repeat_mode,
a BadMatch error results. Each key has an individual mode of whether or not
it should auto-repeat and a default setting for the mode. In addition, there is
a global mode of whether auto-repeat should be enabled or not and a default
setting for that mode. When global mode is AutoRepeatModeOn, keys should obey
their individual auto-repeat modes. When global mode is AutoRepeatModeOff, no
keys should auto-repeat. An auto-repeating key generates alternating KeyPress and
KeyRelease events. When a key is used as a modifier, it is desirable for the key not
to auto-repeat, regardless of its auto-repeat setting.
A bell generator connected with the console but not directly on a keyboard is treated
as if it were part of the keyboard. The order in which controls are verified and
altered is server-dependent. If an error is generated, a subset of the controls may
have been altered.
values Specifies one value for each bit set to 1 in the mask.
244
Input Device Functions
To obtain the current control values for the keyboard, use XGetKeyboardControl.
XGetKeyboardControl(display, values_return);
The XGetKeyboardControl function returns the current control values for the
keyboard to the XKeyboardState structure.
typedef struct {
int key_click_percent;
int bell_percent;
unsigned int bell_pitch, bell_duration;
unsigned long led_mask;
int global_auto_repeat;
char auto_repeats[32];
} XKeyboardState;
For the LEDs, the least significant bit of led_mask corresponds to LED one, and each
bit set to 1 in led_mask indicates an LED that is lit. The global_auto_repeat member
can be set to AutoRepeatModeOn or AutoRepeatModeOff. The auto_repeats
member is a bit vector. Each bit set to 1 indicates that auto-repeat is enabled for the
corresponding key. The vector is represented as 32 bytes. Byte N (from 0) contains
the bits for keys 8N to 8N + 7 with the least significant bit in the byte representing
key 8N.
XAutoRepeatOn(display);
The XAutoRepeatOn function turns on auto-repeat for the keyboard on the specified
display.
XAutoRepeatOff(display);
The XAutoRepeatOff function turns off auto-repeat for the keyboard on the specified
display.
245
Input Device Functions
XBell(display, percent);
percent Specifies the volume for the bell, which can range from
-100 to 100 inclusive.
The XBell function rings the bell on the keyboard on the specified display, if
possible. The specified volume is relative to the base volume for the keyboard. If the
value for the percent argument is not in the range -100 to 100 inclusive, a BadValue
error results. The volume at which the bell rings when the percent argument is
nonnegative is:
The volume at which the bell rings when the percent argument is negative is:
To obtain a bit vector that describes the state of the keyboard, use XQueryKeymap.
XQueryKeymap(display, keys_return[32]);
The XQueryKeymap function returns a bit vector for the logical state of the keyboard,
where each bit set to 1 indicates that the corresponding key is currently pressed
down. The vector is represented as 32 bytes. Byte N (from 0) contains the bits for
keys 8N to 8N + 7 with the least significant bit in the byte representing key 8N.
Note that the logical state of a device (as seen by client applications) may lag the
physical state if device event processing is frozen.
246
Input Device Functions
return, or a BadValue error results. A zero element disables a button, and elements
are not restricted in value by the number of physical buttons. However, no two
elements can have the same nonzero value, or a BadValue error results. If any of the
buttons to be altered are logically in the down state, XSetPointerMapping returns
MappingBusy, and the mapping is not changed.
The XChangePointerControl function defines how the pointing device moves. The
acceleration, expressed as a fraction, is a multiplier for movement. For example,
specifying 3/1 means the pointer moves three times as fast as normal. The fraction
may be rounded arbitrarily by the X server. Acceleration only takes effect if the
pointer moves more than threshold pixels at once and only applies to the amount
beyond the value in the threshold argument. Setting a value to -1 restores the
default. The values of the do_accel and do_threshold arguments must be True for the
pointer values to be set, or the parameters are unchanged. Negative values (other
than -1) generate a BadValue error, as does a zero value for the accel_denominator
argument.
247
Input Device Functions
XGetPointerControl(display, accel_numerator_return,
accel_denominator_return, threshold_return);
A list of KeySyms is associated with each KeyCode. The list is intended to convey
the set of symbols on the corresponding key. If the list (ignoring trailing NoSymbol
entries) is a single KeySym ``K'', then the list is treated as if it were the list ``K
NoSymbol K NoSymbol''. If the list (ignoring trailing NoSymbol entries) is a pair
of KeySyms ``K1 K2'', then the list is treated as if it were the list ``K1 K2 K1 K2''.
If the list (ignoring trailing NoSymbol entries) is a triple of KeySyms ``K1 K2 K3'',
then the list is treated as if it were the list ``K1 K2 K3 NoSymbol''. When an explicit
``void'' element is desired in the list, the value VoidSymbol can be used.
The first four elements of the list are split into two groups of KeySyms. Group
1 contains the first and second KeySyms; Group 2 contains the third and fourth
KeySyms. Within each group, if the second element of the group is NoSymbol, then
the group should be treated as if the second element were the same as the first
element, except when the first element is an alphabetic KeySym ``K'' for which
both lowercase and uppercase forms are defined. In that case, the group should
248
Input Device Functions
be treated as if the first element were the lowercase form of ``K'' and the second
element were the uppercase form of ``K''.
The standard rules for obtaining a KeySym from a KeyPress event make use of only
the Group 1 and Group 2 KeySyms; no interpretation of other KeySyms in the list is
given. Which group to use is determined by the modifier state. Switching between
groups is controlled by the KeySym named MODE SWITCH, by attaching that
KeySym to some KeyCode and attaching that KeyCode to any one of the modifiers
Mod1 through Mod5. This modifier is called the group modifier. For any KeyCode,
Group 1 is used when the group modifier is off, and Group 2 is used when the group
modifier is on.
Within a group, the choice of KeySym is determined by applying the first rule that
is satisfied from the following list:
• The numlock modifier is on and the second KeySym is a keypad KeySym. In this
case, if the Shift modifier is on, or if the Lock modifier is on and is interpreted as
ShiftLock, then the first KeySym is used, otherwise the second KeySym is used.
• The Shift and Lock modifiers are both off. In this case, the first KeySym is used.
• The Shift modifier is off, and the Lock modifier is on and is interpreted as
CapsLock. In this case, the first KeySym is used, but if that KeySym is lowercase
alphabetic, then the corresponding uppercase KeySym is used instead.
• The Shift modifier is on, and the Lock modifier is on and is interpreted as
CapsLock. In this case, the second KeySym is used, but if that KeySym is lowercase
alphabetic, then the corresponding uppercase KeySym is used instead.
• The Shift modifier is on, or the Lock modifier is on and is interpreted as ShiftLock,
or both. In this case, the second KeySym is used.
No spatial geometry of the symbols on the key is defined by their order in the
KeySym list, although a geometry might be defined on a server-specific basis. The X
server does not use the mapping between KeyCodes and KeySyms. Rather, it merely
stores it for reading and writing by clients.
249
Input Device Functions
The XGetKeyboardMapping function returns the symbols for the specified number
of KeyCodes starting with first_keycode. The value specified in first_keycode must
be greater than or equal to min_keycode as returned by XDisplayKeycodes, or a
BadValue error results. In addition, the following expression must be less than or
equal to max_keycode as returned by XDisplayKeycodes:
first_keycode + keycode_count - 1
If this is not the case, a BadValue error results. The number of elements in the
KeySyms list is:
keycode_count * keysyms_per_keycode_return
KeySym number N, counting from zero, for KeyCode K has the following index in
the list, counting from zero:
(K - first_code) * keysyms_per_code_return + N
250
Input Device Functions
num_codes * keysyms_per_keycode
first_keycode + num_codes - 1
KeySym number N, counting from zero, for KeyCode K has the following index in
keysyms, counting from zero:
(K - first_keycode) * keysyms_per_keycode + N
There is no requirement that the X server interpret this mapping. It is merely stored
for reading and writing by clients.
The next six functions make use of the XModifierKeymap data structure, which
contains:
typedef struct {
int max_keypermod; /* This server's max number of keys per modifier */
KeyCode *modifiermap; /* An 8 by max_keypermod array of the modifiers */
} XModifierKeymap;
XModifierKeymap *XNewModifiermap(max_keys_per_mod);
251
Input Device Functions
XFreeModifiermap(modmap);
The XSetModifierMapping function specifies the KeyCodes of the keys (if any) that
are to be used as modifiers. If it succeeds, the X server generates a MappingNotify
event, and XSetModifierMapping returns MappingSuccess. X permits at most 8
252
Input Device Functions
An X server can impose restrictions on how modifiers can be changed, for example,
if certain keys do not generate up transitions in hardware, if auto-repeat cannot be
disabled on certain keys, or if multiple modifier keys are not supported. If some such
restriction is violated, the status reply is MappingFailed, and none of the modifiers
are changed. If the new KeyCodes specified for a modifier differ from those currently
defined and any (current or new) keys for that modifier are in the logically down
state, XSetModifierMapping returns MappingBusy, and none of the modifiers is
changed.
XModifierKeymap *XGetModifierMapping(display);
253
Chapter 13. Locales and
Internationalized Text Functions
An internationalized application is one that is adaptable to the requirements of
different native languages, local customs, and character string encodings. The
process of adapting the operation to a particular native language, local custom,
or string encoding is called localization. A goal of internationalization is to permit
localization without program source modifications or recompilation.
This chapter defines support for localized text imaging and text input and describes
the locale mechanism that controls all locale-dependent Xlib functions. Sets of
functions are provided for multibyte (char *) text as well as wide character (wchar_t)
text in the form supported by the host C language environment. The multibyte and
wide character functions are equivalent except for the form of the text argument.
The Xlib internationalization functions are not meant to provide support for
multilingual applications (mixing multiple languages within a single piece of text),
but they make it possible to implement applications that work in limited fashion
with more than one language in independent contexts.
• X locale management
• Output methods
• Input methods
• String constants
254
Locales and Internationalized
Text Functions
X Locale Management
X supports one or more of the locales defined by the host environment. On
implementations that conform to the ANSI C library, the locale announcement
method is setlocale. This function configures the locale operation of both the
host C library and Xlib. The operation of Xlib is governed by the LC_CTYPE
category; this is called the current locale. An implementation is permitted to provide
implementation-dependent mechanisms for announcing the locale in addition to
setlocale.
The mechanism by which the semantic operation of Xlib is defined for a specific
locale is implementation-dependent.
X is not required to support all the locales supported by the host. To determine if
the current locale is supported by X, use XSupportsLocale.
Bool XSupportsLocale();
The client is responsible for selecting its locale and X modifiers. Clients should
provide a means for the user to override the clients' locale selection at client
invocation. Most single-display X clients operate in a single locale for both X
and the host processing environment. They will configure the locale by calling
three functions: the host locale configuration function, XSupportsLocale, and
XSetLocaleModifiers.
To configure Xlib locale modifiers for the current locale, use XSetLocaleModifiers.
char *XSetLocaleModifiers(modifier_list);
The local host X locale modifiers announcer (on POSIX-compliant systems, the
XMODIFIERS environment variable) is appended to the modifier_list to provide
default values on the local host. If a given category appears more than once in
the list, the first setting in the list is used. If a given category is not included in
255
Locales and Internationalized
Text Functions
If invalid values are given for one or more modifier categories supported by the
locale, a NULL pointer is returned, and none of the current modifiers are changed.
At program startup, the modifiers that are in effect are unspecified until the first
successful call to set them. Whenever the locale is changed, the modifiers that are in
effect become unspecified until the next successful call to set them. Clients should
always call XSetLocaleModifiers with a non-NULL modifier_list after setting the
locale before they call any locale-dependent Xlib routine.
The only standard modifier category currently defined is ``im'', which identifies the
desired input method. The values for input method are not standardized. A single
locale may use multiple input methods, switching input method under user control.
The modifier may specify the initial input method in effect or an ordered list of input
methods. Multiple input methods may be specified in a single im value string in an
implementation-dependent manner.
The returned modifiers string is owned by Xlib and should not be modified or freed
by the client. It may be freed by Xlib after the current locale or modifiers are
changed. Until freed, it will not be modified by Xlib.
The recommended procedure for clients initializing their locale and modifiers is
to obtain locale and modifier announcers separately from one of the following
prioritized sources:
• A resource
The first of these that is defined should be used. Note that when a locale command
line option or locale resource is defined, the effect should be to set all categories
to the specified locale, overriding any category-specific settings in the local host
environment.
256
Locales and Internationalized
Text Functions
XrmGetStringDatabase
XrmDatabase XrmPutFileDatabase Locale of XrmDatabase
XrmLocaleOfDatabase
Setting Standard Properties:
setlocale XmbSetWMProperties Encoding of supplied/
returned text (some
WM_ property text in
environment locale)
setlocale XmbTextPropertyToTextList Encoding of supplied/
returned text
XwcTextPropertyToTextList
XmbTextListToTextProperty
XwcTextListToTextProperty
Text Input:
setlocale XOpenIM XIM input method
selection
XRegisterIMInstantiateCallback XIM selection
XUnregisterIMInstantiateCallback XIM selection
XIM XCreateIC XIC input method
configuration
XLocaleOfIM, and so on Queried locale
XIC XmbLookupString Keyboard layout
XwcLookupString Encoding of returned
text
Text Drawing:
setlocale XOpenOM XOM output method
selection
XCreateFontSet Charsets of fonts in
XFontSet
XOM XCreateOC XOC output method
configuration
XLocaleOfOM, and so on Queried locale
XFontSet XmbDrawText, Locale of supplied text
XwcDrawText, and so on Locale of supplied text
XExtentsOfFontSet, and so on Locale-dependent
metrics
XmbTextExtents,
XwcTextExtents, and so on
257
Locales and Internationalized
Text Functions
Clients may assume that a locale-encoded text string returned by an X function can
be passed to a C library routine, or vice versa, if the locale is the same at the two
calls.
All text strings processed by internationalized Xlib functions are assumed to begin
in the initial state of the encoding of the locale, if the encoding is state-dependent.
All Xlib functions behave as if they do not change the current locale or X modifier
setting. (This means that if they do change locale or call XSetLocaleModifiers with
a non-NULL argument, they must save and restore the current state on entry and
exit.) Also, Xlib functions on implementations that conform to the ANSI C library
do not alter the global state associated with the ANSI C functions mblen, mbtowc,
wctomb, and strtok.
XVaNestedList XVaCreateNestedList(dummy);
The XVaCreateNestedList function allocates memory and copies its arguments into
a single list pointer, which may be used as a value for arguments requiring a list
value. Any entries are copied as specified. Data passed by reference is not copied;
the caller must ensure data remains valid for the lifetime of the nested list. The list
should be freed using XFree when it is no longer needed.
Output Methods
This section provides discussions of the following X Output Method (XOM) topics:
258
Locales and Internationalized
Text Functions
• Drawing locale-dependent text with a font set without the caller needing to be
aware of locale dependencies.
Two different abstractions are used in the representation of the output method for
clients.
259
Locales and Internationalized
Text Functions
The XOpenOM function opens an output method matching the current locale and
modifiers specification. The current locale and modifiers are bound to the output
method when XOpenOM is called. The locale associated with an output method cannot
be changed.
The specific output method to which this call will be routed is identified on the
basis of the current locale and modifiers. XOpenOM will identify a default output
method corresponding to the current locale. That default can be modified using
XSetLocaleModifiers to set the output method modifier.
The db argument is the resource database to be used by the output method for
looking up resources that are private to the output method. It is not intended that
this database be used to look up values that can be set as OC values in an output
context. If db is NULL, no database is passed to the output method.
The res_name and res_class arguments specify the resource name and class of the
application. They are intended to be used as prefixes by the output method when
looking up resources that are common to all output contexts that may be created
for this output method. The characters used for resource names and classes must
be in the X Portable Character Set. The resources looked up are not fully specified
if res_name or res_class is NULL.
The res_name and res_class arguments are not assumed to exist beyond the call
to XOpenOM. The specified resource database is assumed to exist for the lifetime of
the output method.
Status XCloseOM(om);
char *XSetOMValues(om);
260
Locales and Internationalized
Text Functions
function returns NULL if it succeeds; otherwise, it returns the name of the first
argument that could not be obtained.
char *XGetOMValues(om);
Display *XDisplayOfOM(om);
The XDisplayOfOM function returns the display associated with the specified output
method.
char *XLocaleOfOM(om);
The XLocaleOfOM returns the locale associated with the specified output method.
Key Explanation
G This value may be read using XGetOMValues.
261
Locales and Internationalized
Text Functions
typedef struct {
int charset_count;
char **charset_list;
} XOMCharSetList;
The charset_list member is a list of one or more null-terminated charset names, and
the charset_count member is the number of charset names.
The required charset list is owned by Xlib and should not be modified or freed by the
client. It will be freed by a call to XCloseOM with the associated XOM. Until freed,
its contents will not be modified by Xlib.
Query Orientation
The XNQueryOrientation argument returns the global orientation of text when
drawn. Other than XOMOrientation_LTR_TTB, the set of orientations supported is
locale-dependent. The value of the argument is a pointer to a structure of type
XOMOrientation. Clients are responsible for freeing the XOMOrientation structure
by using XFree; this also frees the contents of the structure.
typedef struct {
int num_orientation;
XOrientation *orientation; /* Input Text description */
} XOMOrientation;
typedef enum {
XOMOrientation_LTR_TTB,
XOMOrientation_RTL_TTB,
XOMOrientation_TTB_LTR,
XOMOrientation_TTB_RTL,
XOMOrientation_Context
} XOrientation;
262
Locales and Internationalized
Text Functions
Regardless of the rendering order of characters, the origins of all characters are on
the primary draw direction side of the drawing origin.
XOC XCreateOC(om);
263
Locales and Internationalized
Text Functions
The XCreateOC function creates an output context within the specified output
method.
The base font names argument is mandatory at creation time, and the output context
will not be created unless it is provided. All other output context values can be set
later.
void XDestroyOC(oc);
To get the output method associated with an output context, use XOMOfOC.
XOM XOMOfOC(oc);
The XOMOfOC function returns the output method associated with the specified
output context.
Xlib provides two functions for setting and reading output context values,
respectively, XSetOCValues and XGetOCValues. Both functions have a variable-
length argument list. In that argument list, any XOC value's name must be denoted
with a character string using the X Portable Character Set.
char *XSetOCValues(oc);
264
Locales and Internationalized
Text Functions
Each value to be set must be an appropriate datum, matching the data type imposed
by the semantics of the argument.
char *XGetOCValues(oc);
Each argument value following a name must point to a location where the value is
to be stored.
Key Explanation
C This value must be set with XCreateOC.
D This value may be set using XCreateOC. If it is not set,a default is
provided.
G This value may be read using XGetOCValues.
S This value must be set using XSetOCValues.
265
Locales and Internationalized
Text Functions
Use of XLFD font names permits Xlib to obtain the fonts needed for a variety of
locales from a single locale-independent base font name. The single base font name
should name a family of fonts whose members are encoded in the various charsets
needed by the locales of interest.
An XLFD base font name can explicitly name a charset needed for the locale. This
allows the user to specify an exact font for use with a charset required by a locale,
fully controlling the font selection.
If a base font name is not an XLFD name, Xlib will attempt to obtain an XLFD name
from the font properties for the font. If Xlib is successful, the XGetOCValues function
will return this XLFD name instead of the client-supplied name.
This argument must be set at creation time and cannot be changed. If no fonts exist
for any of the required charsets, or if the locale definition in Xlib requires that a
font exist for a particular charset and a font is not found for that charset, XCreateOC
returns NULL.
When querying for the XNBaseFontName XOC value, XGetOCValues returns a null-
terminated string identifying the base font names that Xlib used to load the fonts
needed for the locale. This string is owned by Xlib and should not be modified
or freed by the client. The string will be freed by a call to XDestroyOC with the
associated XOC. Until freed, the string contents will not be modified by Xlib.
Missing CharSet
The XNMissingCharSet argument returns the list of required charsets that are
missing from the font set. The value of the argument is a pointer to a structure of
type XOMCharSetList.
If fonts exist for all of the charsets required by the current locale, charset_list is set
to NULL and charset_count is set to zero. If no fonts exist for one or more of the
required charsets, charset_list is set to a list of one or more null-terminated charset
names for which no fonts exist, and charset_count is set to the number of missing
charsets. The charsets are from the list of the required charsets for the encoding
of the locale and do not include any charsets to which Xlib may be able to remap
a required charset.
The missing charset list is owned by Xlib and should not be modified or freed by the
client. It will be freed by a call to XDestroyOC with the associated XOC. Until freed,
its contents will not be modified by Xlib.
Default String
When a drawing or measuring function is called with an XOC that has missing
charsets, some characters in the locale will not be drawable. The XNDefaultString
argument returns a pointer to a string that represents the glyphs that are drawn
266
Locales and Internationalized
Text Functions
with this XOC when the charsets of the available fonts do not include all glyphs
required to draw a character. The string does not necessarily consist of valid
characters in the current locale and is not necessarily drawn with the fonts loaded
for the font set, but the client can draw or measure the default glyphs by including
this string in a string being drawn or measured with the XOC.
If the XNDefaultString argument returned the empty string (""), no glyphs are
drawn and the escapement is zero. The returned string is null-terminated. It is
owned by Xlib and should not be modified or freed by the client. It will be freed by
a call to XDestroyOC with the associated XOC. Until freed, its contents will not be
modified by Xlib.
Orientation
The XNOrientation argument specifies the current orientation of text when drawn.
The value of this argument is one of the values returned by the XGetOMValues
function with the XNQueryOrientation argument specified in the XOrientation list.
The value of the argument is of type XOrientation. When XNOrientation is queried,
the value specifies the current orientation. When XNOrientation is set, a value is
used to set the current orientation.
The XNOrientation value does not change the prime drawing direction for Xlib
drawing functions.
It is not intended that values that can be set as XOM values be set as resources.
Font Info
The XNFontInfo argument specifies a list of one or more XFontStruct structures and
font names for the fonts used for drawing by the given output context. The value of
the argument is a pointer to a structure of type XOMFontInfo.
typedef struct {
267
Locales and Internationalized
Text Functions
int num_font;
XFontStruct **font_struct_list;
char **font_name_list;
} XOMFontInfo;
Because it is not guaranteed that a given character will be imaged using a single
font glyph, there is no provision for mapping a character or default string to the font
properties, font ID, or direction hint for the font for the character. The client may
access the XFontStruct list to obtain these values for all the fonts currently in use.
Xlib does not guarantee that fonts are loaded from the server at the creation of
an XOC. Xlib may choose to cache font data, loading it only as needed to draw
text or compute text dimensions. Therefore, existence of the per_char metrics in
the XFontStruct structures in the XFontStructSet is undefined. Also, note that all
properties in the XFontStruct structures are in the STRING encoding.
The client must not free the XOMFontInfo struct itself; it will be freed when the
XOC is closed.
OM Automatic
The XNOMAutomatic argument returns whether the associated output context
was created by XCreateFontSet or not. Because the XFreeFontSet function not
only destroys the output context but also closes the implicit output method
associated with it, XFreeFontSet should be used with any output context created
by XCreateFontSet. However, it is possible that a client does not know how the
output context was created. Before a client destroys the output context, it can query
whether XNOMAutomatic is set to determine whether XFreeFontSet or XDestroyOC
should be used to destroy the output context.
268
Locales and Internationalized
Text Functions
The XCreateFontSet function creates a font set for the specified display. The font
set is bound to the current locale when XCreateFontSet is called. The font set may
be used in subsequent calls to obtain font and character information and to image
text in the locale of the font set.
The base_font_name_list argument is a list of base font names that Xlib uses to
load the fonts needed for the locale. The base font names are a comma-separated
list. The string is null-terminated and is assumed to be in the Host Portable
Character Encoding; otherwise, the result is implementation-dependent. White
space immediately on either side of a separating comma is ignored.
Use of XLFD font names permits Xlib to obtain the fonts needed for a variety of
locales from a single locale-independent base font name. The single base font name
should name a family of fonts whose members are encoded in the various charsets
needed by the locales of interest.
An XLFD base font name can explicitly name a charset needed for the locale. This
allows the user to specify an exact font for use with a charset required by a locale,
fully controlling the font selection.
If a base font name is not an XLFD name, Xlib will attempt to obtain an XLFD name
from the font properties for the font. If this action is successful in obtaining an
XLFD name, the XBaseFontNameListOfFontSet function will return this XLFD name
instead of the client-supplied name.
Xlib uses the following algorithm to select the fonts that will be used to display text
with the XFontSet.
For each font charset required by the locale, the base font name list is searched
for the first appearance of one of the following cases that names a set of fonts that
exist at the server:
• The first XLFD-conforming base font name that specifies the required charset or
a superset of the required charset in its CharSetRegistry and CharSetEncoding
fields. The implementation may use a base font name whose specified charset is
a superset of the required charset, for example, an ISO8859-1 font for an ASCII
charset.
• The first set of one or more XLFD-conforming base font names that specify one
or more charsets that can be remapped to support the required charset. The Xlib
implementation may recognize various mappings from a required charset to one
or more other charsets and use the fonts for those charsets. For example, JIS
Roman is ASCII with tilde and backslash replaced by yen and overbar; Xlib may
load an ISO8859-1 font to support this character set if a JIS Roman font is not
available.
• The first XLFD-conforming font name or the first non-XLFD font name for which an
XLFD font name can be obtained, combined with the required charset (replacing
the CharSetRegistry and CharSetEncoding fields in the XLFD font name). As in
269
Locales and Internationalized
Text Functions
case 1, the implementation may use a charset that is a superset of the required
charset.
ISO8859-1
JISX0208.1983
JISX0201.1976
GB2312-1980.0
The user could supply a base_font_name_list that explicitly specifies the charsets,
ensuring that specific fonts are used if they exist. For example:
"-JIS-Fixed-Medium-R-Normal--26-180-100-100-C-240-JISX0208.1983-0,\\
-JIS-Fixed-Medium-R-Normal--26-180-100-100-C-120-JISX0201.1976-0,\\
-GB-Fixed-Medium-R-Normal--26-180-100-100-C-240-GB2312-1980.0,\\
-Adobe-Courier-Bold-R-Normal--25-180-75-75-M-150-ISO8859-1"
Alternatively, the user could supply a base_font_name_list that omits the charsets,
letting Xlib select font charsets required for the locale. For example:
"-JIS-Fixed-Medium-R-Normal--26-180-100-100-C-240,\\
-JIS-Fixed-Medium-R-Normal--26-180-100-100-C-120,\\
-GB-Fixed-Medium-R-Normal--26-180-100-100-C-240,\\
-Adobe-Courier-Bold-R-Normal--25-180-100-100-M-150"
Alternatively, the user could simply supply a single base font name that allows
Xlib to select from all available fonts that meet certain minimum XLFD property
requirements. For example:
"-*-*-*-R-Normal--*-180-100-100-*-*"
If no font exists for one or more of the required charsets, XCreateFontSet sets
missing_charset_list_return to a list of one or more null-terminated charset names
for which no font exists and sets missing_charset_count_return to the number
of missing fonts. The charsets are from the list of the required charsets for the
encoding of the locale and do not include any charsets to which Xlib may be able
to remap a required charset.
If no font exists for any of the required charsets or if the locale definition in
Xlib requires that a font exist for a particular charset and a font is not found for
270
Locales and Internationalized
Text Functions
If the string returned to def_string_return is the empty string (""), no glyphs are
drawn, and the escapement is zero. The returned string is null-terminated. It is
owned by Xlib and should not be modified or freed by the client. It will be freed by
a call to XFreeFontSet with the associated XFontSet. Until freed, its contents will
not be modified by Xlib.
The client is responsible for constructing an error message from the missing charset
and default string information and may choose to continue operation in the case
that some fonts did not exist.
The returned XFontSet and missing charset list should be freed with XFreeFontSet
and XFreeStringList, respectively. The client-supplied base_font_name_list may be
freed by the client after calling XCreateFontSet.
To obtain a list of XFontStruct structures and full font names given an XFontSet,
use XFontsOfFontSet.
The XFontsOfFontSet function returns a list of one or more XFontStructs and font
names for the fonts used by the Xmb and Xwc layers for the given font set. A list of
pointers to the XFontStruct structures is returned to font_struct_list_return. A list
of pointers to null-terminated, fully specified font name strings in the locale of the
font set is returned to font_name_list_return. The font_name_list order corresponds
to the font_struct_list order. The number of XFontStruct structures and font names
is returned as the value of the function.
Because it is not guaranteed that a given character will be imaged using a single
font glyph, there is no provision for mapping a character or default string to the font
properties, font ID, or direction hint for the font for the character. The client may
access the XFontStruct list to obtain these values for all the fonts currently in use.
Xlib does not guarantee that fonts are loaded from the server at the creation of an
XFontSet. Xlib may choose to cache font data, loading it only as needed to draw
text or compute text dimensions. Therefore, existence of the per_char metrics in
271
Locales and Internationalized
Text Functions
the XFontStruct structures in the XFontStructSet is undefined. Also, note that all
properties in the XFontStruct structures are in the STRING encoding.
The XFontStruct and font name lists are owned by Xlib and should not be modified or
freed by the client. They will be freed by a call to XFreeFontSet with the associated
XFontSet. Until freed, their contents will not be modified by Xlib.
To obtain the base font name list and the selected font name list given an XFontSet,
use XBaseFontNameListOfFontSet.
char *XBaseFontNameListOfFontSet(font_set);
The XBaseFontNameListOfFontSet function returns the original base font name list
supplied by the client when the XFontSet was created. A null-terminated string
containing a list of comma-separated font names is returned as the value of the
function. White space may appear immediately on either side of separating commas.
If XCreateFontSet obtained an XLFD name from the font properties for the font
specified by a non-XLFD base name, the XBaseFontNameListOfFontSet function
will return the XLFD name instead of the non-XLFD base name.
The base font name list is owned by Xlib and should not be modified or freed by the
client. It will be freed by a call to XFreeFontSet with the associated XFontSet. Until
freed, its contents will not be modified by Xlib.
char *XLocaleOfFontSet(font_set);
The XLocaleOfFontSet function returns the name of the locale bound to the
specified XFontSet, as a null-terminated string.
The returned locale name string is owned by Xlib and should not be modified or
freed by the client. It may be freed by a call to XFreeFontSet with the associated
XFontSet. Until freed, it will not be modified by Xlib.
The XFreeFontSet function frees the specified font set. The associated base font
name list, font name list, XFontStruct list, and XFontSetExtents, if any, are freed.
272
Locales and Internationalized
Text Functions
advances for each succeeding character in the string. The Xlib interface is currently
defined to support only a left-to-right primary draw direction. The drawing origin
is the position passed to the drawing function when the text is drawn. The baseline
is a line drawn through the drawing origin parallel to the primary draw direction.
Character ink is the pixels painted in the foreground color and does not include
interline or intercharacter spacing or image text background pixels.
The drawing functions are allowed to implement implicit text directionality control,
reversing the order in which characters are rendered along the primary draw
direction in response to locale-specific lexical analysis of the string.
Regardless of the character rendering order, the origins of all characters are on
the primary draw direction side of the drawing origin. The screen location of a
particular character image may be determined with XmbTextPerCharExtents or
XwcTextPerCharExtents.
Bool XDirectionalDependentDrawing(font_set);
Bool XContextualDrawing(font_set);
The XContextualDrawing function returns True if text drawn with the font set might
include context-dependent drawing; otherwise, it returns False.
Bool XContextDependentDrawing(font_set);
The drawing functions do not interpret newline, tab, or other control characters.
The behavior when nonprinting characters other than space are drawn is
273
Locales and Internationalized
Text Functions
The maximum character extents for the fonts that are used by the text drawing
layers can be accessed by the XFontSetExtents structure:
typedef struct {
XRectangle max_ink_extent; /* over all drawable characters */
XRectangle max_logical_extent; /* over all drawable characters */
} XFontSetExtents;
The XRectangle structures used to return font set metrics are the usual Xlib screen-
oriented rectangles with x, y giving the upper left corner, and width and height
always positive.
The max_ink_extent member gives the maximum extent, over all drawable
characters, of the rectangles that bound the character glyph image drawn in
the foreground color, relative to a constant origin. See XmbTextExtents and
XwcTextExtents for detailed semantics.
The max_logical_extent member gives the maximum extent, over all drawable
characters, of the rectangles that specify minimum spacing to other graphical
features, relative to a constant origin. Other graphical features drawn by the client,
for example, a border surrounding the text, should not intersect this rectangle. The
max_logical_extent member should be used to compute minimum interline spacing
and the minimum area that must be allowed in a text field to draw a given number
of arbitrary characters.
XFontSetExtents *XExtentsOfFontSet(font_set);
The XFontSetExtents structure is owned by Xlib and should not be modified or freed
by the client. It will be freed by a call to XFreeFontSet with the associated XFontSet.
Until freed, its contents will not be modified by Xlib.
274
Locales and Internationalized
Text Functions
275
Locales and Internationalized
Text Functions
When the XFontSet has missing charsets, metrics for each unavailable character
are taken from the default string returned by XCreateFontSet so that the metrics
represent the text as it will actually be drawn. The behavior for an invalid codepoint
is undefined.
To determine the effective drawing origin for a character in a drawn string, the client
should call XmbTextPerCharExtents on the entire string, then on the character, and
subtract the x values of the returned rectangles for the character. This is useful
to redraw portions of a line of text or to justify words, but for context-dependent
rendering, the client should not assume that it can redraw the character by itself
and get the same rendering.
276
Locales and Internationalized
Text Functions
When the XFontSet has missing charsets, metrics for each unavailable character
are taken from the default string returned by XCreateFontSet so that the metrics
represent the text as it will actually be drawn. The behavior for an invalid codepoint
is undefined.
If the array_size is too small for the number of characters in the supplied text,
the functions return zero and num_chars_return is set to the number of rectangles
required. Otherwise, the functions return a nonzero value.
The text is drawn using the fonts loaded for the specified font set; the font in the
GC is ignored and may be modified by the functions. No validation that all fonts
conform to some width rule is performed.
The text functions XmbDrawText and XwcDrawText use the following structures:
typedef struct {
char *chars; /* pointer to string */
int nchars; /* number of bytes */
int delta; /* pixel delta between strings */
XFontSet font_set; /* fonts, None means don't change */
277
Locales and Internationalized
Text Functions
} XmbTextItem;
typedef struct {
wchar_t *chars; /* pointer to wide char string */
int nchars; /* number of wide characters */
int delta; /* pixel delta between strings */
XFontSet font_set; /* fonts, None means don't change */
} XwcTextItem;
To draw text using multiple font sets in a given drawable, use XmbDrawText or
XwcDrawText.
The XmbDrawText and XwcDrawText functions allow complex spacing and font set
shifts between text strings. Each text item is processed in turn, with the origin of
a text element advanced in the primary draw direction by the escapement of the
previous text item. A text item delta specifies an additional escapement of the text
item drawing origin in the primary draw direction. A font_set member other than
None in an item causes the font set to be used for this and subsequent text items
in the text_items list. Leading text items with a font_set member set to None will
not be drawn.
To draw text using a single font set in a given drawable, use XmbDrawString or
XwcDrawString.
278
Locales and Internationalized
Text Functions
The XmbDrawString and XwcDrawString functions draw the specified text with
the foreground pixel. When the XFontSet has missing charsets, each unavailable
character is drawn with the default string returned by XCreateFontSet. The
behavior for an invalid codepoint is undefined.
To draw image text using a single font set in a given drawable, use
XmbDrawImageString or XwcDrawImageString.
279
Locales and Internationalized
Text Functions
When the XFontSet has missing charsets, each unavailable character is drawn
with the default string returned by XCreateFontSet. The behavior for an invalid
codepoint is undefined.
Input Methods
This section provides discussions of the following X Input Method (XIM) topics:
• Event filtering
Korean also has a phonetic symbol set, called Hangul. Each of the 24 basic phonetic
symbols (14 consonants and 10 vowels) represents a specific sound. A syllable is
composed of two or three parts: the initial consonants, the vowels, and the optional
last consonants. With Hangul, syllables can be treated as the basic units on which
text processing is done. For example, a delete operation may work on a phonetic
280
Locales and Internationalized
Text Functions
symbol or a syllable. Korean code sets include several thousands of these syllables.
A user types the phonetic symbols that make up the syllables of the words to be
entered. The display may change as each phonetic symbol is entered. For example,
when the second phonetic symbol of a syllable is entered, the first phonetic symbol
may change its shape and size. Likewise, when the third phonetic symbol is entered,
the first two phonetic symbols may change their shape and size.
Not all languages rely solely on alphabetic or phonetic systems. Some languages,
including Japanese and Korean, employ an ideographic writing system. In an
ideographic system, rather than taking a small set of symbols and combining
them in different ways to create words, each word consists of one unique symbol
(or, occasionally, several symbols). The number of symbols can be very large:
approximately 50,000 have been identified in Hanzi, the Chinese ideographic
system.
Two major aspects of ideographic systems impact their use with computers. First,
the standard computer character sets in Japan, China, and Korea include roughly
8,000 characters, while sets in Taiwan have between 15,000 and 30,000 characters.
This makes it necessary to use more than one byte to represent a character. Second,
it obviously is impractical to have a keyboard that includes all of a given language's
ideographic symbols. Therefore, a mechanism is required for entering characters so
that a keyboard with a reasonable number of keys can be used. Those input methods
are usually based on phonetics, but there also exist methods based on the graphical
properties of characters.
In Japan, both Kana and the ideographic system Kanji are used. In Korea, Hangul
and sometimes the ideographic system Hanja are used. Now consider entering
ideographs in Japan, Korea, China, and Taiwan.
In Japan, either Kana or English characters are typed and then a region is selected
(sometimes automatically) for conversion to Kanji. Several Kanji characters may
have the same phonetic representation. If that is the case with the string entered,
a menu of characters is presented and the user must choose the appropriate one. If
no choice is necessary or a preference has been established, the input method does
the substitution directly. When Latin characters are converted to Kana or Kanji, it
is called a romaji conversion.
In Korea, it is usually acceptable to keep Korean text in Hangul form, but some
people may choose to write Hanja-originated words in Hanja rather than in Hangul.
To change Hangul to Hanja, the user selects a region for conversion and then follows
the same basic method as that described for Japanese.
Probably because there are well-accepted phonetic writing systems for Japanese
and Korean, computer input methods in these countries for entering ideographs are
fairly standard. Keyboard keys have both English characters and phonetic symbols
engraved on them, and the user can switch between the two sets.
The situation is different for Chinese. While there is a phonetic system called Pinyin
promoted by authorities, there is no consensus for entering Chinese text. Some
vendors use a phonetic decomposition (Pinyin or another), others use ideographic
decomposition of Chinese words, with various implementations and keyboard
layouts. There are about 16 known methods, none of which is a clear standard.
Also, there are actually two ideographic sets used: Traditional Chinese (the original
written Chinese) and Simplified Chinese. Several years ago, the People's Republic of
281
Locales and Internationalized
Text Functions
Input methods may require one or more areas in which to show the feedback of the
actual keystrokes, to propose disambiguation to the user, to list dictionaries, and so
on. The input method areas of concern are as follows:
• The status area is a logical extension of the LEDs that exist on the physical
keyboard. It is a window that is intended to present the internal state of the input
method that is critical to the user. The status area may consist of text data and
bitmaps or some combination.
• The preedit area displays the intermediate text for those languages that are
composing prior to the client handling the data.
• The auxiliary area is used for pop-up menus and customizing dialogs that may be
required for an input method. There may be multiple auxiliary areas for an input
method. Auxiliary areas are managed by the input method independent of the
client. Auxiliary areas are assumed to be separate dialogs, which are maintained
by the input method.
There are various user interaction styles used for preediting. The ones supported
by Xlib are as follows:
• For on-the-spot input methods, preediting data will be displayed directly in the
application window. Application data is moved to allow preedit data to appear at
the point of insertion.
• Off-the-spot preediting means that the preedit window is inside the application
window but not at the point of insertion. Often, this type of window is placed at
the bottom of the application window.
• Root-window preediting refers to input methods that use a preedit window that
is the child of RootWindow.
282
Locales and Internationalized
Text Functions
For a given language, the user can choose, to some extent, the user interface style
of input method (if choice is possible among several).
A single input server may be used for one or more languages, supporting one or
more encoding schemes. But the strings returned from an input method will always
be encoded in the (single) locale associated with the XIM object.
Input Contexts
Xlib provides the ability to manage a multi-threaded state for text input. A client may
be using multiple windows, each window with multiple text entry areas, and the user
possibly switching among them at any time. The abstraction for representing the
state of a particular input thread is called an input context. The Xlib representation
of an input context is an XIC.
An input context is the abstraction retaining the state, properties, and semantics
of communication between a client and an input method. An input context is a
combination of an input method, a locale specifying the encoding of the character
strings to be returned, a client window, internal state information, and various
layout or appearance characteristics. The input context concept somewhat matches
for input the graphics context abstraction defined for graphics output.
One input context belongs to exactly one input method. Different input contexts may
be associated with the same input method, possibly with the same client window.
283
Locales and Internationalized
Text Functions
An XIC is created with the XCreateIC function, providing an XIM argument and
affiliating the input context to the input method for its lifetime. When an input
method is closed with XCloseIM, all of its affiliated input contexts should not be used
any more (and should preferably be destroyed before closing the input method).
Considering the example of a client window with multiple text entry areas, the
application programmer could, for example, choose to implement as follows:
• As many input contexts are created as text entry areas, and the client will get the
input accumulated on each context each time it looks up in that context.
Focus Management
For each text entry area in which the XmbLookupString or XwcLookupString
functions are used, there will be an associated input context.
When the application focus moves to a text entry area, the application must set the
input context focus to the input context associated with that area. The input context
focus is set by calling XSetICFocus with the appropriate input context.
Also, when the application focus moves out of a text entry area, the application
should unset the focus for the associated input context by calling XUnsetICFocus.
As an optimization, if XSetICFocus is called successively on two different input
contexts, setting the focus on the second will automatically unset the focus on the
first.
To set and unset the input context focus correctly, it is necessary to track
application-level focus changes. Such focus changes do not necessarily correspond
to X server focus changes.
If a single input context is being used to do input for multiple text entry areas, it
will also be necessary to set the focus window of the input context whenever the
focus window changes (see section 13.5.6.3).
Geometry Management
In most input method architectures (on-the-spot being the notable exception), the
input method will perform the display of its own data. To provide better visual
locality, it is often desirable to have the input method areas embedded within a
client. To do this, the client may need to allocate space for an input method. Xlib
provides support that allows the size and position of input method areas to be
284
Locales and Internationalized
Text Functions
provided by a client. The input method areas that are supported for geometry
management are the status area and the preedit area.
• The client is responsible for the geometry of the input method window.
• The input method is responsible for the contents of the input method window.
An input method is able to suggest a size to the client, but it cannot suggest a
placement. Also the input method can only suggest a size. It does not determine the
size, and it must accept the size it is given.
After a client has established with the input method that it will do geometry
management, the client must negotiate the geometry with the input method. The
geometry is negotiated by the following steps:
• The client suggests an area to the input method by setting the XNAreaNeeded
value for that area. If the client has no constraints for the input method, it either
will not suggest an area or will set the width and height to zero. Otherwise, it will
set one of the values.
• The client will get the XIC value XNAreaNeeded. The input method will return
its suggested size in this value. The input method should pay attention to any
constraints suggested by the client.
• The client sets the XIC value XNArea to inform the input method of the geometry
of its window. The client should try to honor the geometry requested by the input
method. The input method must accept this geometry.
Clients doing geometry management must be aware that setting other XIC values
may affect the geometry desired by an input method. For example, XNFontSet and
XNLineSpace may change the geometry desired by the input method.
The table of XIC values (see section 13.5.6) indicates the values that can cause the
desired geometry to change when they are set. It is the responsibility of the client
to renegotiate the geometry of the input method window when it is needed.
Event Filtering
A filtering mechanism is provided to allow input methods to capture X
events transparently to clients. It is expected that toolkits (or clients) using
XmbLookupString or XwcLookupString will call this filter at some point in the event
processing mechanism to make sure that events needed by an input method can be
filtered by that input method.
285
Locales and Internationalized
Text Functions
If there were no filter, a client could receive and discard events that are necessary
for the proper functioning of an input method. The following provides a few
examples of such events:
• Key events can be sent to a filter before they are bound to translations such as
those the X Toolkit Intrinsics library provides.
Clients are expected to get the XIC value XNFilterEvents and augment the event
mask for the client window with that event mask. This mask may be zero.
Callbacks
When an on-the-spot input method is implemented, only the client can insert or
delete preedit data in place and possibly scroll existing text. This means that the
echo of the keystrokes has to be achieved by the client itself, tightly coupled with
the input method logic.
There are a number of cases where the input method logic has to call back the
client. Each of those cases is associated with a well-defined callback action. It is
possible for the client to specify, for each input context, what callback is to be called
for each action.
There are also callbacks provided for feedback of status information and a callback
to initiate a geometry request for an input method.
286
Locales and Internationalized
Text Functions
The need for string conversion is based on language needs and input method
capabilities. The following are some examples of string conversion:
Context-sensitive conversions just need a copy of the client's text, while other
conversions replace the client's text with new text to achieve the reconversion or
287
Locales and Internationalized
Text Functions
transliteration. Yet in all cases the result of a conversion, either immediately or via
preediting, is returned by the XmbLookupString and XwcLookupString functions.
The difference between these two values is whether the conversion is invoked by
the client or the input method. The XNStringConversion XIC value is used by clients
to request a string conversion from the input method. The client is responsible for
determining which events are used to trigger the string conversion and whether
the string to be converted should be copied or deleted. The type of conversion is
determined by the input method; the client can only pass the string to be converted.
The client is guaranteed that no XNStringConversionCallback will be issued when
this value is set; thus, the client need only set one of these values.
The XNStringConversionCallback XIC value is used by the client to notify the input
method that it will accept requests from the input method for string conversion.
If this value is set, it is the input method's responsibility to determine which
events are used to trigger the string conversion. When such events occur, the
input method issues a call to the client-supplied procedure to retrieve the string
to be converted. The client's callback procedure is notified whether to copy or
delete the string and is provided with hints as to the amount of text needed. The
XIMStringConversionCallbackStruct specifies which text should be passed back to
the input method.
• If the X server, IM server, and X clients are started asynchronously, some clients
may attempt to connect to the IM server before it is fully operational, and fail.
Therefore, some mechanism is needed to allow clients to detect when an IM server
has started.
• Some input methods may allow the underlying IM server to be switched. Such
customization may be desired without restarting the entire client.
288
Locales and Internationalized
Text Functions
Input methods that support switching of IM servers may exhibit some side-effects:
• The input method will ensure that any new IM server supports any of the input
styles being used by input contexts already associated with the input method.
However, the list of supported input styles may be different.
Hot Keys
Some clients need to guarantee which keys can be used to escape from the input
method, regardless of the input method state; for example, the client-specific Help
key or the keys to move the input focus. The HotKey mechanism allows clients
to specify a set of keys for this purpose. However, the input method might not
allow clients to specify hot keys. Therefore, clients have to query support of hot
keys by checking the supported XIC values list by calling XGetIMValues with the
XNQueryICValuesList IM value. When the hot keys specified conflict with the key
bindings of the input method, hot keys take precedence over the key bindings of
the input method.
289
Locales and Internationalized
Text Functions
provides the ability for an application to manage the preedit state programmatically.
Two methods are provided for retrieving the preedit state of an input context. One
method is to query the state by calling XGetICValues with the XNPreeditState
XIC value. Another method is to receive notification whenever the preedit state is
changed. To receive such notification, an application needs to register a callback
by calling XSetICValues with the XNPreeditStateNotifyCallback XIC value. In
order to change the preedit state programmatically, an application needs to call
XSetICValues with XNPreeditState.
Availability of the preedit state is input method dependent. The input method may
not provide the ability to set the state or to retrieve the state programmatically.
Therefore, clients have to query availability of preedit state operations by
checking the supported XIC values list by calling XGetIMValues with the
XNQueryICValuesList IM value.
The XOpenIM function opens an input method, matching the current locale and
modifiers specification. Current locale and modifiers are bound to the input
method at opening time. The locale associated with an input method cannot be
changed dynamically. This implies that the strings returned by XmbLookupString or
XwcLookupString, for any input context affiliated with a given input method, will
be encoded in the locale current at the time the input method is opened.
The specific input method to which this call will be routed is identified on the basis
of the current locale. XOpenIM will identify a default input method corresponding
to the current locale. That default can be modified using XSetLocaleModifiers for
the input method modifier.
The db argument is the resource database to be used by the input method for
looking up resources that are private to the input method. It is not intended that this
database be used to look up values that can be set as IC values in an input context.
If db is NULL, no database is passed to the input method.
The res_name and res_class arguments specify the resource name and class of the
application. They are intended to be used as prefixes by the input method when
looking up resources that are common to all input contexts that may be created
for this input method. The characters used for resource names and classes must be
in the X Portable Character Set. The resources looked up are not fully specified if
res_name or res_class is NULL.
The res_name and res_class arguments are not assumed to exist beyond the call
to XOpenIM. The specified resource database is assumed to exist for the lifetime of
the input method.
290
Locales and Internationalized
Text Functions
Status XCloseIM(im);
char *XSetIMValues(im);
char *XGetIMValues(im);
... Specifies the variable length argument list to get XIM values.
Each XIM value argument (following a name) must point to a location where the
XIM value is to be stored. That is, if the XIM value is of type T, the argument must
be of type T*. If T itself is a pointer type, then XGetIMValues allocates memory to
store the actual data, and the client is responsible for freeing this data by calling
XFree with the returned pointer.
Display *XDisplayOfIM(im);
The XDisplayOfIM function returns the display associated with the specified input
method.
char *XLocaleOfIM(im);
291
Locales and Internationalized
Text Functions
The XLocaleOfIM function returns the locale associated with the specified input
method.
call_data Not used for this callback and always passed as NULL.
292
Locales and Internationalized
Text Functions
Key Explanation
D This value may be set using XSetIMValues. If it is not set, a
default is provided.
S This value may be set using XSetIMValues.
G This value may be read using XGetIMValues.
If the client cannot find an input style that it can support, it should negotiate with
the user the continuation of the program (exit, choose another input method, and
so on).
The argument value must be a pointer to a location where the returned value will
be stored. The returned value is a pointer to a structure of type XIMStyles. Clients
are responsible for freeing the XIMStyles structure. To do so, use XFree.
293
Locales and Internationalized
Text Functions
typedef struct {
unsigned short count_styles;
XIMStyle * supported_styles;
} XIMStyles;
The preedit category defines what type of support is provided by the input method
for preedit information.
The status category defines what type of support is provided by the input method
for status information.
294
Locales and Internationalized
Text Functions
It is not intended that values that can be set as XIM values be set as resources.
Destroy Callback
The XNDestroyCallback argument is a pointer to a structure of type XIMCallback.
XNDestroyCallback is triggered when an input method stops its service for any
reason. After the callback is invoked, the input method is closed and the associated
input context(s) are destroyed by Xlib. Therefore, the client should not call XCloseIM
or XDestroyIC.
call_data Not used for this callback and always passed as NULL.
The argument value must be a pointer to a location where the returned value will be
stored. The returned value is a pointer to a structure of type XIMValuesList. Clients
are responsible for freeing the XIMValuesList structure. To do so, use XFree.
295
Locales and Internationalized
Text Functions
typedef struct {
unsigned short count_values;
char **supported_values;
} XIMValuesList;
Visible Position
The XNVisiblePosition argument indicates whether the visible position masks of
XIMFeedback in XIMText are available.
The argument value must be a pointer to a location where the returned value will
be stored. The returned value is of type Bool. If the returned value is True, the input
method uses the visible position masks of XIMFeedback in XIMText; otherwise, the
input method does not use the masks.
Because this XIM value is optional, a client should call XGetIMValues with argument
XNQueryIMValuesList before using this argument. If the XNVisiblePosition does not
exist in the IM values list returned from XNQueryIMValuesList, the visible position
masks of XIMFeedback in XIMText are not used to indicate the visible position.
The value is of type Bool. When querying for XNR6PreeditCallback, if the returned
value is True, the input method uses the Release 6 behavior; otherwise, it uses the
Release 5 behavior. The default value is False. In order to use Release 6 semantics,
the value of XNR6PreeditCallback must be set to True.
Because this XIM value is optional, a client should call XGetIMValues with argument
XNQueryIMValuesList before using this argument. If the XNR6PreeditCallback
does not exist in the IM values list returned from XNQueryIMValuesList, the
PreeditCallback behavior is Release 5 semantics.
296
Locales and Internationalized
Text Functions
may be multiple input contexts for one input method. The programming interfaces
for creating, reading, or modifying an input context use a variable argument list. The
name elements of the argument lists are referred to as XIC values. It is intended that
input methods be controlled by these XIC values. As new XIC values are created,
they should be registered with the X Consortium.
XIC XCreateIC(im);
... Specifies the variable length argument list to set XIC values.
The XCreateIC function creates a context within the specified input method.
Some of the arguments are mandatory at creation time, and the input context will
not be created if those arguments are not provided. The mandatory arguments are
the input style and the set of text callbacks (if the input style selected requires
callbacks). All other input context values can be set later.
XCreateIC returns a NULL value if no input context could be created. A NULL value
could be returned for any of the following reasons:
void XDestroyIC(ic);
To communicate to and synchronize with input method for any changes in keyboard
focus from the client side, use XSetICFocus and XUnsetICFocus.
void XSetICFocus(ic);
The XSetICFocus function allows a client to notify an input method that the
focus window attached to the specified input context has received keyboard focus.
The input method should take action to provide appropriate feedback. Complete
feedback specification is a matter of user interface policy.
297
Locales and Internationalized
Text Functions
void XUnsetICFocus(ic);
The XUnsetICFocus function allows a client to notify an input method that the
specified input context has lost the keyboard focus and that no more input
is expected on the focus window attached to that input context. The input
method should take action to provide appropriate feedback. Complete feedback
specification is a matter of user interface policy.
Calling XUnsetICFocus does not affect the focus window value; the client may still
receive events from the input method that are directed to the focus window.
To reset the state of an input context to its initial state, use XmbResetIC or
XwcResetIC.
char *XmbResetIC(ic);
wchar_t *XwcResetIC(ic);
The return value of XmbResetIC is its current preedit string as a multibyte string. If
there is any preedit text drawn or visible to the user, then these procedures must
return a non-NULL string. If there is no visible preedit text, then it is input method
implementation-dependent whether these procedures return a non-NULL string or
NULL.
To get the input method associated with an input context, use XIMOfIC.
XIM XIMOfIC(ic);
The XIMOfIC function returns the input method associated with the specified input
context.
Xlib provides two functions for setting and reading XIC values, respectively,
XSetICValues and XGetICValues. Both functions have a variable-length argument
list. In that argument list, any XIC value's name must be denoted with a character
string using the X Portable Character Set.
char *XSetICValues(ic);
298
Locales and Internationalized
Text Functions
... Specifies the variable length argument list to set XIC values.
Each value to be set must be an appropriate datum, matching the data type imposed
by the semantics of the argument.
char *XGetICValues(ic);
... Specifies the variable length argument list to get XIC values.
Each IC attribute value argument (following a name) must point to a location where
the IC value is to be stored. That is, if the IC value is of type T, the argument must
be of type T*. If T itself is a pointer type, then XGetICValues allocates memory to
store the actual data, and the client is responsible for freeing this data by calling
XFree with the returned pointer. The exception to this rule is for an IC value of type
XVaNestedList (for preedit and status attributes). In this case, the argument must
also be of type XVaNestedList. Then, the rule of changing type T to T* and freeing
the allocated data applies to each element of the nested list.
The first column lists the XIC values. The second column indicates which values
are involved in affecting, negotiating, and setting the geometry of the input method
windows. The subentries under the third column indicate the different input styles
that are supported. Each of these columns indicates how each of the XIC values are
treated by that input style.
299
Locales and Internationalized
Text Functions
Key Explanation
C This value must be set with XCreateIC.
D This value may be set using XCreateIC.> If it is not set,> a
default is provided.
G This value may be read using XGetICValues.
GN This value may cause geometry negotiation when its value is set
by means of XCreateIC or XSetICValues.
GR This value will be the response of the input method when any
GN value is changed.
GS This value will cause the geometry of the input method window
to be set.
O This value must be set once and only once. It need not be set at
create time.
S This value may be set with XSetICValues.
Ignored This value is ignored by the input method for the given input
style.
300
Locales and Internationalized
Text Functions
301
Locales and Internationalized
Text Functions
Input Style
The XNInputStyle argument specifies the input style to be used. The value of this
argument must be one of the values returned by the XGetIMValues function with
the XNQueryInputStyle argument specified in the supported_styles list.
Note that this argument must be set at creation time and cannot be changed.
Client Window
The XNClientWindow argument specifies to the input method the client window in
which the input method can display data or create subwindows. Geometry values
for input method areas are given with respect to the client window. Dynamic change
of client window is not supported. This argument may be set only once and should
be set before any input is done using this input context. If it is not set, the input
method may not operate correctly.
If an attempt is made to set this value a second time with XSetICValues, the string
XNClientWindow will be returned by XSetICValues, and the client window will not
be changed.
If the client window is not a valid window ID on the display attached to the input
method, a BadWindow error can be generated when this value is used by the input
method.
Focus Window
The XNFocusWindow argument specifies the focus window. The primary purpose
of the XNFocusWindow is to identify the window that will receive the key event
when input is composed. In addition, the input method may possibly affect the focus
window as follows:
• Select events on it
302
Locales and Internationalized
Text Functions
• Send events to it
The associated value must be of type Window. If the focus window is not a valid
window ID on the display attached to the input method, a BadWindow error can be
generated when this value is used by the input method.
When this XIC value is left unspecified, the input method will use the client window
as the default focus window.
It is not intended that values that can be set as XIC values be set as resources.
Geometry Callback
The XNGeometryCallback argument is a structure of type XIMCallback (see section
13.5.6.13.12).
Filter Events
The XNFilterEvents argument returns the event mask that an input method needs
to have selected for. The client is expected to augment its own event mask for the
client window with this one.
This argument is read-only, is set by the input method at create time, and is never
changed.
The type of this argument is unsigned long. Setting this value will cause an error.
Destroy Callback
The XNDestroyCallback argument is a pointer to a structure of type XIMCallback
(see section 13.5.6.13.12). This callback is triggered when the input method stops
its service for any reason; for example, when a connection to an IM server is broken.
After the destroy callback is called, the input context is destroyed and the input
method is closed. Therefore, the client should not call XDestroyIC and XCloseIM.
303
Locales and Internationalized
Text Functions
Because this XIC value is optional, a client should call XGetIMValues with argument
XNQueryICValuesList before using this argument.
String Conversion
The XNStringConversion argument is a structure of type XIMStringConversionText.
Because this XIC value is optional, a client should call XGetIMValues with argument
XNQueryICValuesList before using this argument.
The feedback member is reserved for future use. The text to be converted is defined
by the string and length members. The length is indicated in characters. To prevent
the library from freeing memory pointed to by an uninitialized pointer, the client
should set the feedback element to NULL.
Reset State
The XNResetState argument specifies the state the input context will return to after
calling XmbResetIC or XwcResetIC.
304
Locales and Internationalized
Text Functions
The XIC state may be set to its initial state, as specified by the XNPreeditState value
when XCreateIC was called, or it may be set to preserve the current state.
If XIMInitialState is set, then XmbResetIC and XwcResetIC will return to the initial
XNPreeditState state of the XIC.
Because this XIC value is optional, a client should call XGetIMValues with argument
XNQueryICValuesList before using this argument.
Hot Keys
The XNHotKey argument specifies the hot key list to the XIC. The hot key list is a
pointer to the structure of type XIMHotKeyTriggers, which specifies the key events
that must be received without any interruption of the input method. For the hot key
list set with this argument to be utilized, the client must also set XNHotKeyState
to XIMHotKeyStateON.
Because this XIC value is optional, a client should call XGetIMValues with argument
XNQueryICValuesList before using this functionality.
If an event for a key in the hot key list is found, then the process will receive the
event and it will be processed inside the client.
typedef struct {
KeySym keysym;
unsigned int modifier;
unsigned int modifier_mask;
} XIMHotKeyTrigger;
typedef struct {
305
Locales and Internationalized
Text Functions
int num_hot_key;
XIMHotKeyTrigger *key;
} XIMHotKeyTriggers;
The combination of modifier and modifier_mask are used to represent one of three
states for each modifier: either the modifier must be on, or the modifier must be off,
or the modifier is a ``don't care'' - it may be on or off. When a modifier_mask bit
is set to 0, the state of the associated modifier is ignored when evaluating whether
the key is hot or not.
Area
The value of the XNArea argument must be a pointer to a structure of type
XRectangle. The interpretation of the XNArea argument is dependent on the input
method style that has been set.
306
Locales and Internationalized
Text Functions
If XNArea is not specified, is set to NULL, or is invalid, the input method will default
the clipping region to the geometry of the XNFocusWindow. If the area specified is
NULL or invalid, the results are undefined.
Area Needed
When set, the XNAreaNeeded argument specifies the geometry suggested by the
client for this area (preedit or status). The value associated with the argument must
be a pointer to a structure of type XRectangle. Note that the x, y values are not
used and that nonzero values for width or height are the constraints that the client
wishes the input method to respect.
When read, the XNAreaNeeded argument specifies the preferred geometry desired
by the input method for the area.
Spot Location
The XNSpotLocation argument specifies to the input method the coordinates
of the spot to be used by an input method executing with XNInputStyle
set to XIMPreeditPosition. When specified to any input method other than
XIMPreeditPosition, this XIC value is ignored.
The x coordinate specifies the position where the next character would be inserted.
The y coordinate is the position of the baseline used by the current text line in the
focus window. The x and y coordinates are relative to the focus window, if it has been
set; otherwise, they are relative to the client window. If neither the focus window
nor the client window has been set, the results are undefined.
Colormap
Two different arguments can be used to indicate what colormap the input method
should use to allocate colors, a colormap ID, or a standard colormap name.
The XNColormap argument is used to specify a colormap ID. The argument value
is of type Colormap. An invalid argument may generate a BadColor error when it
is used by the input method.
307
Locales and Internationalized
Text Functions
If the colormap is left unspecified, the client window colormap becomes the default.
If these values are left unspecified, the default is determined by the input method.
Background Pixmap
The XNBackgroundPixmap argument specifies a background pixmap to be used
as the background of the window. The value must be of type Pixmap. An invalid
argument may generate a BadPixmap error when it is used by the input method.
If this value is left unspecified, the default is determined by the input method.
Font Set
The XNFontSet argument specifies to the input method what font set is to be used.
The argument value is of type XFontSet.
If this value is left unspecified, the default is determined by the input method.
Line Spacing
The XNLineSpace argument specifies to the input method what line spacing is to
be used in the preedit window if more than one line is to be used. This argument
is of type int.
If this value is left unspecified, the default is determined by the input method.
Cursor
The XNCursor argument specifies to the input method what cursor is to be used in
the specified window. This argument is of type Cursor.
An invalid argument may generate a BadCursor error when it is used by the input
method. If this value is left unspecified, the default is determined by the input
method.
Preedit State
The XNPreeditState argument specifies the state of input preediting for the input
method. Input preediting can be on or off.
#define XIMPreeditUnknown 0L
308
Locales and Internationalized
Text Functions
#define XIMPreeditEnable 1L
#define XIMPreeditDisable (1L<<1)
Because this XIC value is optional, a client should call XGetIMValues with argument
XNQueryICValuesList before using this argument.
Because this XIC value is optional, a client should call XGetIMValues with argument
XNQueryICValuesList before using this argument.
309
Locales and Internationalized
Text Functions
A client that wants to support the input style XIMStatusCallbacks must provide a
set of status callbacks to the input method. The set of status callbacks is as follows:
typedef struct {
XPointer client_data;
XIMProc callback;
} XIMCallback;
Each callback has some particular semantics and will carry the data that expresses
the environment necessary to the client into a specific data structure. This
paragraph only describes the arguments to be used to set the callback.
Setting any of these values while doing preedit may cause unexpected results.
Callbacks are mostly provided so that clients (or text editing packages) can
implement on-the-spot preediting in their own window. In that case, the input
method needs to communicate and synchronize with the client. The input method
needs to communicate changes in the preedit window when it is under control of
the client. Those callbacks allow the client to initialize the preedit area, display a
new preedit string, move the text insertion point during preedit, terminate preedit,
or update the status area.
310
Locales and Internationalized
Text Functions
The following paragraphs describe the programming semantics and specific data
structure associated with the different reasons.
Geometry Callback
The geometry callback is triggered by the input method to indicate that it wants the
client to negotiate geometry. The generic prototype is as follows:
call_data Not used for this callback and always passed as NULL.
Destroy Callback
The destroy callback is triggered by the input method when it stops service for any
reason. After the callback is invoked, the input context will be freed by Xlib. The
generic prototype is as follows:
call_data Not used for this callback and always passed as NULL.
311
Locales and Internationalized
Text Functions
The ending position of the text buffer is determined by the direction and
factor members. Specifically, it is the character position relative to the
starting point as defined by the XIMCaretDirection. The factor member of
XIMStringConversionCallbackStruct specifies the number of XIMCaretDirection
positions to be applied. For example, if the direction specifies XIMLineEnd and factor
is 1, then all characters from the starting position to the end of the current display
line are returned. If the direction specifies XIMForwardChar or XIMBackwardChar,
then the factor specifies a relative position, indicated in characters, from the
starting position.
312
Locales and Internationalized
Text Functions
call_data Not used for this callback and always passed as NULL.
When preedit starts on the specified input context, the callback is called with a
NULL call_data argument. PreeditStartCallback will return the maximum size
of the preedit string. A positive number indicates the maximum number of bytes
allowed in the preedit string, and a value of -1 indicates there is no limit.
call_data Not used for this callback and always passed as NULL.
When preedit stops on the specified input context, the callback is called with
a NULL call_data argument. The client can release the data allocated by
PreeditStartCallback.
313
Locales and Internationalized
Text Functions
The client must keep updating a buffer of the preedit text and the callback
arguments referring to indexes in that buffer. The call_data fields have specific
meanings according to the operation, as follows:
• To indicate text deletion, the call_data member specifies a NULL text field. The
text to be deleted is then the current text in the buffer from position chg_first
(starting at zero) on a character length of chg_length.
• A chg_length value of zero indicates that text must be inserted right at the position
specified by chg_first. A value of zero for chg_first specifies the first character in
the buffer.
Text: A B C D E
^ ^ ^ ^ ^ ^
CharPos: 0 1 2 3 4 5
The CharPos in the diagram shows the location of the character position relative
to the character.
314
Locales and Internationalized
Text Functions
• If the value of chg_first is 1 and the value of chg_length is 3, this says to replace
3 characters beginning at character position 1 with the string in the XIMText
structure. Hence, BCD would be replaced by the value in the structure.
• Though chg_length and chg_first are both signed integers they will never have a
negative value.
• The caret member identifies the character position before which the cursor should
be placed - after modification to the preedit buffer has been completed. For
example, if caret is zero, the cursor is at the beginning of the buffer. If the caret
is one, the cursor is between the first and second character.
• The feedback member indicates rendering type for each character in the string
member. If string is NULL (indicating that only highlighting of the existing preedit
buffer should be updated), feedback points to length highlight elements that
should be applied to the existing preedit buffer, beginning at chg_first.
The feedback member expresses the types of rendering feedback the callback
should apply when drawing text. Rendering of the text to be drawn is specified
either in generic ways (for example, primary, secondary) or in specific ways (reverse,
underline). When generic indications are given, the client is free to choose the
rendering style. It is necessary, however, that primary and secondary be mapped to
two distinct rendering styles.
315
Locales and Internationalized
Text Functions
indicates that the preedit text is preferably displayed from the caret position
in the preedit area backward, relative to the primary draw direction. The
XIMVisibleToCenter mask indicates that the preedit text is preferably displayed with
the caret position in the preedit area centered.
The insertion point of the preedit string could exist outside of the visible area when
visibility hints are used. Only one of the masks is valid for the entire preedit string,
and only one character can hold one of these feedbacks for a given input context
at one time. This feedback may be OR'ed together with another highlight (such
as XIMReverse). Only the most recently set feedback is valid, and any previous
feedback is automatically canceled. This is a hint to the client, and the client is free
to choose how to display the preedit string.
The feedback member also specifies how rendering of the text argument should be
performed. If the feedback is NULL, the callback should apply the same feedback
as is used for the surrounding characters in the preedit buffer; if chg_first is at
a highlight boundary, the client can choose which of the two highlights to use. If
feedback is not NULL, feedback specifies an array defining the rendering for each
character of the string, and the length of the array is thus length.
If an input method wants to indicate that it is only updating the feedback of the
preedit text without changing the content of it, the XIMText structure will contain
a NULL value for the string field, the number of characters affected (relative to
chg_first) will be in the length field, and the feedback field will point to an array
of XIMFeedback.
#define XIMReverse 1L
#define XIMUnderline (1L<<1)
#define XIMHighlight (1L<<2)
#define XIMPrimary (1L<<5)*
#define XIMSecondary (1L<<6)*
#define XIMTertiary (1L<<7)*
#define XIMVisibleToForward (1L<<8)
#define XIMVisibleToBackward (1L<<9)
#define XIMVisibleToCenter (1L<<10)
*† The values for XIMPrimary, XIMSecondary, and XIMTertiary were incorrectly define
the R5 specification. The X Consortium’s X11R5 implementation correctly
implemented the values for these highlights. The value of these highlights has
been corrected in this specification to agree with the values in the
Consortium’s X11R5 and X11R6 implementations.
316
Locales and Internationalized
Text Functions
and XIMTertiary highlights should be drawn in some unique manner that must
be different from XIMReverse and XIMUnderline. The values for XIMPrimary,
XIMSecondary, and XIMTertiary were incorrectly defined in the R5 specification.
The X Consortium's X11R5 implementation correctly implemented the values
for these highlights. The value of these highlights has been corrected in this
specification to agree with the values in the Consortium's X11R5 and X11R6
implementations.
The input method will trigger PreeditCaretCallback to move the text insertion
point during preedit. The call_data argument contains a pointer to an
XIMPreeditCaretCallbackStruct structure, which indicates where the caret should
be moved. The callback must move the insertion point to its new location and return,
in field position, the new offset value from the initial position.
typedef enum {
XIMIsInvisible, /* Disable caret feedback */
XIMIsPrimary, /* UI defined caret feedback */
XIMIsSecondary, /* UI defined caret feedback */
} XIMCaretStyle;
317
Locales and Internationalized
Text Functions
typedef enum {
XIMForwardChar, XIMBackwardChar,
XIMForwardWord, XIMBackwardWord,
XIMCaretUp, XIMCaretDown,
XIMNextLine, XIMPreviousLine,
XIMLineStart, XIMLineEnd,
XIMAbsolutePosition,
XIMDontChange,
} XIMCaretDirection;
Status Callbacks
An input method may communicate changes in the status of an input context
(for example, created, destroyed, or focus changes) with three status callbacks:
StatusStartCallback, StatusDoneCallback, and StatusDrawCallback.
When the input context is created or gains focus, the input method calls the
StatusStartCallback callback.
318
Locales and Internationalized
Text Functions
call_data Not used for this callback and always passed as NULL.
The callback should initialize appropriate data for displaying status and for
responding to StatusDrawCallback calls. Once StatusStartCallback is called, it will
not be called again before StatusDoneCallback has been called.
When an input context is destroyed or when it loses focus, the input method calls
StatusDoneCallback.
call_data Not used for this callback and always passed as NULL.
When an input context status has to be updated, the input method calls
StatusDrawCallback.
The callback should update the status area by either drawing a string or imaging
a bitmap in the status area.
typedef enum {
XIMTextType,
XIMBitmapType,
} XIMStatusDataType;
319
Locales and Internationalized
Text Functions
Event Filtering
Xlib provides the ability for an input method to register a filter internal to Xlib.
This filter is called by a client (or toolkit) by calling XFilterEvent after calling
XNextEvent. Any client that uses the XIM interface should call XFilterEvent to
allow input methods to process their events without knowledge of the client's
dispatching mechanism. A client's user interface policy may determine the priority
of event filters with respect to other event-handling mechanisms (for example,
modal grabs).
Clients may not know how many filters there are, if any, and what they do. They may
only know if an event has been filtered on return of XFilterEvent. Clients should
discard filtered events.
If the window argument is None, XFilterEvent applies the filter to the window
specified in the XEvent structure. The window argument is provided so that layers
above Xlib that do event redirection can indicate to which window an event has
been redirected.
If XFilterEvent returns True, then some input method has filtered the event, and
the client should discard the event. If XFilterEvent returns False, then the client
should continue processing the event.
If a grab has occurred in the client and XFilterEvent returns True, the client should
ungrab the keyboard.
bytes_buffer
320
Locales and Internationalized
Text Functions
The XmbLookupString and XwcLookupString functions return the string from the
input method specified in the buffer_return argument. If no string is returned, the
buffer_return argument is unchanged.
The KeySym into which the KeyCode from the event was mapped is returned in the
keysym_return argument if it is non-NULL and the status_return argument indicates
that a KeySym was returned. If both a string and a KeySym are returned, the KeySym
value does not necessarily correspond to the string returned.
Note
To insure proper input processing, it is essential that the client pass only
KeyPress events to XmbLookupString and XwcLookupString. Their behavior
when a client passes a KeyRelease event is undefined.
Clients should check the status_return argument before using the other returned
values. These two functions both return a value to status_return that indicates what
has been returned in the other arguments. The possible values returned are:
321
Locales and Internationalized
Text Functions
It does not make any difference if the input context passed as an argument to
XmbLookupString and XwcLookupString is the one currently in possession of the
focus or not. Input may have been composed within an input context before it lost
the focus, and that input may be returned on subsequent calls to XmbLookupString
or XwcLookupString even though it does not have any more keyboard focus.
Client Conventions
A well-behaved client (or toolkit) should first query the input method style. If the
client cannot satisfy the requirements of the supported styles (in terms of geometry
management or callbacks), it should negotiate with the user continuation of the
program or raise an exception or error of some sort.
Synchronization Conventions
A KeyPress event with a KeyCode of zero is used exclusively as a signal that an
input method has composed input that can be returned by XmbLookupString or
XwcLookupString. No other use is made of a KeyPress event with KeyCode of zero.
• An artificial event created by a input method filter and pushed onto a client's
event queue
When callback support is specified by the client, input methods will not take action
unless they explicitly called back the client and obtained no response (the callback
is not specified or returned invalid data).
String Constants
The following symbols for string constants are defined in <X11/Xlib.h>. Although
they are shown here with particular macro definitions, they may be implemented
as macros, as global symbols, or as a mixture of the two. The string pointer value
itself is not significant; clients must not assume that inequality of two values implies
inequality of the actual string data.
322
Locales and Internationalized
Text Functions
323
Chapter 14. Inter-Client
Communication Functions
The Inter-Client Communication Conventions Manual, hereafter referred to as the
ICCCM, details the X Consortium approved conventions that govern inter-client
communications. These conventions ensure peer-to-peer client cooperation in the
use of selections, cut buffers, and shared resources as well as client cooperation
with window and session managers. For further information, see the Inter-Client
Communication Conventions Manual.
Xlib provides a number of standard properties and programming interfaces that are
ICCCM compliant. The predefined atoms for some of these properties are defined
in the <X11/Xatom.h> header file, where to avoid name conflicts with user symbols
their #define name has an XA_ prefix. For further information about atoms and
properties, see section 4.3.
Xlib’s selection and cut buffer mechanisms provide the primary programming
interfaces by which peer client applications communicate with each other (see
sections 4.5 and 16.6). The functions discussed in this chapter provide the primary
programming interfaces by which client applications communicate with their
window and session managers as well as share standard colormaps.
The standard properties that are of special interest for communicating with window
and session managers are:
324
Inter-Client
Communication Functions
• Standard colormaps
326
Inter-Client
Communication Functions
The XWithdrawWindow function unmaps the specified window and sends a synthetic
UnmapNotify event to the root window of the specified screen. Window managers
may elect to receive this message and may treat it as a request to change the
window's state to withdrawn. When a window is in the withdrawn state, neither its
normal nor its iconic representations is visible. It returns a nonzero status if the
UnmapNotify event is successfully sent; otherwise, it returns a zero status.
327
Inter-Client
Communication Functions
typedef struct {
unsigned char *value; /* property data */
Atom encoding; /* type of property */
int format; /* 8, 16, or 32 */
unsigned long nitems; /* number of items in value */
} XTextProperty;
Xlib provides functions to convert localized text to or from encodings that support
the inter-client communication conventions for text. In addition, functions are
provided for converting between lists of pointers to character strings and text
properties in the STRING encoding.
The functions for localized text return a signed integer error status that encodes
Success as zero, specific error conditions as negative numbers, and partial
conversion as a count of unconvertible characters.
#define #XNoMemory -1
#define #XLocaleNotSupported -2
#define #XConverterNotFound -3
typedef enum {
XStringStyle, /* STRING */
XCompoundTextStyle, /* COMPOUND_TEXT */
XTextStyle, /* text in owner's encoding (current locale) */
XStdICCTextStyle /* STRING, else COMPOUND_TEXT */
} XICCEncodingStyle;
328
Inter-Client
Communication Functions
The functions set the encoding field of text_prop_return to an Atom for the
specified display naming the encoding determined by the specified style and convert
the specified text list to this encoding for storage in the text_prop_return value
field. If the style XStringStyle or XCompoundTextStyle is specified, this encoding
is ``STRING'' or ``COMPOUND_TEXT'', respectively. If the style XTextStyle
is specified, this encoding is the encoding of the current locale. If the style
XStdICCTextStyle is specified, this encoding is ``STRING'' if the text is fully
convertible to STRING, else ``COMPOUND_TEXT''.
If insufficient memory is available for the new value string, the functions
return XNoMemory. If the current locale is not supported, the functions return
XLocaleNotSupported. In both of these error cases, the functions do not set
text_prop_return.
If the supplied text is not fully convertible to the specified encoding, the functions
return the number of unconvertible characters. Each unconvertible character
is converted to an implementation-defined and encoding-specific default string.
Otherwise, the functions return Success. Note that full convertibility to all styles
except XStringStyle is guaranteed.
329
Inter-Client
Communication Functions
Multiple elements of the property (for example, the strings in a disjoint text
selection) are separated by a null byte. The contents of the property are not
required to be null-terminated; any terminating null should not be included in
text_prop.nitems.
If the value field of text_prop is not fully convertible to the encoding of the
current locale, the functions return the number of unconvertible characters. Each
unconvertible character is converted to a string in the current locale that is specific
to the current locale. To obtain the value of this string, use XDefaultString.
Otherwise, XmbTextPropertyToTextList and XwcTextPropertyToTextList return
Success.
To free the storage for the list and its contents returned by
XmbTextPropertyToTextList, use XFreeStringList. To free the storage for
the list and its contents returned by XwcTextPropertyToTextList, use
XwcFreeStringList.
To free the in-memory data associated with the specified wide character string list,
use XwcFreeStringList.
void XwcFreeStringList(list);
To obtain the default string for text conversion in the current locale, use
char *XDefaultString();
The XDefaultString function returns the default string used by Xlib for text
conversion (for example, in XmbTextPropertyToTextList). The default string is the
string in the current locale that is output when an unconvertible character is found
during text conversion. If the string returned by XDefaultString is the empty string
(""), no character is output in the converted text. XDefaultString does not return
NULL.
The string returned by XDefaultString is independent of the default string for text
drawing; see XCreateFontSet to obtain the default string for an XFontSet.
330
Inter-Client
Communication Functions
The behavior when an invalid codepoint is supplied to any Xlib function is undefined.
To free the in-memory data associated with the specified string list, use
XFreeStringList.
void XFreeStringList(list);
331
Inter-Client
Communication Functions
The XSetTextProperty function replaces the existing specified property for the
named window with the data, type, format, and number of items determined by the
value field, the encoding field, the format field, and the nitems field, respectively,
of the specified XTextProperty structure. If the property does not already exist,
XSetTextProperty sets it for the specified window.
The XGetTextProperty function reads the specified property from the window and
stores the data in the returned XTextProperty structure. It stores the data in the
value field, the type of the data in the encoding field, the format of the data in the
format field, and the number of items of data in the nitems field. An extra byte
containing null (which is not included in the nitems member) is stored at the end of
the value field of text_prop_return. The particular interpretation of the property's
encoding and data as text is left to the calling application. If the specified property
does not exist on the window, XGetTextProperty sets the value field to NULL, the
encoding field to None, the format field to zero, and the nitems field to zero.
If it was able to read and store the data in the XTextProperty structure,
XGetTextProperty returns a nonzero status; otherwise, it returns a zero status.
332
Inter-Client
Communication Functions
To set a window's WM_NAME property with the supplied convenience function, use
XSetWMName.
The following two functions have been superseded by XSetWMName and XGetWMName,
respectively. You can use these additional convenience functions for window names
that are encoded as STRING properties.
XStoreName(display, w, window_name);
The XStoreName function assigns the name passed to window_name to the specified
window. A window manager can display the window name in some prominent
place, such as the title bar, to allow users to identify windows easily. Some
window managers may display a window's name in the window's icon, although
they are encouraged to use the window's icon name if one is provided by the
application. If the string is not in the Host Portable Character Encoding, the result
is implementation-dependent.
333
Inter-Client
Communication Functions
The XFetchName function returns the name of the specified window. If it succeeds,
it returns a nonzero status; otherwise, no name has been set for the window,
and it returns zero. If the WM_NAME property has not been set for this window,
XFetchName sets window_name_return to NULL. If the data returned by the server
is in the Latin Portable Character Encoding, then the returned string is in the Host
Portable Character Encoding. Otherwise, the result is implementation-dependent.
When finished with it, a client must free the window name string using XFree.
334
Inter-Client
Communication Functions
XSetIconName(display, w, icon_name);
If the string is not in the Host Portable Character Encoding, the result is
implementation-dependent. XSetIconName can generate BadAlloc and BadWindow
errors.
To get the name a window wants displayed in its icon, use XGetIconName.
XWMHints *XAllocWMHints();
335
Inter-Client
Communication Functions
/* Values */
typedef struct {
long flags; /* marks which fields in this structure are defined */
Bool input; /* does this application rely on the window manager to
get keyboard input? */
int initial_state; /* see below */
Pixmap icon_pixmap; /* pixmap to be used as icon */
Window icon_window; /* window to be used as icon */
int icon_x, icon_y; /* initial position of icon */
Pixmap icon_mask; /* pixmap to be used as mask for icon_pixmap */
XID window_group; /* id of related window group */
/* this structure may be extended in the future */
} XWMHints;
The input member is used to communicate to the window manager the input focus
model used by the application. Applications that expect input but never explicitly set
focus to any of their subwindows (that is, use the push model of focus management),
such as X Version 10 style applications that use real-estate driven focus, should set
this member to True. Similarly, applications that set input focus to their subwindows
only when it is given to their top-level window by a window manager should also set
this member to True. Applications that manage their own input focus by explicitly
setting focus to one of their subwindows whenever they want keyboard input (that
is, use the pull model of focus management) should set this member to False.
Applications that never expect any keyboard input also should set this member to
False.
Pull model window managers should make it possible for push model applications to
get input by setting input focus to the top-level windows of applications whose input
member is True. Push model window managers should make sure that pull model
applications do not break them by resetting input focus to PointerRoot when it is
appropriate (for example, whenever an application whose input member is False
sets input focus to one of its subwindows).
#define WithdrawnState 0
#define NormalState 1 /* most applications start this way */
#define IconicState 3 /* application wants to start as an icon */
The icon_mask specifies which pixels of the icon_pixmap should be used as the icon.
This allows for nonrectangular icons. Both icon_pixmap and icon_mask must be
336
Inter-Client
Communication Functions
bitmaps. The icon_window lets an application provide a window for use as an icon
for window managers that support such use. The window_group lets you specify
that this window belongs to a group of other windows. For example, if a single
application manipulates multiple top-level windows, this allows you to provide
enough information that a window manager can iconify all of the windows rather
than just the one window.
The UrgencyHint flag, if set in the flags field, indicates that the client deems the
window contents to be urgent, requiring the timely response of the user. The window
manager will make some effort to draw the user's attention to this window while
this flag is set. The client must provide some means by which the user can cause the
urgency flag to be cleared (either mitigating the condition that made the window
urgent or merely shutting off the alarm) or the window to be withdrawn.
XSetWMHints(display, w, wmhints);
The XSetWMHints function sets the window manager hints that include icon
information and location, the initial state of the window, and whether the application
relies on the window manager to get keyboard input.
The XGetWMHints function reads the window manager hints and returns NULL if no
WM_HINTS property was set on the window or returns a pointer to an XWMHints
structure if it succeeds. When finished with the data, free the space used for it by
calling XFree.
The size of the XSizeHints structure may grow in future releases, as new
components are added to support new ICCCM features. Passing statically allocated
instances of this structure into Xlib may result in memory corruption when running
against a future release of the library. As such, it is recommended that only
dynamically allocated instances of the structure be used.
337
Inter-Client
Communication Functions
XSizeHints *XAllocSizeHints();
/* Values */
typedef struct {
long flags; /* marks which fields in this structure are defined */
int x, y; /* Obsolete */
int width, height; /* Obsolete */
int min_width, min_height;
int max_width, max_height;
int width_inc, height_inc;
struct {
int x; /* numerator */
int y; /* denominator */
} min_aspect, max_aspect;
int base_width, base_height;
int win_gravity;
/* this structure may be extended in the future */
} XSizeHints;
The x, y, width, and height members are now obsolete and are left solely
for compatibility reasons. The min_width and min_height members specify the
minimum window size that still allows the application to be useful. The max_width
and max_height members specify the maximum window size. The width_inc
and height_inc members define an arithmetic progression of sizes (minimum to
maximum) into which the window prefers to be resized. The min_aspect and
max_aspect members are expressed as ratios of x and y, and they allow an
application to specify the range of aspect ratios it prefers. The base_width and
338
Inter-Client
Communication Functions
base_height members define the desired size of the window. The window manager
will interpret the position of the window and its border width to position the point
of the outer rectangle of the overall window specified by the win_gravity member.
The outer rectangle of the window includes any borders or decorations supplied by
the window manager. In other words, if the window manager decides to place the
window where the client asked, the position on the parent window's border named
by the win_gravity will be placed where the client window would have been placed
in the absence of a window manager.
hints Specifies the size hints for the window in its normal state.
hints_return Returns the size hints for the window in its normal
state.
(USPosition|USSize|PPosition|PSize|PMinSize|
PMaxSize|PResizeInc|PAspect)
339
Inter-Client
Communication Functions
If the property is large enough to contain the base size and window gravity fields
as well, the supplied_return argument will also contain the following bits:
PBaseSize|PWinGravity
The XSetWMSizeHints function replaces the size hints for the specified property
on the named window. If the specified property does not already exist,
XSetWMSizeHints sets the size hints for the specified property on the named
window. The property is stored with a type of WM_SIZE_HINTS and a format of 32.
To set a window's normal size hints, you can use the XSetWMNormalHints function.
The XGetWMSizeHints function returns the size hints stored in the specified
property on the named window. If the property is of type WM_SIZE_HINTS, is of
format 32, and is long enough to contain either an old (pre-ICCCM) or new size
hints structure, XGetWMSizeHints sets the various fields of the XSizeHints structure,
sets the supplied_return argument to the list of fields that were supplied by the
user (whether or not they contained defined values), and returns a nonzero status.
Otherwise, it returns a zero status. To get a window's normal size hints, you can use
the XGetWMNormalHints function.
(USPosition|USSize|PPosition|PSize|PMinSize|
PMaxSize|PResizeInc|PAspect)
340
Inter-Client
Communication Functions
If the property is large enough to contain the base size and window gravity fields
as well, the supplied_return argument will also contain the following bits:
PBaseSize|PWinGravity
XClassHint *XAllocClassHint();
typedef struct {
char *res_name;
char *res_class;
} XClassHint;
The res_name member contains the application name, and the res_class member
contains the application class. Note that the name set in this property may differ
from the name set as WM_NAME. That is, WM_NAME specifies what should be
displayed in the title bar and, therefore, can contain temporal information (for
example, the name of a file currently in an editor's buffer). On the other hand,
the name specified as part of WM_CLASS is the formal name of the application
that should be used when retrieving the application's resources from the resource
database.
XSetClassHint(display, w, class_hints);
The XSetClassHint function sets the class hint for the specified window. If
the strings are not in the Host Portable Character Encoding, the result is
implementation-dependent.
341
Inter-Client
Communication Functions
The XGetClassHint function returns the class hint of the specified window to the
members of the supplied structure. If the data returned by the server is in the Latin
Portable Character Encoding, then the returned strings are in the Host Portable
Character Encoding. Otherwise, the result is implementation-dependent. It returns
a nonzero status on success; otherwise, it returns a zero status. To free res_name
and res_class when finished with the strings, use XFree on each individually.
XSetTransientForHint(display, w, prop_window);
342
Inter-Client
Communication Functions
343
Inter-Client
Communication Functions
344
Inter-Client
Communication Functions
XIconSize *XAllocIconSize();
typedef struct {
int min_width, min_height;
int max_width, max_height;
int width_inc, height_inc;
} XIconSize;
The XSetIconSizes function is used only by window managers to set the supported
icon sizes.
The XGetIconSizes function returns zero if a window manager has not set
icon sizes; otherwise, it returns nonzero. XGetIconSizes should be called by an
application that wants to find out what icon sizes would be most appreciated by the
345
Inter-Client
Communication Functions
window manager under which the application is running. The application should
then use XSetWMHints to supply the window manager with an icon pixmap or
window in one of the supported sizes. To free the data allocated in size_list_return,
use XFree.
hints Specifies the size hints for the window in its normal
state.
346
Inter-Client
Communication Functions
For clients that need to process the property text in a locale, XmbSetWMProperties
sets the WM_LOCALE_NAME property to be the name of the current locale. The
name is assumed to be in the Host Portable Character Encoding and is converted
to STRING for storage in the property.
normal_hints Specifies the size hints for the window in its normal
state.
347
Inter-Client
Communication Functions
The XSetCommand function sets the command and arguments used to invoke the
application. (Typically, argv is the argv array of your main program.) If the strings
348
Inter-Client
Communication Functions
are not in the Host Portable Character Encoding, the result is implementation-
dependent.
The XGetCommand function reads the WM_COMMAND property from the specified
window and returns a string list. If the WM_COMMAND property exists, it is of type
STRING and format 8. If sufficient memory can be allocated to contain the string
list, XGetCommand fills in the argv_return and argc_return arguments and returns
a nonzero status. Otherwise, it returns a zero status. If the data returned by the
server is in the Latin Portable Character Encoding, then the returned strings are
in the Host Portable Character Encoding. Otherwise, the result is implementation-
dependent. To free the memory allocated to the string list, use XFreeStringList.
349
Inter-Client
Communication Functions
Standard Colormaps
Applications with color palettes, smooth-shaded drawings, or digitized images
demand large numbers of colors. In addition, these applications often require an
efficient mapping from color triples to pixel values that display the appropriate
colors.
The user decides to alter some of the colors in the image by invoking a color palette
program to mix and choose colors. The color palette program also needs a colormap
with eight reds, eight greens, and four blues, so just like the image processing
program, it must allocate and install a new colormap.
Because only one colormap can be installed at a time, the color palette may be
displayed incorrectly whenever the image processing program is active. Conversely,
whenever the palette program is active, the image may be displayed incorrectly. The
user can never match or compare colors in the palette and image. Contention for
colormap resources can be reduced if applications with similar color needs share
colormaps.
The image processing program and the color palette program could share the same
colormap if there existed a convention that described how the colormap was set up.
Whenever either program was active, both would be displayed correctly.
350
Inter-Client
Communication Functions
XStandardColormap *XAllocStandardColormap();
/* Hints */
/* Values */
typedef struct {
Colormap colormap;
unsigned long red_max;
unsigned long red_mult;
unsigned long green_max;
unsigned long green_mult;
unsigned long blue_max;
unsigned long blue_mult;
unsigned long base_pixel;
VisualID visualid;
XID killid;
} XStandardColormap;
The red_mult, green_mult, and blue_mult members give the scale factors used to
compose a full pixel value. (See the discussion of the base_pixel members for further
information.) For a 3/3/2 allocation, red_mult might be 32, green_mult might be 4,
and blue_mult might be 1. For a 6-colors-each allocation, red_mult might be 36,
green_mult might be 6, and blue_mult might be 1.
The base_pixel member gives the base pixel value used to compose a full pixel value.
Usually, the base_pixel is obtained from a call to the XAllocColorPlanes function.
Given integer red, green, and blue coefficients in their appropriate ranges, one then
can compute a corresponding pixel value by using the following expression:
351
Inter-Client
Communication Functions
For GrayScale colormaps, only the colormap, red_max, red_mult, and base_pixel
members are defined. The other members are ignored. To compute a GrayScale
pixel value, use the following expression:
The visualid member gives the ID number of the visual from which the colormap
was created. The killid member gives a resource ID that indicates whether the cells
held by this standard colormap are to be released by freeing the colormap ID or by
calling the XKillClient function on the indicated resource. (Note that this method
is necessary for allocating out of an existing colormap.)
The remainder of this section discusses standard colormap properties and atoms as
well as how to manipulate standard colormaps.
352
Inter-Client
Communication Functions
RGB_RED_MAP,RGB_GREEN_MAP
These
,RGB_BLUE_MAP
atoms name properties. The value of each
property is an XStandardColormap.
353
Inter-Client
Communication Functions
• See if the property is on the property list of the root window for the screen.
• Create a colormap (unless you are using the default colormap of the screen).
354
Inter-Client
Communication Functions
355
Chapter 15. Resource Manager
Functions
A program often needs a variety of options in the X environment (for example, fonts,
colors, icons, and cursors). Specifying all of these options on the command line is
awkward because users may want to customize many aspects of the program and
need a convenient way to establish these customizations as the default settings. The
resource manager is provided for this purpose. Resource specifications are usually
stored in human-readable files and in server properties.
For example, a user of your application may want to specify that all windows
should have a blue background but that all mail-reading windows should have a red
background. With well-engineered and coordinated applications, a user can define
this information using only two lines of specifications.
For example, the xmh mail program has a name "xmh" and is one of a class of "Mail"
programs. By convention, the first character of class components is capitalized, and
the first letter of name components is in lowercase. Each name and class finally
has an attribute (for example, "foreground" or "font"). If each window is properly
assigned a name and class, it is easy for the user to specify attributes of any portion
of the application.
At the top level, the application might consist of a paned window (that is, a window
divided into several sections) named "toc". One pane of the paned window is a button
box window named "buttons" and is filled with command buttons. One of these
command buttons is used to incorporate new mail and has the name "incorporate".
This window has a fully qualified name, "xmh.toc.buttons.incorporate", and a fully
qualified class, "Xmh.Paned.Box.Command". Its fully qualified name is the name of
its parent, "xmh.toc.buttons", followed by its name, "incorporate". Its class is the
class of its parent, "Xmh.Paned.Box", followed by its particular class, "Command".
The fully qualified name of a resource is the attribute's name appended to the
object's fully qualified name, and the fully qualified class is its class appended to
the object's class.
356
Resource Manager Functions
The incorporate button might need the following resources: Title string, Font,
Foreground color for its inactive state, Background color for its inactive state,
Foreground color for its active state, and Background color for its active state. Each
resource is considered to be an attribute of the button and, as such, has a name and
a class. For example, the foreground color for the button in its active state might
be named "activeForeground", and its class might be "Foreground".
Elements separated by vertical bar (|) are alternatives. Curly braces ({......})
indicate zero or more repetitions of the enclosed elements. Square brackets ([......])
indicate that the enclosed element is optional. Quotes ("......") are used around literal
characters.
IncludeFile lines are interpreted by replacing the line with the contents of the
specified file. The word "include" must be in lowercase. The file name is interpreted
relative to the directory of the file in which the line occurs (for example, if the file
name contains no directory or contains a relative directory specification).
A resource database never contains more than one entry for a given ResourceName.
If a resource file contains multiple lines with the same ResourceName, the last line
in the file is used.
357
Resource Manager Functions
Any white space characters before or after the name or colon in a ResourceSpec
are ignored. To allow a Value to begin with white space, the two-character
sequence "\\space" (backslash followed by space) is recognized and replaced by
a space character, and the two-character sequence "\\tab" (backslash followed
by horizontal tab) is recognized and replaced by a horizontal tab character. To
allow a Value to contain embedded newline characters, the two-character sequence
"\\n" is recognized and replaced by a newline character. To allow a Value to
be broken across multiple lines in a text file, the two-character sequence "\
\newline" (backslash followed by newline) is recognized and removed from the
value. To allow a Value to contain arbitrary character codes, the four-character
sequence "\\nnn", where each n is a digit character in the range of "0"-"7", is
recognized and replaced with a single byte that contains the octal value specified
by the sequence. Finally, the two-character sequence "\newline" is recognized and
replaced with a single backslash.
magic.values: \\000\
z\n
The full name and class are scanned from left to right (from highest level in the
hierarchy to lowest), one component at a time. At each level, the corresponding
component and/or binding of each matching entry is determined, and these
matching components and bindings are compared according to precedence rules.
Each of the rules is applied at each level before moving to the next level, until a rule
selects a single entry over all others. The rules, in order of precedence, are:
• An entry with a matching name takes precedence over both entries with a
matching class and entries that match using the character "?". An entry with a
matching class takes precedence over entries that match using the character "?".
358
Resource Manager Functions
xmh.toc.messagefunctions.incorporate.activeForeground (name)
Xmh.Paned.Box.Command.Foreground (class)
At the first level (xmh, Xmh), rule 1 eliminates entry B. At the second level (toc,
Paned), rule 2 eliminates entry A. At the third level (messagefunctions, Box), no
entries are eliminated. At the fourth level (incorporate, Command), rule 2 eliminates
entry D. At the fifth level (activeForeground, Foreground), rule 3 eliminates entry C.
Quarks
Most uses of the resource manager involve defining names, classes, and
representation types as string constants. However, always referring to strings in
the resource manager can be slow, because it is so heavily used in some toolkits. To
solve this problem, a shorthand for a string is used in place of the string in many
of the resource manager functions. Simple comparisons can be performed rather
than string comparisons. The shorthand name for a string is called a quark and is
the type XrmQuark. On some occasions, you may want to allocate a quark that has
no string equivalent.
A quark is to a string what an atom is to a string in the server, but its use is entirely
local to your application.
XrmQuark XrmUniqueQuark();
359
Resource Manager Functions
Lists are represented as null-terminated arrays of quarks. The size of the array must
be large enough for the number of components used.
XrmQuark XrmStringToQuark(string);
For any given quark, if XrmStringToQuark returns a non-NULL value, all future calls
will return the same value (identical address).
char *XrmQuarkToString(quark);
quark Specifies the quark for which the equivalent string is desired.
These functions can be used to convert from quark representation to string. The
string pointed to by the return value must not be modified or freed. The returned
string is byte-for-byte equal to the original string passed to one of the string-to-
quark routines. If no string exists for that quark, XrmQuarkToString returns NULL.
For any given quark, if XrmQuarkToString returns a non-NULL value, all future calls
will return the same value (identical address).
360
Resource Manager Functions
To convert a string with one or more components to a binding list and a quark list,
use XrmStringToBindingQuarkList.
quarks: a b c
bindings: loose tight loose
361
Resource Manager Functions
typedef struct {
unsigned int size;
XPointer addr;
} XrmValue, *XrmValuePtr;
void XrmInitialize(XrmInitialize(\|));
XrmDatabase XrmGetFileDatabase(filename);
The XrmGetFileDatabase function opens the specified file, creates a new resource
database, and loads it with the specifications read in from the specified file. The
specified file should contain a sequence of entries in valid ResourceLine format
(see section 15.1); the database that results from reading a file with incorrect
syntax is implementation-dependent. The file is parsed in the current locale, and
the database is created in the current locale. If it cannot open the specified file,
XrmGetFileDatabase returns NULL.
char *XResourceManagerString(display);
362
Resource Manager Functions
char *XScreenResourceString(screen);
XrmDatabase XrmGetStringDatabase(data);
char *XrmLocaleOfDatabase(database);
The XrmLocaleOfDatabase function returns the name of the locale bound to the
specified database, as a null-terminated string. The returned locale name string is
owned by Xlib and should not be modified or freed by the client. Xlib is not permitted
to free the string until the database is destroyed. Until the string is freed, it will
not be modified by Xlib.
void XrmDestroyDatabase(database);
363
Resource Manager Functions
The XrmSetDatabase function associates the specified resource database (or NULL)
with the specified display. The database previously associated with the display (if
any) is not destroyed. A client or toolkit may find this function convenient for
retaining a database once it is constructed.
XrmDatabase XrmGetDatabase(display);
The XrmGetDatabase function returns the database associated with the specified
display. It returns NULL if a database has not yet been set.
364
Resource Manager Functions
To merge the contents of one database into another database with override
semantics, use XrmMergeDatabases.
Looking Up Resources
To retrieve a resource from a resource database, use XrmGetResource,
XrmQGetResource, or XrmQGetSearchResource.
365
Resource Manager Functions
Most applications and toolkits do not make random probes into a resource database
to fetch resources. The X toolkit access pattern for a resource database is quite
stylized. A series of from 1 to 20 probes is made with only the last name/class
n
differing in each probe. The XrmGetResource function is at worst a 2 algorithm,
where n is the length of the name/class list. This can be improved upon by the
application programmer by prefetching a list of database levels that might match
the first part of a name/class list.
list_return Returns a search list for further use. The caller must
allocate sufficient space for the list before calling
XrmQGetSearchList.
The XrmQGetSearchList function takes a list of names and classes and returns a list
of database levels where a match might occur. The returned list is in best-to-worst
order and uses the same algorithm as XrmGetResource for determining precedence.
If list_return was large enough for the search list, XrmQGetSearchList returns True;
otherwise, it returns False.
The size of the search list that the caller must allocate is dependent upon the number
of levels and wildcards in the resource specifiers that are stored in the database.
n
The worst case length is 3 , where n is the number of name or class components
in names or classes.
366
Resource Manager Functions
A call to XrmQGetSearchList with a name and class list containing all but the
last component of a resource name followed by a call to XrmQGetSearchResource
with the last component name and class returns the same database entry as
XrmGetResource and XrmQGetResource with the fully qualified name and class.
367
Resource Manager Functions
If the specifier and type are not in the Host Portable Character Encoding, the
result is implementation-dependent. The value is stored in the database without
modification.
368
Resource Manager Functions
To add a single resource entry that is specified as a string that contains both a name
and a value, use XrmPutLineResource.
#define XrmEnumAllLevels 0
#define XrmEnumOneLevel 0
The XrmEnumerateDatabase function calls the specified procedure for each resource
in the database that would match some completion of the given name/class resource
prefix. The order in which resources are found is implementation-dependent. If
mode is XrmEnumOneLevel, a resource must match the given name/class prefix
with just a single name and class appended. If mode is XrmEnumAllLevels, the
resource must match the given name/class prefix with one or more names and
369
Resource Manager Functions
classes appended. If the procedure returns True, the enumeration terminates and
the function returns True. If the procedure always returns False, all matching
resources are enumerated and the function returns False.
The bindings and quarks lists are terminated by NULLQUARK. Note that pointers
to the database and type are passed, but these values should not be modified.
The procedure must not modify the database. If Xlib has been initialized for threads,
the procedure is called with the database locked and the result of a call by the
procedure to any Xlib function using the same database is not defined.
typedef enum {
XrmoptionNoArg, /* Value is specified in XrmOptionDescRec.value */
XrmoptionIsArg, /* Value is the option string itself */
XrmoptionStickyArg, /* Value is characters immediately following option */
XrmoptionSepArg, /* Value is next argument in argv */
XrmoptionResArg, /* Resource and value in next argument in argv */
XrmoptionSkipArg, /* Ignore this option and the next argument in argv */
XrmoptionSkipLine, /* Ignore this option and the rest of argv */
XrmoptionSkipNArgs /* Ignore this option and the next
\ \ \ XrmOptionDescRec.value arguments in argv */
} XrmOptionKind;
370
Resource Manager Functions
typedef struct {
char *option; /* Option specification string in argv */
char *specifier; /* Binding and resource name (sans application name) *
XrmOptionKind argKind; /* Which style of option it is */
XPointer value; /* Value to provide if XrmoptionNoArg or
\ \ \ XrmoptionSkipNArgs */
} XrmOptionDescRec, *XrmOptionDescList;
The XrmParseCommand function parses an (argc, argv) pair according to the specified
option table, loads recognized options into the specified database with type
``String,'' and modifies the (argc, argv) pair to remove all recognized options. If
database contains NULL, XrmParseCommand creates a new database and returns a
pointer to it. Otherwise, entries are added to the database specified. If a database
is created, it is created in the current locale.
The specified table is used to parse the command line. Recognized options in
the table are removed from argv, and entries are added to the specified resource
database in the order they occur in argv. The table entries contain information on the
option string, the option name, the style of option, and a value to provide if the option
kind is XrmoptionNoArg. The option names are compared byte-for-byte to arguments
in argv, independent of any locale. The resource values given in the table are stored
in the resource database without modification. All resource database entries are
created using a ``String'' representation type. The argc argument specifies the
number of arguments in argv and is set on return to the remaining number of
arguments that were not parsed. The name argument should be the name of your
application for use in building the database entry. The name argument is prefixed
to the resourceName in the option table before storing a database entry. The name
argument is treated as a single component, even if it has embedded periods. No
separating (binding) character is inserted, so the table must contain either a period
(.) or an asterisk (*) as the first character in each resourceName entry. To specify
a more completely qualified resource name, the resourceName entry can contain
multiple components. If the name argument and the resourceNames are not in the
Host Portable Character Encoding, the result is implementation-dependent.
371
Resource Manager Functions
In this table, if the -background (or -bg) option is used to set background colors,
the stored resource specifier matches all resources of attribute background. If the
-borderwidth option is used, the stored resource specifier applies only to border
width attributes of class TopLevelShell (that is, outer-most windows, including pop-
up windows). If the -title option is used to set a window name, only the topmost
application windows receive the resource.
When parsing the command line, any unique unambiguous abbreviation for an
option name in the table is considered a match for the option. Note that uppercase
and lowercase matter.
372
Chapter 16. Application Utility
Functions
Once you have initialized the X system, you can use the Xlib utility functions to:
• Manipulate regions
• Manipulate images
• Manipulate bitmaps
As a group, the functions discussed in this chapter provide the functionality that is
frequently needed and that spans toolkits. Many of these functions do not generate
actual protocol requests to the server.
index Specifies the index into the KeySyms list for the event's
KeyCode.
The XLookupKeysym function uses a given keyboard event and the index you
specified to return the KeySym from the list that corresponds to the KeyCode
member in the XKeyPressedEvent or XKeyReleasedEvent structure. If no KeySym
is defined for the KeyCode of the event, XLookupKeysym returns NoSymbol.
373
Application Utility Functions
The XKeycodeToKeysym function uses internal Xlib tables and returns the KeySym
defined for the specified KeyCode and the element of the KeyCode vector. If no
symbol is defined, XKeycodeToKeysym returns NoSymbol.
If the specified KeySym is not defined for any KeyCode, XKeysymToKeycode returns
zero.
The mapping between KeyCodes and KeySyms is cached internal to Xlib. When
this information is changed at the server, an Xlib function must be called to
refresh the cache. To refresh the stored modifier and keymap information, use
XRefreshKeyboardMapping.
XRefreshKeyboardMapping(event_map);
The XConvertCase function returns the uppercase and lowercase forms of the
specified Keysym, if the KeySym is subject to case conversion; otherwise, the
specified KeySym is returned to both lower_return and upper_return. Support for
conversion of other than Latin and Cyrillic KeySyms is implementation-dependent.
KeySyms have string names as well as numeric codes. To convert the name of the
KeySym to the KeySym code, use XStringToKeysym.
KeySym XStringToKeysym(string);
374
Application Utility Functions
If the KeySym name is not in the Host Portable Character Encoding, the result is
implementation-dependent. If the specified string does not match a valid KeySym,
XStringToKeysym returns NoSymbol.
char *XKeysymToString(keysym);
The returned string is in a static area and must not be modified. The returned string
is in the Host Portable Character Encoding. If the specified KeySym is not defined,
XKeysymToString returns a NULL.
IsCursorKey(keysym)
IsFunctionKey(keysym)
IsKeypadKey(keysym)
IsPrivateKeypadKey(keysym)
IsMiscFunctionKey(keysym)
IsModifierKey(keysym)
375
Application Utility Functions
IsPFKey(keysym)
The XLookupString function translates a key event to a KeySym and a string. The
KeySym is obtained by using the standard interpretation of the Shift, Lock, group,
and numlock modifiers as defined in the X Protocol specification. If the KeySym has
been rebound (see XRebindKeysym), the bound string will be stored in the buffer.
Otherwise, the KeySym is mapped, if possible, to an ISO Latin-1 character or (if the
Control modifier is on) to an ASCII control character, and that character is stored
in the buffer. XLookupString returns the number of characters that are stored in
the buffer.
376
Application Utility Functions
The XRebindKeysym function can be used to rebind the meaning of a KeySym for the
client. It does not redefine any key in the X server but merely provides an easy way
for long strings to be attached to keys. XLookupString returns this string when the
appropriate set of modifier keys are pressed and when the KeySym would have been
used for the translation. No text conversions are performed; the client is responsible
for supplying appropriately encoded strings. Note that you can rebind a KeySym
that may not exist.
char *Xpermalloc(size);
The Xpermalloc function allocates storage that can never be freed for the life
of the program. The memory is allocated with alignment for the C type double.
This function may provide some performance and space savings over the standard
operating system memory allocator.
x_return
width_return
377
Application Utility Functions
allows you to parse the standard window geometry. Specifically, this function lets
you parse strings of the form:
[=][<width>{xX}<height>][{+-}<xoffset>{+-}<yoffset>]
The fields map into the arguments associated with this function. (Items enclosed in
<> are integers, items in [] are optional, and items enclosed in {} indicate ``choose
one of.'' Note that the brackets should not appear in the actual string.) If the
string is not in the Host Portable Character Encoding, the result is implementation-
dependent.
The XParseGeometry function returns a bitmask that indicates which of the four
values (width, height, xoffset, and yoffset) were actually found in the string and
whether the x and y values are negative. By convention, −0 is not equal to +0,
because the user needs to be able to say ``position the window relative to the right
or bottom edge.'' For each value found, the corresponding argument is updated. For
each value not found, the argument is left unchanged. The bits are represented by
XValue, YValue, WidthValue, HeightValue, XNegative, or YNegative and are defined
in <X11/Xutil.h>. They will be set whenever one of the values is defined or one
of the signs is set.
If the function returns either the XValue or YValue flag, you should place the window
at the requested position.
hints Specifies the size hints for the window in its normal
state.
x_return
width_return
The XWMGeometry function combines any geometry information (given in the format
used by XParseGeometry) specified by the user and by the calling program with
size hints (usually the ones to be stored in WM_NORMAL_HINTS) and returns the
378
Application Utility Functions
Note that invalid geometry specifications can cause a width or height of zero to
be returned. The caller may pass the address of the hints win_gravity field as
gravity_return to update the hints directly.
Manipulating Regions
Regions are arbitrary sets of pixel locations. Xlib provides functions for
manipulating regions. The opaque type Region is defined in <X11/Xutil.h>. Xlib
provides functions that you can use to manipulate regions. This section discusses
how to:
Region XCreateRegion();
fill_rule Specifies the fill-rule you want to set for the specified GC.
You can pass EvenOddRule or WindingRule.
The XPolygonRegion function returns a region for the polygon defined by the points
array. For an explanation of fill_rule, see XCreateGC.
379
Application Utility Functions
The XSetRegion function sets the clip-mask in the GC to the specified region. The
region is specified relative to the drawable's origin. The resulting GC clip origin is
implementation-dependent. Once it is set in the GC, the region can be destroyed.
XDestroyRegion(r);
dx
dx
Positive values shrink the size of the region, and negative values expand the region.
XClipBox(r, rect_return);
The XClipBox function returns the smallest rectangle enclosing the specified region.
380
Application Utility Functions
sra
srb Specify the two regions with which you want to perform
the computation.
sra
srb Specify the two regions with which you want to perform
the computation.
sra
srb Specify the two regions with which you want to perform
the computation.
The XSubtractRegion function subtracts srb from sra and stores the results in
dr_return.
To calculate the difference between the union and intersection of two regions, use
XXorRegion.
sra
srb Specify the two regions with which you want to perform
the computation.
381
Application Utility Functions
Bool XEmptyRegion(r);
To determine if two regions have the same offset, size, and shape, use
XEqualRegion.
r1
The XEqualRegion function returns True if the two regions have the same offset,
size, and shape.
The XPointInRegion function returns True if the point (x, y) is contained in the
region r.
width
height Specify the width and height, which define the rectangle.
382
Application Utility Functions
Cut buffers are implemented as properties on the first root window of the display.
The buffers can only contain text, in the STRING encoding. The text encoding is not
changed by Xlib when fetching or storing. Eight buffers are provided and can be
accessed as a ring or as explicit buffers (numbered 0 through 7).
bytes Specifies the bytes, which are not necessarily ASCII or null-
terminated.
The data can have embedded null characters and need not be null-terminated. The
cut buffer's contents can be retrieved later by any client calling XFetchBytes.
bytes Specifies the bytes, which are not necessarily ASCII or null-
terminated.
buffer Specifies the buffer in which you want to store the bytes.
If an invalid buffer is specified, the call has no effect. The data can have embedded
null characters and need not be null-terminated.
383
Application Utility Functions
sets nbytes to 0. The appropriate amount of storage is allocated and the pointer
returned. The client must free this storage when finished with it by calling XFree.
buffer Specifies the buffer from which you want the stored
data returned.
XRotateBuffers(display, rotate);
The XRotateBuffers function rotates the cut buffers, such that buffer 0 becomes
buffer n, buffer 1 becomes n + 1 mod 8, and so on. This cut buffer numbering is
global to the display. Note that XRotateBuffers generates BadMatch errors if any
of the eight buffers have not been created.
The functions in this section use the visual information masks and the XVisualInfo
structure, which is defined in <X11/Xutil.h> and contains:
384
Application Utility Functions
/* Values */
typedef struct {
Visual *visual;
VisualID visualid;
int screen;
unsigned int depth;
int class;
unsigned long red_mask;
unsigned long green_mask;
unsigned long blue_mask;
int colormap_size;
int bits_per_rgb;
} XVisualInfo;
To obtain a list of visual information structures that match a specified template, use
XGetVisualInfo.
The XGetVisualInfo function returns a list of visual structures that have attributes
equal to the attributes specified by vinfo_template. If no visual structures match the
template using the specified vinfo_mask, XGetVisualInfo returns a NULL. To free
the data returned by this function, use XFree.
To obtain the visual information that matches the specified depth and class of the
screen, use XMatchVisualInfo.
The XMatchVisualInfo function returns the visual information for a visual that
matches the specified depth and class for a screen. Because multiple visuals that
385
Application Utility Functions
match the specified depth and class can exist, the exact visual chosen is undefined.
If a visual is found, XMatchVisualInfo returns nonzero and the information on the
visual to vinfo_return. Otherwise, when a visual is not found, XMatchVisualInfo
returns zero.
Manipulating Images
Xlib provides several functions that perform basic operations on images. All
operations on images are defined using an XImage structure, as defined in <X11/
Xlib.h>. Because the number of different types of image formats can be very
large, this hides details of image storage properly from applications.
Note that no functions have been defined, as yet, to read and write images to and
from disk files.
The XImage structure describes an image as it exists in the client's memory. The
user can request that some of the members such as height, width, and xoffset
be changed when the image is sent to the server. Note that bytes_per_line in
concert with offset can be used to extract a subset of the image. Other members
(for example, byte order, bitmap_unit, and so forth) are characteristics of both the
image and the server. If these members differ between the image and the server,
XPutImage makes the appropriate conversions. The first byte of the first line of
plane n must be located at the address (data + (n * height * bytes_per_line)). For a
description of the XImage structure, see section 8.7.
To allocate an XImage structure and initialize it with image format values from a
display, use XCreateImage.
format Specifies the format for the image. You can pass
XYBitmap, XYPixmap, or ZPixmap.
386
Application Utility Functions
The XCreateImage function allocates the memory needed for an XImage structure
for the specified display but does not allocate space for the image itself. Rather,
it initializes the structure byte-order, bit-order, and bitmap-unit values from the
display and returns a pointer to the XImage structure. The red, green, and blue
mask values are defined for Z format images only and are derived from the Visual
structure passed in. Other values also are passed in. The offset permits the rapid
displaying of the image without requiring each scanline to be shifted into position.
If you pass a zero value in bytes_per_line, Xlib assumes that the scanlines are
contiguous in memory and calculates the value of bytes_per_line itself.
Note that when the image is created using XCreateImage, XGetImage, or XSubImage,
the destroy procedure that the XDestroyImage function calls frees both the image
structure and the data pointed to by the image structure.
The basic functions used to get a pixel, set a pixel, create a subimage, and add a
constant value to an image are defined in the image object. The functions in this
section are really macro invocations of the functions in the image object and are
defined in <X11/Xutil.h>.
The XGetPixel function returns the specified pixel from the named image. The pixel
value is returned in normalized format (that is, the least significant byte of the
long is the least significant byte of the pixel). The image must contain the x and y
coordinates.
XPutPixel(ximage, x, y, pixel);
The XPutPixel function overwrites the pixel in the named image with the specified
pixel value. The input pixel value must be in normalized format (that is, the least
387
Application Utility Functions
significant byte of the long is the least significant byte of the pixel). The image must
contain the x and y coordinates.
XAddPixel(ximage, value);
XDestroyImage(ximage);
The XDestroyImage function deallocates the memory associated with the XImage
structure.
Note that when the image is created using XCreateImage, XGetImage, or XSubImage,
the destroy procedure that this macro calls frees both the image structure and the
data pointed to by the image structure.
Manipulating Bitmaps
Xlib provides functions that you can use to read a bitmap from a file, save a bitmap
to a file, or create a bitmap. This section describes those functions that transfer
bitmaps to and from the client's file system, thus allowing their reuse in a later
connection (for example, from an entirely different client or to a different display
or server).
388
Application Utility Functions
The lines for the variables ending with _x_hot and _y_hot suffixes are optional
because they are present only if a hotspot has been defined for this bitmap. The
lines for the other variables are required. The word ``unsigned'' is optional; that is,
the type of the _bits array can be ``char'' or ``unsigned char''. The _bits array must
be large enough to contain the size bitmap. The bitmap unit is 8.
filename Specifies the file name to use. The format of the file
name is operating-system dependent.
width_return
x_hot_return
XReadBitmapFile returns the bitmap's height and width, as read from the file, to
width_return and height_return. It then creates a pixmap of the appropriate size,
reads the bitmap data from the file into the pixmap, and assigns the pixmap to the
caller's variable bitmap. The caller must free the bitmap using XFreePixmap when
finished. If name_x_hot and name_y_hot exist, XReadBitmapFile returns them to
x_hot_return and y_hot_return; otherwise, it returns −1,−1.
389
Application Utility Functions
filename Specifies the file name to use. The format of the file
name is operating-system dependent.
width_return
x_hot_return
filename Specifies the file name to use. The format of the file name
is operating-system dependent.
width
x_hot
To create a pixmap and then store bitmap-format data into it, use
XCreatePixmapFromBitmapData.
390
Application Utility Functions
width
fg
width
#include "gray.bitmap"
Pixmap bitmap;
bitmap = XCreateBitmapFromData(display, window, gray_bits, gray_width, gray_height)
391
Application Utility Functions
number of pieces can be associated with a resource ID, and each piece of data has
a type associated with it. The context manager requires knowledge of the resource
ID and type to store or retrieve data.
To save a data value that corresponds to a resource ID and context type, use
XSaveContext.
If an entry with the specified resource ID and type already exists, XSaveContext
overrides it with the specified context. The XSaveContext function returns a
nonzero error code if an error has occurred and zero otherwise. Possible errors are
XCNOMEM (out of memory).
To get the data associated with a resource ID and type, use XFindContext.
Because it is a return value, the data is a pointer. The XFindContext function returns
a nonzero error code if an error has occurred and zero otherwise. Possible errors
are XCNOENT (context-not-found).
The XDeleteContext function deletes the entry for the given resource ID and
type from the data structure. This function returns the same error codes that
392
Application Utility Functions
XFindContext returns if called with the same arguments. XDeleteContext does not
free the data whose address was saved.
XContext XUniqueContext();
393
Appendix A. Xlib Functions and
Protocol Requests
This appendix provides two tables that relate to Xlib functions and the X protocol.
The following table lists each Xlib function (in alphabetical order) and the
corresponding protocol request that it generates.
394
Xlib Functions and
Protocol Requests
395
Xlib Functions and
Protocol Requests
396
Xlib Functions and
Protocol Requests
397
Xlib Functions and
Protocol Requests
398
Xlib Functions and
Protocol Requests
399
Xlib Functions and
Protocol Requests
The following table lists each X protocol request (in alphabetical order) and the Xlib
functions that reference it.
400
Xlib Functions and
Protocol Requests
401
Xlib Functions and
Protocol Requests
402
Xlib Functions and
Protocol Requests
403
Xlib Functions and
Protocol Requests
404
Xlib Functions and
Protocol Requests
405
Xlib Functions and
Protocol Requests
406
Xlib Functions and
Protocol Requests
407
Appendix B. X Font Cursors
The following are the available cursors that can be used with XCreateFontCursor.
408
Appendix C. Extensions
Because X can evolve by extensions to the core protocol, it is important that
extensions not be perceived as second-class citizens. At some point, your favorite
extensions may be adopted as additional parts of the X Standard.
This appendix describes techniques for writing extensions to Xlib that will run at
essentially the same performance as the core protocol requests.
Note
It is expected that a given extension to X consists of multiple requests.
Defining 10 new features as 10 separate extensions is a bad practice. Rather,
they should be packaged into a single extension and should use minor
opcodes to distinguish the requests.
The symbols and macros used for writing stubs to Xlib are listed in <X11/
Xlibint.h>.
409
Extensions
If the extension name is not in the Host Portable Character Encoding the result is
implementation-dependent. Uppercase and lowercase matter; the strings ``thing'',
``Thing'', and ``thinG'' are all considered different names.
XFreeExtensionList(list);
In extensions, stubs first should check to see if they have initialized themselves on
a connection. If they have not, they then should call XInitExtension to attempt to
initialize themselves on the connection.
410
Extensions
If the extension name is not in the Host Portable Character Encoding, the result is
implementation-dependent. Uppercase and lowercase matter; the strings ``thing'',
``Thing'', and ``thinG'' are all considered different names.
The extension number in the XExtCodes structure is needed in the other calls that
follow. This extension number is unique only to a single connection.
XExtCodes *XAddExtension(display);
For local Xlib extensions, the XAddExtension function allocates the XExtCodes
structure, bumps the extension number count, and chains the extension onto the
extension list. (This permits extensions to Xlib without requiring server extensions.)
All of these functions return the previous procedure defined for this extension.
411
Extensions
412
Extensions
Your procedure must return status to indicate if the conversion succeeded. The re
argument is a pointer to where the host format event should be stored, and the
event argument is the 32-byte wire event structure. In the XEvent structure you
are creating, you must fill in the five required members of the event structure. You
413
Extensions
should fill in the type member with the type specified for the xEvent structure.
You should copy all other members from the xEvent structure (wire format) to the
XEvent structure (host format). Your conversion procedure should return True if the
event should be placed in the queue or False if it should not be placed in the queue.
The re argument is a pointer to the host format event, and the event argument is a
pointer to where the 32-byte wire event structure should be stored. You should fill
in the type with the type from the XEvent structure. All other members then should
be copied from the host format to the xEvent structure.
414
Extensions
Use this function for extension errors that contain additional error values beyond
those in a core X error, when multiple wire errors must be combined into a single
Xlib error, or when it is necessary to intercept an X error before it is otherwise
examined.
When Xlib needs to convert an error from wire format to host format, the procedure
is called with these arguments:
The he argument is a pointer to where the host format error should be stored. The
structure pointed at by he is guaranteed to be as large as an XEvent structure and
so can be cast to a type larger than an XErrorEvent to store additional values. If
the error is to be completely ignored by Xlib (for example, several protocol error
structures will be combined into one Xlib error), then the function should return
False; otherwise, it should return True.
Inside Xlib, there are times that you may want to suppress the calling of the external
error handling when an error occurs. This allows status to be returned on a call
at the cost of the call being synchronous (though most such functions are query
operations, in any case, and are typically programmed to be synchronous).
When Xlib detects a protocol error in _XReply, it calls your procedure with these
arguments:
The err argument is a pointer to the 32-byte wire format error. The codes argument
is a pointer to the extension codes structure. The ret_code argument is the return
code you may want _XReply returned to.
If your procedure returns a zero value, the error is not suppressed, and the
client's error handler is called. (For further information, see section 11.8.2.) If your
procedure returns nonzero, the error is suppressed, and _XReply returns the value
of ret_code.
415
Extensions
Your procedure is called with the error code for every error detected. You should
copy nbytes of a null-terminated string containing the error message into buffer.
When Xlib needs to print an error, the procedure is called with these arguments:
The procedure set by the XESetFlushGC function has the same interface as the
procedure set by the XESetCopyGC function, but is called when a GC cache needs
to be updated in the server.
The data argument specifies a portion of the outgoing data buffer, and its length in
bytes is specified by the len argument. Your procedure must not alter the contents
of the data and must not do additional protocol requests to the same display.
416
Extensions
The following structure is used in the functions in this section and is defined in
<X11/Xlib.h>
When any of the data structures listed above are freed, the list is walked, and the
structure's free procedure (if any) is called. If free is NULL, then the library frees
both the data pointed to by the private_data member and the structure itself.
XExtData **XEHeadOfExtensionList(object);
XAddToExtensionList(structure, ext_data);
The structure argument is a pointer to one of the data structures enumerated above.
You must initialize ext_data->number with the extension number before calling this
function.
417
Extensions
The XFindOnExtensionList function returns the first extension data structure for
the extension numbered number. It is expected that an extension will add at most
one extension data structure to any single data structure's extension data list. There
is no way to find additional structures.
The XAllocID macro, which allocates and returns a resource ID, is defined in <X11/
Xlib.h>.
XAllocID(display);
GC Caching
GCs are cached by the library to allow merging of independent change requests
to the same GC into single protocol requests. This is typically called a write-back
cache. Any extension procedure whose behavior depends on the contents of a GC
must flush the GC cache to make sure the server has up-to-date contents in its GC.
The FlushGC macro checks the dirty bits in the library's GC structure and calls
_XFlushGCCache if any elements have changed. The FlushGC macro is defined as
follows:
FlushGC(display, gc);
Note that if you extend the GC to add additional resource ID components, you should
ensure that the library stub sends the change request immediately. This is because
a client can free a resource immediately after using it, so if you only stored the value
in the cache without forcing a protocol request, the resource might be destroyed
before being set into the GC. You can use the _XFlushGCCache procedure to force
the cache to be flushed. The _XFlushGCCache procedure is defined as follows:
_XFlushGCCache(display, gc);
418
Extensions
Graphics Batching
If you extend X to add more poly graphics primitives, you may be able to take
advantage of facilities in the library to allow back-to-back single calls to be
transformed into poly requests. This may dramatically improve performance of
programs that are not written using poly requests. A pointer to an xReq, called
last_req in the display structure, is the last request being processed. By checking
that the last request type, drawable, gc, and other options are the same as the
new one and that there is enough space left in the buffer, you may be able to just
extend the previous graphics request by extending the length field of the request
and appending the data to the buffer. This can improve performance by five times or
more in naive programs. For example, here is the source for the XDrawPoint stub.
(Writing extension stubs is discussed in the next section.)
#include <X11/Xlibint.h>
XDrawPoint(dpy, d, gc, x, y)
register Display *dpy;
Drawable d;
GC gc;
int x, y; /* INT16 */
{
xPoint *point;
LockDisplay(dpy);
FlushGC(dpy, gc);
{
register xPolyPointReq *req = (xPolyPointReq *) dpy->last_req;
/* if same as previous request, with same drawable, batch requests */
if (
(req->reqType == X_PolyPoint)
&& (req->drawable == d)
&& (req->gc == gc->gid)
&& (req->coordMode == CoordModeOrigin)
&& ((dpy->bufptr + sizeof (xPoint)) <= dpy->bufmax)
&& (((char *)dpy->bufptr - (char *)req) < size) ) {
point = (xPoint *) dpy->bufptr;
req->length += sizeof (xPoint) >> 2;
dpy->bufptr += sizeof (xPoint);
}
else {
GetReqExtra(PolyPoint, 4, req); /* 1 point = 4 bytes */
req->drawable = d;
req->gc = gc->gid;
req->coordMode = CoordModeOrigin;
419
Extensions
To keep clients from generating very long requests that may monopolize the server,
there is a symbol defined in <X11/Xlibint.h> of EPERBATCH on the number of
requests batched. Most of the performance benefit occurs in the first few merged
requests. Note that FlushGC is called before picking up the value of last_req,
because it may modify this field.
You need to generate a file equivalent to <X11/Xproto.h> for your extension and
need to include it in your stub procedure. Each stub procedure also must include
<X11/Xlibint.h>.
The identifiers are deliberately chosen in such a way that, if the request is called
X_DoSomething, then its request structure is xDoSomethingReq, and its reply is
xDoSomethingReply. The GetReq family of macros, defined in <X11/Xlibint.h>,
takes advantage of this naming scheme.
For each X request, there is a definition in <X11/Xproto.h> that looks similar to this:
#define X_DoSomething 42
In your extension header file, this will be a minor opcode, instead of a major opcode.
Request Format
Every request contains an 8-bit major opcode and a 16-bit length field expressed in
units of 4 bytes. Every request consists of 4 bytes of header (containing the major
opcode, the length field, and a data byte) followed by zero or more additional bytes
of data. The length field defines the total length of the request, including the header.
The length field in a request must equal the minimum length required to contain
the request. If the specified length is smaller or larger than the required length,
the server should generate a BadLength error. Unused bytes in a request are not
required to be zero. Extensions should be designed in such a way that long protocol
420
Extensions
requests can be split up into smaller requests, if it is possible to exceed the maximum
request size of the server. The protocol guarantees the maximum request size to be
no smaller than 4096 units (16384 bytes).
Major opcodes 128 through 255 are reserved for extensions. Extensions are
intended to contain multiple requests, so extension requests typically have an
additional minor opcode encoded in the second data byte in the request header, but
the placement and interpretation of this minor opcode as well as all other fields in
extension requests are not defined by the core protocol. Every request is implicitly
assigned a sequence number (starting with one) used in replies, errors, and events.
If a core protocol request has a single 32-bit argument, you need not declare a
request structure in your extension header file. Instead, such requests use the
xResourceReq structure in <X11/Xproto.h>. This structure is used for any request
whose single argument is a Window, Pixmap, Drawable, GContext, Font, Cursor,
Colormap, Atom, or VisualID.
In both of these structures, the reqType field identifies the type of the request
(for example, X_MapWindow or X_CreatePixmap). The length field tells how long
the request is in units of 4-byte longwords. This length includes both the request
structure itself and any variable-length data, such as strings or lists, that follow the
request structure. Request structures come in different sizes, but all requests are
padded to be multiples of four bytes long.
A few protocol requests take no arguments at all. Instead, they use the xReq
structure in <X11/Xproto.h>, which contains only a reqType and a length (and a
pad byte).
If the protocol request requires a reply, then <X11/Xproto.h> also contains a reply
structure typedef:
421
Extensions
Most of these reply structures are 32 bytes long. If there are not that many reply
values, then they contain a sufficient number of pad fields to bring them up to 32
bytes. The length field is the total number of bytes in the request minus 32, divided
by 4. This length will be nonzero only if:
A few protocol requests return replies that contain no data. <X11/Xproto.h> does
not define reply structures for these. Instead, they use the xGenericReply structure,
which contains only a type, length, and sequence number (and sufficient padding
to make it 32 bytes long).
#include "<X11/Xlibint.h>
If the protocol request has a reply, then the variable declarations should include the
reply structure for the request. The following is an example:
xDoSomethingReply rep;
422
Extensions
Generally, this section is the point from just before the appropriate GetReq call until
all arguments to the call have been stored into the buffer. The precise instructions
needed for this locking depend upon the machine architecture. Two calls, which are
generally implemented as macros, have been provided.
LockDisplay(display);
UnlockDisplay(display);
If the protocol request has no arguments (for instance, X_GrabServer), then use
GetEmptyReq.
If the protocol request has a single 32-bit argument (such as a Pixmap, Window,
Drawable, Atom, and so on), then use GetResReq. The second argument to the macro
is the 32-bit object. X_MapWindow is a good example.
If the protocol request takes any other argument list, then call GetReq. After the
GetReq, you need to set all the other fields in the request structure, usually from
arguments to the stub procedure.
423
Extensions
...
return (rid);
It is necessary to add the length of any variable-length data to the length field of
the request structure. That length field is in units of 32-bit longwords. If the data
is a string or other sequence of 8-bit bytes, then you must round the length up and
shift it before adding:
req->length += (nbytes+3)>>2;
To transmit variable-length data, use the Data macros. If the data fits into the output
buffer, then this macro copies it to the buffer. If it does not fit, however, the Data
macro calls _XSend, which transmits first the contents of the buffer and then your
data. The Data macros take three arguments: the display, a pointer to the beginning
of the data, and the number of bytes to be sent.
Data, Data16, and Data32 are macros that may use their last argument more
than once, so that argument should be a variable rather than an expression such
as ``nitems*sizeof(item)''. You should do that kind of computation in a separate
statement before calling them. Use the appropriate macro when sending byte, short,
or long data.
If the protocol request requires a reply, then call the procedure _XSend instead
of the Data macro. _XSend takes the same arguments, but because it sends your
data immediately instead of copying it into the output buffer (which would later be
flushed anyway by the following call on _XReply), it is faster.
Replies
If the protocol request has a reply, then call _XReply after you have finished dealing
with all the fixed-length and variable-length arguments. _XReply flushes the output
424
Extensions
buffer and waits for an xReply packet to arrive. If any events arrive in the meantime,
_XReply places them in the queue for later use.
The _XReply function waits for a reply packet and copies its contents into the
specified rep. _XReply handles error and event packets that occur before the reply
is received. _XReply takes four arguments:
• A Display * structure
Because most reply structures are 32 bytes long, the third argument is usually 0. The
only core protocol exceptions are the replies to GetWindowAttributesl, QueryFont,
QueryKeymap, and GetKeyboardControl, which have longer replies.
The last argument should be False if the reply structure is followed by additional
variable-length data (such as a list or string). It should be True if there is not
any variable-length data. This last argument is provided for upward-compatibility
reasons to allow a client to communicate properly with a hypothetical later
version of the server that sends more data than the client expected. For example,
some later version of GetWindowAttributesl might use a larger, but compatible,
xGetWindowAttributesReply that contains additional attribute data at the end.
_XReply returns True if it received a reply successfully or False if it received any
sort of error.
For a request with a reply that is not followed by variable-length data, you write
something like:
425
Extensions
If there is variable-length data after the reply, change the True to False, and use the
appropriate _XRead function to read the variable-length data.
The _XRead function reads the specified number of bytes into data_return.
The _XRead16 function reads the specified number of bytes, unpacking them as 16-
bit quantities, into the specified array as shorts.
The _XRead32 function reads the specified number of bytes, unpacking them as 32-
bit quantities, into the specified array as longs.
The _XRead16Pad function reads the specified number of bytes, unpacking them as
16-bit quantities, into the specified array as shorts. If the number of bytes is not a
multiple of four, _XRead16Pad reads and discards up to two additional pad bytes.
The _XReadPad function reads the specified number of bytes into data_return. If the
number of bytes is not a multiple of four, _XReadPad reads and discards up to three
additional pad bytes.
426
Extensions
Each protocol request is a little different. For further information, see the Xlib
sources for examples.
Synchronous Calling
Each procedure should have a call, just before returning to the user, to a macro
called SyncHandle. If synchronous mode is enabled (see XSynchronize), the request
is sent immediately. The library, however, waits until any error the procedure could
generate at the server has been handled.
These should be used in place of any calls you would make to the normal C library
functions.
If you need a single scratch buffer inside a critical section (for example, to pack
and unpack data to and from the wire protocol), the general memory allocators may
be too expensive to use (particularly in output functions, which are performance
critical). The following function returns a scratch buffer for use within a critical
section:
This storage must only be used inside of a critical section of your stub. The returned
pointer cannot be assumed valid after any call that might permit another thread to
execute inside Xlib. For example, the pointer cannot be assumed valid after any use
of the GetReq or Data families of macros, after any use of _XReply, or after any use
of the _XSend or _XRead families of functions.
The following function returns a scratch buffer for use across critical sections:
This storage can be used across calls that might permit another thread to execute
inside Xlib. The storage must be explicitly returned to Xlib. The following function
returns the storage:
427
Extensions
You must pass back the same pointer and size that were returned by _XAllocTemp.
Portability Considerations
Many machine architectures do not correctly or efficiently access data at unaligned
locations; their compilers pad out structures to preserve this characteristic. Many
other machines capable of unaligned references pad inside of structures as well to
preserve alignment, because accessing aligned data is usually much faster. Because
the library and the server use structures to access data at arbitrary points in a
byte stream, all data in request and reply packets must be naturally aligned; that
is, 16-bit data starts on 16-bit boundaries in the request and 32-bit data on 32-
bit boundaries. All requests must be a multiple of 32 bits in length to preserve
the natural alignment in the data stream. You must pad structures out to 32-bit
boundaries. Pad information does not have to be zeroed unless you want to preserve
such fields for future use in your protocol requests, but it is recommended to zero it
to avoid inadvertant data leakage and improve compressability. Floating point varies
radically between machines and should be avoided completely if at all possible.
This code may run on machines with 16-bit ints. So, if any integer argument,
variable, or return value either can take only nonnegative values or is declared as a
CARD16 in the protocol, be sure to declare it as unsigned int and not as int. (This,
of course, does not apply to Booleans or enumerations.)
The library has always assumed that a char is 8 bits, a short is 16 bits, an int
is 16 or 32 bits, and a long is 32 bits. Unfortunately, this assumption remains on
machines where a long can hold 64-bits, and many functions and structures require
unnecessarily large fields to avoid breaking compatibility with existing code. Special
care must be taken with arrays of values that are transmitted in the protocol as
CARD32 or INT32 but have to be converted to arrays of 64-bit long when passed
to or from client applications.
The PackData macro is a half-hearted attempt to deal with the possibility of 32 bit
shorts. However, much more work is needed to make this work properly.
• When your stub is entered, your initialization test is just to use the display pointer
passed in to access the file descriptor and an index into the array. If the entry is
428
Extensions
NULL, then this is the first time you are entering the procedure for this display.
Call your initialization procedure and pass to it the display pointer.
• After returning from your initialization procedure, the stub can now continue
normally, because it has its major opcode safely in its hand in the XExtCodes
structure.
429
Appendix D. Compatibility Functions
The X Version 11 and X Version 10 functions discussed in this appendix are obsolete,
have been superseded by newer X Version 11 functions, and are maintained for
compatibility reasons only.
430
Compatibility Functions
To set the size hints for a given window in its normal state, use XSetNormalHints.
This function has been superseded by XSetWMNormalHints.
XSetNormalHints(display, w, hints);
hints Specifies a pointer to the size hints for the window in its
normal state.
The XSetNormalHints function sets the size hints structure for the specified window.
Applications use XSetNormalHints to inform the window manager of the size or
position desirable for that window. In addition, an application that wants to move
or resize itself should call XSetNormalHints and specify its new desired location
and size as well as making direct Xlib calls to move or resize. This is because
window managers may ignore redirected configure requests, but they pay attention
to property changes.
To set size hints, an application not only must assign values to the appropriate
members in the hints structure but also must set the flags member of the structure
to indicate which information is present and where it came from. A call to
XSetNormalHints is meaningless, unless the flags member is set to indicate which
members of the structure have been assigned values.
To return the size hints for a window in its normal state, use XGetNormalHints. This
function has been superseded by XGetWMNormalHints.
hints_return Returns the size hints for the window in its normal
state.
The XGetNormalHints function returns the size hints for a window in its normal
state. It returns a nonzero status if it succeeds or zero if the application specified
no normal size hints for this window.
431
Compatibility Functions
The next two functions set and read the WM_ZOOM_HINTS property.
To set the zoom hints for a window, use XSetZoomHints. This function is no longer
supported by the Inter-Client Communication Conventions Manual.
XSetZoomHints(display, w, zhints);
Many window managers think of windows in one of three states: iconic, normal,
or zoomed. The XSetZoomHints function provides the window manager with
information for the window in the zoomed state.
To read the zoom hints for a window, use XGetZoomHints. This function is no longer
supported by the Inter-Client Communication Conventions Manual.
The XGetZoomHints function returns the size hints for a window in its zoomed state.
It returns a nonzero status if it succeeds or zero if the application specified no zoom
size hints for this window.
To set the value of any property of type WM_SIZE_HINTS, use XSetSizeHints. This
function has been superseded by XSetWMSizeHints.
The XSetSizeHints function sets the XSizeHints structure for the named property
and the specified window. This is used by XSetNormalHints and XSetZoomHints and
can be used to set the value of any property of type WM_SIZE_HINTS. Thus, it may
be useful if other properties of that type get defined.
432
Compatibility Functions
The XGetSizeHints function returns the XSizeHints structure for the named
property and the specified window. This is used by XGetNormalHints and
XGetZoomHints. It also can be used to retrieve the value of any property of type
WM_SIZE_HINTS. Thus, it may be useful if other properties of that type get defined.
XGetSizeHints returns a nonzero status if a size hint was defined or zero otherwise.
433
Compatibility Functions
position
fheight
xadder
x_return
width_return
You pass in the border width (bwidth), size of the increments fwidth and fheight
(typically font width and height), and any additional interior space (xadder and
yadder) to make it easy to compute the resulting size. The XGeometry function
returns the position the window should be placed given a position and a default
position. XGeometry determines the placement of a window using a geometry
specification as specified by XParseGeometry and the additional information about
the window. Given a fully qualified default geometry specification and an incomplete
geometry specification, XParseGeometry returns a bitmask value as defined above
in the XParseGeometry call, by using the position argument.
434
Compatibility Functions
The returned width and height will be the width and height specified by
default_position as overridden by any user-specified position. They are not affected
by fwidth, fheight, xadder, or yadder. The x and y coordinates are computed by using
the border width, the screen width and height, padding as specified by xadder and
yadder, and the fheight and fwidth times the width and height from the geometry
specifications.
program Specifies the program name for the Xlib defaults (usually
argv[0] of the main program).
The XGetDefault function returns the value of the resource prog.option, where prog
is the program argument with the directory prefix removed and option must be a
single component. Note that multilevel resources cannot be used with XGetDefault.
The class "Program.Name" is always used for the resource lookup. If the specified
option name does not exist for this program, XGetDefault returns NULL. The
strings returned by XGetDefault are owned by Xlib and should not be modified or
freed by the client.
If a database has been set with XrmSetDatabase, that database is used for
the lookup. Otherwise, a database is created and is set in the display (as if
by calling XrmSetDatabase). The database is created in the current locale. To
create a database, XGetDefault uses resources from the RESOURCE_MANAGER
property on the root window of screen zero. If no such property exists, a resource
file in the user's home directory is used. On a POSIX-conformant system, this
file is "$HOME/.Xdefaults". After loading these defaults, XGetDefault merges
additional defaults specified by the XENVIRONMENT environment variable. If
XENVIRONMENT is defined, it contains a full path name for the additional resource
file. If XENVIRONMENT is not defined, XGetDefault looks for "$HOME/.Xdefaults-
name" , where name specifies the name of the machine on which the application is
running.
435
Compatibility Functions
no server support. That is, they call other Xlib functions, not the server directly.
Thus, if you just have straight lines to draw, using XDrawLines or XDrawSegments
is much faster.
The functions discussed here provide all the functionality of the X Version 10
functions XDraw, XDrawFilled, XDrawPatterned, XDrawDashed, and XDrawTiled.
They are as compatible as possible given X Version 11's new line-drawing functions.
One thing to note, however, is that VertexDrawLastPoint is no longer supported.
Also, the error status returned is the opposite of what it was under X Version 10 (this
is the X Version 11 standard error status). XAppendVertex and XClearVertexFlag
from X Version 10 also are not supported.
Just how the graphics context you use is set up actually determines whether you get
dashes or not, and so on. Lines are properly joined if they connect and include the
closing of a closed figure (see XDrawLines). The functions discussed here fail (return
zero) only if they run out of memory or are passed a Vertex list that has a Vertex with
VertexStartClosed set that is not followed by a Vertex with VertexEndClosed set.
#include <X11/X10.h>
The XDraw function draws an arbitrary polygon or curve. The figure drawn is defined
by the specified list of vertices (vlist). The points are connected by lines as specified
in the flags in the vertex structure.
The x and y members are the coordinates of the vertex that are relative to either the
upper left inside corner of the drawable (if VertexRelative is zero) or the previous
vertex (if VertexRelative is one).
436
Compatibility Functions
• If VertexRelative is not set, the coordinates are absolute (that is, relative to the
drawable's origin). The first vertex must be an absolute vertex.
• If VertexStartClosed is one, then this point marks the beginning of a closed curve.
This vertex must be followed later in the array by another vertex whose effective
coordinates are identical and that has a VertexEndClosed bit of one. The points
in between form a cycle to determine predecessor and successor vertices for the
spline algorithm.
#include <X11/X10.h>
The XDrawFilled function draws arbitrary polygons or curves and then fills them.
437
Compatibility Functions
An XAssocTable can be used to type X resources. For example, the user may want
to have three or four types of windows, each with different properties. This can be
accomplished by associating each X window ID with a pointer to a window property
data structure defined by the user. A generic type has been defined in the X library
for resource IDs. It is called an XID.
There are a few guidelines that should be observed when using an XAssocTable :
• Because of the hashing scheme used by the association mechanism, the following
rules for determining the size of a XAssocTable should be followed. Associations
will be made and looked up more efficiently if the table size (number of buckets
in the hashing system) is a power of two and if there are not more than 8 XIDs
per bucket.
XAssocTable *XCreateAssocTable(size);
The size argument specifies the number of buckets in the hash system of
XAssocTable. For reasons of efficiency the number of buckets should be a power
of two. Some size suggestions might be: use 32 buckets per 100 objects, and a
reasonable maximum number of objects per buckets is 8. If an error allocating
memory for the XAssocTable occurs, a NULL pointer is returned.
The XMakeAssoc function inserts data into an XAssocTable keyed on an XID. Data is
inserted into the table only once. Redundant inserts are ignored. The queue in each
association bucket is sorted from the lowest XID to the highest XID.
438
Compatibility Functions
The XLookUpAssoc function retrieves the data stored in an XAssocTable by its XID.
If an appropriately matching XID can be found in the table, XLookUpAssoc returns
the data associated with it. If the x_id cannot be found in the table, it returns NULL.
XDestroyAssocTable(table);
439
Glossary
References
Draft Proposed Multibyte Extension of ANSI C, Draft 1.1. November 30, 1989 SC22/C WG/
SWG IPSJ/ITSCJ Japan.
ISO2022: Information processing - ISO 7-bit and 8-bit coded character sets - Code extension
techniques..
ISO8859-1: Information processing - 8-bit single-byte coded graphic character sets - Part 1:
Latin alphabet No. 1..
X/Open Portability Guide, Issue 3, December 1988 (XPG3), X/Open Company, Ltd, Prentice-
Hall, Inc. 1989. ISBN 0-13-685835-8. (See especially Volume 3: XSI Supplementary
Definitions.).
Access control list X maintains a list of hosts from which client programs can
be run. By default, only programs on the local host and hosts
specified in an initial list read by the server can use the display.
This access control list can be changed by clients on the local
host. Some server implementations can also implement other
authorization mechanisms in addition to or in place of this
mechanism. The action of this mechanism can be conditional
based on the authorization protocol name and data received by
the server at connection setup.
Active grab A grab is active when the pointer or keyboard is actually owned
by the single grabbing client.
Backing store When a server maintains the contents of a window, the pixels
saved off-screen are known as a backing store.
Base font name A font name used to select a family of fonts whose members
may be encoded in various charsets. The CharSetRegistry and
CharSetEncoding fields of an XLFD name identify the charset of
the font. A base font name may be a full XLFD name, with all
440
Glossary
Bit gravity When a window is resized, the contents of the window are not
necessarily discarded. It is possible to request that the server
relocate the previous contents to some region of the window
(though no guarantees are made). This attraction of window
contents for some location of a window is known as bit gravity.
Byte order For image (pixmap/bitmap) data, the server defines the byte
order, and clients with different native byte ordering must swap
bytes as necessary. For all other parts of the protocol, the client
defines the byte order, and the server swaps bytes as necessary.
Character glyph The abstract graphical symbol for a character. Character glyphs
may or may not map one-to-one to font glyphs, and may
be context-dependent, varying with the adjacent characters.
Multiple characters may map to a single character glyph.
441
Glossary
Coded character set A set of unambiguous rules that establishes a character set and
the one-to-one relationship between each character of the set
and its bit representation. (ISO2022, as adapted by XPG3) A
definition of a one-to-one mapping of a set of characters to a set
of codepoints.
Connection The IPC path between the server and client program is known
as a connection. A client program typically (but not necessarily)
has one connection to the server over which requests and events
are sent.
Containment A window contains the pointer if the window is viewable and the
hotspot of the cursor is within a visible region of the window or
a visible region of one of its inferiors. The border of the window
is included as part of the window for containment. The pointer
442
Glossary
Coordinate system The coordinate system has X horizontal and Y vertical, with
the origin [0, 0] at the upper left. Coordinates are integral and
coincide with pixel centers. Each window and pixmap has its own
coordinate system. For a window, the origin is inside the border
at the inside upper-left corner.
Depth The depth of a window or pixmap is the number of bits per pixel it
has. The depth of a graphics context is the depth of the drawables
it can be used in conjunction with graphics output.
Display A server, together with its screens and input devices, is called a
display. The Xlib Display structure contains all information about
the particular display and its screens as well as the state that
Xlib needs to communicate with the display over a particular
connection.
443
Glossary
Event mask Events are requested relative to a window. The set of event types
a client requests relative to a window is described by using an
event mask.
Event source The deepest viewable window that the pointer is in is called the
source of a device-related event.
Event synchronization There are certain race conditions possible when demultiplexing
device events to clients (in particular, deciding where pointer
and keyboard events should be sent when in the middle of
window management operations). The event synchronization
mechanism allows synchronous processing of device events.
Font glyph The abstract graphical symbol for an index into a font.
Frozen events Clients can freeze event processing during keyboard and pointer
grabs.
444
Glossary
Grab Keyboard keys, the keyboard, pointer buttons, the pointer, and
the server can be grabbed for exclusive use by a client. In
general, these facilities are not intended to be used by normal
applications but are intended for various input and window
managers to implement various styles of user interfaces.
Host Portable Character The encoding of the X Portable Character Set on the host. The
Encoding encoding itself is not defined by this standard, but the encoding
must be the same in all locales supported by Xlib on the host. If
a string is said to be in the Host Portable Character Encoding,
then it only contains characters from the X Portable Character
Set, in the host encoding.
Hotspot A cursor has an associated hotspot, which defines the point in the
cursor corresponding to the coordinates reported for the pointer.
Inferiors The inferiors of a window are all of the subwindows nested below
it: the children, the children's children, and so on.
Input focus The input focus is usually a window defining the scope for
processing of keyboard input. If a generated keyboard event
usually would be reported to this window or one of its inferiors,
the event is reported as usual. Otherwise, the event is reported
with respect to the focus window. The input focus also can be
set such that all keyboard events are discarded and such that
the focus window is dynamically taken to be the root window of
whatever screen the pointer is on at each keyboard event.
445
Glossary
InputOutput window An InputOutput window is the normal kind of window that is used
for both input and output. InputOutput windows can have both
InputOutput and InputOnly windows as inferiors.
ISO2022 ISO standard for code extension techniques for 7-bit and 8-bit
coded character sets.
Key grabbing Keys on the keyboard can be passively grabbed by a client. When
the key is pressed, the keyboard is then actively grabbed by the
client.
Keyboard grabbing A client can actively grab control of the keyboard, and key events
will be sent to that client rather than the client the events would
normally have been sent to.
Latin Portable Character The encoding of the X Portable Character Set using the Latin-1
Encoding codepoints plus ASCII control characters. If a string is said to be
in the Latin Portable Character Encoding, then it only contains
characters from the X Portable Character Set, not all of Latin-1.
446
Glossary
Locale name The identifier used to select the desired locale for the host C
library and X library functions. On ANSI C library compliant
systems, the locale argument to the setlocale function.
Modifier keys Shift, Control, Meta, Super, Hyper, Alt, Compose, Apple,
CapsLock, ShiftLock, and similar keys are called modifier keys.
Padding Some padding bytes are inserted in the data stream to maintain
alignment of the protocol requests on natural boundaries. This
increases ease of portability to some machine architectures.
Passive grab Grabbing a key or button is a passive grab. The grab activates
when the key or button is actually pressed.
Pixel value A pixel is an N-bit value, where N is the number of bit planes
used in a particular window or pixmap (that is, is the depth of
447
Glossary
Pointer grabbing A client can actively grab control of the pointer. Then button and
motion events will be sent to that client rather than the client
the events would normally have been sent to.
POSIX Portable The set of 65 characters which can be used in naming files on a
Filename Character Set POSIX-compliant host that are correctly processed in all locales.
The set is:
Property list The property list of a window is the list of properties that have
been defined for the window.
448
Glossary
Redirecting control Window managers (or client programs) may enforce window
layout policy in various ways. When a client attempts to change
the size or position of a window, the operation may be redirected
to a specified client rather than the operation actually being
performed.
RGB values RGB values are the red, green, and blue intensity values that
are used to define a color. These values are always represented
as 16-bit, unsigned numbers, with 0 the minimum intensity and
65535 the maximum intensity. The X server scales these values
to match the display hardware.
Root The root of a pixmap or graphics context is the same as the root
of whatever drawable was used when the pixmap or GC was
created. The root of a window is the root window under which
the window was created.
Root window Each screen has a root window covering it. The root window
cannot be reconfigured or unmapped, but otherwise it acts as a
full-fledged window. A root window has no parent.
Save set The save set of a client is a list of other clients' windows that,
if they are inferiors of one of the client's windows at connection
close, should not be destroyed and that should be remapped
if currently unmapped. Save sets are typically used by window
managers to avoid lost windows if the manager should terminate
abnormally.
449
Glossary
The target type can also be used to control the class of contents
transmitted; for example, asking for the ``looks'' (fonts, line
spacing, indentation, and so forth) of a paragraph selection,
rather than the text of the paragraph. The target type can also
be used for other purposes. The protocol does not constrain the
semantics.
Server grabbing The server can be grabbed by a single client for exclusive
use. This prevents processing of any requests from other client
connections until the grab is completed. This is typically only a
transient state for such things as rubber-banding, pop-up menus,
or executing requests indivisibly.
Shift sequence ISO2022 defines control characters and escape sequences which
temporarily (single shift) or permanently (locking shift) cause a
different character set to be in effect (``invoking'' a character
set).
Stacking order Sibling windows, similar to sheets of paper on a desk, can stack
on top of each other. Windows above both obscure and occlude
lower windows. The relationship between sibling windows is
known as the stacking order.
450
Glossary
State-independent Any encoding in which the invocations of the charsets are fixed,
encoding or span only a single character. In ISO2022 terms, this means
use of at most single shifts, not locking shifts.
Status Many Xlib functions return a success status. If the function does
not succeed, however, its arguments are not disturbed.
String Equivalence Two ISO Latin-1 STRING8 values are considered equal if they
are the same length and if corresponding bytes are either
equal or are equivalent as follows: decimal values 65 to 90
inclusive (characters ``A'' to ``Z'') are pairwise equivalent to
decimal values 97 to 122 inclusive (characters ``a'' to ``z''),
decimal values 192 to 214 inclusive (characters ``A grave'' to
``O diaeresis'') are pairwise equivalent to decimal values 224
to 246 inclusive (characters ``a grave'' to ``o diaeresis''), and
decimal values 216 to 222 inclusive (characters ``O oblique'' to
``THORN'') are pairwise equivalent to decimal values 246 to 254
inclusive (characters ``o oblique'' to ``thorn'').
451
Glossary
for many frequently used types, and clients also can define new
types.
Window manager Manipulation of windows on the screen and much of the user
interface (policy) is typically provided by a window manager
client.
X Portable Character Set A basic set of 97 characters which are assumed to exist in
all locales supported by Xlib. This set contains the following
characters:
452
BadWindow, 228
Index Base font name, 440
Bit
gravity, 441
Symbols plane, 441
_XAllocScratch, 427 Bitmap, 2, 441
_XAllocTemp, 427 BitmapBitOrder, 16
_Xdebug, 225 BitmapPad, 16
_XFlushGCCache, 418 BitmapUnit, 15
_XFreeTemp, 427 BlackPixel, 9
_XReply, 425 BlackPixelOfScreen, 17
_XSetLastRequestRead, 414 Bool, 4
Border, 441
A Button
Access control list, 173, 440 grabbing, 234, 441
Active grab, 231, 440 ungrabbing, 236
Allocation ButtonPress, 185
colormap, 82 ButtonRelease, 185
read-only colormap cells, 82, 82, 83, 83 Byte
read/write colormap cells, 84 order, 441
read/write colormap planes, 85
AllPlanes, 9
Ancestors, 440
C
Arcs CallbackPrototype, 311
drawing, 141 CCC, 78
filling, 145 creation, 94
Areas default, 78, 91, 92, 92
clearing, 134 freeing, 95
copying, 135 of colormap, 78, 91, 91, 91
Atom, 56, 56, 440 CellsOfScreen, 17
getting name, 58, 58 Changing
interning, 57, 58 pointer grab, 234
predefined, 56 Character, 441
Authentication, 173 Character glyph, 441
Character set, 441
Charset, 441
B Child window, 2
Background, 440
Child Window, 51
Backing store, 440
Children, 442
BadAccess, 227
Chroma, 107, 107, 108
BadAlloc, 227
maximum, 107, 107, 108
BadAtom, 227
CIE metric lightness, 103, 103, 104, 104, 105,
BadColor, 227
105, 106, 106
BadCursor, 227
maximum, 103, 104, 105, 106
BadDrawable, 227
minimum, 104, 106
BadFont, 227
CirculateNotify, 199
BadGC, 227
CirculateRequest, 207
BadIDChoice, 227
Class, 442
BadImplementation, 228
Clearing
BadLength, 228
areas, 134
BadMatch, 228
windows, 135
BadName, 228
Client, 442
BadPixmap, 228
Client White Point, 78
BadRequest, 228
of Color Conversion Context, 93
BadValue, 228
453
Index
D E
Debugging Encoding, 443
error event, 226 EnterNotify, 188
error handlers, 226 Environment
error message strings, 228 DISPLAY, 7
error numbers, 227 Error
synchronous mode, 225 codes, 227
Default Protection, 173 handlers, 226
DefaultColormap, 10 handling, 3
DefaultColormapOfScreen, 17 Escapement, 444
DefaultDepth, 10 Event, 3, 178, 444
454
Index
455
Index
456
Index
457
Index
458
Index
X11/Xcms.h, 3, 71 XCirculateSubwindowsDown, 46
X11/Xlib.h, 3, 8, 71, 179, 386 XCirculateSubwindowsUp, 46
X11/Xlibint.h, 4 XClassHint, 341
X11/Xproto.h, 4, 199 XClearArea, 134
X11/Xprotostr.h, 4 XClearWindow, 135
X11/Xresource.h, 3, 357 XClientMessageEvent, 211
X11/Xutil.h, 3, 335, 337, 341, 344, 378, 379, XClipBox, 380
384, 387, 392, 431 XCloseDisplay, 20, 21
XActivateScreenSaver, 172 XCloseIM, 291
XAddExtension, 411 XCloseOM, 260
XAddHost, 175 XcmsAddColorSpace, 109
XAddHosts, 175 XcmsAddFunctionSet, 113
XAddPixel, 388 XcmsAllocColor, 82
XAddToExtensionList, 417 XcmsAllocNamedColor, 83
XAddToSaveSet, 167 XcmsCCCOfColormap, 91
XAllocClassHint, 341 XcmsCIELab, 74
XAllocColor, 82, 86 XcmsCIELabQueryMaxC, 103
XAllocColorCells, 84, 86 XcmsCIELabQueryMaxL, 103
XAllocColorPlanes, 85, 86 XcmsCIELabQueryMaxLC, 104
XAllocID, 418 XcmsCIELabQueryMinL, 104
XAllocIDs, 418 XcmsCIELuv, 75
XAllocNamedColor, 83, 86 XcmsCIELuvQueryMaxC, 105
XAllowEvents, 239 XcmsCIELuvQueryMaxL, 105
XAllPlanes, 9 XcmsCIELuvQueryMaxLC, 106
XAnyEvent, 179 XcmsCIELuvQueryMinL, 106
XArc, 138 XcmsCIEuvY, 74
XAutoRepeatOff, 245 XcmsCIExyY, 74
XAutoRepeatOn, 245 XcmsCIEXYZ, 74
XBaseFontNameListOfFontSet, 272 XcmsClientWhitePointOfCCC, 93
XBell, 246 XcmsColor, 72
XBitmapBitOrder, 16 XcmsCompressionProc, 96
XBitmapPad, 16 XcmsConvertColors, 95
XBitmapUnit, 15 XcmsCreateCCC, 94
XBlackPixel, 9 XcmsDefaultCCC, 92
XBlackPixelOfScreen, 17 XcmsDisplayOfCCC, 92
XCellsOfScreen, 17 XcmsFormatOfPrefix, 110
XChangeActivePointerGrab, 234 XcmsFreeCCC, 95
XChangeGC, 124 XcmsLookupColor, 81
XChangeKeyboardControl, 244 XcmsPad, 75
XChangeKeyboardMapping, 250 XcmsParseStringProc, 111
XChangePointerControl, 247 XcmsPrefixOfFormat, 110
XChangeProperty, 61 XcmsQueryBlack, 101
XChangeSaveSet, 167 XcmsQueryBlue, 101
XChangeWindowAttributes, 47 XcmsQueryColor, 90
XChar2b, 147 XcmsQueryColors, 90
XCharStruct, 147 XcmsQueryGreen, 102
XCheckIfEvent, 220 XcmsQueryRed, 102
XCheckMaskEvent, 222 XcmsQueryWhite, 102
XCheckTypedEvent, 222 XcmsRGB, 73
XCheckTypedWindowEvent, 222 XcmsRGBi, 74
XCheckWindowEvent, 221, 221 XcmsScreenInitProc, 114
XCirculateEvent, 200 XcmsScreenNumberOfCCC, 92
XCirculateRequestEvent, 208 XcmsScreenWhitePointOfCCC, 93
XCirculateSubwindows, 46 XcmsSetCCCOfColormap, 91
459
Index
XcmsSetCompressionProc, 93 XDefaultVisualOfScreen, 18
XcmsSetWhiteAdjustProc, 94 XDefineCursor, 36, 50
XcmsSetWhitePoint, 93 XDeleteAssoc, 439
XcmsStoreColor, 87 XDeleteContext, 392
XcmsStoreColors, 88 XDeleteModifiermapEntry, 252
XcmsTekHVC, 75 XDeleteProperty, 62
XcmsTekHVCQueryMaxC, 107 XDestroyAssocTable, 439
XcmsTekHVCQueryMaxV, 107 XDestroyIC, 297
XcmsTekHVCQueryMaxVC, 107 XDestroyImage, 388
XcmsTekHVCQueryMaxVSamples, 108 XDestroyOC, 264
XcmsTekHVCQueryMinV, 108 XDestroyRegion, 380
XcmsVisualOfCCC, 92 XDestroySubwindows, 38
XcmsWhiteAdjustProc, 99 XDestroyWindow, 37
XColor, 72 XDestroyWindowEvent, 202
XColormapEvent, 211 XDirectionalDependentDrawing, 273
XConfigureEvent, 201 XDisableAccessControl, 177
XConfigureRequestEvent, 209 XDisplayCells, 12
XConfigureWindow, 42 XDisplayHeight, 16
XConnectionNumber, 10 XDisplayHeightMM, 16
XContextDependentDrawing, 273 XDisplayKeycodes, 249
XContextualDrawing, 273 XDisplayMotionBufferSize, 224
XConvertCase, 374 XDisplayName, 229
XConvertSelection, 64 XDisplayOfIM, 291
XCopyArea, 135 XDisplayOfOM, 261
XCopyColormapAndFree, 79 XDisplayOfScreen, 18
XCopyGC, 123 XDisplayPlanes, 12
XCopyPlane, 136 XDisplayString, 12
XCreateAssocTable, 438 XDisplayWidth, 16
XCreateBitmapFromData, 391 XDisplayWidthMM, 17
XCreateColormap, 79 XDoesBackingStore, 18
XCreateFontCursor, 67 XDoesSaveUnders, 18
XCreateFontSet, 268 xDoSomethingReply, 422
XCreateGC, 123 xDoSomethingReq, 421
XCreateGlyphCursor, 67 XDrawArc, 141, 141
XCreateIC, 297 XDrawArcs, 141, 142
XCreateImage, 386 XDrawImageString, 160, 160
XCreateOC, 263 XDrawImageString16, 160, 160
XCreatePixmap, 66 XDrawLine, 139, 139
XCreatePixmapCursor, 68 XDrawLines, 139, 139, 436
XCreatePixmapFromBitmapData, 390 XDrawPoint, 138, 138
XCreateSimpleWindow, 36 XDrawPoints, 138, 138
XCreateWindow, 35 XDrawRectangle, 140, 140
XCreateWindowEvent, 202 XDrawRectangles, 140, 141
XCrossingEvent, 189 XDrawSegments, 139, 139, 436
XDefaultColormap, 10 XDrawString, 159
XDefaultColormapOfScreen, 17 XDrawString16, 159
XDefaultDepth, 10 XDrawText, 158
XDefaultDepthOfScreen, 17 XDrawText16, 158
XDefaultGC, 11 XEHeadOfExtensionList, 417
XDefaultGCOfScreen, 18 XEmptyRegion, 382
XDefaultRootWindow, 11 XEnableAccessControl, 176
XDefaultScreen, 11 XEnterWindowEvent, 189
XDefaultScreenOfDisplay, 11 XEqualRegion, 382
XDefaultVisual, 12 XErrorEvent, 226
460
Index
461
Index
462
Index
463
Index
464
Index
465