Xlib - C Language X Interface

X Consortium Standard

James Gettys

Digital Equipment Corporation
Cambridge Research Laboratory

Robert W. Scheifler

Massachusetts Institute of Technology
Laboratory for Computer Science

Chuck Adams

Tektronix, Inc.

Vania Joloboff

Open Software Foundation

Hideki Hiura

Sun Microsystems, Inc.

Bill McMahon

Hewlett-Packard Company

Ron Newman

Massachusetts Institute of Technology

Al Tabayoyon

Tektronix, Inc.

Glenn Widener

Tektronix, Inc.

Shigeru Yamada

Fujitsu OSSI

X Version 11, Release 7.7

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

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.

TekHVC is a trademark of Tektronix, Inc.


Table of Contents

Acknowledgments
1. Introduction to Xlib
Overview of the X Window System
Errors
Standard Header Files
Generic Values and Types
Naming and Argument Conventions within Xlib
Programming Considerations
Character Sets and Encodings
Formatting Conventions
2. Display Functions
Opening the Display
Obtaining Information about the Display, Image Formats, or Screens
Display Macros
Image Format Functions and Macros
Screen Information Macros
Generating a NoOperation Protocol Request
Freeing Client-Created Data
Closing the Display
Using X Server Connection Close Operations
Using Xlib with Threads
Using Internal Connections
3. Window Functions
Visual Types
Window Attributes
Background Attribute
Border Attribute
Gravity Attributes
Backing Store Attribute
Save Under Flag
Backing Planes and Backing Pixel Attributes
Event Mask and Do Not Propagate Mask Attributes
Override Redirect Flag
Colormap Attribute
Cursor Attribute
Creating Windows
Destroying Windows
Mapping Windows
Unmapping Windows
Configuring Windows
Changing Window Stacking Order
Changing Window Attributes
4. Window Information Functions
Obtaining Window Information
Translating Screen Coordinates
Properties and Atoms
Obtaining and Changing Window Properties
Selections
5. Pixmap and Cursor Functions
Creating and Freeing Pixmaps
Creating, Recoloring, and Freeing Cursors
6. Color Management Functions
Color Structures
Color Strings
RGB Device String Specification
RGB Intensity String Specification
Device-Independent String Specifications
Color Conversion Contexts and Gamut Mapping
Creating, Copying, and Destroying Colormaps
Mapping Color Names to Values
Allocating and Freeing Color Cells
Modifying and Querying Colormap Cells
Color Conversion Context Functions
Getting and Setting the Color Conversion Context of a Colormap
Obtaining the Default Color Conversion Context
Color Conversion Context Macros
Modifying Attributes of a Color Conversion Context
Creating and Freeing a Color Conversion Context
Converting between Color Spaces
Callback Functions
Prototype Gamut Compression Procedure
Supplied Gamut Compression Procedures
Prototype White Point Adjustment Procedure
Supplied White Point Adjustment Procedures
Gamut Querying Functions
Red, Green, and Blue Queries
CIELab Queries
CIELuv Queries
TekHVC Queries
Color Management Extensions
Color Spaces
Adding Device-Independent Color Spaces
Querying Color Space Format and Prefix
Creating Additional Color Spaces
Parse String Callback
Color Specification Conversion Callback
Function Sets
Adding Function Sets
Creating Additional Function Sets
7. Graphics Context Functions
Manipulating Graphics Context/State
Using Graphics Context Convenience Routines
Setting the Foreground, Background, Function, or Plane Mask
Setting the Line Attributes and Dashes
Setting the Fill Style and Fill Rule
Setting the Fill Tile and Stipple
Setting the Current Font
Setting the Clip Region
Setting the Arc Mode, Subwindow Mode, and Graphics Exposure
8. Graphics Functions
Clearing Areas
Copying Areas
Drawing Points, Lines, Rectangles, and Arcs
Drawing Single and Multiple Points
Drawing Single and Multiple Lines
Drawing Single and Multiple Rectangles
Drawing Single and Multiple Arcs
Filling Areas
Filling Single and Multiple Rectangles
Filling a Single Polygon
Filling Single and Multiple Arcs
Font Metrics
Loading and Freeing Fonts
Obtaining and Freeing Font Names and Information
Computing Character String Sizes
Computing Logical Extents
Querying Character String Sizes
Drawing Text
Drawing Complex Text
Drawing Text Characters
Drawing Image Text Characters
Transferring Images between Client and Server
9. Window and Session Manager Functions
Changing the Parent of a Window
Controlling the Lifetime of a Window
Managing Installed Colormaps
Setting and Retrieving the Font Search Path
Grabbing the Server
Killing Clients
Controlling the Screen Saver
Controlling Host Access
Adding, Getting, or Removing Hosts
Changing, Enabling, or Disabling Access Control
10. Events
Event Types
Event Structures
Event Masks
Event Processing Overview
Keyboard and Pointer Events
Pointer Button Events
Keyboard and Pointer Events
Window Entry/Exit Events
Normal Entry/Exit Events
Grab and Ungrab Entry/Exit Events
Input Focus Events
Normal Focus Events and Focus Events While Grabbed
Focus Events Generated by Grabs
Key Map State Notification Events
Exposure Events
Expose Events
GraphicsExpose and NoExpose Events
Window State Change Events
CirculateNotify Events
ConfigureNotify Events
CreateNotify Events
DestroyNotify Events
GravityNotify Events
MapNotify Events
MappingNotify Events
ReparentNotify Events
UnmapNotify Events
VisibilityNotify Events
Structure Control Events
CirculateRequest Events
ConfigureRequest Events
MapRequest Events
ResizeRequest Events
Colormap State Change Events
Client Communication Events
ClientMessage Events
PropertyNotify Events
SelectionClear Events
SelectionRequest Events
SelectionNotify Events
11. Event Handling Functions
Selecting Events
Handling the Output Buffer
Event Queue Management
Manipulating the Event Queue
Returning the Next Event
Selecting Events Using a Predicate Procedure
Selecting Events Using a Window or Event Mask
Putting an Event Back into the Queue
Sending Events to Other Applications
Getting Pointer Motion History
Handling Protocol Errors
Enabling or Disabling Synchronization
Using the Default Error Handlers
12. Input Device Functions
Pointer Grabbing
Keyboard Grabbing
Resuming Event Processing
Moving the Pointer
Controlling Input Focus
Manipulating the Keyboard and Pointer Settings
Manipulating the Keyboard Encoding
13. Locales and Internationalized Text Functions
X Locale Management
Locale and Modifier Dependencies
Variable Argument Lists
Output Methods
Output Method Overview
Output Method Functions
X Output Method Values
Output Context Functions
Output Context Values
Creating and Freeing a Font Set
Obtaining Font Set Metrics
Drawing Text Using Font Sets
Input Methods
Input Method Overview
Input Method Management
Input Method Functions
Input Method Values
Input Context Functions
Input Context Values
Input Method Callback Semantics
Event Filtering
Getting Keyboard Input
Input Method Conventions
String Constants
14. Inter-Client Communication Functions
Client to Window Manager Communication
Manipulating Top-Level Windows
Converting String Lists
Setting and Reading Text Properties
Setting and Reading the WM_NAME Property
Setting and Reading the WM_ICON_NAME Property
Setting and Reading the WM_HINTS Property
Setting and Reading the WM_NORMAL_HINTS Property
Setting and Reading the WM_CLASS Property
Setting and Reading the WM_TRANSIENT_FOR Property
Setting and Reading the WM_PROTOCOLS Property
Setting and Reading the WM_COLORMAP_WINDOWS Property
Setting and Reading the WM_ICON_SIZE Property
Using Window Manager Convenience Functions
Client to Session Manager Communication
Setting and Reading the WM_COMMAND Property
Setting and Reading the WM_CLIENT_MACHINE Property
Standard Colormaps
Standard Colormap Properties and Atoms
Setting and Obtaining Standard Colormaps
15. Resource Manager Functions
Resource File Syntax
Resource Manager Matching Rules
Quarks
Creating and Storing Databases
Merging Resource Databases
Looking Up Resources
Storing into a Resource Database
Enumerating Database Entries
Parsing Command Line Options
16. Application Utility Functions
Using Keyboard Utility Functions
KeySym Classification Macros
Using Latin-1 Keyboard Event Functions
Allocating Permanent Storage
Parsing the Window Geometry
Manipulating Regions
Creating, Copying, or Destroying Regions
Moving or Shrinking Regions
Computing with Regions
Determining if Regions Are Empty or Equal
Locating a Point or a Rectangle in a Region
Using Cut Buffers
Determining the Appropriate Visual Type
Manipulating Images
Manipulating Bitmaps
Using the Context Manager
A. Xlib Functions and Protocol Requests
B. X Font Cursors
C. Extensions
Basic Protocol Support Routines
Hooking into Xlib
Hooks into the Library
Hooks onto Xlib Data Structures
GC Caching
Graphics Batching
Writing Extension Stubs
Requests, Replies, and Xproto.h
Request Format
Starting to Write a Stub Procedure
Locking Data Structures
Sending the Protocol Request and Arguments
Variable Length Arguments
Replies
Synchronous Calling
Allocating and Deallocating Memory
Portability Considerations
Deriving the Correct Extension Opcode
D. Compatibility Functions
X Version 11 Compatibility Functions
Setting Standard Properties
Setting and Getting Window Sizing Hints
Getting and Setting an XStandardColormap Structure
Parsing Window Geometry
Getting the X Environment Defaults
X Version 10 Compatibility Functions
Drawing and Filling Polygons and Curves
Associating User Data with a Value
Glossary
Index

List of Tables

A.1. Protocol requests made by each Xlib function
A.2. Xlib functions which use each Protocol Request

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.

Our special thanks must go to Sam Fuller, Vice-President of Corporate Research at Digital, who has remained committed to the widest public availability of X and who made it possible to greatly supplement MIT's resources with the Digital staff 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.

Of course, we must particularly thank Paul Asente, formerly of Stanford University and now of Digital UEG-WSL, who wrote W, the predecessor to X, and Brian Reid, formerly of Stanford University and now of Digital WRL, who had much to do with W's design.

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).

We are deeply indebted to Tatsuya Kato (NTT), Hiroshi Kuribayashi (OMRON), Seiji Kuwari (OMRON), Muneiyoshi Suzuki (NTT), and Li Yuhong (OMRON) for producing one of the first complete sample implementation of the internationalization facilities, and Hiromu Inukai (Nihon Sun), Takashi Fujiwara (Fujitsu), Hideki Hiura (Sun), Yasuhiro Kawai (Oki Technosystems Laboratory), Kazunori Nishihara (Fuji Xerox), Masaki Takeuchi (Sony), Katsuhisa Yano (Toshiba), Makoto Wakamatsu (Sony Corporation) for producing the another complete sample implementation of the internationalization facilities.

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.

The principal authors of the internationalization facilities, including Input and Output Methods, are Hideki Hiura (SunSoft) and Shigeru Yamada (Fujitsu OSSI). Although the words and much of the design are due to them, many others have contributed substantially to the design and implementation. They are: Takashi Fujiwara (Fujitsu), Yoshio Horiuchi (IBM), Makoto Inada (Digital), Hiromu Inukai (Nihon SunSoft), Song JaeKyung (KAIST), Franky Ling (Digital), Tom McFarland (HP), Hiroyuki Miyamoto (Digital), Masahiko Narita (Fujitsu), Frank Rojas (IBM), Hidetoshi Tajima (HP), Masaki Takeuchi (Sony), Makoto Wakamatsu (Sony), Masaki Wakao (IBM), Katsuhisa Yano(Toshiba) and Jinsoo Yoon (KAIST).

The principal producers of the sample implementation of the internationalization facilities are: Jeffrey Bloomfield (Fujitsu OSSI), Takashi Fujiwara (Fujitsu), Hideki Hiura (SunSoft), Yoshio Horiuchi (IBM), Makoto Inada (Digital), Hiromu Inukai (Nihon SunSoft), Song JaeKyung (KAIST), Riki Kawaguchi (Fujitsu), Franky Ling (Digital), Hiroyuki Miyamoto (Digital), Hidetoshi Tajima (HP), Toshimitsu Terazono (Fujitsu), Makoto Wakamatsu (Sony), Masaki Wakao (IBM), Shigeru Yamada (Fujitsu OSSI) and Katsuhisa Yano (Toshiba).

The coordinators of the integration, testing, and release of this implementation of the internationalization facilities are Nobuyuki Tanaka (Sony) and Makoto Wakamatsu (Sony).

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
Laboratory for Computer Science
Massachusetts Institute of Technology

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.

Xlib − C Language X Interface is a reference guide to the low-level C language interface to the X Window System protocol. It is neither a tutorial nor a user’s guide to programming the X Window System. Rather, it provides a detailed description of each function in the library as well as a discussion of the related background information. Xlib − C Language X Interface assumes a basic understanding of a graphics window system and of the C programming language. Other higher-level abstractions (for example, those provided by the toolkits for X) are built on top of the Xlib library. For further information about these higher-level libraries, see the appropriate toolkit documentation. The X Window System Protocol provides the definitive word on the behavior of X. Although additional information appears here, the protocol document is the ruling document.

To provide an introduction to X programming, this chapter discusses:

Overview of the X Window System

Some of the terms used in this book are unique to X, and other terms that are common to other window systems have different meanings in X. You may find it helpful to refer to the glossary, which is located at the end of the book.

The X Window System supports one or more screens containing overlapping windows or subwindows. A screen is a physical monitor and hardware that can be color, grayscale, or monochrome. There can be multiple screens for each display or workstation. A single X server can provide display services for any number of screens. A set of screens for a single user with one keyboard and one pointer (usually a mouse) is called a display.

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.

X also provides off-screen storage of graphics objects, called pixmaps. Single plane (depth 1) pixmaps are sometimes referred to as bitmaps. Pixmaps can be used in most graphics functions interchangeably with windows and are used in various graphics operations to define patterns or tiles. Windows and pixmaps together are referred to as drawables.

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 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.

Standard Header Files

The following include files are part of the Xlib standard:

<X11/Xlib.h>

This is the main header file for Xlib. The majority of all Xlib symbols are declared by including this file. This file also contains the preprocessor symbol XlibSpecificationRelease. This symbol is defined to have the 6 in this release of the standard. (Release 5 of Xlib was the first release to have this symbol.)

<X11/X.h>

This file declares types and constants for the X protocol that are to be used by applications. It is included automatically from <X11/Xlib.h> so application code should never need to reference this file directly.

<X11/Xcms.h>

This file contains symbols for much of the color management facilities described in chapter 6. All functions, types, and symbols with the prefix "Xcms", plus the Color Conversion Contexts macros, are declared in this file. <X11/Xlib.h> must be included before including this file.

<X11/Xutil.h>

This file declares various functions, types, and symbols used for inter-client communication and application utility functions, which are described in chapters 14 and 16. <X11/Xlib.h> must be included before including this file.

<X11/Xresource.h>

This file declares all functions, types, and symbols for the resource manager facilities, which are described in chapter 15. <X11/Xlib.h> must be included before including this file.

<X11/Xatom.h>

This file declares all predefined atoms, which are symbols with the prefix "XA_".

<X11/cursorfont.h>

This file declares the cursor symbols for the standard cursor font, which are listed in Appendix B. All cursor symbols have the prefix "XC_".

<X11/keysymdef.h>

This file declares all standard KeySym values, which are symbols with the prefix "XK_". The KeySyms are arranged in groups, and a preprocessor symbol controls inclusion of each group. The preprocessor symbol must be defined prior to inclusion of the file to obtain the associated values. The preprocessor symbols are XK_MISCELLANY, XK_XKB_KEYS, XK_3270, XK_LATIN1, XK_LATIN2, XK_LATIN3, XK_LATIN4, XK_KATAKANA, XK_ARABIC, XK_CYRILLIC, XK_GREEK, XK_TECHNICAL, XK_SPECIAL, XK_PUBLISHING, XK_APL, XK_HEBREW, XK_THAI, and XK_KOREAN.

<X11/keysym.h>

This file defines the preprocessor symbols XK_MISCELLANY, XK_XKB_KEYS, XK_LATIN1, XK_LATIN2, XK_LATIN3, XK_LATIN4, and XK_GREEK and then includes <X11/keysymdef.h>.

<X11/Xlibint.h>

This file declares all the functions, types, and symbols used for extensions, which are described in Appendix C. This file automatically includes <X11/Xlib.h>.

<X11/Xproto.h>

This file declares types and symbols for the basic X protocol, for use in implementing extensions. It is included automatically from <X11/Xlibint.h>, so application and extension code should never need to reference this file directly.

<X11/Xprotostr.h>

This file declares types and symbols for the basic X protocol, for use in implementing extensions. It is included automatically from <X11/Xproto.h>, so application and extension code should never need to reference this file directly.

<X11/X10.h>

This file declares all the functions, types, and symbols used for the X10 compatibility functions, which are described in Appendix D.

Generic Values and Types

The following symbols are defined by Xlib and used throughout the manual:

  • Xlib defines the type Bool and the Boolean values True and False.

  • None is the universal null resource ID or atom.

  • The type XID is used for generic resource IDs.

  • The type XPointer is defined to be char * and is used as a generic opaque pointer to data.

Naming and Argument Conventions within Xlib

Xlib follows a number of conventions for the naming and syntax of the functions. Given that you remember what information the function requires, these conventions are intended to make the syntax of the functions more predictable.

The major naming conventions are:

  • 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 Xlib functions begin with a capital X.

  • The beginnings of all function names and symbols are capitalized.

  • 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.

  • All elements of or variables in a data structure are in lowercase. Compound words, where needed, are constructed with underscores (_).

  • 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.

  • When a graphics context is present together with another type of resource (most commonly, a drawable), the graphics context occurs in the argument list after the other resource. Drawables outrank all other resources.

  • Source arguments always precede the destination arguments in the argument list.

  • The x argument always precedes the y argument in the argument list.

  • 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.

  • Keyboards are the greatest variable between different manufacturers' workstations. If you want your program to be portable, you should be particularly conservative here.

  • 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 his 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.

Character Sets and Encodings

Some of the Xlib functions make reference to specific character sets and character encodings. The following are the most common:

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:


a..z A..Z 0..9 !"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~ <space>, <tab>, and <newline>

This set is the left/lower half of the graphic character set of ISO8859-1 plus space, tab, and newline. It is also the set of graphic characters in 7-bit ASCII plus the same three control characters. The actual encoding of these characters on the host is system dependent.

Host Portable Character Encoding

The encoding of the X Portable Character Set on the host. The 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.

Latin-1

The coded character set defined by the ISO8859-1 standard.

Latin Portable Character Encoding

The encoding of the X Portable Character Set using 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.

STRING Encoding

Latin-1, plus tab and newline.

POSIX Portable Filename Character Set

The set of 65 characters, which can be used in naming files on a POSIX-compliant host, that are correctly processed in all locales. The set is:


a..z A..Z 0..9 ._-

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.

  • Each function is introduced by a general discussion that distinguishes it from other functions. The function declaration itself follows, and each argument is specifically explained. Although ANSI C function prototype syntax is not used, Xlib header files normally declare functions using function prototypes in ANSI C environments. General discussion of the function, if any is required, follows the arguments. Where applicable, the last paragraph of the explanation lists the possible Xlib error codes that the function can generate. For a complete discussion of the Xlib error codes, see section 11.8.2.

  • 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.

  • Any pointer to a structure that is used to return a value is designated as such by the _return suffix as part of its name. All other pointers passed to these functions are used for reading only. A few arguments use pointers to structures that are used for both input and output and are indicated by using the _in_out suffix.

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:

  • Open (connect to) the display

  • Obtain information about the display, image formats, or screens

  • Generate a NoOperation protocol request

  • Free client-created data

  • Close (disconnect from) a display

  • Use X Server connection close operations

  • Use Xlib with threads

  • Use internal connections

Opening the Display

To open a connection to the X server that controls a display, use XOpenDisplay.

Display *XOpenDisplay(char *display_name);

display_name

Specifies the hardware display name, which determines the display and communications domain to be used. On a POSIX-conformant system, if the display_name is NULL, it defaults to the value of the DISPLAY environment variable.

The encoding and interpretation of the display name are implementation-dependent. Strings in the Host Portable Character Encoding are supported; support for other characters is implementation-dependent. On POSIX-conformant systems, the display name or DISPLAY environment variable can be a string in the format:



	protocol/hostname:number.screen_number

protocol

Specifies a protocol family or an alias for a protocol family. Supported protocol families are implementation dependent. The protocol entry is optional. If protocol is not specified, the / separating protocol and hostname must also not be specified.

hostname

Specifies the name of the host machine on which the display is physically attached. You follow the hostname with either a single colon (:) or a double colon (::).

number

Specifies the number of the display server on that host machine. You may optionally follow this display number with a period (.). A single CPU can have more than one display. Multiple displays are usually numbered starting with zero.

screen_number

Specifies the screen to be used on that server. Multiple screens can be controlled by a single X server. The screen_number sets an internal variable that can be accessed by using the DefaultScreen macro or the XDefaultScreen function if you are using languages other than C (see section 2.2.1).

For example, the following would specify screen 1 of display 0 on the machine named “dual-headed”:

dual-headed:0.1

The XOpenDisplay function returns a Display structure that serves as the connection to the X server and that contains all the information about that X server. XOpenDisplay connects your application to the X server through TCP or DECnet communications protocols, or through some local inter-process communication protocol. If the protocol is specified as "tcp", "inet", or "inet6", or if no protocol is specified and the hostname is a host machine name and a single colon (:) separates the hostname and display number, XOpenDisplay connects using TCP streams. (If the protocol is specified as "inet", TCP over IPv4 is used. If the protocol is specified as "inet6", TCP over IPv6 is used. Otherwise, the implementation determines which IP version is used.) If the hostname and protocol are both not specified, Xlib uses whatever it believes is the fastest transport. If the hostname is a host machine name and a double colon (::) separates the hostname and display number, XOpenDisplay connects using DECnet. A single X server can support any or all of these transport mechanisms simultaneously. A particular Xlib implementation can support many more of these transport mechanisms.

If successful, XOpenDisplay returns a pointer to a Display structure, which is defined in <X11/Xlib.h>. If XOpenDisplay does not succeed, it returns NULL. After a successful call to XOpenDisplay, all of the screens in the display can be used by the client. The screen number specified in the display_name argument is returned by the DefaultScreen macro (or the XDefaultScreen function). You can access elements of the Display and Screen structures only by using the information macros or functions. For information about using macros and functions to obtain information from the Display structure, see section 2.2.1.

X servers may implement various types of access control mechanisms (see section 9.8).

Obtaining Information about the Display, Image Formats, or Screens

The Xlib library provides a number of useful macros and corresponding functions that return data from the Display structure. The macros are used for C programming, and their corresponding function equivalents are for other language bindings. This section discusses the:

  • Display macros

  • Image format functions and macros

  • Screen information 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()

XAllPlanes()

Both return a value with all bits set to 1 suitable for use in a plane argument to a procedure.

Both BlackPixel and WhitePixel can be used in implementing a monochrome application. These pixel values are for permanently allocated entries in the default colormap. The actual RGB (red, green, and blue) values are settable on some screens and, in any case, may not actually be black or white. The names are intended to convey the expected relative intensity of the colors.

BlackPixel(display, screen_number)

unsigned long XBlackPixel(Display *display, int screen_number);

display

Specifies the connection to the X server.

screen_number

Specifies the appropriate screen number on the host server.

Both return the black pixel value for the specified screen.

WhitePixel(display, screen_number)

unsigned long XWhitePixel(Display *display, int screen_number);

display

Specifies the connection to the X server.

screen_number

Specifies the appropriate screen number on the host server.

Both return the white pixel value for the specified screen.

ConnectionNumber(display)

int XConnectionNumber(Display *display);

display

Specifies the connection to the X server.

Both return a connection number for the specified display. On a POSIX-conformant system, this is the file descriptor of the connection.

DefaultColormap(display, screen_number)

Colormap XDefaultColormap(Display *display, int screen_number);

display

Specifies the connection to the X server.

screen_number

Specifies the appropriate screen number on the host server.

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)

int XDefaultDepth(Display *display, int screen_number);

display

Specifies the connection to the X server.

screen_number

Specifies the appropriate screen number on the host server.

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.

DefaultGC(display, screen_number)

GC XDefaultGC(Display *display, int screen_number, int *count_return);

display

Specifies the connection to the X server.

screen_number

Specifies the appropriate screen number on the host server.

count_return

Returns the number of (Cn.

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 .

DefaultGC(display, screen_number)

GC XDefaultGC(Display *display, int screen_number);

display

Specifies the connection to the X server.

screen_number

Specifies the appropriate screen number on the host server.

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 *display);

display

Specifies the connection to the X server.

Both return the root window for the default screen.

DefaultScreenOfDisplay(display)

Screen *XDefaultScreenOfDisplay(Display *display);

display

Specifies the connection to the X server.

Both return a pointer to the default screen.

ScreenOfDisplay(display, screen_number)

Screen *XScreenOfDisplay(Display *display, int screen_number);

display

Specifies the connection to the X server.

screen_number

Specifies the appropriate screen number on the host server.

Both return a pointer to the indicated screen.

DefaultScreen(display)

int XDefaultScreen(Display *display);

display

Specifies the connection to the X server.

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)

Visual *XDefaultVisual(Display *display, int screen_number);

display

Specifies the connection to the X server.

screen_number

Specifies the appropriate screen number on the host server.

Both return the default visual type for the specified screen. For further information about visual types, see section 3.1.

DisplayCells(display, screen_number)

int XDisplayCells(Display *display, int screen_number);

display

Specifies the connection to the X server.

screen_number

Specifies the appropriate screen number on the host server.

Both return the number of entries in the default colormap.

DisplayPlanes(display, screen_number)

int XDisplayPlanes(Display *display, int screen_number);

display

Specifies the connection to the X server.

screen_number

Specifies the appropriate screen number on the host server.

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 *display);

display

Specifies the connection to the X server.

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.

LastKnownRequestProcessed(display)

unsigned long XLastKnownRequestProcessed(Display *display);

display

Specifies the connection to the X server.

The XExtendedMaxRequestSize function returns zero if the specified display does not support an extended-length protocol encoding; otherwise, it returns the maximum request size (in 4-byte units) supported by the server using the extended-length encoding. The Xlib functions XDrawLines, XDrawArcs, XFillPolygon, XChangeProperty, XSetClipRectangles, and XSetRegion will use the extended-length encoding as necessary, if supported by the server. Use of the extended-length encoding in other Xlib functions (for example, XDrawPoints, XDrawRectangles, XDrawSegments, XFillArcs, XFillRectangles, XPutImage) is permitted but not required; an Xlib implementation may choose to split the data across multiple smaller requests instead.

LastKnownRequestProcessed(display)

unsigned long XLastKnownRequestProcessed(Display *display);

display

Specifies the connection to the X server.

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)

unsigned long XLastKnownRequestProcessed(Display *display);

display

Specifies the connection to the X server.

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)

unsigned long XNextRequest(Display *display);

display

Specifies the connection to the X server.

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 *display);

display

Specifies the connection to the X server.

Both return the major version number (11) of the X protocol associated with the connected display.

ProtocolRevision(display)

int XProtocolRevision(Display *display);

display

Specifies the connection to the X server.

Both return the minor protocol revision number of the X server.

QLength(display)

int XQLength(Display *display);

display

Specifies the connection to the X server.

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)

Window XRootWindow(Display *display, int screen_number);

display

Specifies the connection to the X server.

screen_number

Specifies the appropriate screen number on the host server.

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 *display);

display

Specifies the connection to the X server.

Both return the number of available screens.

ServerVendor(display)

char *XServerVendor(Display *display);

display

Specifies the connection to the X server.

Both return a pointer to a null-terminated string that provides some identification of the owner of the X server implementation. If the data returned by the server is in the Latin Portable Character Encoding, then the string is in the Host Portable Character Encoding. Otherwise, the contents of the string are implementation-dependent.

VendorRelease(display)

int XVendorRelease(Display *display);

display

Specifies the connection to the X server.

Both return a number related to a vendor's release of the X server.

Image Format Functions and Macros

Applications are required to present data to the X server in a format that the server demands. To help simplify applications, most of the work required to convert the data is provided by Xlib (see sections 8.7 and 16.8).

The XPixmapFormatValues structure provides an interface to the pixmap format information that is returned at the time of a connection setup. It contains:



typedef struct {
	int depth;
	int bits_per_pixel;
	int scanline_pad;
} XPixmapFormatValues;

To obtain the pixmap format information for a given display, use XListPixmapFormats.

ImageByteOrder(display)

int XImageByteOrder(Display *display, int *count_return);

display

Specifies the connection to the X server.

count_return

Returns the number of (Cn.

The XListPixmapFormats function returns an array of XPixmapFormatValues structures that describe the types of Z format images supported by the specified display. If insufficient memory is available, XListPixmapFormats returns NULL. To free the allocated storage for the XPixmapFormatValues structures, use .

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 *display);

display

Specifies the connection to the X server.

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.

BitmapUnit(display)

int XBitmapUnit(Display *display);

display

Specifies the connection to the X server.

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 *display);

display

Specifies the connection to the X server.

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 *display);

display

Specifies the connection to the X server.

Each scanline must be padded to a multiple of bits returned by this macro or function.

DisplayHeight(display, screen_number)

int XDisplayHeight(Display *display, int screen_number);

display

Specifies the connection to the X server.

screen_number

Specifies the appropriate screen number on the host server.

Both return an integer that describes the height of the screen in pixels.

DisplayHeightMM(display, screen_number)

int XDisplayHeightMM(Display *display, int screen_number);

display

Specifies the connection to the X server.

screen_number

Specifies the appropriate screen number on the host server.

Both return the height of the specified screen in millimeters.

DisplayWidth(display, screen_number)

int XDisplayWidth(Display *display, int screen_number);

display

Specifies the connection to the X server.

screen_number

Specifies the appropriate screen number on the host server.

Both return the width of the screen in pixels.

DisplayWidthMM(display, screen_number)

int XDisplayWidthMM(Display *display, int screen_number);

display

Specifies the connection to the X server.

screen_number

Specifies the appropriate screen number on the host server.

Both return the width of the specified screen in millimeters.

Screen Information Macros

The following lists the C language macros, their corresponding function equivalents that are for other language bindings, and what data they both can return. These macros or functions all take a pointer to the appropriate screen structure.

BlackPixelOfScreen(screen)

unsigned long XBlackPixelOfScreen(Screen *screen);

screen

Specifies the appropriate Screen structure.

Both return the black pixel value of the specified screen.

WhitePixelOfScreen(screen)

unsigned long XWhitePixelOfScreen(Screen *screen);

screen

Specifies the appropriate Screen structure.

Both return the white pixel value of the specified screen.

CellsOfScreen(screen)

int XCellsOfScreen(Screen *screen);

screen

Specifies the appropriate Screen structure.

Both return the number of colormap cells in the default colormap of the specified screen.

DefaultColormapOfScreen(screen)

Colormap XDefaultColormapOfScreen(Screen *screen);

screen

Specifies the appropriate Screen structure.

Both return the default colormap of the specified screen.

DefaultDepthOfScreen(screen)

int XDefaultDepthOfScreen(Screen *screen);

screen

Specifies the appropriate Screen structure.

Both return the depth of the root window.

DefaultGCOfScreen(screen)

GC XDefaultGCOfScreen(Screen *screen);

screen

Specifies the appropriate Screen structure.

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.

DefaultVisualOfScreen(screen)

Visual *XDefaultVisualOfScreen(Screen *screen);

screen

Specifies the appropriate Screen structure.

Both return the default visual of the specified screen. For information on visual types, see section 3.1.

DoesBackingStore(screen)

int XDoesBackingStore(Screen *screen);

screen

Specifies the appropriate Screen structure.

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 *screen);

screen

Specifies the appropriate Screen structure.

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 *screen);

screen

Specifies the appropriate Screen structure.

Both return the display of the specified screen.

EventMaskOfScreen(screen)

long XEventMaskOfScreen(Screen *screen);

screen

Specifies the appropriate Screen structure.

The XScreenNumberOfScreen function returns the screen index number of the specified screen.

EventMaskOfScreen(screen)

long XEventMaskOfScreen(Screen *screen);

screen

Specifies the appropriate Screen structure.

Both return the event mask of the root window for the specified screen at connection setup time.

WidthOfScreen(screen)

int XWidthOfScreen(Screen *screen);

screen

Specifies the appropriate Screen structure.

Both return the width of the specified screen in pixels.

HeightOfScreen(screen)

int XHeightOfScreen(Screen *screen);

screen

Specifies the appropriate Screen structure.

Both return the height of the specified screen in pixels.

WidthMMOfScreen(screen)

int XWidthMMOfScreen(Screen *screen);

screen

Specifies the appropriate Screen structure.

Both return the width of the specified screen in millimeters.

HeightMMOfScreen(screen)

int XHeightMMOfScreen(Screen *screen);

screen

Specifies the appropriate Screen structure.

Both return the height of the specified screen in millimeters.

MaxCmapsOfScreen(screen)

int XMaxCmapsOfScreen(Screen *screen);

screen

Specifies the appropriate Screen structure.

Both return the maximum number of installed colormaps supported by the specified screen (see section 9.3).

MinCmapsOfScreen(screen)

int XMinCmapsOfScreen(Screen *screen);

screen

Specifies the appropriate Screen structure.

Both return the minimum number of installed colormaps supported by the specified screen (see section 9.3).

PlanesOfScreen(screen)

int XPlanesOfScreen(Screen *screen);

screen

Specifies the appropriate Screen structure.

Both return the depth of the root window.

RootWindowOfScreen(screen)

Window XRootWindowOfScreen(Screen *screen);

screen

Specifies the appropriate Screen structure.

Both return the root window of the specified screen.

Generating a NoOperation Protocol Request

To execute a NoOperation protocol request, use XNoOp.

XNoOp(Display *display);

display

Specifies the connection to the X server.

The XNoOp function sends a NoOperation protocol request to the X server, thereby exercising the connection.

Freeing Client-Created Data

To free in-memory data that was created by an Xlib function, use .

XFree(void *data);

data

Specifies the data that is to be freed.

The 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.

Closing the Display

To close a display or disconnect from the X server, use XCloseDisplay.

XCloseDisplay(Display *display);

display

Specifies the connection to the X server.

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, Font, Pixmap, Colormap, Cursor, and GContext), or other resources that the client has created on this display, unless the close-down mode of the resource has been changed (see ). 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.

XCloseDisplay can generate a BadGC error.

Xlib provides a function to permit the resources owned by a client to survive after the client's connection is closed. To change a client's close-down mode, use .

XSetCloseDownMode(Display *display, int close_mode);

display

Specifies the connection to the X server.

close_mode

Specifies the client close-down mode. You can pass DestroyAll, RetainPermanent, or RetainTemporary.

The 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.

can generate a BadValue error.

Using X Server Connection Close Operations

When the X server's connection to a client is closed either by an explicit call to XCloseDisplay or by a process that exits, the X server performs the following automatic operations:

  • It disowns all selections owned by the client (see XSetSelectionOwner).

  • It performs an XUngrabPointer and XUngrabKeyboard if the client has actively grabbed the pointer or the keyboard.

  • It performs an XUngrabServer if the client has grabbed the server.

  • It releases all passive grabs made by the client.

  • 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 ).

When the close-down mode is DestroyAll, the X server destroys all of a client's resources as follows:

  • It examines each window in the client's save-set to determine if it is an inferior (subwindow) of a window created by the client. (The save-set is a list of other clients' windows that are referred to as save-set windows.) If so, the X server reparents the save-set window to the closest ancestor so that the save-set window is not an inferior of a window created by the client. The reparenting leaves unchanged the absolute coordinates (with respect to the root window) of the upper-left outer corner of the save-set window.

  • It performs a MapWindow request on the save-set window if the save-set window is unmapped. The X server does this even if the save-set window was not an inferior of a window created by the client.

  • It destroys all windows created by the client.

  • It performs the appropriate free request on each nonwindow resource created by the client in the server (for example, Font, Pixmap, Cursor, Colormap, and GContext).

  • It frees all colors and colormap entries allocated by a client application.

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 deletes all but the predefined atom identifiers.

  • It deletes all properties on all root windows (see section 4.3).

  • It resets all device maps and attributes (for example, key click, bell volume, and acceleration) as well as the access control list.

  • It restores the standard root tiles and cursors.

  • It restores the default font path.

  • It restores the input focus to state PointerRoot.

However, the X server does not reset if you close a connection with a close-down mode set to RetainPermanent or RetainTemporary.

Using Xlib with Threads

On systems that have threads, support may be provided to permit multiple threads to use Xlib concurrently.

To initialize support for concurrent threads, use XInitThreads.

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 mechanism (for example, a mutual exclusion lock in a toolkit or through explicit client programming), Xlib thread initialization is not required. It is recommended that single-threaded programs not call this function.

To lock a display across several Xlib calls, use XLockDisplay.

XLockDisplay(Display *display);

display

Specifies the connection to the X server.

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 has been called the same number of times as XLockDisplay. This function has no effect unless Xlib was successfully initialized for threads using XInitThreads.

To unlock a display, use .

XUnlockDisplay(Display *display);

display

Specifies the connection to the X server.

The 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 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.

Using Internal Connections

In addition to the connection to the X server, an Xlib implementation may require connections to other kinds of servers (for example, to input method servers as described in chapter 13). Toolkits and clients that use multiple displays, or that use displays in combination with other inputs, need to obtain these additional connections to correctly block until input is available and need to process that input when it is available. Simple clients that use a single display and block for input in an Xlib event function do not need to use these facilities.

To track internal connections for a display, use .

type void XConnectionWatchProc(Display *display, XPointer client_data, int fd, Bool opening, XPointer *watch_data);

Status XAddConnectionWatch(Display *display, XWatchProc procedure, XPointer client_data);

display

Specifies the connection to the X server.

procedure

Specifies the procedure to be called.

client_data

Specifies the additional client data.

The function registers a procedure to be called each time Xlib opens or closes an internal connection for the specified display. The procedure is passed the display, the specified client_data, the file descriptor for the connection, a Boolean indicating whether the connection is being opened or closed, and a pointer to a location for private watch data. If opening is True, the procedure can store a pointer to private data in the location pointed to by watch_data; when the procedure is later called for this same connection and opening is False, the location pointed to by watch_data will hold this same private data pointer.

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 returns. 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.

To stop tracking internal connections for a display, use XRemoveConnectionWatch.

()

Status XRemoveConnectionWatch(Display *display, XWatchProc procedure, XPointer client_data);

display

Specifies the connection to the X server.

procedure

Specifies the procedure to be called.

client_data

Specifies the additional client data.

The XRemoveConnectionWatch function removes a previously registered connection watch procedure. The client_data must match the client_data used when the procedure was initially registered.

To process input on an internal connection, use XProcessInternalConnection.

()

void XProcessInternalConnection(Display *display, int fd);

display

Specifies the connection to the X server.

fd

Specifies the file descriptor.

The XProcessInternalConnection function processes input available on an internal connection. This function should be called for an internal connection only after an operating system facility (for example, select or poll) has indicated that input is available; otherwise, the effect is not defined.

To obtain all of the current internal connections for a display, use XInternalConnectionNumbers.

()

Status XInternalConnectionNumbers(Display *display, int ** fd, int * count_return);

display

Specifies the connection to the X server.

fd_return

Returns the file descriptors.

count_return

Returns the number of (Cn.

The XInternalConnectionNumbers function returns a list of the file descriptors for all internal connections currently open for the specified display. When the allocated list is no longer needed, free it by using . This functions returns a nonzero status if the list is successfully allocated; otherwise, it returns zero.

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

 Decomposed       True   Direct
   Colormap       Color  Color
----------------------------------------------

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:

  • For PseudoColor, a pixel value indexes a colormap to produce independent RGB values, and the RGB values can be changed dynamically.

  • 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.

  • 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.

To obtain the visual ID from a Visual, use XVisualIDFromVisual.

VisualID XVisualIDFromVisual(Visual *visual);

visual

Specifies the visual type.

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.

Windows also have associated property lists (see section 4.3).

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

  • 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.

Windows have borders of a programmable width and pattern as well as a background pattern or tile. Pixel values can be used for solid colors. The background and border pixmaps can be destroyed immediately after creating the window if no further explicit references to them are to be made. The pattern can either be relative to the parent or absolute. If ParentRelative, the parent's background is used.

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.

To set an attribute of a window, set the appropriate member of the XSetWindowAttributes structure and OR in the corresponding value bitmask in your subsequent calls to XCreateWindow and XChangeWindowAttributes, or use one of the other convenience functions that set the appropriate attribute. The symbols for the value mask bits and the XSetWindowAttributes structure are:

/* Window attribute value mask bits */

/* Window attribute value mask bits */
#define    CWBackPixmap                    (1L<<0)
#define    CWBackPixel                     (1L<<1)
#define    CWBorderPixmap                  (1L<<2)
#define    CWBorderPixel                   (1L<<3)
#define    CWBitGravity                    (1L<<4)
#define    CWWinGravity                    (1L<<5)
#define    CWBackingStore                  (1L<<6)
#define    CWBackingPlanes                 (1L<<7)
#define    CWBackingPixel                  (1L<<8)
#define    CWOverrideRedirect              (1L<<9)
#define    CWSaveUnder                     (1L<<10)
#define    CWEventMask                     (1L<<11)
#define    CWDontPropagate                 (1L<<12)
#define    CWColormap                      (1L<<13)
#define    CWCursor                        (1L<<14)



/* 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:

AttributeDefaultInputOutputInputOnly
background-pixmapNoneYesNo
background-pixelUndefinedYesNo
border-pixmapCopyFromParentYesNo
border-pixelUndefinedYesNo
bit-gravityForgetGravityYesNo
win-gravityNorthWestGravityYesYes
backing-storeNotUsefulYesNo
backing-planesAll onesYesNo
backing-pixelzeroYesNo
save-underFalseYesNo
event-maskempty setYesYes
do-not-propagate-maskempty setYesYes
override-redirectFalseYesYes
colormapCopyFromParentYesNo
cursorNoneYesYes

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.

The background-pixmap attribute of a window specifies the pixmap to be used for a window's background. This pixmap can be of any size, although some sizes may be faster than others. The background-pixel attribute of a window specifies a pixel value used to paint a window's background in a single color.

You can set the background-pixmap to a pixmap, None (default), or ParentRelative. You can set the background-pixel of a window to any pixel value (no default). If you specify a background-pixel, it overrides either the default background-pixmap or any value you may have set in the background-pixmap. A pixmap of an undefined size that is filled with the background-pixel is used for the background. Range checking is not performed on the background pixel; it simply is truncated to the appropriate number of bits.

If you set the background-pixmap, it overrides the default. The background-pixmap and the window must have the same depth, or a BadMatch error results. If you set background-pixmap to None, the window has no defined background. If you set the background-pixmap to ParentRelative:

  • The parent window's background-pixmap is used. The child window, however, must have the same depth as its parent, or a BadMatch error results.

  • If the parent window has a background-pixmap of None, the window also has a background-pixmap of None.

  • A copy of the parent window's background-pixmap is not made. The parent's background-pixmap is examined each time the child window's background-pixmap is required.

  • 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.

Setting a new background, whether by setting background-pixmap or background-pixel, overrides any previous background. The background-pixmap can be freed immediately if no further explicit reference is made to it (the X server will keep a copy to use when needed). If you later draw into the pixmap used for the background, what happens is undefined because the X implementation is free to make a copy of the pixmap or to use the same pixmap.

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 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.

The border-pixmap attribute of a window specifies the pixmap to be used for a window's border. The border-pixel attribute of a window specifies a pixmap of undefined size filled with that pixel be used for a window's border. Range checking is not performed on the background pixel; it simply is truncated to the appropriate number of bits. The border tile origin is always the same as the background tile origin.

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.

The border-pixmap can be freed immediately if no further explicit reference is made to it. If you later draw into the pixmap used for the border, what happens is undefined because the X implementation is free either to make a copy of the pixmap or to use the same pixmap. If you specify a border-pixel, it overrides either the default border-pixmap or any value you may have set in the border-pixmap. All pixels in the window's border will be set to the border-pixel. Setting a new border, whether by setting border-pixel or by setting border-pixmap, overrides any previous border.

Output to a window is always clipped to the inside of the window. Therefore, graphics operations never affect the window border.

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:

Gravity DirectionCoordinates
NorthWestGravity(0, 0)
NorthGravity(Width/2, 0)
NorthEastGravity(Width, 0)
WestGravity(0, Height/2)
CenterGravity(Width/2, Height/2)
EastGravity(Width, Height/2)
SouthWestGravity(0, Height)
SouthGravity(Width/2, Height)
SouthEastGravity(Width, Height)

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.

A bit-gravity of ForgetGravity indicates that the window's contents are always discarded after a size change, even if a backing store or save under has been requested. The window is tiled with its background and zero or more Expose events are generated. If no background is defined, the existing screen contents are not altered. Some X servers may also ignore the specified bit-gravity and always generate Expose events.

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.

A win-gravity of UnmapGravity is like NorthWestGravity (the window is not moved), except the child is also unmapped when the parent is resized, and an UnmapNotify event is generated.

Backing Store Attribute

Some implementations of the X server may choose to maintain the contents of InputOutput windows. If the X server maintains the contents of a window, the off-screen saved pixels are known as backing store. The backing store advises the X server on what to do with the contents of a window. The backing-store attribute can be set to NotUseful (default), WhenMapped, or Always.

A backing-store attribute of NotUseful advises the X server that maintaining contents is unnecessary, although some X implementations may still choose to maintain contents and, therefore, not generate Expose events. A backing-store attribute of WhenMapped advises the X server that maintaining contents of obscured regions when the window is mapped would be beneficial. In this case, 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.

Save Under Flag

Some server implementations may preserve contents of InputOutput windows under other InputOutput windows. This is not the same as preserving the contents of a window for you. You may get better visual appeal if transient windows (for example, pop-up menus) request that the system preserve the screen contents under them, so the temporarily obscured applications do not have to repaint.

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.

Backing Planes and Backing Pixel Attributes

You can set backing planes to indicate (with bits set to 1) which bit planes of an InputOutput window hold dynamic data that must be preserved in backing store and during save unders. The default value for the backing-planes attribute is all bits set to 1. You can set backing pixel to specify what bits to use in planes not covered by backing planes. The default value for the backing-pixel attribute is all bits set to 0. The X server is free to save only the specified bit planes in the backing store or the save under and is free to regenerate the remaining planes with the specified pixel value. Any extraneous bits in these values (that is, those bits beyond the specified depth of the window) may be simply ignored. If you request backing store or save unders, you should use these members to minimize the amount of off-screen memory required to store your window.

Event Mask and Do Not Propagate Mask Attributes

The event mask defines which events the client is interested in for this InputOutput or InputOnly window (or, for some event types, inferiors of this window). The event mask is the bitwise inclusive OR of zero or more of the valid event mask bits. You can specify that no maskable events are reported by setting NoEventMask (default).

The do-not-propagate-mask attribute defines which events should not be propagated to ancestor windows when no client has the event type selected in this InputOutput or InputOnly window. The do-not-propagate-mask is the bitwise inclusive OR of zero or more of the following masks: KeyPress, KeyRelease, ButtonPress, ButtonRelease, PointerMotion, Button1Motion, Button2Motion, Button3Motion, Button4Motion, Button5Motion, and ButtonMotion. You can specify that all events are propagated by setting NoEventMask (default).

Override Redirect Flag

To control window placement or to add decoration, a window manager often needs to intercept (redirect) any map or configure request. Pop-up windows, however, often need to be mapped without a window manager getting in the way. To control whether an InputOutput or InputOnly window is to ignore these structure control facilities, use the override-redirect flag.

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:

  • 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.

For further information, see chapter 14 and the Inter-Client Communication Conventions Manual.

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.

Window XCreateWindow(Display *display, Window parent, intx, y, unsignedintwidth, height, unsignedint border_width, int depth, unsignedint class, Visual *visual, unsignedlong valuemask, XSetWindowAttributes *attributes);

display

Specifies the connection to the X server.

parent

Specifies the parent window. borders and are relative to the inside of the parent window's borders

x

y

Specify the x and y coordinates(Xy. and do not include the created window's borders

width

height

Specify the width and height(Wh. The dimensions must be nonzero, or a BadValue error results.

border_width

Specifies the width of the created window's border in pixels.

depth

Specifies the window's depth. A depth of CopyFromParent means the depth is taken from the parent.

class

Specifies the created window's class. You can pass InputOutput, InputOnly, or CopyFromParent. A class of CopyFromParent means the class is taken from the parent.

visual

Specifies the visual type. A visual of CopyFromParent means the visual type is taken from the parent.

valuemask

Specifies which window attributes are defined in the attributes argument. This mask is the bitwise inclusive OR of the valid attribute mask bits. If valuemask is zero, the attributes are ignored and are not referenced.

attributes

Specifies the structure from which the values (as specified by the value mask) are to be taken. The value mask should have the appropriate bits set to indicate which attributes have been set in the structure.

The XCreateWindow function creates an unmapped subwindow for a specified parent window, returns the window ID of the created window, and causes the X server to generate a CreateNotify event. The created window is placed on top in the stacking order with respect to siblings.

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 border_width for an InputOnly window must be zero, or a BadMatch error results. For class InputOutput, the visual type and depth must be a combination supported for the screen, or a BadMatch error results. The depth need not be the same as the parent, but the parent must not be a window of class InputOnly, or a BadMatch error results. For an InputOnly window, the depth must be zero, and the visual must be one supported by the screen. If either condition is not met, a BadMatch error results. The parent window, however, may have any depth and class. If you specify any invalid window attribute for a window, a BadMatch error results.

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.

XCreateWindow can generate BadAlloc, BadColor, BadCursor, BadMatch, BadPixmap, BadValue, and BadWindow errors.

To create an unmapped InputOutput subwindow of a given parent window, use XCreateSimpleWindow.

Window XCreateSimpleWindow(Display *display, Window parent, intx, y, unsignedintwidth, height, unsignedint border_width, unsignedlong border, unsignedlong background);

display

Specifies the connection to the X server.

parent

Specifies the parent window. and are relative to the inside of the parent window's borders

x

y

Specify the x and y coordinates(Xy. and do not include the created window's borders

width

height

Specify the width and height(Wh. The dimensions must be nonzero, or a BadValue error results.

border_width

Specifies the width of the created window's border in pixels.

border

Specifies the border pixel value of the window.

background

Specifies the background pixel value of the window.

The XCreateSimpleWindow function creates an unmapped InputOutput subwindow for a specified parent window, returns the window ID of the created window, and causes the X server to generate a CreateNotify event. The created window is placed on top in the stacking order with respect to siblings. Any part of the window that extends outside its parent window is clipped. The border_width for an InputOnly window must be zero, or a BadMatch error results. XCreateSimpleWindow inherits its depth, class, and visual from its parent. All other window attributes, except background and border, have their default values.

XCreateSimpleWindow can generate BadAlloc, BadMatch, BadValue, and BadWindow errors.

Destroying Windows

Xlib provides functions that you can use to destroy a window or destroy all subwindows of a window.

To destroy a window and all of its subwindows, use XDestroyWindow.

XDestroyWindow(Display *display, Window w);

display

Specifies the connection to the X server.

w

Specifies the window.

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 are destroyed. Destroying a mapped window will generate Expose events on other windows that were obscured by the window being destroyed.

XDestroyWindow can generate a BadWindow error.

To destroy all subwindows of a specified window, use XDestroySubwindows.

XDestroySubwindows(Display *display, Window w);

display

Specifies the connection to the X server.

w

Specifies the window.

The XDestroySubwindows function destroys all inferior windows of the specified window, in bottom-to-top stacking order. It causes the X server to generate a DestroyNotify event for each window. If any mapped subwindows were actually destroyed, XDestroySubwindows causes the X server to generate Expose events on the specified window. This is much more efficient than deleting many windows one at a time because much of the work need be performed only once for all of the windows, rather than for each window. The subwindows should never be referenced again.

XDestroySubwindows can generate a BadWindow error.

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:

  • It is obscured by another opaque window.

  • One of its ancestors is not mapped.

  • It is entirely clipped by an ancestor.

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 window manager may want to control the placement of subwindows. If SubstructureRedirectMask has been selected by a window manager on a parent window (usually a root window), a map request initiated by other clients on a child window is not performed, and the window manager is sent a MapRequest event. However, if the override-redirect flag on the child had been set to True (usually only on pop-up menus), the map request is performed.

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.

Similarly, a single client can select for ResizeRedirectMask on a parent window. Then, any attempt to resize the window by another client is suppressed, and the client receives a ResizeRequest event.

To map a given window, use XMapWindow.

XMapWindow(Display *display, Window w);

display

Specifies the connection to the X server.

w

Specifies the window.

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.

If the window is an InputOutput window, XMapWindow generates Expose events on each InputOutput window that it causes to be displayed. If the client maps and paints the window and if the client begins processing events, the window is painted twice. To avoid this, first ask for Expose events and then map the window, so the client processes input events as usual. The event list will include Expose for each window that has appeared on the screen. The client's normal response to an Expose event should be to repaint the window. This method usually leads to simpler programs and to proper interaction with window managers.

XMapWindow can generate a BadWindow error.

To map and raise a window, use XMapRaised.

XMapRaised(Display *display, Window w);

display

Specifies the connection to the X server.

w

Specifies the window.

The XMapRaised function essentially is similar to XMapWindow in that it maps the window and all of its subwindows that have had map requests. However, it also raises the specified window to the top of the stack. For additional information, see XMapWindow.

XMapRaised can generate multiple BadWindow errors.

To map all subwindows for a specified window, use XMapSubwindows.

XMapSubwindows(Display *display, Window w);

display

Specifies the connection to the X server.

w

Specifies the window.

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.

XMapSubwindows can generate a BadWindow error.

Unmapping Windows

Xlib provides functions that you can use to unmap a window or all subwindows.

To unmap a window, use XUnmapWindow.

XUnmapWindow(Display *display, Window w);

display

Specifies the connection to the X server.

w

Specifies the window.

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.

XUnmapWindow can generate a BadWindow error.

To unmap all subwindows for a specified window, use XUnmapSubwindows.

XUnmapSubwindows(Display *display, Window w);

display

Specifies the connection to the X server.

w

Specifies the window.

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.

XUnmapSubwindows can generate a BadWindow error.

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 parameters, set the appropriate member of the XWindowChanges structure and OR in the corresponding value mask in subsequent calls to XConfigureWindow. The symbols for the value mask bits and the XWindowChanges structure are:

/* Configure window value mask bits */
#define      CWX              (1<<0)
#define      CWY              (1<<1)
#define      CWWidth          (1<<2)
#define      CWHeight         (1<<3)
#define      CWBorderWidth    (1<<4)
#define      CWSibling        (1<<5)
#define      CWStackMode      (1<<6)

/* 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 actually changes. GravityNotify events are generated after ConfigureNotify events. If the inside width or height of the window has actually changed, children of the window are affected as specified.

If a window's size actually changes, the window's subwindows move according to their window gravity. Depending on the window's bit gravity, the contents of the window also may be moved (see section 3.2.3).

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.

If a sibling and a stack_mode are specified, the window is restacked as follows:

AboveThe window is placed just above the sibling.
BelowThe window is placed just below the sibling.
TopIfIf the sibling occludes the window, the window is placed at the top of the stack.
BottomIfIf the window occludes the sibling, the window is placed at the bottom of the stack.
Opposite If the sibling occludes the window, the window is placed at the top of the stack. If the window occludes the sibling, the window is placed at the bottom of the stack.

If a stack_mode is specified but no sibling is specified, the window is restacked as follows:

AboveThe window is placed at the top of the stack.
BelowThe window is placed at the bottom of the stack.
TopIf If any sibling occludes the window, the window is placed at the top of the stack.
BottomIf If the window occludes any sibling, the window is placed at the bottom of the stack.
Opposite If any sibling occludes the window, the window is placed at the top of the stack. If the window occludes any sibling, the window is placed at the bottom of the stack.

Attempts to configure a root window have no effect.

To configure a window's size, location, stacking, or border, use XConfigureWindow.

XConfigureWindow(Display *display, Window w, unsignedint value_mask, XWindowChanges *values);

display

Specifies the connection to the X server.

w

Specifies the window (Wi.

value_mask

Specifies which values are to be set using information in the values structure. This mask is the bitwise inclusive OR of the valid configure window values bits.

values

Specifies the XWindowChanges structure.

The XConfigureWindow function uses the values specified in the XWindowChanges structure to reconfigure a window's size, position, border, and stacking order. Values not specified are taken from the existing geometry of the window.

If a sibling is specified without a stack_mode or if the window is not actually a sibling, a BadMatch error results. Note that the computations for BottomIf, TopIf, and Opposite are performed with respect to the window's final geometry (as controlled by the other arguments passed to XConfigureWindow), not its initial geometry. Any backing store contents of the window, its inferiors, and other newly visible windows are either discarded or changed to reflect the current screen contents (depending on the implementation).

XConfigureWindow can generate BadMatch, BadValue, and BadWindow errors.

To move a window without changing its size, use XMoveWindow.

XMoveWindow(Display *display, Window w, intx, y);

display

Specifies the connection to the X server.

w

Specifies the window (Wi. of the window's border or the window itself if it has no border

x

y

Specify the x and y coordinates(Xy.

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.

XMoveWindow can generate a BadWindow error.

To change a window's size without changing the upper-left coordinate, use XResizeWindow.

XResizeWindow(Display *display, Window w, unsignedintwidth, height);

display

Specifies the connection to the X server.

w

Specifies the window. after the call completes

width

height

Specify the width and height(Wh.

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.

XResizeWindow can generate BadValue and BadWindow errors.

To change the size and location of a window, use XMoveResizeWindow.

XMoveResizeWindow(Display *display, Window w, intx, y, unsignedintwidth, height);

display

Specifies the connection to the X server.

w

Specifies the window (Wi.

x

y

Specify the x and y coordinates(Xy.

width

height

Specify the width and height(Wh.

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.

XMoveResizeWindow can generate BadValue and BadWindow errors.

To change the border width of a given window, use XSetWindowBorderWidth.

XSetWindowBorderWidth(Display *display, Window w, unsignedint width);

display

Specifies the connection to the X server.

w

Specifies the window.

width

Specifies the width of the window border.

The XSetWindowBorderWidth function sets the specified window's border width to the specified width.

XSetWindowBorderWidth can generate a BadWindow error.

Changing Window Stacking Order

Xlib provides functions that you can use to raise, lower, circulate, or restack windows.

To raise a window so that no sibling window obscures it, use XRaiseWindow.

XRaiseWindow(Display *display, Window w);

display

Specifies the connection to the X server.

w

Specifies the window.

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.

XRaiseWindow can generate a BadWindow error.

To lower a window so that it does not obscure any sibling windows, use XLowerWindow.

XLowerWindow(Display *display, Window w);

display

Specifies the connection to the X server.

w

Specifies the window.

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.

XLowerWindow can generate a BadWindow error.

To circulate a subwindow up or down, use XCirculateSubwindows.

XCirculateSubwindows(Display *display, Window w, int direction);

display

Specifies the connection to the X server.

w

Specifies the window.

direction

Specifies the direction (up or down) that you want to circulate the window. You can pass RaiseLowest or LowerHighest.

The XCirculateSubwindows function circulates children of the specified window in the specified direction. If you specify RaiseLowest, XCirculateSubwindows raises the lowest mapped child (if any) that is occluded by another child to the top of the stack. If you specify LowerHighest, XCirculateSubwindows lowers the highest mapped child (if any) that occludes another child to the bottom of the stack. Exposure processing is then performed on formerly obscured windows. If some other client has selected SubstructureRedirectMask on the window, the X server generates a CirculateRequest event, and no further processing is performed. If a child is actually restacked, the X server generates a CirculateNotify event.

XCirculateSubwindows can generate BadValue and BadWindow errors.

To raise the lowest mapped child of a window that is partially or completely occluded by another child, use XCirculateSubwindowsUp.

XCirculateSubwindowsUp(Display *display, Window w);

display

Specifies the connection to the X server.

w

Specifies the window.

The XCirculateSubwindowsUp function raises the lowest mapped child of the specified window that is partially or completely occluded by another child. Completely unobscured children are not affected. This is a convenience function equivalent to XCirculateSubwindows with RaiseLowest specified.

XCirculateSubwindowsUp can generate a BadWindow error.

To lower the highest mapped child of a window that partially or completely occludes another child, use XCirculateSubwindowsDown.

XCirculateSubwindowsDown(Display *display, Window w);

display

Specifies the connection to the X server.

w

Specifies the window.

The XCirculateSubwindowsDown function lowers the highest mapped child of the specified window that partially or completely occludes another child. Completely unobscured children are not affected. This is a convenience function equivalent to XCirculateSubwindows with LowerHighest specified.

XCirculateSubwindowsDown can generate a BadWindow error.

To restack a set of windows from top to bottom, use XRestackWindows.

XRestackWindows(Display *display, Window windows[], int nwindows);

display

Specifies the connection to the X server.

windows

Specifies an array containing the windows to be restacked.

nwindows

Specifies the number of windows to be restacked.

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.

If the override-redirect attribute of a window is False and some other client has selected SubstructureRedirectMask on the parent, the X server generates ConfigureRequest events for each window whose override-redirect flag is not set, and no further processing is performed. Otherwise, the windows will be restacked in top-to-bottom order.

XRestackWindows can generate a BadWindow error.

Changing Window Attributes

Xlib provides functions that you can use to set window attributes. XChangeWindowAttributes is the more general function that allows you to set one or more window attributes provided by the XSetWindowAttributes structure. The other functions described in this section allow you to set one specific window attribute, such as a window's background.

To change one or more attributes for a given window, use XChangeWindowAttributes.

XChangeWindowAttributes(Display *display, Window w, unsignedlong valuemask, XSetWindowAttributes *attributes);

display

Specifies the connection to the X server.

w

Specifies the window.

valuemask

Specifies which window attributes are defined in the attributes argument. This mask is the bitwise inclusive OR of the valid attribute mask bits. If valuemask is zero, the attributes are ignored and are not referenced. The values and restrictions are the same as for XCreateWindow.

attributes

Specifies the structure from which the values (as specified by the value mask) are to be taken. The value mask should have the appropriate bits set to indicate which attributes have been set in the structure (see section 3.2).

Depending on the valuemask, the XChangeWindowAttributes function uses the window attributes in the XSetWindowAttributes structure to change the specified window attributes. Changing the background does not cause the window contents to be changed. To repaint the window and its background, use XClearWindow. Setting the border or changing the background such that the border tile origin changes causes the border to be repainted. Changing the background of a root window to None or ParentRelative restores the default background pixmap. Changing the border of a root window to CopyFromParent restores the default border pixmap. Changing the win-gravity does not affect the current position of the window. Changing the backing-store of an obscured window to WhenMapped or Always, or changing the backing-planes, backing-pixel, or save-under of a mapped window may have no immediate effect. Changing the colormap of a window (that is, defining a new map, not changing the contents of the existing map) generates a ColormapNotify event. Changing the colormap of a visible window may have no immediate effect on the screen because the map may not be installed (see XInstallColormap). Changing the cursor of a root window to None restores the default cursor. Whenever possible, you are encouraged to share colormaps.

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.

XChangeWindowAttributes can generate BadAccess, BadColor, BadCursor, BadMatch, BadPixmap, BadValue, and BadWindow errors.

To set the background of a window to a given pixel, use XSetWindowBackground.

XSetWindowBackground(Display *display, Window w, unsignedlong background_pixel);

display

Specifies the connection to the X server.

w

Specifies the window.

background_pixel

Specifies the pixel that is to be used for the background.

The XSetWindowBackground function sets the background of the window to the specified pixel value. Changing the background does not cause the window contents to be changed. XSetWindowBackground uses a pixmap of undefined size filled with the pixel value you passed. If you try to change the background of an InputOnly window, a BadMatch error results.

XSetWindowBackground can generate BadMatch and BadWindow errors.

To set the background of a window to a given pixmap, use XSetWindowBackgroundPixmap.

XSetWindowBackgroundPixmap(Display *display, Window w, Pixmap background_pixmap);

display

Specifies the connection to the X server.

w

Specifies the window.

background_pixmap

Specifies the background pixmap, ParentRelative, or None.

The XSetWindowBackgroundPixmap function sets the background pixmap of the window to the specified pixmap. The background pixmap can immediately be freed if no further explicit references to it are to be made. If ParentRelative is specified, the background pixmap of the window's parent is used, or on the root window, the default background is restored. If you try to change the background of an InputOnly window, a BadMatch error results. If the background is set to None, the window has no defined background.

XSetWindowBackgroundPixmap can generate BadMatch, BadPixmap, and BadWindow errors. XSetWindowBackground and XSetWindowBackgroundPixmap do not change the current contents of the window.

To change and repaint a window's border to a given pixel, use XSetWindowBorder.

XSetWindowBorder(Display *display, Window w, unsignedlong border_pixel);

display

Specifies the connection to the X server.

w

Specifies the window.

border_pixel

Specifies the entry in the colormap.

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.

XSetWindowBorder can generate BadMatch and BadWindow errors.

To change and repaint the border tile of a given window, use XSetWindowBorderPixmap.

XSetWindowBorderPixmap(Display *display, Window w, Pixmap border_pixmap);

display

Specifies the connection to the X server.

w

Specifies the window.

border_pixmap

Specifies the border pixmap or CopyFromParent.

The XSetWindowBorderPixmap function sets the border pixmap of the window to the pixmap you specify. The border pixmap can be freed immediately if no further explicit references to it are to be made. If you specify CopyFromParent, a copy of the parent window's border pixmap is used. If you attempt to perform this on an InputOnly window, a BadMatch error results.

XSetWindowBorderPixmap can generate BadMatch, BadPixmap, and BadWindow errors.

To set the colormap of a given window, use XSetWindowColormap.

XSetWindowColormap(Display *display, Window w, Colormap colormap);

display

Specifies the connection to the X server.

w

Specifies the window.

colormap

Specifies the colormap.

The XSetWindowColormap function sets the specified colormap of the specified window. The colormap must have the same visual type as the window, or a BadMatch error results.

XSetWindowColormap can generate BadColor, BadMatch, and BadWindow errors.

To define which cursor will be used in a window, use XDefineCursor.

XDefineCursor(Display *display, Window w, Cursor cursor);

display

Specifies the connection to the X server.

w

Specifies the window.

cursor

Specifies the cursor that is to be displayed or None.

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.

XDefineCursor can generate BadCursor and BadWindow errors.

To undefine the cursor in a given window, use XUndefineCursor.

XUndefineCursor(Display *display, Window w);

display

Specifies the connection to the X server.

w

Specifies the window.

The XUndefineCursor function undoes the effect of a previous XDefineCursor for this window. When the pointer is in the window, the parent's cursor will now be used. On the root window, the default cursor is restored.

XUndefineCursor can generate a BadWindow error.

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:

  • Obtain information about a window

  • Translate screen coordinates

  • Manipulate property lists

  • Obtain and change window properties

  • Manipulate selections

Obtaining Window Information

Xlib provides functions that you can use to obtain information about the window tree, the window's current attributes, the window's current geometry, or the current pointer coordinates. Because they are most frequently used by window managers, these functions all return a status to indicate whether the window still exists.

To obtain the parent, a list of children, and number of children for a given window, use XQueryTree.

Status XQueryTree(Display *display, Window w, Window *root_return, Window *parent_return, Window **children_return, unsignedint *nchildren_return);

display

Specifies the connection to the X server. you want to obtain

w

Specifies the window (Wi.

root_return

Returns the root window.

parent_return

Returns the parent window.

children_return

Returns the list of children.

nchildren_return

Returns the number of children.

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 .

XQueryTree can generate a BadWindow error.

To obtain the current attributes of a given window, use XGetWindowAttributes.

Status XGetWindowAttributes(Display *display, Window w, XWindowAttributes *window_attributes_return);

display

Specifies the connection to the X server.

w

Specifies the window (Wi.

window_attributes_return

Returns the specified window's attributes in the XWindowAttributes structure.

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:

ForgetGravityEastGravity
NorthWestGravitySouthWestGravity
NorthGravitySouthGravity
NorthEastGravitySouthEastGravity
WestGravityStaticGravity

The win_gravity member is set to the window's window gravity and can be one of the following:

UnmapGravitySouthWestGravity
NorthWestGravitySouthGravity
NorthGravitySouthEastGravity
NorthEastGravityStaticGravity
WestGravityCenterGravity
EastGravity 

For additional information on gravity, see section 3.2.3.

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 override_redirect member is set to indicate whether this window overrides structure control facilities and can be True or False. Window manager clients should ignore the window if this member is True.

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.

XGetWindowAttributes can generate BadDrawable and BadWindow errors.

To obtain the current geometry of a given drawable, use XGetGeometry.

Status XGetGeometry(Display *display, Drawable d, Window *root_return, int*x_return, *y_return, unsignedint*width_return, *height_return, unsignedint *border_width_return, unsignedint *depth_return);

display

Specifies the connection to the X server.

d

Specifies the drawable(Dr.

root_return

Returns the root window.

x_return

y_return

Return the x and y coordinates that define the location of the drawable. For a window, these coordinates specify the upper-left outer corner relative to its parent's origin. For pixmaps, these coordinates are always zero.

width_return

height_return

Return the drawable's dimensions (width and height). For a window, these dimensions specify the inside size, not including the border.

border_width_return

Returns the border width in pixels. If the drawable is a pixmap, it returns zero.

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.

XGetGeometry can generate a BadDrawable error.

Translating Screen Coordinates

Applications sometimes need to perform a coordinate transformation from the coordinate space of one window to another window or need to determine which window the pointing device is in. XTranslateCoordinates and XQueryPointer fulfill these needs (and avoid any race conditions) by asking the X server to perform these operations.

To translate a coordinate in one window to the coordinate space of another window, use XTranslateCoordinates.

Bool XTranslateCoordinates(Display *display, Windowsrc_w, dest_w, intsrc_x, src_y, int*dest_x_return, *dest_y_return, Window *child_return);

display

Specifies the connection to the X server.

src_w

Specifies the source window.

dest_w

Specifies the destination window.

src_x

src_y

Specify the x and y coordinates within the source window.

dest_x_return

dest_y_return

Return the x and y coordinates within the destination window.

child_return

Returns the child if the coordinates are contained in a mapped child of the destination window.

If XTranslateCoordinates returns True, it takes the src_x and src_y coordinates relative to the source window's origin and returns these coordinates to dest_x_return and dest_y_return relative to the destination window's origin. If XTranslateCoordinates returns False, src_w and dest_w are on different screens, and dest_x_return and dest_y_return are zero. If the coordinates are contained in a mapped child of dest_w, that child is returned to child_return. Otherwise, child_return is set to None.

XTranslateCoordinates can generate a BadWindow error.

To obtain the screen coordinates of the pointer or to determine the pointer coordinates relative to a specified window, use XQueryPointer.

Bool XQueryPointer(Display *display, Window w, Window*root_return, *child_return, int*root_x_return, *root_y_return, int*win_x_return, *win_y_return, unsignedint *mask_return);

display

Specifies the connection to the X server.

w

Specifies the window.

root_return

Returns the root window (Ro.

child_return

Returns the child window that the pointer is located in, if any.

root_x_return

root_y_return

Return the pointer coordinates relative to the root window's origin.

win_x_return

win_y_return

Return the pointer coordinates relative to the specified window.

mask_return

Returns the current state of the modifier keys and pointer buttons.

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).

XQueryPointer can generate a BadWindow error.

Properties and Atoms

A property is a collection of named, typed data. The window system has a set of predefined properties (for example, the name of a window, size hints, and so on), and users can define any other arbitrary information and associate it with windows. Each property has a name, which is an ISO Latin-1 string. For each named property, a unique identifier (atom) is associated with it. A property also has a type, for example, string or integer. These types are also indicated using atoms, so arbitrary new types can be defined. Data of only one type may be associated with a single property name. Clients can store and retrieve properties associated with windows. For efficiency reasons, an atom is used rather than a character string. XInternAtom can be used to obtain the atom for property names.

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

  • Type of a ClientMessage event (none are built into the X server)

The built-in selection property names are:

PRIMARYSECONDARY

The built-in property names are:

CUT_BUFFER0RESOURCE_MANAGER
CUT_BUFFER1WM_CLASS
CUT_BUFFER2WM_CLIENT_MACHINE
CUT_BUFFER3WM_COLORMAP_WINDOWS
CUT_BUFFER4WM_COMMAND
CUT_BUFFER5WM_HINTS
CUT_BUFFER6WM_ICON_NAME
CUT_BUFFER7WM_ICON_SIZE
RGB_BEST_MAPWM_NAME
RGB_BLUE_MAPWM_NORMAL_HINTS
RGB_DEFAULT_MAPWM_PROTOCOLS
RGB_GRAY_MAPWM_STATE
RGB_GREEN_MAPWM_TRANSIENT_FOR
RGB_RED_MAPWM_ZOOM_HINTS

The built-in property types are:

ARCPIXMAP
ATOMPOINT
BITMAPRGB_COLOR_MAP
CARDINALRECTANGLE
COLORMAPSTRING
CURSORVISUALID
DRAWABLEWINDOW
FONTWM_HINTS
INTEGERWM_SIZE_HINTS

The built-in font property names are:

MIN_SPACESTRIKEOUT_DESCENT
NORM_SPACESTRIKEOUT_ASCENT
MAX_SPACEITALIC_ANGLE
END_SPACEX_HEIGHT
SUPERSCRIPT_XQUAD_WIDTH
SUPERSCRIPT_YWEIGHT
SUBSCRIPT_XPOINT_SIZE
SUBSCRIPT_YRESOLUTION
UNDERLINE_POSITIONCOPYRIGHT
UNDERLINE_THICKNESSNOTICE
FONT_NAMEFAMILY_NAME
FULL_NAMECAP_HEIGHT

For further information about font properties, see section 8.5.

To return an atom for a given name, use XInternAtom.

Atom XInternAtom(Display *display, char *atom_name, Bool only_if_exists);

display

Specifies the connection to the X server.

atom_name

Specifies the name associated with the atom you want returned.

only_if_exists

Specifies a Boolean value that indicates whether the atom must be created.

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.

XInternAtom can generate BadAlloc and BadValue errors.

To return atoms for an array of names, use XInternAtoms.

Status XInternAtoms(Display *display, char **names, int count, Bool only_if_exists, Atom *atoms_return);

display

Specifies the connection to the X server.

names

Specifies the array of atom names.

count

Specifies the number of (Cn.

only_if_exists

Specifies a Boolean value that indicates whether the atom must be created.

atoms_return

Returns the atoms.

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.

XInternAtoms can generate BadAlloc and BadValue errors.

To return a name for a given atom identifier, use XGetAtomName.

char *XGetAtomName(Display *display, Atom atom);

display

Specifies the connection to the X server.

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 .

XGetAtomName can generate a BadAtom error.

To return the names for an array of atom identifiers, use XGetAtomNames.

Status XGetAtomNames(Display *display, Atom *atoms, int count, char **names_return);

display

Specifies the connection to the X server.

atoms

Specifies the array of atoms.

count

Specifies the number of (Cn.

names_return

Returns the atom names.

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.

XGetAtomNames can generate a BadAtom error.

Obtaining and Changing Window Properties

You can attach a property list to every window. Each property has a name, a type, and a value (see section 4.3). The value is an array of 8-bit, 16-bit, or 32-bit quantities, whose interpretation is left to the clients. The type char is used to represent 8-bit quantities, the type short is used to represent 16-bit quantities, and the type long is used to represent 32-bit quantities.

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.

int XGetWindowProperty( display, w, property, long_offset, long_length, delete, req_type, actual_type_return, actual_format_return, nitems_return, bytes_after_return, prop_return);

display

Specifies the connection to the X server.

w

Specifies the window (Wi.

property

Specifies the property name.

long_offset

Specifies the offset in the specified property (in 32-bit quantities) where the data is to be retrieved.

long_length

Specifies the length in 32-bit multiples of the data to be retrieved.

delete

Specifies a Boolean value that determines whether the property is deleted.

req_type

Specifies the atom identifier associated with the property type or AnyPropertyType.

actual_type_return

Returns the atom identifier that defines the actual type of the property.

actual_format_return

Returns the actual format of the property.

nitems_return

Returns the actual number of 8-bit, 16-bit, or 32-bit items stored in the prop_return data.

bytes_after_return

Returns the number of bytes remaining to be read in the property if a partial read was performed.

prop_return

Returns the data in the specified format.

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.

XGetWindowProperty always allocates one extra byte in prop_return (even if the property is zero length) and sets it to zero so that simple properties consisting of characters do not have to be copied into yet another string before use.

If delete is True and bytes_after_return is zero, XGetWindowProperty deletes the property from the window and generates a PropertyNotify event on the window.

The function returns Success if it executes successfully. To free the resulting data, use .

XGetWindowProperty can generate BadAtom, BadValue, and BadWindow errors.

To obtain a given window's property list, use XListProperties.

Atom *XListProperties(Display *display, Window w, int *num_prop_return);

display

Specifies the connection to the X server.

w

Specifies the window (Wi.

num_prop_return

Returns the length of the properties array.

The XListProperties function returns a pointer to an array of atom properties that are defined for the specified window or returns NULL if no properties were found. To free the memory allocated by this function, use .

XListProperties can generate a BadWindow error.

To change a property of a given window, use XChangeProperty.

XChangeProperty(Display *display, Window w, Atomproperty, type, int format, int mode, unsignedchar *data, int nelements);

display

Specifies the connection to the X server.

w

Specifies the window (Wi.

property

Specifies the property name.

type

Specifies the type of the property. The X server does not interpret the type but simply passes it back to an application that later calls XGetWindowProperty.

format

Specifies whether the data should be viewed as a list of 8-bit, 16-bit, or 32-bit quantities. Possible values are 8, 16, and 32. This information allows the X server to correctly perform byte-swap operations as necessary. If the format is 16-bit or 32-bit, you must explicitly cast your data pointer to an (unsigned char *) in the call to XChangeProperty.

mode

Specifies the mode of the operation. You can pass PropModeReplace, PropModePrepend, or PropModeAppend.

data

Specifies the property data.

nelements

Specifies the number of elements of the specified data format.

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:

  • If mode is PropModeReplace, XChangeProperty discards the previous property value and stores the new data.

  • If mode is PropModePrepend or PropModeAppend, XChangeProperty inserts the specified data before the beginning of the existing data or onto the end of the existing data, respectively. The type and format must match the existing property value, or a BadMatch error results. If the property is undefined, it is treated as defined with the correct type and format with zero-length data.

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.)

XChangeProperty can generate BadAlloc, BadAtom, BadMatch, BadValue, and BadWindow errors.

To rotate a window's property list, use XRotateWindowProperties.

XRotateWindowProperties(Display *display, Window w, Atom properties[], int num_prop, int npositions);

display

Specifies the connection to the X server.

w

Specifies the window.

properties

Specifies the array of properties that are to be rotated.

num_prop

Specifies the length of the properties array.

npositions

Specifies the rotation amount.

The XRotateWindowProperties function allows you to rotate properties on a window and causes the X server to generate PropertyNotify events. If the property names in the properties array are viewed as being numbered starting from zero and if there are num_prop property names in the list, then the value associated with property name I becomes the value associated with property name (I + npositions) mod N for all I from zero to N − 1. The effect is to rotate the states by npositions places around the virtual ring of property names (right for positive npositions, left for negative npositions). If npositions mod N is nonzero, the X server generates a PropertyNotify event for each property in the order that they are listed in the array. If an atom occurs more than once in the list or no property with that name is defined for the window, a BadMatch error results. If a BadAtom or BadMatch error results, no properties are changed.

XRotateWindowProperties can generate BadAtom, BadMatch, and BadWindow errors.

To delete a property on a given window, use XDeleteProperty.

XDeleteProperty(Display *display, Window w, Atom property);

display

Specifies the connection to the X server.

w

Specifies the window (Wi.

property

Specifies the property name.

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.

XDeleteProperty can generate BadAtom and BadWindow errors.

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.

To set the selection owner, use XSetSelectionOwner.

XSetSelectionOwner(Display *display, Atom selection, Window owner, Time time);

display

Specifies the connection to the X server.

selection

Specifies the selection atom.

owner

Specifies the owner of the specified selection atom. You can pass a window or None.

time

Specifies the time. You can pass either a timestamp or CurrentTime.

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 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.

XSetSelectionOwner can generate BadAtom and BadWindow errors.

To return the selection owner, use XGetSelectionOwner.

Window XGetSelectionOwner(Display *display, Atom selection);

display

Specifies the connection to the X server.

selection

Specifies the selection atom (Se.

The XGetSelectionOwner function returns the window ID associated with the window that currently owns the specified selection. If no selection was specified, the function returns the constant None. If None is returned, there is no owner for the selection.

XGetSelectionOwner can generate a BadAtom error.

To request conversion of a selection, use XConvertSelection.

XConvertSelection(Display *display, Atomselection, target, Atom property, Window requestor, Time time);

display

Specifies the connection to the X server.

selection

Specifies the selection atom.

target

Specifies the target atom.

property

Specifies the property name. You also can pass None.

requestor

Specifies the requestor.

time

Specifies the time. You can pass either a timestamp or CurrentTime.

XConvertSelection requests that the specified selection be converted to the specified target type:

  • If the specified selection has an owner, the X server sends a SelectionRequest event to that owner.

  • If no owner for the specified selection exists, the X server generates a SelectionNotify event to the requestor with property None.

The arguments are passed on unchanged in either of the events. There are two predefined selection atoms: PRIMARY and SECONDARY.

XConvertSelection can generate BadAtom and BadWindow errors.

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.

To create a pixmap of a given size, use XCreatePixmap.

Pixmap XCreatePixmap(Display *display, Drawable d, unsignedintwidth, height, unsignedint depth);

display

Specifies the connection to the X server.

d

Specifies which screen the pixmap is created on.

width

height

Specify the width and height(Wh.

depth

Specifies the depth 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.

XCreatePixmap can generate BadAlloc, BadDrawable, and BadValue errors.

To free all storage associated with a specified pixmap, use XFreePixmap.

XFreePixmap(Display *display, Pixmap pixmap);

display

Specifies the connection to the X server.

pixmap

Specifies the 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.

XFreePixmap can generate a BadPixmap error.

Creating, Recoloring, and Freeing Cursors

Each window can have a different cursor defined for it. Whenever the pointer is in a visible window, it is set to the cursor defined for that window. If no cursor was defined for that window, the cursor is the one defined for the parent window.

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.

To create a cursor from the standard cursor font, use XCreateFontCursor.

#include <X11/cursorfont.h>

Cursor XCreateFontCursor(Display *display, unsignedint shape);

display

Specifies the connection to the X server.

shape

Specifies the shape of the cursor.

X provides a set of standard cursor shapes in a special font named cursor. Applications are encouraged to use this interface for their cursors because the font can be customized for the individual display type. The shape argument specifies which glyph of the standard fonts to use.

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.

XCreateFontCursor can generate BadAlloc and BadValue errors.

To create a cursor from font glyphs, use XCreateGlyphCursor.

Cursor XCreateGlyphCursor(Display *display, Fontsource_font, mask_font, unsignedintsource_char, mask_char, XColor *foreground_color, XColor *background_color);

display

Specifies the connection to the X server.

source_font

Specifies the font for the source glyph.

mask_font

Specifies the font for the mask glyph or None.

source_char

Specifies the character glyph for the source.

mask_char

Specifies the glyph character for the mask.

foreground_color

Specifies the RGB values for the foreground of the source.

background_color

Specifies the RGB values for the background of the source.

The XCreateGlyphCursor function is similar to XCreatePixmapCursor except that the source and mask bitmaps are obtained from the specified font glyphs. The source_char must be a defined glyph in source_font, or a BadValue error results. If mask_font is given, mask_char must be a defined glyph in mask_font, or a BadValue error results. The mask_font and character are optional. The origins of the source_char and mask_char (if defined) glyphs are positioned coincidently and define the hotspot. The source_char and mask_char need not have the same bounding box metrics, and there is no restriction on the placement of the hotspot relative to the bounding boxes. If no mask_char is given, all pixels of the source are displayed. You can free the fonts immediately by calling XFreeFont if no further explicit references to them are to be made.

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.

XCreateGlyphCursor can generate BadAlloc, BadFont, and BadValue errors.

To create a cursor from two bitmaps, use XCreatePixmapCursor.

Cursor XCreatePixmapCursor(Display *display, Pixmap source, Pixmap mask, XColor *foreground_color, XColor *background_color, unsignedintx, y);

display

Specifies the connection to the X server.

source

Specifies the shape of the source cursor.

mask

Specifies the cursor's source bits to be displayed or None.

foreground_color

Specifies the RGB values for the foreground of the source.

background_color

Specifies the RGB values for the background of the source.

x

y

Specify the x and y coordinates(Xy.

The XCreatePixmapCursor function creates a cursor and returns the cursor ID associated with it. The foreground and background RGB values must be specified using foreground_color and background_color, even if the X server only has a StaticGray or GrayScale screen. The foreground color is used for the pixels set to 1 in the source, and the background color is used for the pixels set to 0. Both source and mask, if specified, must have depth one (or a BadMatch error results) but can have any root. The mask argument defines the shape of the cursor. The pixels set to 1 in the mask define which source pixels are displayed, and the pixels set to 0 define which pixels are ignored. If no mask is given, all pixels of the source are displayed. The mask, if present, must be the same size as the pixmap defined by the source argument, or a BadMatch error results. The hotspot must be a point within the source, or a BadMatch error results.

The components of the cursor can be transformed arbitrarily to meet display limitations. The pixmaps can be freed immediately if no further explicit references to them are to be made. Subsequent drawing in the source or mask pixmap has an undefined effect on the cursor. The X server might or might not make a copy of the pixmap.

XCreatePixmapCursor can generate BadAlloc and BadPixmap errors.

To determine useful cursor sizes, use XQueryBestCursor.

Status XQueryBestCursor(Display *display, Drawable d, unsignedintwidth, height, unsignedint*width_return, *height_return);

display

Specifies the connection to the X server.

d

Specifies the drawable(Dr.

width

height

Specify the width and height(Wh.

width_return

height_return

Return the best width and height that is closest to the specified width and height.

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.

XQueryBestCursor can generate a BadDrawable error.

To change the color of a given cursor, use XRecolorCursor.

XRecolorCursor(Display *display, Cursor cursor, XColor*foreground_color, *background_color);

display

Specifies the connection to the X server.

cursor

Specifies the cursor.

foreground_color

Specifies the RGB values for the foreground of the source.

background_color

Specifies the RGB values for the background of the source.

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.

XRecolorCursor can generate a BadCursor error.

To free (destroy) a given cursor, use XFreeCursor.

XFreeCursor(Display *display, Cursor cursor);

display

Specifies the connection to the X server.

cursor

Specifies the cursor.

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.

XFreeCursor can generate a BadCursor error.

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.

This chapter discusses how to:

  • Create, copy, and destroy a colormap

  • Specify colors by name or value

  • Allocate, modify, and free color cells

  • Read entries in a colormap

  • Convert between color spaces

  • Control aspects of color conversion

  • Query the color gamut of a screen

  • Add new color spaces

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.

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.

The DefaultColormap macro returns the default colormap. The DefaultVisual macro returns the default visual type for the specified screen. Possible visual types are StaticGray, GrayScale, StaticColor, PseudoColor, TrueColor, or DirectColor (see section 3.1).

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).



typedef unsigned long XcmsColorFormat;			/* Color Specification Format */

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.

#define          XcmsUndefinedFormat   0x00000000
#define          XcmsCIEXYZFormat      0x00000001  /* CIE XYZ */
#define          XcmsCIEuvYFormat      0x00000002  /* CIE u'v'Y */
#define          XcmsCIExyYFormat      0x00000003  /* CIE xyY */
#define          XcmsCIELabFormat      0x00000004  /* CIE L*a*b* */
#define          XcmsCIELuvFormat      0x00000005  /* CIE L*u*v* */
#define          XcmsTekHVCFormat      0x00000006  /* TekHVC */
#define          XcmsRGBFormat         0x80000000  /* RGB Device */
#define          XcmsRGBiFormat        0x80000001  /* RGB Intensity */

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 double XcmsFloat;

typedef struct {
	unsigned short red;	/* 0x0000 to 0xffff */
	unsigned short green;	/* 0x0000 to 0xffff */
	unsigned short blue;	/* 0x0000 to 0xffff */
} XcmsRGB;		/* RGB Device */



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 */
	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 */

The device-dependent formats provided allow color specification in:

  • RGB Intensity (XcmsRGBi)

  • 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.

  • RGB Device (XcmsRGB)

  • 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.

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.

Color strings are used in the following functions:

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>

The following are examples of valid color strings.

"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 Device String Specification

An RGB Device specification is identified by the prefix “rgb:” and conforms to the following syntax:

rgb:<red>/<green>/<blue>

    <red>, <green>, <blue> := h | hh | hhh | hhhh
    h := single hexadecimal digits (case insignificant)

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:



#RGB	(4 bits each)
#RRGGBB	(8 bits each)
#RRRGGGBBB	(12 bits each)
#RRRRGGGGBBBB	(16 bits each)

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”.

RGB Intensity String Specification

An RGB intensity specification is identified by the prefix “rgbi:” and conforms to the following syntax:

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.

Device-Independent String Specifications

The standard device-independent string specifications have the following syntax:

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.

Color Conversion Contexts and Gamut Mapping

When Xlib converts device-independent color specifications into device-dependent specifications and vice versa, it uses knowledge about the color limitations of the screen hardware. This information, typically called the device profile, is available in a Color Conversion Context (CCC).

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:

  • Gamut compression occurs when conversion of device-independent color specifications to device-dependent color specifications results in a color out of the target screen's gamut.

  • 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.

Associated with each colormap is an initial CCC transparently generated by Xlib. Therefore, when you specify a colormap as an argument to an Xlib function, you are indirectly specifying a CCC. There is a default CCC associated with each screen. Newly created CCCs inherit attributes from the default CCC, so the default CCC attributes can be modified to affect new CCCs.

Xcms functions in which gamut mapping can occur return Status and have specific status values defined for them, as follows:

  • XcmsFailure indicates that the function failed.

  • XcmsSuccess indicates that the function succeeded. In addition, if the function performed any color conversion, the colors did not need to be compressed.

  • XcmsSuccessWithCompression indicates the function performed color conversion and at least one of the colors needed to be compressed. The gamut compression method is determined by the gamut compression procedure in the CCC that is specified directly as a function argument or in the CCC indirectly specified by means of the colormap argument.

Creating, Copying, and Destroying Colormaps

To create a colormap for a screen, use XCreateColormap.

Colormap XCreateColormap(Display *display, Window w, Visual *visual, int alloc);

display

Specifies the connection to the X server.

w

Specifies the window (Wi.

visual

Specifies a visual type supported on the screen. If the visual type is not one supported by the screen, a BadMatch error results.

alloc

Specifies the colormap entries to be allocated. You can pass AllocNone or AllocAll.

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.

XCreateColormap can generate BadAlloc, BadMatch, BadValue, and BadWindow errors.

To create a new colormap when the allocation out of a previously shared colormap has failed because of resource exhaustion, use XCopyColormapAndFree.

Colormap XCopyColormapAndFree(Display *display, Colormap colormap);

display

Specifies the connection to the X server.

colormap

Specifies the colormap.

The XCopyColormapAndFree function creates a colormap of the same visual type and for the same screen as the specified colormap and returns the new colormap ID. It also moves all of the client's existing allocation from the specified colormap to the new colormap with their color values intact and their read-only or writable characteristics intact and frees those entries in the specified colormap. Color values in other entries in the new colormap are undefined. If the specified colormap was created by the client with alloc set to AllocAll, the new colormap is also created 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.

XCopyColormapAndFree can generate BadAlloc and BadColor errors.

To destroy a colormap, use XFreeColormap.

XFreeColormap(Display *display, Colormap colormap);

display

Specifies the connection to the X server.

colormap

Specifies the colormap (Cm.

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.

XFreeColormap can generate a BadColor error.

Mapping Color Names to Values

To map a color name to an RGB value, use XLookupColor.

Status XLookupColor(Display *display, Colormap colormap, char *color_name, XColor*exact_def_return, *screen_def_return);

display

Specifies the connection to the X server.

colormap

Specifies the colormap.

color_name

Specifies the color name string (for example, red) whose color definition structure you want returned.

exact_def_return

Returns the exact RGB values.

screen_def_return

Returns the closest RGB values provided by the hardware.

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.

XLookupColor can generate a BadColor error.

To map a color name to the exact RGB value, use XParseColor.

Status XParseColor(Display *display, Colormap colormap, char *spec, XColor *exact_def_return);

display

Specifies the connection to the X server.

colormap

Specifies the colormap.

spec

Specifies the color name string; case is ignored.

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.

XParseColor can generate a BadColor error.

To map a color name to a value in an arbitrary color space, use XcmsLookupColor.

Status XcmsLookupColor(Display *display, Colormap colormap, char *color_string, XcmsColor*color_exact_return, *color_screen_return, XcmsColorFormat result_format);

display

Specifies the connection to the X server.

colormap

Specifies the colormap.

color_string

Specifies the color string(St.

color_exact_return

Returns the color specification parsed from the color string or parsed from the corresponding string found in a color-name database.

color_screen_return

Returns the color that can be reproduced on the screen.

result_format

Specifies the color format for the returned color specifications (color_screen_return and color_exact_return arguments). If the format is XcmsUndefinedFormat and the color string contains a numerical color specification, the specification is returned in the format used in that numerical color specification. If the format is XcmsUndefinedFormat and the color string contains a color name, the specification is returned in the format used to store the color in the database.

The XcmsLookupColor 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. The values are returned in the format specified by result_format. 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. XcmsLookupColor returns XcmsSuccess or XcmsSuccessWithCompression if the name is resolved; otherwise, it returns XcmsFailure. If XcmsSuccessWithCompression is returned, the color specification returned in color_screen_return is the result of gamut compression.

Allocating and Freeing Color Cells

There are two ways of allocating color cells: explicitly as read-only entries, one pixel value at a time, or read/write, where you can allocate a number of color cells and planes simultaneously. A read-only cell has its RGB value set by the server. Read/write cells do not have defined colors initially; functions described in the next section must be used to store values into them. Although it is possible for any client to store values into a read/write cell allocated by another client, read/write cells normally should be considered private to the client that allocated them.

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.

To allocate a read-only color cell with an RGB value, use XAllocColor.

Status XAllocColor(Display *display, Colormap colormap, XColor *screen_in_out);

display

Specifies the connection to the X server.

colormap

Specifies the colormap.

screen_in_out

Specifies and returns the values actually used in the colormap.

The XAllocColor function allocates a read-only colormap entry corresponding to the closest RGB value supported by the hardware. XAllocColor returns the pixel value of the color closest to the specified RGB elements supported by the hardware and returns the RGB value actually used. The corresponding colormap cell is read-only. In addition, XAllocColor returns nonzero if it succeeded or zero if it failed. Multiple clients that request the same effective RGB value can be assigned the same read-only entry, thus allowing entries to be shared. When the last client deallocates a shared cell, it is deallocated. XAllocColor does not use or affect the flags in the XColor structure.

XAllocColor can generate a BadColor error. delim %%

To allocate a read-only color cell with a color in arbitrary format, use XcmsAllocColor.

Status XcmsAllocColor(Display *display, Colormap colormap, XcmsColor *color_in_out, XcmsColorFormat result_format);

display

Specifies the connection to the X server.

colormap

Specifies the colormap.

color_in_out

Specifies the color to allocate and returns the pixel and color that is actually used in the colormap.

result_format

Specifies the color format for the returned color specification.

The XcmsAllocColor function is similar to XAllocColor except the color can be specified in any format. The XcmsAllocColor function ultimately calls XAllocColor to allocate a read-only color cell (colormap entry) with the specified color. XcmsAllocColor first converts the color specified to an RGB value and then passes this to XAllocColor. XcmsAllocColor returns the pixel value of the color cell and the color specification actually allocated. This returned color specification is the result of converting the RGB value returned by XAllocColor into the format specified with the result_format argument. If there is no interest in a returned color specification, unnecessary computation can be bypassed if result_format is set to XcmsRGBFormat. The corresponding colormap cell is read-only. If this routine returns XcmsFailure, the color_in_out color specification is left unchanged.

XcmsAllocColor can generate a BadColor error.

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.

Status XAllocNamedColor(Display *display, Colormap colormap, char *color_name, XColor*screen_def_return, *exact_def_return);

display

Specifies the connection to the X server.

colormap

Specifies the colormap.

color_name

Specifies the color name string (for example, red) whose color definition structure you want returned.

screen_def_return

Returns the closest RGB values provided by the hardware.

exact_def_return

Returns the exact RGB values.

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.

XAllocNamedColor can generate a BadColor error.

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.

Status XcmsAllocNamedColor(Display *display, Colormap colormap, char *color_string, XcmsColor *color_screen_return, XcmsColor *color_exact_return, XcmsColorFormat result_format);

display

Specifies the connection to the X server.

colormap

Specifies the colormap.

color_string

Specifies the color string(St.

color_screen_return

Returns the pixel value of the color cell and color specification that actually is stored for that cell.

color_exact_return

Returns the color specification parsed from the color string or parsed from the corresponding string found in a color-name database.

result_format

Specifies the color format for the returned color specifications (color_screen_return and color_exact_return arguments). If the format is XcmsUndefinedFormat and the color string contains a numerical color specification, the specification is returned in the format used in that numerical color specification. If the format is XcmsUndefinedFormat and the color string contains a color name, the specification is returned in the format used to store the color in the database.

The XcmsAllocNamedColor function is similar to XAllocNamedColor except that the color returned can be in any format specified. This function ultimately calls XAllocColor to allocate a read-only color cell with the color specified by a color string. The color string is parsed into an XcmsColor structure (see XcmsLookupColor), converted to an RGB value, and finally passed to XAllocColor. 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.

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.

XcmsAllocNamedColor can generate a BadColor error.

To allocate read/write color cell and color plane combinations for a PseudoColor model, use XAllocColorCells.

Status XAllocColorCells(Display *display, Colormap colormap, Bool contig, unsignedlong plane_masks_return[], unsignedint nplanes, unsignedlong pixels_return[], unsignedint npixels);

display

Specifies the connection to the X server.

colormap

Specifies the colormap.

contig

Specifies a Boolean value that indicates whether the planes must be contiguous.

plane_mask_return

Returns an array of plane masks.

nplanes

Specifies the number of plane masks that are to be returned in the plane masks array.

pixels_return

Returns an array of pixel values.

npixels

Specifies the number of pixel values that are to be returned in the pixels_return array.

The XAllocColorCells function allocates read/write color cells. The number of colors must be positive and the number of planes nonnegative, or a BadValue error results. If ncolors and nplanes are requested, then ncolors pixels and nplane plane masks are returned. No mask will have any bits set to 1 in common with any other mask or with any of the pixels. By ORing together each pixel with zero or more masks, ncolors × 2nplanes distinct pixels can be produced. All of these are allocated writable by the request. For GrayScale or PseudoColor, each mask has exactly one bit set to 1. For DirectColor, each has exactly three bits set to 1. If contig is True and if all masks are ORed together, a single contiguous set of bits set to 1 will be formed for GrayScale or PseudoColor and three contiguous sets of bits set to 1 (one within each pixel subfield) for DirectColor. The RGB values of the allocated entries are undefined. XAllocColorCells returns nonzero if it succeeded or zero if it failed.

XAllocColorCells can generate BadColor and BadValue errors.

To allocate read/write color resources for a DirectColor model, use XAllocColorPlanes.

Status XAllocColorPlanes(Display *display, Colormap colormap, Bool contig, unsignedlong pixels_return[], int ncolors, intnreds,ngreens, nblues, unsignedlong*rmask_return,*gmask_return, *bmask_return);

display

Specifies the connection to the X server.

colormap

Specifies the colormap.

contig

Specifies a Boolean value that indicates whether the planes must be contiguous.

pixels_return

Returns an array of pixel values. XAllocColorPlanes returns the pixel values in this array.

ncolors

Specifies the number of pixel values that are to be returned in the pixels_return array.

nreds

ngreens

nblues

Specify the number of red, green, and blue planes. The value you pass must be nonnegative.

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, each mask will lie within the corresponding pixel subfield. By ORing together subsets of masks with each pixel value, ncolors × 2(nreds+ngreens+nblues) distinct pixel values can be produced. All of these are allocated by the request. However, in the colormap, there are only ncolors × 2nreds independent red entries, ncolors × 2ngreens independent green entries, and ncolors × 2nblues 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.

XAllocColorPlanes can generate BadColor and BadValue errors.

To free colormap cells, use XFreeColors.

XFreeColors(Display *display, Colormap colormap, unsignedlong pixels[], int npixels, unsignedlong planes);

display

Specifies the connection to the X server.

colormap

Specifies the colormap.

pixels

Specifies an array of pixel values (Pi.

npixels

Specifies the number of pixels.

planes

Specifies the planes you want to free.

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.

XFreeColors can generate BadAccess, BadColor, and BadValue errors.

Modifying and Querying Colormap Cells

To store an RGB value in a single colormap cell, use XStoreColor.

XStoreColor(Display *display, Colormap colormap, XColor *color);

display

Specifies the connection to the X server.

colormap

Specifies the colormap.

color

Specifies the pixel and RGB values.

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.

XStoreColor can generate BadAccess, BadColor, and BadValue errors.

To store multiple RGB values in multiple colormap cells, use XStoreColors.

XStoreColors(Display *display, Colormap colormap, XColor color[], int ncolors);

display

Specifies the connection to the X server.

colormap

Specifies the colormap.

color

Specifies an array of color definition structures to be stored.

ncolors

Specifies the number of XColor structures in the color definition array.

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.

XStoreColors can generate BadAccess, BadColor, and BadValue errors.

To store a color of arbitrary format in a single colormap cell, use XcmsStoreColor.

Status XcmsStoreColor(Display *display, Colormap colormap, XcmsColor *color);

display

Specifies the connection to the X server.

colormap

Specifies the colormap.

color

Specifies the color cell and the color to store. Values specified in this XcmsColor structure remain unchanged on return.

The XcmsStoreColor function converts the color specified in the XcmsColor structure into RGB values. It then uses this RGB specification in an XColor structure, whose three flags (DoRed, DoGreen, and DoBlue) are set, in a call to XStoreColor to change the color cell specified by the pixel member of the XcmsColor structure. This pixel value must be a valid index for the specified colormap, and the color cell specified by the pixel value must be a read/write cell. If the pixel value is not a valid index, a BadValue error results. If the color cell is unallocated or is allocated read-only, a BadAccess error results. If the colormap is an installed map for its screen, the changes are visible immediately.

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.

XcmsStoreColor can generate BadAccess, BadColor, and BadValue errors.

To store multiple colors of arbitrary format in multiple colormap cells, use XcmsStoreColors.

Status XcmsStoreColors(Display *display, Colormap colormap, XcmsColor colors[], int ncolors, Bool compression_flags_return[]);

display

Specifies the connection to the X server.

colormap

Specifies the colormap.

colors

Specifies the color specification array of XcmsColor structures, each specifying a color cell and the color to store in that cell. Values specified in the array remain unchanged upon return.

ncolors

Specifies the number of XcmsColor structures in the color-specification array.

compression_flags_return

Returns an array of Boolean values indicating compression status. If a non-NULL pointer is supplied, each element of the array is set to True if the corresponding color was compressed and False otherwise. Pass NULL if the compression status is not useful.

The XcmsStoreColors function converts the colors specified in the array of XcmsColor structures into RGB values and then uses these RGB specifications in XColor structures, whose three flags (DoRed, DoGreen, and DoBlue) are set, in a call to XStoreColors to change the color cells specified by the pixel member of the corresponding XcmsColor structure. Each pixel value must be a valid index for the specified colormap, and the color cell specified by each pixel value must be a read/write cell. If a pixel value is not a valid index, a BadValue error results. If a color cell 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. If the colormap is an installed map for its screen, the changes are visible immediately.

Note that XStoreColors has no return value; therefore, an XcmsSuccess return value from this function indicates that conversions to RGB succeeded and the call to 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.

XcmsStoreColors can generate BadAccess, BadColor, and BadValue errors.

To store a color specified by name in a single colormap cell, use XStoreNamedColor.

XStoreNamedColor(Display *display, Colormap colormap, char *color, unsignedlong pixel, int flags);

display

Specifies the connection to the X server.

colormap

Specifies the colormap.

color

Specifies the color name string (for example, red).

pixel

Specifies the entry in the colormap.

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.

XStoreNamedColor can generate BadAccess, BadColor, BadName, and BadValue errors.

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.

To query the RGB value of a single colormap cell, use XQueryColor.

XQueryColor(Display *display, Colormap colormap, XColor *def_in_out);

display

Specifies the connection to the X server.

colormap

Specifies the colormap.

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.

XQueryColor can generate BadColor and BadValue errors.

To query the RGB values of multiple colormap cells, use XQueryColors.

XQueryColors(Display *display, Colormap colormap, XColor defs_in_out[], int ncolors);

display

Specifies the connection to the X server.

colormap

Specifies the colormap.

defs_in_out

Specifies and returns an array of color definition structures for the pixel specified in the structure.

ncolors

Specifies the number of XColor structures in the color definition array.

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.

XQueryColors can generate BadColor and BadValue errors.

To query the color of a single colormap cell in an arbitrary format, use XcmsQueryColor.

Status XcmsQueryColor(Display *display, Colormap colormap, XcmsColor *color_in_out, XcmsColorFormat result_format);

display

Specifies the connection to the X server.

colormap

Specifies the colormap.

color_in_out

Specifies the pixel member that indicates the color cell to query. The color specification stored for the color cell is returned in this XcmsColor structure.

result_format

Specifies the color format for the returned color specification.

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.

XcmsQueryColor can generate BadColor and BadValue errors.

To query the color of multiple colormap cells in an arbitrary format, use XcmsQueryColors.

Status XcmsQueryColors(Display *display, Colormap colormap, XcmsColor colors_in_out[], unsignedint ncolors, XcmsColorFormat result_format);

display

Specifies the connection to the X server.

colormap

Specifies the colormap.

colors_in_out

Specifies an array of XcmsColor structures, each pixel member indicating the color cell to query. The color specifications for the color cells are returned in these structures.

ncolors

Specifies the number of XcmsColor structures in the color-specification array.

result_format

Specifies the color format for the returned color specification.

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.

XcmsQueryColors can generate BadColor and BadValue errors.

Color Conversion Context Functions

This section describes functions to create, modify, and query Color Conversion Contexts (CCCs).

Associated with each colormap is an initial CCC transparently generated by Xlib. Therefore, when you specify a colormap as an argument to a function, you are indirectly specifying a CCC. The CCC attributes that can be modified by the X client are:

  • Client White Point

  • Gamut compression procedure and client data

  • White point adjustment procedure and client data

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.

Getting and Setting the Color Conversion Context of a Colormap

To obtain the CCC associated with a colormap, use XcmsCCCOfColormap.

XcmsCCC XcmsCCCOfColormap(Display *display, Colormap colormap);

display

Specifies the connection to the X server.

colormap

Specifies the colormap.

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.

To change the CCC associated with a colormap, use XcmsSetCCCOfColormap.

XcmsCCC XcmsSetCCCOfColormap(Display *display, Colormap colormap, XcmsCCC ccc);

display

Specifies the connection to the X server.

colormap

Specifies the colormap.

ccc

Specifies the CCC.

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.

Obtaining the Default Color Conversion Context

You can change the default CCC attributes for subsequently created CCCs by changing the CCC attributes of the default CCC. A default CCC is associated with each screen.

To obtain the default CCC for a screen, use XcmsDefaultCCC.

XcmsCCC XcmsDefaultCCC(Display *display, int screen_number);

display

Specifies the connection to the X server.

screen_number

Specifies the appropriate screen number on the host server.

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.

Color Conversion Context Macros

Applications should not directly modify any part of the XcmsCCC. The following lists the C language macros, their corresponding function equivalents for other language bindings, and what data they both can return.

DisplayOfCCC(XcmsCCC ccc);

Display *XcmsDisplayOfCCC(XcmsCCC ccc);

ccc

Specifies the CCC.

Both return the display associated with the specified CCC.

VisualOfCCC(XcmsCCC ccc);

Visual *XcmsVisualOfCCC(XcmsCCC ccc);

ccc

Specifies the CCC.

Both return the visual associated with the specified CCC.

ScreenNumberOfCCC(XcmsCCC ccc);

int XcmsScreenNumberOfCCC(XcmsCCC ccc);

ccc

Specifies the CCC.

Both return the number of the screen associated with the specified CCC.

ScreenWhitePointOfCCC(XcmsCCC ccc);

XcmsColor XcmsScreenWhitePointOfCCC(XcmsCCC ccc);

ccc

Specifies the CCC.

Both return the white point of the screen associated with the specified CCC.

ClientWhitePointOfCCC(XcmsCCC ccc);

XcmsColor *XcmsClientWhitePointOfCCC(XcmsCCC ccc);

ccc

Specifies the CCC.

Both return the Client White Point of the specified CCC.

Modifying Attributes of a Color Conversion Context

To set the Client White Point in the CCC, use XcmsSetWhitePoint.

Status XcmsSetWhitePoint(XcmsCCC ccc, XcmsColor *color);

ccc

Specifies the CCC.

color

Specifies the new Client White Point.

The XcmsSetWhitePoint function changes the Client White Point in the specified CCC. Note that the pixel member is ignored and that the color specification is left unchanged upon return. The format for the new white point must be XcmsCIEXYZFormat, XcmsCIEuvYFormat, XcmsCIExyYFormat, or XcmsUndefinedFormat. If the color argument is NULL, this function sets the format component of the Client White Point specification to XcmsUndefinedFormat, indicating that the Client White Point is assumed to be the same as the Screen White Point.

This function returns nonzero status if the format for the new white point is valid; otherwise, it returns zero.

To set the gamut compression procedure and corresponding client data in a specified CCC, use XcmsSetCompressionProc.

XcmsCompressionProc XcmsSetCompressionProc(XcmsCCC ccc, XcmsCompressionProc compression_proc, XPointer client_data);

ccc

Specifies the CCC.

compression_proc

Specifies the gamut compression procedure that is to be applied when a color lies outside the screen's color gamut. If NULL is specified and a function using this CCC must convert a color specification to a device-dependent format and encounters a color that lies outside the screen's color gamut, that function will return XcmsFailure.

client_data

Specifies client data for gamut compression procedure or NULL.

The XcmsSetCompressionProc function first sets the gamut compression procedure and client data in the specified CCC with the newly specified procedure and client data and then returns the old procedure.

To set the white point adjustment procedure and corresponding client data in a specified CCC, use XcmsSetWhiteAdjustProc.

XcmsWhiteAdjustProc XcmsSetWhiteAdjustProc(XcmsCCC ccc, XcmsWhiteAdjustProc white_adjust_proc, XPointer client_data);

ccc

Specifies the CCC.

white_adjust_proc

Specifies the white point adjustment procedure.

client_data

Specifies client data for white point adjustment procedure or NULL.

The XcmsSetWhiteAdjustProc function first sets the white point adjustment procedure and client data in the specified CCC with the newly specified procedure and client data and then returns the old procedure.

Creating and Freeing a Color Conversion Context

You can explicitly create a CCC within your application by calling XcmsCreateCCC. These created CCCs can then be used by those functions that explicitly call for a CCC argument. Old CCCs that will not be used by the application should be freed using XcmsFreeCCC.

To create a CCC, use XcmsCreateCCC.

XcmsCCC XcmsCreateCCC(Display *display, int screen_number, Visual *visual, XcmsColor *client_white_point, XcmsCompressionProc compression_proc, XPointer compression_client_data, XcmsWhiteAdjustProc white_adjust_proc, XPointer white_adjust_client_data);

display

Specifies the connection to the X server.

screen_number

Specifies the appropriate screen number on the host server.

visual

Specifies the visual type.

client_white_point

Specifies the Client White Point. If NULL is specified, the Client White Point is to be assumed to be the same as the Screen White Point. Note that the pixel member is ignored.

compression_proc

Specifies the gamut compression procedure that is to be applied when a color lies outside the screen's color gamut. If NULL is specified and a function using this CCC must convert a color specification to a device-dependent format and encounters a color that lies outside the screen's color gamut, that function will return XcmsFailure.

compression_client_data

Specifies client data for use by the gamut compression procedure or NULL.

white_adjust_proc

Specifies the white adjustment procedure that is to be applied when the Client White Point differs from the Screen White Point. NULL indicates that no white point adjustment is desired.

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.

To free a CCC, use XcmsFreeCCC.

void XcmsFreeCCC(XcmsCCC ccc);

ccc

Specifies the CCC.

The XcmsFreeCCC function frees the memory used for the specified CCC. Note that default CCCs and those currently associated with colormaps are ignored.

Converting between Color Spaces

To convert an array of color specifications in arbitrary color formats to a single destination format, use XcmsConvertColors.

Status XcmsConvertColors(XcmsCCC ccc, XcmsColor colors_in_out[], unsignedint ncolors, XcmsColorFormat target_format, Bool compression_flags_return[]);

ccc

Specifies the CCC. If conversion is between device-independent color spaces only (for example, TekHVC to CIELuv), the CCC is necessary only to specify the Client White Point.

colors_in_out

Specifies an array of color specifications. Pixel members are ignored and remain unchanged upon return.

ncolors

Specifies the number of XcmsColor structures in the color-specification array.

target_format

Specifies the target color specification format.

compression_flags_return

Returns an array of Boolean values indicating compression status. If a non-NULL pointer is supplied, each element of the array is set to True if the corresponding color was compressed and False otherwise. Pass NULL if the compression status is not useful.

The XcmsConvertColors function converts the color specifications in the specified array of XcmsColor structures from their current format to a single target format, using the specified CCC. When the return value is XcmsFailure, the contents of the color specification array are left unchanged.

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 and device-dependent color specifications and the target_format argument specifies a device-dependent format (for example, XcmsRGBiFormat, XcmsRGBFormat), all specifications are converted to CIE XYZ format and then to the target device-dependent format.

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.

During color specification conversion between device-independent and device-dependent color spaces, if a white point adjustment procedure is specified in the CCC, it is triggered when the Client White Point and Screen White Point differ. If required, the client data is obtained from the CCC.

Prototype Gamut Compression Procedure

The gamut compression callback interface must adhere to the following:

typedef Status(*XcmsCompressionProc)(XcmsCCC ccc, XcmsColor colors_in_out[], unsignedint ncolors, unsignedint index, Bool compression_flags_return[]);

ccc

Specifies the CCC.

colors_in_out

Specifies an array of color specifications. Pixel members should be ignored and must remain unchanged upon return.

ncolors

Specifies the number of XcmsColor structures in the color-specification array.

index

Specifies the index into the array of XcmsColor structures for the encountered color specification that lies outside the screen's color gamut. Valid values are 0 (for the first element) to ncolors - 1.

compression_flags_return

Returns an array of Boolean values for indicating compression status. If a non-NULL pointer is supplied and a color at a given index is compressed, then True should be stored at the corresponding index in this array; otherwise, the array should not be modified.

When implementing a gamut compression procedure, consider the following rules and assumptions:

  • The gamut compression procedure can attempt to compress one or multiple specifications at a time.

  • When called, elements 0 to index - 1 in the color specification array can be assumed to fall within the screen's color gamut. In addition, these color specifications are already in some device-dependent format (typically XcmsRGBi). If any modifications are made to these color specifications, they must be in their initial device-dependent format upon return.

  • 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.

  • If the gamut compression procedure uses a device-independent color space not initially accessible for use in the color management system, use XcmsAddColorSpace to ensure that it is added.

Supplied Gamut Compression Procedures

The following equations are useful in describing gamut compression functions: delim %%

%CIELab~Psychometric~Chroma ~=~ sqrt(a_star sup 2 ~+~ b_star sup 2 )%

%CIELab~Psychometric~Hue ~=~ tan sup -1 left [ b_star over a_star right ]%

%CIELuv~Psychometric~Chroma ~=~ sqrt(u_star sup 2 ~+~ v_star sup 2 )%

%CIELuv~Psychometric~Hue ~=~ tan sup -1 left [ v_star over u_star right ]%

The gamut compression callback procedures provided by Xlib are as follows:

  • 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.

  • 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.

Prototype White Point Adjustment Procedure

The white point adjustment procedure interface must adhere to the following:

typedef Status (*XcmsWhiteAdjustProc)(XcmsCCC ccc, XcmsColor *initial_white_point, XcmsColor *target_white_point, XcmsColorFormat target_format, XcmsColor colors_in_out[], unsignedint ncolors, Bool compression_flags_return[]);

ccc

Specifies the CCC.

initial_white_point

Specifies the initial white point.

target_white_point

Specifies the target white point.

target_format

Specifies the target color specification format.

colors_in_out

Specifies an array of color specifications. Pixel members should be ignored and must remain unchanged upon return.

ncolors

Specifies the number of XcmsColor structures in the color-specification array.

compression_flags_return

Returns an array of Boolean values for indicating compression status. If a non-NULL pointer is supplied and a color at a given index is compressed, then True should be stored at the corresponding index in this array; otherwise, the array should not be modified.

Supplied White Point Adjustment Procedures

White point adjustment procedures provided by Xlib are as follows:

  • 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 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.

From an implementation point of view, these white point adjustment procedures convert the color specifications to a device-independent but white-point-dependent color space (for example, CIE L*u*v*, CIE L*a*b*, TekHVC) using one white point and then converting those specifications to the target color space using another white point. In other words, the specification goes in the color space with one white point but comes out with another white point, resulting in a chromatic shift based on the chromatic displacement between the initial white point and target white point. The CIE color spaces that are assumed to be white-point-independent are CIE u'v'Y, CIE XYZ, and CIE xyY. When developing a custom white point adjustment procedure that uses a device-independent color space not initially accessible for use in the color management system, use XcmsAddColorSpace to ensure that it is added.

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:

  • Once to convert to XcmsRGB

  • A second time to convert from XcmsRGB

For example, assume the specification is in XcmsCIEuvY and the adjustment procedure is XcmsCIELuvWhiteShiftColors. During conversion to XcmsRGB, the call to XcmsAllocColor results in the following series of color specification conversions:

  • From XcmsCIEuvY to XcmsCIELuv using the Client White Point

  • From XcmsCIELuv to XcmsCIEuvY using the Screen White Point

  • From XcmsCIEuvY to XcmsCIEXYZ (CIE u'v'Y and XYZ are white-point-independent color spaces)

  • From XcmsCIEXYZ to XcmsRGBi

  • From XcmsRGBi to XcmsRGB

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.

Gamut Querying Functions

This section describes the gamut querying functions that Xlib provides. These functions allow the client to query the boundary of the screen's color gamut in terms of the CIE L*a*b*, CIE L*u*v*, and TekHVC color spaces. Functions are also provided that allow you to query the color specification of:

  • White (full-intensity red, green, and blue)

  • Red (full-intensity red while green and blue are zero)

  • Green (full-intensity green while red and blue are zero)

  • Blue (full-intensity blue while red and green are zero)

  • Black (zero-intensity red, green, and blue)

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.

Red, Green, and Blue Queries

To obtain the color specification for black (zero-intensity red, green, and blue), use XcmsQueryBlack.

Status XcmsQueryBlack(XcmsCCC ccc, XcmsColorFormat target_format, XcmsColor *color_return);

ccc

Specifies the CCC. The CCC's Client White Point and white point adjustment procedures are ignored.

target_format

Specifies the target color specification format.

color_return

Returns the color specification in the specified target format for (Cs. The white point associated with the returned color specification is the Screen White Point. The value returned in the pixel member is undefined.

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.

Status XcmsQueryBlue(XcmsCCC ccc, XcmsColorFormat target_format, XcmsColor *color_return);

ccc

Specifies the CCC. The CCC's Client White Point and white point adjustment procedures are ignored.

target_format

Specifies the target color specification format.

color_return

Returns the color specification in the specified target format for (Cs. The white point associated with the returned color specification is the Screen White Point. The value returned in the pixel member is undefined.

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.

Status XcmsQueryGreen(XcmsCCC ccc, XcmsColorFormat target_format, XcmsColor *color_return);

ccc

Specifies the CCC. The CCC's Client White Point and white point adjustment procedures are ignored.

target_format

Specifies the target color specification format.

color_return

Returns the color specification in the specified target format for (Cs. The white point associated with the returned color specification is the Screen White Point. The value returned in the pixel member is undefined.

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.

Status XcmsQueryRed(XcmsCCC ccc, XcmsColorFormat target_format, XcmsColor *color_return);

ccc

Specifies the CCC. The CCC's Client White Point and white point adjustment procedures are ignored.

target_format

Specifies the target color specification format.

color_return

Returns the color specification in the specified target format for (Cs. The white point associated with the returned color specification is the Screen White Point. The value returned in the pixel member is undefined.

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.

Status XcmsQueryWhite(XcmsCCC ccc, XcmsColorFormat target_format, XcmsColor *color_return);

ccc

Specifies the CCC. The CCC's Client White Point and white point adjustment procedures are ignored.

target_format

Specifies the target color specification format.

color_return

Returns the color specification in the specified target format for (Cs. The white point associated with the returned color specification is the Screen White Point. The value returned in the pixel member is undefined.

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 %%

%CIELab~Psychometric~Chroma ~=~ sqrt(a_star sup 2 ~+~ b_star sup 2 )%

%CIELab~Psychometric~Hue ~=~ tan sup -1 left [ b_star over a_star right ]%

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.

Status XcmsCIELabQueryMaxC(XcmsCCC ccc, XcmsFloat hue_angle, XcmsFloat L_star, XcmsColor *color_return);

ccc

Specifies the CCC. The CCC's Client White Point and white point adjustment procedures are ignored.

hue_angle

Specifies the hue angle (in degrees) at which to find (Ha.

L_star

Specifies the lightness (L*) at which to find (Ls.

color_return

Returns the CIE L*a*b* coordinates of (Lc displayable by the screen for the given (lC. The white point associated with the returned color specification is the Screen White Point. The value returned in the pixel member is undefined.

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.

To obtain the CIE L*a*b* coordinates of maximum CIE metric lightness (L*) for a given Psychometric Hue Angle and Psychometric Chroma, use XcmsCIELabQueryMaxL.

Status XcmsCIELabQueryMaxL(XcmsCCC ccc, XcmsFloat hue_angle, XcmsFloat chroma, XcmsColor *color_return);

ccc

Specifies the CCC. The CCC's Client White Point and white point adjustment procedures are ignored.

hue_angle

Specifies the hue angle (in degrees) at which to find (Ha.

chroma

Specifies the chroma at which to find (Ch.

color_return

Returns the CIE L*a*b* coordinates of (Lc displayable by the screen for the given (lC. The white point associated with the returned color specification is the Screen White Point. The value returned in the pixel member is undefined.

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.

Status XcmsCIELabQueryMaxLC(XcmsCCC ccc, XcmsFloat hue_angle, XcmsColor *color_return);

ccc

Specifies the CCC. The CCC's Client White Point and white point adjustment procedures are ignored.

hue_angle

Specifies the hue angle (in degrees) at which to find (Ha.

color_return

Returns the CIE L*a*b* coordinates of (Lc displayable by the screen for the given (lC. The white point associated with the returned color specification is the Screen White Point. The value returned in the pixel member is undefined.

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.

To obtain the CIE L*a*b* coordinates of minimum CIE metric lightness (L*) for a given Psychometric Hue Angle and Psychometric Chroma, use XcmsCIELabQueryMinL.

Status XcmsCIELabQueryMinL(XcmsCCC ccc, XcmsFloat hue_angle, XcmsFloat chroma, XcmsColor *color_return);

ccc

Specifies the CCC. The CCC's Client White Point and white point adjustment procedures are ignored.

hue_angle

Specifies the hue angle (in degrees) at which to find (Ha.

chroma

Specifies the chroma at which to find (Ch.

color_return

Returns the CIE L*a*b* coordinates of (Lc displayable by the screen for the given (lC. The white point associated with the returned color specification is the Screen White Point. The value returned in the pixel member is undefined.

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 %%

%CIELuv~Psychometric~Chroma ~=~ sqrt(u_star sup 2 ~+~ v_star sup 2 )%

%CIELuv~Psychometric~Hue ~=~ tan sup -1 left [ v_star over u_star right ]%

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.

Status XcmsCIELuvQueryMaxC(XcmsCCC ccc, XcmsFloat hue_angle, XcmsFloat L_star, XcmsColor *color_return);

ccc

Specifies the CCC. The CCC's Client White Point and white point adjustment procedures are ignored.

hue_angle

Specifies the hue angle (in degrees) at which to find (Ha.

L_star

Specifies the lightness (L*) at which to find (Ls.

color_return

Returns the CIE L*u*v* coordinates of (Lc displayable by the screen for the given (lC. The white point associated with the returned color specification is the Screen White Point. The value returned in the pixel member is undefined.

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.

To obtain the CIE L*u*v* coordinates of maximum CIE metric lightness (L*) for a given Psychometric Hue Angle and Psychometric Chroma, use XcmsCIELuvQueryMaxL.

Status XcmsCIELuvQueryMaxL(XcmsCCC ccc, XcmsFloat hue_angle, XcmsFloat chroma, XcmsColor *color_return);

ccc

Specifies the CCC. The CCC's Client White Point and white point adjustment procedures are ignored.

hue_angle

Specifies the hue angle (in degrees) at which to find (Ha.

L_star

Specifies the lightness (L*) at which to find (Ls.

color_return

Returns the CIE L*u*v* coordinates of (Lc displayable by the screen for the given (lC. The white point associated with the returned color specification is the Screen White Point. The value returned in the pixel member is undefined.

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.

Status XcmsCIELuvQueryMaxLC(XcmsCCC ccc, XcmsFloat hue_angle, XcmsColor *color_return);

ccc

Specifies the CCC. The CCC's Client White Point and white point adjustment procedures are ignored.

hue_angle

Specifies the hue angle (in degrees) at which to find (Ha.

color_return

Returns the CIE L*u*v* coordinates of (Lc displayable by the screen for the given (lC. The white point associated with the returned color specification is the Screen White Point. The value returned in the pixel member is undefined.

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.

To obtain the CIE L*u*v* coordinates of minimum CIE metric lightness (L*) for a given Psychometric Hue Angle and Psychometric Chroma, use XcmsCIELuvQueryMinL.

Status XcmsCIELuvQueryMinL(XcmsCCC ccc, XcmsFloat hue_angle, XcmsFloat chroma, XcmsColor *color_return);

ccc

Specifies the CCC. The CCC's Client White Point and white point adjustment procedures are ignored.

hue_angle

Specifies the hue angle (in degrees) at which to find (Ha.

chroma

Specifies the chroma at which to find (Ch.

color_return

Returns the CIE L*u*v* coordinates of (Lc displayable by the screen for the given (lC. The white point associated with the returned color specification is the Screen White Point. The value returned in the pixel member is undefined.

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 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.

Status XcmsTekHVCQueryMaxC(XcmsCCC ccc, XcmsFloat hue, XcmsFloat value, XcmsColor *color_return);

ccc

Specifies the CCC. The CCC's Client White Point and white point adjustment procedures are ignored.

hue

Specifies the Hue (Hu.

value

Specifies the Value in which to find the (Va.

color_return

Returns the (Lc at which the (lC 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.

The XcmsTekHVCQueryMaxC function, given a Hue and Value, determines the maximum Chroma in TekHVC color space displayable by the screen. It returns the maximum Chroma along with the actual Hue and Value at which the maximum Chroma was found.

To obtain the maximum Value for a given Hue and Chroma, use XcmsTekHVCQueryMaxV.

Status XcmsTekHVCQueryMaxV(XcmsCCC ccc, XcmsFloat hue, XcmsFloat chroma, XcmsColor *color_return);

ccc

Specifies the CCC. The CCC's Client White Point and white point adjustment procedures are ignored.

hue

Specifies the Hue (Hu.

chroma

Specifies the chroma at which to find (Ch.

color_return

Returns the (Lc at which the (lC 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.

The XcmsTekHVCQueryMaxV function, given a Hue and Chroma, determines the maximum Value in TekHVC color space displayable by the screen. It returns the maximum Value and the actual Hue and Chroma at which the maximum Value was found.

To obtain the maximum Chroma and Value at which it is reached for a specified Hue, use XcmsTekHVCQueryMaxVC.

Status XcmsTekHVCQueryMaxVC(XcmsCCC ccc, XcmsFloat hue, XcmsColor *color_return);

ccc

Specifies the CCC. The CCC's Client White Point and white point adjustment procedures are ignored.

hue

Specifies the Hue (Hu. XcmsTekHVC for the maximum Chroma, the Value at which \ that maximum Chroma is reached, and the actual Hue

color_return

Returns the (Lc at which the (lC 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.

The XcmsTekHVCQueryMaxVC function, given a Hue, determines the maximum Chroma in TekHVC color space displayable by the screen and the Value at which that maximum Chroma is reached. It returns the maximum Chroma, the Value at which that maximum Chroma is reached, and the actual Hue for which the maximum Chroma was found.

To obtain a specified number of TekHVC specifications such that they contain maximum Values for a specified Hue and the Chroma at which the maximum Values are reached, use XcmsTekHVCQueryMaxVSamples.

Status XcmsTekHVCQueryMaxVSamples(XcmsCCC ccc, XcmsFloat hue, XcmsColor colors_return[], unsignedint nsamples);

ccc

Specifies the CCC. The CCC's Client White Point and white point adjustment procedures are ignored.

hue

Specifies the Hue (Hu.

nsamples

Specifies the number of samples.

colors_return

Returns nsamples of color specifications in XcmsTekHVC such that the Chroma is the maximum attainable for the Value and Hue. The white point associated with the returned color specification is the Screen White Point. The value returned in the pixel member is undefined.

The XcmsTekHVCQueryMaxVSamples returns nsamples of maximum Value, the Chroma at which that maximum Value is reached, and the actual Hue for which the maximum Chroma was found. These sample points may then be used to plot the maximum Value/Chroma boundary of the screen's color gamut for the specified Hue in TekHVC color space.

To obtain the minimum Value for a given Hue and Chroma, use XcmsTekHVCQueryMinV.

Status XcmsTekHVCQueryMinV(XcmsCCC ccc, XcmsFloat hue, XcmsFloat chroma, XcmsColor *color_return);

ccc

Specifies the CCC. The CCC's Client White Point and white point adjustment procedures are ignored.

hue

Specifies the Hue (Hu.

value

Specifies the Value in which to find the (Va.

color_return

Returns the (Lc at which the (lC 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.

The XcmsTekHVCQueryMinV function, given a Hue and Chroma, determines the minimum Value in TekHVC color space displayable by the screen. It returns the minimum Value and the actual Hue and Chroma at which the minimum Value was found.

Color Management Extensions

The Xlib color management facilities can be extended in two ways:

  • Device-Independent Color Spaces

  • Device-independent color spaces that are derivable to CIE XYZ space can be added using the XcmsAddColorSpace function.

  • Color Characterization Function Set

  • A Color Characterization Function Set consists of device-dependent color spaces and their functions that convert between these color spaces and the CIE XYZ color space, bundled together for a specific class of output devices. A function set can be added using the XcmsAddFunctionSet 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.

Of course, when converting between only device-independent color spaces or only device-dependent color spaces, shortcuts are taken whenever possible. For example, conversion from TekHVC to CIE L*u*v* is performed by intermediate conversion to CIE u*v*Y and then to CIE L*u*v*, thus bypassing conversion between CIE u*v*Y and CIE XYZ.

Adding Device-Independent Color Spaces

To add a device-independent color space, use XcmsAddColorSpace.

Status XcmsAddColorSpace(XcmsColorSpace *color_space);

color_space

Specifies the device-independent color space to add.

The XcmsAddColorSpace function makes a device-independent color space (actually an XcmsColorSpace structure) accessible by the color management system. Because format values for unregistered color spaces are assigned at run time, they should be treated as private to the client. If references to an unregistered color space must be made outside the client (for example, storing color specifications in a file using the unregistered color space), then reference should be made by color space prefix (see XcmsFormatOfPrefix and XcmsPrefixOfFormat).

If the XcmsColorSpace structure is already accessible in the color management system, XcmsAddColorSpace returns XcmsSuccess.

Note that added XcmsColorSpaces must be retained for reference by Xlib.

Querying Color Space Format and Prefix

To obtain the format associated with the color space associated with a specified color string prefix, use XcmsFormatOfPrefix.

XcmsColorFormat XcmsFormatOfPrefix(char *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(XcmsColorFormat format);

format

Specifies the color specification 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.

Creating Additional Color Spaces

Color space specific information necessary for color space conversion and color string parsing is stored in an XcmsColorSpace structure. Therefore, a new structure containing this information is required for each additional color space. In the case of device-independent color spaces, a handle to this new structure (that is, by means of a global variable) is usually made accessible to the client program for use with the XcmsAddColorSpace function.

If a new XcmsColorSpace structure specifies a color space not registered with the X Consortium, they should be treated as private to the client because format values for unregistered color spaces are assigned at run time. If references to an unregistered color space must be made outside the client (for example, storing color 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*/

typedef struct _XcmsColorSpace {
	char *prefix;
	XcmsColorFormat format;
	XcmsParseStringProc parseString;
	XcmsFuncListPtr to_CIEXYZ;
	XcmsFuncListPtr from_CIEXYZ;
	int inverse_flag;
} XcmsColorSpace;

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:

Given:  n = number of functions in each list

for each i, such that 0 <= i < n
    from_CIEXYZ[n - i - 1] is the inverse of to_CIEXYZ[i].

This allows Xlib to use the shortest conversion path, thus bypassing CIE XYZ if possible (for example, TekHVC to CIE L*u*v*).

Parse String Callback

The callback in the XcmsColorSpace structure for parsing a color string for the particular color space must adhere to the following software interface specification:

Status XcmsParseStringProc(char *color_string, XcmsColor *color_return);

color_string

Specifies the color string to parse.

color_return

Returns the color specification in the color space's format.

Color Specification Conversion Callback

Callback functions in the XcmsColorSpace structure for converting a color specification between device-independent spaces must adhere to the following software interface specification:

Status ConversionProc(XcmsCCC ccc, XcmsColor *white_point, XcmsColor *colors_in_out, unsignedint ncolors);

ccc

Specifies the CCC.

white_point

Specifies the white point associated with color specifications. The pixel member should be ignored, and the entire structure remain unchanged upon return.

colors_in_out

Specifies an array of color specifications. Pixel members should be ignored and must remain unchanged upon return.

ncolors

Specifies the number of XcmsColor structures in the color-specification array.

Callback functions in the XcmsColorSpace structure for converting a color specification to or from a device-dependent space must adhere to the following software interface specification:

Status ConversionProc(XcmsCCC ccc, XcmsColor *colors_in_out, unsignedint ncolors, Bool compression_flags_return[]);

ccc

Specifies the CCC.

colors_in_out

Specifies an array of color specifications. Pixel members should be ignored and must remain unchanged upon return.

ncolors

Specifies the number of XcmsColor structures in the color-specification array.

compression_flags_return

Returns an array of Boolean values for indicating compression status. If a non-NULL pointer is supplied and a color at a given index is compressed, then True should be stored at the corresponding index in this array; otherwise, the array should not be modified.

Conversion functions are available globally for use by other color spaces. The conversion functions provided by Xlib are:

FunctionConverts fromConverts to
XcmsCIELabToCIEXYZXcmsCIELabFormatXcmsCIEXYZFormat
XcmsCIELuvToCIEuvYXcmsCIELuvFormatXcmsCIEuvYFormat
XcmsCIEXYZToCIELabXcmsCIEXYZFormatXcmsCIELabFormat
XcmsCIEXYZToCIEuvYXcmsCIEXYZFormatXcmsCIEuvYFormat
XcmsCIEXYZToCIExyYXcmsCIEXYZFormatXcmsCIExyYFormat
XcmsCIEXYZToRGBiXcmsCIEXYZFormatXcmsRGBiFormat
XcmsCIEuvYToCIELuvXcmsCIEuvYFormatXcmsCIELabFormat
XcmsCIEuvYToCIEXYZXcmsCIEuvYFormatXcmsCIEXYZFormat
XcmsCIEuvYToTekHVCXcmsCIEuvYFormatXcmsTekHVCFormat
XcmsCIExyYToCIEXYZXcmsCIExyYFormatXcmsCIEXYZFormat
XcmsRGBToRGBiXcmsRGBFormatXcmsRGBiFormat
XcmsRGBiToCIEXYZXcmsRGBiFormatXcmsCIEXYZFormat
XcmsRGBiToRGBXcmsRGBiFormatXcmsRGBFormat
XcmsTekHVCToCIEuvYXcmsTekHVCFormatXcmsCIEuvYFormat

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.

Adding Function Sets

To add a function set, use XcmsAddFunctionSet.

Status XcmsAddFunctionSet(XcmsFunctionSet *function_set);

function_set

Specifies the function set to add.

The XcmsAddFunctionSet function adds a function set to the color management system. If the function set uses device-dependent XcmsColorSpace structures not accessible in the color management system, XcmsAddFunctionSet adds them. If an added XcmsColorSpace structure is for a device-dependent color space not registered with the X Consortium, they should be treated as private to the client because format values for unregistered color spaces are assigned at run time. If references to an unregistered color space must be made outside the client (for example, storing color specifications in a file using the unregistered color space), then reference should be made by color space prefix (see XcmsFormatOfPrefix and XcmsPrefixOfFormat).

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.

Creating Additional Function Sets

The creation of additional function sets should be required only when an output device does not conform to existing function sets or when additional device-dependent color spaces are necessary. A function set consists primarily of a collection of device-dependent XcmsColorSpace structures and a means to read and store a screen's color characterization data. This data is stored in an XcmsFunctionSet structure. A handle to this structure (that is, by means of global variable) is usually made accessible to the client program for use with XcmsAddFunctionSet.

If a function set uses new device-dependent XcmsColorSpace structures, they will be transparently processed into the color management system. Function sets can share an XcmsColorSpace structure for a device-dependent color space. In addition, multiple XcmsColorSpace structures are allowed for a device-dependent color space; however, a function set can reference only one of them. These XcmsColorSpace structures will differ in the functions to convert to and from CIE XYZ, thus tailored for the specific function set.



typedef struct _XcmsFunctionSet {
	XcmsColorSpace **DDColorSpaces;
	XcmsScreenInitProc screenInitProc;
	XcmsScreenFreeProc screenFreeProc;
} XcmsFunctionSet;

The DDColorSpaces member is a pointer to a NULL terminated list of pointers to XcmsColorSpace structures for the device-dependent color spaces that are supported by the function set. The screenInitProc member is set to the callback procedure (see the following interface specification) that initializes the XcmsPerScrnInfo structure for a particular screen.

The screen initialization callback must adhere to the following software interface specification:

typedef Status (*XcmsScreenInitProc)(Display *display, int screen_number, ScmsPerScrnInfo *screen_info);

display

Specifies the connection to the X server.

screen_number

Specifies the appropriate screen number on the host server.

screen_info

Specifies the XcmsPerScrnInfo structure, which contains the per screen information.

The screen initialization callback in the XcmsFunctionSet structure fetches the color characterization data (device profile) for the specified screen, typically off properties on the screen's root window. It then initializes the specified XcmsPerScrnInfo structure. If successful, the procedure fills in the XcmsPerScrnInfo structure as follows:

  • It sets the screenData member to the address of the created device profile data structure (contents known only by the function set).

  • It next sets the screenWhitePoint member.

  • It next sets the functionSet member to the address of the XcmsFunctionSet structure.

  • It then sets the state member to XcmsInitSuccess and finally returns XcmsSuccess.

If unsuccessful, the procedure sets the state member to XcmsInitFailure and returns XcmsFailure.

The XcmsPerScrnInfo structure contains:



typedef struct _XcmsPerScrnInfo {
	XcmsColor screenWhitePoint;
	XPointer functionSet;
	XPointer screenData;
	unsigned char state;
	char pad[3];
} XcmsPerScrnInfo;

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:

  • XcmsInitNone indicates initialization has not been previously attempted.

  • XcmsInitFailure indicates initialization has been previously attempted but failed.

  • XcmsInitSuccess indicates initialization has been previously attempted and succeeded.

The screen free callback must adhere to the following software interface specification:

typedef void (*XcmsScreenFreeProc)(XPointer screenData);

screenData

Specifies the data to be freed.

This function is called to free the screenData stored in an XcmsPerScrnInfo structure.

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.

Graphics operations can be performed to either windows or pixmaps, which collectively are called drawables. Each drawable exists on a single screen. A GC is created for a specific screen and drawable depth and can only be used with drawables of matching screen and depth.

This chapter discusses how to:

  • Manipulate graphics context/state

  • Use graphics context convenience functions

Manipulating Graphics Context/State

Most attributes of graphics operations are stored in GCs. These include line width, line style, plane mask, foreground, background, tile, stipple, clipping region, end style, join style, and so on. Graphics operations (for example, drawing lines) use these values to determine the actual drawing operation. Extensions to X may add additional components to GCs. The contents of a GC are private to Xlib.

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:

/* GC attribute value mask bits */

#define     GCFunction              (1L<<0)
#define     GCPlaneMask             (1L<<1)
#define     GCForeground            (1L<<2)
#define     GCBackground            (1L<<3)
#define     GCLineWidth             (1L<<4)
#define     GCLineStyle             (1L<<5)
#define     GCCapStyle              (1L<<6)
#define     GCJoinStyle             (1L<<7)
#define     GCFillStyle             (1L<<8)
#define     GCFillRule              (1L<<9)
#define     GCTile                  (1L<<10)
#define     GCStipple               (1L<<11)
#define     GCTileStipXOrigin       (1L<<12)
#define     GCTileStipYOrigin       (1L<<13)
#define     GCFont                  (1L<<14)
#define     GCSubwindowMode         (1L<<15)
#define     GCGraphicsExposures     (1L<<16)
#define     GCClipXOrigin           (1L<<17)
#define     GCClipYOrigin           (1L<<18)
#define     GCClipMask              (1L<<19)
#define     GCDashOffset            (1L<<20)
#define     GCDashList              (1L<<21)
#define     GCArcMode               (1L<<22)


/* 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 FillOpaqueStippled*/
     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;

The default GC values are:

ComponentDefault
functionGXcopy
plane_maskAll ones
foreground0
background1
line_width0
line_styleLineSolid
cap_styleCapButt
join_styleJoinMiter
fill_styleFillSolid
fill_ruleEvenOddRule
arc_modeArcPieSlice
tile

Pixmap of unspecified size filled with foreground pixel

(that is, client specified pixel if any, else 0)

(subsequent changes to foreground do not affect this pixmap)

stipplePixmap of unspecified size filled with ones
ts_x_origin0
ts_y_origin0
font<implementation dependent>
subwindow_modeClipByChildren
graphics_exposuresTrue
clip_x_origin0
clip_y_origin0
clip_maskNone
dash_offset0
dashes4 (that is, the list [4, 4])

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:

Function NameValueOperation
GXclear0x00
GXand0x1src AND dst
GXandReverse0x2src AND NOT dst
GXcopy0x3src
GXandInverted0x4(NOT src) AND dst
GXnoop0x5dst
GXxor0x6src XOR dst
GXor0x7src OR dst
GXnor0x8(NOT src) AND (NOT dst)
GXequiv0x9(NOT src) XOR dst
GXinvert0xaNOT dst
GXorReverse0xbsrc OR (NOT dst)
GXcopyInverted0xcNOT src
GXorInverted0xd(NOT src) OR dst
GXnand0xe(NOT src) OR (NOT dst)
GXset0xf1

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:

((src FUNC dst) AND plane-mask) OR (dst AND (NOT plane-mask))

Range checking is not performed on the values for foreground, background, or plane_mask. They are simply truncated to the appropriate number of bits. The line-width is measured in pixels and either can be greater than or equal to one (wide line) or can be the special value zero (thin line).

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:



[x1-(w*sn/2), y1+(w*cs/2)], [x1+(w*sn/2), y1-(w*cs/2)],
[x2-(w*sn/2), y2+(w*cs/2)], [x2+(w*sn/2), y2-(w*cs/2)]

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 or the boundary is immediately below (y increasing direction) and the interior or the boundary is immediately to the right (x increasing direction).

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.

The line-style defines which sections of a line are drawn:

LineSolid

The full path of the line is drawn.

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.

The cap-style defines how the endpoints of a path are drawn:

CapNotLast

This is equivalent to CapButt except that for a line-width of zero the final endpoint is not drawn.

CapButt

The line is square at the endpoint (perpendicular to the slope of the line) with no projection beyond.

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).

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:

CapNotLastthinThe results are device dependent, but the desired effect is that nothing is drawn.
CapButtthinThe results are device dependent, but the desired effect is that a single pixel is drawn.
CapRoundthinThe results are the same as for CapButt /thin.
CapProjectingthinThe results are the same as for CapButt /thin.
CapButtwideNothing is drawn.
CapRoundwideThe closed path is a circle, centered at the endpoint, and with the diameter equal to the line-width.
CapProjectingwideThe closed path is a square, aligned with the coordinate axes, centered at the endpoint, and with the sides equal to the line-width.

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 tile/stipple represents an infinite two-dimensional plane, with the tile/stipple replicated in all dimensions. When that plane is superimposed on the drawable for use in a graphics operation, the upper-left corner of some instance of the tile/stipple is at the coordinates within the drawable specified by the tile/stipple origin. The tile/stipple and clip origins are interpreted relative to the origin of whatever destination drawable is specified in a graphics request. The tile pixmap must have the same root and depth as the GC, or a BadMatch error results. The stipple pixmap must have depth one and must have the same root as the GC, or a BadMatch error results. For stipple operations where the fill-style is FillStippled but not FillOpaqueStippled, the stipple pattern is tiled in a single plane and acts as an additional clip mask to be ANDed with the clip-mask. Although some sizes may be faster to use than others, any size pixmap can be used for tiling or stippling.

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:

FillSolidForeground
FillTiledTile
FillOpaqueStippledA 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
FillStippledForeground masked by stipple

When drawing lines with line-style LineDoubleDash, the odd dashes are controlled by the fill-style in the following manner:

FillSolidBackground
FillTiledSame as for even dashes
FillOpaqueStippledSame as for even dashes
FillStippledBackground 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.

You can set the subwindow-mode to ClipByChildren or IncludeInferiors. For ClipByChildren, both source and destination windows are additionally clipped by all viewable InputOutput children. For IncludeInferiors, neither source nor destination window is clipped by inferiors. This will result in including subwindow contents in the source and drawing through subwindow boundaries of the destination. The use of IncludeInferiors on a window of one depth with mapped inferiors of differing depth is not illegal, but the semantics are undefined by the core protocol.

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 origin crosses an unequal number of clockwise and counterclockwise directed path segments. A clockwise directed path segment is one that crosses the ray from left to right as observed from the point. A counterclockwise segment is one that crosses the ray from right to left as observed from the point. The case where a directed line segment is coincident with the ray is uninteresting because you can simply choose a different ray that is not coincident with a segment.

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.

The graphics-exposure flag controls GraphicsExpose event generation for XCopyArea and XCopyPlane requests (and any similar requests defined by extensions).

To create a new GC that is usable on a given screen with a depth of drawable, use XCreateGC.

GC XCreateGC(Display *display, Drawable d, unsignedlong valuemask, XGCValues *values);

display

Specifies the connection to the X server.

d

Specifies the drawable.

valuemask

Specifies which components in the GC are to be (Vm. This argument is the bitwise inclusive OR of zero or more of the valid GC component mask bits.

values

Specifies any values as specified by the valuemask.

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.

XCreateGC can generate BadAlloc, BadDrawable, BadFont, BadMatch, BadPixmap, and BadValue errors.

To copy components from a source GC to a destination GC, use XCopyGC.

XCopyGC(Display *display, GCsrc, dest, unsignedlong valuemask);

display

Specifies the connection to the X server.

src

Specifies the components of the source GC.

valuemask

Specifies which components in the GC are to be (Vm. This argument is the bitwise inclusive OR of zero or more of the valid GC component mask bits.

dest

Specifies the destination GC.

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.

XCopyGC can generate BadAlloc, BadGC, and BadMatch errors.

To change the components in a given GC, use XChangeGC.

XChangeGC(Display *display, GC gc, unsignedlong valuemask, XGCValues *values);

display

Specifies the connection to the X server.

gc

Specifies the GC.

valuemask

Specifies which components in the GC are to be (Vm. This argument is the bitwise inclusive OR of zero or more of the valid GC component mask bits.

values

Specifies any values as specified by the valuemask.

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.

XChangeGC can generate BadAlloc, BadFont, BadGC, BadMatch, BadPixmap, and BadValue errors.

To obtain components of a given GC, use XGetGCValues.

Status XGetGCValues(Display *display, GC gc, unsignedlong valuemask, XGCValues *values_return);

display

Specifies the connection to the X server.

gc

Specifies the GC.

valuemask

Specifies which components in the GC are to be (Vm. This argument is the bitwise inclusive OR of zero or more of the valid GC component mask bits.

values_return

Returns the GC values in the specified XGCValues structure.

The XGetGCValues function returns the components specified by valuemask for the specified GC. If the valuemask contains a valid set of GC mask bits (GCFunction, GCPlaneMask, GCForeground, GCBackground, GCLineWidth, GCLineStyle, GCCapStyle, GCJoinStyle, GCFillStyle, GCFillRule, GCTile, GCStipple, GCTileStipXOrigin, GCTileStipYOrigin, GCFont, GCSubwindowMode, GCGraphicsExposures, GCClipXOrigin, GCClipYOrigin, GCDashOffset, or GCArcMode) and no error occurs, XGetGCValues sets the requested components in values_return and returns a nonzero status. Otherwise, it returns a zero status. Note that the clip-mask and dash-list (represented by the GCClipMask and GCDashList bits, respectively, in the valuemask) cannot be requested. Also note that an invalid resource ID (with one or more of the three most significant bits set to 1) will be returned for GCFont, GCTile, and GCStipple if the component has never been explicitly set by the client.

To free a given GC, use XFreeGC.

XFreeGC(Display *display, GC gc);

display

Specifies the connection to the X server.

gc

Specifies the GC.

The XFreeGC function destroys the specified GC as well as all the associated storage.

XFreeGC can generate a BadGC error.

To obtain the GContext resource ID for a given GC, use XGContextFromGC.

GContext XGContextFromGC(GC gc);

gc

Specifies the GC (Gc.

Xlib usually defers sending changes to the components of a GC to the server until a graphics function is actually called with that GC. This permits batching of component changes into a single server request. In some circumstances, however, it may be necessary for the client to explicitly force sending the changes to the server. An example might be when a protocol extension uses the GC indirectly, in such a way that the extension interface cannot know what GC will be used. To force sending GC component changes, use XFlushGC.

void XFlushGC(Display *display, GC gc);

display

Specifies the connection to the X server.

gc

Specifies the GC.

Using Graphics Context Convenience Routines

This section discusses how to set the:

  • Foreground, background, plane mask, or function components

  • Line attributes and dashes components

  • Fill style and fill rule components

  • Fill tile and stipple components

  • Font component

  • Clip region component

  • Arc mode, subwindow mode, and graphics exposure components

Setting the Foreground, Background, Function, or Plane Mask

To set the foreground, background, plane mask, and function components for a given GC, use XSetState.

XSetState(Display *display, GC gc, unsignedlongforeground, background, int function, unsignedlong plane_mask);

display

Specifies the connection to the X server.

gc

Specifies the GC.

foreground

Specifies the foreground you want to set for the specified GC.

background

Specifies the background you want to set for the specified GC.

function

Specifies the function you want to set for the specified GC.

plane_mask

Specifies the plane mask.

XSetState can generate BadAlloc, BadGC, and BadValue errors.

To set the foreground of a given GC, use XSetForeground.

XSetForeground(Display *display, GC gc, unsignedlong foreground);

display

Specifies the connection to the X server.

gc

Specifies the GC.

foreground

Specifies the foreground you want to set for the specified GC.

XSetForeground can generate BadAlloc and BadGC errors.

To set the background of a given GC, use XSetBackground.

XSetBackground(Display *display, GC gc, unsignedlong background);

display

Specifies the connection to the X server.

gc

Specifies the GC.

background

Specifies the background you want to set for the specified GC.

XSetBackground can generate BadAlloc and BadGC errors.

To set the display function in a given GC, use XSetFunction.

XSetFunction(Display *display, GC gc, int function);

display

Specifies the connection to the X server.

gc

Specifies the GC.

function

Specifies the function you want to set for the specified GC.

XSetFunction can generate BadAlloc, BadGC, and BadValue errors.

To set the plane mask of a given GC, use XSetPlaneMask.

XSetPlaneMask(Display *display, GC gc, unsignedlong plane_mask);

display

Specifies the connection to the X server.

gc

Specifies the GC.

plane_mask

Specifies the plane mask.

XSetPlaneMask can generate BadAlloc and BadGC errors.

Setting the Line Attributes and Dashes

To set the line drawing components of a given GC, use XSetLineAttributes.

XSetLineAttributes(Display *display, GC gc, unsignedint line_width, int line_style, int cap_style, int join_style);

display

Specifies the connection to the X server.

gc

Specifies the GC.

line_width

Specifies the line-width you want to set for the specified GC.

line_style

Specifies the line-style you want to set for the specified GC. You can pass LineSolid, LineOnOffDash, or LineDoubleDash.

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.

XSetLineAttributes can generate BadAlloc, BadGC, and BadValue errors.

To set the dash-offset and dash-list for dashed line styles of a given GC, use XSetDashes.

XSetDashes(Display *display, GC gc, int dash_offset, char dash_list[], int n);

display

Specifies the connection to the X server.

gc

Specifies the GC.

dash_offset

Specifies the phase of the pattern for the dashed line-style you want to set for the specified GC.

dash_list

Specifies the dash-list for the dashed line-style you want to set for the specified GC.

n

Specifies the number of elements in dash_list.

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.

XSetDashes can generate BadAlloc, BadGC, and BadValue errors.

Setting the Fill Style and Fill Rule

To set the fill-style of a given GC, use XSetFillStyle.

XSetFillStyle(Display *display, GC gc, int fill_style);

display

Specifies the connection to the X server.

gc

Specifies the GC.

fill_style

Specifies the fill-style you want to set for the specified GC. You can pass FillSolid, FillTiled, FillStippled, or FillOpaqueStippled.

XSetFillStyle can generate BadAlloc, BadGC, and BadValue errors.

To set the fill-rule of a given GC, use XSetFillRule.

XSetFillRule(Display *display, GC gc, int fill_rule);

display

Specifies the connection to the X server.

gc

Specifies the GC.

fill_rule

Specifies the fill-rule you want to set for the specified GC. You can pass EvenOddRule or WindingRule.

XSetFillRule can generate BadAlloc, BadGC, and BadValue errors.

Setting the Fill Tile and Stipple

Some displays have hardware support for tiling or stippling with patterns of specific sizes. Tiling and stippling operations that restrict themselves to those specific sizes run much faster than such operations with arbitrary size patterns. Xlib provides functions that you can use to determine the best size, tile, or stipple for the display as well as to set the tile or stipple shape and the tile or stipple origin.

To obtain the best size of a tile, stipple, or cursor, use XQueryBestSize.

Status XQueryBestSize(Display *display, int class, Drawable which_screen, unsignedintwidth, height, unsignedint*width_return, *height_return);

display

Specifies the connection to the X server.

class

Specifies the class that you are interested in. You can pass TileShape, CursorShape, or StippleShape.

which_screen

Specifies any drawable on the screen.

width

height

Specify the width and height.

width_return

height_return

Return the width and height of the object best supported by the display hardware.

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.

XQueryBestSize can generate BadDrawable, BadMatch, and BadValue errors.

To obtain the best fill tile shape, use XQueryBestTile.

Status XQueryBestTile(Display *display, Drawable which_screen, unsignedintwidth, height, unsignedint*width_return, *height_return);

display

Specifies the connection to the X server.

which_screen

Specifies any drawable on the screen.

width

height

Specify the width and height.

width_return

height_return

Return the width and height of the object best supported by the display hardware.

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.

XQueryBestTile can generate BadDrawable and BadMatch errors.

To obtain the best stipple shape, use XQueryBestStipple.

Status XQueryBestStipple(Display *display, Drawable which_screen, unsignedintwidth, height, unsignedint*width_return, *height_return);

display

Specifies the connection to the X server.

which_screen

Specifies any drawable on the screen.

width

height

Specify the width and height.

width_return

height_return

Return the width and height of the object best supported by the display hardware.

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.

XQueryBestStipple can generate BadDrawable and BadMatch errors.

To set the fill tile of a given GC, use XSetTile.

XSetTile(Display *display, GC gc, Pixmap tile);

display

Specifies the connection to the X server.

gc

Specifies the GC.

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.

XSetTile can generate BadAlloc, BadGC, BadMatch, and BadPixmap errors.

To set the stipple of a given GC, use XSetStipple.

XSetStipple(Display *display, GC gc, Pixmap stipple);

display

Specifies the connection to the X server.

gc

Specifies the GC.

stipple

Specifies the stipple you want to set for the specified GC.

The stipple must have a depth of one, or a BadMatch error results.

XSetStipple can generate BadAlloc, BadGC, BadMatch, and BadPixmap errors.

To set the tile or stipple origin of a given GC, use XSetTSOrigin.

XSetTSOrigin(Display *display, GC gc, intts_x_origin, ts_y_origin);

display

Specifies the connection to the X server.

gc

Specifies the GC.

ts_x_origin

ts_y_origin

Specify the x and y coordinates of the tile and stipple 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.

XSetTSOrigin can generate BadAlloc and BadGC errors.

Setting the Current Font

To set the current font of a given GC, use XSetFont.

XSetFont(Display *display, GC gc, Font font);

display

Specifies the connection to the X server.

gc

Specifies the GC.

font

Specifies the font.

XSetFont can generate BadAlloc, BadFont, and BadGC errors.

Setting the Clip Region

Xlib provides functions that you can use to set the clip-origin and the clip-mask or set the clip-mask to a list of rectangles.

To set the clip-origin of a given GC, use XSetClipOrigin.

XSetClipOrigin(Display *display, GC gc, intclip_x_origin, clip_y_origin);

display

Specifies the connection to the X server.

gc

Specifies the GC.

clip_x_origin

clip_y_origin

Specify the x and y coordinates of the clip-mask origin.

The clip-mask origin is interpreted relative to the origin of whatever destination drawable is specified in the graphics request.

XSetClipOrigin can generate BadAlloc and BadGC errors.

To set the clip-mask of a given GC to the specified pixmap, use XSetClipMask.

XSetClipMask(Display *display, GC gc, Pixmap pixmap);

display

Specifies the connection to the X server.

gc

Specifies the GC.

pixmap

Specifies the pixmap or None.

If the clip-mask is set to None, the pixels are always drawn (regardless of the clip-origin).

XSetClipMask can generate BadAlloc, BadGC, BadMatch, and BadPixmap errors.

To set the clip-mask of a given GC to the specified list of rectangles, use XSetClipRectangles.

XSetClipRectangles(Display *display, GC gc, intclip_x_origin, clip_y_origin, XRectangle rectangles[], int n, int ordering);

display

Specifies the connection to the X server.

gc

Specifies the GC.

clip_x_origin

clip_y_origin

Specify the x and y coordinates of the clip-mask origin.

rectangles

Specifies an array of rectangles that define the clip-mask.

n

Specifies the number of rectangles.

ordering

Specifies the ordering relations on the rectangles. You can pass Unsorted, YSorted, YXSorted, or YXBanded.

The XSetClipRectangles function changes the clip-mask in the specified GC to the specified list of rectangles and sets the clip origin. The output is clipped to remain contained within the rectangles. The clip-origin is interpreted relative to the origin of whatever destination drawable is specified in a graphics request. The rectangle coordinates are interpreted relative to the clip-origin. The rectangles should be nonintersecting, or the graphics results will be undefined. Note that the list of rectangles can be empty, which effectively disables output. This is the opposite of passing None as the clip-mask in XCreateGC, XChangeGC, and XSetClipMask.

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.

XSetClipRectangles can generate BadAlloc, BadGC, BadMatch, and BadValue errors.

Xlib provides a set of basic functions for performing region arithmetic. For information about these functions, see section 16.5.

Setting the Arc Mode, Subwindow Mode, and Graphics Exposure

To set the arc mode of a given GC, use XSetArcMode.

XSetArcMode(Display *display, GC gc, int arc_mode);

display

Specifies the connection to the X server.

gc

Specifies the GC.

arc_mode

Specifies the arc mode. You can pass ArcChord or ArcPieSlice.

XSetArcMode can generate BadAlloc, BadGC, and BadValue errors.

To set the subwindow mode of a given GC, use XSetSubwindowMode.

XSetSubwindowMode(Display *display, GC gc, int subwindow_mode);

display

Specifies the connection to the X server.

gc

Specifies the GC.

subwindow_mode

Specifies the subwindow mode. You can pass ClipByChildren or IncludeInferiors.

XSetSubwindowMode can generate BadAlloc, BadGC, and BadValue errors.

To set the graphics-exposures flag of a given GC, use XSetGraphicsExposures.

XSetGraphicsExposures(Display *display, GC gc, Bool graphics_exposures);

display

Specifies the connection to the X server.

gc

Specifies the GC.

graphics_exposures

Specifies a Boolean value that indicates whether you want GraphicsExpose and NoExpose events to be reported when calling XCopyArea and XCopyPlane with this GC.

XSetGraphicsExposures can generate BadAlloc, BadGC, and BadValue errors.

Chapter 8. Graphics Functions

Once you have established a connection to a display, you can use the Xlib graphics functions to:

  • Clear and copy areas

  • Draw points, lines, rectangles, and arcs

  • Fill areas

  • Manipulate fonts

  • Draw text

  • Transfer images between clients and the server

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.

To clear a rectangular area of a given window, use XClearArea.

XClearArea(Display *display, Window w, intx, y, unsignedintwidth, height, Bool exposures);

display

Specifies the connection to the X server.

w

Specifies the window. and specify the upper-left corner of the rectangle

x

y

Specify the x and y coordinates(Xy.

width

height

Specify the width and height(Wh.

exposures

Specifies a Boolean value that indicates if Expose events are to be generated.

The XClearArea function paints a rectangular area in the specified window according to the specified dimensions with the window's background pixel or pixmap. The subwindow-mode effectively is ClipByChildren. If width is zero, it is replaced with the current width of the window minus x. If height is zero, it is 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.

XClearArea can generate BadMatch, BadValue, and BadWindow errors.

To clear the entire area in a given window, use XClearWindow.

XClearWindow(Display *display, Window w);

display

Specifies the connection to the X server.

w

Specifies the window.

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.

XClearWindow can generate BadMatch and BadWindow errors.

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.

XCopyArea(Display *display, Drawablesrc, dest, GC gc, intsrc_x, src_y, unsignedintwidth, height, intdest_x, dest_y);

display

Specifies the connection to the X server.

src

dest

Specify the source and destination rectangles to be combined.

gc

Specifies the GC.

src_x

src_y

Specify the x and y coordinates, which are relative to the origin of the source rectangle and specify its upper-left corner. and destination rectangles

width

height

Specify the width and height(Wh. and specify its upper-left corner

dest_x

dest_y

Specify the x and y coordinates(Dx.

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.

This function uses these GC components: function, plane-mask, subwindow-mode, graphics-exposures, clip-x-origin, clip-y-origin, and clip-mask.

XCopyArea can generate BadDrawable, BadGC, and BadMatch errors.

To copy a single bit plane of a given drawable, use XCopyPlane.

XCopyPlane(Display *display, Drawablesrc, dest, GC gc, intsrc_x, src_y, unsignedintwidth, height, intdest_x, dest_y, unsignedlong plane);

display

Specifies the connection to the X server.

src

dest

Specify the source and destination rectangles to be combined.

gc

Specifies the GC.

src_x

src_y

Specify the x and y coordinates, which are relative to the origin of the source rectangle and specify its upper-left corner.

width

height

Specify the width and height(Wh. and specify its upper-left corner

dest_x

dest_y

Specify the x and y coordinates(Dx.

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.

This function uses these GC components: function, plane-mask, foreground, background, subwindow-mode, graphics-exposures, clip-x-origin, clip-y-origin, and clip-mask.

XCopyPlane can generate BadDrawable, BadGC, BadMatch, and BadValue errors.

Drawing Points, Lines, Rectangles, and Arcs

Xlib provides functions that you can use to draw:

  • A single point or multiple points

  • A single line or multiple lines

  • A single rectangle or multiple rectangles

  • A single arc or multiple arcs

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;



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.

Drawing Single and Multiple Points

To draw a single point in a given drawable, use XDrawPoint.

XDrawPoint(Display *display, Drawable d, GC gc, intx, y);

display

Specifies the connection to the X server.

d

Specifies the drawable.

gc

Specifies the GC.

x

y

Specify the x and y coordinates where you want the point drawn.

To draw multiple points in a given drawable, use XDrawPoints.

XDrawPoints(Display *display, Drawable d, GC gc, XPoint *points, int npoints, int mode);

display

Specifies the connection to the X server.

d

Specifies the drawable.

gc

Specifies the GC.

points

Specifies an array of points.

npoints

Specifies the number of points in the array.

mode

Specifies the coordinate mode. You can pass CoordModeOrigin or CoordModePrevious.

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.

Both functions use these GC components: function, plane-mask, foreground, subwindow-mode, clip-x-origin, clip-y-origin, and clip-mask.

XDrawPoint can generate BadDrawable, BadGC, and BadMatch errors. XDrawPoints can generate BadDrawable, BadGC, BadMatch, and BadValue errors.

Drawing Single and Multiple Lines

To draw a single line between two points in a given drawable, use XDrawLine.

XDrawLine(Display *display, Drawable d, GC gc, intx1,y1,x2, y2);

display

Specifies the connection to the X server.

d

Specifies the drawable.

gc

Specifies the GC.

x1

y1

x2

y2

Specify the points (x1, y1) and (x2, y2) to be connected.

To draw multiple lines in a given drawable, use XDrawLines.

XDrawLines(Display *display, Drawable d, GC gc, XPoint *points, int npoints, int mode);

display

Specifies the connection to the X server.

d

Specifies the drawable.

gc

Specifies the GC.

points

Specifies an array of points.

npoints

Specifies the number of points in the array.

mode

Specifies the coordinate mode. You can pass CoordModeOrigin or CoordModePrevious.

To draw multiple, unconnected lines in a given drawable, use XDrawSegments.

XDrawSegments(Display *display, Drawable d, GC gc, XSegment *segments, int nsegments);

display

Specifies the connection to the X server.

d

Specifies the drawable.

gc

Specifies the GC.

segments

Specifies an array of segments.

nsegments

Specifies the number of segments in the array.

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.

All three functions use these GC components: function, plane-mask, line-width, line-style, cap-style, fill-style, subwindow-mode, clip-x-origin, clip-y-origin, and clip-mask. The XDrawLines function also uses the join-style GC component. All three functions also use these GC mode-dependent components: foreground, background, tile, stipple, tile-stipple-x-origin, tile-stipple-y-origin, dash-offset, and dash-list.

XDrawLine, XDrawLines, and XDrawSegments can generate BadDrawable, BadGC, and BadMatch errors. XDrawLines also can generate BadValue errors.

Drawing Single and Multiple Rectangles

To draw the outline of a single rectangle in a given drawable, use XDrawRectangle.

XDrawRectangle(Display *display, Drawable d, GC gc, intx, y, unsignedintwidth, height);

display

Specifies the connection to the X server.

d

Specifies the drawable.

gc

Specifies the GC.

x

y

Specify the x and y coordinates(Xy.

width

height

Specify the width and height(Wh.

To draw the outline of multiple rectangles in a given drawable, use XDrawRectangles.

XDrawRectangles(Display *display, Drawable d, GC gc, XRectangle rectangles[], int nrectangles);

display

Specifies the connection to the X server.

d

Specifies the drawable.

gc

Specifies the GC.

rectangles

Specifies an array of rectangles.

nrectangles

Specifies the number of rectangles in the array.

The XDrawRectangle and XDrawRectangles functions draw the outlines of the specified rectangle or rectangles as if a five-point PolyLine protocol request were specified for each rectangle:

  • [x,y] [x+width,y] [x+width,y+height] [x,y+height] [x,y]

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.

Both functions use these GC components: function, plane-mask, line-width, line-style, cap-style, join-style, fill-style, subwindow-mode, clip-x-origin, clip-y-origin, and clip-mask. They also use these GC mode-dependent components: foreground, background, tile, stipple, tile-stipple-x-origin, tile-stipple-y-origin, dash-offset, and dash-list.

XDrawRectangle and XDrawRectangles can generate BadDrawable, BadGC, and BadMatch errors.

Drawing Single and Multiple Arcs

To draw a single arc in a given drawable, use XDrawArc.

XDrawArc(Display *display, Drawable d, GC gc, intx, y, unsignedintwidth, height, intangle1, angle2);

display

Specifies the connection to the X server.

d

Specifies the drawable.

gc

Specifies the GC. and specify the upper-left corner of the bounding rectangle

x

y

Specify the x and y coordinates(Xy.

width

height

Specify the width and height(Wh.

angle1

Specifies the start of the arc relative to the three-o'clock position from the center, in units of degrees * 64.

angle2

Specifies the path and extent of the arc relative to the start of the arc, in units of degrees * 64.

To draw multiple arcs in a given drawable, use XDrawArcs.

XDrawArcs(Display *display, Drawable d, GC gc, XArc *arcs, int narcs);

display

Specifies the connection to the X server.

d

Specifies the drawable.

gc

Specifies the GC.

arcs

Specifies an array of arcs.

narcs

Specifies the number of arcs in the array.

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:

% roman "skewed-angle" ~ = ~ atan left ( tan ( roman "normal-angle" )
 * width over height right ) +^ adjust%

The skewed-angle and normal-angle are expressed in radians (rather than in degrees scaled by 64) in the range % [ 0 , ~2 pi ]% and where atan returns a value in the range % [ - pi over 2 , ~pi over 2 ] % and adjust is:



%0%     for normal-angle in the range % [ 0 , ~pi over 2  ]%
%pi%     for normal-angle in the range % [ pi over 2 , ~{3 pi} over 2  ]%
%2 pi%     for normal-angle in the range % [ {3 pi} over 2 , ~2 pi  ]%

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.

Both functions use these GC components: function, plane-mask, line-width, line-style, cap-style, join-style, fill-style, subwindow-mode, clip-x-origin, clip-y-origin, and clip-mask. They also use these GC mode-dependent components: foreground, background, tile, stipple, tile-stipple-x-origin, tile-stipple-y-origin, dash-offset, and dash-list.

XDrawArc and XDrawArcs can generate BadDrawable, BadGC, and BadMatch errors.

Filling Areas

Xlib provides functions that you can use to fill:

  • A single rectangle or multiple rectangles

  • A single polygon

  • A single arc or multiple arcs

Filling Single and Multiple Rectangles

To fill a single rectangular area in a given drawable, use XFillRectangle.

XFillRectangle(Display *display, Drawable d, GC gc, intx, y, unsignedintwidth, height);

display

Specifies the connection to the X server.

d

Specifies the drawable.

gc

Specifies the GC. and specify the upper-left corner of the rectangle

x

y

Specify the x and y coordinates(Xy.

width

height

Specify the width and height(Wh.

To fill multiple rectangular areas in a given drawable, use XFillRectangles.

XFillRectangles(Display *display, Drawable d, GC gc, XRectangle *rectangles, int nrectangles);

display

Specifies the connection to the X server.

d

Specifies the drawable.

gc

Specifies the GC.

rectangles

Specifies an array of rectangles.

nrectangles

Specifies the number of rectangles in the array.

The XFillRectangle and XFillRectangles functions fill the specified rectangle or rectangles as if a four-point FillPolygon protocol request were specified for each rectangle:

[x,y] [x+width,y] [x+width,y+height] [x,y+height]

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.

Both functions use these GC components: function, plane-mask, fill-style, subwindow-mode, clip-x-origin, clip-y-origin, and clip-mask. They also use these GC mode-dependent components: foreground, background, tile, stipple, tile-stipple-x-origin, and tile-stipple-y-origin.

XFillRectangle and XFillRectangles can generate BadDrawable, BadGC, and BadMatch errors.

Filling a Single Polygon

To fill a polygon area in a given drawable, use XFillPolygon.

XFillPolygon(Display *display, Drawable d, GC gc, XPoint *points, int npoints, int shape, int mode);

display

Specifies the connection to the X server.

d

Specifies the drawable.

gc

Specifies the GC.

points

Specifies an array of points.

npoints

Specifies the number of points in the array.

shape

Specifies a shape that helps the server to improve performance. You can pass Complex, Convex, or Nonconvex.

mode

Specifies the coordinate mode. You can pass CoordModeOrigin or CoordModePrevious.

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.

Depending on the specified shape, the following occurs:

  • 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.

The fill-rule of the GC controls the filling behavior of self-intersecting polygons.

This function uses these GC components: function, plane-mask, fill-style, fill-rule, subwindow-mode, clip-x-origin, clip-y-origin, and clip-mask. It also uses these GC mode-dependent components: foreground, background, tile, stipple, tile-stipple-x-origin, and tile-stipple-y-origin.

XFillPolygon can generate BadDrawable, BadGC, BadMatch, and BadValue errors.

Filling Single and Multiple Arcs

To fill a single arc in a given drawable, use XFillArc.

XFillArc(Display *display, Drawable d, GC gc, intx, y, unsignedintwidth, height, intangle1, angle2);

display

Specifies the connection to the X server.

d

Specifies the drawable.

gc

Specifies the GC. and specify the upper-left corner of the bounding rectangle

x

y

Specify the x and y coordinates(Xy.

width

height

Specify the width and height(Wh.

angle1

Specifies the start of the arc relative to the three-o'clock position from the center, in units of degrees * 64.

angle2

Specifies the path and extent of the arc relative to the start of the arc, in units of degrees * 64.

To fill multiple arcs in a given drawable, use XFillArcs.

XFillArcs(Display *display, Drawable d, GC gc, XArc *arcs, int narcs);

display

Specifies the connection to the X server.

d

Specifies the drawable.

gc

Specifies the GC.

arcs

Specifies an array of arcs.

narcs

Specifies the number of arcs in the array.

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.

Both functions use these GC components: function, plane-mask, fill-style, arc-mode, subwindow-mode, clip-x-origin, clip-y-origin, and clip-mask. They also use these GC mode-dependent components: foreground, background, tile, stipple, tile-stipple-x-origin, and tile-stipple-y-origin.

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.

This section discusses how to:

  • Load and free fonts

  • Obtain and free font names

  • Compute character string sizes

  • Compute logical extents

  • Query character string sizes

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;



typedef struct {     /* normal 16 bit characters are two bytes */
    unsigned char byte1;
    unsigned char byte2;
} XChar2b;



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 spacing */
} XFontStruct;

X supports single byte/character, two bytes/character matrix, and 16-bit character text operations. Note that any of these forms can be used with a font, but a single byte/character text request can only specify a single byte (that is, the first row of a 2-byte font). You should view 2-byte fonts as a two-dimensional matrix of defined characters: byte1 specifies the range of defined rows and byte2 defines the range of defined columns of the font. Single byte/character fonts have one row defined, and the byte2 range specified in the structure defines a range of characters.

The bounding box of a character is defined by the XCharStruct of that character. When characters are absent from a font, the default_char is used. When fonts have all characters of the same size, only the information in the XFontStruct min and max bounds are used.

The members of the XFontStruct have the following semantics:

  • The direction member can be either FontLeftToRight or FontRightToLeft. It is just a hint as to whether most XCharStruct elements have a positive (FontLeftToRight) or a negative (FontRightToLeft) character width metric. The core protocol defines no support for vertical text.

  • If the min_byte1 and max_byte1 members are both zero, min_char_or_byte2 specifies the linear character index corresponding to the first element of the per_char array, and max_char_or_byte2 specifies the linear character index of the last element.

  • If either min_byte1 or max_byte1 are nonzero, both min_char_or_byte2 and max_char_or_byte2 are less than 256, and the 2-byte character index values corresponding to the per_char array element N (counting from 0) are:

  • byte1 = N/D + min_byte1 byte2 = N\\D + min_char_or_byte2

  • where:

  • D = max_char_or_byte2 - min_char_or_byte2 + 1 / = integer division \\ = integer modulus

  • 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.

  • If all_chars_exist is True, all characters in the per_char array have nonzero bounding boxes.

  • 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]
    

  • Its width is:

         max_bounds.rbearing - min_bounds.lbearing
    

  • Its height is:

         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.

  • If the baseline is at Y-coordinate y, the logical extent of the font is inclusive between the Y-coordinate values (y - font.ascent) and (y + font.descent - 1). Typically, the minimum interline spacing between rows of text is given by ascent + descent.

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]

Its width is:

rbearing - lbearing

Its height is:

ascent + descent

The origin for the next character is defined to be:

[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.

Loading and Freeing Fonts

Xlib provides functions that you can use to load fonts, get font information, unload fonts, and free font information. A few font functions use a GContext resource ID or a font ID interchangeably.

To load a given font, use XLoadFont.

Font XLoadFont(Display *display, char *name);

display

Specifies the connection to the X server.

name

Specifies the name of the font, which is a null-terminated string.

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 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.

XLoadFont can generate BadAlloc and BadName errors.

To return information about an available font, use XQueryFont.

XFontStruct *XQueryFont(Display *display, XID font_ID);

display

Specifies the connection to the X server.

font_ID

Specifies the font ID or the GContext ID.

The XQueryFont function returns a pointer to the XFontStruct structure, which contains information associated with the font. You can query a font or the font stored in a GC. The font ID stored in the XFontStruct structure will be the GContext ID, and you need to be careful when using this ID in other functions (see XGContextFromGC). If the font does not exist, XQueryFont returns NULL. To free this data, use XFreeFontInfo.

To perform a XLoadFont and XQueryFont in a single operation, use XLoadQueryFont.

XFontStruct *XLoadQueryFont(Display *display, char *name);

display

Specifies the connection to the X server.

name

Specifies the name of the font, which is a null-terminated string.

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.

XLoadQueryFont can generate a BadAlloc error.

To unload the font and free the storage used by the font structure that was allocated by XQueryFont or XLoadQueryFont, use XFreeFont.

XFreeFont(Display *display, XFontStruct *font_struct);

display

Specifies the connection to the X server.

font_struct

Specifies the storage associated with the font.

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.

XFreeFont can generate a BadFont error.

To return a given font property, use XGetFontProperty.

Bool XGetFontProperty(XFontStruct *font_struct, Atom atom, unsignedlong *value_return);

font_struct

Specifies the storage associated with the font.

atom

Specifies the atom for the property name you want returned.

value_return

Returns the value of the font property.

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.

To unload a font that was loaded by XLoadFont, use XUnloadFont.

XUnloadFont(Display *display, Font font);

display

Specifies the connection to the X server.

font

Specifies the 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.

XUnloadFont can generate a BadFont error.

Obtaining and Freeing Font Names and Information

You obtain font names and information by matching a wildcard specification when querying a font type for a list of available sizes and so on.

To return a list of the available font names, use XListFonts.

char **XListFonts(Display *display, char *pattern, int maxnames, int *actual_count_return);

display

Specifies the connection to the X server.

pattern

Specifies the null-terminated pattern string that can contain wildcard characters.

maxnames

Specifies the maximum number of names to be returned.

actual_count_return

Returns the actual number of font names.

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 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.

To free a font name array, use XFreeFontNames.

XFreeFontNames(char *list[]);

list

Specifies the array of strings you want to free.

The XFreeFontNames function frees the array and strings returned by XListFonts or XListFontsWithInfo.

To obtain the names and information about available fonts, use XListFontsWithInfo.

char **XListFontsWithInfo(Display *display, char *pattern, int maxnames, int *count_return, XFontStruct **info_return);

display

Specifies the connection to the X server.

pattern

Specifies the null-terminated pattern string that can contain wildcard characters.

maxnames

Specifies the maximum number of names to be returned.

count_return

Returns the actual number of matched font names.

info_return

Returns the font information.

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.

To free font structures and font names, use XFreeFontInfo.

XFreeFontInfo(char **names, XFontStruct *free_info, int actual_count);

names

Specifies the list of font names.

free_info

Specifies the font information.

actual_count

Specifies the actual number of font names.

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.

Computing Character String Sizes

Xlib provides functions that you can use to compute the width, the logical extents, and the server information about 8-bit and 2-byte text strings. The width is computed by adding the character widths of all the characters. It does not matter if the font is an 8-bit or 2-byte font. These functions return the sum of the character metrics in pixels.

To determine the width of an 8-bit character string, use XTextWidth.

int XTextWidth(XFontStruct *font_struct, char *string, int count);

font_struct

Specifies the font used for the width computation.

string

Specifies the character string.

count

Specifies the character count in the specified string.

To determine the width of a 2-byte character string, use XTextWidth16.

int XTextWidth16(XFontStruct *font_struct, XChar2b *string, int count);

font_struct

Specifies the font used for the width computation.

string

Specifies the character string.

count

Specifies the character count in the specified string.

Computing Logical Extents

To compute the bounding box of an 8-bit character string in a given font, use XTextExtents.

XTextExtents(XFontStruct *font_struct, char *string, int nchars, int *direction_return, int*font_ascent_return, *font_descent_return, XCharStruct *overall_return);

font_struct

Specifies the XFontStruct structure.

string

Specifies the character string.

nchars

Specifies the number of characters in the character string.

direction_return

Returns the value of the direction hint (FontLeftToRight or FontRightToLeft).

font_ascent_return

Returns the font ascent.

font_descent_return

Returns the font descent.

overall_return

Returns the overall size in the specified XCharStruct structure.

To compute the bounding box of a 2-byte character string in a given font, use XTextExtents16.

XTextExtents16(XFontStruct *font_struct, XChar2b *string, int nchars, int *direction_return, int*font_ascent_return, *font_descent_return, XCharStruct *overall_return);

font_struct

Specifies the XFontStruct structure.

string

Specifies the character string.

nchars

Specifies the number of characters in the character string.

direction_return

Returns the value of the direction hint (FontLeftToRight or FontRightToLeft).

font_ascent_return

Returns the font ascent.

font_descent_return

Returns the font descent.

overall_return

Returns the overall size in the specified XCharStruct structure.

The XTextExtents and XTextExtents16 functions perform the size computation locally and, thereby, avoid the round-trip overhead of XQueryTextExtents and XQueryTextExtents16. Both functions return an XCharStruct structure, whose members are set to the values as follows.

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.

Querying Character String Sizes

To query the server for the bounding box of an 8-bit character string in a given font, use XQueryTextExtents.

XQueryTextExtents(Display *display, XID font_ID, char *string, int nchars, int *direction_return, int*font_ascent_return, *font_descent_return, XCharStruct *overall_return);

display

Specifies the connection to the X server.

font_ID

Specifies either the font ID or the GContext ID that contains the font.

string

Specifies the character string.

nchars

Specifies the number of characters in the character string.

direction_return

Returns the value of the direction hint (FontLeftToRight or FontRightToLeft).

font_ascent_return

Returns the font ascent.

font_descent_return

Returns the font descent.

overall_return

Returns the overall size in the specified XCharStruct structure.

To query the server for the bounding box of a 2-byte character string in a given font, use XQueryTextExtents16.

XQueryTextExtents16(Display *display, XID font_ID, XChar2b *string, int nchars, int *direction_return, int*font_ascent_return, *font_descent_return, XCharStruct *overall_return);

display

Specifies the connection to the X server.

font_ID

Specifies either the font ID or the GContext ID that contains the font.

string

Specifies the character string.

nchars

Specifies the number of characters in the character string.

direction_return

Returns the value of the direction hint (FontLeftToRight or FontRightToLeft).

font_ascent_return

Returns the font ascent.

font_descent_return

Returns the font descent.

overall_return

Returns the overall size in the specified XCharStruct structure.

The XQueryTextExtents and XQueryTextExtents16 functions return the bounding box of the specified 8-bit and 16-bit character string in the specified font or the font contained in the specified GC. These functions query the X server and, therefore, suffer the round-trip overhead that is avoided by XTextExtents and XTextExtents16. Both functions return a XCharStruct structure, whose members are set to the values as follows.

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.

Characters with all zero metrics are ignored. If the font has no defined default_char, the undefined characters in the string are also ignored.

XQueryTextExtents and XQueryTextExtents16 can generate BadFont and BadGC errors.

Drawing Text

This section discusses how to draw:

  • Complex text

  • Text characters

  • Image 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.

For example, consider the background rectangle drawn by XDrawImageString. If you want the upper-left corner of the background rectangle to be at pixel coordinate (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.

Drawing Complex Text

To draw 8-bit characters in a given drawable, use XDrawText.

XDrawText(Display *display, Drawable d, GC gc, intx, y, XTextItem *items, int nitems);

display

Specifies the connection to the X server.

d

Specifies the drawable.

gc

Specifies the GC. and define the origin of the first character

x

y

Specify the x and y coordinates(Xy.

items

Specifies an array of text items.

nitems

Specifies the number of text items in the array.

To draw 2-byte characters in a given drawable, use XDrawText16.

XDrawText16(Display *display, Drawable d, GC gc, intx, y, XTextItem16 *items, int nitems);

display

Specifies the connection to the X server.

d

Specifies the drawable.

gc

Specifies the GC. and define the origin of the first character

x

y

Specify the x and y coordinates(Xy.

items

Specifies an array of text items.

nitems

Specifies the number of text items in the array.

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 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.

Both functions use these GC components: function, plane-mask, fill-style, font, subwindow-mode, clip-x-origin, clip-y-origin, and clip-mask. They also use these GC mode-dependent components: foreground, background, tile, stipple, tile-stipple-x-origin, and tile-stipple-y-origin.

XDrawText and XDrawText16 can generate BadDrawable, BadFont, BadGC, and BadMatch errors.

Drawing Text Characters

To draw 8-bit characters in a given drawable, use XDrawString.

XDrawString(Display *display, Drawable d, GC gc, int x, int y, char *string, int length);

display

Specifies the connection to the X server.

d

Specifies the drawable.

gc

Specifies the GC. and define the origin of the first character

x

y

Specify the x and y coordinates(Xy.

string

Specifies the character string.

length

Specifies the number of characters in the string argument.

To draw 2-byte characters in a given drawable, use XDrawString16.

XDrawString16(Display *display, Drawable d, GC gc, intx, y, XChar2b *string, int length);

display

Specifies the connection to the X server.

d

Specifies the drawable.

gc

Specifies the GC. and define the origin of the first character

x

y

Specify the x and y coordinates(Xy.

string

Specifies the character string.

length

Specifies the number of characters in the string argument.

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.

Both functions use these GC components: function, plane-mask, fill-style, font, subwindow-mode, clip-x-origin, clip-y-origin, and clip-mask. They also use these GC mode-dependent components: foreground, background, tile, stipple, tile-stipple-x-origin, and tile-stipple-y-origin.

XDrawString and XDrawString16 can generate BadDrawable, BadGC, and BadMatch errors.

Drawing Image Text Characters

Some applications, in particular terminal emulators, need to print image text in which both the foreground and background bits of each character are painted. This prevents annoying flicker on many displays.

To draw 8-bit image text characters in a given drawable, use XDrawImageString.

XDrawImageString(Display *display, Drawable d, GC gc, intx, y, char *string, int length);

display

Specifies the connection to the X server.

d

Specifies the drawable.

gc

Specifies the GC. and define the origin of the first character

x

y

Specify the x and y coordinates(Xy.

string

Specifies the character string.

length

Specifies the number of characters in the string argument.

To draw 2-byte image text characters in a given drawable, use XDrawImageString16.

XDrawImageString16(Display *display, Drawable d, GC gc, intx, y, XChar2b *string, int length);

display

Specifies the connection to the X server.

d

Specifies the drawable.

gc

Specifies the GC. and define the origin of the first character

x

y

Specify the x and y coordinates(Xy.

string

Specifies the character string.

length

Specifies the number of characters in the string argument.

The XDrawImageString16 function is similar to XDrawImageString except that it uses 2-byte or 16-bit characters. Both functions also use both the foreground and background pixels of the GC in the destination.

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]

The width is:

overall-width

The height is:

font-ascent + font-descent

The overall-width, font-ascent, and font-descent are as would be returned by XQueryTextExtents using gc and string. The function and fill-style defined in the GC are ignored for these functions. The effective function is GXcopy, and the effective fill-style is FillSolid.

For fonts defined with 2-byte matrix indexing and used with XDrawImageString, each byte is used as a byte2 with a byte1 of zero.

Both functions use these GC components: plane-mask, foreground, background, font, subwindow-mode, clip-x-origin, clip-y-origin, and clip-mask.

XDrawImageString and XDrawImageString16 can generate BadDrawable, BadGC, and BadMatch errors.

Transferring Images between Client and Server

Xlib provides functions that you can use to transfer images between a client and the server. Because the server may require diverse data formats, Xlib provides an image object that fully describes the data in memory and that provides for basic operations on that data. You should reference the data through the image object rather than referencing the data directly. However, some implementations of the Xlib library may efficiently deal with frequently used data formats by replacing functions in the procedure vector with special case functions. Supported operations include destroying the image, getting a pixel, storing a pixel, extracting a subimage of an image, and adding a constant to an image (see section 16.8).

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.



typedef struct _XImage {
     int width, height;         /* size of image */
     int xoffset;               /* number of pixels offset in X direction */
     int format;                /* XYBitmap, XYPixmap, ZPixmap */
     char *data;                /* pointer to image data */
     int byte_order;            /* data byte order, LSBFirst, MSBFirst */
     int bitmap_unit;           /* quant. of scanline 8, 16, 32 */
     int bitmap_bit_order;      /* LSBFirst, MSBFirst */
     int bitmap_pad;            /* 8, 16, 32 either XY or ZPixmap */
     int depth;                 /* depth of image */
     int bytes_per_line;        /* accelerator to next scanline */
     int bits_per_pixel;        /* bits per pixel (ZPixmap) */
     unsigned long red_mask;    /* bits in z arrangement */
     unsigned long green_mask;
     unsigned long blue_mask;
     XPointer obdata;           /* hook for the object routines to hang on */
     struct funcs {             /* image manipulation routines */
          struct _XImage *(*create_image)();
          int             (*destroy_image)();
          unsigned long   (*get_pixel)();
          int             (*put_pixel)();
          struct _XImage  *(*sub_image)();
          int            (*add_pixel)();
     } f;
} XImage;

To initialize the image manipulation routines of an image structure, use XInitImage.

Status XInitImage(XImage *image);

ximage

Specifies the image.

The XInitImage function initializes the internal image manipulation routines of an image structure, based on the values of the various structure members. All fields other than the manipulation routines must already be initialized. If the bytes_per_line member is zero, XInitImage will assume the image data is contiguous in memory and set the bytes_per_line member to an appropriate value based on the other members; otherwise, the value of bytes_per_line is not changed. All of the manipulation routines are initialized to functions that other Xlib image manipulation functions need to operate on the type of image specified by the rest of the structure.

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.

This function returns a nonzero status if initialization of the structure is successful. It returns zero if it detected some error or inconsistency in the structure, in which case the image is not changed.

To combine an image with a rectangle of a drawable on the display, use XPutImage.

XPutImage(Display *display, Drawable d, GC gc, XImage *image, intsrc_x, src_y, intdest_x, dest_y, unsignedintwidth, height);

display

Specifies the connection to the X server.

d

Specifies the drawable.

gc

Specifies the GC.

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. and are the coordinates of the subimage

dest_x

dest_y

Specify the x and y coordinates(Dx.

width

height

Specify the width and height(Wh.

The XPutImage function combines an image with a rectangle of the specified drawable. The section of the image defined by the src_x, src_y, width, and height arguments is drawn on the specified part of the drawable. If XYBitmap format is used, the depth of the image must be one, or a BadMatch error results. The foreground pixel in the GC defines the source for the one bits in the image, and the background pixel defines the source for the zero bits. For XYPixmap and ZPixmap, the depth of the image must match the depth of the drawable, or a BadMatch error results.

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.

This function uses these GC components: function, plane-mask, subwindow-mode, clip-x-origin, clip-y-origin, and clip-mask. It also uses these GC mode-dependent components: foreground and background.

XPutImage can generate BadDrawable, BadGC, BadMatch, and BadValue errors.

To return the contents of a rectangle in a given drawable on the display, use XGetImage. This function specifically supports rudimentary screen dumps.

XImage *XGetImage(Display *display, Drawable d, intx, y, unsignedintwidth, height, unsignedlong plane_mask, int format);

display

Specifies the connection to the X server.

d

Specifies the drawable. and define the upper-left corner of the rectangle

x

y

Specify the x and y coordinates(Xy.

width

height

Specify the width and height(Wh.

plane_mask

Specifies the plane mask.

format

Specifies the format for the image. You can pass XYPixmap or ZPixmap.

The XGetImage function returns a pointer to an XImage structure. This structure provides you with the contents of the specified rectangle of the drawable in the format you specify. If the format argument is XYPixmap, the image contains only the bit planes you passed to the plane_mask argument. If the plane_mask argument only requests a subset of the planes of the display, the depth of the returned image will be the number of planes requested. If the format argument is ZPixmap, XGetImage 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.

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.

XGetImage can generate BadDrawable, BadMatch, and BadValue errors.

To copy the contents of a rectangle on the display to a location within a preexisting image structure, use XGetSubImage.

XImage *XGetSubImage(Display *display, Drawable d, intx, y, unsignedintwidth, height, unsignedlong plane_mask, int format, XImage *dest_image, intdest_x, dest_y);

display

Specifies the connection to the X server.

d

Specifies the drawable. and define the upper-left corner of the rectangle

x

y

Specify the x and y coordinates(Xy.

width

height

Specify the width and height(Wh.

plane_mask

Specifies the plane mask.

format

Specifies the format for the image. You can pass XYPixmap or ZPixmap.

dest_image

Specifies the destination image. specify its upper-left corner, and determine where the subimage \ is placed in the destination image

dest_x

dest_y

Specify the x and y coordinates(Dx.

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.

XGetSubImage can generate BadDrawable, BadGC, BadMatch, and BadValue errors.

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:

  • Change the parent of a window

  • Control the lifetime of a window

  • Manage installed colormaps

  • Set and retrieve the font search path

  • Grab the server

  • Kill a client

  • Control the screen saver

  • Control host access

Changing the Parent of a Window

To change a window's parent to another window on the same screen, use XReparentWindow. There is no way to move a window between screens.

XReparentWindow(Display *display, Window w, Window parent, intx, y);

display

Specifies the connection to the X server.

w

Specifies the window.

parent

Specifies the parent window.

x

y

Specify the x and y coordinates(Xy.

If the specified window is mapped, XReparentWindow automatically performs an UnmapWindow request on it, removes it from its current position in the hierarchy, and inserts it as the child of the specified parent. The window is placed in the stacking order on top with respect to sibling windows.

After reparenting the specified window, XReparentWindow causes the X server to generate a ReparentNotify event. The override_redirect member returned in this event is set to the window's corresponding attribute. Window manager clients usually should ignore this window if this member is set to True. Finally, if the specified window was originally mapped, the X server automatically performs a MapWindow request on it.

The X server performs normal exposure processing on formerly obscured windows. The X server might not generate Expose events for regions from the initial UnmapWindow request that are immediately obscured by the final MapWindow request. A BadMatch error results if:

  • 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 new parent is InputOnly, and the window is not.

  • The specified window has a ParentRelative background, and the new parent window is not the same depth as the specified window.

XReparentWindow can generate BadMatch and BadWindow errors.

Controlling the Lifetime of a Window

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 should be remapped if they are unmapped. For further information about close-connection processing, see section 2.6. To allow an application's window to survive when a window manager that has reparented a window fails, Xlib provides the save-set functions that you can use to control the longevity of subwindows that are normally destroyed when the parent is destroyed. For example, a window manager that wants to add decoration to a window by adding a frame might reparent an application's window. When the frame is destroyed, the application's window should not be destroyed but be returned to its previous place in the window hierarchy.

The X server automatically removes windows from the save-set when they are destroyed.

To add or remove a window from the client's save-set, use XChangeSaveSet.

XChangeSaveSet(Display *display, Window w, int change_mode);

display

Specifies the connection to the X server.

w

Specifies the window (Wi.

change_mode

Specifies the mode. You can pass SetModeInsert or SetModeDelete.

Depending on the specified mode, XChangeSaveSet either inserts or deletes 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.

XChangeSaveSet can generate BadMatch, BadValue, and BadWindow errors.

To add a window to the client's save-set, use XAddToSaveSet.

XAddToSaveSet(Display *display, Window w);

display

Specifies the connection to the X server.

w

Specifies the window (Wi.

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.

XAddToSaveSet can generate BadMatch and BadWindow errors.

To remove a window from the client's save-set, use XRemoveFromSaveSet.

XRemoveFromSaveSet(Display *display, Window w);

display

Specifies the connection to the X server.

w

Specifies the window (Wi.

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.

XRemoveFromSaveSet can generate BadMatch and BadWindow errors.

Managing Installed Colormaps

The X server maintains a list of installed colormaps. Windows using these colormaps are guaranteed to display with correct colors; windows using other colormaps may or may not display with correct colors. Xlib provides functions that you can use to install a colormap, uninstall a colormap, and obtain a list of installed colormaps.

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.

To install a colormap, use XInstallColormap.

XInstallColormap(Display *display, Colormap colormap);

display

Specifies the connection to the X server.

colormap

Specifies the colormap.

The XInstallColormap function installs the specified colormap for its associated screen. All windows associated with this colormap immediately display with true 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.

XInstallColormap can generate a BadColor error.

To uninstall a colormap, use XUninstallColormap.

XUninstallColormap(Display *display, Colormap colormap);

display

Specifies the connection to the X server.

colormap

Specifies the colormap.

The XUninstallColormap function removes the specified colormap from the required list for its screen. As a result, the specified colormap might be uninstalled, and the X server might implicitly install or uninstall additional colormaps. Which colormaps get installed or uninstalled is server dependent except that the required list must remain installed.

If the specified colormap becomes uninstalled, the X server generates a ColormapNotify event on each window that has that colormap. In addition, for every other colormap that is installed or uninstalled as a result of a call to XUninstallColormap, the X server generates a ColormapNotify event on each window that has that colormap.

XUninstallColormap can generate a BadColor error.

To obtain a list of the currently installed colormaps for a given screen, use XListInstalledColormaps.

Colormap *XListInstalledColormaps(Display *display, Window w, int *num_return);

display

Specifies the connection to the X server.

w

Specifies the window (Wi.

num_return

Returns the number of currently installed colormaps.

The XListInstalledColormaps function returns a list of the currently installed colormaps for the screen of the specified window. The order of the colormaps in the list is not significant and is no explicit indication of the required list. When the allocated list is no longer needed, free it by using .

XListInstalledColormaps can generate a BadWindow error.

Setting and Retrieving the Font Search Path

The set of fonts available from a server depends on a font search path. Xlib provides functions to set and retrieve the search path for a server.

To set the font search path, use XSetFontPath.

XSetFontPath(Display *display, char **directories, int ndirs);

display

Specifies the connection to the X server.

directories

Specifies the directory path used to look for a font. Setting the path to the empty list restores the default path defined for the X server.

ndirs

Specifies the number of directories in the path.

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.

XSetFontPath can generate a BadValue error.

To get the current font search path, use XGetFontPath.

char **XGetFontPath(Display *display, int *npaths_return);

display

Specifies the connection to the X server.

npaths_return

Returns the number of strings in the font path array.

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.

To free data returned by XGetFontPath, use XFreeFontPath.

XFreeFontPath(char **list);

list

Specifies the array of strings you want to free.

The XFreeFontPath function frees the data allocated by XGetFontPath.

Grabbing the Server

Xlib provides functions that you can use to grab and ungrab the server. These functions can be used to control processing of output on other connections by the window system server. While the server is grabbed, no processing of requests or close downs on any other connection will occur. A client closing its connection automatically ungrabs the server. Although grabbing the server is highly discouraged, it is sometimes necessary.

To grab the server, use XGrabServer.

XGrabServer(Display *display);

display

Specifies the connection to the X server.

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.

To ungrab the server, use XUngrabServer.

XUngrabServer(Display *display);

display

Specifies the connection to the X server.

The XUngrabServer function restarts processing of requests and close downs on other connections. You should avoid grabbing the X server as much as possible.

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 *display, XID resource);

display

Specifies the connection to the X server.

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.

XKillClient can generate a BadValue error.

Controlling the Screen Saver

Xlib provides functions that you can use to set or reset the mode of the screen saver, to force or activate the screen saver, or to obtain the current screen saver values.

To set the screen saver mode, use XSetScreenSaver.

XSetScreenSaver(Display *display, inttimeout, interval, int prefer_blanking, int allow_exposures);

display

Specifies the connection to the X server.

timeout

Specifies the timeout, in seconds, until the screen saver turns on.

interval

Specifies the interval, in seconds, between screen saver alterations.

prefer_blanking

Specifies how to enable screen blanking. You can pass DontPreferBlanking, PreferBlanking, or DefaultBlanking.

allow_exposures

Specifies the screen save control values. You can pass DontAllowExposures, AllowExposures, or DefaultExposures.

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.

XSetScreenSaver can generate a BadValue error.

To force the screen saver on or off, use XForceScreenSaver.

XForceScreenSaver(Display *display, int mode);

display

Specifies the connection to the X server.

mode

Specifies the mode that is to be applied. You can pass ScreenSaverActive or ScreenSaverReset.

If the specified mode is ScreenSaverActive and the screen saver currently is deactivated, XForceScreenSaver activates the screen saver even if the screen saver had been disabled with a timeout of zero. If the specified mode is ScreenSaverReset and the screen saver currently is enabled, XForceScreenSaver deactivates the screen saver if it was activated, and the activation timer is reset to its initial state (as if device input had been received).

XForceScreenSaver can generate a BadValue error.

To activate the screen saver, use XActivateScreenSaver.

XActivateScreenSaver(Display *display);

display

Specifies the connection to the X server.

To reset the screen saver, use XResetScreenSaver.

XResetScreenSaver(Display *display);

display

Specifies the connection to the X server.

To get the current screen saver values, use XGetScreenSaver.

XGetScreenSaver(Display *display, int*timeout_return, *interval_return, int *prefer_blanking_return, int *allow_exposures_return);

display

Specifies the connection to the X server.

timeout_return

Returns the timeout, in seconds, until the screen saver turns on.

interval_return

Returns the interval between screen saver invocations.

prefer_blanking_return

Returns the current screen blanking preference (DontPreferBlanking, PreferBlanking, or DefaultBlanking).

allow_exposures_return

Returns the current screen save control value (DontAllowExposures, AllowExposures, or DefaultExposures).

Controlling Host Access

This section discusses how to:

  • Add, get, or remove hosts from the access control list

  • Change, enable, or disable access

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:

  • The host the window system is running on.

  • On POSIX-conformant systems, each host listed in the /etc/X?.hosts file. The ? indicates the number of the display. This file should consist of host names separated by newlines. DECnet nodes must terminate in :: to distinguish them from Internet hosts.

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.

Adding, Getting, or Removing Hosts

Xlib provides functions that you can use to add, get, or remove hosts from the access control list. All the host access control functions use the XHostAddress structure, which contains:



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 */
     char *value;        /* pointer to where to find the address */
} XServerInterpretedAddress;

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.

To add a single host, use XAddHost.

XAddHost(Display *display, XHostAddress *host);

display

Specifies the connection to the X server.

host

Specifies the host that is to be (Ho.

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.

XAddHost can generate BadAccess and BadValue errors.

To add multiple hosts at one time, use XAddHosts.

XAddHosts(Display *display, XHostAddress *hosts, int num_hosts);

display

Specifies the connection to the X server.

hosts

Specifies each host that is to be (Ho.

num_hosts

Specifies the number of hosts.

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.

XAddHosts can generate BadAccess and BadValue errors.

To obtain a host list, use XListHosts.

XHostAddress *XListHosts(Display *display, int *nhosts_return, Bool *state_return);

display

Specifies the connection to the X server.

nhosts_return

Returns the number of hosts currently in the access control list.

state_return

Returns the state of the access control.

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 .

To remove a single host, use XRemoveHost.

XRemoveHost(Display *display, XHostAddress *host);

display

Specifies the connection to the X server.

host

Specifies the host that is to be (Ho.

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.

XRemoveHost can generate BadAccess and BadValue errors.

To remove multiple hosts at one time, use XRemoveHosts.

XRemoveHosts(Display *display, XHostAddress *hosts, int num_hosts);

display

Specifies the connection to the X server.

hosts

Specifies each host that is to be (Ho.

num_hosts

Specifies the number of hosts.

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.

XRemoveHosts can generate BadAccess and BadValue errors.

Changing, Enabling, or Disabling Access Control

Xlib provides functions that you can use to enable, disable, or change access control.

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.

To change access control, use XSetAccessControl.

XSetAccessControl(Display *display, int mode);

display

Specifies the connection to the X server.

mode

Specifies the mode. You can pass EnableAccess or DisableAccess.

The XSetAccessControl function either enables or disables the use of the access control list at each connection setup.

XSetAccessControl can generate BadAccess and BadValue errors.

To enable access control, use XEnableAccessControl.

XEnableAccessControl(Display *display);

display

Specifies the connection to the X server.

The XEnableAccessControl function enables the use of the access control list at each connection setup.

XEnableAccessControl can generate a BadAccess error.

To disable access control, use XDisableAccessControl.

XDisableAccessControl(Display *display);

display

Specifies the connection to the X server.

The XDisableAccessControl function disables the use of the access control list at each connection setup.

XDisableAccessControl can generate a BadAccess error.

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.

This chapter discusses the following topics associated with events:

  • 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.

Event CategoryEvent Type
Keyboard eventsKeyPress, KeyRelease
Pointer eventsButtonPress, ButtonRelease, MotionNotify
Window crossing eventsEnterNotify, LeaveNotify
Input focus eventsFocusIn, FocusOut
Keymap state notification eventKeymapNotify
Exposure eventsExpose, GraphicsExpose, NoExpose
Structure control eventsCirculateRequest, ConfigureRequest, MapRequest, ResizeRequest
Window state notification events CirculateNotify, ConfigureNotify, CreateNotify, DestroyNotify, GravityNotify, MapNotify, MappingNotify, ReparentNotify, UnmapNotify, VisibilityNotify
Colormap state notification eventColormapNotify
Client communication eventsClientMessage, PropertyNotify, SelectionClear, SelectionNotify, SelectionRequest

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 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.



typedef union _XEvent {
     int                            type;          /* must not be changed */
     XAnyEvent                      xany;
     XKeyEvent                      xkey;
     XButtonEvent                   xbutton;
     XMotionEvent                   xmotion;
     XCrossingEvent                 xcrossing;
     XFocusChangeEvent              xfocus;
     XExposeEvent                   xexpose;
     XGraphicsExposeEvent           xgraphicsexpose;
     XNoExposeEvent                 xnoexpose;
     XVisibilityEvent               xvisibility;
     XCreateWindowEvent             xcreatewindow;
     XDestroyWindowEvent            xdestroywindow;
     XUnmapEvent                    xunmap;
     XMapEvent                      xmap;
     XMapRequestEvent               xmaprequest;
     XReparentEvent                 xreparent;
     XConfigureEvent                xconfigure;
     XGravityEvent                  xgravity;
     XResizeRequestEvent            xresizerequest;
     XConfigureRequestEvent         xconfigurerequest;
     XCirculateEvent                xcirculate;
     XCirculateRequestEvent         xcirculaterequest;
     XPropertyEvent                 xproperty;
     XSelectionClearEvent           xselectionclear;
     XSelectionRequestEvent         xselectionrequest;
     XSelectionEvent                xselection;
     XColormapEvent                 xcolormap;
     XClientMessageEvent            xclient;
     XMappingEvent                  xmapping;
     XErrorEvent                    xerror;
     XKeymapEvent                   xkeymap;
     long                           pad[24];
} XEvent;

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:

Event MaskCircumstances
NoEventMaskNo events wanted
KeyPressMaskKeyboard down events wanted
KeyReleaseMaskKeyboard up events wanted
ButtonPressMaskPointer button down events wanted
ButtonReleaseMaskPointer button up events wanted
EnterWindowMaskPointer window entry events wanted
LeaveWindowMaskPointer window leave events wanted
PointerMotionMaskPointer motion events wanted
PointerMotionHintMaskPointer motion hints wanted
Button1MotionMaskPointer motion while button 1 down
Button2MotionMaskPointer motion while button 2 down
Button3MotionMaskPointer motion while button 3 down
Button4MotionMaskPointer motion while button 4 down
Button5MotionMaskPointer motion while button 5 down
ButtonMotionMaskPointer motion while any button down
KeymapStateMaskKeyboard state wanted at window entry and focus in
ExposureMaskAny exposure wanted
VisibilityChangeMaskAny change in visibility wanted
StructureNotifyMaskAny change in window structure wanted
ResizeRedirectMaskRedirect resize of this window
SubstructureNotifyMaskSubstructure notification wanted
SubstructureRedirectMaskRedirect structure requests on children
FocusChangeMaskAny change in input focus wanted
PropertyChangeMaskAny change in property wanted
ColormapChangeMaskAny change in colormap wanted
OwnerGrabButtonMaskAutomatic grabs should activate with owner_events set to True

Event Processing Overview

The event reported to a client application during event processing depends on which event masks you provide as the event-mask attribute for a window. For some event masks, there is a one-to-one correspondence between the event mask constant and the event type constant. For example, if you pass the event mask ButtonPressMask, the X server sends back only ButtonPress events. Most events contain a time member, which is the time at which an event occurred.

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.

Event MaskEvent TypeStructureGeneric Structure

ButtonMotionMask

Button1MotionMask

Button2MotionMask

Button3MotionMask

Button4MotionMask

Button5MotionMask

MotionNotifyXPointerMovedEventXMotionEvent
ButtonPressMaskButtonPressXButtonPressedEventXButtonEvent
ButtonReleaseMaskButtonReleaseXButtonReleasedEventXButtonEvent
ColormapChangeMaskColormapNotifyXColormapEvent 
EnterWindowMaskEnterNotifyXEnterWindowEventXCrossingEvent
LeaveWindowMaskLeaveNotifyXLeaveWindowEventXCrossingEvent
ExposureMaskExposeXExposeEvent  
GCGraphicsExposures in GCGraphicsExposeXGraphicsExposeEvent 
NoExposeXNoExposeEvent 
FocusChangeMaskFocusInXFocusInEventXFocusChangeEvent
FocusOutXFocusOutEventXFocusChangeEvent
KeymapStateMaskKeymapNotifyXKeymapEvent 
KeyPressMaskKeyPressXKeyPressedEventXKeyEvent
KeyReleaseMaskKeyReleaseXKeyReleasedEventXKeyEvent
OwnerGrabButtonMaskN.A.N.A. 
PointerMotionMaskMotionNotifyXPointerMovedEventXMotionEvent
PointerMotionHintMaskN.A.N.A. 
PropertyChangeMaskPropertyNotifyXPropertyEvent 
ResizeRedirectMaskResizeRequestXResizeRequestEvent 
StructureNotifyMaskCirculateNotifyXCirculateEvent 
ConfigureNotifyXConfigureEvent 
DestroyNotifyXDestroyWindowEvent 
GravityNotifyXGravityEvent 
MapNotifyXMapEvent 
ReparentNotifyXReparentEvent 
UnmapNotifyXUnmapEvent 
SubstructureNotifyMaskCirculateNotifyXCirculateEvent 
ConfigureNotifyXConfigureEvent 
CreateNotifyXCreateWindowEvent 
DestroyNotifyXDestroyWindowEvent 
GravityNotifyXGravityEvent 
MapNotifyXMapEvent 
ReparentNotifyXReparentEvent 
UnmapNotifyXUnmapEvent 
SubstructureRedirectMaskCirculateRequestXCirculateRequestEvent 
ConfigureRequestXConfigureRequestEvent 
MapRequestXMapRequestEvent 
N.A.ClientMessageXClientMessageEvent 
N.A.MappingNotifyXMappingEvent 
N.A.SelectionClearXSelectionClearEvent 
N.A.SelectionNotifyXSelectionEvent 
N.A.SelectionRequestXSelectionRequestEvent 
VisibilityChangeMaskVisibilityNotifyXVisibilityEvent 

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:

  • Keyboard and pointer events

  • Window crossing events

  • Input focus events

  • Keymap state notification events

  • Exposure events

  • Window state notification events

  • Structure control events

  • Colormap state notification events

  • Client communication events

Keyboard and Pointer Events

This section discusses:

  • Pointer button events

  • Keyboard and pointer events

Pointer Button Events

The following describes the event processing that occurs when a pointer button press is processed with the pointer in some window w and when no active pointer grab is in progress.

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:

ArgumentValue
wThe event window
event_maskThe client's selected pointer events on the event window
pointer_modeGrabModeAsync
keyboard_modeGrabModeAsync
owner_eventsTrue, if the client has selected OwnerGrabButtonMask on the event window, otherwise False
confine_toNone
cursorNone

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.

Keyboard and Pointer Events

This section discusses the processing that occurs for the keyboard events KeyPress and KeyRelease and the pointer events ButtonPress, ButtonRelease, and MotionNotify. For information about the keyboard event-handling utilities, see chapter 11.

The X server reports KeyPress or KeyRelease events to clients wanting information about keys that logically change state. Note that these events are generated for all keys, even those mapped to modifier bits. The X server reports ButtonPress or ButtonRelease events to clients wanting information about buttons that logically change state.

The X server reports MotionNotify events to clients wanting information about when the pointer logically moves. The X server generates this event whenever the pointer is moved and the pointer motion begins and ends in the window. The granularity of MotionNotify events is not guaranteed, but a client that selects this event type is guaranteed to receive at least one event when the pointer moves and then rests.

The generation of the logical changes lags the physical changes if device event processing is frozen.

To receive KeyPress, KeyRelease, ButtonPress, and ButtonRelease events, set KeyPressMask, KeyReleaseMask, ButtonPressMask, and ButtonReleaseMask bits in the event-mask attribute of the window.

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.

  • PointerMotionMask

  • The client application receives MotionNotify events independent of the state of the pointer buttons.

  • PointerMotionHintMask

  • If PointerMotionHintMask is selected in combination with one or more of the above masks, the X server is free to send only one MotionNotify event (with the is_hint member of the XPointerMovedEvent structure set to NotifyHint) to the client for the event window, until either the key or button state changes, the pointer leaves the event window, or the client calls XQueryPointer or . The server still may send MotionNotify events without is_hint set to NotifyHint.

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.

The structures for these event types contain:

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 */
     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   keycode;         /* detail */
     Bool           same_screen;     /* same screen flag */
} XKeyEvent;
typedef XKeyEvent XKeyPressedEvent;
typedef XKeyEvent XKeyReleasedEvent;
typedef struct {
     int            type;              /* MotionNotify */
     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 */
     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.

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).

For the XButtonPressedEvent and XButtonReleasedEvent structures, this member is called button. It represents the pointer button that changed state and can be the Button1, Button2, Button3, Button4, or Button5 value. For the XPointerMovedEvent structure, this member is called is_hint. It can be set to NotifyNormal or NotifyHint.

Some of the symbols mentioned in this section have fixed values, as follows:

SymbolValue
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)
Button11
Button22
Button33
Button44
Button55

Window Entry/Exit Events

This section describes the processing that occurs for the window crossing events EnterNotify and LeaveNotify. If a pointer motion or a window hierarchy change causes the pointer to be in a different window than before, the X server reports EnterNotify or LeaveNotify events to clients who have selected for these events. All EnterNotify and LeaveNotify events caused by a hierarchy change are generated after any hierarchy event (UnmapNotify, MapNotify, ConfigureNotify, GravityNotify, 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.

To receive EnterNotify or LeaveNotify events, set the EnterWindowMask or LeaveWindowMask bits of the event-mask attribute of the window.

The structure for these event types contains:



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 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.

Normal Entry/Exit Events

EnterNotify and LeaveNotify events are generated when the pointer moves from one window to another window. Normal events are identified by XEnterWindowEvent or XLeaveWindowEvent structures whose mode member is set to NotifyNormal.

  • When the pointer moves from window A to window B and A is an inferior of B, the X server does the following:

  • It generates a LeaveNotify event on window A, with the detail member of the XLeaveWindowEvent structure set to NotifyAncestor.

  • It generates a LeaveNotify event on each window between window A and window B, exclusive, with the detail member of each XLeaveWindowEvent structure set to NotifyVirtual.

  • It generates an EnterNotify event on window B, with the detail member of the XEnterWindowEvent structure set to NotifyInferior.

  • When the pointer moves from window A to window B and B is an inferior of A, the X server does the following:

  • It generates a LeaveNotify event on window A, with the detail member of the XLeaveWindowEvent structure set to NotifyInferior.

  • It generates an EnterNotify event on each window between window A and window B, exclusive, with the detail member of each XEnterWindowEvent structure set to NotifyVirtual.

  • It generates an EnterNotify event on window B, with the detail member of the XEnterWindowEvent structure set to NotifyAncestor.

  • When the pointer moves from window A to window B and window C is their least common ancestor, the X server does the following:

  • It generates a LeaveNotify event on window A, with the detail member of the XLeaveWindowEvent structure set to NotifyNonlinear.

  • It generates a LeaveNotify event on each window between window A and window C, exclusive, with the detail member of each XLeaveWindowEvent structure set to NotifyNonlinearVirtual.

  • It generates an EnterNotify event on each window between window C and window B, exclusive, with the detail member of each XEnterWindowEvent structure set to NotifyNonlinearVirtual.

  • It generates an EnterNotify event on window B, with the detail member of the XEnterWindowEvent structure set to NotifyNonlinear.

  • When the pointer moves from window A to window B on different screens, the X server does the following:

  • It generates a LeaveNotify event on window A, with the detail member of the XLeaveWindowEvent structure set to NotifyNonlinear.

  • If window A is not a root window, it generates a LeaveNotify event on each window above window A up to and including its root, with the detail member of each XLeaveWindowEvent structure set to NotifyNonlinearVirtual.

  • If window B is not a root window, it generates an EnterNotify event on each window from window B's root down to but not including window B, with the detail member of each XEnterWindowEvent structure set to NotifyNonlinearVirtual.

  • It generates an EnterNotify event on window B, with the detail member of the XEnterWindowEvent structure set to NotifyNonlinear.

Grab and Ungrab Entry/Exit Events

Pseudo-motion mode EnterNotify and LeaveNotify events are generated when a pointer grab activates or deactivates. Events in which the pointer grab activates are identified by XEnterWindowEvent or XLeaveWindowEvent structures whose mode member is set to NotifyGrab. Events in which the pointer grab deactivates are identified by XEnterWindowEvent or XLeaveWindowEvent structures whose mode member is set to NotifyUngrab (see XGrabPointer).

  • 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:

  • 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.

Input Focus Events

This section describes the processing that occurs for the input focus events FocusIn and FocusOut. The X server can report FocusIn or FocusOut events to clients wanting information about when the input focus changes. The keyboard is always attached to some window (typically, the root window or a top-level window), which is called the focus window. The focus window and the position of the pointer determine the window that receives keyboard input. Clients may need to know when the input focus changes to control highlighting of areas on the screen.

To receive FocusIn or FocusOut events, set the FocusChangeMask bit in the event-mask attribute of the window.

The structure for these event types contains:



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 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.

Normal Focus Events and Focus Events While Grabbed

Normal focus events are identified by XFocusInEvent or XFocusOutEvent structures whose mode member is set to NotifyNormal. Focus events while grabbed are identified by XFocusInEvent or XFocusOutEvent structures whose mode member is set to NotifyWhileGrabbed. The X server processes normal focus and focus events while grabbed according to the following:

  • 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:

  • It generates a FocusOut event on window A, with the detail member of the XFocusOutEvent structure set to NotifyAncestor.

  • It generates a FocusOut event on each window between window A and window B, exclusive, with the detail member of each XFocusOutEvent structure set to NotifyVirtual.

  • It generates a FocusIn event on window B, with the detail member of the XFocusOutEvent structure set to NotifyInferior.

  • If window P is an inferior of window B but window P is not window A or an inferior or ancestor of window A, it generates a FocusIn event on each window below window B, down to and including window P, with the detail member of each XFocusInEvent structure set to NotifyPointer.

  • 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:

  • If window P is an inferior of window A but P is not an inferior of window B or an ancestor of B, it generates a FocusOut event on each window from window P up to but not including window A, with the detail member of each XFocusOutEvent structure set to NotifyPointer.

  • It generates a FocusOut event on window A, with the detail member of the XFocusOutEvent structure set to NotifyInferior.

  • It generates a FocusIn event on each window between window A and window B, exclusive, with the detail member of each XFocusInEvent structure set to NotifyVirtual.

  • It generates a FocusIn event on window B, with the detail member of the XFocusInEvent structure set to NotifyAncestor.

  • 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:

  • If window P is an inferior of window A, it generates a FocusOut event on each window from window P up to but not including window A, with the detail member of the XFocusOutEvent structure set to NotifyPointer.

  • It generates a FocusOut event on window A, with the detail member of the XFocusOutEvent structure set to NotifyNonlinear.

  • It generates a FocusOut event on each window between window A and window C, exclusive, with the detail member of each XFocusOutEvent structure set to NotifyNonlinearVirtual.

  • It generates a FocusIn event on each window between C and B, exclusive, with the detail member of each XFocusInEvent structure set to NotifyNonlinearVirtual.

  • It generates a FocusIn event on window B, with the detail member of the XFocusInEvent structure set to NotifyNonlinear.

  • If window P is an inferior of window B, it generates a FocusIn event on each window below window B down to and including window P, with the detail member of the XFocusInEvent structure set to NotifyPointer.

  • 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:

  • If window P is an inferior of window A, it generates a FocusOut event on each window from window P up to but not including window A, with the detail member of each XFocusOutEvent structure set to NotifyPointer.

  • It generates a FocusOut event on window A, with the detail member of the XFocusOutEvent structure set to NotifyNonlinear.

  • If window A is not a root window, it generates a FocusOut event on each window above window A up to and including its root, with the detail member of each XFocusOutEvent structure set to NotifyNonlinearVirtual.

  • If window B is not a root window, it generates a FocusIn event on each window from window B's root down to but not including window B, with the detail member of each XFocusInEvent structure set to NotifyNonlinearVirtual.

  • It generates a FocusIn event on window B, with the detail member of each XFocusInEvent structure set to NotifyNonlinear.

  • If window P is an inferior of window B, it generates a FocusIn event on each window below window B down to and including window P, with the detail member of each XFocusInEvent structure set to NotifyPointer.

  • 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:

  • If window P is an inferior of window A, it generates a FocusOut event on each window from window P up to but not including window A, with the detail member of each XFocusOutEvent structure set to NotifyPointer.

  • It generates a FocusOut event on window A, with the detail member of the XFocusOutEvent structure set to NotifyNonlinear.

  • If window A is not a root window, it generates a FocusOut event on each window above window A up to and including its root, with the detail member of each XFocusOutEvent structure set to NotifyNonlinearVirtual.

  • 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:

  • If the old focus is PointerRoot, it generates a FocusOut event on each window from window P up to and including window P's root, with the detail member of each XFocusOutEvent structure set to NotifyPointer.

  • It generates a FocusOut event on all root windows, with the detail member of each XFocusOutEvent structure set to NotifyPointerRoot (or NotifyDetailNone).

  • If window A is not a root window, it generates a FocusIn event on each window from window A's root down to but not including window A, with the detail member of each XFocusInEvent structure set to NotifyNonlinearVirtual.

  • It generates a FocusIn event on window A, with the detail member of the XFocusInEvent structure set to NotifyNonlinear.

  • If window P is an inferior of window A, it generates a FocusIn event on each window below window A 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) to None (or vice versa), and the pointer is in window P, the X server does the following:

  • If the old focus is PointerRoot, it generates a FocusOut event on each window from window P up to and including window P's root, with the detail member of each XFocusOutEvent structure set to NotifyPointer.

  • 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.

Focus Events Generated by Grabs

Focus events in which the keyboard grab activates are identified by XFocusInEvent or XFocusOutEvent structures whose mode member is set to NotifyGrab. Focus events in which the keyboard grab deactivates are identified by XFocusInEvent or XFocusOutEvent structures whose mode member is set to NotifyUngrab (see XGrabKeyboard).

  • 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.

Key Map State Notification Events

The X server can report KeymapNotify events to clients that want information about changes in their keyboard state.

To receive KeymapNotify events, set the KeymapStateMask bit in the event-mask attribute of the window. The X server generates this event immediately after every EnterNotify and FocusIn event.

The structure for this event type contains:



/* generated on EnterWindow and FocusIn when KeymapState selected */
typedef struct {
     int            type;           /* KeymapNotify */
     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;
     char           key_vector[32];
} XKeymapEvent;     

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.

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.

The structure for this event type contains:



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 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.

GraphicsExpose and NoExpose Events

The X server can report GraphicsExpose events to clients wanting information about when a destination region could not be computed during certain graphics requests: XCopyArea or XCopyPlane. The X server generates this event whenever a destination region could not be computed because of an obscured or out-of-bounds source region. In addition, the X server guarantees to report contiguously all of the regions exposed by some graphics request (for example, copying an area of a drawable to a destination drawable).

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.

The structures for these event types contain:



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 */
     Drawable      drawable;
     int           major_code;   /* core is CopyArea or CopyPlane */
     int           minor_code;   /* not defined in the core */
} XNoExposeEvent;

Both structures have these common members: drawable, major_code, and minor_code. The drawable member is set to the drawable of the destination region on which the graphics request was to be performed. The major_code member is set to the graphics request initiated by the client and can be either X_CopyArea or X_CopyPlane. If it is X_CopyArea, a call to XCopyArea initiated the request. If it is X_CopyPlane, a call to XCopyPlane initiated the request. These constants are defined in <X11/Xproto.h>. The minor_code member, like the major_code member, indicates which graphics request was initiated by the client. However, the minor_code member is not defined by the core X protocol and will be zero in these cases, although it may be used by an extension.

The XGraphicsExposeEvent structure has these additional members: x, y, width, height, and count. The x and y members are set to the coordinates relative to the drawable'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 GraphicsExpose events to follow. If count is zero, no more GraphicsExpose events follow for this window. However, if count is nonzero, at least that number of GraphicsExpose events (and possibly more) are to follow for this window.

Window State Change Events

The following sections discuss:

  • 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 client application calling XCirculateSubwindows, XCirculateSubwindowsUp, or XCirculateSubwindowsDown.

To receive CirculateNotify events, set the StructureNotifyMask bit in the event-mask attribute of the window or the SubstructureNotifyMask bit in the event-mask attribute of the parent window (in which case, circulating any child generates an event).

The structure for this event type contains:



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:

To receive ConfigureNotify events, set the StructureNotifyMask bit in the event-mask attribute of the window or the SubstructureNotifyMask bit in the event-mask attribute of the parent window (in which case, configuring any child generates an event).

The structure for this event type contains:



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.

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.

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.

To receive CreateNotify events, set the SubstructureNotifyMask bit in the event-mask attribute of the window. Creating any children then generates an event.

The structure for the event type contains:



typedef struct {
     int           type;               /* CreateNotify */
     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;             /* 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.

To receive DestroyNotify events, set the StructureNotifyMask bit in the event-mask attribute of the window or the SubstructureNotifyMask bit in the event-mask attribute of the parent window (in which case, destroying any child generates an event).

The structure for this event type contains:



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 */
     Display       *display;   /* Display the event was read from */
     Window        event;
     Window        window;
} XDestroyWindowEvent;

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.

To receive GravityNotify events, set the StructureNotifyMask bit in the event-mask attribute of the window or the SubstructureNotifyMask bit in the event-mask attribute of the parent window (in which case, any child that is moved because its parent has been resized generates an event).

The structure for this event type contains:



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.

To receive MapNotify events, set the StructureNotifyMask bit in the event-mask attribute of the window or the SubstructureNotifyMask bit in the event-mask attribute of the parent window (in which case, mapping any child generates an event).

The structure for this event type contains:



typedef struct {
     int           type;                  /* MapNotify */
     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          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:

The structure for this event type contains:



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  */
     int           first_keycode;  /* first keycode */
     int           count;          /* defines range of change w. first_keycode*/
} XMappingEvent;

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.

To receive ReparentNotify events, set the StructureNotifyMask bit in the event-mask attribute of the window or the SubstructureNotifyMask bit in the event-mask attribute of either the old or the new parent window (in which case, reparenting any child generates an event).

The structure for this event type contains:



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.

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.

To receive UnmapNotify events, set the StructureNotifyMask bit in the event-mask attribute of the window or the SubstructureNotifyMask bit in the event-mask attribute of the parent window (in which case, unmapping any child window generates an event).

The structure for this event type contains:



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.

All VisibilityNotify events caused by a hierarchy change are generated after any hierarchy event (UnmapNotify, MapNotify, ConfigureNotify, GravityNotify, CirculateNotify) caused by that change. Any VisibilityNotify event on a given window is generated before any Expose events on that window, but it is not required that all VisibilityNotify events on all windows be generated before all Expose events on all windows. The X protocol does not constrain the ordering of VisibilityNotify events with respect to FocusOut, EnterNotify, and LeaveNotify events.

To receive VisibilityNotify events, set the VisibilityChangeMask bit in the event-mask attribute of the window.

The structure for this event type contains:



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.

Structure Control Events

This section discusses:

  • 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 on the window by calling XCirculateSubwindows, XCirculateSubwindowsUp, or XCirculateSubwindowsDown.

To receive CirculateRequest events, set the SubstructureRedirectMask in the event-mask attribute of the window. Then, in the future, the circulate window request for the specified window is not executed, and thus, any subwindow's position in the stack is not changed. For example, suppose a client application calls XCirculateSubwindowsUp to raise a subwindow to the top of the stack. If you had selected SubstructureRedirectMask on the window, the X server reports to you a CirculateRequest event and does not raise the subwindow to the top of the stack.

The structure for this event type contains:



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.

To receive ConfigureRequest events, set the SubstructureRedirectMask bit in the event-mask attribute of the window. ConfigureRequest events are generated when a ConfigureWindow protocol request is issued on a child window by another client. For example, suppose a client application calls XLowerWindow to lower a window. If you had selected SubstructureRedirectMask on the parent window and if the override-redirect attribute of the window is set to False, the X server reports a ConfigureRequest event to you and does not lower the specified window.

The structure for this event type contains:



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.

To receive MapRequest events, set the SubstructureRedirectMask bit in the event-mask attribute of the window. This means another client's attempts to map a child window by calling one of the map window request functions is intercepted, and you are sent a MapRequest instead. For example, suppose a client application calls XMapWindow to map a window. If you (usually a window manager) had selected SubstructureRedirectMask on the parent window and if the override-redirect attribute of the window is set to False, the X server reports a MapRequest event to you and does not map the specified window. Thus, this event gives your window manager client the ability to control the placement of subwindows.

The structure for this event type contains:



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.

To receive ResizeRequest events, set the ResizeRedirect bit in the event-mask attribute of the window. Any attempts to change the size by other clients are then redirected.

The structure for this event type contains:



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.

Colormap State Change Events

The X server can report ColormapNotify events to clients wanting information about when the colormap changes and when a colormap is installed or uninstalled. The X server generates this event type whenever a client application:

To receive ColormapNotify events, set the ColormapChangeMask bit in the event-mask attribute of the window.

The structure for this event type contains:



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.

Client Communication Events

This section discusses:

  • 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.

The structure for this event type contains:



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.

To receive PropertyNotify events, set the PropertyChangeMask bit in the ev