Xlib - C Language X Interface X Consortium Standard X Version 11, Release 6.4 James Gettys Cambridge Research Laboratory Digital Equipment Corporation Robert W. Scheifler Laboratory for Computer Science Massachusetts Institute of Technology with contributions from Chuck Adams, Tektronix, Inc. Vania Joloboff, Open Software Foundation Hideki Hiura, SunSoft, Inc. Bill McMahon, Hewlett-Packard Company Ron Newman, Massachusetts Institute of Technology Al Tabayoyon, Tektronix, Inc. Glenn Widener, Tektronix, Inc. Shigeru Yamada, Fujitsu OSSI The X Window System is a trademark of X Consortium, Inc. TekHVC is a trademark of Tektronix, Inc. Copyright (C) 1985, 1986, 1987, 1988, 1989, 1990, 1991, 1994,1996 X Consortium Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documenta- tion 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 PUR- POSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE X CONSOR- TIUM 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 X Con- sortium 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 X Consortium. Copyright (C) 1985, 1986, 1987, 1988, 1989, 1990, 1991 by Digital Equipment Corporation Portions Copyright (C) 1990, 1991 by Tektronix, Inc. Permission to use, copy, modify and distribute this documen- tation 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 permis- sion notice appear in all copies, and that the names of Dig- ital and Tektronix not be used in in advertising or public- ity pertaining to this documentation without specific, writ- ten prior permission. Digital and Tektronix makes no repre- sentations about the suitability of this documentation for any purpose. It is provided ``as is'' without express or implied warranty. Acknowledgments The design and implementation of the first 10 versions of X were primarily the work of three individuals: Robert Schei- fler of the MIT Laboratory for Computer Science and Jim Get- tys 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 acknowl- edge 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 con- tributed substantially to the design and implementation of the Version 11 Xlib interface. Our thanks also goes to Ralph Swick (Project Athena and Dig- ital) 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 suc- cessful 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 pro- vided the sample generic color frame buffer device-dependent code. The alpha and beta test participants deserve special recog- nition 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 uni- versities is certainly to the benefit of the entire X commu- nity. 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 suc- cess. 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 Stan- ford University and now of Digital WRL, who had much to do with W's design. Finally, our thanks goes to MIT, Digital Equipment Corpora- tion, 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 Com- munication Conventions (ICCCM) support. We also thank Al Mento of Digital for his continued effort in maintaining this document and Jim Fulton and Donna Con- verse (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 (Tek- tronix). 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 Bad- shah (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 Kurib- ayashi (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 Tech- nosystems Laboratory), Kazunori Nishihara (Fuji Xerox), Masaki Takeuchi (Sony), Katsuhisa Yano (Toshiba), Makoto Wakamatsu (Sony Corporation) for producing the another com- plete sample implementation of the internationalization facilities. The principal authors (design and implementation) of the Xcms color management facilities are Al Tabayoyon (Tek- tronix) and Chuck Adams (Tektronix). Joann Taylor (Tek- tronix), Bob Toole (Tektronix), and Keith Packard (MIT X Consortium) also contributed significantly to the design. Others who contributed are: Harold Boll (Kodak), Ken Bron- stein (HP), Nancy Cam (SGI), Donna Converse (MIT X Consor- tium), 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 substan- tially by testing the facilities and reporting bugs in a timely fashion. The principal authors of the internationalization facili- ties, 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 implementa- tion. They are: Takashi Fujiwara (Fujitsu), Yoshio Horiuchi (IBM), Makoto Inada (Digital), Hiromu Inukai (Nihon Sun- Soft), 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 Tera- zono (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 international- ization facilities are: Hector Chan (Digital), Michael Kung (IBM), Joseph Kwok (Digital), Hiroyuki Machida (Sony), Nel- son 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 comput- ers 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 sub- routine library that application programs (clients) use to interface with the window system by means of a stream con- nection. 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 proto- col. It is neither a tutorial nor a user's guide to pro- gramming 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: o Overview of the X Window System o Errors o Standard header files o Generic values and types o Naming and argument conventions within Xlib o Programming considerations o Character sets and encodings o Formatting conventions 1 Xlib - C Library X11, Release 6.4 1.1. 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 ser- vices 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 hier- archies. 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 win- dow 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. 2 Xlib - C Library X11, Release 6.4 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 some- times 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 asyn- chronously, 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 . 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 applica- tions, and in fact, windows are manipulated explicitly by window manager programs. Fonts and cursors are shared auto- matically 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 sup- port for sharing graphics contexts between applications. Client programs are informed of events. Events may either be side effects of a request (for example, restacking win- dows 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. 3 Xlib - C Library X11, Release 6.4 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 asyn- chronously, 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. 1.2. 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 val- ues, 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 synchro- nization is enabled, errors are reported as they are gener- ated. 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. 1.3. Standard Header Files The following include files are part of the Xlib standard: o 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 Xlib- SpecificationRelease. 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.) o 4 Xlib - C Library X11, Release 6.4 This file declares types and constants for the X proto- col that are to be used by applications. It is included automatically from , so applica- tion code should never need to reference this file directly. o This file contains symbols for much of the color man- agement facilities described in chapter 6. All func- tions, types, and symbols with the prefix ``Xcms'', plus the Color Conversion Contexts macros, are declared in this file. must be included before including this file. o This file declares various functions, types, and sym- bols used for inter-client communication and applica- tion utility functions, which are described in chapters 14 and 16. must be included before including this file. o This file declares all functions, types, and symbols for the resource manager facilities, which are described in chapter 15. must be included before including this file. o This file declares all predefined atoms, which are sym- bols with the prefix ``XA_''. o This file declares the cursor symbols for the standard cursor font, which are listed in appendix B. All cur- sor symbols have the prefix ``XC_''. o 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_ARA- BIC, XK_CYRILLIC, XK_GREEK, XK_TECHNICAL, XK_SPECIAL, XK_PUBLISHING, XK_APL, XK_HEBREW, XK_THAI, and XK_KOREAN. 5 Xlib - C Library X11, Release 6.4 o This file defines the preprocessor symbols XK_MISCEL- LANY, XK_XKB_KEYS, XK_LATIN1, XK_LATIN2, XK_LATIN3, XK_LATIN4, and XK_GREEK and then includes . o This file declares all the functions, types, and sym- bols used for extensions, which are described in appendix C. This file automatically includes . o This file declares types and symbols for the basic X protocol, for use in implementing extensions. It is included automatically from , so appli- cation and extension code should never need to refer- ence this file directly. o This file declares types and symbols for the basic X protocol, for use in implementing extensions. It is included automatically from , so applica- tion and extension code should never need to reference this file directly. o This file declares all the functions, types, and sym- bols used for the X10 compatibility functions, which are described in appendix D. 1.4. Generic Values and Types The following symbols are defined by Xlib and used through- out the manual: o Xlib defines the type Bool and the Boolean values True and False. o None is the universal null resource ID or atom. o The type XID is used for generic resource IDs. o The type XPointer is defined to be char* and is used as a generic opaque pointer to data. 6 Xlib - C Library X11, Release 6.4 1.5. Naming and Argument Conventions within Xlib Xlib follows a number of conventions for the naming and syn- tax of the functions. Given that you remember what informa- tion the function requires, these conventions are intended to make the syntax of the functions more predictable. The major naming conventions are: o 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. o All Xlib functions begin with a capital X. o The beginnings of all function names and symbols are capitalized. o All user-visible data structures begin with a capital X. More generally, anything that a user might derefer- ence begins with a capital X. o 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. o All elements of or variables in a data structure are in lowercase. Compound words, where needed, are con- structed with underscores (_). o The display argument, where used, is always first in the argument list. o All resource objects, where used, occur at the begin- ning of the argument list immediately after the display argument. o 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. o Source arguments always precede the destination argu- ments in the argument list. o The x argument always precedes the y argument in the argument list. o The width argument always precedes the height argument in the argument list. 7 Xlib - C Library X11, Release 6.4 o Where the x, y, width, and height arguments are used together, the x and y arguments always precede the width and height arguments. o Where a mask is accompanied with a structure, the mask always precedes the pointer to the structure in the argument list. 1.6. Programming Considerations The major programming considerations are: o Coordinates and sizes in X are actually 16-bit quanti- ties. 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. Val- ues larger than 16 bits are truncated silently. Sizes (width and height) are declared as unsigned quantities. o Keyboards are the greatest variable between different manufacturers' workstations. If you want your program to be portable, you should be particularly conservative here. o Many display systems have limited amounts of off-screen memory. If you can, you should minimize use of pixmaps and backing store. o 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 fur- ther information, see chapter 14 and the Inter-Client Communication Conventions Manual. 1.7. Character Sets and Encodings Some of the Xlib functions make reference to specific char- acter sets and character encodings. The following are the most common: o X Portable Character Set A basic set of 97 characters, which are assumed to exist in all locales supported by Xlib. This set con- tains the following characters: a..z A..Z 0..9 !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~ , , and 8 Xlib - C Library X11, Release 6.4 This set is the left/lower half of the graphic charac- ter 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. o Host Portable Character Encoding The encoding of the X Portable Character Set on the host. The encoding itself is not defined by this stan- dard, 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. o Latin-1 The coded character set defined by the ISO 8859-1 stan- dard. o 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. o STRING Encoding Latin-1, plus tab and newline. o UTF-8 Encoding The ASCII compatible character encoding scheme defined by the ISO 10646-1 standard. o 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 ._- 1.8. Formatting Conventions Xlib - C Language X Interface uses the following conven- tions: 9 Xlib - C Library X11, Release 6.4 o 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. o Each function is introduced by a general discussion that distinguishes it from other functions. The func- tion declaration itself follows, and each argument is specifically explained. Although ANSI C function pro- totype 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 applica- ble, the last paragraph of the explanation lists the possible Xlib error codes that the function can gener- ate. For a complete discussion of the Xlib error codes, see section 11.8.2. o 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 argu- ments, 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 speci- fies and returns. o 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 suf- fix. 10 Xlib - C Library X11, Release 6.4 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: o Open (connect to) the display o Obtain information about the display, image formats, or screens o Generate a NoOperation protocol request o Free client-created data o Close (disconnect from) a display o Use X Server connection close operations o Use Xlib with threads o Use internal connections 2.1. Opening the Display To open a connection to the X server that controls a dis- play, use XOpenDisplay. __ | Display *XOpenDisplay(display_name) char *display_name; display_name Specifies the hardware display name, which deter- mines the display and communications domain to be used. On a POSIX-conformant system, if the dis- play_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 charac- ters is implementation-dependent. On POSIX-conformant 11 Xlib - C Library X11, Release 6.4 systems, the display name or DISPLAY environment variable can be a string in the format: __ | hostname:number.screen_number 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 dis- play 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 vari- able that can be accessed by using the Default- Screen 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 con- nects your application to the X server through TCP or DECnet communications protocols, or through some local inter-pro- cess communication protocol. If the hostname is a host machine name and a single colon (:) separates the hostname and display number, XOpenDisplay connects using TCP streams. If the hostname is 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. 12 Xlib - C Library X11, Release 6.4 If successful, XOpenDisplay returns a pointer to a Display structure, which is defined in . If XOpenDis- play 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). 2.2. Obtaining Information about the Display, Image For- mats, or Screens The Xlib library provides a number of useful macros and cor- responding 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: o Display macros o Image format functions and macros o 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. Note The XDisplayWidth, XDisplayHeight, XDisplayCells, XDisplayPlanes, XDisplayWidthMM, and XDisplay- HeightMM functions in the next sections are mis- named. These functions really should be named Screenwhatever and XScreenwhatever, not Display- whatever or XDisplaywhatever. Our apologies for the resulting confusion. 2.2.1. Display Macros Applications should not directly modify any part of the Dis- play and Screen structures. The members should be consid- ered read-only, although they may change as the result of other operations on the display. 13 Xlib - C Library X11, Release 6.4 The following lists the C language macros, their correspond- ing function equivalents that are for other language bind- ings, and what data both can return. __ | AllPlanes unsigned long 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 perma- nently 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 rela- tive intensity of the colors. __ | BlackPixel(display, screen_number) unsigned long XBlackPixel(display, screen_number) 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. 14 Xlib - C Library X11, Release 6.4 __ | WhitePixel(display, screen_number) unsigned long XWhitePixel(display, screen_number) 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; 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, screen_number) 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. 15 Xlib - C Library X11, Release 6.4 __ | DefaultDepth(display, screen_number) int XDefaultDepth(display, screen_number) 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. __ | int *XListDepths(display, screen_number, count_return) 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 depths. |__ 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 num- ber of available depths. Otherwise, it does not set count_return and returns NULL. To release the memory allo- cated for the array of depths, use XFree. 16 Xlib - C Library X11, Release 6.4 __ | DefaultGC(display, screen_number) GC XDefaultGC(display, screen_number) 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 conve- nience 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; display Specifies the connection to the X server. |__ Both return the root window for the default screen. __ | DefaultScreenOfDisplay(display) Screen *XDefaultScreenOfDisplay(display) Display *display; display Specifies the connection to the X server. |__ Both return a pointer to the default screen. 17 Xlib - C Library X11, Release 6.4 __ | ScreenOfDisplay(display, screen_number) Screen *XScreenOfDisplay(display, screen_number) 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; 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, screen_number) 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. 18 Xlib - C Library X11, Release 6.4 __ | DisplayCells(display, screen_number) int XDisplayCells(display, screen_number) 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, screen_number) 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; 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 sys- tems, 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 19 Xlib - C Library X11, Release 6.4 the fork system call and want to open a new connection to the same display from the child process as well as for printing error messages. __ | long XExtendedMaxRequestSize(display) 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 proto- col 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, XSetClipRectan- gles, 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 exam- ple, 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. __ | long XMaxRequestSize(display) 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. 20 Xlib - C Library X11, Release 6.4 __ | LastKnownRequestProcessed(display) unsigned long XLastKnownRequestProcessed(display) 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; 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; display Specifies the connection to the X server. |__ Both return the major version number (11) of the X protocol associated with the connected display. 21 Xlib - C Library X11, Release 6.4 __ | ProtocolRevision(display) int XProtocolRevision(display) 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; 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, screen_number) 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 func- tions that need a drawable of a particular screen and for creating top-level windows. 22 Xlib - C Library X11, Release 6.4 __ | ScreenCount(display) int XScreenCount(display) Display *display; display Specifies the connection to the X server. |__ Both return the number of available screens. __ | ServerVendor(display) char *XServerVendor(display) Display *display; display Specifies the connection to the X server. |__ Both return a pointer to a null-terminated string that pro- vides 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 con- tents of the string are implementation-dependent. __ | VendorRelease(display) int XVendorRelease(display) Display *display; display Specifies the connection to the X server. |__ Both return a number related to a vendor's release of the X server. 2.2.2. 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 applica- tions, most of the work required to convert the data is pro- vided by Xlib (see sections 8.7 and 16.8). 23 Xlib - C Library X11, Release 6.4 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. __ | XPixmapFormatValues *XListPixmapFormats(display, count_return) Display *display; int *count_return; display Specifies the connection to the X server. count_return Returns the number of pixmap formats that are sup- ported by the display. |__ The XListPixmapFormats function returns an array of XPixmap- FormatValues 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 XFree. The following lists the C language macros, their correspond- ing function equivalents that are for other language bind- ings, and what data they both return for the specified server and screen. These are often used by toolkits as well as by simple applications. 24 Xlib - C Library X11, Release 6.4 __ | ImageByteOrder(display) int XImageByteOrder(display) 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 LSB- First or MSBFirst. __ | BitmapUnit(display) int XBitmapUnit(display) 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; 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. 25 Xlib - C Library X11, Release 6.4 __ | BitmapPad(display) int XBitmapPad(display) 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, screen_number) 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, screen_number) 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 millime- ters. 26 Xlib - C Library X11, Release 6.4 __ | DisplayWidth(display, screen_number) int XDisplayWidth(display, screen_number) 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, screen_number) 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 millime- ters. 2.2.3. Screen Information Macros The following lists the C language macros, their correspond- ing function equivalents that are for other language bind- ings, and what data they both can return. These macros or functions all take a pointer to the appropriate screen structure. 27 Xlib - C Library X11, Release 6.4 __ | BlackPixelOfScreen(screen) unsigned long XBlackPixelOfScreen(screen) 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; screen Specifies the appropriate Screen structure. |__ Both return the white pixel value of the specified screen. __ | CellsOfScreen(screen) int XCellsOfScreen(screen) Screen *screen; screen Specifies the appropriate Screen structure. |__ Both return the number of colormap cells in the default col- ormap of the specified screen. __ | DefaultColormapOfScreen(screen) Colormap XDefaultColormapOfScreen(screen) Screen *screen; screen Specifies the appropriate Screen structure. |__ Both return the default colormap of the specified screen. 28 Xlib - C Library X11, Release 6.4 __ | DefaultDepthOfScreen(screen) int XDefaultDepthOfScreen(screen) Screen *screen; screen Specifies the appropriate Screen structure. |__ Both return the depth of the root window. __ | DefaultGCOfScreen(screen) GC XDefaultGCOfScreen(screen) 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; screen Specifies the appropriate Screen structure. |__ Both return the default visual of the specified screen. For information on visual types, see section 3.1. 29 Xlib - C Library X11, Release 6.4 __ | DoesBackingStore(screen) int XDoesBackingStore(screen) 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 When- Mapped, NotUseful, or Always (see section 3.2.4). __ | DoesSaveUnders(screen) Bool XDoesSaveUnders(screen) 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; screen Specifies the appropriate Screen structure. |__ Both return the display of the specified screen. 30 Xlib - C Library X11, Release 6.4 __ | int XScreenNumberOfScreen(screen) 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; screen Specifies the appropriate Screen structure. |__ Both return the event mask of the root window for the speci- fied screen at connection setup time. __ | WidthOfScreen(screen) int XWidthOfScreen(screen) 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; screen Specifies the appropriate Screen structure. |__ Both return the height of the specified screen in pixels. 31 Xlib - C Library X11, Release 6.4 __ | WidthMMOfScreen(screen) int XWidthMMOfScreen(screen) Screen *screen; screen Specifies the appropriate Screen structure. |__ Both return the width of the specified screen in millime- ters. __ | HeightMMOfScreen(screen) int XHeightMMOfScreen(screen) Screen *screen; screen Specifies the appropriate Screen structure. |__ Both return the height of the specified screen in millime- ters. __ | MaxCmapsOfScreen(screen) int XMaxCmapsOfScreen(screen) Screen *screen; screen Specifies the appropriate Screen structure. |__ Both return the maximum number of installed colormaps sup- ported by the specified screen (see section 9.3). 32 Xlib - C Library X11, Release 6.4 __ | MinCmapsOfScreen(screen) int XMinCmapsOfScreen(screen) Screen *screen; screen Specifies the appropriate Screen structure. |__ Both return the minimum number of installed colormaps sup- ported by the specified screen (see section 9.3). __ | PlanesOfScreen(screen) int XPlanesOfScreen(screen) Screen *screen; screen Specifies the appropriate Screen structure. |__ Both return the depth of the root window. __ | RootWindowOfScreen(screen) Window XRootWindowOfScreen(screen) Screen *screen; screen Specifies the appropriate Screen structure. |__ Both return the root window of the specified screen. 2.3. Generating a NoOperation Protocol Request To execute a NoOperation protocol request, use XNoOp. __ | XNoOp(display) Display *display; display Specifies the connection to the X server. |__ The XNoOp function sends a NoOperation protocol request to 33 Xlib - C Library X11, Release 6.4 the X server, thereby exercising the connection. 2.4. Freeing Client-Created Data To free in-memory data that was created by an Xlib function, use XFree. __ | XFree(data) void *data; data Specifies the data that is to be freed. |__ The XFree function is a general-purpose Xlib routine that frees the specified data. You must use it to free any objects that were allocated by Xlib, unless an alternate function is explicitly specified for the object. A NULL pointer cannot be passed to this function. 2.5. Closing the Display To close a display or disconnect from the X server, use XCloseDisplay. __ | XCloseDisplay(display) 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 XSet- CloseDownMode). 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. 34 Xlib - C Library X11, Release 6.4 __ | XSetCloseDownMode(display, close_mode) 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 RetainTempo- rary. |__ The XSetCloseDownMode 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 Retain- Permanent or RetainTemporary, see section 2.6. XSetCloseDownMode can generate a BadValue error. 2.6. 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 opera- tions: o It disowns all selections owned by the client (see XSetSelectionOwner). o It performs an XUngrabPointer and XUngrabKeyboard if the client has actively grabbed the pointer or the key- board. o It performs an XUngrabServer if the client has grabbed the server. o It releases all passive grabs made by the client. o It marks all resources (including colormap entries) allocated by the client either as permanent or tempo- rary, depending on whether the close-down mode is RetainPermanent or RetainTemporary. However, this does not prevent other client applications from explicitly destroying the resources (see XSetCloseDownMode). When the close-down mode is DestroyAll, the X server destroys all of a client's resources as follows: o 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 35 Xlib - C Library X11, Release 6.4 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. o 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. o It destroys all windows created by the client. o It performs the appropriate free request on each non- window resource created by the client in the server (for example, Font, Pixmap, Cursor, Colormap, and GCon- text). o 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 connec- tion closing with the close_mode of DestroyAll, the X server does the following: o 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 Retain- Permanent or RetainTemporary mode. o It deletes all but the predefined atom identifiers. o It deletes all properties on all root windows (see sec- tion 4.3). o It resets all device maps and attributes (for example, key click, bell volume, and acceleration) as well as the access control list. o It restores the standard root tiles and cursors. o It restores the default font path. o It restores the input focus to state PointerRoot. However, the X server does not reset if you close a connec- tion with a close-down mode set to RetainPermanent or RetainTemporary. 36 Xlib - C Library X11, Release 6.4 2.7. 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 XInit- Threads. __ | Status XInitThreads(); |__ The XInitThreads function initializes Xlib support for con- current threads. This function must be the first Xlib func- tion 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 pro- grams not call this function. To lock a display across several Xlib calls, use XLockDis- play. __ | void XLockDisplay(display) 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 XUnlockDis- play has been called the same number of times as XLockDis- play. This function has no effect unless Xlib was success- fully initialized for threads using XInitThreads. To unlock a display, use XUnlockDisplay. 37 Xlib - C Library X11, Release 6.4 __ | void XUnlockDisplay(display) Display *display; display Specifies the connection to the X server. |__ The XUnlockDisplay function allows other threads to use the specified display again. Any threads that have blocked on the display are allowed to continue. Nested locking works correctly; if XLockDisplay has been called multiple times by a thread, then XUnlockDisplay must be called an equal number of times before the display is actually unlocked. This function has no effect unless Xlib was successfully initial- ized for threads using XInitThreads. 2.8. 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 dis- plays, or that use displays in combination with other inputs, need to obtain these additional connections to cor- rectly 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 XAddConnec- tionWatch. 38 Xlib - C Library X11, Release 6.4 __ | typedef void (*XConnectionWatchProc)(display, client_data, fd, opening, watch_data) Display *display; XPointer client_data; int fd; Bool opening; XPointer *watch_data; Status XAddConnectionWatch(display, procedure, client_data) 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 XAddConnectionWatch 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 dis- play, 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 pri- vate 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 regis- tered procedure will immediately be called for each of them, before XAddConnectionWatch returns. XAddConnectionWatch returns a nonzero status if the procedure is successfully registered; otherwise, it returns zero. The registered procedure should not call any Xlib functions. If the procedure directly or indirectly causes the state of internal connections or watch procedures to change, the result is not defined. If Xlib has been initialized for threads, the procedure is called with the display locked and the result of a call by the procedure to any Xlib function that locks the display is not defined unless the executing thread has externally locked the display using XLockDisplay. To stop tracking internal connections for a display, use XRemoveConnectionWatch. 39 Xlib - C Library X11, Release 6.4 __ | Status XRemoveConnectionWatch(display, procedure, client_data) 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 XProcessIn- ternalConnection. __ | void XProcessInternalConnection(display, fd) 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 dis- play, use XInternalConnectionNumbers. 40 Xlib - C Library X11, Release 6.4 __ | Status XInternalConnectionNumbers(display, fd_return, count_return) Display *display; int **fd_return; int *count_return; display Specifies the connection to the X server. fd_return Returns the file descriptors. count_return Returns the number of file descriptors. |__ 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 XFree. This functions returns a nonzero status if the list is successfully allo- cated; otherwise, it returns zero. 41 Xlib - C Library X11, Release 6.4 Chapter 3 Window Functions In the X Window System, a window is a rectangular area on the screen that lets you view graphic output. Client appli- cations can display overlapping and nested windows on one or more screens that are driven by X servers on one or more machines. Clients who want to create windows must first connect their program to the X server by calling XOpenDis- play. This chapter begins with a discussion of visual types and window attributes. The chapter continues with a discus- sion of the Xlib functions you can use to: o Create windows o Destroy windows o Map windows o Unmap windows o Configure windows o Change window stacking order o Change window attributes This chapter also identifies the window actions that may generate events. Note that it is vital that your application conform to the established conventions for communicating with window man- agers for it to work well with the various window managers in use (see section 14.1). Toolkits generally adhere to these conventions for you, relieving you of the burden. Toolkits also often supersede many functions in this chapter with versions of their own. For more information, refer to the documentation for the toolkit that you are using. 3.1. 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 42 Xlib - C Library X11, Release 6.4 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 informa- tion 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 col- ormap_size. The class member specifies one of the possible visual classes of the screen and can be StaticGray, Static- Color, 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 sepa- rate 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 hard- ware, and not at all on other hardware. The visual types affect the colormap and the RGB values in the following ways: o For PseudoColor, a pixel value indexes a colormap to produce independent RGB values, and the RGB values can be changed dynamically. o GrayScale is treated the same way as PseudoColor except that the primary that drives the screen is undefined. 43 Xlib - C Library X11, Release 6.4 Thus, the client should always store the same value for red, green, and blue in the colormaps. o For DirectColor, a pixel value is decomposed into sepa- rate RGB subfields, and each subfield separately indexes the colormap for the corresponding value. The RGB values can be changed dynamically. o 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 lin- ear or near-linear ramps in each primary. o StaticColor is treated the same way as PseudoColor except that the colormap has predefined, read-only, server-dependent RGB values. o 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. Stat- icGray 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 con- tiguous 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 XVisualIDFromVi- sual. __ | VisualID XVisualIDFromVisual(visual) Visual *visual; visual Specifies the visual type. |__ The XVisualIDFromVisual function returns the visual ID for the specified visual type. 3.2. 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 44 Xlib - C Library X11, Release 6.4 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 win- dow, 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 Inpu- tOnly window: o win-gravity o event-mask o do-not-propagate-mask o override-redirect o 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. Inpu- tOnly windows are invisible; can only be used to control such things as cursors, input event generation, and grab- bing; 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 win- dow 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. 45 Xlib - C Library X11, Release 6.4 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 com- mand to do so. Instead, either your program should use the space given to it, or if the space is too small for any use- ful work, your program might ask the user to resize the win- dow. 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 corre- sponding value bitmask in your subsequent calls to XCre- ateWindow 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: 46 Xlib - C Library X11, Release 6.4 __ | /* 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: ------------------------------------------------------------- Attribute Default InputOut- Inpu- put tOnly ------------------------------------------------------------- background-pixmap None Yes No background-pixel Undefined Yes No 47 Xlib - C Library X11, Release 6.4 ------------------------------------------------------------- Attribute Default InputOut- Inpu- put tOnly ------------------------------------------------------------- border-pixmap CopyFromPar- Yes No ent border-pixel Undefined Yes No bit-gravity ForgetGravity Yes No win-gravity NorthWest- Yes Yes Gravity backing-store NotUseful Yes No backing-planes All ones Yes No backing-pixel zero Yes No save-under False Yes No event-mask empty set Yes Yes do-not-propagate-mask empty set Yes Yes override-redirect False Yes Yes colormap CopyFromPar- Yes No ent cursor None Yes Yes ------------------------------------------------------------- 3.2.1. 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 speci- fies 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 back- ground-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: o The parent window's background-pixmap is used. The child window, however, must have the same depth as its 48 Xlib - C Library X11, Release 6.4 parent, or a BadMatch error results. o If the parent window has a background-pixmap of None, the window also has a background-pixmap of None. o 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. o The background tile origin always aligns with the par- ent window's background tile origin. If the back- ground-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 back- ground. 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 main- taining 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). 3.2.2. 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 ori- gin. 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 49 Xlib - C Library X11, Release 6.4 (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. 3.2.3. Gravity Attributes The bit gravity of a window defines which region of the win- dow 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 win- dow. 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 recon- figured (depending on their win-gravity). For a change of width and height, the (x, y) pairs are defined: ---------------------------------------- Gravity Direction Coordinates ---------------------------------------- NorthWestGravity (0, 0) NorthGravity (Width/2, 0) NorthEastGravity (Width, 0) 50 Xlib - C Library X11, Release 6.4 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 posi- tion of each pixel in the window. When a window with one of these win-gravities has its parent window resized, the cor- responding 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 gener- ated. 3.2.4. Backing Store Attribute Some implementations of the X server may choose to maintain the contents of InputOutput windows. If the X server main- tains 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. 51 Xlib - C Library X11, Release 6.4 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 maintain- ing 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 benefi- cial. 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 main- taining 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. 3.2.5. 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. 3.2.6. 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 speci- fied bit planes in the backing store or the save under and is free to regenerate the remaining planes with the speci- fied 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 52 Xlib - C Library X11, Release 6.4 of off-screen memory required to store your window. 3.2.7. 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, KeyRe- lease, ButtonPress, ButtonRelease, PointerMotion, But- ton1Motion, Button2Motion, Button3Motion, Button4Motion, Button5Motion, and ButtonMotion. You can specify that all events are propagated by setting NoEventMask (default). 3.2.8. Override Redirect Flag To control window placement or to add decoration, a window manager often needs to intercept (redirect) any map or con- figure request. Pop-up windows, however, often need to be mapped without a window manager getting in the way. To con- trol whether an InputOutput or InputOnly window is to ignore these structure control facilities, use the override-redi- rect flag. The override-redirect flag specifies whether map and config- ure requests on this window should override a Substructur- eRedirectMask on the parent. You can set the override-redi- rect flag to True or False (default). Window managers use this information to avoid tampering with pop-up windows (see also chapter 14). 3.2.9. 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 Copy- FromParent (default). If you set the colormap to CopyFromParent, the parent win- dow's colormap is copied and used by its child. However, the child window must have the same visual type as the par- ent, or a BadMatch error results. The parent window must not have a colormap of None, or a BadMatch error results. 53 Xlib - C Library X11, Release 6.4 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. 3.2.10. 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 immedi- ate 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. 3.3. Creating Windows Xlib provides basic ways for creating windows, and toolkits often supply higher-level functions specifically for creat- ing 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: o You must never fight with the window manager for the size or placement of your top-level window. o 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. o 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.) o If you do not use a toolkit that automatically sets standard window properties, you should set these prop- erties for top-level windows before mapping them. 54 Xlib - C Library X11, Release 6.4 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 con- trol, and so on). Extension packages can define other classes of windows. To create an unmapped window and set its window attributes, use XCreateWindow. 55 Xlib - C Library X11, Release 6.4 __ | Window XCreateWindow(display, parent, x, y, width, height, border_width, depth, class, visual, valuemask, attributes) Display *display; Window parent; int x, y; unsigned int width, height; unsigned int border_width; int depth; unsigned int class; Visual *visual; unsigned long valuemask; XSetWindowAttributes *attributes; display Specifies the connection to the X server. parent Specifies the parent window. x y Specify the x and y coordinates, which are the top-left outside corner of the created window's borders and are relative to the inside of the par- ent window's borders. width height Specify the width and height, which are the cre- ated window's inside dimensions and do not include the created window's borders. 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 Copy- FromParent means the depth is taken from the par- ent. 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 Copy- FromParent 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. 56 Xlib - C Library X11, Release 6.4 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 cre- ated window, and causes the X server to generate a CreateNo- tify 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 cor- ner. 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, how- ever, 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 par- ent window, use XCreateSimpleWindow. 57 Xlib - C Library X11, Release 6.4 __ | Window XCreateSimpleWindow(display, parent, x, y, width, height, border_width, border, background) Display *display; Window parent; int x, y; unsigned int width, height; unsigned int border_width; unsigned long border; unsigned long background; display Specifies the connection to the X server. parent Specifies the parent window. x y Specify the x and y coordinates, which are the top-left outside corner of the new window's bor- ders and are relative to the inside of the parent window's borders. width height Specify the width and height, which are the cre- ated window's inside dimensions and do not include the created window's borders. 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 win- dow. |__ 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 sib- lings. Any part of the window that extends outside its par- ent window is clipped. The border_width for an InputOnly window must be zero, or a BadMatch error results. XCreateS- impleWindow 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, Bad- Value, and BadWindow errors. 58 Xlib - C Library X11, Release 6.4 3.4. 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 XDestroy- Window. __ | XDestroyWindow(display, w) 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 sub- hierarchies 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 XDe- stroySubwindows. __ | XDestroySubwindows(display, w) Display *display; Window w; display Specifies the connection to the X server. w Specifies the window. |__ The XDestroySubwindows function destroys all inferior win- dows of the specified window, in bottom-to-top stacking 59 Xlib - C Library X11, Release 6.4 order. It causes the X server to generate a DestroyNotify event for each window. If any mapped subwindows were actu- ally 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. 3.5. 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: o It is obscured by another opaque window. o One of its ancestors is not mapped. o 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 sub- windows. 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 Sub- structureRedirectMask. 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. 60 Xlib - C Library X11, Release 6.4 __ | XMapWindow(display, w) 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 sub- windows 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 expo- sure 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. 61 Xlib - C Library X11, Release 6.4 To map and raise a window, use XMapRaised. __ | XMapRaised(display, w) 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 speci- fied window to the top of the stack. For additional infor- mation, see XMapWindow. XMapRaised can generate multiple BadWindow errors. To map all subwindows for a specified window, use XMapSub- windows. __ | XMapSubwindows(display, w) Display *display; Window w; display Specifies the connection to the X server. w Specifies the window. |__ The XMapSubwindows function maps all subwindows for a speci- fied 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. 3.6. Unmapping Windows Xlib provides functions that you can use to unmap a window or all subwindows. To unmap a window, use XUnmapWindow. 62 Xlib - C Library X11, Release 6.4 __ | XUnmapWindow(display, w) 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 XUnmap- Subwindows. __ | XUnmapSubwindows(display, w) 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 sub- window 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. 3.7. Configuring Windows 63 Xlib - C Library X11, Release 6.4 Xlib provides functions that you can use to move a window, resize a window, move and resize a window, or change a win- dow'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 bor- der in pixels. Note that setting just the border width leaves the outer-left corner of the window in a fixed posi- tion but moves the absolute position of the window's origin. If you attempt to set the border-width attribute of an Inpu- tOnly 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 64 Xlib - C Library X11, Release 6.4 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 Resiz- eRedirectMask and that SubstructureRedirectMask on the par- ent 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 Config- ureNotify events. If the inside width or height of the win- dow 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 pro- cessing 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 Bot- tomIf, 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: Above The window is placed just above the sibling. Below The window is placed just below the sibling. TopIf If the sibling occludes the window, the window is placed at the top of the stack. BottomIf If 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: 65 Xlib - C Library X11, Release 6.4 Above The window is placed at the top of the stack. Below The 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, w, value_mask, values) Display *display; Window w; unsigned int value_mask; XWindowChanges *values; display Specifies the connection to the X server. w Specifies the window to be reconfigured. value_mask Specifies which values are to be set using infor- mation 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 XConfig- ureWindow), not its initial geometry. Any backing store contents of the window, its inferiors, and other newly visi- ble windows are either discarded or changed to reflect the current screen contents (depending on the implementation). 66 Xlib - C Library X11, Release 6.4 XConfigureWindow can generate BadMatch, BadValue, and Bad- Window errors. To move a window without changing its size, use XMoveWindow. __ | XMoveWindow(display, w, x, y) Display *display; Window w; int x, y; display Specifies the connection to the X server. w Specifies the window to be moved. x y Specify the x and y coordinates, which define the new location of the top-left pixel of the window's border or the window itself if it has no border. |__ 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 con- tents 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 win- dow is moved. XMoveWindow can generate a BadWindow error. To change a window's size without changing the upper-left coordinate, use XResizeWindow. 67 Xlib - C Library X11, Release 6.4 __ | XResizeWindow(display, w, width, height) Display *display; Window w; unsigned int width, height; display Specifies the connection to the X server. w Specifies the window. width height Specify the width and height, which are the inte- rior dimensions of the window after the call com- pletes. |__ The XResizeWindow function changes the inside dimensions of the specified window, not including its borders. This func- tion 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 XMoveRe- sizeWindow. 68 Xlib - C Library X11, Release 6.4 __ | XMoveResizeWindow(display, w, x, y, width, height) Display *display; Window w; int x, y; unsigned int width, height; display Specifies the connection to the X server. w Specifies the window to be reconfigured. x y Specify the x and y coordinates, which define the new position of the window relative to its parent. width height Specify the width and height, which define the interior size of the window. |__ The XMoveResizeWindow function changes the size and location of the specified window without raising it. Moving and resizing a mapped window may generate an Expose event on the window. Depending on the new size and location parameters, moving and resizing a window may generate Expose events on windows that the window formerly obscured. If the override-redirect flag of the window is False and some other client has selected SubstructureRedirectMask on the parent, the X server generates a ConfigureRequest event, and no further processing is performed. Otherwise, the win- dow size and location are changed. XMoveResizeWindow can generate BadValue and BadWindow errors. To change the border width of a given window, use XSetWin- dowBorderWidth. 69 Xlib - C Library X11, Release 6.4 __ | XSetWindowBorderWidth(display, w, width) Display *display; Window w; unsigned int 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 win- dow's border width to the specified width. XSetWindowBorderWidth can generate a BadWindow error. 3.8. 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, w) 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 win- dow 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 win- dow is raised. 70 Xlib - C Library X11, Release 6.4 XRaiseWindow can generate a BadWindow error. To lower a window so that it does not obscure any sibling windows, use XLowerWindow. __ | XLowerWindow(display, w) 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 analo- gous 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 win- dow is lowered to the bottom of the stack. XLowerWindow can generate a BadWindow error. To circulate a subwindow up or down, use XCirculateSubwin- dows. 71 Xlib - C Library X11, Release 6.4 __ | XCirculateSubwindows(display, w, direction) 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, XCirculateSub- windows lowers the highest mapped child (if any) that occludes