Release 1
Release 4
Release 5
Release 6
1.1. Overview of the X Window SystemSome of the terms used in this book are unique to X, andother terms that are common to other window systems havedifferent meanings in X. You may find it helpful to referto the glossary, which is located at the end of the book.The X Window System supports one or more screens containingoverlapping windows or subwindows. A screen is a physicalmonitor and hardware that can be color, grayscale, ormonochrome. There can be multiple screens for each displayor workstation. A single X server can provide displayservices for any number of screens. A set of screens for asingle user with one keyboard and one pointer (usually amouse) is called a display.All the windows in an X server are arranged in stricthierarchies. At the top of each hierarchy is a root window,which covers each of the display screens. Each root windowis partially or completely covered by child windows. Allwindows, except for root windows, have parents. There isusually at least one window for each application program.Child windows may in turn have their own children. In thisway, an application program can create an arbitrarily deeptree on each screen. X provides graphics, text, and rasteroperations for windows.A child window can be larger than its parent. That is, partor all of the child window can extend beyond the boundariesof the parent, but all output to a window is clipped by itsparent. If several children of a window have overlappinglocations, one of the children is considered to be on top ofor raised over the others, thus obscuring them. Output toareas covered by other windows is suppressed by the windowsystem unless the window has backing store. If a window isobscured by a second window, the second window obscures onlythose ancestors of the second window that are also ancestorsof the first window.A window has a border zero or more pixels in width, whichcan be any pattern (pixmap) or solid color you like. Awindow 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 operationsin the parent window usually are clipped by the children.Each window and pixmap has its own coordinate system. Thecoordinate system has the X axis horizontal and the Y axisvertical with the origin [0, 0] at the upper-left corner.Coordinates are integral, in terms of pixels, and coincidewith pixel centers. For a window, the origin is inside theborder at the inside, upper-left corner.X does not guarantee to preserve the contents of windows.When part or all of a window is hidden and then brought backonto the screen, its contents may be lost. The server thensends the client program an Expose event to notify it thatpart or all of the window needs to be repainted. Programsmust be prepared to regenerate the contents of windows ondemand.X also provides off-screen storage of graphics objects,called pixmaps. Single plane (depth 1) pixmaps aresometimes referred to as bitmaps. Pixmaps can be used inmost graphics functions interchangeably with windows and areused in various graphics operations to define patterns ortiles. Windows and pixmaps together are referred to asdrawables.Most of the functions in Xlib just add requests to an outputbuffer. These requests later execute asynchronously on theX server. Functions that return values of informationstored in the server do not return (that is, they block)until an explicit reply is received or an error occurs. Youcan provide an error handler, which will be called when theerror is reported.If a client does not want a request to executeasynchronously, it can follow the request with a call toXSync, which blocks until all previously bufferedasynchronous events have been sent and acted on. As animportant side effect, the output buffer in Xlib is alwaysflushed by a call to any function that returns a value fromthe server or waits for input.Many Xlib functions will return an integer resource ID,which allows you to refer to objects stored on the X server.These can be of type Window, Font, Pixmap, Colormap, Cursor,and GContext, as defined in the file <X11/X.h>. Theseresources are created by requests and are destroyed (orfreed) by requests or when connections are closed. Most ofthese resources are potentially sharable betweenapplications, and in fact, windows are manipulatedexplicitly by window manager programs. Fonts and cursorsare shared automatically across multiple screens. Fonts areloaded and unloaded as needed and are shared by multipleclients. Fonts are often cached in the server. Xlibprovides no support for sharing graphics contexts betweenapplications.Client programs are informed of events. Events may eitherbe side effects of a request (for example, restackingwindows generates Expose events) or completely asynchronous(for example, from the keyboard). A client program asks tobe informed of events. Because other applications can sendevents to your application, programs must be prepared tohandle (or ignore) events of all types.Input events (for example, a key pressed or the pointermoved) arrive asynchronously from the server and are queueduntil they are requested by an explicit call (for example,XNextEvent or XWindowEvent). In addition, some libraryfunctions (for example, XRaiseWindow) generate Expose andConfigureRequest events. These events also arriveasynchronously, but the client may wish to explicitly waitfor them by calling XSync after calling a function that cancause the server to generate events.1.2. ErrorsSome functions return Status, an integer error indication.If the function fails, it returns a zero. If the functionreturns a status of zero, it has not updated the returnarguments. Because C does not provide multiple returnvalues, many functions must return their results by writinginto client-passed storage. By default, errors are handledeither by a standard library function or by one that youprovide. Functions that return pointers to strings returnNULL pointers if the string does not exist.The X server reports protocol errors at the time that itdetects them. If more than one error could be generated fora given request, the server can report any of them.Because Xlib usually does not transmit requests to theserver immediately (that is, it buffers them), errors can bereported much later than they actually occur. For debuggingpurposes, however, Xlib provides a mechanism for forcingsynchronous behavior (see section 11.8.1). Whensynchronization is enabled, errors are reported as they aregenerated.When Xlib detects an error, it calls an error handler, whichyour program can provide. If you do not provide an errorhandler, the error is printed, and your program terminates.1.3. Standard Header FilesThe following include files are part of the Xlib standard:• <X11/Xlib.h>This is the main header file for Xlib. The majority ofall Xlib symbols are declared by including this file.This file also contains the preprocessor symbolXlibSpecificationRelease. This symbol is defined tohave the 6 in this release of the standard. (Release 5of Xlib was the first release to have this symbol.)• <X11/X.h>This file declares types and constants for the Xprotocol that are to be used by applications. It isincluded automatically from <X11/Xlib.h>, soapplication code should never need to reference thisfile directly.• <X11/Xcms.h>This file contains symbols for much of the colormanagement facilities described in chapter 6. Allfunctions, types, and symbols with the prefix ‘‘Xcms’’,plus the Color Conversion Contexts macros, are declaredin this file. <X11/Xlib.h> must be included beforeincluding this file.• <X11/Xutil.h>This file declares various functions, types, andsymbols used for inter-client communication andapplication utility functions, which are described inchapters 14 and 16. <X11/Xlib.h> must be includedbefore including this file.• <X11/Xresource.h>This file declares all functions, types, and symbolsfor the resource manager facilities, which aredescribed in chapter 15. <X11/Xlib.h> must be includedbefore including this file.• <X11/Xatom.h>This file declares all predefined atoms, which aresymbols with the prefix ‘‘XA_’’.• <X11/cursorfont.h>This file declares the cursor symbols for the standardcursor font, which are listed in appendix B. Allcursor symbols have the prefix ‘‘XC_’’.• <X11/keysymdef.h>This file declares all standard KeySym values, whichare symbols with the prefix ‘‘XK_’’. The KeySyms arearranged in groups, and a preprocessor symbol controlsinclusion of each group. The preprocessor symbol mustbe defined prior to inclusion of the file to obtain theassociated values. The preprocessor symbols areXK_MISCELLANY, XK_XKB_KEYS, XK_3270, XK_LATIN1,XK_LATIN2, XK_LATIN3, XK_LATIN4, XK_KATAKANA,XK_ARABIC, XK_CYRILLIC, XK_GREEK, XK_TECHNICAL,XK_SPECIAL, XK_PUBLISHING, XK_APL, XK_HEBREW, XK_THAI,and XK_KOREAN.• <X11/keysym.h>This file defines the preprocessor symbolsXK_MISCELLANY, XK_XKB_KEYS, XK_LATIN1, XK_LATIN2,XK_LATIN3, XK_LATIN4, and XK_GREEK and then includes<X11/keysymdef.h>.• <X11/Xlibint.h>This file declares all the functions, types, andsymbols used for extensions, which are described inappendix C. This file automatically includes<X11/Xlib.h>.• <X11/Xproto.h>This file declares types and symbols for the basic Xprotocol, for use in implementing extensions. It isincluded automatically from <X11/Xlibint.h>, soapplication and extension code should never need toreference this file directly.• <X11/Xprotostr.h>This file declares types and symbols for the basic Xprotocol, for use in implementing extensions. It isincluded automatically from <X11/Xproto.h>, soapplication and extension code should never need toreference this file directly.• <X11/X10.h>This file declares all the functions, types, andsymbols used for the X10 compatibility functions, whichare described in appendix D.1.4. Generic Values and TypesThe following symbols are defined by Xlib and usedthroughout the manual:• Xlib defines the type Bool and the Boolean values Trueand False.• None is the universal null resource ID or atom.• The type XID is used for generic resource IDs.• The type XPointer is defined to be char* and is used asa generic opaque pointer to data.1.5. Naming and Argument Conventions within XlibXlib follows a number of conventions for the naming andsyntax of the functions. Given that you remember whatinformation the function requires, these conventions areintended to make the syntax of the functions morepredictable.The major naming conventions are:• To differentiate the X symbols from the other symbols,the library uses mixed case for external symbols. Itleaves lowercase for variables and all uppercase foruser macros, as per existing convention.• All Xlib functions begin with a capital X.• The beginnings of all function names and symbols arecapitalized.• All user-visible data structures begin with a capitalX. More generally, anything that a user mightdereference begins with a capital X.• Macros and other symbols do not begin with a capital X.To distinguish them from all user symbols, each word inthe macro is capitalized.• All elements of or variables in a data structure arein lowercase. Compound words, where needed, areconstructed with underscores (_).• The display argument, where used, is always first inthe argument list.• All resource objects, where used, occur at thebeginning of the argument list immediately after thedisplay argument.• When a graphics context is present together withanother type of resource (most commonly, a drawable),the graphics context occurs in the argument list afterthe other resource. Drawables outrank all otherresources.• Source arguments always precede the destinationarguments in the argument list.• The x argument always precedes the y argument in theargument list.• The width argument always precedes the height argumentin the argument list.• Where the x, y, width, and height arguments are usedtogether, the x and y arguments always precede thewidth and height arguments.• Where a mask is accompanied with a structure, the maskalways precedes the pointer to the structure in theargument list.1.6. Programming ConsiderationsThe major programming considerations are:• Coordinates and sizes in X are actually 16-bitquantities. This decision was made to minimize thebandwidth required for a given level of performance.Coordinates usually are declared as an int in theinterface. Values larger than 16 bits are truncatedsilently. Sizes (width and height) are declared asunsigned quantities.• Keyboards are the greatest variable between differentmanufacturers’ workstations. If you want your programto be portable, you should be particularly conservativehere.• Many display systems have limited amounts of off-screenmemory. If you can, you should minimize use of pixmapsand backing store.• The user should have control of his screen real estate.Therefore, you should write your applications to reactto window management rather than presume control of theentire screen. What you do inside of your top-levelwindow, however, is up to your application. Forfurther information, see chapter 14 and theInter-Client Communication Conventions Manual.1.7. Character Sets and EncodingsSome of the Xlib functions make reference to specificcharacter sets and character encodings. The following arethe most common:• X Portable Character SetA basic set of 97 characters, which are assumed toexist in all locales supported by Xlib. This setcontains the following characters:a..z A..Z 0..9!"#$%&’()*+,-./:;<=>?@[\]^_‘{|}~<space>, <tab>, and <newline>This set is the left/lower half of the graphiccharacter set of ISO8859-1 plus space, tab, andnewline. It is also the set of graphic characters in7-bit ASCII plus the same three control characters.The actual encoding of these characters on the host issystem dependent.• Host Portable Character EncodingThe encoding of the X Portable Character Set on thehost. The encoding itself is not defined by thisstandard, but the encoding must be the same in alllocales supported by Xlib on the host. If a string issaid to be in the Host Portable Character Encoding,then it only contains characters from the X PortableCharacter Set, in the host encoding.• Latin-1The coded character set defined by the ISO 8859-1standard.• Latin Portable Character EncodingThe encoding of the X Portable Character Set using theLatin-1 codepoints plus ASCII control characters. If astring is said to be in the Latin Portable CharacterEncoding, then it only contains characters from the XPortable Character Set, not all of Latin-1.• STRING EncodingLatin-1, plus tab and newline.• UTF-8 EncodingThe ASCII compatible character encoding scheme definedby the ISO 10646-1 standard.• POSIX Portable Filename Character SetThe set of 65 characters, which can be used in namingfiles on a POSIX-compliant host, that are correctlyprocessed in all locales. The set is:a..z A..Z 0..9 ._-1.8. Formatting ConventionsXlib − C Language X Interface uses the followingconventions:• Global symbols are printed in this special font. Thesecan be either function names, symbols defined ininclude files, or structure names. When declared anddefined, function arguments are printed in italics. Inthe explanatory text that follows, they usually areprinted in regular type.• Each function is introduced by a general discussionthat distinguishes it from other functions. Thefunction declaration itself follows, and each argumentis specifically explained. Although ANSI C functionprototype syntax is not used, Xlib header filesnormally declare functions using function prototypes inANSI C environments. General discussion of thefunction, if any is required, follows the arguments.Where applicable, the last paragraph of the explanationlists the possible Xlib error codes that the functioncan generate. For a complete discussion of the Xliberror codes, see section 11.8.2.• To eliminate any ambiguity between those arguments thatyou pass and those that a function returns to you, theexplanations for all arguments that you pass start withthe word specifies or, in the case of multiplearguments, the word specify. The explanations for allarguments that are returned to you start with the wordreturns or, in the case of multiple arguments, the wordreturn. The explanations for all arguments that youcan pass and are returned start with the wordsspecifies and returns.• Any pointer to a structure that is used to return avalue is designated as such by the _return suffix aspart of its name. All other pointers passed to thesefunctions are used for reading only. A few argumentsuse pointers to structures that are used for both inputand output and are indicated by using the _in_outsuffix. 1
2.1. Opening the DisplayTo open a connection to the X server that controls adisplay, use XOpenDisplay.__│ Display *XOpenDisplay(display_name)char *display_name;display_nameSpecifies the hardware display name, whichdetermines the display and communications domainto be used. On a POSIX-conformant system, if thedisplay_name is NULL, it defaults to the value ofthe DISPLAY environment variable.│__ The encoding and interpretation of the display name areimplementation-dependent. Strings in the Host PortableCharacter Encoding are supported; support for othercharacters is implementation-dependent. On POSIX-conformantsystems, the display name or DISPLAY environment variablecan be a string in the format:__│ protocol/hostname:number.screen_numberprotocol Specifies a protocol family or an alias for aprotocol family. Supported protocol families areimplementation dependent. The protocol entry isoptional. If protocol is not specified, the /separating protocol and hostname must also not bespecified.hostname Specifies the name of the host machine on whichthe display is physically attached. You followthe hostname with either a single colon (:) or adouble colon (::).number Specifies the number of the display server on thathost machine. You may optionally follow thisdisplay number with a period (.). A single CPUcan have more than one display. Multiple displaysare usually numbered starting with zero.screen_numberSpecifies the screen to be used on that server.Multiple screens can be controlled by a single Xserver. The screen_number sets an internalvariable that can be accessed by using theDefaultScreen macro or the XDefaultScreen functionif you are using languages other than C (seesection 2.2.1).│__ For example, the following would specify screen 1 of display0 on the machine named ‘‘dual-headed’’:dual-headed:0.1The XOpenDisplay function returns a Display structure thatserves as the connection to the X server and that containsall the information about that X server. XOpenDisplayconnects your application to the X server through TCP orDECnet communications protocols, or through some localinter-process communication protocol. If the protocol isspecified as "tcp", "inet", or "inet6", or if no protocol isspecified and the hostname is a host machine name and asingle colon (:) separates the hostname and display number,XOpenDisplay connects using TCP streams. (If the protocolis specified as "inet", TCP over IPv4 is used. If theprotocol is specified as "inet6", TCP over IPv6 is used.Otherwise, the implementation determines which IP version isused.) If the hostname and protocol are both not specified,Xlib uses whatever it believes is the fastest transport. Ifthe hostname is a host machine name and a double colon (::)separates the hostname and display number, XOpenDisplayconnects using DECnet. A single X server can support any orall of these transport mechanisms simultaneously. Aparticular Xlib implementation can support many more ofthese transport mechanisms.If successful, XOpenDisplay returns a pointer to a Displaystructure, which is defined in <X11/Xlib.h>. IfXOpenDisplay does not succeed, it returns NULL. After asuccessful call to XOpenDisplay, all of the screens in thedisplay can be used by the client. The screen numberspecified in the display_name argument is returned by theDefaultScreen macro (or the XDefaultScreen function). Youcan access elements of the Display and Screen structuresonly by using the information macros or functions. Forinformation about using macros and functions to obtaininformation from the Display structure, see section 2.2.1.X servers may implement various types of access controlmechanisms (see section 9.8).2.2. Obtaining Information about the Display, ImageFormats, or ScreensThe Xlib library provides a number of useful macros andcorresponding functions that return data from the Displaystructure. The macros are used for C programming, and theircorresponding function equivalents are for other languagebindings. This section discusses the:• Display macros• Image format functions and macros• Screen information macrosAll other members of the Display structure (that is, thosefor which no macros are defined) are private to Xlib andmust not be used. Applications must never directly modifyor inspect these private members of the Display structure.NoteThe XDisplayWidth, XDisplayHeight, XDisplayCells,XDisplayPlanes, XDisplayWidthMM, andXDisplayHeightMM functions in the next sectionsare misnamed. These functions really should benamed Screenwhatever and XScreenwhatever, notDisplaywhatever or XDisplaywhatever. Ourapologies for the resulting confusion.2.2.1. Display MacrosApplications should not directly modify any part of theDisplay and Screen structures. The members should beconsidered read-only, although they may change as the resultof other operations on the display.The following lists the C language macros, theircorresponding function equivalents that are for otherlanguage bindings, and what data both can return.__│ AllPlanesunsigned long XAllPlanes()│__ Both return a value with all bits set to 1 suitable for usein a plane argument to a procedure.Both BlackPixel and WhitePixel can be used in implementing amonochrome application. These pixel values are forpermanently allocated entries in the default colormap. Theactual RGB (red, green, and blue) values are settable onsome screens and, in any case, may not actually be black orwhite. The names are intended to convey the expectedrelative 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_numberSpecifies the appropriate screen number on thehost server.│__ Both return the black pixel value for the specified screen.__│ WhitePixel(display, screen_number)unsigned long XWhitePixel(display, screen_number)Display *display;int screen_number;display Specifies the connection to the X server.screen_numberSpecifies the appropriate screen number on thehost 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 ofthe connection.__│ DefaultColormap(display, screen_number)Colormap XDefaultColormap(display, screen_number)Display *display;int screen_number;display Specifies the connection to the X server.screen_numberSpecifies the appropriate screen number on thehost server.│__ Both return the default colormap ID for allocation on thespecified screen. Most routine allocations of color shouldbe made out of this colormap.__│ DefaultDepth(display, screen_number)int XDefaultDepth(display, screen_number)Display *display;int screen_number;display Specifies the connection to the X server.screen_numberSpecifies the appropriate screen number on thehost server.│__ Both return the depth (number of planes) of the default rootwindow for the specified screen. Other depths may also besupported on this screen (see XMatchVisualInfo).To determine the number of depths that are available on agiven 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_numberSpecifies the appropriate screen number on thehost server.count_returnReturns the number of depths.│__ The XListDepths function returns the array of depths thatare available on the specified screen. If the specifiedscreen_number is valid and sufficient memory for the arraycan be allocated, XListDepths sets count_return to thenumber of available depths. Otherwise, it does not setcount_return and returns NULL. To release the memoryallocated for the array of depths, use XFree.__│ DefaultGC(display, screen_number)GC XDefaultGC(display, screen_number)Display *display;int screen_number;display Specifies the connection to the X server.screen_numberSpecifies the appropriate screen number on thehost server.│__ Both return the default graphics context for the root windowof the specified screen. This GC is created for theconvenience of simple applications and contains the defaultGC components with the foreground and background pixelvalues initialized to the black and white pixels for thescreen, respectively. You can modify its contents freelybecause it is not used in any Xlib function. This GC shouldnever 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.__│ ScreenOfDisplay(display, screen_number)Screen *XScreenOfDisplay(display, screen_number)Display *display;int screen_number;display Specifies the connection to the X server.screen_numberSpecifies the appropriate screen number on thehost 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 theXOpenDisplay function. This macro or function should beused to retrieve the screen number in applications that willuse 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_numberSpecifies the appropriate screen number on thehost server.│__ Both return the default visual type for the specifiedscreen. For further information about visual types, seesection 3.1.__│ DisplayCells(display, screen_number)int XDisplayCells(display, screen_number)Display *display;int screen_number;display Specifies the connection to the X server.screen_numberSpecifies the appropriate screen number on thehost 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_numberSpecifies the appropriate screen number on thehost server.│__ Both return the depth of the root window of the specifiedscreen. 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 whenthe current display was opened. On POSIX-conformantsystems, if the passed string was NULL, these return thevalue of the DISPLAY environment variable when the currentdisplay was opened. These are useful to applications thatinvoke the fork system call and want to open a newconnection to the same display from the child process aswell as for printing error messages.__│ long XExtendedMaxRequestSize(display)Display *display;display Specifies the connection to the X server.│__ The XExtendedMaxRequestSize function returns zero if thespecified display does not support an extended-lengthprotocol encoding; otherwise, it returns the maximum requestsize (in 4-byte units) supported by the server using theextended-length encoding. The Xlib functions XDrawLines,XDrawArcs, XFillPolygon, XChangeProperty,XSetClipRectangles, and XSetRegion will use theextended-length encoding as necessary, if supported by theserver. Use of the extended-length encoding in other Xlibfunctions (for example, XDrawPoints, XDrawRectangles,XDrawSegments, XFillArcs, XFillRectangles, XPutImage) ispermitted but not required; an Xlib implementation maychoose to split the data across multiple smaller requestsinstead.__│ long XMaxRequestSize(display)Display *display;display Specifies the connection to the X server.│__ The XMaxRequestSize function returns the maximum requestsize (in 4-byte units) supported by the server without usingan extended-length protocol encoding. Single protocolrequests to the server can be no larger than this sizeunless an extended-length protocol encoding is supported bythe server. The protocol guarantees the size to be nosmaller than 4096 units (16384 bytes). Xlib automaticallybreaks data up into multiple protocol requests as necessaryfor the following functions: XDrawPoints, XDrawRectangles,XDrawSegments, XFillArcs, XFillRectangles, and XPutImage.__│ 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 requestknown by Xlib to have been processed by the X server. Xlibautomatically sets this number when replies, events, anderrors 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 forthe next request. Serial numbers are maintained separatelyfor 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 protocolassociated with the connected display.__│ ProtocolRevision(display)int XProtocolRevision(display)Display *display;display Specifies the connection to the X server.│__ Both return the minor protocol revision number of the Xserver.__│ 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 connecteddisplay. Note that there may be more events that have notbeen 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_numberSpecifies the appropriate screen number on thehost server.│__ Both return the root window. These are useful withfunctions that need a drawable of a particular screen andfor creating top-level windows.__│ 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 thatprovides some identification of the owner of the X serverimplementation. If the data returned by the server is inthe Latin Portable Character Encoding, then the string is inthe Host Portable Character Encoding. Otherwise, thecontents 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 Xserver.2.2.2. Image Format Functions and MacrosApplications are required to present data to the X server ina format that the server demands. To help simplifyapplications, most of the work required to convert the datais provided by Xlib (see sections 8.7 and 16.8).The XPixmapFormatValues structure provides an interface tothe pixmap format information that is returned at the timeof 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_returnReturns the number of pixmap formats that aresupported by the display.│__ The XListPixmapFormats function returns an array ofXPixmapFormatValues structures that describe the types of Zformat images supported by the specified display. Ifinsufficient memory is available, XListPixmapFormats returnsNULL. To free the allocated storage for theXPixmapFormatValues structures, use XFree.The following lists the C language macros, theircorresponding function equivalents that are for otherlanguage bindings, and what data they both return for thespecified server and screen. These are often used bytoolkits as well as by simple applications.__│ ImageByteOrder(display)int XImageByteOrder(display)Display *display;display Specifies the connection to the X server.│__ Both specify the required byte order for images for eachscanline unit in XY format (bitmap) or for each pixel valuein Z format. The macro or function can return eitherLSBFirst 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 asdisplayed on the screen is either the least significant ormost significant bit in the unit. This macro or functioncan return LSBFirst or MSBFirst.__│ 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 returnedby 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_numberSpecifies the appropriate screen number on thehost server.│__ Both return an integer that describes the height of thescreen 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_numberSpecifies the appropriate screen number on thehost server.│__ Both return the height of the specified screen inmillimeters.__│ DisplayWidth(display, screen_number)int XDisplayWidth(display, screen_number)Display *display;int screen_number;display Specifies the connection to the X server.screen_numberSpecifies the appropriate screen number on thehost 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_numberSpecifies the appropriate screen number on thehost server.│__ Both return the width of the specified screen inmillimeters.2.2.3. Screen Information MacrosThe following lists the C language macros, theircorresponding function equivalents that are for otherlanguage bindings, and what data they both can return.These macros or functions all take a pointer to theappropriate screen structure.__│ 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 defaultcolormap 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.__│ 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 specifiedscreen, which has the same depth as the root window of thescreen. 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. Forinformation on visual types, see section 3.1.__│ DoesBackingStore(screen)int XDoesBackingStore(screen)Screen *screen;screen Specifies the appropriate Screen structure.│__ Both return a value indicating whether the screen supportsbacking stores. The value returned can be one ofWhenMapped, 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 screensupports save unders. If True, the screen supports saveunders. 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.__│ int XScreenNumberOfScreen(screen)Screen *screen;screen Specifies the appropriate Screen structure.│__ The XScreenNumberOfScreen function returns the screen indexnumber 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 thespecified 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.__│ WidthMMOfScreen(screen)int XWidthMMOfScreen(screen)Screen *screen;screen Specifies the appropriate Screen structure.│__ Both return the width of the specified screen inmillimeters.__│ HeightMMOfScreen(screen)int XHeightMMOfScreen(screen)Screen *screen;screen Specifies the appropriate Screen structure.│__ Both return the height of the specified screen inmillimeters.__│ MaxCmapsOfScreen(screen)int XMaxCmapsOfScreen(screen)Screen *screen;screen Specifies the appropriate Screen structure.│__ Both return the maximum number of installed colormapssupported by the specified screen (see section 9.3).__│ MinCmapsOfScreen(screen)int XMinCmapsOfScreen(screen)Screen *screen;screen Specifies the appropriate Screen structure.│__ Both return the minimum number of installed colormapssupported 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 RequestTo 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 tothe X server, thereby exercising the connection.2.4. Freeing Client-Created DataTo 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 thatfrees the specified data. You must use it to free anyobjects that were allocated by Xlib, unless an alternatefunction is explicitly specified for the object. A NULLpointer cannot be passed to this function.2.5. Closing the DisplayTo close a display or disconnect from the X server, useXCloseDisplay.__│ XCloseDisplay(display)Display *display;display Specifies the connection to the X server.│__ The XCloseDisplay function closes the connection to the Xserver for the display specified in the Display structureand destroys all windows, resource IDs (Window, Font,Pixmap, Colormap, Cursor, and GContext), or other resourcesthat the client has created on this display, unless theclose-down mode of the resource has been changed (seeXSetCloseDownMode). Therefore, these windows, resource IDs,and other resources should never be referenced again or anerror will be generated. Before exiting, you should callXCloseDisplay explicitly so that any pending errors arereported as XCloseDisplay performs a final XSync operation.XCloseDisplay can generate a BadGC error.Xlib provides a function to permit the resources owned by aclient to survive after the client’s connection is closed.To change a client’s close-down mode, use XSetCloseDownMode.__│ XSetCloseDownMode(display, close_mode)Display *display;int close_mode;display Specifies the connection to the X server.close_modeSpecifies the client close-down mode. You canpass DestroyAll, RetainPermanent, orRetainTemporary.│__ The XSetCloseDownMode defines what will happen to theclient’s resources at connection close. A connection startsin DestroyAll mode. For information on what happens to theclient’s resources when the close_mode argument isRetainPermanent or RetainTemporary, see section 2.6.XSetCloseDownMode can generate a BadValue error.2.6. Using X Server Connection Close OperationsWhen the X server’s connection to a client is closed eitherby an explicit call to XCloseDisplay or by a process thatexits, the X server performs the following automaticoperations:• It disowns all selections owned by the client (seeXSetSelectionOwner).• It performs an XUngrabPointer and XUngrabKeyboard ifthe client has actively grabbed the pointer or thekeyboard.• It performs an XUngrabServer if the client has grabbedthe server.• It releases all passive grabs made by the client.• It marks all resources (including colormap entries)allocated by the client either as permanent ortemporary, depending on whether the close-down mode isRetainPermanent or RetainTemporary. However, this doesnot prevent other client applications from explicitlydestroying the resources (see XSetCloseDownMode).When the close-down mode is DestroyAll, the X serverdestroys all of a client’s resources as follows:• It examines each window in the client’s save-set todetermine if it is an inferior (subwindow) of a windowcreated by the client. (The save-set is a list ofother clients’ windows that are referred to as save-setwindows.) If so, the X server reparents the save-setwindow to the closest ancestor so that the save-setwindow is not an inferior of a window created by theclient. The reparenting leaves unchanged the absolutecoordinates (with respect to the root window) of theupper-left outer corner of the save-set window.• It performs a MapWindow request on the save-set windowif the save-set window is unmapped. The X server doesthis even if the save-set window was not an inferior ofa window created by the client.• It destroys all windows created by the client.• It performs the appropriate free request on eachnonwindow resource created by the client in the server(for example, Font, Pixmap, Cursor, Colormap, andGContext).• It frees all colors and colormap entries allocated by aclient application.Additional processing occurs when the last connection to theX server closes. An X server goes through a cycle of havingno connections and having some connections. When the lastconnection to the X server closes as a result of aconnection closing with the close_mode of DestroyAll, the Xserver does the following:• It resets its state as if it had just been started.The X server begins by destroying all lingeringresources from clients that have terminated inRetainPermanent or RetainTemporary mode.• It deletes all but the predefined atom identifiers.• It deletes all properties on all root windows (seesection 4.3).• It resets all device maps and attributes (for example,key click, bell volume, and acceleration) as well asthe access control list.• It restores the standard root tiles and cursors.• It restores the default font path.• It restores the input focus to state PointerRoot.However, the X server does not reset if you close aconnection with a close-down mode set to RetainPermanent orRetainTemporary.2.7. Using Xlib with ThreadsOn systems that have threads, support may be provided topermit multiple threads to use Xlib concurrently.To initialize support for concurrent threads, useXInitThreads.__│ Status XInitThreads();│__ The XInitThreads function initializes Xlib support forconcurrent threads. This function must be the first Xlibfunction a multi-threaded program calls, and it mustcomplete before any other Xlib call is made. This functionreturns a nonzero status if initialization was successful;otherwise, it returns zero. On systems that do not supportthreads, this function always returns zero.It is only necessary to call this function if multiplethreads might use Xlib concurrently. If all calls to Xlibfunctions are protected by some other access mechanism (forexample, a mutual exclusion lock in a toolkit or throughexplicit client programming), Xlib thread initialization isnot required. It is recommended that single-threadedprograms not call this function.To lock a display across several Xlib calls, useXLockDisplay.__│ void XLockDisplay(display)Display *display;display Specifies the connection to the X server.│__ The XLockDisplay function locks out all other threads fromusing the specified display. Other threads attempting touse the display will block until the display is unlocked bythis thread. Nested calls to XLockDisplay work correctly;the display will not actually be unlocked untilXUnlockDisplay has been called the same number of times asXLockDisplay. This function has no effect unless Xlib wassuccessfully initialized for threads using XInitThreads.To unlock a display, use XUnlockDisplay.__│ void XUnlockDisplay(display)Display *display;display Specifies the connection to the X server.│__ The XUnlockDisplay function allows other threads to use thespecified display again. Any threads that have blocked onthe display are allowed to continue. Nested locking workscorrectly; if XLockDisplay has been called multiple times bya thread, then XUnlockDisplay must be called an equal numberof times before the display is actually unlocked. Thisfunction has no effect unless Xlib was successfullyinitialized for threads using XInitThreads.2.8. Using Internal ConnectionsIn addition to the connection to the X server, an Xlibimplementation may require connections to other kinds ofservers (for example, to input method servers as describedin chapter 13). Toolkits and clients that use multipledisplays, or that use displays in combination with otherinputs, need to obtain these additional connections tocorrectly block until input is available and need to processthat input when it is available. Simple clients that use asingle display and block for input in an Xlib event functiondo not need to use these facilities.To track internal connections for a display, useXAddConnectionWatch.__│ 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_dataSpecifies the additional client data.│__ The XAddConnectionWatch function registers a procedure to becalled each time Xlib opens or closes an internal connectionfor the specified display. The procedure is passed thedisplay, the specified client_data, the file descriptor forthe connection, a Boolean indicating whether the connectionis being opened or closed, and a pointer to a location forprivate watch data. If opening is True, the procedure canstore a pointer to private data in the location pointed toby watch_data; when the procedure is later called for thissame connection and opening is False, the location pointedto by watch_data will hold this same private data pointer.This function can be called at any time after a display isopened. If internal connections already exist, theregistered procedure will immediately be called for each ofthem, before XAddConnectionWatch returns.XAddConnectionWatch returns a nonzero status if theprocedure is successfully registered; otherwise, it returnszero.The registered procedure should not call any Xlib functions.If the procedure directly or indirectly causes the state ofinternal connections or watch procedures to change, theresult is not defined. If Xlib has been initialized forthreads, the procedure is called with the display locked andthe result of a call by the procedure to any Xlib functionthat locks the display is not defined unless the executingthread has externally locked the display using XLockDisplay.To stop tracking internal connections for a display, useXRemoveConnectionWatch.__│ 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_dataSpecifies the additional client data.│__ The XRemoveConnectionWatch function removes a previouslyregistered connection watch procedure. The client_data mustmatch the client_data used when the procedure was initiallyregistered.To process input on an internal connection, useXProcessInternalConnection.__│ 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 inputavailable on an internal connection. This function shouldbe called for an internal connection only after an operatingsystem facility (for example, select or poll) has indicatedthat input is available; otherwise, the effect is notdefined.To obtain all of the current internal connections for adisplay, use XInternalConnectionNumbers.__│ 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_returnReturns the number of file descriptors.│__ The XInternalConnectionNumbers function returns a list ofthe file descriptors for all internal connections currentlyopen for the specified display. When the allocated list isno longer needed, free it by using XFree. This functionsreturns a nonzero status if the list is successfullyallocated; otherwise, it returns zero.2
3.1. Visual TypesOn some display hardware, it may be possible to deal withcolor resources in more than one way. For example, you maybe able to deal with a screen of either 12-bit depth witharbitrary mapping of pixel to color (pseudo-color) or 24-bitdepth with 8 bits of the pixel dedicated to each of red,green, and blue. These different ways of dealing with thevisual aspects of the screen are called visuals. For eachscreen of the display, there may be a list of valid visualtypes supported at different depths of the screen. Becausedefault windows and visual types are defined for eachscreen, most simple applications need not deal with thiscomplexity. Xlib provides macros and functions that returnthe default root window, the default depth of the defaultroot window, and the default visual type (see sections 2.2.1and 16.7).Xlib uses an opaque Visual structure that containsinformation about the possible color mapping. The visualutility functions (see section 16.7) use an XVisualInfostructure to return this information to an application. Themembers of this structure pertinent to this discussion areclass, red_mask, green_mask, blue_mask, bits_per_rgb, andcolormap_size. The class member specifies one of thepossible visual classes of the screen and can be StaticGray,StaticColor, TrueColor, GrayScale, PseudoColor, orDirectColor.The following concepts may serve to make the explanation ofvisual types clearer. The screen can be color or grayscale,can have a colormap that is writable or read-only, and canalso have a colormap whose indices are decomposed intoseparate RGB pieces, provided one is not on a grayscalescreen. This leads to the following diagram:Conceptually, as each pixel is read out of video memory fordisplay on the screen, it goes through a look-up stage byindexing into a colormap. Colormaps can be manipulatedarbitrarily on some hardware, in limited ways on otherhardware, and not at all on other hardware. The visualtypes affect the colormap and the RGB values in thefollowing ways:• For PseudoColor, a pixel value indexes a colormap toproduce independent RGB values, and the RGB values canbe changed dynamically.• GrayScale is treated the same way as PseudoColor exceptthat the primary that drives the screen is undefined.Thus, the client should always store the same value forred, green, and blue in the colormaps.• For DirectColor, a pixel value is decomposed intoseparate RGB subfields, and each subfield separatelyindexes the colormap for the corresponding value. TheRGB values can be changed dynamically.• TrueColor is treated the same way as DirectColor exceptthat the colormap has predefined, read-only RGB values.These RGB values are server dependent but providelinear or near-linear ramps in each primary.• StaticColor is treated the same way as PseudoColorexcept that the colormap has predefined, read-only,server-dependent RGB values.• StaticGray is treated the same way as StaticColorexcept that the RGB values are equal for any singlepixel value, thus resulting in shades of gray.StaticGray with a two-entry colormap can be thought ofas monochrome.The red_mask, green_mask, and blue_mask members are onlydefined for DirectColor and TrueColor. Each has onecontiguous set of bits with no intersections. Thebits_per_rgb member specifies the log base 2 of the numberof distinct color values (individually) of red, green, andblue. Actual RGB values are unsigned 16-bit numbers. Thecolormap_size member defines the number of availablecolormap entries in a newly created colormap. ForDirectColor and TrueColor, this is the size of an individualpixel subfield.To obtain the visual ID from a Visual, useXVisualIDFromVisual.__│ VisualID XVisualIDFromVisual(visual)Visual *visual;visual Specifies the visual type.│__ The XVisualIDFromVisual function returns the visual ID forthe specified visual type.3.2. Window AttributesAll InputOutput windows have a border width of zero or morepixels, an optional background, an event suppression mask(which suppresses propagation of events from children), anda property list (see section 4.3). The window border andbackground can be a solid color or a pattern, called a tile.All windows except the root have a parent and are clipped bytheir parent. If a window is stacked on top of anotherwindow, it obscures that other window for the purpose ofinput. If a window has a background (almost all do), itobscures the other window for purposes of output. Attemptsto output to the obscured area do nothing, and no inputevents (for example, pointer motion) are generated for theobscured area.Windows also have associated property lists (see section4.3).Both InputOutput and InputOnly windows have the followingcommon attributes, which are the only attributes of anInputOnly window:• win-gravity• event-mask• do-not-propagate-mask• override-redirect• cursorIf you specify any other attributes for an InputOnly window,a BadMatch error results.InputOnly windows are used for controlling input events insituations where InputOutput windows are unnecessary.InputOnly windows are invisible; can only be used to controlsuch things as cursors, input event generation, andgrabbing; and cannot be used in any graphics requests. Notethat InputOnly windows cannot have InputOutput windows asinferiors.Windows have borders of a programmable width and pattern aswell as a background pattern or tile. Pixel values can beused for solid colors. The background and border pixmapscan be destroyed immediately after creating the window if nofurther explicit references to them are to be made. Thepattern 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 (notmapped) on the screen. Any output to a window that is notvisible on the screen and that does not have backing storewill be discarded. An application may wish to create awindow long before it is mapped to the screen. When awindow is eventually mapped to the screen (usingXMapWindow), the X server generates an Expose event for thewindow if backing store has not been maintained.A window manager can override your choice of size, borderwidth, and position for a top-level window. Your programmust be prepared to use the actual size and position of thetop window. It is not acceptable for a client applicationto resize itself unless in direct response to a humancommand to do so. Instead, either your program should usethe space given to it, or if the space is too small for anyuseful work, your program might ask the user to resize thewindow. The border of your top-level window is consideredfair game for window managers.To set an attribute of a window, set the appropriate memberof the XSetWindowAttributes structure and OR in thecorresponding value bitmask in your subsequent calls toXCreateWindow and XChangeWindowAttributes, or use one of theother convenience functions that set the appropriateattribute. The symbols for the value mask bits and theXSetWindowAttributes structure are:__│ /* Window attribute value mask bits *//* 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 attributeand indicates whether the attribute is applicable toInputOutput and InputOnly windows:3.2.1. Background AttributeOnly InputOutput windows can have a background. You can setthe background of an InputOutput window by using a pixel ora pixmap.The background-pixmap attribute of a window specifies thepixmap to be used for a window’s background. This pixmapcan be of any size, although some sizes may be faster thanothers. The background-pixel attribute of a windowspecifies a pixel value used to paint a window’s backgroundin a single color.You can set the background-pixmap to a pixmap, None(default), or ParentRelative. You can set thebackground-pixel of a window to any pixel value (nodefault). If you specify a background-pixel, it overrideseither the default background-pixmap or any value you mayhave set in the background-pixmap. A pixmap of an undefinedsize that is filled with the background-pixel is used forthe background. Range checking is not performed on thebackground pixel; it simply is truncated to the appropriatenumber of bits.If you set the background-pixmap, it overrides the default.The background-pixmap and the window must have the samedepth, or a BadMatch error results. If you setbackground-pixmap to None, the window has no definedbackground. If you set the background-pixmap toParentRelative:• The parent window’s background-pixmap is used. Thechild window, however, must have the same depth as itsparent, or a BadMatch error results.• If the parent window has a background-pixmap of None,the window also has a background-pixmap of None.• A copy of the parent window’s background-pixmap is notmade. The parent’s background-pixmap is examined eachtime the child window’s background-pixmap is required.• The background tile origin always aligns with theparent window’s background tile origin. If thebackground-pixmap is not ParentRelative, the backgroundtile origin is the child window’s origin.Setting a new background, whether by settingbackground-pixmap or background-pixel, overrides anyprevious background. The background-pixmap can be freedimmediately if no further explicit reference is made to it(the X server will keep a copy to use when needed). If youlater draw into the pixmap used for the background, whathappens is undefined because the X implementation is free tomake a copy of the pixmap or to use the same pixmap.When no valid contents are available for regions of a windowand either the regions are visible or the server ismaintaining backing store, the server automatically tilesthe regions with the window’s background unless the windowhas a background of None. If the background is None, theprevious screen contents from other windows of the samedepth as the window are simply left in place as long as thecontents come from the parent of the window or an inferiorof the parent. Otherwise, the initial contents of theexposed regions are undefined. Expose events are thengenerated for the regions, even if the background-pixmap isNone (see section 10.9).3.2.2. Border AttributeOnly InputOutput windows can have a border. You can set theborder of an InputOutput window by using a pixel or apixmap.The border-pixmap attribute of a window specifies the pixmapto be used for a window’s border. The border-pixelattribute of a window specifies a pixmap of undefined sizefilled with that pixel be used for a window’s border. Rangechecking is not performed on the background pixel; it simplyis truncated to the appropriate number of bits. The bordertile origin is always the same as the background tileorigin.You can also set the border-pixmap to a pixmap of any size(some may be faster than others) or to CopyFromParent(default). You can set the border-pixel to any pixel value(no default).If you set a border-pixmap, it overrides the default. Theborder-pixmap and the window must have the same depth, or aBadMatch error results. If you set the border-pixmap toCopyFromParent, the parent window’s border-pixmap is copied.Subsequent changes to the parent window’s border attributedo not affect the child window. However, the child windowmust have the same depth as the parent window, or a BadMatcherror results.The border-pixmap can be freed immediately if no furtherexplicit reference is made to it. If you later draw intothe pixmap used for the border, what happens is undefinedbecause the X implementation is free either to make a copyof the pixmap or to use the same pixmap. If you specify aborder-pixel, it overrides either the default border-pixmapor any value you may have set in the border-pixmap. Allpixels in the window’s border will be set to theborder-pixel. Setting a new border, whether by settingborder-pixel or by setting border-pixmap, overrides anyprevious border.Output to a window is always clipped to the inside of thewindow. Therefore, graphics operations never affect thewindow border.3.2.3. Gravity AttributesThe bit gravity of a window defines which region of thewindow should be retained when an InputOutput window isresized. The default value for the bit-gravity attribute isForgetGravity. The window gravity of a window allows you todefine how the InputOutput or InputOnly window should berepositioned if its parent is resized. The default valuefor the win-gravity attribute is NorthWestGravity.If the inside width or height of a window is not changed andif the window is moved or its border is changed, then thecontents of the window are not lost but move with thewindow. Changing the inside width or height of the windowcauses its contents to be moved or lost (depending on thebit-gravity of the window) and causes children to bereconfigured (depending on their win-gravity). For a changeof width and height, the (x, y) pairs are defined:When a window with one of these bit-gravity values isresized, the corresponding pair defines the change inposition of each pixel in the window. When a window withone of these win-gravities has its parent window resized,the corresponding pair defines the change in position of thewindow 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 contentsor origin should not move relative to the origin of the rootwindow. If the change in size of the window is coupled witha change in position (x, y), then for bit-gravity the changein position of each pixel is (−x, −y), and for win-gravitythe change in position of a child when its parent is soresized is (−x, −y). Note that StaticGravity still onlytakes effect when the width or height of the window ischanged, not when the window is moved.A bit-gravity of ForgetGravity indicates that the window’scontents are always discarded after a size change, even if abacking store or save under has been requested. The windowis tiled with its background and zero or more Expose eventsare generated. If no background is defined, the existingscreen contents are not altered. Some X servers may alsoignore the specified bit-gravity and always generate Exposeevents.The contents and borders of inferiors are not affected bytheir parent’s bit-gravity. A server is permitted to ignorethe specified bit-gravity and use Forget instead.A win-gravity of UnmapGravity is like NorthWestGravity (thewindow is not moved), except the child is also unmapped whenthe parent is resized, and an UnmapNotify event isgenerated.3.2.4. Backing Store AttributeSome implementations of the X server may choose to maintainthe contents of InputOutput windows. If the X servermaintains the contents of a window, the off-screen savedpixels are known as backing store. The backing storeadvises the X server on what to do with the contents of awindow. The backing-store attribute can be set to NotUseful(default), WhenMapped, or Always.A backing-store attribute of NotUseful advises the X serverthat maintaining contents is unnecessary, although some Ximplementations may still choose to maintain contents and,therefore, not generate Expose events. A backing-storeattribute of WhenMapped advises the X server thatmaintaining contents of obscured regions when the window ismapped would be beneficial. In this case, the server maygenerate an Expose event when the window is created. Abacking-store attribute of Always advises the X server thatmaintaining contents even when the window is unmapped wouldbe beneficial. Even if the window is larger than itsparent, this is a request to the X server to maintaincomplete contents, not just the region within the parentwindow boundaries. While the X server maintains thewindow’s contents, Expose events normally are not generated,but the X server may stop maintaining contents at any time.When the contents of obscured regions of a window are beingmaintained, regions obscured by noninferior windows areincluded in the destination of graphics requests (andsource, when the window is the source). However, regionsobscured by inferior windows are not included.3.2.5. Save Under FlagSome server implementations may preserve contents ofInputOutput windows under other InputOutput windows. Thisis not the same as preserving the contents of a window foryou. You may get better visual appeal if transient windows(for example, pop-up menus) request that the system preservethe screen contents under them, so the temporarily obscuredapplications 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, whenthis window is mapped, saving the contents of windows itobscures would be beneficial.3.2.6. Backing Planes and Backing Pixel AttributesYou can set backing planes to indicate (with bits set to 1)which bit planes of an InputOutput window hold dynamic datathat must be preserved in backing store and during saveunders. The default value for the backing-planes attributeis all bits set to 1. You can set backing pixel to specifywhat bits to use in planes not covered by backing planes.The default value for the backing-pixel attribute is allbits set to 0. The X server is free to save only thespecified bit planes in the backing store or the save underand is free to regenerate the remaining planes with thespecified pixel value. Any extraneous bits in these values(that is, those bits beyond the specified depth of thewindow) may be simply ignored. If you request backing storeor save unders, you should use these members to minimize theamount of off-screen memory required to store your window.3.2.7. Event Mask and Do Not Propagate Mask AttributesThe event mask defines which events the client is interestedin for this InputOutput or InputOnly window (or, for someevent types, inferiors of this window). The event mask isthe bitwise inclusive OR of zero or more of the valid eventmask bits. You can specify that no maskable events arereported by setting NoEventMask (default).The do-not-propagate-mask attribute defines which eventsshould not be propagated to ancestor windows when no clienthas the event type selected in this InputOutput or InputOnlywindow. The do-not-propagate-mask is the bitwise inclusiveOR of zero or more of the following masks: KeyPress,KeyRelease, ButtonPress, ButtonRelease, PointerMotion,Button1Motion, Button2Motion, Button3Motion, Button4Motion,Button5Motion, and ButtonMotion. You can specify that allevents are propagated by setting NoEventMask (default).3.2.8. Override Redirect FlagTo control window placement or to add decoration, a windowmanager often needs to intercept (redirect) any map orconfigure request. Pop-up windows, however, often need tobe mapped without a window manager getting in the way. Tocontrol whether an InputOutput or InputOnly window is toignore these structure control facilities, use theoverride-redirect flag.The override-redirect flag specifies whether map andconfigure requests on this window should override aSubstructureRedirectMask on the parent. You can set theoverride-redirect flag to True or False (default). Windowmanagers use this information to avoid tampering with pop-upwindows (see also chapter 14).3.2.9. Colormap AttributeThe colormap attribute specifies which colormap bestreflects the true colors of the InputOutput window. Thecolormap must have the same visual type as the window, or aBadMatch error results. X servers capable of supportingmultiple hardware colormaps can use this information, andwindow managers can use it for calls to XInstallColormap.You can set the colormap attribute to a colormap or toCopyFromParent (default).If you set the colormap to CopyFromParent, the parentwindow’s colormap is copied and used by its child. However,the child window must have the same visual type as theparent, or a BadMatch error results. The parent window mustnot have a colormap of None, or a BadMatch error results.The colormap is copied by sharing the colormap objectbetween the child and parent, not by making a complete copyof the colormap contents. Subsequent changes to the parentwindow’s colormap attribute do not affect the child window.3.2.10. Cursor AttributeThe cursor attribute specifies which cursor is to be usedwhen 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 usedwhen the pointer is in the InputOutput or InputOnly window,and any change in the parent’s cursor will cause animmediate change in the displayed cursor. By callingXFreeCursor, the cursor can be freed immediately as long asno further explicit reference to it is made.3.3. Creating WindowsXlib provides basic ways for creating windows, and toolkitsoften supply higher-level functions specifically forcreating and placing top-level windows, which are discussedin the appropriate toolkit documentation. If you do not usea toolkit, however, you must provide some standardinformation or hints for the window manager by using theXlib inter-client communication functions (see chapter 14).If you use Xlib to create your own top-level windows (directchildren of the root window), you must observe the followingrules so that all applications interact reasonably acrossthe different styles of window management:• You must never fight with the window manager for thesize or placement of your top-level window.• You must be able to deal with whatever size window youget, even if this means that your application justprints a message like ‘‘Please make me bigger’’ in itswindow.• You should only attempt to resize or move top-levelwindows in direct response to a user request. If arequest to change the size of a top-level window fails,you must be prepared to live with what you get. Youare free to resize or move the children of top-levelwindows as necessary. (Toolkits often have facilitiesfor automatic relayout.)• If you do not use a toolkit that automatically setsstandard window properties, you should set theseproperties for top-level windows before mapping them.For further information, see chapter 14 and the Inter-ClientCommunication Conventions Manual.XCreateWindow is the more general function that allows youto set specific window attributes when you create a window.XCreateSimpleWindow creates a window that inherits itsattributes from its parent window.The X server acts as if InputOnly windows do not exist forthe purposes of graphics requests, exposure processing, andVisibilityNotify events. An InputOnly window cannot be usedas a drawable (that is, as a source or destination forgraphics requests). InputOnly and InputOutput windows actidentically in other respects (properties, grabs, inputcontrol, and so on). Extension packages can define otherclasses of windows.To create an unmapped window and set its window attributes,use XCreateWindow.__│ 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.xy Specify the x and y coordinates, which are thetop-left outside corner of the created window’sborders and are relative to the inside of theparent window’s borders.widthheight Specify the width and height, which are thecreated window’s inside dimensions and do notinclude the created window’s borders. Thedimensions must be nonzero, or a BadValue errorresults.border_widthSpecifies the width of the created window’s borderin pixels.depth Specifies the window’s depth. A depth ofCopyFromParent means the depth is taken from theparent.class Specifies the created window’s class. You canpass InputOutput, InputOnly, or CopyFromParent. Aclass of CopyFromParent means the class is takenfrom the parent.visual Specifies the visual type. A visual ofCopyFromParent means the visual type is taken fromthe parent.valuemask Specifies which window attributes are defined inthe attributes argument. This mask is the bitwiseinclusive OR of the valid attribute mask bits. Ifvaluemask is zero, the attributes are ignored andare not referenced.attributesSpecifies the structure from which the values (asspecified by the value mask) are to be taken. Thevalue mask should have the appropriate bits set toindicate which attributes have been set in thestructure.│__ The XCreateWindow function creates an unmapped subwindow fora specified parent window, returns the window ID of thecreated window, and causes the X server to generate aCreateNotify event. The created window is placed on top inthe stacking order with respect to siblings.The coordinate system has the X axis horizontal and the Yaxis vertical with the origin [0, 0] at the upper-leftcorner. Coordinates are integral, in terms of pixels, andcoincide with pixel centers. Each window and pixmap has itsown coordinate system. For a window, the origin is insidethe border at the inside, upper-left corner.The border_width for an InputOnly window must be zero, or aBadMatch error results. For class InputOutput, the visualtype and depth must be a combination supported for thescreen, or a BadMatch error results. The depth need not bethe same as the parent, but the parent must not be a windowof class InputOnly, or a BadMatch error results. For anInputOnly window, the depth must be zero, and the visualmust be one supported by the screen. If either condition isnot met, a BadMatch error results. The parent window,however, may have any depth and class. If you specify anyinvalid window attribute for a window, a BadMatch errorresults.The created window is not yet displayed (mapped) on theuser’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 callingXDefineCursor. The window will not be visible on the screenunless it and all of its ancestors are mapped and it is notobscured 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 givenparent window, use XCreateSimpleWindow.__│ 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.xy Specify the x and y coordinates, which are thetop-left outside corner of the new window’sborders and are relative to the inside of theparent window’s borders.widthheight Specify the width and height, which are thecreated window’s inside dimensions and do notinclude the created window’s borders. Thedimensions must be nonzero, or a BadValue errorresults.border_widthSpecifies the width of the created window’s borderin pixels.border Specifies the border pixel value of the window.backgroundSpecifies the background pixel value of thewindow.│__ The XCreateSimpleWindow function creates an unmappedInputOutput subwindow for a specified parent window, returnsthe window ID of the created window, and causes the X serverto generate a CreateNotify event. The created window isplaced on top in the stacking order with respect tosiblings. Any part of the window that extends outside itsparent window is clipped. The border_width for an InputOnlywindow must be zero, or a BadMatch error results.XCreateSimpleWindow inherits its depth, class, and visualfrom its parent. All other window attributes, exceptbackground and border, have their default values.XCreateSimpleWindow can generate BadAlloc, BadMatch,BadValue, and BadWindow errors.3.4. Destroying WindowsXlib provides functions that you can use to destroy a windowor destroy all subwindows of a window.To destroy a window and all of its subwindows, useXDestroyWindow.__│ 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 aswell as all of its subwindows and causes the X server togenerate a DestroyNotify event for each window. The windowshould never be referenced again. If the window specifiedby the w argument is mapped, it is unmapped automatically.The ordering of the DestroyNotify events is such that forany given window being destroyed, DestroyNotify is generatedon any inferiors of the window before being generated on thewindow itself. The ordering among siblings and acrosssubhierarchies is not otherwise constrained. If the windowyou specified is a root window, no windows are destroyed.Destroying a mapped window will generate Expose events onother windows that were obscured by the window beingdestroyed.XDestroyWindow can generate a BadWindow error.To destroy all subwindows of a specified window, useXDestroySubwindows.__│ XDestroySubwindows(display, w)Display *display;Window w;display Specifies the connection to the X server.w Specifies the window.│__ The XDestroySubwindows function destroys all inferiorwindows of the specified window, in bottom-to-top stackingorder. It causes the X server to generate a DestroyNotifyevent for each window. If any mapped subwindows wereactually destroyed, XDestroySubwindows causes the X serverto generate Expose events on the specified window. This ismuch more efficient than deleting many windows one at a timebecause much of the work need be performed only once for allof the windows, rather than for each window. The subwindowsshould never be referenced again.XDestroySubwindows can generate a BadWindow error.3.5. Mapping WindowsA window is considered mapped if an XMapWindow call has beenmade on it. It may not be visible on the screen for one ofthe following reasons:• It is obscured by another opaque window.• One of its ancestors is not mapped.• It is entirely clipped by an ancestor.Expose events are generated for the window when part or allof it becomes visible on the screen. A client receives theExpose events only if it has asked for them. Windows retaintheir position in the stacking order when they are unmapped.A window manager may want to control the placement ofsubwindows. If SubstructureRedirectMask has been selectedby a window manager on a parent window (usually a rootwindow), a map request initiated by other clients on a childwindow is not performed, and the window manager is sent aMapRequest event. However, if the override-redirect flag onthe child had been set to True (usually only on pop-upmenus), the map request is performed.A tiling window manager might decide to reposition andresize other clients’ windows and then decide to map thewindow to its final location. A window manager that wantsto provide decoration might reparent the child into a framefirst. For further information, see sections 3.2.8 and10.10. Only a single client at a time can select forSubstructureRedirectMask.Similarly, a single client can select for ResizeRedirectMaskon a parent window. Then, any attempt to resize the windowby another client is suppressed, and the client receives aResizeRequest event.To map a given window, use XMapWindow.__│ 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 itssubwindows that have had map requests. Mapping a windowthat has an unmapped ancestor does not display the windowbut marks it as eligible for display when the ancestorbecomes mapped. Such a window is called unviewable. Whenall its ancestors are mapped, the window becomes viewableand will be visible on the screen if it is not obscured byanother window. This function has no effect if the windowis already mapped.If the override-redirect of the window is False and if someother client has selected SubstructureRedirectMask on theparent window, then the X server generates a MapRequestevent, and the XMapWindow function does not map the window.Otherwise, the window is mapped, and the X server generatesa MapNotify event.If the window becomes viewable and no earlier contents forit are remembered, the X server tiles the window with itsbackground. If the window’s background is undefined, theexisting screen contents are not altered, and the X servergenerates zero or more Expose events. If backing-store wasmaintained while the window was unmapped, no Expose eventsare generated. If backing-store will now be maintained, afull-window exposure is always generated. Otherwise, onlyvisible regions may be reported. Similar tiling andexposure take place for any newly viewable inferiors.If the window is an InputOutput window, XMapWindow generatesExpose events on each InputOutput window that it causes tobe displayed. If the client maps and paints the window andif the client begins processing events, the window ispainted twice. To avoid this, first ask for Expose eventsand then map the window, so the client processes inputevents as usual. The event list will include Expose foreach window that has appeared on the screen. The client’snormal response to an Expose event should be to repaint thewindow. This method usually leads to simpler programs andto proper interaction with window managers.XMapWindow can generate a BadWindow error.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 XMapWindowin that it maps the window and all of its subwindows thathave had map requests. However, it also raises thespecified window to the top of the stack. For additionalinformation, see XMapWindow.XMapRaised can generate multiple BadWindow errors.To map all subwindows for a specified window, useXMapSubwindows.__│ 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 aspecified window in top-to-bottom stacking order. The Xserver generates Expose events on each newly displayedwindow. This may be much more efficient than mapping manywindows one at a time because the server needs to performmuch of the work only once, for all of the windows, ratherthan for each window.XMapSubwindows can generate a BadWindow error.3.6. Unmapping WindowsXlib provides functions that you can use to unmap a windowor all subwindows.To unmap a window, use XUnmapWindow.__│ 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 andcauses the X server to generate an UnmapNotify event. Ifthe specified window is already unmapped, XUnmapWindow hasno effect. Normal exposure processing on formerly obscuredwindows is performed. Any child window will no longer bevisible until another map call is made on the parent. Inother words, the subwindows are still mapped but are notvisible until the parent is mapped. Unmapping a window willgenerate Expose events on windows that were formerlyobscured by it.XUnmapWindow can generate a BadWindow error.To unmap all subwindows for a specified window, useXUnmapSubwindows.__│ 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 thespecified window in bottom-to-top stacking order. It causesthe X server to generate an UnmapNotify event on eachsubwindow and Expose events on formerly obscured windows.Using this function is much more efficient than unmappingmultiple windows one at a time because the server needs toperform 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 WindowsXlib provides functions that you can use to move a window,resize a window, move and resize a window, or change awindow’s border width. To change one of these parameters,set the appropriate member of the XWindowChanges structureand OR in the corresponding value mask in subsequent callsto XConfigureWindow. The symbols for the value mask bitsand the XWindowChanges structure are:__│ /* Configure window value mask bits *//* 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 ycoordinates, which are relative to the parent’s origin andindicate the position of the upper-left outer corner of thewindow. The width and height members are used to set theinside size of the window, not including the border, andmust be nonzero, or a BadValue error results. Attempts toconfigure a root window have no effect.The border_width member is used to set the width of theborder in pixels. Note that setting just the border widthleaves the outer-left corner of the window in a fixedposition but moves the absolute position of the window’sorigin. If you attempt to set the border-width attribute ofan InputOnly window nonzero, a BadMatch error results.The sibling member is used to set the sibling window forstacking operations. The stack_mode member is used to sethow 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 ifsome other client has selected SubstructureRedirectMask onthe parent, the X server generates a ConfigureRequest event,and no further processing is performed. Otherwise, if someother client has selected ResizeRedirectMask on the windowand the inside width or height of the window is beingchanged, a ResizeRequest event is generated, and the currentinside width and height are used instead. Note that theoverride-redirect flag of the window has no effect onResizeRedirectMask and that SubstructureRedirectMask on theparent has precedence over ResizeRedirectMask on the window.When the geometry of the window is changed as specified, thewindow is restacked among siblings, and a ConfigureNotifyevent is generated if the state of the window actuallychanges. GravityNotify events are generated afterConfigureNotify events. If the inside width or height ofthe window has actually changed, children of the window areaffected as specified.If a window’s size actually changes, the window’s subwindowsmove according to their window gravity. Depending on thewindow’s bit gravity, the contents of the window also may bemoved (see section 3.2.3).If regions of the window were obscured but now are not,exposure processing is performed on these formerly obscuredwindows, including the window itself and its inferiors. Asa result of increasing the width or height, exposureprocessing is also performed on any new regions of thewindow and any regions where window contents are lost.The restack check (specifically, the computation forBottomIf, TopIf, and Opposite) is performed with respect tothe window’s final size and position (as controlled by theother arguments of the request), not its initial position.If a sibling is specified without a stack_mode, a BadMatcherror results.If a sibling and a stack_mode are specified, the window isrestacked as follows:If a stack_mode is specified but no sibling is specified,the window is restacked as follows: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_maskSpecifies which values are to be set usinginformation in the values structure. This mask isthe bitwise inclusive OR of the valid configurewindow values bits.values Specifies the XWindowChanges structure.│__ The XConfigureWindow function uses the values specified inthe XWindowChanges structure to reconfigure a window’s size,position, border, and stacking order. Values not specifiedare taken from the existing geometry of the window.If a sibling is specified without a stack_mode or if thewindow is not actually a sibling, a BadMatch error results.Note that the computations for BottomIf, TopIf, and Oppositeare performed with respect to the window’s final geometry(as controlled by the other arguments passed toXConfigureWindow), not its initial geometry. Any backingstore contents of the window, its inferiors, and other newlyvisible windows are either discarded or changed to reflectthe current screen contents (depending on theimplementation).XConfigureWindow can generate BadMatch, BadValue, andBadWindow 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.xy Specify the x and y coordinates, which define thenew location of the top-left pixel of the window’sborder or the window itself if it has no border.│__ The XMoveWindow function moves the specified window to thespecified x and y coordinates, but it does not change thewindow’s size, raise the window, or change the mapping stateof the window. Moving a mapped window may or may not losethe window’s contents depending on if the window is obscuredby nonchildren and if no backing store exists. If thecontents of the window are lost, the X server generatesExpose events. Moving a mapped window generates Exposeevents on any formerly obscured windows.If the override-redirect flag of the window is False andsome other client has selected SubstructureRedirectMask onthe parent, the X server generates a ConfigureRequest event,and no further processing is performed. Otherwise, thewindow is moved.XMoveWindow can generate a BadWindow error.To change a window’s size without changing the upper-leftcoordinate, use XResizeWindow.__│ 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.widthheight Specify the width and height, which are theinterior dimensions of the window after the callcompletes.│__ The XResizeWindow function changes the inside dimensions ofthe specified window, not including its borders. Thisfunction does not change the window’s upper-left coordinateor the origin and does not restack the window. Changing thesize of a mapped window may lose its contents and generateExpose events. If a mapped window is made smaller, changingits size generates Expose events on windows that the mappedwindow formerly obscured.If the override-redirect flag of the window is False andsome other client has selected SubstructureRedirectMask onthe parent, the X server generates a ConfigureRequest event,and no further processing is performed. If either width orheight is zero, a BadValue error results.XResizeWindow can generate BadValue and BadWindow errors.To change the size and location of a window, useXMoveResizeWindow.__│ 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.xy Specify the x and y coordinates, which define thenew position of the window relative to its parent.widthheight Specify the width and height, which define theinterior size of the window.│__ The XMoveResizeWindow function changes the size and locationof the specified window without raising it. Moving andresizing a mapped window may generate an Expose event on thewindow. Depending on the new size and location parameters,moving and resizing a window may generate Expose events onwindows that the window formerly obscured.If the override-redirect flag of the window is False andsome other client has selected SubstructureRedirectMask onthe parent, the X server generates a ConfigureRequest event,and no further processing is performed. Otherwise, thewindow size and location are changed.XMoveResizeWindow can generate BadValue and BadWindowerrors.To change the border width of a given window, useXSetWindowBorderWidth.__│ 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 specifiedwindow’s border width to the specified width.XSetWindowBorderWidth can generate a BadWindow error.3.8. Changing Window Stacking OrderXlib provides functions that you can use to raise, lower,circulate, or restack windows.To raise a window so that no sibling window obscures it, useXRaiseWindow.__│ 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 thetop of the stack so that no sibling window obscures it. Ifthe windows are regarded as overlapping sheets of paperstacked on a desk, then raising a window is analogous tomoving the sheet to the top of the stack but leaving its xand y location on the desk constant. Raising a mappedwindow may generate Expose events for the window and anymapped subwindows that were formerly obscured.If the override-redirect attribute of the window is Falseand some other client has selected SubstructureRedirectMaskon the parent, the X server generates a ConfigureRequestevent, and no processing is performed. Otherwise, thewindow is raised.XRaiseWindow can generate a BadWindow error.To lower a window so that it does not obscure any siblingwindows, 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 thebottom of the stack so that it does not obscure any siblingwindows. If the windows are regarded as overlapping sheetsof paper stacked on a desk, then lowering a window isanalogous to moving the sheet to the bottom of the stack butleaving its x and y location on the desk constant. Loweringa mapped window will generate Expose events on any windowsit formerly obscured.If the override-redirect attribute of the window is Falseand some other client has selected SubstructureRedirectMaskon the parent, the X server generates a ConfigureRequestevent, and no processing is performed. Otherwise, thewindow is lowered to the bottom of the stack.XLowerWindow can generate a BadWindow error.To circulate a subwindow up or down, useXCirculateSubwindows.__│ 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 wantto circulate the window. You can pass RaiseLowestor LowerHighest.│__ The XCirculateSubwindows function circulates children of thespecified window in the specified direction. If you specifyRaiseLowest, XCirculateSubwindows raises the lowest mappedchild (if any) that is occluded by another child to the topof the stack. If you specify LowerHighest,XCirculateSubwindows lowers the highest mapped child (ifany) that occludes another child to the bottom of the stack.Exposure processing is then performed on formerly obscuredwindows. If some other client has selectedSubstructureRedirectMask on the window, the X servergenerates a CirculateRequest event, and no furtherprocessing is performed. If a child is actually restacked,the X server generates a CirculateNotify event.XCirculateSubwindows can generate BadValue and BadWindowerrors.To raise the lowest mapped child of a window that ispartially or completely occluded by another child, useXCirculateSubwindowsUp.__│ XCirculateSubwindowsUp(display, w)Display *display;Window w;display Specifies the connection to the X server.w Specifies the window.│__ The XCirculateSubwindowsUp function raises the lowest mappedchild of the specified window that is partially orcompletely occluded by another child. Completely unobscuredchildren are not affected. This is a convenience functionequivalent to XCirculateSubwindows with RaiseLowestspecified.XCirculateSubwindowsUp can generate a BadWindow error.To lower the highest mapped child of a window that partiallyor completely occludes another child, useXCirculateSubwindowsDown.__│ XCirculateSubwindowsDown(display, w)Display *display;Window w;display Specifies the connection to the X server.w Specifies the window.│__ The XCirculateSubwindowsDown function lowers the highestmapped child of the specified window that partially orcompletely occludes another child. Completely unobscuredchildren are not affected. This is a convenience functionequivalent to XCirculateSubwindows with LowerHighestspecified.XCirculateSubwindowsDown can generate a BadWindow error.To restack a set of windows from top to bottom, useXRestackWindows.__│ XRestackWindows(display, windows, nwindows);Display *display;Window windows[];int nwindows;display Specifies the connection to the X server.windows Specifies an array containing the windows to berestacked.nwindows Specifies the number of windows to be restacked.│__ The XRestackWindows function restacks the windows in theorder specified, from top to bottom. The stacking order ofthe first window in the windows array is unaffected, but theother windows in the array are stacked underneath the firstwindow, in the order of the array. The stacking order ofthe other windows is not affected. For each window in thewindow array that is not a child of the specified window, aBadMatch error results.If the override-redirect attribute of a window is False andsome other client has selected SubstructureRedirectMask onthe parent, the X server generates ConfigureRequest eventsfor each window whose override-redirect flag is not set, andno further processing is performed. Otherwise, the windowswill be restacked in top-to-bottom order.XRestackWindows can generate a BadWindow error.3.9. Changing Window AttributesXlib provides functions that you can use to set windowattributes. XChangeWindowAttributes is the more generalfunction that allows you to set one or more windowattributes provided by the XSetWindowAttributes structure.The other functions described in this section allow you toset one specific window attribute, such as a window’sbackground.To change one or more attributes for a given window, useXChangeWindowAttributes.__│ XChangeWindowAttributes(display, w, valuemask, attributes)Display *display;Window w;unsigned long valuemask;XSetWindowAttributes *attributes;display Specifies the connection to the X server.w Specifies the window.valuemask Specifies which window attributes are defined inthe attributes argument. This mask is the bitwiseinclusive OR of the valid attribute mask bits. Ifvaluemask is zero, the attributes are ignored andare not referenced. The values and restrictionsare the same as for XCreateWindow.attributesSpecifies the structure from which the values (asspecified by the value mask) are to be taken. Thevalue mask should have the appropriate bits set toindicate which attributes have been set in thestructure (see section 3.2).│__ Depending on the valuemask, the XChangeWindowAttributesfunction uses the window attributes in theXSetWindowAttributes structure to change the specifiedwindow attributes. Changing the background does not causethe window contents to be changed. To repaint the windowand its background, use XClearWindow. Setting the border orchanging the background such that the border tile originchanges causes the border to be repainted. Changing thebackground of a root window to None or ParentRelativerestores the default background pixmap. Changing the borderof a root window to CopyFromParent restores the defaultborder pixmap. Changing the win-gravity does not affect thecurrent position of the window. Changing the backing-storeof an obscured window to WhenMapped or Always, or changingthe backing-planes, backing-pixel, or save-under of a mappedwindow may have no immediate effect. Changing the colormapof a window (that is, defining a new map, not changing thecontents of the existing map) generates a ColormapNotifyevent. Changing the colormap of a visible window may haveno immediate effect on the screen because the map may not beinstalled (see XInstallColormap). Changing the cursor of aroot window to None restores the default cursor. Wheneverpossible, you are encouraged to share colormaps.Multiple clients can select input on the same window. Theirevent masks are maintained separately. When an event isgenerated, it is reported to all interested clients.However, only one client at a time can select forSubstructureRedirectMask, ResizeRedirectMask, andButtonPressMask. If a client attempts to select any ofthese event masks and some other client has already selectedone, a BadAccess error results. There is only onedo-not-propagate-mask for a window, not one per client.XChangeWindowAttributes can generate BadAccess, BadColor,BadCursor, BadMatch, BadPixmap, BadValue, and BadWindowerrors.To set the background of a window to a given pixel, useXSetWindowBackground.__│ XSetWindowBackground(display, w, background_pixel)Display *display;Window w;unsigned long background_pixel;display Specifies the connection to the X server.w Specifies the window.background_pixelSpecifies the pixel that is to be used for thebackground.│__ The XSetWindowBackground function sets the background of thewindow to the specified pixel value. Changing thebackground does not cause the window contents to be changed.XSetWindowBackground uses a pixmap of undefined size filledwith the pixel value you passed. If you try to change thebackground of an InputOnly window, a BadMatch error results.XSetWindowBackground can generate BadMatch and BadWindowerrors.To set the background of a window to a given pixmap, useXSetWindowBackgroundPixmap.__│ XSetWindowBackgroundPixmap(display, w, background_pixmap)Display *display;Window w;Pixmap background_pixmap;display Specifies the connection to the X server.w Specifies the window.background_pixmapSpecifies the background pixmap, ParentRelative,or None.│__ The XSetWindowBackgroundPixmap function sets the backgroundpixmap of the window to the specified pixmap. Thebackground pixmap can immediately be freed if no furtherexplicit references to it are to be made. If ParentRelativeis specified, the background pixmap of the window’s parentis used, or on the root window, the default background isrestored. If you try to change the background of anInputOnly window, a BadMatch error results. If thebackground is set to None, the window has no definedbackground.XSetWindowBackgroundPixmap can generate BadMatch, BadPixmap,and BadWindow errors. NoteXSetWindowBackground andXSetWindowBackgroundPixmap do not change thecurrent contents of the window.To change and repaint a window’s border to a given pixel,use XSetWindowBorder.__│ XSetWindowBorder(display, w, border_pixel)Display *display;Window w;unsigned long border_pixel;display Specifies the connection to the X server.w Specifies the window.border_pixelSpecifies the entry in the colormap.│__ The XSetWindowBorder function sets the border of the windowto the pixel value you specify. If you attempt to performthis on an InputOnly window, a BadMatch error results.XSetWindowBorder can generate BadMatch and BadWindow errors.To change and repaint the border tile of a given window, useXSetWindowBorderPixmap.__│ XSetWindowBorderPixmap(display, w, border_pixmap)Display *display;Window w;Pixmap border_pixmap;display Specifies the connection to the X server.w Specifies the window.border_pixmapSpecifies the border pixmap or CopyFromParent.│__ The XSetWindowBorderPixmap function sets the border pixmapof the window to the pixmap you specify. The border pixmapcan be freed immediately if no further explicit referencesto it are to be made. If you specify CopyFromParent, a copyof the parent window’s border pixmap is used. If youattempt to perform this on an InputOnly window, a BadMatcherror results.XSetWindowBorderPixmap can generate BadMatch, BadPixmap, andBadWindow errors.To set the colormap of a given window, useXSetWindowColormap.__│ XSetWindowColormap(display, w, colormap)Display *display;Window w;Colormap colormap;display Specifies the connection to the X server.w Specifies the window.colormap Specifies the colormap.│__ The XSetWindowColormap function sets the specified colormapof the specified window. The colormap must have the samevisual type as the window, or a BadMatch error results.XSetWindowColormap can generate BadColor, BadMatch, andBadWindow errors.To define which cursor will be used in a window, useXDefineCursor.__│ XDefineCursor(display, w, cursor)Display *display;Window w;Cursor cursor;display Specifies the connection to the X server.w Specifies the window.cursor Specifies the cursor that is to be displayed orNone.│__ If a cursor is set, it will be used when the pointer is inthe window. If the cursor is None, it is equivalent toXUndefineCursor.XDefineCursor can generate BadCursor and BadWindow errors.To undefine the cursor in a given window, useXUndefineCursor.__│ XUndefineCursor(display, w)Display *display;Window w;display Specifies the connection to the X server.w Specifies the window.│__ The XUndefineCursor function undoes the effect of a previousXDefineCursor for this window. When the pointer is in thewindow, the parent’s cursor will now be used. On the rootwindow, the default cursor is restored.XUndefineCursor can generate a BadWindow error.3
4.1. Obtaining Window InformationXlib provides functions that you can use to obtaininformation about the window tree, the window’s currentattributes, the window’s current geometry, or the currentpointer coordinates. Because they are most frequently usedby window managers, these functions all return a status toindicate whether the window still exists.To obtain the parent, a list of children, and number ofchildren for a given window, use XQueryTree.__│ Status XQueryTree(display, w, root_return, parent_return, children_return, nchildren_return)Display *display;Window w;Window *root_return;Window *parent_return;Window **children_return;unsigned int *nchildren_return;display Specifies the connection to the X server.w Specifies the window whose list of children, root,parent, and number of children you want to obtain.root_returnReturns the root window.parent_returnReturns the parent window.children_returnReturns the list of children.nchildren_returnReturns the number of children.│__ The XQueryTree function returns the root ID, the parentwindow ID, a pointer to the list of children windows (NULLwhen there are no children), and the number of children inthe list for the specified window. The children are listedin current stacking order, from bottom-most (first) totop-most (last). XQueryTree returns zero if it fails andnonzero if it succeeds. To free a non-NULL children listwhen it is no longer needed, use XFree.XQueryTree can generate a BadWindow error.To obtain the current attributes of a given window, useXGetWindowAttributes.__│ Status XGetWindowAttributes(display, w, window_attributes_return)Display *display;Window w;XWindowAttributes *window_attributes_return;display Specifies the connection to the X server.w Specifies the window whose current attributes youwant to obtain.window_attributes_returnReturns the specified window’s attributes in theXWindowAttributes structure.│__ The XGetWindowAttributes function returns the currentattributes for the specified window to an XWindowAttributesstructure.__│ typedef struct {int x, y; /* location of window */int width, height; /* width and height of window */int border_width; /* border width of window */int depth; /* depth of window */Visual *visual; /* the associated visual structure */Window root; /* root of screen containing window */int class; /* InputOutput, InputOnly*/int bit_gravity; /* one of the bit gravity values */int win_gravity; /* one of the window gravity values */int backing_store; /* NotUseful, WhenMapped, Always */unsigned long backing_planes;/* planes to be preserved if possible */unsigned long backing_pixel;/* value to be used when restoring planes */Bool save_under; /* boolean, should bits under be saved? */Colormap colormap; /* color map to be associated with window */Bool map_installed; /* boolean, is color map currently installed*/int map_state; /* IsUnmapped, IsUnviewable, IsViewable */long all_event_masks; /* set of events all people have interest in*/long your_event_mask; /* my event mask */long do_not_propagate_mask;/* set of events that should not propagate */Bool override_redirect; /* boolean value for override-redirect */Screen *screen; /* back pointer to correct screen */} XWindowAttributes;│__ The x and y members are set to the upper-left outer cornerrelative to the parent window’s origin. The width andheight members are set to the inside size of the window, notincluding the border. The border_width member is set to thewindow’s border width in pixels. The depth member is set tothe depth of the window (that is, bits per pixel for theobject). The visual member is a pointer to the screen’sassociated Visual structure. The root member is set to theroot window of the screen containing the window. The classmember is set to the window’s class and can be eitherInputOutput or InputOnly.The bit_gravity member is set to the window’s bit gravityand can be one of the following:The win_gravity member is set to the window’s window gravityand can be one of the following:For additional information on gravity, see section 3.2.3.The backing_store member is set to indicate how the X servershould maintain the contents of a window and can beWhenMapped, Always, or NotUseful. The backing_planes memberis set to indicate (with bits set to 1) which bit planes ofthe window hold dynamic data that must be preserved inbacking_stores and during save_unders. The backing_pixelmember is set to indicate what values to use for planes notset in backing_planes.The save_under member is set to True or False. The colormapmember is set to the colormap for the specified window andcan be a colormap ID or None. The map_installed member isset to indicate whether the colormap is currently installedand can be True or False. The map_state member is set toindicate the state of the window and can be IsUnmapped,IsUnviewable, or IsViewable. IsUnviewable is used if thewindow is mapped but some ancestor is unmapped.The all_event_masks member is set to the bitwise inclusiveOR of all event masks selected on the window by all clients.The your_event_mask member is set to the bitwise inclusiveOR of all event masks selected by the querying client. Thedo_not_propagate_mask member is set to the bitwise inclusiveOR of the set of events that should not propagate.The override_redirect member is set to indicate whether thiswindow overrides structure control facilities and can beTrue or False. Window manager clients should ignore thewindow if this member is True.The screen member is set to a screen pointer that gives youa back pointer to the correct screen. This makes it easierto obtain the screen information without having to loop overthe root window fields to see which field matches.XGetWindowAttributes can generate BadDrawable and BadWindowerrors.To obtain the current geometry of a given drawable, useXGetGeometry.__│ Status XGetGeometry(display, d, root_return, x_return, y_return, width_return,height_return, border_width_return, depth_return)Display *display;Drawable d;Window *root_return;int *x_return, *y_return;unsigned int *width_return, *height_return;unsigned int *border_width_return;unsigned int *depth_return;display Specifies the connection to the X server.d Specifies the drawable, which can be a window or apixmap.root_returnReturns the root window.x_returny_return Return the x and y coordinates that define thelocation of the drawable. For a window, thesecoordinates specify the upper-left outer cornerrelative to its parent’s origin. For pixmaps,these coordinates are always zero.width_returnheight_returnReturn the drawable’s dimensions (width andheight). For a window, these dimensions specifythe inside size, not including the border.border_width_returnReturns the border width in pixels. If thedrawable is a pixmap, it returns zero.depth_returnReturns the depth of the drawable (bits per pixelfor the object).│__ The XGetGeometry function returns the root window and thecurrent geometry of the drawable. The geometry of thedrawable includes the x and y coordinates, width and height,border width, and depth. These are described in theargument list. It is legal to pass to this function awindow whose class is InputOnly.XGetGeometry can generate a BadDrawable error.4.2. Translating Screen CoordinatesApplications sometimes need to perform a coordinatetransformation from the coordinate space of one window toanother window or need to determine which window thepointing device is in. XTranslateCoordinates andXQueryPointer fulfill these needs (and avoid any raceconditions) by asking the X server to perform theseoperations.To translate a coordinate in one window to the coordinatespace of another window, use XTranslateCoordinates.__│ Bool XTranslateCoordinates(display, src_w, dest_w, src_x, src_y, dest_x_return,dest_y_return, child_return)Display *display;Window src_w, dest_w;int src_x, src_y;int *dest_x_return, *dest_y_return;Window *child_return;display Specifies the connection to the X server.src_w Specifies the source window.dest_w Specifies the destination window.src_xsrc_y Specify the x and y coordinates within the sourcewindow.dest_x_returndest_y_returnReturn the x and y coordinates within thedestination window.child_returnReturns the child if the coordinates are containedin a mapped child of the destination window.│__ If XTranslateCoordinates returns True, it takes the src_xand src_y coordinates relative to the source window’s originand returns these coordinates to dest_x_return anddest_y_return relative to the destination window’s origin.If XTranslateCoordinates returns False, src_w and dest_w areon different screens, and dest_x_return and dest_y_returnare zero. If the coordinates are contained in a mappedchild of dest_w, that child is returned to child_return.Otherwise, child_return is set to None.XTranslateCoordinates can generate a BadWindow error.To obtain the screen coordinates of the pointer or todetermine the pointer coordinates relative to a specifiedwindow, use XQueryPointer.__│ Bool XQueryPointer(display, w, root_return, child_return, root_x_return, root_y_return,win_x_return, win_y_return, mask_return)Display *display;Window w;Window *root_return, *child_return;int *root_x_return, *root_y_return;int *win_x_return, *win_y_return;unsigned int *mask_return;display Specifies the connection to the X server.w Specifies the window.root_returnReturns the root window that the pointer is in.child_returnReturns the child window that the pointer islocated in, if any.root_x_returnroot_y_returnReturn the pointer coordinates relative to theroot window’s origin.win_x_returnwin_y_returnReturn the pointer coordinates relative to thespecified window.mask_returnReturns the current state of the modifier keys andpointer buttons.│__ The XQueryPointer function returns the root window thepointer is logically on and the pointer coordinates relativeto the root window’s origin. If XQueryPointer returnsFalse, the pointer is not on the same screen as thespecified window, and XQueryPointer returns None tochild_return and zero to win_x_return and win_y_return. IfXQueryPointer returns True, the pointer coordinates returnedto win_x_return and win_y_return are relative to the originof the specified window. In this case, XQueryPointerreturns the child that contains the pointer, if any, or elseNone to child_return.XQueryPointer returns the current logical state of thekeyboard buttons and the modifier keys in mask_return. Itsets mask_return to the bitwise inclusive OR of one or moreof the button or modifier key bitmasks to match the currentstate of the mouse buttons and the modifier keys.Note that the logical state of a device (as seen throughXlib) may lag the physical state if device event processingis frozen (see section 12.1).XQueryPointer can generate a BadWindow error.4.3. Properties and AtomsA property is a collection of named, typed data. The windowsystem has a set of predefined properties (for example, thename of a window, size hints, and so on), and users candefine any other arbitrary information and associate it withwindows. Each property has a name, which is an ISO Latin-1string. For each named property, a unique identifier (atom)is associated with it. A property also has a type, forexample, string or integer. These types are also indicatedusing atoms, so arbitrary new types can be defined. Data ofonly one type may be associated with a single property name.Clients can store and retrieve properties associated withwindows. For efficiency reasons, an atom is used ratherthan a character string. XInternAtom can be used to obtainthe atom for property names.A property is also stored in one of several possibleformats. The X server can store the information as 8-bitquantities, 16-bit quantities, or 32-bit quantities. Thispermits the X server to present the data in the byte orderthat the client expects. NoteIf you define further properties of complex type,you must encode and decode them yourself. Thesefunctions must be carefully written if they are tobe portable. For further information about how towrite a library extension, see appendix C.The type of a property is defined by an atom, which allowsfor arbitrary extension in this type scheme.Certain property names are predefined in the server forcommonly used functions. The atoms for these properties aredefined in <X11/Xatom.h>. To avoid name clashes with usersymbols, the #define name for each atom has the XA_ prefix.For an explanation of the functions that let you get and setmuch of the information stored in these predefinedproperties, see chapter 14.The core protocol imposes no semantics on these propertynames, but semantics are specified in other X Consortiumstandards, such as the Inter-Client CommunicationConventions Manual and the X Logical Font DescriptionConventions.You can use properties to communicate other informationbetween applications. The functions described in thissection let you define new properties and get the uniqueatom IDs in your applications.Although any particular atom can have some clientinterpretation within each of the name spaces, atoms occurin five distinct name spaces within the protocol:• Selections• Property names• Property types• Font properties• Type of a ClientMessage event (none are built into theX server)The built-in selection property names are:PRIMARYSECONDARYThe built-in property names are:The built-in property types are:The built-in font property names are:For further information about font properties, see section8.5.To return an atom for a given name, use XInternAtom.__│ Atom XInternAtom(display, atom_name, only_if_exists)Display *display;char *atom_name;Bool only_if_exists;display Specifies the connection to the X server.atom_name Specifies the name associated with the atom youwant returned.only_if_existsSpecifies a Boolean value that indicates whetherthe atom must be created.│__ The XInternAtom function returns the atom identifierassociated with the specified atom_name string. Ifonly_if_exists is False, the atom is created if it does notexist. Therefore, XInternAtom can return None. If the atomname is not in the Host Portable Character Encoding, theresult is implementation-dependent. Uppercase and lowercasematter; the strings ‘‘thing’’, ‘‘Thing’’, and ‘‘thinG’’ alldesignate different atoms. The atom will remain definedeven after the client’s connection closes. It will becomeundefined only when the last connection to the X servercloses.XInternAtom can generate BadAlloc and BadValue errors.To return atoms for an array of names, use XInternAtoms.__│ Status XInternAtoms(display, names, count, only_if_exists, atoms_return)Display *display;char **names;int count;Bool only_if_exists;Atom *atoms_return;display Specifies the connection to the X server.names Specifies the array of atom names.count Specifies the number of atom names in the array.only_if_existsSpecifies a Boolean value that indicates whetherthe atom must be created.atoms_returnReturns the atoms.│__ The XInternAtoms function returns the atom identifiersassociated with the specified names. The atoms are storedin the atoms_return array supplied by the caller. Callingthis function is equivalent to calling XInternAtom for eachof the names in turn with the specified value ofonly_if_exists, but this function minimizes the number ofround-trip protocol exchanges between the client and the Xserver.This function returns a nonzero status if atoms are returnedfor all of the names; otherwise, it returns zero.XInternAtoms can generate BadAlloc and BadValue errors.To return a name for a given atom identifier, useXGetAtomName.__│ char *XGetAtomName(display, atom)Display *display;Atom atom;display Specifies the connection to the X server.atom Specifies the atom for the property name you wantreturned.│__ The XGetAtomName function returns the name associated withthe specified atom. If the data returned by the server isin the Latin Portable Character Encoding, then the returnedstring is in the Host Portable Character Encoding.Otherwise, the result is implementation-dependent. To freethe resulting string, call XFree.XGetAtomName can generate a BadAtom error.To return the names for an array of atom identifiers, useXGetAtomNames.__│ Status XGetAtomNames(display, atoms, count, names_return)Display *display;Atom *atoms;int count;char **names_return;display Specifies the connection to the X server.atoms Specifies the array of atoms.count Specifies the number of atoms in the array.names_returnReturns the atom names.│__ The XGetAtomNames function returns the names associated withthe specified atoms. The names are stored in thenames_return array supplied by the caller. Calling thisfunction is equivalent to calling XGetAtomName for each ofthe atoms in turn, but this function minimizes the number ofround-trip protocol exchanges between the client and the Xserver.This function returns a nonzero status if names are returnedfor all of the atoms; otherwise, it returns zero.XGetAtomNames can generate a BadAtom error.4.4. Obtaining and Changing Window PropertiesYou can attach a property list to every window. Eachproperty has a name, a type, and a value (see section 4.3).The value is an array of 8-bit, 16-bit, or 32-bitquantities, whose interpretation is left to the clients.The type char is used to represent 8-bit quantities, thetype short is used to represent 16-bit quantities, and thetype long is used to represent 32-bit quantities.Xlib provides functions that you can use to obtain, change,update, or interchange window properties. In addition, Xlibprovides other utility functions for inter-clientcommunication (see chapter 14).To obtain the type, format, and value of a property of agiven window, use XGetWindowProperty.__│ int XGetWindowProperty(display, w, property, long_offset, long_length, delete, req_type,actual_type_return, actual_format_return, nitems_return, bytes_after_return,prop_return)Display *display;Window w;Atom property;long long_offset, long_length;Bool delete;Atom req_type;Atom *actual_type_return;int *actual_format_return;unsigned long *nitems_return;unsigned long *bytes_after_return;unsigned char **prop_return;display Specifies the connection to the X server.w Specifies the window whose property you want toobtain.property Specifies the property name.long_offsetSpecifies the offset in the specified property (in32-bit quantities) where the data is to beretrieved.long_lengthSpecifies the length in 32-bit multiples of thedata to be retrieved.delete Specifies a Boolean value that determines whetherthe property is deleted.req_type Specifies the atom identifier associated with theproperty type or AnyPropertyType.actual_type_returnReturns the atom identifier that defines theactual type of the property.actual_format_returnReturns the actual format of the property.nitems_returnReturns the actual number of 8-bit, 16-bit, or32-bit items stored in the prop_return data.bytes_after_returnReturns the number of bytes remaining to be readin the property if a partial read was performed.prop_returnReturns the data in the specified format.│__ The XGetWindowProperty function returns the actual type ofthe property; the actual format of the property; the numberof 8-bit, 16-bit, or 32-bit items transferred; the number ofbytes remaining to be read in the property; and a pointer tothe data actually returned. XGetWindowProperty sets thereturn arguments as follows:• If the specified property does not exist for thespecified window, XGetWindowProperty returns None toactual_type_return and the value zero toactual_format_return and bytes_after_return. Thenitems_return argument is empty. In this case, thedelete argument is ignored.• If the specified property exists but its type does notmatch the specified type, XGetWindowProperty returnsthe actual property type to actual_type_return, theactual property format (never zero) toactual_format_return, and the property length in bytes(even if the actual_format_return is 16 or 32) tobytes_after_return. It also ignores the deleteargument. The nitems_return argument is empty.• If the specified property exists and either you assignAnyPropertyType to the req_type argument or thespecified type matches the actual property type,XGetWindowProperty returns the actual property type toactual_type_return and the actual property format(never zero) to actual_format_return. It also returnsa value to bytes_after_return and nitems_return, bydefining the following values:N = actual length of the stored property in bytes(even if the format is 16 or 32)I = 4 * long_offsetT = N - IL = MINIMUM(T, 4 * long_length)A = N - (I + L)The returned value starts at byte index I in theproperty (indexing from zero), and its length in bytesis L. If the value for long_offset causes L to benegative, a BadValue error results. The value ofbytes_after_return is A, giving the number of trailingunread bytes in the stored property.If the returned format is 8, the returned data isrepresented as a char array. If the returned format is 16,the returned data is represented as a short array and shouldbe cast to that type to obtain the elements. If thereturned format is 32, the returned data is represented as along array and should be cast to that type to obtain theelements.XGetWindowProperty always allocates one extra byte inprop_return (even if the property is zero length) and setsit to zero so that simple properties consisting ofcharacters do not have to be copied into yet another stringbefore use.If delete is True and bytes_after_return is zero,XGetWindowProperty deletes the property from the window andgenerates a PropertyNotify event on the window.The function returns Success if it executes successfully.To free the resulting data, use XFree.XGetWindowProperty can generate BadAtom, BadValue, andBadWindow errors.To obtain a given window’s property list, useXListProperties.__│ Atom *XListProperties(display, w, num_prop_return)Display *display;Window w;int *num_prop_return;display Specifies the connection to the X server.w Specifies the window whose property list you wantto obtain.num_prop_returnReturns the length of the properties array.│__ The XListProperties function returns a pointer to an arrayof atom properties that are defined for the specified windowor returns NULL if no properties were found. To free thememory allocated by this function, use XFree.XListProperties can generate a BadWindow error.To change a property of a given window, use XChangeProperty.__│ XChangeProperty(display, w, property, type, format, mode, data, nelements)Display *display;Window w;Atom property, type;int format;int mode;unsigned char *data;int nelements;display Specifies the connection to the X server.w Specifies the window whose property you want tochange.property Specifies the property name.type Specifies the type of the property. The X serverdoes not interpret the type but simply passes itback to an application that later callsXGetWindowProperty.format Specifies whether the data should be viewed as alist of 8-bit, 16-bit, or 32-bit quantities.Possible values are 8, 16, and 32. Thisinformation allows the X server to correctlyperform byte-swap operations as necessary. If theformat is 16-bit or 32-bit, you must explicitlycast your data pointer to an (unsigned char *) inthe call to XChangeProperty.mode Specifies the mode of the operation. You can passPropModeReplace, PropModePrepend, orPropModeAppend.data Specifies the property data.nelements Specifies the number of elements of the specifieddata format.│__ The XChangeProperty function alters the property for thespecified window and causes the X server to generate aPropertyNotify event on that window. XChangePropertyperforms the following:• If mode is PropModeReplace, XChangeProperty discardsthe previous property value and stores the new data.• If mode is PropModePrepend or PropModeAppend,XChangeProperty inserts the specified data before thebeginning of the existing data or onto the end of theexisting data, respectively. The type and format mustmatch the existing property value, or a BadMatch errorresults. If the property is undefined, it is treatedas defined with the correct type and format withzero-length data.If the specified format is 8, the property data must be achar array. If the specified format is 16, the propertydata must be a short array. If the specified format is 32,the property data must be a long array.The lifetime of a property is not tied to the storingclient. Properties remain until explicitly deleted, untilthe window is destroyed, or until the server resets. For adiscussion of what happens when the connection to the Xserver is closed, see section 2.6. The maximum size of aproperty is server dependent and can vary dynamicallydepending on the amount of memory the server has available.(If there is insufficient space, a BadAlloc error results.)XChangeProperty can generate BadAlloc, BadAtom, BadMatch,BadValue, and BadWindow errors.To rotate a window’s property list, useXRotateWindowProperties.__│ XRotateWindowProperties(display, w, properties, num_prop, npositions)Display *display;Window w;Atom properties[];int num_prop;int npositions;display Specifies the connection to the X server.w Specifies the window.propertiesSpecifies the array of properties that are to berotated.num_prop Specifies the length of the properties array.npositionsSpecifies the rotation amount.│__ The XRotateWindowProperties function allows you to rotateproperties on a window and causes the X server to generatePropertyNotify events. If the property names in theproperties array are viewed as being numbered starting fromzero and if there are num_prop property names in the list,then the value associated with property name I becomes thevalue associated with property name (I + npositions) mod Nfor all I from zero to N − 1. The effect is to rotate thestates by npositions places around the virtual ring ofproperty names (right for positive npositions, left fornegative npositions). If npositions mod N is nonzero, the Xserver generates a PropertyNotify event for each property inthe order that they are listed in the array. If an atomoccurs more than once in the list or no property with thatname is defined for the window, a BadMatch error results.If a BadAtom or BadMatch error results, no properties arechanged.XRotateWindowProperties can generate BadAtom, BadMatch, andBadWindow errors.To delete a property on a given window, use XDeleteProperty.__│ XDeleteProperty(display, w, property)Display *display;Window w;Atom property;display Specifies the connection to the X server.w Specifies the window whose property you want todelete.property Specifies the property name.│__ The XDeleteProperty function deletes the specified propertyonly if the property was defined on the specified window andcauses the X server to generate a PropertyNotify event onthe window unless the property does not exist.XDeleteProperty can generate BadAtom and BadWindow errors.4.5. SelectionsSelections are one method used by applications to exchangedata. By using the property mechanism, applications canexchange data of arbitrary types and can negotiate the typeof the data. A selection can be thought of as an indirectproperty with a dynamic type. That is, rather than havingthe property stored in the X server, the property ismaintained by some client (the owner). A selection isglobal in nature (considered to belong to the user but bemaintained by clients) rather than being private to aparticular window subhierarchy or a particular set ofclients.Xlib provides functions that you can use to set, get, orrequest conversion of selections. This allows applicationsto implement the notion of current selection, which requiresthat notification be sent to applications when they nolonger own the selection. Applications that supportselection often highlight the current selection and so mustbe informed when another application has acquired theselection so that they can unhighlight the selection.When a client asks for the contents of a selection, itspecifies a selection target type. This target type can beused to control the transmitted representation of thecontents. For example, if the selection is ‘‘the last thingthe user clicked on’’ and that is currently an image, thenthe target type might specify whether the contents of theimage should be sent in XY format or Z format.The target type can also be used to control the class ofcontents transmitted, for example, asking for the ‘‘looks’’(fonts, line spacing, indentation, and so forth) of aparagraph selection, not the text of the paragraph. Thetarget type can also be used for other purposes. Theprotocol does not constrain the semantics.To set the selection owner, use XSetSelectionOwner.__│ XSetSelectionOwner(display, selection, owner, time)Display *display;Atom selection;Window owner;Time time;display Specifies the connection to the X server.selection Specifies the selection atom.owner Specifies the owner of the specified selectionatom. You can pass a window or None.time Specifies the time. You can pass either atimestamp or CurrentTime.│__ The XSetSelectionOwner function changes the owner andlast-change time for the specified selection and has noeffect if the specified time is earlier than the currentlast-change time of the specified selection or is later thanthe current X server time. Otherwise, the last-change timeis set to the specified time, with CurrentTime replaced bythe current server time. If the owner window is specifiedas None, then the owner of the selection becomes None (thatis, no owner). Otherwise, the owner of the selectionbecomes the client executing the request.If the new owner (whether a client or None) is not the sameas the current owner of the selection and the current owneris not None, the current owner is sent a SelectionClearevent. If the client that is the owner of a selection islater terminated (that is, its connection is closed) or ifthe owner window it has specified in the request is laterdestroyed, the owner of the selection automatically revertsto None, but the last-change time is not affected. Theselection atom is uninterpreted by the X server.XGetSelectionOwner returns the owner window, which isreported in SelectionRequest and SelectionClear events.Selections are global to the X server.XSetSelectionOwner can generate BadAtom and BadWindowerrors.To return the selection owner, use XGetSelectionOwner.__│ Window XGetSelectionOwner(display, selection)Display *display;Atom selection;display Specifies the connection to the X server.selection Specifies the selection atom whose owner you wantreturned.│__ The XGetSelectionOwner function returns the window IDassociated with the window that currently owns the specifiedselection. If no selection was specified, the functionreturns the constant None. If None is returned, there is noowner for the selection.XGetSelectionOwner can generate a BadAtom error.To request conversion of a selection, use XConvertSelection.__│ XConvertSelection(display, selection, target, property, requestor, time)Display *display;Atom selection, target;Atom property;Window requestor;Time time;display Specifies the connection to the X server.selection Specifies the selection atom.target Specifies the target atom.property Specifies the property name. You also can passNone.requestor Specifies the requestor.time Specifies the time. You can pass either atimestamp or CurrentTime.│__ XConvertSelection requests that the specified selection beconverted to the specified target type:• If the specified selection has an owner, the X serversends a SelectionRequest event to that owner.• If no owner for the specified selection exists, the Xserver generates a SelectionNotify event to therequestor with property None.The arguments are passed on unchanged in either of theevents. There are two predefined selection atoms: PRIMARYand SECONDARY.XConvertSelection can generate BadAtom and BadWindow errors.4
5.1. Creating and Freeing PixmapsPixmaps can only be used on the screen on which they werecreated. Pixmaps are off-screen resources that are used forvarious operations, such as defining cursors as tilingpatterns or as the source for certain raster operations.Most graphics requests can operate either on a window or ona pixmap. A bitmap is a single bit-plane pixmap.To create a pixmap of a given size, use XCreatePixmap.__│ Pixmap XCreatePixmap(display, d, width, height, depth)Display *display;Drawable d;unsigned int width, height;unsigned int depth;display Specifies the connection to the X server.d Specifies which screen the pixmap is created on.widthheight Specify the width and height, which define thedimensions of the pixmap.depth Specifies the depth of the pixmap.│__ The XCreatePixmap function creates a pixmap of the width,height, and depth you specified and returns a pixmap ID thatidentifies it. It is valid to pass an InputOnly window tothe drawable argument. The width and height arguments mustbe nonzero, or a BadValue error results. The depth argumentmust be one of the depths supported by the screen of thespecified drawable, or a BadValue error results.The server uses the specified drawable to determine on whichscreen to create the pixmap. The pixmap can be used only onthis screen and only with other drawables of the same depth(see XCopyPlane for an exception to this rule). The initialcontents of the pixmap are undefined.XCreatePixmap can generate BadAlloc, BadDrawable, andBadValue errors.To free all storage associated with a specified pixmap, useXFreePixmap.__│ XFreePixmap(display, pixmap)Display *display;Pixmap pixmap;display Specifies the connection to the X server.pixmap Specifies the pixmap.│__ The XFreePixmap function first deletes the associationbetween the pixmap ID and the pixmap. Then, the X serverfrees the pixmap storage when there are no references to it.The pixmap should never be referenced again.XFreePixmap can generate a BadPixmap error.5.2. Creating, Recoloring, and Freeing CursorsEach window can have a different cursor defined for it.Whenever the pointer is in a visible window, it is set tothe cursor defined for that window. If no cursor wasdefined for that window, the cursor is the one defined forthe parent window.From X’s perspective, a cursor consists of a cursor source,mask, colors, and a hotspot. The mask pixmap determines theshape of the cursor and must be a depth of one. The sourcepixmap must have a depth of one, and the colors determinethe colors of the source. The hotspot defines the point onthe cursor that is reported when a pointer event occurs.There may be limitations imposed by the hardware on cursorsas to size and whether a mask is implemented.XQueryBestCursor can be used to find out what sizes arepossible. There is a standard font for creating cursors,but Xlib provides functions that you can use to createcursors from an arbitrary font or from bitmaps.To create a cursor from the standard cursor font, useXCreateFontCursor.__│ #include <X11/cursorfont.h>Cursor XCreateFontCursor(display, shape)Display *display;unsigned int shape;display Specifies the connection to the X server.shape Specifies the shape of the cursor.│__ X provides a set of standard cursor shapes in a special fontnamed cursor. Applications are encouraged to use thisinterface for their cursors because the font can becustomized for the individual display type. The shapeargument specifies which glyph of the standard fonts to use.The hotspot comes from the information stored in the cursorfont. The initial colors of a cursor are a black foregroundand a white background (see XRecolorCursor). For furtherinformation about cursor shapes, see appendix B.XCreateFontCursor can generate BadAlloc and BadValue errors.To create a cursor from font glyphs, use XCreateGlyphCursor.__│ Cursor XCreateGlyphCursor(display, source_font, mask_font, source_char, mask_char,foreground_color, background_color)Display *display;Font source_font, mask_font;unsigned int source_char, mask_char;XColor *foreground_color;XColor *background_color;display Specifies the connection to the X server.source_fontSpecifies the font for the source glyph.mask_font Specifies the font for the mask glyph or None.source_charSpecifies the character glyph for the source.mask_char Specifies the glyph character for the mask.foreground_colorSpecifies the RGB values for the foreground of thesource.background_colorSpecifies the RGB values for the background of thesource.│__ The XCreateGlyphCursor function is similar toXCreatePixmapCursor except that the source and mask bitmapsare obtained from the specified font glyphs. Thesource_char must be a defined glyph in source_font, or aBadValue error results. If mask_font is given, mask_charmust be a defined glyph in mask_font, or a BadValue errorresults. The mask_font and character are optional. Theorigins of the source_char and mask_char (if defined) glyphsare positioned coincidently and define the hotspot. Thesource_char and mask_char need not have the same boundingbox metrics, and there is no restriction on the placement ofthe hotspot relative to the bounding boxes. If no mask_charis given, all pixels of the source are displayed. You canfree the fonts immediately by calling XFreeFont if nofurther explicit references to them are to be made.For 2-byte matrix fonts, the 16-bit value should be formedwith the byte1 member in the most significant byte and thebyte2 member in the least significant byte.XCreateGlyphCursor can generate BadAlloc, BadFont, andBadValue errors.To create a cursor from two bitmaps, useXCreatePixmapCursor.__│ Cursor XCreatePixmapCursor(display, source, mask, foreground_color, background_color, x, y)Display *display;Pixmap source;Pixmap mask;XColor *foreground_color;XColor *background_color;unsigned int x, y;display Specifies the connection to the X server.source Specifies the shape of the source cursor.mask Specifies the cursor’s source bits to be displayedor None.foreground_colorSpecifies the RGB values for the foreground of thesource.background_colorSpecifies the RGB values for the background of thesource.xy Specify the x and y coordinates, which indicatethe hotspot relative to the source’s origin.│__ The XCreatePixmapCursor function creates a cursor andreturns the cursor ID associated with it. The foregroundand background RGB values must be specified usingforeground_color and background_color, even if the X serveronly has a StaticGray or GrayScale screen. The foregroundcolor is used for the pixels set to 1 in the source, and thebackground color is used for the pixels set to 0. Bothsource and mask, if specified, must have depth one (or aBadMatch error results) but can have any root. The maskargument defines the shape of the cursor. The pixels set to1 in the mask define which source pixels are displayed, andthe pixels set to 0 define which pixels are ignored. If nomask is given, all pixels of the source are displayed. Themask, if present, must be the same size as the pixmapdefined by the source argument, or a BadMatch error results.The hotspot must be a point within the source, or a BadMatcherror results.The components of the cursor can be transformed arbitrarilyto meet display limitations. The pixmaps can be freedimmediately if no further explicit references to them are tobe made. Subsequent drawing in the source or mask pixmaphas an undefined effect on the cursor. The X server mightor might not make a copy of the pixmap.XCreatePixmapCursor can generate BadAlloc and BadPixmaperrors.To determine useful cursor sizes, use XQueryBestCursor.__│ Status XQueryBestCursor(display, d, width, height, width_return, height_return)Display *display;Drawable d;unsigned int width, height;unsigned int *width_return, *height_return;display Specifies the connection to the X server.d Specifies the drawable, which indicates thescreen.widthheight Specify the width and height of the cursor thatyou want the size information for.width_returnheight_returnReturn the best width and height that is closestto the specified width and height.│__ Some displays allow larger cursors than other displays. TheXQueryBestCursor function provides a way to find out whatsize cursors are actually possible on the display. Itreturns the largest size that can be displayed.Applications should be prepared to use smaller cursors ondisplays that cannot support large ones.XQueryBestCursor can generate a BadDrawable error.To change the color of a given cursor, use XRecolorCursor.__│ XRecolorCursor(display, cursor, foreground_color, background_color)Display *display;Cursor cursor;XColor *foreground_color, *background_color;display Specifies the connection to the X server.cursor Specifies the cursor.foreground_colorSpecifies the RGB values for the foreground of thesource.background_colorSpecifies the RGB values for the background of thesource.│__ The XRecolorCursor function changes the color of thespecified cursor, and if the cursor is being displayed on ascreen, the change is visible immediately. The pixelmembers of the XColor structures are ignored; only the RGBvalues are used.XRecolorCursor can generate a BadCursor error.To free (destroy) a given cursor, use XFreeCursor.__│ XFreeCursor(display, cursor)Display *display;Cursor cursor;display Specifies the connection to the X server.cursor Specifies the cursor.│__ The XFreeCursor function deletes the association between thecursor resource ID and the specified cursor. The cursorstorage is freed when no other resource references it. Thespecified cursor ID should not be referred to again.XFreeCursor can generate a BadCursor error.5
6.1. Color StructuresFunctions that operate only on RGB color space values use anXColor structure, which contains:__│ typedef struct {unsigned long pixel;/* pixel value */unsigned short red, green, blue;/* rgb values */char flags; /* DoRed, DoGreen, DoBlue */char pad;} XColor;│__ The red, green, and blue values are always in the range 0 to65535 inclusive, independent of the number of bits actuallyused in the display hardware. The server scales thesevalues down to the range used by the hardware. Black isrepresented by (0,0,0), and white is represented by(65535,65535,65535). In some functions, the flags membercontrols which of the red, green, and blue members is usedand can be the inclusive OR of zero or more of DoRed,DoGreen, and DoBlue.Functions that operate on all color space values use anXcmsColor structure. This structure contains a union ofsubstructures, each supporting color specification encodingfor a particular color space. Like the XColor structure,the XcmsColor structure contains pixel and colorspecification information (the spec member in the XcmsColorstructure).__│ typedef unsigned long XcmsColorFormat;/* Color Specification Format */typedef struct {union {XcmsRGB RGB;XcmsRGBi RGBi;XcmsCIEXYZ CIEXYZ;XcmsCIEuvY CIEuvY;XcmsCIExyY CIExyY;XcmsCIELab CIELab;XcmsCIELuv CIELuv;XcmsTekHVC TekHVC;XcmsPad Pad;} spec;unsigned long pixel;XcmsColorFormat format;} XcmsColor; /* Xcms Color Structure */│__ Because the color specification can be encoded for thevarious color spaces, encoding for the spec member isidentified by the format member, which is of typeXcmsColorFormat. The following macros define standardformats.__││__ Formats for device-independent color spaces aredistinguishable from those for device-dependent spaces bythe 32nd bit. If this bit is set, it indicates that thecolor specification is in a device-dependent form;otherwise, it is in a device-independent form. If the 31stbit is set, this indicates that the color space has beenadded to Xlib at run time (see section 6.12.4). The formatvalue for a color space added at run time may be differenteach time the program is executed. If references to such acolor space must be made outside the client (for example,storing a color specification in a file), then referenceshould be made by color space string prefix (seeXcmsFormatOfPrefix and XcmsPrefixOfFormat).Data types that describe the color specification encodingfor the various color spaces are defined as follows:__│ typedef double XcmsFloat;typedef struct {unsigned short red; /* 0x0000 to 0xffff */unsigned short green;/* 0x0000 to 0xffff */unsigned short blue;/* 0x0000 to 0xffff */} XcmsRGB; /* RGB Device */typedef struct {XcmsFloat red; /* 0.0 to 1.0 */XcmsFloat green; /* 0.0 to 1.0 */XcmsFloat blue; /* 0.0 to 1.0 */} XcmsRGBi; /* RGB Intensity */typedef struct {XcmsFloat X;XcmsFloat Y; /* 0.0 to 1.0 */XcmsFloat Z;} XcmsCIEXYZ; /* CIE XYZ */typedef struct {XcmsFloat u_prime; /* 0.0 to ~0.6 */XcmsFloat v_prime; /* 0.0 to ~0.6 */XcmsFloat Y; /* 0.0 to 1.0 */} XcmsCIEuvY; /* CIE u’v’Y */typedef struct {XcmsFloat x; /* 0.0 to ~.75 */XcmsFloat y; /* 0.0 to ~.85 */XcmsFloat Y; /* 0.0 to 1.0 */} XcmsCIExyY; /* CIE xyY */typedef struct {XcmsFloat L_star; /* 0.0 to 100.0 */XcmsFloat a_star;XcmsFloat b_star;} XcmsCIELab; /* CIE L*a*b* */typedef struct {XcmsFloat L_star; /* 0.0 to 100.0 */XcmsFloat u_star;XcmsFloat v_star;} XcmsCIELuv; /* CIE L*u*v* */typedef struct {XcmsFloat H; /* 0.0 to 360.0 */XcmsFloat V; /* 0.0 to 100.0 */XcmsFloat C; /* 0.0 to 100.0 */} XcmsTekHVC; /* TekHVC */typedef struct {XcmsFloat pad0;XcmsFloat pad1;XcmsFloat pad2;XcmsFloat pad3;} XcmsPad; /* four doubles */│__ The device-dependent formats provided allow colorspecification in:• RGB Intensity (XcmsRGBi)Red, green, and blue linear intensity values,floating-point values from 0.0 to 1.0, where 1.0indicates full intensity, 0.5 half intensity, and soon.• RGB Device (XcmsRGB)Red, green, and blue values appropriate for thespecified output device. XcmsRGB values are of typeunsigned short, scaled from 0 to 65535 inclusive, andare interchangeable with the red, green, and bluevalues in an XColor structure.It is important to note that RGB Intensity values are notgamma corrected values. In contrast, RGB Device valuesgenerated as a result of converting color specifications arealways gamma corrected, and RGB Device values acquired as aresult of querying a colormap or passed in by the client areassumed by Xlib to be gamma corrected. The term RGB valuein this manual always refers to an RGB Device value.6.2. Color StringsXlib provides a mechanism for using string names for colors.A color string may either contain an abstract color name ora numerical color specification. Color strings arecase-insensitive.Color strings are used in the following functions:• XAllocNamedColor• XcmsAllocNamedColor• XLookupColor• XcmsLookupColor• XParseColor• XStoreNamedColorXlib supports the use of abstract color names, for example,red or blue. A value for this abstract name is obtained bysearching one or more color name databases. Xlib firstsearches zero or more client-side databases; the number,location, and content of these databases isimplementation-dependent and might depend on the currentlocale. If the name is not found, Xlib then looks for thecolor in the X server’s database. If the color name is notin the Host Portable Character Encoding, the result isimplementation-dependent.A numerical color specification consists of a color spacename and a set of values in the following syntax:__│ <color_space_name>:<value>/.../<value>│__ The following are examples of valid color strings."CIEXYZ:0.3227/0.28133/0.2493""RGBi:1.0/0.0/0.0""rgb:00/ff/00""CIELuv:50.0/0.0/0.0"The syntax and semantics of numerical specifications aregiven for each standard color space in the followingsections.6.2.1. RGB Device String SpecificationAn RGB Device specification is identified by the prefix‘‘rgb:’’ and conforms to the following syntax:rgb:<red>/<green>/<blue><red>, <green>, <blue> := h | hh | hhh | hhhhh := single hexadecimal digits (case insignificant)Note that h indicates the value scaled in 4 bits, hh thevalue scaled in 8 bits, hhh the value scaled in 12 bits, andhhhh the value scaled in 16 bits, respectively.Typical examples are the strings ‘‘rgb:ea/75/52’’ and‘‘rgb:ccc/320/320’’, but mixed numbers of hexadecimal digitstrings (‘‘rgb:ff/a5/0’’ and ‘‘rgb:ccc/32/0’’) are alsoallowed.For backward compatibility, an older syntax for RGB Deviceis supported, but its continued use is not encouraged. Thesyntax is an initial sharp sign character followed by anumeric specification, in one of the following formats:#RGB (4 bits each)#RRGGBB (8 bits each)#RRRGGGBBB (12 bits each)#RRRRGGGGBBBB (16 bits each)The R, G, and B represent single hexadecimal digits. Whenfewer than 16 bits each are specified, they represent themost significant bits of the value (unlike the ‘‘rgb:’’syntax, in which values are scaled). For example, thestring ‘‘#3a7’’ is the same as ‘‘#3000a0007000’’.6.2.2. RGB Intensity String SpecificationAn RGB intensity specification is identified by the prefix‘‘rgbi:’’ and conforms to the following syntax:rgbi:<red>/<green>/<blue>Note that red, green, and blue are floating-point valuesbetween 0.0 and 1.0, inclusive. The input format for thesevalues is an optional sign, a string of numbers possiblycontaining a decimal point, and an optional exponent fieldcontaining an E or e followed by a possibly signed integerstring.6.2.3. Device-Independent String SpecificationsThe standard device-independent string specifications havethe following syntax:CIEXYZ:<X>/<Y>/<Z>CIEuvY:<u>/<v>/<Y>CIExyY:<x>/<y>/<Y>CIELab:<L>/<a>/<b>CIELuv:<L>/<u>/<v>TekHVC:<H>/<V>/<C>All of the values (C, H, V, X, Y, Z, a, b, u, v, y, x) arefloating-point values. The syntax for these values is anoptional plus or minus sign, a string of digits possiblycontaining a decimal point, and an optional exponent fieldconsisting of an ‘‘E’’ or ‘‘e’’ followed by an optional plusor minus followed by a string of digits.6.3. Color Conversion Contexts and Gamut MappingWhen Xlib converts device-independent color specificationsinto device-dependent specifications and vice versa, it usesknowledge about the color limitations of the screenhardware. This information, typically called the deviceprofile, is available in a Color Conversion Context (CCC).Because a specified color may be outside the color gamut ofthe target screen and the white point associated with thecolor specification may differ from the white point inherentto the screen, Xlib applies gamut mapping when it encounterscertain conditions:• Gamut compression occurs when conversion ofdevice-independent color specifications todevice-dependent color specifications results in acolor out of the target screen’s gamut.• White adjustment occurs when the inherent white pointof the screen differs from the white point assumed bythe client.Gamut handling methods are stored as callbacks in the CCC,which in turn are used by the color space conversionroutines. Client data is also stored in the CCC for eachcallback. The CCC also contains the white point the clientassumes to be associated with color specifications (that is,the Client White Point). The client can specify the gamuthandling callbacks and client data as well as the ClientWhite Point. Xlib does not preclude the X client fromperforming other forms of gamut handling (for example, gamutexpansion); however, Xlib does not provide direct supportfor gamut handling other than white adjustment and gamutcompression.Associated with each colormap is an initial CCCtransparently generated by Xlib. Therefore, when youspecify a colormap as an argument to an Xlib function, youare indirectly specifying a CCC. There is a default CCCassociated with each screen. Newly created CCCs inheritattributes from the default CCC, so the default CCCattributes can be modified to affect new CCCs.Xcms functions in which gamut mapping can occur returnStatus and have specific status values defined for them, asfollows:• XcmsFailure indicates that the function failed.• XcmsSuccess indicates that the function succeeded. Inaddition, if the function performed any colorconversion, the colors did not need to be compressed.• XcmsSuccessWithCompression indicates the functionperformed color conversion and at least one of thecolors needed to be compressed. The gamut compressionmethod is determined by the gamut compression procedurein the CCC that is specified directly as a functionargument or in the CCC indirectly specified by means ofthe colormap argument.6.4. Creating, Copying, and Destroying ColormapsTo create a colormap for a screen, use XCreateColormap.__│ Colormap XCreateColormap(display, w, visual, alloc)Display *display;Window w;Visual *visual;int alloc;display Specifies the connection to the X server.w Specifies the window on whose screen you want tocreate a colormap.visual Specifies a visual type supported on the screen.If the visual type is not one supported by thescreen, a BadMatch error results.alloc Specifies the colormap entries to be allocated.You can pass AllocNone or AllocAll.│__ The XCreateColormap function creates a colormap of thespecified visual type for the screen on which the specifiedwindow resides and returns the colormap ID associated withit. Note that the specified window is only used todetermine the screen.The initial values of the colormap entries are undefined forthe visual classes GrayScale, PseudoColor, and DirectColor.For StaticGray, StaticColor, and TrueColor, the entries havedefined values, but those values are specific to the visualand are not defined by X. For StaticGray, StaticColor, andTrueColor, alloc must be AllocNone, or a BadMatch errorresults. For the other visual classes, if alloc isAllocNone, the colormap initially has no allocated entries,and clients can allocate them. For information about thevisual types, see section 3.1.If alloc is AllocAll, the entire colormap is allocatedwritable. The initial values of all allocated entries areundefined. For GrayScale and PseudoColor, the effect is asif an XAllocColorCells call returned all pixel values fromzero to N − 1, where N is the colormap entries value in thespecified visual. For DirectColor, the effect is as if anXAllocColorPlanes call returned a pixel value of zero andred_mask, green_mask, and blue_mask values containing thesame bits as the corresponding masks in the specifiedvisual. However, in all cases, none of these entries can befreed by using XFreeColors.XCreateColormap can generate BadAlloc, BadMatch, BadValue,and BadWindow errors.To create a new colormap when the allocation out of apreviously shared colormap has failed because of resourceexhaustion, use XCopyColormapAndFree.__│ Colormap XCopyColormapAndFree(display, colormap)Display *display;Colormap colormap;display Specifies the connection to the X server.colormap Specifies the colormap.│__ The XCopyColormapAndFree function creates a colormap of thesame visual type and for the same screen as the specifiedcolormap and returns the new colormap ID. It also moves allof the client’s existing allocation from the specifiedcolormap to the new colormap with their color values intactand their read-only or writable characteristics intact andfrees those entries in the specified colormap. Color valuesin other entries in the new colormap are undefined. If thespecified colormap was created by the client with alloc setto AllocAll, the new colormap is also created with AllocAll,all color values for all entries are copied from thespecified colormap, and then all entries in the specifiedcolormap are freed. If the specified colormap was notcreated by the client with AllocAll, the allocations to bemoved are all those pixels and planes that have beenallocated by the client using XAllocColor, XAllocNamedColor,XAllocColorCells, or XAllocColorPlanes and that have notbeen freed since they were allocated.XCopyColormapAndFree can generate BadAlloc and BadColorerrors.To destroy a colormap, use XFreeColormap.__│ XFreeColormap(display, colormap)Display *display;Colormap colormap;display Specifies the connection to the X server.colormap Specifies the colormap that you want to destroy.│__ The XFreeColormap function deletes the association betweenthe colormap resource ID and the colormap and frees thecolormap storage. However, this function has no effect onthe default colormap for a screen. If the specifiedcolormap is an installed map for a screen, it is uninstalled(see XUninstallColormap). If the specified colormap isdefined as the colormap for a window (by XCreateWindow,XSetWindowColormap, or XChangeWindowAttributes),XFreeColormap changes the colormap associated with thewindow to None and generates a ColormapNotify event. X doesnot define the colors displayed for a window with a colormapof None.XFreeColormap can generate a BadColor error.6.5. Mapping Color Names to ValuesTo map a color name to an RGB value, use XLookupColor.__│ Status XLookupColor(display, colormap, color_name, exact_def_return, screen_def_return)Display *display;Colormap colormap;char *color_name;XColor *exact_def_return, *screen_def_return;display Specifies the connection to the X server.colormap Specifies the colormap.color_nameSpecifies the color name string (for example, red)whose color definition structure you wantreturned.exact_def_returnReturns the exact RGB values.screen_def_returnReturns the closest RGB values provided by thehardware.│__ The XLookupColor function looks up the string name of acolor with respect to the screen associated with thespecified colormap. It returns both the exact color valuesand the closest values provided by the screen with respectto the visual type of the specified colormap. If the colorname is not in the Host Portable Character Encoding, theresult is implementation-dependent. Use of uppercase orlowercase does not matter. XLookupColor returns nonzero ifthe name is resolved; otherwise, it returns zero.XLookupColor can generate a BadColor error.To map a color name to the exact RGB value, use XParseColor.__│ Status XParseColor(display, colormap, spec, exact_def_return)Display *display;Colormap colormap;char *spec;XColor *exact_def_return;display Specifies the connection to the X server.colormap Specifies the colormap.spec Specifies the color name string; case is ignored.exact_def_returnReturns the exact color value for later use andsets the DoRed, DoGreen, and DoBlue flags.│__ The XParseColor function looks up the string name of a colorwith respect to the screen associated with the specifiedcolormap. It returns the exact color value. If the colorname is not in the Host Portable Character Encoding, theresult is implementation-dependent. Use of uppercase orlowercase does not matter. XParseColor returns nonzero ifthe name is resolved; otherwise, it returns zero.XParseColor can generate a BadColor error.To map a color name to a value in an arbitrary color space,use XcmsLookupColor.__│ Status XcmsLookupColor(display, colormap, color_string, color_exact_return, color_screen_return,result_format)Display *display;Colormap colormap;char *color_string;XcmsColor *color_exact_return, *color_screen_return;XcmsColorFormat result_format;display Specifies the connection to the X server.colormap Specifies the colormap.color_stringSpecifies the color string.color_exact_returnReturns the color specification parsed from thecolor string or parsed from the correspondingstring found in a color-name database.color_screen_returnReturns the color that can be reproduced on thescreen.result_formatSpecifies the color format for the returned colorspecifications (color_screen_return andcolor_exact_return arguments). If the format isXcmsUndefinedFormat and the color string containsa numerical color specification, the specificationis returned in the format used in that numericalcolor specification. If the format isXcmsUndefinedFormat and the color string containsa color name, the specification is returned in theformat used to store the color in the database.│__ The XcmsLookupColor function looks up the string name of acolor with respect to the screen associated with thespecified colormap. It returns both the exact color valuesand the closest values provided by the screen with respectto the visual type of the specified colormap. The valuesare returned in the format specified by result_format. Ifthe color name is not in the Host Portable CharacterEncoding, the result is implementation-dependent. Use ofuppercase or lowercase does not matter. XcmsLookupColorreturns XcmsSuccess or XcmsSuccessWithCompression if thename is resolved; otherwise, it returns XcmsFailure. IfXcmsSuccessWithCompression is returned, the colorspecification returned in color_screen_return is the resultof gamut compression.6.6. Allocating and Freeing Color CellsThere are two ways of allocating color cells: explicitly asread-only entries, one pixel value at a time, or read/write,where you can allocate a number of color cells and planessimultaneously. A read-only cell has its RGB value set bythe server. Read/write cells do not have defined colorsinitially; functions described in the next section must beused to store values into them. Although it is possible forany client to store values into a read/write cell allocatedby another client, read/write cells normally should beconsidered private to the client that allocated them.Read-only colormap cells are shared among clients. Theserver counts each allocation and freeing of the cell byclients. When the last client frees a shared cell, the cellis finally deallocated. If a single client allocates thesame read-only cell multiple times, the server counts eachsuch allocation, not just the first one.To allocate a read-only color cell with an RGB value, useXAllocColor.__│ Status XAllocColor(display, colormap, screen_in_out)Display *display;Colormap colormap;XColor *screen_in_out;display Specifies the connection to the X server.colormap Specifies the colormap.screen_in_outSpecifies and returns the values actually used inthe colormap.│__ The XAllocColor function allocates a read-only colormapentry corresponding to the closest RGB value supported bythe hardware. XAllocColor returns the pixel value of thecolor closest to the specified RGB elements supported by thehardware and returns the RGB value actually used. Thecorresponding colormap cell is read-only. In addition,XAllocColor returns nonzero if it succeeded or zero if itfailed. Multiple clients that request the same effectiveRGB value can be assigned the same read-only entry, thusallowing entries to be shared. When the last clientdeallocates a shared cell, it is deallocated. XAllocColordoes not use or affect the flags in the XColor structure.XAllocColor can generate a BadColor error.To allocate a read-only color cell with a color in arbitraryformat, use XcmsAllocColor.__│ Status XcmsAllocColor(display, colormap, color_in_out, result_format)Display *display;Colormap colormap;XcmsColor *color_in_out;XcmsColorFormat result_format;display Specifies the connection to the X server.colormap Specifies the colormap.color_in_outSpecifies the color to allocate and returns thepixel and color that is actually used in thecolormap.result_formatSpecifies the color format for the returned colorspecification.│__ The XcmsAllocColor function is similar to XAllocColor exceptthe color can be specified in any format. TheXcmsAllocColor function ultimately calls XAllocColor toallocate a read-only color cell (colormap entry) with thespecified color. XcmsAllocColor first converts the colorspecified to an RGB value and then passes this toXAllocColor. XcmsAllocColor returns the pixel value of thecolor cell and the color specification actually allocated.This returned color specification is the result ofconverting the RGB value returned by XAllocColor into theformat specified with the result_format argument. If thereis no interest in a returned color specification,unnecessary computation can be bypassed if result_format isset to XcmsRGBFormat. The corresponding colormap cell isread-only. If this routine returns XcmsFailure, thecolor_in_out color specification is left unchanged.XcmsAllocColor can generate a BadColor error.To allocate a read-only color cell using a color name andreturn the closest color supported by the hardware in RGBformat, use XAllocNamedColor.__│ Status XAllocNamedColor(display, colormap, color_name, screen_def_return, exact_def_return)Display *display;Colormap colormap;char *color_name;XColor *screen_def_return, *exact_def_return;display Specifies the connection to the X server.colormap Specifies the colormap.color_nameSpecifies the color name string (for example, red)whose color definition structure you wantreturned.screen_def_returnReturns the closest RGB values provided by thehardware.exact_def_returnReturns the exact RGB values.│__ The XAllocNamedColor function looks up the named color withrespect to the screen that is associated with the specifiedcolormap. It returns both the exact database definition andthe closest color supported by the screen. The allocatedcolor cell is read-only. The pixel value is returned inscreen_def_return. If the color name is not in the HostPortable Character Encoding, the result isimplementation-dependent. Use of uppercase or lowercasedoes not matter. If screen_def_return and exact_def_returnpoint to the same structure, the pixel field will be setcorrectly, but the color values are undefined.XAllocNamedColor returns nonzero if a cell is allocated;otherwise, it returns zero.XAllocNamedColor can generate a BadColor error.To allocate a read-only color cell using a color name andreturn the closest color supported by the hardware in anarbitrary format, use XcmsAllocNamedColor.__│ Status XcmsAllocNamedColor(display, colormap, color_string, color_screen_return, color_exact_return,result_format)Display *display;Colormap colormap;char *color_string;XcmsColor *color_screen_return;XcmsColor *color_exact_return;XcmsColorFormat result_format;display Specifies the connection to the X server.colormap Specifies the colormap.color_stringSpecifies the color string whose color definitionstructure is to be returned.color_screen_returnReturns the pixel value of the color cell andcolor specification that actually is stored forthat cell.color_exact_returnReturns the color specification parsed from thecolor string or parsed from the correspondingstring found in a color-name database.result_formatSpecifies the color format for the returned colorspecifications (color_screen_return andcolor_exact_return arguments). If the format isXcmsUndefinedFormat and the color string containsa numerical color specification, the specificationis returned in the format used in that numericalcolor specification. If the format isXcmsUndefinedFormat and the color string containsa color name, the specification is returned in theformat used to store the color in the database.│__ The XcmsAllocNamedColor function is similar toXAllocNamedColor except that the color returned can be inany format specified. This function ultimately callsXAllocColor to allocate a read-only color cell with thecolor specified by a color string. The color string isparsed into an XcmsColor structure (see XcmsLookupColor),converted to an RGB value, and finally passed toXAllocColor. If the color name is not in the Host PortableCharacter Encoding, the result is implementation-dependent.Use of uppercase or lowercase does not matter.This function returns both the color specification as aresult of parsing (exact specification) and the actual colorspecification stored (screen specification). This screenspecification is the result of converting the RGB valuereturned by XAllocColor into the format specified inresult_format. If there is no interest in a returned colorspecification, unnecessary computation can be bypassed ifresult_format is set to XcmsRGBFormat. Ifcolor_screen_return and color_exact_return point to the samestructure, the pixel field will be set correctly, but thecolor values are undefined.XcmsAllocNamedColor can generate a BadColor error.To allocate read/write color cell and color planecombinations for a PseudoColor model, use XAllocColorCells.__│ Status XAllocColorCells(display, colormap, contig, plane_masks_return, nplanes,pixels_return, npixels)Display *display;Colormap colormap;Bool contig;unsigned long plane_masks_return[];unsigned int nplanes;unsigned long pixels_return[];unsigned int npixels;display Specifies the connection to the X server.colormap Specifies the colormap.contig Specifies a Boolean value that indicates whetherthe planes must be contiguous.plane_mask_returnReturns an array of plane masks.nplanes Specifies the number of plane masks that are to bereturned in the plane masks array.pixels_returnReturns an array of pixel values.npixels Specifies the number of pixel values that are tobe returned in the pixels_return array.│__ TheXAllocColorCellsfunction allocates read/write color cells.The number of colors must be positive and the number of planes nonnegative,or aBadValueerror results.If ncolors and nplanes are requested,then ncolors pixelsand nplane plane masks are returned.No mask will have any bits set to 1 in common withany other mask or with any of the pixels.By ORing together each pixel with zero or more masks,ncolors * 2nplanes distinct pixels can be produced.All of these areallocated writable by the request.ForGrayScaleorPseudoColor,each mask has exactly one bit set to 1.ForDirectColor,each has exactly three bits set to 1.If contig isTrueand if all masks are ORedtogether, a single contiguous set of bits set to 1 will be formed forGrayScaleorPseudoColorand three contiguous sets of bits set to 1 (one within eachpixel subfield) forDirectColor.The RGB values of the allocatedentries are undefined.XAllocColorCellsreturns nonzero if it succeeded or zero if it failed.XAllocColorCells can generate BadColor and BadValue errors.To allocate read/write color resources for a DirectColormodel, use XAllocColorPlanes.__│ Status XAllocColorPlanes(display, colormap, contig, pixels_return, ncolors, nreds, ngreens,nblues, rmask_return, gmask_return, bmask_return)Display *display;Colormap colormap;Bool contig;unsigned long pixels_return[];int ncolors;int nreds, ngreens, nblues;unsigned long *rmask_return, *gmask_return, *bmask_return;display Specifies the connection to the X server.colormap Specifies the colormap.contig Specifies a Boolean value that indicates whetherthe planes must be contiguous.pixels_returnReturns an array of pixel values.XAllocColorPlanes returns the pixel values in thisarray.ncolors Specifies the number of pixel values that are tobe returned in the pixels_return array.nredsngreensnblues Specify the number of red, green, and blue planes.The value you pass must be nonnegative.rmask_returngmask_returnbmask_returnReturn bit masks for the red, green, and blueplanes.│__ The specified ncolors must be positive;and nreds, ngreens, and nblues must be nonnegative,or aBadValueerror results.If ncolors colors, nreds reds, ngreens greens, and nblues blues are requested,ncolors pixels are returned; and the masks have nreds, ngreens, andnblues bits set to 1, respectively.If contig isTrue,each mask will havea contiguous set of bits set to 1.No mask will have any bits set to 1 in common withany other mask or with any of the pixels.ForDirectColor,each maskwill lie within the corresponding pixel subfield.By ORing togethersubsets of masks with each pixel value,ncolors * 2(nreds+ngreens+nblues) distinct pixel values can be produced.All of these are allocated by the request.However, in thecolormap, there are only ncolors * 2nreds independent red entries,ncolors * 2ngreens independent green entries,and ncolors * 2nblues independent blue entries.This is true even forPseudoColor.When the colormap entry of a pixelvalue is changed (usingXStoreColors,XStoreColor,orXStoreNamedColor),the pixel is decomposed according to the masks,and the corresponding independent entries are updated.XAllocColorPlanesreturns nonzero if it succeeded or zero if it failed.XAllocColorPlanes can generate BadColor and BadValue errors.To free colormap cells, use XFreeColors.__│ XFreeColors(display, colormap, pixels, npixels, planes)Display *display;Colormap colormap;unsigned long pixels[];int npixels;unsigned long planes;display Specifies the connection to the X server.colormap Specifies the colormap.pixels Specifies an array of pixel values that map to thecells in the specified colormap.npixels Specifies the number of pixels.planes Specifies the planes you want to free.│__ The XFreeColors function frees the cells represented bypixels whose values are in the pixels array. The planesargument should not have any bits set to 1 in common withany of the pixels. The set of all pixels is produced byORing together subsets of the planes argument with thepixels. The request frees all of these pixels that wereallocated by the client (using XAllocColor,XAllocNamedColor, XAllocColorCells, and XAllocColorPlanes).Note that freeing an individual pixel obtained fromXAllocColorPlanes may not actually allow it to be reuseduntil all of its related pixels are also freed. Similarly,a read-only entry is not actually freed until it has beenfreed by all clients, and if a client allocates the sameread-only entry multiple times, it must free the entry thatmany times before the entry is actually freed.All specified pixels that are allocated by the client in thecolormap are freed, even if one or more pixels produce anerror. If a specified pixel is not a valid index into thecolormap, a BadValue error results. If a specified pixel isnot allocated by the client (that is, is unallocated or isonly allocated by another client) or if the colormap wascreated with all entries writable (by passing AllocAll toXCreateColormap), a BadAccess error results. If more thanone pixel is in error, the one that gets reported isarbitrary.XFreeColors can generate BadAccess, BadColor, and BadValueerrors.6.7. Modifying and Querying Colormap CellsTo store an RGB value in a single colormap cell, useXStoreColor.__│ XStoreColor(display, colormap, color)Display *display;Colormap colormap;XColor *color;display Specifies the connection to the X server.colormap Specifies the colormap.color Specifies the pixel and RGB values.│__ The XStoreColor function changes the colormap entry of thepixel value specified in the pixel member of the XColorstructure. You specified this value in the pixel member ofthe XColor structure. This pixel value must be a read/writecell and a valid index into the colormap. If a specifiedpixel is not a valid index into the colormap, a BadValueerror results. XStoreColor also changes the red, green,and/or blue color components. You specify which colorcomponents are to be changed by setting DoRed, DoGreen,and/or DoBlue in the flags member of the XColor structure.If the colormap is an installed map for its screen, thechanges are visible immediately.XStoreColor can generate BadAccess, BadColor, and BadValueerrors.To store multiple RGB values in multiple colormap cells, useXStoreColors.__│ XStoreColors(display, colormap, color, ncolors)Display *display;Colormap colormap;XColor color[];int ncolors;display Specifies the connection to the X server.colormap Specifies the colormap.color Specifies an array of color definition structuresto be stored.ncolors Specifies the number of XColor structures in thecolor definition array.│__ The XStoreColors function changes the colormap entries ofthe pixel values specified in the pixel members of theXColor structures. You specify which color components areto be changed by setting DoRed, DoGreen, and/or DoBlue inthe flags member of the XColor structures. If the colormapis an installed map for its screen, the changes are visibleimmediately. XStoreColors changes the specified pixels ifthey are allocated writable in the colormap by any client,even if one or more pixels generates an error. If aspecified pixel is not a valid index into the colormap, aBadValue error results. If a specified pixel either isunallocated or is allocated read-only, a BadAccess errorresults. If more than one pixel is in error, the one thatgets reported is arbitrary.XStoreColors can generate BadAccess, BadColor, and BadValueerrors.To store a color of arbitrary format in a single colormapcell, use XcmsStoreColor.__│ Status XcmsStoreColor(display, colormap, color)Display *display;Colormap colormap;XcmsColor *color;display Specifies the connection to the X server.colormap Specifies the colormap.color Specifies the color cell and the color to store.Values specified in this XcmsColor structureremain unchanged on return.│__ The XcmsStoreColor function converts the color specified inthe XcmsColor structure into RGB values. It then uses thisRGB specification in an XColor structure, whose three flags(DoRed, DoGreen, and DoBlue) are set, in a call toXStoreColor to change the color cell specified by the pixelmember of the XcmsColor structure. This pixel value must bea valid index for the specified colormap, and the color cellspecified by the pixel value must be a read/write cell. Ifthe pixel value is not a valid index, a BadValue errorresults. If the color cell is unallocated or is allocatedread-only, a BadAccess error results. If the colormap is aninstalled map for its screen, the changes are visibleimmediately.Note that XStoreColor has no return value; therefore, anXcmsSuccess return value from this function indicates thatthe conversion to RGB succeeded and the call to XStoreColorwas made. To obtain the actual color stored, useXcmsQueryColor. Because of the screen’s hardwarelimitations or gamut compression, the color stored in thecolormap may not be identical to the color specified.XcmsStoreColor can generate BadAccess, BadColor, andBadValue errors.To store multiple colors of arbitrary format in multiplecolormap cells, use XcmsStoreColors.__│ Status XcmsStoreColors(display, colormap, colors, ncolors, compression_flags_return)Display *display;Colormap colormap;XcmsColor colors[];int ncolors;Bool compression_flags_return[];display Specifies the connection to the X server.colormap Specifies the colormap.colors Specifies the color specification array ofXcmsColor structures, each specifying a color celland the color to store in that cell. Valuesspecified in the array remain unchanged uponreturn.ncolors Specifies the number of XcmsColor structures inthe color-specification array.compression_flags_returnReturns an array of Boolean values indicatingcompression status. If a non-NULL pointer issupplied, each element of the array is set to Trueif the corresponding color was compressed andFalse otherwise. Pass NULL if the compressionstatus is not useful.│__ The XcmsStoreColors function converts the colors specifiedin the array of XcmsColor structures into RGB values andthen uses these RGB specifications in XColor structures,whose three flags (DoRed, DoGreen, and DoBlue) are set, in acall to XStoreColors to change the color cells specified bythe pixel member of the corresponding XcmsColor structure.Each pixel value must be a valid index for the specifiedcolormap, and the color cell specified by each pixel valuemust be a read/write cell. If a pixel value is not a validindex, a BadValue error results. If a color cell isunallocated or is allocated read-only, a BadAccess errorresults. If more than one pixel is in error, the one thatgets reported is arbitrary. If the colormap is an installedmap for its screen, the changes are visible immediately.Note that XStoreColors has no return value; therefore, anXcmsSuccess return value from this function indicates thatconversions to RGB succeeded and the call to XStoreColorswas made. To obtain the actual colors stored, useXcmsQueryColors. Because of the screen’s hardwarelimitations or gamut compression, the colors stored in thecolormap may not be identical to the colors specified.XcmsStoreColors can generate BadAccess, BadColor, andBadValue errors.To store a color specified by name in a single colormapcell, use XStoreNamedColor.__│ XStoreNamedColor(display, colormap, color, pixel, flags)Display *display;Colormap colormap;char *color;unsigned long pixel;int flags;display Specifies the connection to the X server.colormap Specifies the colormap.color Specifies the color name string (for example,red).pixel Specifies the entry in the colormap.flags Specifies which red, green, and blue componentsare set.│__ The XStoreNamedColor function looks up the named color withrespect to the screen associated with the colormap andstores the result in the specified colormap. The pixelargument determines the entry in the colormap. The flagsargument determines which of the red, green, and bluecomponents are set. You can set this member to the bitwiseinclusive OR of the bits DoRed, DoGreen, and DoBlue. If thecolor name is not in the Host Portable Character Encoding,the result is implementation-dependent. Use of uppercase orlowercase does not matter. If the specified pixel is not avalid index into the colormap, a BadValue error results. Ifthe specified pixel either is unallocated or is allocatedread-only, a BadAccess error results.XStoreNamedColor can generate BadAccess, BadColor, BadName,and BadValue errors.The XQueryColor and XQueryColors functions take pixel valuesin the pixel member of XColor structures and store in thestructures the RGB values for those pixels from thespecified colormap. The values returned for an unallocatedentry are undefined. These functions also set the flagsmember in the XColor structure to all three colors. If apixel is not a valid index into the specified colormap, aBadValue error results. If more than one pixel is in error,the one that gets reported is arbitrary.To query the RGB value of a single colormap cell, useXQueryColor.__│ XQueryColor(display, colormap, def_in_out)Display *display;Colormap colormap;XColor *def_in_out;display Specifies the connection to the X server.colormap Specifies the colormap.def_in_outSpecifies and returns the RGB values for the pixelspecified in the structure.│__ The XQueryColor function returns the current RGB value forthe pixel in the XColor structure and sets the DoRed,DoGreen, and DoBlue flags.XQueryColor can generate BadColor and BadValue errors.To query the RGB values of multiple colormap cells, useXQueryColors.__│ XQueryColors(display, colormap, defs_in_out, ncolors)Display *display;Colormap colormap;XColor defs_in_out[];int ncolors;display Specifies the connection to the X server.colormap Specifies the colormap.defs_in_outSpecifies and returns an array of color definitionstructures for the pixel specified in thestructure.ncolors Specifies the number of XColor structures in thecolor definition array.│__ The XQueryColors function returns the RGB value for eachpixel in each XColor structure and sets the DoRed, DoGreen,and DoBlue flags in each structure.XQueryColors can generate BadColor and BadValue errors.To query the color of a single colormap cell in an arbitraryformat, use XcmsQueryColor.__│ Status XcmsQueryColor(display, colormap, color_in_out, result_format)Display *display;Colormap colormap;XcmsColor *color_in_out;XcmsColorFormat result_format;display Specifies the connection to the X server.colormap Specifies the colormap.color_in_outSpecifies the pixel member that indicates thecolor cell to query. The color specificationstored for the color cell is returned in thisXcmsColor structure.result_formatSpecifies the color format for the returned colorspecification.│__ The XcmsQueryColor function obtains the RGB value for thepixel value in the pixel member of the specified XcmsColorstructure and then converts the value to the target formatas specified by the result_format argument. If the pixel isnot a valid index in the specified colormap, a BadValueerror results.XcmsQueryColor can generate BadColor and BadValue errors.To query the color of multiple colormap cells in anarbitrary format, use XcmsQueryColors.__│ Status XcmsQueryColors(display, colormap, colors_in_out, ncolors, result_format)Display *display;Colormap colormap;XcmsColor colors_in_out[];unsigned int ncolors;XcmsColorFormat result_format;display Specifies the connection to the X server.colormap Specifies the colormap.colors_in_outSpecifies an array of XcmsColor structures, eachpixel member indicating the color cell to query.The color specifications for the color cells arereturned in these structures.ncolors Specifies the number of XcmsColor structures inthe color-specification array.result_formatSpecifies the color format for the returned colorspecification.│__ The XcmsQueryColors function obtains the RGB values forpixel values in the pixel members of XcmsColor structuresand then converts the values to the target format asspecified by the result_format argument. If a pixel is nota valid index into the specified colormap, a BadValue errorresults. If more than one pixel is in error, the one thatgets reported is arbitrary.XcmsQueryColors can generate BadColor and BadValue errors.6.8. Color Conversion Context FunctionsThis section describes functions to create, modify, andquery Color Conversion Contexts (CCCs).Associated with each colormap is an initial CCCtransparently generated by Xlib. Therefore, when youspecify a colormap as an argument to a function, you areindirectly specifying a CCC. The CCC attributes that can bemodified by the X client are:• Client White Point• Gamut compression procedure and client data• White point adjustment procedure and client dataThe initial values for these attributes are implementationspecific. The CCC attributes for subsequently created CCCscan be defined by changing the CCC attributes of the defaultCCC. There is a default CCC associated with each screen.6.8.1. Getting and Setting the Color Conversion Context ofa ColormapTo obtain the CCC associated with a colormap, useXcmsCCCOfColormap.__│ XcmsCCC XcmsCCCOfColormap(display, colormap)Display *display;Colormap colormap;display Specifies the connection to the X server.colormap Specifies the colormap.│__ The XcmsCCCOfColormap function returns the CCC associatedwith the specified colormap. Once obtained, the CCCattributes can be queried or modified. Unless the CCCassociated with the specified colormap is changed withXcmsSetCCCOfColormap, this CCC is used when the specifiedcolormap is used as an argument to color functions.To change the CCC associated with a colormap, useXcmsSetCCCOfColormap.__│ XcmsCCC XcmsSetCCCOfColormap(display, colormap, ccc)Display *display;Colormap colormap;XcmsCCC ccc;display Specifies the connection to the X server.colormap Specifies the colormap.ccc Specifies the CCC.│__ The XcmsSetCCCOfColormap function changes the CCC associatedwith the specified colormap. It returns the CCC previouslyassociated with the colormap. If they are not used again inthe application, CCCs should be freed by callingXcmsFreeCCC. Several colormaps may share the same CCCwithout restriction; this includes the CCCs generated byXlib with each colormap. Xlib, however, creates a new CCCwith each new colormap.6.8.2. Obtaining the Default Color Conversion ContextYou can change the default CCC attributes for subsequentlycreated CCCs by changing the CCC attributes of the defaultCCC. A default CCC is associated with each screen.To obtain the default CCC for a screen, use XcmsDefaultCCC.__│ XcmsCCC XcmsDefaultCCC(display, screen_number)Display *display;int screen_number;display Specifies the connection to the X server.screen_numberSpecifies the appropriate screen number on thehost server.│__ The XcmsDefaultCCC function returns the default CCC for thespecified screen. Its visual is the default visual of thescreen. Its initial gamut compression and white pointadjustment procedures as well as the associated client dataare implementation specific.6.8.3. Color Conversion Context MacrosApplications should not directly modify any part of theXcmsCCC. The following lists the C language macros, theircorresponding function equivalents for other languagebindings, and what data they both can return.__│ DisplayOfCCC(ccc)XcmsCCC ccc;Display *XcmsDisplayOfCCC(ccc)XcmsCCC ccc;ccc Specifies the CCC.│__ Both return the display associated with the specified CCC.__│ VisualOfCCC(ccc)XcmsCCC ccc;Visual *XcmsVisualOfCCC(ccc)XcmsCCC ccc;ccc Specifies the CCC.│__ Both return the visual associated with the specified CCC.__│ ScreenNumberOfCCC(ccc)XcmsCCC ccc;int XcmsScreenNumberOfCCC(ccc)XcmsCCC ccc;ccc Specifies the CCC.│__ Both return the number of the screen associated with thespecified CCC.__│ ScreenWhitePointOfCCC(ccc)XcmsCCC ccc;XcmsColor *XcmsScreenWhitePointOfCCC(ccc)XcmsCCC ccc;ccc Specifies the CCC.│__ Both return the white point of the screen associated withthe specified CCC.__│ ClientWhitePointOfCCC(ccc)XcmsCCC ccc;XcmsColor *XcmsClientWhitePointOfCCC(ccc)XcmsCCC ccc;ccc Specifies the CCC.│__ Both return the Client White Point of the specified CCC.6.8.4. Modifying Attributes of a Color Conversion ContextTo set the Client White Point in the CCC, useXcmsSetWhitePoint.__│ Status XcmsSetWhitePoint(ccc, color)XcmsCCC ccc;XcmsColor *color;ccc Specifies the CCC.color Specifies the new Client White Point.│__ The XcmsSetWhitePoint function changes the Client WhitePoint in the specified CCC. Note that the pixel member isignored and that the color specification is left unchangedupon return. The format for the new white point must beXcmsCIEXYZFormat, XcmsCIEuvYFormat, XcmsCIExyYFormat, orXcmsUndefinedFormat. If the color argument is NULL, thisfunction sets the format component of the Client White Pointspecification to XcmsUndefinedFormat, indicating that theClient White Point is assumed to be the same as the ScreenWhite Point.This function returns nonzero status if the format for thenew white point is valid; otherwise, it returns zero.To set the gamut compression procedure and correspondingclient data in a specified CCC, use XcmsSetCompressionProc.__│ XcmsCompressionProc XcmsSetCompressionProc(ccc, compression_proc, client_data)XcmsCCC ccc;XcmsCompressionProc compression_proc;XPointer client_data;ccc Specifies the CCC.compression_procSpecifies the gamut compression procedure that isto be applied when a color lies outside thescreen’s color gamut. If NULL is specified and afunction using this CCC must convert a colorspecification to a device-dependent format andencounters a color that lies outside the screen’scolor gamut, that function will returnXcmsFailure.client_dataSpecifies client data for the gamut compressionprocedure or NULL.│__ The XcmsSetCompressionProc function first sets the gamutcompression procedure and client data in the specified CCCwith the newly specified procedure and client data and thenreturns the old procedure.To set the white point adjustment procedure andcorresponding client data in a specified CCC, useXcmsSetWhiteAdjustProc.__│ XcmsWhiteAdjustProc XcmsSetWhiteAdjustProc(ccc, white_adjust_proc, client_data)XcmsCCC ccc;XcmsWhiteAdjustProc white_adjust_proc;XPointer client_data;ccc Specifies the CCC.white_adjust_procSpecifies the white point adjustment procedure.client_dataSpecifies client data for the white pointadjustment procedure or NULL.│__ The XcmsSetWhiteAdjustProc function first sets the whitepoint adjustment procedure and client data in the specifiedCCC with the newly specified procedure and client data andthen returns the old procedure.6.8.5. Creating and Freeing a Color Conversion ContextYou can explicitly create a CCC within your application bycalling XcmsCreateCCC. These created CCCs can then be usedby those functions that explicitly call for a CCC argument.Old CCCs that will not be used by the application should befreed using XcmsFreeCCC.To create a CCC, use XcmsCreateCCC.__│ XcmsCCC XcmsCreateCCC(display, screen_number, visual, client_white_point, compression_proc,compression_client_data, white_adjust_proc, white_adjust_client_data)Display *display;int screen_number;Visual *visual;XcmsColor *client_white_point;XcmsCompressionProc compression_proc;XPointer compression_client_data;XcmsWhiteAdjustProc white_adjust_proc;XPointer white_adjust_client_data;display Specifies the connection to the X server.screen_numberSpecifies the appropriate screen number on thehost server.visual Specifies the visual type.client_white_pointSpecifies the Client White Point. If NULL isspecified, the Client White Point is to be assumedto be the same as the Screen White Point. Notethat the pixel member is ignored.compression_procSpecifies the gamut compression procedure that isto be applied when a color lies outside thescreen’s color gamut. If NULL is specified and afunction using this CCC must convert a colorspecification to a device-dependent format andencounters a color that lies outside the screen’scolor gamut, that function will returnXcmsFailure.compression_client_dataSpecifies client data for use by the gamutcompression procedure or NULL.white_adjust_procSpecifies the white adjustment procedure that isto be applied when the Client White Point differsfrom the Screen White Point. NULL indicates thatno white point adjustment is desired.white_adjust_client_dataSpecifies client data for use with the white pointadjustment procedure or NULL.│__ The XcmsCreateCCC function creates a CCC for the specifieddisplay, screen, and visual.To free a CCC, use XcmsFreeCCC.__│ void XcmsFreeCCC(ccc)XcmsCCC ccc;ccc Specifies the CCC.│__ The XcmsFreeCCC function frees the memory used for thespecified CCC. Note that default CCCs and those currentlyassociated with colormaps are ignored.6.9. Converting between Color SpacesTo convert an array of color specifications in arbitrarycolor formats to a single destination format, useXcmsConvertColors.__│ Status XcmsConvertColors(ccc, colors_in_out, ncolors, target_format, compression_flags_return)XcmsCCC ccc;XcmsColor colors_in_out[];unsigned int ncolors;XcmsColorFormat target_format;Bool compression_flags_return[];ccc Specifies the CCC. If conversion is betweendevice-independent color spaces only (for example,TekHVC to CIELuv), the CCC is necessary only tospecify the Client White Point.colors_in_outSpecifies an array of color specifications. Pixelmembers are ignored and remain unchanged uponreturn.ncolors Specifies the number of XcmsColor structures inthe color-specification array.target_formatSpecifies the target color specification format.compression_flags_returnReturns an array of Boolean values indicatingcompression status. If a non-NULL pointer issupplied, each element of the array is set to Trueif the corresponding color was compressed andFalse otherwise. Pass NULL if the compressionstatus is not useful.│__ The XcmsConvertColors function converts the colorspecifications in the specified array of XcmsColorstructures from their current format to a single targetformat, using the specified CCC. When the return value isXcmsFailure, the contents of the color specification arrayare left unchanged.The array may contain a mixture of color specificationformats (for example, 3 CIE XYZ, 2 CIE Luv, and so on).When the array contains both device-independent anddevice-dependent color specifications and the target_formatargument specifies a device-dependent format (for example,XcmsRGBiFormat, XcmsRGBFormat), all specifications areconverted to CIE XYZ format and then to the targetdevice-dependent format.6.10. Callback FunctionsThis section describes the gamut compression and white pointadjustment callbacks.The gamut compression procedure specified in the CCC iscalled when an attempt to convert a color specification fromXcmsCIEXYZ to a device-dependent format (typically XcmsRGBi)results in a color that lies outside the screen’s colorgamut. If the gamut compression procedure requires clientdata, this data is passed via the gamut compression clientdata in the CCC.During color specification conversion betweendevice-independent and device-dependent color spaces, if awhite point adjustment procedure is specified in the CCC, itis triggered when the Client White Point and Screen WhitePoint differ. If required, the client data is obtained fromthe CCC.6.10.1. Prototype Gamut Compression ProcedureThe gamut compression callback interface must adhere to thefollowing:__│ typedef Status (*XcmsCompressionProc)(ccc, colors_in_out, ncolors, index, compression_flags_return)XcmsCCC ccc;XcmsColor colors_in_out[];unsigned int ncolors;unsigned int index;Bool compression_flags_return[];ccc Specifies the CCC.colors_in_outSpecifies an array of color specifications. Pixelmembers should be ignored and must remainunchanged upon return.ncolors Specifies the number of XcmsColor structures inthe color-specification array.index Specifies the index into the array of XcmsColorstructures for the encountered color specificationthat lies outside the screen’s color gamut. Validvalues are 0 (for the first element) to ncolors −1.compression_flags_returnReturns an array of Boolean values for indicatingcompression status. If a non-NULL pointer issupplied and a color at a given index iscompressed, then True should be stored at thecorresponding index in this array; otherwise, thearray should not be modified.│__ When implementing a gamut compression procedure, considerthe following rules and assumptions:• The gamut compression procedure can attempt to compressone or multiple specifications at a time.• When called, elements 0 to index − 1 in the colorspecification array can be assumed to fall within thescreen’s color gamut. In addition, these colorspecifications are already in some device-dependentformat (typically XcmsRGBi). If any modifications aremade to these color specifications, they must be intheir initial device-dependent format upon return.• When called, the element in the color specificationarray specified by the index argument contains thecolor specification outside the screen’s color gamutencountered by the calling routine. In addition, thiscolor specification can be assumed to be in XcmsCIEXYZ.Upon return, this color specification must be inXcmsCIEXYZ.• When called, elements from index to ncolors − 1 in thecolor specification array may or may not fall withinthe screen’s color gamut. In addition, these colorspecifications can be assumed to be in XcmsCIEXYZ. Ifany modifications are made to these colorspecifications, they must be in XcmsCIEXYZ upon return.• The color specifications passed to the gamutcompression procedure have already been adjusted to theScreen White Point. This means that at this point thecolor specification’s white point is the Screen WhitePoint.• If the gamut compression procedure uses adevice-independent color space not initially accessiblefor use in the color management system, useXcmsAddColorSpace to ensure that it is added.6.10.2. Supplied Gamut Compression ProceduresThe following equations are useful in describing gamutcompression functions:CIELabPsychometricChroma=sqrt(a_star2+b_star2)CIELabPsychometricHue=tan−1⎣b__staa star⎦CIELuvPsychometricChroma=sqrt(u_star2+v_star2)CIELuvPsychometricHue=tan−1⎣v__stau star⎦The gamut compression callback procedures provided by Xlibare as follows:• XcmsCIELabClipLThis brings the encountered out-of-gamut colorspecification into the screen’s color gamut by reducingor increasing CIE metric lightness (L*) in the CIEL*a*b* color space until the color is within the gamut.If the Psychometric Chroma of the color specificationis beyond maximum for the Psychometric Hue Angle, thenwhile maintaining the same Psychometric Hue Angle, thecolor will be clipped to the CIE L*a*b* coordinates ofmaximum Psychometric Chroma. See XcmsCIELabQueryMaxC.No client data is necessary.• XcmsCIELabClipabThis brings the encountered out-of-gamut colorspecification into the screen’s color gamut by reducingPsychometric Chroma, while maintaining Psychometric HueAngle, until the color is within the gamut. No clientdata is necessary.• XcmsCIELabClipLabThis brings the encountered out-of-gamut colorspecification into the screen’s color gamut byreplacing it with CIE L*a*b* coordinates that fallwithin the color gamut while maintaining the originalPsychometric Hue Angle and whose vector to the originalcoordinates is the shortest attainable. No client datais necessary.• XcmsCIELuvClipLThis brings the encountered out-of-gamut colorspecification into the screen’s color gamut by reducingor increasing CIE metric lightness (L*) in the CIEL*u*v* color space until the color is within the gamut.If the Psychometric Chroma of the color specificationis beyond maximum for the Psychometric Hue Angle, then,while maintaining the same Psychometric Hue Angle, thecolor will be clipped to the CIE L*u*v* coordinates ofmaximum Psychometric Chroma. See XcmsCIELuvQueryMaxC.No client data is necessary.• XcmsCIELuvClipuvThis brings the encountered out-of-gamut colorspecification into the screen’s color gamut by reducingPsychometric Chroma, while maintaining Psychometric HueAngle, until the color is within the gamut. No clientdata is necessary.• XcmsCIELuvClipLuvThis brings the encountered out-of-gamut colorspecification into the screen’s color gamut byreplacing it with CIE L*u*v* coordinates that fallwithin the color gamut while maintaining the originalPsychometric Hue Angle and whose vector to the originalcoordinates is the shortest attainable. No client datais necessary.• XcmsTekHVCClipVThis brings the encountered out-of-gamut colorspecification into the screen’s color gamut by reducingor increasing the Value dimension in the TekHVC colorspace until the color is within the gamut. If Chromaof the color specification is beyond maximum for theparticular Hue, then, while maintaining the same Hue,the color will be clipped to the Value and Chromacoordinates that represent maximum Chroma for thatparticular Hue. No client data is necessary.• XcmsTekHVCClipCThis brings the encountered out-of-gamut colorspecification into the screen’s color gamut by reducingthe Chroma dimension in the TekHVC color space untilthe color is within the gamut. No client data isnecessary.• XcmsTekHVCClipVCThis brings the encountered out-of-gamut colorspecification into the screen’s color gamut byreplacing it with TekHVC coordinates that fall withinthe color gamut while maintaining the original Hue andwhose vector to the original coordinates is theshortest attainable. No client data is necessary.6.10.3. Prototype White Point Adjustment ProcedureThe white point adjustment procedure interface must adhereto the following:__│ typedef Status (*XcmsWhiteAdjustProc)(ccc, initial_white_point, target_white_point, target_format,colors_in_out, ncolors, compression_flags_return)XcmsCCC ccc;XcmsColor *initial_white_point;XcmsColor *target_white_point;XcmsColorFormat target_format;XcmsColor colors_in_out[];unsigned int ncolors;Bool compression_flags_return[];ccc Specifies the CCC.initial_white_pointSpecifies the initial white point.target_white_pointSpecifies the target white point.target_formatSpecifies the target color specification format.colors_in_outSpecifies an array of color specifications. Pixelmembers should be ignored and must remainunchanged upon return.ncolors Specifies the number of XcmsColor structures inthe color-specification array.compression_flags_returnReturns an array of Boolean values for indicatingcompression status. If a non-NULL pointer issupplied and a color at a given index iscompressed, then True should be stored at thecorresponding index in this array; otherwise, thearray should not be modified.│__ 6.10.4. Supplied White Point Adjustment ProceduresWhite point adjustment procedures provided by Xlib are asfollows:• XcmsCIELabWhiteShiftColorsThis uses the CIE L*a*b* color space for adjusting thechromatic character of colors to compensate for thechromatic differences between the source anddestination white points. This procedure simplyconverts the color specifications to XcmsCIELab usingthe source white point and then converts to the targetspecification format using the destination’s whitepoint. No client data is necessary.• XcmsCIELuvWhiteShiftColorsThis uses the CIE L*u*v* color space for adjusting thechromatic character of colors to compensate for thechromatic differences between the source anddestination white points. This procedure simplyconverts the color specifications to XcmsCIELuv usingthe source white point and then converts to the targetspecification format using the destination’s whitepoint. No client data is necessary.• XcmsTekHVCWhiteShiftColorsThis uses the TekHVC color space for adjusting thechromatic character of colors to compensate for thechromatic differences between the source anddestination white points. This procedure simplyconverts the color specifications to XcmsTekHVC usingthe source white point and then converts to the targetspecification format using the destination’s whitepoint. An advantage of this procedure over thosepreviously described is an attempt to minimize hueshift. No client data is necessary.From an implementation point of view, these white pointadjustment procedures convert the color specifications to adevice-independent but white-point-dependent color space(for example, CIE L*u*v*, CIE L*a*b*, TekHVC) using onewhite point and then converting those specifications to thetarget color space using another white point. In otherwords, the specification goes in the color space with onewhite point but comes out with another white point,resulting in a chromatic shift based on the chromaticdisplacement between the initial white point and targetwhite point. The CIE color spaces that are assumed to bewhite-point-independent are CIE u’v’Y, CIE XYZ, and CIE xyY.When developing a custom white point adjustment procedurethat uses a device-independent color space not initiallyaccessible for use in the color management system, useXcmsAddColorSpace to ensure that it is added.As an example, if the CCC specifies a white point adjustmentprocedure and if the Client White Point and Screen WhitePoint differ, the XcmsAllocColor function will use the whitepoint adjustment procedure twice:• Once to convert to XcmsRGB• A second time to convert from XcmsRGBFor example, assume the specification is in XcmsCIEuvY andthe adjustment procedure is XcmsCIELuvWhiteShiftColors.During conversion to XcmsRGB, the call to XcmsAllocColorresults in the following series of color specificationconversions:• From XcmsCIEuvY to XcmsCIELuv using the Client WhitePoint• From XcmsCIELuv to XcmsCIEuvY using the Screen WhitePoint• From XcmsCIEuvY to XcmsCIEXYZ (CIE u’v’Y and XYZ arewhite-point-independent color spaces)• From XcmsCIEXYZ to XcmsRGBi• From XcmsRGBi to XcmsRGBThe resulting RGB specification is passed to XAllocColor,and the RGB specification returned by XAllocColor isconverted back to XcmsCIEuvY by reversing the colorconversion sequence.6.11. Gamut Querying FunctionsThis section describes the gamut querying functions thatXlib provides. These functions allow the client to querythe boundary of the screen’s color gamut in terms of the CIEL*a*b*, CIE L*u*v*, and TekHVC color spaces. Functions arealso provided that allow you to query the colorspecification of:• White (full-intensity red, green, and blue)• Red (full-intensity red while green and blue are zero)• Green (full-intensity green while red and blue arezero)• Blue (full-intensity blue while red and green are zero)• Black (zero-intensity red, green, and blue)The white point associated with color specifications passedto and returned from these gamut querying functions isassumed to be the Screen White Point. This is a reasonableassumption, because the client is trying to query thescreen’s color gamut.The following naming convention is used for the Max and Minfunctions:Xcms<color_space>QueryMax<dimensions>Xcms<color_space>QueryMin<dimensions>The <dimensions> consists of a letter or letters thatidentify the dimensions of the color space that are notfixed. For example, XcmsTekHVCQueryMaxC is given a fixedHue and Value for which maximum Chroma is found.6.11.1. Red, Green, and Blue QueriesTo obtain the color specification for black (zero-intensityred, green, and blue), use XcmsQueryBlack.__│ Status XcmsQueryBlack(ccc, target_format, color_return)XcmsCCC ccc;XcmsColorFormat target_format;XcmsColor *color_return;ccc Specifies the CCC. The CCC’s Client White Pointand white point adjustment procedures are ignored.target_formatSpecifies the target color specification format.color_returnReturns the color specification in the specifiedtarget format for zero-intensity red, green, andblue. The white point associated with thereturned color specification is the Screen WhitePoint. The value returned in the pixel member isundefined.│__ The XcmsQueryBlack function returns the color specificationin the specified target format for zero-intensity red,green, and blue.To obtain the color specification for blue (full-intensityblue while red and green are zero), use XcmsQueryBlue.__│ Status XcmsQueryBlue(ccc, target_format, color_return)XcmsCCC ccc;XcmsColorFormat target_format;XcmsColor *color_return;ccc Specifies the CCC. The CCC’s Client White Pointand white point adjustment procedures are ignored.target_formatSpecifies the target color specification format.color_returnReturns the color specification in the specifiedtarget format for full-intensity blue while redand green are zero. The white point associatedwith the returned color specification is theScreen White Point. The value returned in thepixel member is undefined.│__ The XcmsQueryBlue function returns the color specificationin the specified target format for full-intensity blue whilered and green are zero.To obtain the color specification for green (full-intensitygreen while red and blue are zero), use XcmsQueryGreen.__│ Status XcmsQueryGreen(ccc, target_format, color_return)XcmsCCC ccc;XcmsColorFormat target_format;XcmsColor *color_return;ccc Specifies the CCC. The CCC’s Client White Pointand white point adjustment procedures are ignored.target_formatSpecifies the target color specification format.color_returnReturns the color specification in the specifiedtarget format for full-intensity green while redand blue are zero. The white point associatedwith the returned color specification is theScreen White Point. The value returned in thepixel member is undefined.│__ The XcmsQueryGreen function returns the color specificationin the specified target format for full-intensity greenwhile red and blue are zero.To obtain the color specification for red (full-intensityred while green and blue are zero), use XcmsQueryRed.__│ Status XcmsQueryRed(ccc, target_format, color_return)XcmsCCC ccc;XcmsColorFormat target_format;XcmsColor *color_return;ccc Specifies the CCC. The CCC’s Client White Pointand white point adjustment procedures are ignored.target_formatSpecifies the target color specification format.color_returnReturns the color specification in the specifiedtarget format for full-intensity red while greenand blue are zero. The white point associatedwith the returned color specification is theScreen White Point. The value returned in thepixel member is undefined.│__ The XcmsQueryRed function returns the color specification inthe specified target format for full-intensity red whilegreen and blue are zero.To obtain the color specification for white (full-intensityred, green, and blue), use XcmsQueryWhite.__│ Status XcmsQueryWhite(ccc, target_format, color_return)XcmsCCC ccc;XcmsColorFormat target_format;XcmsColor *color_return;ccc Specifies the CCC. The CCC’s Client White Pointand white point adjustment procedures are ignored.target_formatSpecifies the target color specification format.color_returnReturns the color specification in the specifiedtarget format for full-intensity red, green, andblue. The white point associated with thereturned color specification is the Screen WhitePoint. The value returned in the pixel member isundefined.│__ The XcmsQueryWhite function returns the color specificationin the specified target format for full-intensity red,green, and blue.6.11.2. CIELab QueriesThe following equations are useful in describing the CIELabquery functions:CIELabPsychometricChroma=sqrt(a_star2+b_star2)CIELabPsychometricHue=tan−1⎣b__staa star⎦To obtain the CIE L*a*b* coordinates of maximum PsychometricChroma for a given Psychometric Hue Angle and CIE metriclightness (L*), use XcmsCIELabQueryMaxC.__│ Status XcmsCIELabQueryMaxC(ccc, hue_angle, L_star, color_return)XcmsCCC ccc;XcmsFloat hue_angle;XcmsFloat L_star;XcmsColor *color_return;ccc Specifies the CCC. The CCC’s Client White Pointand white point adjustment procedures are ignored.hue_angle Specifies the hue angle (in degrees) at which tofind maximum chroma.L_star Specifies the lightness (L*) at which to findmaximum chroma.color_returnReturns the CIE L*a*b* coordinates of maximumchroma displayable by the screen for the given hueangle and lightness. The white point associatedwith the returned color specification is theScreen White Point. The value returned in thepixel member is undefined.│__ The XcmsCIELabQueryMaxC function, given a hue angle andlightness, finds the point of maximum chroma displayable bythe screen. It returns this point in CIE L*a*b*coordinates.To obtain the CIE L*a*b* coordinates of maximum CIE metriclightness (L*) for a given Psychometric Hue Angle andPsychometric Chroma, use XcmsCIELabQueryMaxL.__│ Status XcmsCIELabQueryMaxL(ccc, hue_angle, chroma, color_return)XcmsCCC ccc;XcmsFloat hue_angle;XcmsFloat chroma;XcmsColor *color_return;ccc Specifies the CCC. The CCC’s Client White Pointand white point adjustment procedures are ignored.hue_angle Specifies the hue angle (in degrees) at which tofind maximum lightness.chroma Specifies the chroma at which to find maximumlightness.color_returnReturns the CIE L*a*b* coordinates of maximumlightness displayable by the screen for the givenhue angle and chroma. The white point associatedwith the returned color specification is theScreen White Point. The value returned in thepixel member is undefined.│__ The XcmsCIELabQueryMaxL function, given a hue angle andchroma, finds the point in CIE L*a*b* color space of maximumlightness (L*) displayable by the screen. It returns thispoint in CIE L*a*b* coordinates. An XcmsFailure returnvalue usually indicates that the given chroma is beyondmaximum for the given hue angle.To obtain the CIE L*a*b* coordinates of maximum PsychometricChroma for a given Psychometric Hue Angle, useXcmsCIELabQueryMaxLC.__│ Status XcmsCIELabQueryMaxLC(ccc, hue_angle, color_return)XcmsCCC ccc;XcmsFloat hue_angle;XcmsColor *color_return;ccc Specifies the CCC. The CCC’s Client White Pointand white point adjustment procedures are ignored.hue_angle Specifies the hue angle (in degrees) at which tofind maximum chroma.color_returnReturns the CIE L*a*b* coordinates of maximumchroma displayable by the screen for the given hueangle. The white point associated with thereturned color specification is the Screen WhitePoint. The value returned in the pixel member isundefined.│__ The XcmsCIELabQueryMaxLC function, given a hue angle, findsthe point of maximum chroma displayable by the screen. Itreturns this point in CIE L*a*b* coordinates.To obtain the CIE L*a*b* coordinates of minimum CIE metriclightness (L*) for a given Psychometric Hue Angle andPsychometric Chroma, use XcmsCIELabQueryMinL.__│ Status XcmsCIELabQueryMinL(ccc, hue_angle, chroma, color_return)XcmsCCC ccc;XcmsFloat hue_angle;XcmsFloat chroma;XcmsColor *color_return;ccc Specifies the CCC. The CCC’s Client White Pointand white point adjustment procedures are ignored.hue_angle Specifies the hue angle (in degrees) at which tofind minimum lightness.chroma Specifies the chroma at which to find minimumlightness.color_returnReturns the CIE L*a*b* coordinates of minimumlightness displayable by the screen for the givenhue angle and chroma. The white point associatedwith the returned color specification is theScreen White Point. The value returned in thepixel member is undefined.│__ The XcmsCIELabQueryMinL function, given a hue angle andchroma, finds the point of minimum lightness (L*)displayable by the screen. It returns this point in CIEL*a*b* coordinates. An XcmsFailure return value usuallyindicates that the given chroma is beyond maximum for thegiven hue angle.6.11.3. CIELuv QueriesThe following equations are useful in describing the CIELuvquery functions:CIELuvPsychometricChroma=sqrt(u_star2+v_star2)CIELuvPsychometricHue=tan−1⎣v__stau star⎦To obtain the CIE L*u*v* coordinates of maximum PsychometricChroma for a given Psychometric Hue Angle and CIE metriclightness (L*), use XcmsCIELuvQueryMaxC.__│ Status XcmsCIELuvQueryMaxC(ccc, hue_angle, L_star, color_return)XcmsCCC ccc;XcmsFloat hue_angle;XcmsFloat L_star;XcmsColor *color_return;ccc Specifies the CCC. The CCC’s Client White Pointand white point adjustment procedures are ignored.hue_angle Specifies the hue angle (in degrees) at which tofind maximum chroma.L_star Specifies the lightness (L*) at which to findmaximum chroma.color_returnReturns the CIE L*u*v* coordinates of maximumchroma displayable by the screen for the given hueangle and lightness. The white point associatedwith the returned color specification is theScreen White Point. The value returned in thepixel member is undefined.│__ The XcmsCIELuvQueryMaxC function, given a hue angle andlightness, finds the point of maximum chroma displayable bythe screen. It returns this point in CIE L*u*v*coordinates.To obtain the CIE L*u*v* coordinates of maximum CIE metriclightness (L*) for a given Psychometric Hue Angle andPsychometric Chroma, use XcmsCIELuvQueryMaxL.__│ Status XcmsCIELuvQueryMaxL(ccc, hue_angle, chroma, color_return)XcmsCCC ccc;XcmsFloat hue_angle;XcmsFloat chroma;XcmsColor *color_return;ccc Specifies the CCC. The CCC’s Client White Pointand white point adjustment procedures are ignored.hue_angle Specifies the hue angle (in degrees) at which tofind maximum lightness.L_star Specifies the lightness (L*) at which to findmaximum lightness.color_returnReturns the CIE L*u*v* coordinates of maximumlightness displayable by the screen for the givenhue angle and chroma. The white point associatedwith the returned color specification is theScreen White Point. The value returned in thepixel member is undefined.│__ The XcmsCIELuvQueryMaxL function, given a hue angle andchroma, finds the point in CIE L*u*v* color space of maximumlightness (L*) displayable by the screen. It returns thispoint in CIE L*u*v* coordinates. An XcmsFailure returnvalue usually indicates that the given chroma is beyondmaximum for the given hue angle.To obtain the CIE L*u*v* coordinates of maximum PsychometricChroma for a given Psychometric Hue Angle, useXcmsCIELuvQueryMaxLC.__│ Status XcmsCIELuvQueryMaxLC(ccc, hue_angle, color_return)XcmsCCC ccc;XcmsFloat hue_angle;XcmsColor *color_return;ccc Specifies the CCC. The CCC’s Client White Pointand white point adjustment procedures are ignored.hue_angle Specifies the hue angle (in degrees) at which tofind maximum chroma.color_returnReturns the CIE L*u*v* coordinates of maximumchroma displayable by the screen for the given hueangle. The white point associated with thereturned color specification is the Screen WhitePoint. The value returned in the pixel member isundefined.│__ The XcmsCIELuvQueryMaxLC function, given a hue angle, findsthe point of maximum chroma displayable by the screen. Itreturns this point in CIE L*u*v* coordinates.To obtain the CIE L*u*v* coordinates of minimum CIE metriclightness (L*) for a given Psychometric Hue Angle andPsychometric Chroma, use XcmsCIELuvQueryMinL.__│ Status XcmsCIELuvQueryMinL(ccc, hue_angle, chroma, color_return)XcmsCCC ccc;XcmsFloat hue_angle;XcmsFloat chroma;XcmsColor *color_return;ccc Specifies the CCC. The CCC’s Client White Pointand white point adjustment procedures are ignored.hue_angle Specifies the hue angle (in degrees) at which tofind minimum lightness.chroma Specifies the chroma at which to find minimumlightness.color_returnReturns the CIE L*u*v* coordinates of minimumlightness displayable by the screen for the givenhue angle and chroma. The white point associatedwith the returned color specification is theScreen White Point. The value returned in thepixel member is undefined.│__ The XcmsCIELuvQueryMinL function, given a hue angle andchroma, finds the point of minimum lightness (L*)displayable by the screen. It returns this point in CIEL*u*v* coordinates. An XcmsFailure return value usuallyindicates that the given chroma is beyond maximum for thegiven hue angle.6.11.4. TekHVC QueriesTo obtain the maximum Chroma for a given Hue and Value, useXcmsTekHVCQueryMaxC.__│ Status XcmsTekHVCQueryMaxC(ccc, hue, value, color_return)XcmsCCC ccc;XcmsFloat hue;XcmsFloat value;XcmsColor *color_return;ccc Specifies the CCC. The CCC’s Client White Pointand white point adjustment procedures are ignored.hue Specifies the Hue in which to find the maximumChroma.value Specifies the Value in which to find the maximumChroma.color_returnReturns the maximum Chroma along with the actualHue and Value at which the maximum Chroma wasfound. The white point associated with thereturned color specification is the Screen WhitePoint. The value returned in the pixel member isundefined.│__ The XcmsTekHVCQueryMaxC function, given a Hue and Value,determines the maximum Chroma in TekHVC color spacedisplayable by the screen. It returns the maximum Chromaalong with the actual Hue and Value at which the maximumChroma was found.To obtain the maximum Value for a given Hue and Chroma, useXcmsTekHVCQueryMaxV.__│ Status XcmsTekHVCQueryMaxV(ccc, hue, chroma, color_return)XcmsCCC ccc;XcmsFloat hue;XcmsFloat chroma;XcmsColor *color_return;ccc Specifies the CCC. The CCC’s Client White Pointand white point adjustment procedures are ignored.hue Specifies the Hue in which to find the maximumValue.chroma Specifies the chroma at which to find maximumValue.color_returnReturns the maximum Value along with the Hue andChroma at which the maximum Value was found. Thewhite point associated with the returned colorspecification is the Screen White Point. Thevalue returned in the pixel member is undefined.│__ The XcmsTekHVCQueryMaxV function, given a Hue and Chroma,determines the maximum Value in TekHVC color spacedisplayable by the screen. It returns the maximum Value andthe actual Hue and Chroma at which the maximum Value wasfound.To obtain the maximum Chroma and Value at which it isreached for a specified Hue, use XcmsTekHVCQueryMaxVC.__│ Status XcmsTekHVCQueryMaxVC(ccc, hue, color_return)XcmsCCC ccc;XcmsFloat hue;XcmsColor *color_return;ccc Specifies the CCC. The CCC’s Client White Pointand white point adjustment procedures are ignored.hue Specifies the Hue in which to find the maximumChroma.color_returnReturns the color specification in XcmsTekHVC forthe maximum Chroma, the Value at which thatmaximum Chroma is reached, and the actual Hue atwhich the maximum Chroma was found. The whitepoint associated with the returned colorspecification is the Screen White Point. Thevalue returned in the pixel member is undefined.│__ The XcmsTekHVCQueryMaxVC function, given a Hue, determinesthe maximum Chroma in TekHVC color space displayable by thescreen and the Value at which that maximum Chroma isreached. It returns the maximum Chroma, the Value at whichthat maximum Chroma is reached, and the actual Hue for whichthe maximum Chroma was found.To obtain a specified number of TekHVC specifications suchthat they contain maximum Values for a specified Hue and theChroma at which the maximum Values are reached, useXcmsTekHVCQueryMaxVSamples.__│ Status XcmsTekHVCQueryMaxVSamples(ccc, hue, colors_return, nsamples)XcmsCCC ccc;XcmsFloat hue;XcmsColor colors_return[];unsigned int nsamples;ccc Specifies the CCC. The CCC’s Client White Pointand white point adjustment procedures are ignored.hue Specifies the Hue for maximum Chroma/Valuesamples.nsamples Specifies the number of samples.colors_returnReturns nsamples of color specifications inXcmsTekHVC such that the Chroma is the maximumattainable for the Value and Hue. The white pointassociated with the returned color specificationis the Screen White Point. The value returned inthe pixel member is undefined.│__ The XcmsTekHVCQueryMaxVSamples returns nsamples of maximumValue, the Chroma at which that maximum Value is reached,and the actual Hue for which the maximum Chroma was found.These sample points may then be used to plot the maximumValue/Chroma boundary of the screen’s color gamut for thespecified Hue in TekHVC color space.To obtain the minimum Value for a given Hue and Chroma, useXcmsTekHVCQueryMinV.__│ Status XcmsTekHVCQueryMinV(ccc, hue, chroma, color_return)XcmsCCC ccc;XcmsFloat hue;XcmsFloat chroma;XcmsColor *color_return;ccc Specifies the CCC. The CCC’s Client White Pointand white point adjustment procedures are ignored.hue Specifies the Hue in which to find the minimumValue.value Specifies the Value in which to find the minimumValue.color_returnReturns the minimum Value and the actual Hue andChroma at which the minimum Value was found. Thewhite point associated with the returned colorspecification is the Screen White Point. Thevalue returned in the pixel member is undefined.│__ The XcmsTekHVCQueryMinV function, given a Hue and Chroma,determines the minimum Value in TekHVC color spacedisplayable by the screen. It returns the minimum Value andthe actual Hue and Chroma at which the minimum Value wasfound.6.12. Color Management ExtensionsThe Xlib color management facilities can be extended in twoways:• Device-Independent Color SpacesDevice-independent color spaces that are derivable toCIE XYZ space can be added using the XcmsAddColorSpacefunction.• Color Characterization Function SetA Color Characterization Function Set consists ofdevice-dependent color spaces and their functions thatconvert between these color spaces and the CIE XYZcolor space, bundled together for a specific class ofoutput devices. A function set can be added using theXcmsAddFunctionSet function.6.12.1. Color SpacesThe CIE XYZ color space serves as the hub for allconversions between device-independent and device-dependentcolor spaces. Therefore, the knowledge to convert anXcmsColor structure to and from CIE XYZ format is associatedwith each color space. For example, conversion from CIEL*u*v* to RGB requires the knowledge to convert from CIEL*u*v* to CIE XYZ and from CIE XYZ to RGB. This knowledgeis stored as an array of functions that, when applied inseries, will convert the XcmsColor structure to or from CIEXYZ format. This color specification conversion mechanismfacilitates the addition of color spaces.Of course, when converting between only device-independentcolor spaces or only device-dependent color spaces,shortcuts are taken whenever possible. For example,conversion from TekHVC to CIE L*u*v* is performed byintermediate conversion to CIE u*v*Y and then to CIE L*u*v*,thus bypassing conversion between CIE u*v*Y and CIE XYZ.6.12.2. Adding Device-Independent Color SpacesTo add a device-independent color space, useXcmsAddColorSpace.__│ Status XcmsAddColorSpace(color_space)XcmsColorSpace *color_space;color_spaceSpecifies the device-independent color space toadd.│__ The XcmsAddColorSpace function makes a device-independentcolor space (actually an XcmsColorSpace structure)accessible by the color management system. Because formatvalues for unregistered color spaces are assigned at runtime, they should be treated as private to the client. Ifreferences to an unregistered color space must be madeoutside the client (for example, storing colorspecifications in a file using the unregistered colorspace), then reference should be made by color space prefix(see XcmsFormatOfPrefix and XcmsPrefixOfFormat).If the XcmsColorSpace structure is already accessible in thecolor management system, XcmsAddColorSpace returnsXcmsSuccess.Note that added XcmsColorSpaces must be retained forreference by Xlib.6.12.3. Querying Color Space Format and PrefixTo obtain the format associated with the color spaceassociated with a specified color string prefix, useXcmsFormatOfPrefix.__│ XcmsColorFormat XcmsFormatOfPrefix(prefix)char *prefix;prefix Specifies the string that contains the color spaceprefix.│__ The XcmsFormatOfPrefix function returns the format for thespecified color space prefix (for example, the string‘‘CIEXYZ’’). The prefix is case-insensitive. If the colorspace is not accessible in the color management system,XcmsFormatOfPrefix returns XcmsUndefinedFormat.To obtain the color string prefix associated with the colorspace specified by a color format, use XcmsPrefixOfFormat.__│ char *XcmsPrefixOfFormat(format)XcmsColorFormat format;format Specifies the color specification format.│__ The XcmsPrefixOfFormat function returns the string prefixassociated with the color specification encoding specifiedby the format argument. Otherwise, if no encoding is found,it returns NULL. The returned string must be treated asread-only.6.12.4. Creating Additional Color SpacesColor space specific information necessary for color spaceconversion and color string parsing is stored in anXcmsColorSpace structure. Therefore, a new structurecontaining this information is required for each additionalcolor space. In the case of device-independent colorspaces, a handle to this new structure (that is, by means ofa global variable) is usually made accessible to the clientprogram for use with the XcmsAddColorSpace function.If a new XcmsColorSpace structure specifies a color spacenot registered with the X Consortium, they should be treatedas private to the client because format values forunregistered color spaces are assigned at run time. Ifreferences to an unregistered color space must be madeoutside the client (for example, storing colorspecifications in a file using the unregistered colorspace), then reference should be made by color space prefix(see XcmsFormatOfPrefix and XcmsPrefixOfFormat).__│ typedef (*XcmsConversionProc)();typedef XcmsConversionProc *XcmsFuncListPtr;/* A NULL terminated list of function pointers*/typedef struct _XcmsColorSpace {char *prefix;XcmsColorFormat format;XcmsParseStringProc parseString;XcmsFuncListPtr to_CIEXYZ;XcmsFuncListPtr from_CIEXYZ;int inverse_flag;} XcmsColorSpace;│__ The prefix member specifies the prefix that indicates acolor string is in this color space’s string format. Forexample, the strings ‘‘ciexyz’’ or ‘‘CIEXYZ’’ for CIE XYZ,and ‘‘rgb’’ or ‘‘RGB’’ for RGB. The prefix is caseinsensitive. The format member specifies the colorspecification format. Formats for unregistered color spacesare assigned at run time. The parseString member contains apointer to the function that can parse a color string intoan XcmsColor structure. This function returns an integer(int): nonzero if it succeeded and zero otherwise. Theto_CIEXYZ and from_CIEXYZ members contain pointers, each toa NULL terminated list of function pointers. When the listof functions is executed in series, it will convert thecolor specified in an XcmsColor structure from/to thecurrent color space format to/from the CIE XYZ format. Eachfunction returns an integer (int): nonzero if it succeededand zero otherwise. The white point to be associated withthe colors is specified explicitly, even though white pointscan be found in the CCC. The inverse_flag member, ifnonzero, specifies that for each function listed into_CIEXYZ, its inverse function can be found in from_CIEXYZsuch that:Given: n = number of functions in each listfor each i, such that 0 <= i < nfrom_CIEXYZ[n - i - 1] is the inverse of to_CIEXYZ[i].This allows Xlib to use the shortest conversion path, thusbypassing CIE XYZ if possible (for example, TekHVC to CIEL*u*v*).6.12.5. Parse String CallbackThe callback in the XcmsColorSpace structure for parsing acolor string for the particular color space must adhere tothe following software interface specification:__│ typedef int (*XcmsParseStringProc)(color_string, color_return)char *color_string;XcmsColor *color_return;color_stringSpecifies the color string to parse.color_returnReturns the color specification in the colorspace’s format.│__ 6.12.6. Color Specification Conversion CallbackCallback functions in the XcmsColorSpace structure forconverting a color specification between device-independentspaces must adhere to the following software interfacespecification:__│ Status ConversionProc(ccc, white_point, colors_in_out, ncolors)XcmsCCC ccc;XcmsColor *white_point;XcmsColor *colors_in_out;unsigned int ncolors;ccc Specifies the CCC.white_pointSpecifies the white point associated with colorspecifications. The pixel member should beignored, and the entire structure remain unchangedupon return.colors_in_outSpecifies an array of color specifications. Pixelmembers should be ignored and must remainunchanged upon return.ncolors Specifies the number of XcmsColor structures inthe color-specification array.│__ Callback functions in the XcmsColorSpace structure forconverting a color specification to or from adevice-dependent space must adhere to the following softwareinterface specification:__│ Status ConversionProc(ccc, colors_in_out, ncolors, compression_flags_return)XcmsCCC ccc;XcmsColor *colors_in_out;unsigned int ncolors;Bool compression_flags_return[];ccc Specifies the CCC.colors_in_outSpecifies an array of color specifications. Pixelmembers should be ignored and must remainunchanged upon return.ncolors Specifies the number of XcmsColor structures inthe color-specification array.compression_flags_returnReturns an array of Boolean values for indicatingcompression status. If a non-NULL pointer issupplied and a color at a given index iscompressed, then True should be stored at thecorresponding index in this array; otherwise, thearray should not be modified.│__ Conversion functions are available globally for use by othercolor spaces. The conversion functions provided by Xlibare:6.12.7. Function SetsFunctions to convert between device-dependent color spacesand CIE XYZ may differ for different classes of outputdevices (for example, color versus gray monitors).Therefore, the notion of a Color Characterization FunctionSet has been developed. A function set consists ofdevice-dependent color spaces and the functions that convertcolor specifications between these device-dependent colorspaces and the CIE XYZ color space appropriate for aparticular class of output devices. The function set alsocontains a function that reads color characterization dataoff root window properties. It is this characterizationdata that will differ between devices within a class ofoutput devices. For details about how colorcharacterization data is stored in root window properties,see the section on Device Color Characterization in theInter-Client Communication Conventions Manual. TheLINEAR_RGB function set is provided by Xlib and will supportmost color monitors. Function sets may require data thatdiffers from those needed for the LINEAR_RGB function set.In that case, its corresponding data may be stored ondifferent root window properties.6.12.8. Adding Function SetsTo add a function set, use XcmsAddFunctionSet.__│ Status XcmsAddFunctionSet(function_set)XcmsFunctionSet *function_set;function_setSpecifies the function set to add.│__ The XcmsAddFunctionSet function adds a function set to thecolor management system. If the function set usesdevice-dependent XcmsColorSpace structures not accessible inthe color management system, XcmsAddFunctionSet adds them.If an added XcmsColorSpace structure is for adevice-dependent color space not registered with the XConsortium, they should be treated as private to the clientbecause format values for unregistered color spaces areassigned at run time. If references to an unregisteredcolor space must be made outside the client (for example,storing color specifications in a file using theunregistered color space), then reference should be made bycolor space prefix (see XcmsFormatOfPrefix andXcmsPrefixOfFormat).Additional function sets should be added before any calls toother Xlib routines are made. If not, the XcmsPerScrnInfomember of a previously created XcmsCCC does not have theopportunity to initialize with the added function set.6.12.9. Creating Additional Function SetsThe creation of additional function sets should be requiredonly when an output device does not conform to existingfunction sets or when additional device-dependent colorspaces are necessary. A function set consists primarily ofa collection of device-dependent XcmsColorSpace structuresand a means to read and store a screen’s colorcharacterization data. This data is stored in anXcmsFunctionSet structure. A handle to this structure (thatis, by means of global variable) is usually made accessibleto the client program for use with XcmsAddFunctionSet.If a function set uses new device-dependent XcmsColorSpacestructures, they will be transparently processed into thecolor management system. Function sets can share anXcmsColorSpace structure for a device-dependent color space.In addition, multiple XcmsColorSpace structures are allowedfor a device-dependent color space; however, a function setcan reference only one of them. These XcmsColorSpacestructures will differ in the functions to convert to andfrom CIE XYZ, thus tailored for the specific function set.__│ typedef struct _XcmsFunctionSet {XcmsColorSpace **DDColorSpaces;XcmsScreenInitProc screenInitProc;XcmsScreenFreeProc screenFreeProc;} XcmsFunctionSet;│__ The DDColorSpaces member is a pointer to a NULL terminatedlist of pointers to XcmsColorSpace structures for thedevice-dependent color spaces that are supported by thefunction set. The screenInitProc member is set to thecallback procedure (see the following interfacespecification) that initializes the XcmsPerScrnInfostructure for a particular screen.The screen initialization callback must adhere to thefollowing software interface specification:__│ typedef Status (*XcmsScreenInitProc)(display, screen_number, screen_info)Display *display;int screen_number;XcmsPerScrnInfo *screen_info;display Specifies the connection to the X server.screen_numberSpecifies the appropriate screen number on thehost server.screen_infoSpecifies the XcmsPerScrnInfo structure, whichcontains the per screen information.│__ The screen initialization callback in the XcmsFunctionSetstructure fetches the color characterization data (deviceprofile) for the specified screen, typically off propertieson the screen’s root window. It then initializes thespecified XcmsPerScrnInfo structure. If successful, theprocedure fills in the XcmsPerScrnInfo structure as follows:• It sets the screenData member to the address of thecreated device profile data structure (contents knownonly by the function set).• It next sets the screenWhitePoint member.• It next sets the functionSet member to the address ofthe XcmsFunctionSet structure.• It then sets the state member to XcmsInitSuccess andfinally returns XcmsSuccess.If unsuccessful, the procedure sets the state member toXcmsInitFailure and returns XcmsFailure.The XcmsPerScrnInfo structure contains:__│ typedef struct _XcmsPerScrnInfo {XcmsColor screenWhitePoint;XPointer functionSet;XPointer screenData;unsigned char state;char pad[3];} XcmsPerScrnInfo;│__ The screenWhitePoint member specifies the white pointinherent to the screen. The functionSet member specifiesthe appropriate function set. The screenData memberspecifies the device profile. The state member is set toone of the following:• XcmsInitNone indicates initialization has not beenpreviously attempted.• XcmsInitFailure indicates initialization has beenpreviously attempted but failed.• XcmsInitSuccess indicates initialization has beenpreviously attempted and succeeded.The screen free callback must adhere to the followingsoftware interface specification:__│ typedef void (*XcmsScreenFreeProc)(screenData)XPointer screenData;screenDataSpecifies the data to be freed.│__ This function is called to free the screenData stored in anXcmsPerScrnInfo structure. 6
7.1. Manipulating Graphics Context/StateMost attributes of graphics operations are stored in GCs.These include line width, line style, plane mask,foreground, background, tile, stipple, clipping region, endstyle, join style, and so on. Graphics operations (forexample, drawing lines) use these values to determine theactual drawing operation. Extensions to X may addadditional components to GCs. The contents of a GC areprivate to Xlib.Xlib implements a write-back cache for all elements of a GCthat are not resource IDs to allow Xlib to implement thetransparent coalescing of changes to GCs. For example, acall to XSetForeground of a GC followed by a call toXSetLineAttributes results in only a single-change GCprotocol request to the server. GCs are neither expectednor encouraged to be shared between client applications, sothis write-back caching should present no problems.Applications cannot share GCs without externalsynchronization. Therefore, sharing GCs betweenapplications is highly discouraged.To set an attribute of a GC, set the appropriate member ofthe XGCValues structure and OR in the corresponding valuebitmask in your subsequent calls to XCreateGC. The symbolsfor the value mask bits and the XGCValues structure are:__│ /* GC attribute value mask bits *//* Values */typedef struct {int function; /* logical operation */unsigned long plane_mask;/* plane mask */unsigned long foreground;/* foreground pixel */unsigned long background;/* background pixel */int line_width; /* line width (in pixels) */int line_style; /* LineSolid, LineOnOffDash, LineDoubleDash */int cap_style; /* CapNotLast, CapButt, CapRound, CapProjecting */int join_style; /* JoinMiter, JoinRound, JoinBevel */int fill_style; /* FillSolid, FillTiled, FillStippled FillOpaqueStippled*/int fill_rule; /* EvenOddRule, WindingRule */int arc_mode; /* ArcChord, ArcPieSlice */Pixmap tile; /* tile pixmap for tiling operations */Pixmap stipple; /* stipple 1 plane pixmap for stippling */int ts_x_origin; /* offset for tile or stipple operations */int ts_y_origin;Font font; /* default text font for text operations */int subwindow_mode; /* ClipByChildren, IncludeInferiors */Bool graphics_exposures; /* boolean, should exposures be generated */int clip_x_origin; /* origin for clipping */int clip_y_origin;Pixmap clip_mask; /* bitmap clipping; other calls for rects */int dash_offset; /* patterned/dashed line information */char dashes;} XGCValues;│__ The default GC values are:Note that foreground and background are not set to anyvalues likely to be useful in a window.The function attributes of a GC are used when you update asection of a drawable (the destination) with bits fromsomewhere else (the source). The function in a GC defineshow the new destination bits are to be computed from thesource bits and the old destination bits. GXcopy istypically the most useful because it will work on a colordisplay, but special applications may use other functions,particularly in concert with particular planes of a colordisplay. The 16 GC functions, defined in <X11/X.h>, are:Many graphics operations depend on either pixel values orplanes in a GC. The planes attribute is of type long, andit specifies which planes of the destination are to bemodified, one bit per plane. A monochrome display has onlyone plane and will be the least significant bit of the word.As planes are added to the display hardware, they willoccupy more significant bits in the plane mask.In graphics operations, given a source and destinationpixel, the result is computed bitwise on corresponding bitsof the pixels. That is, a Boolean operation is performed ineach bit plane. The plane_mask restricts the operation to asubset of planes. A macro constant AllPlanes can be used torefer to all planes of the screen simultaneously. Theresult is computed by the following:((src FUNC dst) AND plane-mask) OR (dst AND (NOT plane-mask))Range checking is not performed on the values forforeground, background, or plane_mask. They are simplytruncated to the appropriate number of bits. The line-widthis measured in pixels and either can be greater than orequal to one (wide line) or can be the special value zero(thin line).Wide lines are drawn centered on the path described by thegraphics request. Unless otherwise specified by thejoin-style or cap-style, the bounding box of a wide linewith endpoints [x1, y1], [x2, y2] and width w is a rectanglewith vertices at the following real coordinates:[x1-(w*sn/2), y1+(w*cs/2)], [x1+(w*sn/2), y1-(w*cs/2)],[x2-(w*sn/2), y2+(w*cs/2)], [x2+(w*sn/2), y2-(w*cs/2)]Here sn is the sine of the angle of the line, and cs is thecosine of the angle of the line. A pixel is part of theline and so is drawn if the center of the pixel is fullyinside the bounding box (which is viewed as havinginfinitely thin edges). If the center of the pixel isexactly on the bounding box, it is part of the line if andonly if the interior is immediately to its right (xincreasing direction). Pixels with centers on a horizontaledge are a special case and are part of the line if and onlyif the interior or the boundary is immediately below (yincreasing direction) and the interior or the boundary isimmediately to the right (x increasing direction).Thin lines (zero line-width) are one-pixel-wide lines drawnusing an unspecified, device-dependent algorithm. There areonly two constraints on this algorithm.1. If a line is drawn unclipped from [x1,y1] to [x2,y2]and if another line is drawn unclipped from[x1+dx,y1+dy] to [x2+dx,y2+dy], a point [x,y] istouched by drawing the first line if and only if thepoint [x+dx,y+dy] is touched by drawing the secondline.2. The effective set of points comprising a line cannot beaffected by clipping. That is, a point is touched in aclipped line if and only if the point lies inside theclipping region and the point would be touched by theline when drawn unclipped.A wide line drawn from [x1,y1] to [x2,y2] always draws thesame pixels as a wide line drawn from [x2,y2] to [x1,y1],not counting cap-style and join-style. It is recommendedthat this property be true for thin lines, but this is notrequired. A line-width of zero may differ from a line-widthof one in which pixels are drawn. This permits the use ofmany manufacturers’ line drawing hardware, which may runmany times faster than the more precisely specified widelines.In general, drawing a thin line will be faster than drawinga wide line of width one. However, because of theirdifferent drawing algorithms, thin lines may not mix wellaesthetically with wide lines. If it is desirable to obtainprecise and uniform results across all displays, a clientshould always use a line-width of one rather than aline-width of zero.The line-style defines which sections of a line are drawn:The cap-style defines how the endpoints of a path are drawn:The join-style defines how corners are drawn for wide lines:For a line with coincident endpoints (x1=x2, y1=y2), whenthe cap-style is applied to both endpoints, the semanticsdepends on the line-width and the cap-style:For a line with coincident endpoints (x1=x2, y1=y2), whenthe join-style is applied at one or both endpoints, theeffect is as if the line was removed from the overall path.However, if the total path consists of or is reduced to asingle point joined with itself, the effect is the same aswhen the cap-style is applied at both endpoints.The tile/stipple represents an infinite two-dimensionalplane, with the tile/stipple replicated in all dimensions.When that plane is superimposed on the drawable for use in agraphics operation, the upper-left corner of some instanceof the tile/stipple is at the coordinates within thedrawable specified by the tile/stipple origin. Thetile/stipple and clip origins are interpreted relative tothe origin of whatever destination drawable is specified ina graphics request. The tile pixmap must have the same rootand depth as the GC, or a BadMatch error results. Thestipple pixmap must have depth one and must have the sameroot as the GC, or a BadMatch error results. For stippleoperations where the fill-style is FillStippled but notFillOpaqueStippled, the stipple pattern is tiled in a singleplane and acts as an additional clip mask to be ANDed withthe clip-mask. Although some sizes may be faster to usethan others, any size pixmap can be used for tiling orstippling.The fill-style defines the contents of the source for line,text, and fill requests. For all text and fill requests(for example, XDrawText, XDrawText16, XFillRectangle,XFillPolygon, and XFillArc); for line requests withline-style LineSolid (for example, XDrawLine, XDrawSegments,XDrawRectangle, XDrawArc); and for the even dashes for linerequests with line-style LineOnOffDash or LineDoubleDash,the following apply:When drawing lines with line-style LineDoubleDash, the odddashes are controlled by the fill-style in the followingmanner:Storing a pixmap in a GC might or might not result in a copybeing made. If the pixmap is later used as the destinationfor a graphics request, the change might or might not bereflected in the GC. If the pixmap is used simultaneouslyin a graphics request both as a destination and as a tile orstipple, the results are undefined.For optimum performance, you should draw as much as possiblewith the same GC (without changing its components). Thecosts of changing GC components relative to using differentGCs depend on the display hardware and the serverimplementation. It is quite likely that some amount of GCinformation will be cached in display hardware and that suchhardware can only cache a small number of GCs.The dashes value is actually a simplified form of the moregeneral patterns that can be set with XSetDashes.Specifying a value of N is equivalent to specifying thetwo-element list [N, N] in XSetDashes. The value must benonzero, or a BadValue error results.The clip-mask restricts writes to the destination drawable.If the clip-mask is set to a pixmap, it must have depth oneand have the same root as the GC, or a BadMatch errorresults. If clip-mask is set to None, the pixels are alwaysdrawn regardless of the clip origin. The clip-mask also canbe set by calling the XSetClipRectangles or XSetRegionfunctions. Only pixels where the clip-mask has a bit set to1 are drawn. Pixels are not drawn outside the area coveredby the clip-mask or where the clip-mask has a bit set to 0.The clip-mask affects all graphics requests. The clip-maskdoes not clip sources. The clip-mask origin is interpretedrelative to the origin of whatever destination drawable isspecified in a graphics request.You can set the subwindow-mode to ClipByChildren orIncludeInferiors. For ClipByChildren, both source anddestination windows are additionally clipped by all viewableInputOutput children. For IncludeInferiors, neither sourcenor destination window is clipped by inferiors. This willresult in including subwindow contents in the source anddrawing through subwindow boundaries of the destination.The use of IncludeInferiors on a window of one depth withmapped inferiors of differing depth is not illegal, but thesemantics are undefined by the core protocol.The fill-rule defines what pixels are inside (drawn) forpaths given in XFillPolygon requests and can be set toEvenOddRule or WindingRule. For EvenOddRule, a point isinside if an infinite ray with the point as origin crossesthe path an odd number of times. For WindingRule, a pointis inside if an infinite ray with the point as origincrosses an unequal number of clockwise and counterclockwisedirected path segments. A clockwise directed path segmentis one that crosses the ray from left to right as observedfrom the point. A counterclockwise segment is one thatcrosses the ray from right to left as observed from thepoint. The case where a directed line segment is coincidentwith the ray is uninteresting because you can simply choosea different ray that is not coincident with a segment.For both EvenOddRule and WindingRule, a point is infinitelysmall, and the path is an infinitely thin line. A pixel isinside if the center point of the pixel is inside and thecenter point is not on the boundary. If the center point ison the boundary, the pixel is inside if and only if thepolygon interior is immediately to its right (x increasingdirection). Pixels with centers on a horizontal edge are aspecial case and are inside if and only if the polygoninterior is immediately below (y increasing direction).The arc-mode controls filling in the XFillArcs function andcan be set to ArcPieSlice or ArcChord. For ArcPieSlice, thearcs are pie-slice filled. For ArcChord, the arcs are chordfilled.The graphics-exposure flag controls GraphicsExpose eventgeneration for XCopyArea and XCopyPlane requests (and anysimilar requests defined by extensions).To create a new GC that is usable on a given screen with adepth of drawable, use XCreateGC.__│ GC XCreateGC(display, d, valuemask, values)Display *display;Drawable d;unsigned long valuemask;XGCValues *values;display Specifies the connection to the X server.d Specifies the drawable.valuemask Specifies which components in the GC are to be setusing the information in the specified valuesstructure. This argument is the bitwise inclusiveOR of zero or more of the valid GC component maskbits.values Specifies any values as specified by thevaluemask.│__ The XCreateGC function creates a graphics context andreturns a GC. The GC can be used with any destinationdrawable having the same root and depth as the specifieddrawable. Use with other drawables results in a BadMatcherror.XCreateGC can generate BadAlloc, BadDrawable, BadFont,BadMatch, BadPixmap, and BadValue errors.To copy components from a source GC to a destination GC, useXCopyGC.__│ XCopyGC(display, src, valuemask, dest)Display *display;GC src, dest;unsigned long valuemask;display Specifies the connection to the X server.src Specifies the components of the source GC.valuemask Specifies which components in the GC are to becopied to the destination GC. This argument isthe bitwise inclusive OR of zero or more of thevalid GC component mask bits.dest Specifies the destination GC.│__ The XCopyGC function copies the specified components fromthe source GC to the destination GC. The source anddestination GCs must have the same root and depth, or aBadMatch error results. The valuemask specifies whichcomponent to copy, as for XCreateGC.XCopyGC can generate BadAlloc, BadGC, and BadMatch errors.To change the components in a given GC, use XChangeGC.__│ XChangeGC(display, gc, valuemask, values)Display *display;GC gc;unsigned long valuemask;XGCValues *values;display Specifies the connection to the X server.gc Specifies the GC.valuemask Specifies which components in the GC are to bechanged using information in the specified valuesstructure. This argument is the bitwise inclusiveOR of zero or more of the valid GC component maskbits.values Specifies any values as specified by thevaluemask.│__ The XChangeGC function changes the components specified byvaluemask for the specified GC. The values argumentcontains the values to be set. The values and restrictionsare the same as for XCreateGC. Changing the clip-maskoverrides any previous XSetClipRectangles request on thecontext. Changing the dash-offset or dash-list overridesany previous XSetDashes request on the context. The orderin which components are verified and altered is serverdependent. If an error is generated, a subset of thecomponents may have been altered.XChangeGC can generate BadAlloc, BadFont, BadGC, BadMatch,BadPixmap, and BadValue errors.To obtain components of a given GC, use XGetGCValues.__│ Status XGetGCValues(display, gc, valuemask, values_return)Display *display;GC gc;unsigned long valuemask;XGCValues *values_return;display Specifies the connection to the X server.gc Specifies the GC.valuemask Specifies which components in the GC are to bereturned in the values_return argument. Thisargument is the bitwise inclusive OR of zero ormore of the valid GC component mask bits.values_returnReturns the GC values in the specified XGCValuesstructure.│__ The XGetGCValues function returns the components specifiedby valuemask for the specified GC. If the valuemaskcontains a valid set of GC mask bits (GCFunction,GCPlaneMask, GCForeground, GCBackground, GCLineWidth,GCLineStyle, GCCapStyle, GCJoinStyle, GCFillStyle,GCFillRule, GCTile, GCStipple, GCTileStipXOrigin,GCTileStipYOrigin, GCFont, GCSubwindowMode,GCGraphicsExposures, GCClipXOrigin, GCCLipYOrigin,GCDashOffset, or GCArcMode) and no error occurs,XGetGCValues sets the requested components in values_returnand returns a nonzero status. Otherwise, it returns a zerostatus. Note that the clip-mask and dash-list (representedby the GCClipMask and GCDashList bits, respectively, in thevaluemask) cannot be requested. Also note that an invalidresource ID (with one or more of the three most significantbits set to 1) will be returned for GCFont, GCTile, andGCStipple if the component has never been explicitly set bythe client.To free a given GC, use XFreeGC.__│ XFreeGC(display, gc)Display *display;GC gc;display Specifies the connection to the X server.gc Specifies the GC.│__ The XFreeGC function destroys the specified GC as well asall the associated storage.XFreeGC can generate a BadGC error.To obtain the GContext resource ID for a given GC, useXGContextFromGC.__│ GContext XGContextFromGC(gc)GC gc;gc Specifies the GC for which you want the resourceID.│__ Xlib usually defers sending changes to the components of aGC to the server until a graphics function is actuallycalled with that GC. This permits batching of componentchanges into a single server request. In somecircumstances, however, it may be necessary for the clientto explicitly force sending the changes to the server. Anexample might be when a protocol extension uses the GCindirectly, in such a way that the extension interfacecannot know what GC will be used. To force sending GCcomponent changes, use XFlushGC.__│ void XFlushGC(display, gc)Display *display;GC gc;display Specifies the connection to the X server.gc Specifies the GC.│__ 7.2. Using Graphics Context Convenience RoutinesThis section discusses how to set the:• Foreground, background, plane mask, or functioncomponents• Line attributes and dashes components• Fill style and fill rule components• Fill tile and stipple components• Font component• Clip region component• Arc mode, subwindow mode, and graphics exposurecomponents7.2.1. Setting the Foreground, Background, Function, orPlane MaskTo set the foreground, background, plane mask, and functioncomponents for a given GC, use XSetState.__│ XSetState(display, gc, foreground, background, function, plane_mask)Display *display;GC gc;unsigned long foreground, background;int function;unsigned long plane_mask;display Specifies the connection to the X server.gc Specifies the GC.foregroundSpecifies the foreground you want to set for thespecified GC.backgroundSpecifies the background you want to set for thespecified GC.function Specifies the function you want to set for thespecified GC.plane_maskSpecifies the plane mask.│__ XSetState can generate BadAlloc, BadGC, and BadValue errors.To set the foreground of a given GC, use XSetForeground.__│ XSetForeground(display, gc, foreground)Display *display;GC gc;unsigned long foreground;display Specifies the connection to the X server.gc Specifies the GC.foregroundSpecifies the foreground you want to set for thespecified GC.│__ XSetForeground can generate BadAlloc and BadGC errors.To set the background of a given GC, use XSetBackground.__│ XSetBackground(display, gc, background)Display *display;GC gc;unsigned long background;display Specifies the connection to the X server.gc Specifies the GC.backgroundSpecifies the background you want to set for thespecified GC.│__ XSetBackground can generate BadAlloc and BadGC errors.To set the display function in a given GC, use XSetFunction.__│ XSetFunction(display, gc, function)Display *display;GC gc;int function;display Specifies the connection to the X server.gc Specifies the GC.function Specifies the function you want to set for thespecified GC.│__ XSetFunction can generate BadAlloc, BadGC, and BadValueerrors.To set the plane mask of a given GC, use XSetPlaneMask.__│ XSetPlaneMask(display, gc, plane_mask)Display *display;GC gc;unsigned long plane_mask;display Specifies the connection to the X server.gc Specifies the GC.plane_maskSpecifies the plane mask.│__ XSetPlaneMask can generate BadAlloc and BadGC errors.7.2.2. Setting the Line Attributes and DashesTo set the line drawing components of a given GC, useXSetLineAttributes.__│ XSetLineAttributes(display, gc, line_width, line_style, cap_style, join_style)Display *display;GC gc;unsigned int line_width;int line_style;int cap_style;int join_style;display Specifies the connection to the X server.gc Specifies the GC.line_widthSpecifies the line-width you want to set for thespecified GC.line_styleSpecifies the line-style you want to set for thespecified GC. You can pass LineSolid,LineOnOffDash, or LineDoubleDash.cap_style Specifies the line-style and cap-style you want toset for the specified GC. You can passCapNotLast, CapButt, CapRound, or CapProjecting.join_styleSpecifies the line join-style you want to set forthe specified GC. You can pass JoinMiter,JoinRound, or JoinBevel.│__ XSetLineAttributes can generate BadAlloc, BadGC, andBadValue errors.To set the dash-offset and dash-list for dashed line stylesof a given GC, use XSetDashes.__│ XSetDashes(display, gc, dash_offset, dash_list, n)Display *display;GC gc;int dash_offset;char dash_list[];int n;display Specifies the connection to the X server.gc Specifies the GC.dash_offsetSpecifies the phase of the pattern for the dashedline-style you want to set for the specified GC.dash_list Specifies the dash-list for the dashed line-styleyou want to set for the specified GC.n Specifies the number of elements in dash_list.│__ The XSetDashes function sets the dash-offset and dash-listattributes for dashed line styles in the specified GC.There must be at least one element in the specifieddash_list, or a BadValue error results. The initial andalternating elements (second, fourth, and so on) of thedash_list are the even dashes, and the others are the odddashes. Each element specifies a dash length in pixels.All of the elements must be nonzero, or a BadValue errorresults. Specifying an odd-length list is equivalent tospecifying the same list concatenated with itself to producean even-length list.The dash-offset defines the phase of the pattern, specifyinghow many pixels into the dash-list the pattern shouldactually begin in any single graphics request. Dashing iscontinuous through path elements combined with a join-stylebut is reset to the dash-offset between each sequence ofjoined lines.The unit of measure for dashes is the same for the ordinarycoordinate system. Ideally, a dash length is measured alongthe slope of the line, but implementations are only requiredto match this ideal for horizontal and vertical lines.Failing the ideal semantics, it is suggested that the lengthbe measured along the major axis of the line. The majoraxis is defined as the x axis for lines drawn at an angle ofbetween −45 and +45 degrees or between 135 and 225 degreesfrom the x axis. For all other lines, the major axis is they axis.XSetDashes can generate BadAlloc, BadGC, and BadValueerrors.7.2.3. Setting the Fill Style and Fill RuleTo set the fill-style of a given GC, use XSetFillStyle.__│ XSetFillStyle(display, gc, fill_style)Display *display;GC gc;int fill_style;display Specifies the connection to the X server.gc Specifies the GC.fill_styleSpecifies the fill-style you want to set for thespecified GC. You can pass FillSolid, FillTiled,FillStippled, or FillOpaqueStippled.│__ XSetFillStyle can generate BadAlloc, BadGC, and BadValueerrors.To set the fill-rule of a given GC, use XSetFillRule.__│ XSetFillRule(display, gc, fill_rule)Display *display;GC gc;int fill_rule;display Specifies the connection to the X server.gc Specifies the GC.fill_rule Specifies the fill-rule you want to set for thespecified GC. You can pass EvenOddRule orWindingRule.│__ XSetFillRule can generate BadAlloc, BadGC, and BadValueerrors.7.2.4. Setting the Fill Tile and StippleSome displays have hardware support for tiling or stipplingwith patterns of specific sizes. Tiling and stipplingoperations that restrict themselves to those specific sizesrun much faster than such operations with arbitrary sizepatterns. Xlib provides functions that you can use todetermine the best size, tile, or stipple for the display aswell as to set the tile or stipple shape and the tile orstipple origin.To obtain the best size of a tile, stipple, or cursor, useXQueryBestSize.__│ Status XQueryBestSize(display, class, which_screen, width, height, width_return, height_return)Display *display;int class;Drawable which_screen;unsigned int width, height;unsigned int *width_return, *height_return;display Specifies the connection to the X server.class Specifies the class that you are interested in.You can pass TileShape, CursorShape, orStippleShape.which_screenSpecifies any drawable on the screen.widthheight Specify the width and height.width_returnheight_returnReturn the width and height of the object bestsupported by the display hardware.│__ The XQueryBestSize function returns the best or closest sizeto the specified size. For CursorShape, this is the largestsize that can be fully displayed on the screen specified bywhich_screen. For TileShape, this is the size that can betiled fastest. For StippleShape, this is the size that canbe stippled fastest. For CursorShape, the drawableindicates the desired screen. For TileShape andStippleShape, the drawable indicates the screen and possiblythe window class and depth. An InputOnly window cannot beused as the drawable for TileShape or StippleShape, or aBadMatch error results.XQueryBestSize can generate BadDrawable, BadMatch, andBadValue errors.To obtain the best fill tile shape, use XQueryBestTile.__│ Status XQueryBestTile(display, which_screen, width, height, width_return, height_return)Display *display;Drawable which_screen;unsigned int width, height;unsigned int *width_return, *height_return;display Specifies the connection to the X server.which_screenSpecifies any drawable on the screen.widthheight Specify the width and height.width_returnheight_returnReturn the width and height of the object bestsupported by the display hardware.│__ The XQueryBestTile function returns the best or closestsize, that is, the size that can be tiled fastest on thescreen specified by which_screen. The drawable indicatesthe screen and possibly the window class and depth. If anInputOnly window is used as the drawable, a BadMatch errorresults.XQueryBestTile can generate BadDrawable and BadMatch errors.To obtain the best stipple shape, use XQueryBestStipple.__│ Status XQueryBestStipple(display, which_screen, width, height, width_return, height_return)Display *display;Drawable which_screen;unsigned int width, height;unsigned int *width_return, *height_return;display Specifies the connection to the X server.which_screenSpecifies any drawable on the screen.widthheight Specify the width and height.width_returnheight_returnReturn the width and height of the object bestsupported by the display hardware.│__ The XQueryBestStipple function returns the best or closestsize, that is, the size that can be stippled fastest on thescreen specified by which_screen. The drawable indicatesthe screen and possibly the window class and depth. If anInputOnly window is used as the drawable, a BadMatch errorresults.XQueryBestStipple can generate BadDrawable and BadMatcherrors.To set the fill tile of a given GC, use XSetTile.__│ XSetTile(display, gc, tile)Display *display;GC gc;Pixmap tile;display Specifies the connection to the X server.gc Specifies the GC.tile Specifies the fill tile you want to set for thespecified GC.│__ The tile and GC must have the same depth, or a BadMatcherror results.XSetTile can generate BadAlloc, BadGC, BadMatch, andBadPixmap errors.To set the stipple of a given GC, use XSetStipple.__│ XSetStipple(display, gc, stipple)Display *display;GC gc;Pixmap stipple;display Specifies the connection to the X server.gc Specifies the GC.stipple Specifies the stipple you want to set for thespecified GC.│__ The stipple must have a depth of one, or a BadMatch errorresults.XSetStipple can generate BadAlloc, BadGC, BadMatch, andBadPixmap errors.To set the tile or stipple origin of a given GC, useXSetTSOrigin.__│ XSetTSOrigin(display, gc, ts_x_origin, ts_y_origin)Display *display;GC gc;int ts_x_origin, ts_y_origin;display Specifies the connection to the X server.gc Specifies the GC.ts_x_origints_y_originSpecify the x and y coordinates of the tile andstipple origin.│__ When graphics requests call for tiling or stippling, theparent’s origin will be interpreted relative to whateverdestination drawable is specified in the graphics request.XSetTSOrigin can generate BadAlloc and BadGC errors.7.2.5. Setting the Current FontTo set the current font of a given GC, use XSetFont.__│ XSetFont(display, gc, font)Display *display;GC gc;Font font;display Specifies the connection to the X server.gc Specifies the GC.font Specifies the font.│__ XSetFont can generate BadAlloc, BadFont, and BadGC errors.7.2.6. Setting the Clip RegionXlib provides functions that you can use to set theclip-origin and the clip-mask or set the clip-mask to a listof rectangles.To set the clip-origin of a given GC, use XSetClipOrigin.__│ XSetClipOrigin(display, gc, clip_x_origin, clip_y_origin)Display *display;GC gc;int clip_x_origin, clip_y_origin;display Specifies the connection to the X server.gc Specifies the GC.clip_x_originclip_y_originSpecify the x and y coordinates of the clip-maskorigin.│__ The clip-mask origin is interpreted relative to the originof whatever destination drawable is specified in thegraphics request.XSetClipOrigin can generate BadAlloc and BadGC errors.To set the clip-mask of a given GC to the specified pixmap,use XSetClipMask.__│ XSetClipMask(display, gc, pixmap)Display *display;GC gc;Pixmap pixmap;display Specifies the connection to the X server.gc Specifies the GC.pixmap Specifies the pixmap or None.│__ If the clip-mask is set to None, the pixels are always drawn(regardless of the clip-origin).XSetClipMask can generate BadAlloc, BadGC, BadMatch, andBadPixmap errors.To set the clip-mask of a given GC to the specified list ofrectangles, use XSetClipRectangles.__│ XSetClipRectangles(display, gc, clip_x_origin, clip_y_origin, rectangles, n, ordering)Display *display;GC gc;int clip_x_origin, clip_y_origin;XRectangle rectangles[];int n;int ordering;display Specifies the connection to the X server.gc Specifies the GC.clip_x_originclip_y_originSpecify the x and y coordinates of the clip-maskorigin.rectanglesSpecifies an array of rectangles that define theclip-mask.n Specifies the number of rectangles.ordering Specifies the ordering relations on therectangles. You can pass Unsorted, YSorted,YXSorted, or YXBanded.│__ The XSetClipRectangles function changes the clip-mask in thespecified GC to the specified list of rectangles and setsthe clip origin. The output is clipped to remain containedwithin the rectangles. The clip-origin is interpretedrelative to the origin of whatever destination drawable isspecified in a graphics request. The rectangle coordinatesare interpreted relative to the clip-origin. The rectanglesshould be nonintersecting, or the graphics results will beundefined. Note that the list of rectangles can be empty,which effectively disables output. This is the opposite ofpassing None as the clip-mask in XCreateGC, XChangeGC, andXSetClipMask.If known by the client, ordering relations on the rectanglescan be specified with the ordering argument. This mayprovide faster operation by the server. If an incorrectordering is specified, the X server may generate a BadMatcherror, but it is not required to do so. If no error isgenerated, the graphics results are undefined. Unsortedmeans the rectangles are in arbitrary order. YSorted meansthat the rectangles are nondecreasing in their Y origin.YXSorted additionally constrains YSorted order in that allrectangles with an equal Y origin are nondecreasing in theirX origin. YXBanded additionally constrains YXSorted byrequiring that, for every possible Y scanline, allrectangles that include that scanline have an identical Yorigins and Y extents.XSetClipRectangles can generate BadAlloc, BadGC, BadMatch,and BadValue errors.Xlib provides a set of basic functions for performing regionarithmetic. For information about these functions, seesection 16.5.7.2.7. Setting the Arc Mode, Subwindow Mode, and GraphicsExposureTo set the arc mode of a given GC, use XSetArcMode.__│ XSetArcMode(display, gc, arc_mode)Display *display;GC gc;int arc_mode;display Specifies the connection to the X server.gc Specifies the GC.arc_mode Specifies the arc mode. You can pass ArcChord orArcPieSlice.│__ XSetArcMode can generate BadAlloc, BadGC, and BadValueerrors.To set the subwindow mode of a given GC, useXSetSubwindowMode.__│ XSetSubwindowMode(display, gc, subwindow_mode)Display *display;GC gc;int subwindow_mode;display Specifies the connection to the X server.gc Specifies the GC.subwindow_modeSpecifies the subwindow mode. You can passClipByChildren or IncludeInferiors.│__ XSetSubwindowMode can generate BadAlloc, BadGC, and BadValueerrors.To set the graphics-exposures flag of a given GC, useXSetGraphicsExposures.__│ XSetGraphicsExposures(display, gc, graphics_exposures)Display *display;GC gc;Bool graphics_exposures;display Specifies the connection to the X server.gc Specifies the GC.graphics_exposuresSpecifies a Boolean value that indicates whetheryou want GraphicsExpose and NoExpose events to bereported when calling XCopyArea and XCopyPlanewith this GC.│__ XSetGraphicsExposures can generate BadAlloc, BadGC, andBadValue errors. 7
8.1. Clearing AreasXlib provides functions that you can use to clear an area orthe entire window. Because pixmaps do not have definedbackgrounds, they cannot be filled by using the functionsdescribed in this section. Instead, to accomplish ananalogous operation on a pixmap, you should useXFillRectangle, which sets the pixmap to a known value.To clear a rectangular area of a given window, useXClearArea.__│ XClearArea(display, w, x, y, width, height, exposures)Display *display;Window w;int x, y;unsigned int width, height;Bool exposures;display Specifies the connection to the X server.w Specifies the window.xy Specify the x and y coordinates, which arerelative to the origin of the window and specifythe upper-left corner of the rectangle.widthheight Specify the width and height, which are thedimensions of the rectangle.exposures Specifies a Boolean value that indicates if Exposeevents are to be generated.│__ The XClearArea function paints a rectangular area in thespecified window according to the specified dimensions withthe window’s background pixel or pixmap. The subwindow-modeeffectively is ClipByChildren. If width is zero, it isreplaced with the current width of the window minus x. Ifheight is zero, it is replaced with the current height ofthe window minus y. If the window has a defined backgroundtile, the rectangle clipped by any children is filled withthis tile. If the window has background None, the contentsof the window are not changed. In either case, if exposuresis True, one or more Expose events are generated for regionsof the rectangle that are either visible or are beingretained in a backing store. If you specify a window whoseclass is InputOnly, a BadMatch error results.XClearArea can generate BadMatch, BadValue, and BadWindowerrors.To clear the entire area in a given window, useXClearWindow.__│ XClearWindow(display, w)Display *display;Window w;display Specifies the connection to the X server.w Specifies the window.│__ The XClearWindow function clears the entire area in thespecified window and is equivalent to XClearArea (display,w, 0, 0, 0, 0, False). If the window has a definedbackground tile, the rectangle is tiled with a plane-mask ofall ones and GXcopy function. If the window has backgroundNone, the contents of the window are not changed. If youspecify a window whose class is InputOnly, a BadMatch errorresults.XClearWindow can generate BadMatch and BadWindow errors.8.2. Copying AreasXlib provides functions that you can use to copy an area ora bit plane.To copy an area between drawables of the same root anddepth, use XCopyArea.__│ XCopyArea(display, src, dest, gc, src_x, src_y, width, height, dest_x, dest_y)Display *display;Drawable src, dest;GC gc;int src_x, src_y;unsigned int width, height;int dest_x, dest_y;display Specifies the connection to the X server.srcdest Specify the source and destination rectangles tobe combined.gc Specifies the GC.src_xsrc_y Specify the x and y coordinates, which arerelative to the origin of the source rectangle andspecify its upper-left corner.widthheight Specify the width and height, which are thedimensions of both the source and destinationrectangles.dest_xdest_y Specify the x and y coordinates, which arerelative to the origin of the destinationrectangle and specify its upper-left corner.│__ The XCopyArea function combines the specified rectangle ofsrc with the specified rectangle of dest. The drawablesmust have the same root and depth, or a BadMatch errorresults.If regions of the source rectangle are obscured and have notbeen retained in backing store or if regions outside theboundaries of the source drawable are specified, thoseregions are not copied. Instead, the following occurs onall corresponding destination regions that are eithervisible or are retained in backing store. If thedestination is a window with a background other than None,corresponding regions of the destination are tiled with thatbackground (with plane-mask of all ones and GXcopyfunction). Regardless of tiling or whether the destinationis a window or a pixmap, if graphics-exposures is True, thenGraphicsExpose events for all corresponding destinationregions are generated. If graphics-exposures is True but noGraphicsExpose events are generated, a NoExpose event isgenerated. Note that by default graphics-exposures is Truein new GCs.This function uses these GC components: function,plane-mask, subwindow-mode, graphics-exposures,clip-x-origin, clip-y-origin, and clip-mask.XCopyArea can generate BadDrawable, BadGC, and BadMatcherrors.To copy a single bit plane of a given drawable, useXCopyPlane.__│ XCopyPlane(display, src, dest, gc, src_x, src_y, width, height, dest_x, dest_y, plane)Display *display;Drawable src, dest;GC gc;int src_x, src_y;unsigned int width, height;int dest_x, dest_y;unsigned long plane;display Specifies the connection to the X server.srcdest Specify the source and destination rectangles tobe combined.gc Specifies the GC.src_xsrc_y Specify the x and y coordinates, which arerelative to the origin of the source rectangle andspecify its upper-left corner.widthheight Specify the width and height, which are thedimensions of both the source and destinationrectangles.dest_xdest_y Specify the x and y coordinates, which arerelative to the origin of the destinationrectangle and specify its upper-left corner.plane Specifies the bit plane. You must set exactly onebit to 1.│__ The XCopyPlane function uses a single bit plane of thespecified source rectangle combined with the specified GC tomodify the specified rectangle of dest. The drawables musthave the same root but need not have the same depth. If thedrawables do not have the same root, a BadMatch errorresults. If plane does not have exactly one bit set to 1and the value of plane is not less than 2n, where n is thedepth of src, a BadValue error results.Effectively, XCopyPlane forms a pixmap of the same depth asthe rectangle of dest and with a size specified by thesource region. It uses the foreground/background pixels inthe GC (foreground everywhere the bit plane in src containsa bit set to 1, background everywhere the bit plane in srccontains a bit set to 0) and the equivalent of a CopyAreaprotocol request is performed with all the same exposuresemantics. This can also be thought of as using thespecified region of the source bit plane as a stipple with afill-style of FillOpaqueStippled for filling a rectangulararea of the destination.This function uses these GC components: function,plane-mask, foreground, background, subwindow-mode,graphics-exposures, clip-x-origin, clip-y-origin, andclip-mask.XCopyPlane can generate BadDrawable, BadGC, BadMatch, andBadValue errors.8.3. Drawing Points, Lines, Rectangles, and ArcsXlib provides functions that you can use to draw:• A single point or multiple points• A single line or multiple lines• A single rectangle or multiple rectangles• A single arc or multiple arcsSome of the functions described in the following sectionsuse these structures:__│ typedef struct {short x1, y1, x2, y2;} XSegment;│____│ typedef struct {short x, y;} XPoint;│____│ typedef struct {short x, y;unsigned short width, height;} XRectangle;│____│ typedef struct {short x, y;unsigned short width, height;short angle1, angle2; /* Degrees * 64 */} XArc;│__ All x and y members are signed integers. The width andheight members are 16-bit unsigned integers. You should becareful not to generate coordinates and sizes out of the16-bit ranges, because the protocol only has 16-bit fieldsfor these values.8.3.1. Drawing Single and Multiple PointsTo draw a single point in a given drawable, use XDrawPoint.__│ XDrawPoint(display, d, gc, x, y)Display *display;Drawable d;GC gc;int x, y;display Specifies the connection to the X server.d Specifies the drawable.gc Specifies the GC.xy Specify the x and y coordinates where you want thepoint drawn.│__ To draw multiple points in a given drawable, useXDrawPoints.__│ XDrawPoints(display, d, gc, points, npoints, mode)Display *display;Drawable d;GC gc;XPoint *points;int npoints;int mode;display Specifies the connection to the X server.d Specifies the drawable.gc Specifies the GC.points Specifies an array of points.npoints Specifies the number of points in the array.mode Specifies the coordinate mode. You can passCoordModeOrigin or CoordModePrevious.│__ The XDrawPoint function uses the foreground pixel andfunction components of the GC to draw a single point intothe specified drawable; XDrawPoints draws multiple pointsthis way. CoordModeOrigin treats all coordinates asrelative to the origin, and CoordModePrevious treats allcoordinates after the first as relative to the previouspoint. XDrawPoints draws the points in the order listed inthe array.Both functions use these GC components: function,plane-mask, foreground, subwindow-mode, clip-x-origin,clip-y-origin, and clip-mask.XDrawPoint can generate BadDrawable, BadGC, and BadMatcherrors. XDrawPoints can generate BadDrawable, BadGC,BadMatch, and BadValue errors.8.3.2. Drawing Single and Multiple LinesTo draw a single line between two points in a givendrawable, use XDrawLine.__│ XDrawLine(display, d, gc, x1, y1, x2, y2)Display *display;Drawable d;GC gc;int x1, y1, x2, y2;display Specifies the connection to the X server.d Specifies the drawable.gc Specifies the GC.x1y1x2y2 Specify the points (x1, y1) and (x2, y2) to beconnected.│__ To draw multiple lines in a given drawable, use XDrawLines.__│ XDrawLines(display, d, gc, points, npoints, mode)Display *display;Drawable d;GC gc;XPoint *points;int npoints;int mode;display Specifies the connection to the X server.d Specifies the drawable.gc Specifies the GC.points Specifies an array of points.npoints Specifies the number of points in the array.mode Specifies the coordinate mode. You can passCoordModeOrigin or CoordModePrevious.│__ To draw multiple, unconnected lines in a given drawable, useXDrawSegments.__│ XDrawSegments(display, d, gc, segments, nsegments)Display *display;Drawable d;GC gc;XSegment *segments;int nsegments;display Specifies the connection to the X server.d Specifies the drawable.gc Specifies the GC.segments Specifies an array of segments.nsegments Specifies the number of segments in the array.│__ The XDrawLine function uses the components of the specifiedGC to draw a line between the specified set of points (x1,y1) and (x2, y2). It does not perform joining at coincidentendpoints. For any given line, XDrawLine does not draw apixel more than once. If lines intersect, the intersectingpixels are drawn multiple times.The XDrawLines function uses the components of the specifiedGC to draw npoints−1 lines between each pair of points(point[i], point[i+1]) in the array of XPoint structures.It draws the lines in the order listed in the array. Thelines join correctly at all intermediate points, and if thefirst and last points coincide, the first and last linesalso join correctly. For any given line, XDrawLines doesnot draw a pixel more than once. If thin (zero line-width)lines intersect, the intersecting pixels are drawn multipletimes. If wide lines intersect, the intersecting pixels aredrawn only once, as though the entire PolyLine protocolrequest were a single, filled shape. CoordModeOrigin treatsall coordinates as relative to the origin, andCoordModePrevious treats all coordinates after the first asrelative to the previous point.The XDrawSegments function draws multiple, unconnectedlines. For each segment, XDrawSegments draws a line between(x1, y1) and (x2, y2). It draws the lines in the orderlisted in the array of XSegment structures and does notperform joining at coincident endpoints. For any givenline, XDrawSegments does not draw a pixel more than once.If lines intersect, the intersecting pixels are drawnmultiple times.All three functions use these GC components: function,plane-mask, line-width, line-style, cap-style, fill-style,subwindow-mode, clip-x-origin, clip-y-origin, and clip-mask.The XDrawLines function also uses the join-style GCcomponent. All three functions also use these GCmode-dependent components: foreground, background, tile,stipple, tile-stipple-x-origin, tile-stipple-y-origin,dash-offset, and dash-list.XDrawLine, XDrawLines, and XDrawSegments can generateBadDrawable, BadGC, and BadMatch errors. XDrawLines alsocan generate BadValue errors.8.3.3. Drawing Single and Multiple RectanglesTo draw the outline of a single rectangle in a givendrawable, use XDrawRectangle.__│ XDrawRectangle(display, d, gc, x, y, width, height)Display *display;Drawable d;GC gc;int x, y;unsigned int width, height;display Specifies the connection to the X server.d Specifies the drawable.gc Specifies the GC.xy Specify the x and y coordinates, which specify theupper-left corner of the rectangle.widthheight Specify the width and height, which specify thedimensions of the rectangle.│__ To draw the outline of multiple rectangles in a givendrawable, use XDrawRectangles.__│ XDrawRectangles(display, d, gc, rectangles, nrectangles)Display *display;Drawable d;GC gc;XRectangle rectangles[];int nrectangles;display Specifies the connection to the X server.d Specifies the drawable.gc Specifies the GC.rectanglesSpecifies an array of rectangles.nrectanglesSpecifies the number of rectangles in the array.│__ The XDrawRectangle and XDrawRectangles functions draw theoutlines of the specified rectangle or rectangles as if afive-point PolyLine protocol request were specified for eachrectangle:[x,y] [x+width,y] [x+width,y+height] [x,y+height] [x,y]For the specified rectangle or rectangles, these functionsdo not draw a pixel more than once. XDrawRectangles drawsthe rectangles in the order listed in the array. Ifrectangles intersect, the intersecting pixels are drawnmultiple times.Both functions use these GC components: function,plane-mask, line-width, line-style, cap-style, join-style,fill-style, subwindow-mode, clip-x-origin, clip-y-origin,and clip-mask. They also use these GC mode-dependentcomponents: foreground, background, tile, stipple,tile-stipple-x-origin, tile-stipple-y-origin, dash-offset,and dash-list.XDrawRectangle and XDrawRectangles can generate BadDrawable,BadGC, and BadMatch errors.8.3.4. Drawing Single and Multiple ArcsTo draw a single arc in a given drawable, use XDrawArc.__│ XDrawArc(display, d, gc, x, y, width, height, angle1, angle2)Display *display;Drawable d;GC gc;int x, y;unsigned int width, height;int angle1, angle2;display Specifies the connection to the X server.d Specifies the drawable.gc Specifies the GC.xy Specify the x and y coordinates, which arerelative to the origin of the drawable and specifythe upper-left corner of the bounding rectangle.widthheight Specify the width and height, which are the majorand minor axes of the arc.angle1 Specifies the start of the arc relative to thethree-o’clock position from the center, in unitsof degrees * 64.angle2 Specifies the path and extent of the arc relativeto the start of the arc, in units of degrees * 64.│__ To draw multiple arcs in a given drawable, use XDrawArcs.__│ XDrawArcs(display, d, gc, arcs, narcs)Display *display;Drawable d;GC gc;XArc *arcs;int narcs;display Specifies the connection to the X server.d Specifies the drawable.gc Specifies the GC.arcs Specifies an array of arcs.narcs Specifies the number of arcs in the array.│__ XDrawArcdraws a single circular or elliptical arc, andXDrawArcsdraws multiple circular or elliptical arcs.Each arc is specified by a rectangle and two angles.The center of the circle or ellipse is the center of therectangle, and the major and minor axes are specified by the width and height.Positive angles indicate counterclockwise motion,and negative angles indicate clockwise motion.If the magnitude of angle2 is greater than 360 degrees,XDrawArcorXDrawArcstruncates it to 360 degrees.For an arc specified as [x,y,width,height,angle1,angle2],the origin of the major and minor axes is at[x+width2 ,y+height2 ], and the infinitely thin path describingthe entire circle or ellipse intersects the horizontal axisat [x,y+height2 ] and [x+width,y+height2 ] and intersects thevertical axis at [x+width2 ,y] and [x+width2 ,y+height]. Thesecoordinates can be fractional and so are not truncated todiscrete coordinates. The path should be defined by theideal mathematical path. For a wide line with line-widthlw, the bounding outlines for filling are given by the twoinfinitely thin paths consisting of all points whoseperpendicular distance from the path of the circle/ellipseis equal to lw/2 (which may be a fractional value). Thecap-style and join-style are applied the same as for a linecorresponding to the tangent of the circle/ellipse at theendpoint.For an arc specified as [x,y,width,height,angle1,angle2],the angles must be specified in the effectively skewedcoordinate system of the ellipse (for a circle, the anglesand coordinate systems are identical). The relationshipbetween these angles and angles expressed in the normalcoordinate system of the screen (as measured with aprotractor) is as follows:skewed-angle=atan⎝tan(normal-angle)* widtheight⎠+adjustThe skewed-angle and normal-angle are expressed in radians(rather than in degrees scaled by 64) in the range [0,2π]and where atan returns a value in the range [−2,2] andadjust is:0 for normal-angle in the range [0,2]π for normal-angle in the range [2,32]2π for normal-angle in the range [32,2π]For any given arc, XDrawArc and XDrawArcs do not draw apixel more than once. If two arcs join correctly and if theline-width is greater than zero and the arcs intersect,XDrawArc and XDrawArcs do not draw a pixel more than once.Otherwise, the intersecting pixels of intersecting arcs aredrawn multiple times. Specifying an arc with one endpointand a clockwise extent draws the same pixels as specifyingthe other endpoint and an equivalent counterclockwiseextent, except as it affects joins.If the last point in one arc coincides with the first pointin the following arc, the two arcs will join correctly. Ifthe first point in the first arc coincides with the lastpoint in the last arc, the two arcs will join correctly. Byspecifying one axis to be zero, a horizontal or verticalline can be drawn. Angles are computed based solely on thecoordinate system and ignore the aspect ratio.Both functions use these GC components: function,plane-mask, line-width, line-style, cap-style, join-style,fill-style, subwindow-mode, clip-x-origin, clip-y-origin,and clip-mask. They also use these GC mode-dependentcomponents: foreground, background, tile, stipple,tile-stipple-x-origin, tile-stipple-y-origin, dash-offset,and dash-list.XDrawArc and XDrawArcs can generate BadDrawable, BadGC, andBadMatch errors.8.4. Filling AreasXlib provides functions that you can use to fill:• A single rectangle or multiple rectangles• A single polygon• A single arc or multiple arcs8.4.1. Filling Single and Multiple RectanglesTo fill a single rectangular area in a given drawable, useXFillRectangle.__│ XFillRectangle(display, d, gc, x, y, width, height)Display *display;Drawable d;GC gc;int x, y;unsigned int width, height;display Specifies the connection to the X server.d Specifies the drawable.gc Specifies the GC.xy Specify the x and y coordinates, which arerelative to the origin of the drawable and specifythe upper-left corner of the rectangle.widthheight Specify the width and height, which are thedimensions of the rectangle to be filled.│__ To fill multiple rectangular areas in a given drawable, useXFillRectangles.__│ XFillRectangles(display, d, gc, rectangles, nrectangles)Display *display;Drawable d;GC gc;XRectangle *rectangles;int nrectangles;display Specifies the connection to the X server.d Specifies the drawable.gc Specifies the GC.rectanglesSpecifies an array of rectangles.nrectanglesSpecifies the number of rectangles in the array.│__ The XFillRectangle and XFillRectangles functions fill thespecified rectangle or rectangles as if a four-pointFillPolygon protocol request were specified for eachrectangle:[x,y] [x+width,y] [x+width,y+height] [x,y+height]Each function uses the x and y coordinates, width and heightdimensions, and GC you specify.XFillRectangles fills the rectangles in the order listed inthe array. For any given rectangle, XFillRectangle andXFillRectangles do not draw a pixel more than once. Ifrectangles intersect, the intersecting pixels are drawnmultiple times.Both functions use these GC components: function,plane-mask, fill-style, subwindow-mode, clip-x-origin,clip-y-origin, and clip-mask. They also use these GCmode-dependent components: foreground, background, tile,stipple, tile-stipple-x-origin, and tile-stipple-y-origin.XFillRectangle and XFillRectangles can generate BadDrawable,BadGC, and BadMatch errors.8.4.2. Filling a Single PolygonTo fill a polygon area in a given drawable, useXFillPolygon.__│ XFillPolygon(display, d, gc, points, npoints, shape, mode)Display *display;Drawable d;GC gc;XPoint *points;int npoints;int shape;int mode;display Specifies the connection to the X server.d Specifies the drawable.gc Specifies the GC.points Specifies an array of points.npoints Specifies the number of points in the array.shape Specifies a shape that helps the server to improveperformance. You can pass Complex, Convex, orNonconvex.mode Specifies the coordinate mode. You can passCoordModeOrigin or CoordModePrevious.│__ XFillPolygon fills the region closed by the specified path.The path is closed automatically if the last point in thelist does not coincide with the first point. XFillPolygondoes not draw a pixel of the region more than once.CoordModeOrigin treats all coordinates as relative to theorigin, and CoordModePrevious treats all coordinates afterthe first as relative to the previous point.Depending on the specified shape, the following occurs:• If shape is Complex, the path may self-intersect. Notethat contiguous coincident points in the path are nottreated as self-intersection.• If shape is Convex, for every pair of points inside thepolygon, the line segment connecting them does notintersect the path. If known by the client, specifyingConvex can improve performance. If you specify Convexfor a path that is not convex, the graphics results areundefined.• If shape is Nonconvex, the path does notself-intersect, but the shape is not wholly convex. Ifknown by the client, specifying Nonconvex instead ofComplex may improve performance. If you specifyNonconvex for a self-intersecting path, the graphicsresults are undefined.The fill-rule of the GC controls the filling behavior ofself-intersecting polygons.This function uses these GC components: function,plane-mask, fill-style, fill-rule, subwindow-mode,clip-x-origin, clip-y-origin, and clip-mask. It also usesthese GC mode-dependent components: foreground, background,tile, stipple, tile-stipple-x-origin, andtile-stipple-y-origin.XFillPolygon can generate BadDrawable, BadGC, BadMatch, andBadValue errors.8.4.3. Filling Single and Multiple ArcsTo fill a single arc in a given drawable, use XFillArc.__│ XFillArc(display, d, gc, x, y, width, height, angle1, angle2)Display *display;Drawable d;GC gc;int x, y;unsigned int width, height;int angle1, angle2;display Specifies the connection to the X server.d Specifies the drawable.gc Specifies the GC.xy Specify the x and y coordinates, which arerelative to the origin of the drawable and specifythe upper-left corner of the bounding rectangle.widthheight Specify the width and height, which are the majorand minor axes of the arc.angle1 Specifies the start of the arc relative to thethree-o’clock position from the center, in unitsof degrees * 64.angle2 Specifies the path and extent of the arc relativeto the start of the arc, in units of degrees * 64.│__ To fill multiple arcs in a given drawable, use XFillArcs.__│ XFillArcs(display, d, gc, arcs, narcs)Display *display;Drawable d;GC gc;XArc *arcs;int narcs;display Specifies the connection to the X server.d Specifies the drawable.gc Specifies the GC.arcs Specifies an array of arcs.narcs Specifies the number of arcs in the array.│__ For each arc, XFillArc or XFillArcs fills the region closedby the infinitely thin path described by the specified arcand, depending on the arc-mode specified in the GC, one ortwo line segments. For ArcChord, the single line segmentjoining the endpoints of the arc is used. For ArcPieSlice,the two line segments joining the endpoints of the arc withthe center point are used. XFillArcs fills the arcs in theorder listed in the array. For any given arc, XFillArc andXFillArcs do not draw a pixel more than once. If regionsintersect, the intersecting pixels are drawn multiple times.Both functions use these GC components: function,plane-mask, fill-style, arc-mode, subwindow-mode,clip-x-origin, clip-y-origin, and clip-mask. They also usethese GC mode-dependent components: foreground, background,tile, stipple, tile-stipple-x-origin, andtile-stipple-y-origin.XFillArc and XFillArcs can generate BadDrawable, BadGC, andBadMatch errors.8.5. Font MetricsA font is a graphical description of a set of charactersthat are used to increase efficiency whenever a set ofsmall, similar sized patterns are repeatedly used.This section discusses how to:• Load and free fonts• Obtain and free font names• Compute character string sizes• Compute logical extents• Query character string sizesThe X server loads fonts whenever a program requests a newfont. The server can cache fonts for quick lookup. Fontsare global across all screens in a server. Several levelsare possible when dealing with fonts. Most applicationssimply use XLoadQueryFont to load a font and query the fontmetrics.Characters in fonts are regarded as masks. Except for imagetext requests, the only pixels modified are those in whichbits are set to 1 in the character. This means that itmakes sense to draw text using stipples or tiles (forexample, many menus gray-out unusable entries).__│ The XFontStruct structure contains all of the informationfor the font and consists of the font-specific informationas well as a pointer to an array of XCharStruct structuresfor the characters contained in the font. The XFontStruct,XFontProp, and XCharStruct structures contain:typedef struct {short lbearing; /* origin to left edge of raster */short rbearing; /* origin to right edge of raster */short width; /* advance to next char’s origin */short ascent; /* baseline to top edge of raster */short descent; /* baseline to bottom edge of raster */unsigned short attributes;/* per char flags (not predefined) */} XCharStruct;typedef struct {Atom name;unsigned long card32;} XFontProp;typedef struct { /* normal 16 bit characters are two bytes */unsigned char byte1;unsigned char byte2;} XChar2b;typedef struct {XExtData *ext_data; /* hook for extension to hang data */Font fid; /* Font id for this font */unsigned direction; /* hint about the direction font is painted */unsigned min_char_or_byte2;/* first character */unsigned max_char_or_byte2;/* last character */unsigned min_byte1; /* first row that exists */unsigned max_byte1; /* last row that exists */Bool all_chars_exist; /* flag if all characters have nonzero size */unsigned default_char; /* char to print for undefined character */int n_properties; /* how many properties there are */XFontProp *properties; /* pointer to array of additional properties */XCharStruct min_bounds; /* minimum bounds over all existing char */XCharStruct max_bounds; /* maximum bounds over all existing char */XCharStruct *per_char; /* first_char to last_char information */int ascent; /* logical extent above baseline for spacing */int descent; /* logical descent below baseline for spacing */} XFontStruct;│__ X supports single byte/character, two bytes/charactermatrix, and 16-bit character text operations. Note that anyof these forms can be used with a font, but a singlebyte/character text request can only specify a single byte(that is, the first row of a 2-byte font). You should view2-byte fonts as a two-dimensional matrix of definedcharacters: byte1 specifies the range of defined rows andbyte2 defines the range of defined columns of the font.Single byte/character fonts have one row defined, and thebyte2 range specified in the structure defines a range ofcharacters.The bounding box of a character is defined by theXCharStruct of that character. When characters are absentfrom a font, the default_char is used. When fonts have allcharacters of the same size, only the information in theXFontStruct min and max bounds are used.The members of the XFontStruct have the following semantics:• The direction member can be either FontLeftToRight orFontRightToLeft. It is just a hint as to whether mostXCharStruct elements have a positive (FontLeftToRight)or a negative (FontRightToLeft) character width metric.The core protocol defines no support for vertical text.• If the min_byte1 and max_byte1 members are both zero,min_char_or_byte2 specifies the linear character indexcorresponding to the first element of the per_chararray, and max_char_or_byte2 specifies the linearcharacter index of the last element.If either min_byte1 or max_byte1 are nonzero, bothmin_char_or_byte2 and max_char_or_byte2 are less than256, and the 2-byte character index valuescorresponding to the per_char array element N (countingfrom 0) are:byte1 = N/D + min_byte1byte2 = N\D + min_char_or_byte2where: D = max_char_or_byte2 − min_char_or_byte2 + 1/ = integer division\ = integer modulus• If the per_char pointer is NULL, all glyphs between thefirst and last character indexes inclusive have thesame information, as given by both min_bounds andmax_bounds.• If all_chars_exist is True, all characters in theper_char array have nonzero bounding boxes.• The default_char member specifies the character thatwill be used when an undefined or nonexistent characteris printed. The default_char is a 16-bit character(not a 2-byte character). For a font using 2-bytematrix format, the default_char has byte1 in themost-significant byte and byte2 in the leastsignificant byte. If the default_char itself specifiesan undefined or nonexistent character, no printing isperformed for an undefined or nonexistent character.• The min_bounds and max_bounds members contain the mostextreme values of each individual XCharStruct componentover all elements of this array (and ignore nonexistentcharacters). The bounding box of the font (thesmallest rectangle enclosing the shape obtained bysuperimposing all of the characters at the same origin[x,y]) has its upper-left coordinate at:[x + min_bounds.lbearing, y − max_bounds.ascent]Its width is:max_bounds.rbearing − min_bounds.lbearingIts height is:max_bounds.ascent + max_bounds.descent• The ascent member is the logical extent of the fontabove the baseline that is used for determining linespacing. Specific characters may extend beyond this.• The descent member is the logical extent of the font ator below the baseline that is used for determining linespacing. Specific characters may extend beyond this.• If the baseline is at Y-coordinate y, the logicalextent of the font is inclusive between theY-coordinate values (y − font.ascent) and (y +font.descent − 1). Typically, the minimum interlinespacing between rows of text is given by ascent +descent.For a character origin at [x,y], the bounding box of acharacter (that is, the smallest rectangle that encloses thecharacter’s shape) described in terms of XCharStructcomponents is a rectangle with its upper-left corner at:[x + lbearing, y − ascent]Its width is:rbearing − lbearingIts height is:ascent + descentThe origin for the next character is defined to be:[x + width, y]The lbearing member defines the extent of the left edge ofthe character ink from the origin. The rbearing memberdefines the extent of the right edge of the character inkfrom the origin. The ascent member defines the extent ofthe top edge of the character ink from the origin. Thedescent member defines the extent of the bottom edge of thecharacter ink from the origin. The width member defines thelogical width of the character.Note that the baseline (the y position of the characterorigin) is logically viewed as being the scanline just belownondescending characters. When descent is zero, only pixelswith Y-coordinates less than y are drawn, and the origin islogically viewed as being coincident with the left edge of anonkerned character. When lbearing is zero, no pixels withX-coordinate less than x are drawn. Any of the XCharStructmetric members could be negative. If the width is negative,the next character will be placed to the left of the currentorigin.The X protocol does not define the interpretation of theattributes member in the XCharStruct structure. Anonexistent character is represented with all members of itsXCharStruct set to zero.A font is not guaranteed to have any properties. Theinterpretation of the property value (for example, long orunsigned long) must be derived from a priori knowledge ofthe property. A basic set of font properties is specifiedin the X Consortium standard X Logical Font DescriptionConventions.8.5.1. Loading and Freeing FontsXlib provides functions that you can use to load fonts, getfont information, unload fonts, and free font information.A few font functions use a GContext resource ID or a font IDinterchangeably.To load a given font, use XLoadFont.__│ Font XLoadFont(display, name)Display *display;char *name;display Specifies the connection to the X server.name Specifies the name of the font, which is anull-terminated string.│__ The XLoadFont function loads the specified font and returnsits associated font ID. If the font name is not in the HostPortable Character Encoding, the result isimplementation-dependent. Use of uppercase or lowercasedoes not matter. When the characters ‘‘?’’ and ‘‘*’’ areused in a font name, a pattern match is performed and anymatching font is used. In the pattern, the ‘‘?’’ characterwill match any single character, and the ‘‘*’’ characterwill match any number of characters. A structured formatfor font names is specified in the X Consortium standard XLogical Font Description Conventions. If XLoadFont wasunsuccessful at loading the specified font, a BadName errorresults. Fonts are not associated with a particular screenand can be stored as a component of any GC. When the fontis no longer needed, call XUnloadFont.XLoadFont can generate BadAlloc and BadName errors.To return information about an available font, useXQueryFont.__│ XFontStruct *XQueryFont(display, font_ID)Display *display;XID font_ID;display Specifies the connection to the X server.font_ID Specifies the font ID or the GContext ID.│__ The XQueryFont function returns a pointer to the XFontStructstructure, which contains information associated with thefont. You can query a font or the font stored in a GC. Thefont ID stored in the XFontStruct structure will be theGContext ID, and you need to be careful when using this IDin other functions (see XGContextFromGC). If the font doesnot exist, XQueryFont returns NULL. To free this data, useXFreeFontInfo.To perform a XLoadFont and XQueryFont in a single operation,use XLoadQueryFont.__│ XFontStruct *XLoadQueryFont(display, name)Display *display;char *name;display Specifies the connection to the X server.name Specifies the name of the font, which is anull-terminated string.│__ The XLoadQueryFont function provides the most common way foraccessing a font. XLoadQueryFont both opens (loads) thespecified font and returns a pointer to the appropriateXFontStruct structure. If the font name is not in the HostPortable Character Encoding, the result isimplementation-dependent. If the font does not exist,XLoadQueryFont returns NULL.XLoadQueryFont can generate a BadAlloc error.To unload the font and free the storage used by the fontstructure that was allocated by XQueryFont orXLoadQueryFont, use XFreeFont.__│ XFreeFont(display, font_struct)Display *display;XFontStruct *font_struct;display Specifies the connection to the X server.font_structSpecifies the storage associated with the font.│__ The XFreeFont function deletes the association between thefont resource ID and the specified font and frees theXFontStruct structure. The font itself will be freed whenno other resource references it. The data and the fontshould not be referenced again.XFreeFont can generate a BadFont error.To return a given font property, use XGetFontProperty.__│ Bool XGetFontProperty(font_struct, atom, value_return)XFontStruct *font_struct;Atom atom;unsigned long *value_return;font_structSpecifies the storage associated with the font.atom Specifies the atom for the property name you wantreturned.value_returnReturns the value of the font property.│__ Given the atom for that property, the XGetFontPropertyfunction returns the value of the specified font property.XGetFontProperty also returns False if the property was notdefined or True if it was defined. A set of predefinedatoms exists for font properties, which can be found in<X11/Xatom.h>. This set contains the standard propertiesassociated with a font. Although it is not guaranteed, itis likely that the predefined font properties will bepresent.To unload a font that was loaded by XLoadFont, useXUnloadFont.__│ XUnloadFont(display, font)Display *display;Font font;display Specifies the connection to the X server.font Specifies the font.│__ The XUnloadFont function deletes the association between thefont resource ID and the specified font. The font itselfwill be freed when no other resource references it. Thefont should not be referenced again.XUnloadFont can generate a BadFont error.8.5.2. Obtaining and Freeing Font Names and InformationYou obtain font names and information by matching a wildcardspecification when querying a font type for a list ofavailable sizes and so on.To return a list of the available font names, useXListFonts.__│ char **XListFonts(display, pattern, maxnames, actual_count_return)Display *display;char *pattern;int maxnames;int *actual_count_return;display Specifies the connection to the X server.pattern Specifies the null-terminated pattern string thatcan contain wildcard characters.maxnames Specifies the maximum number of names to bereturned.actual_count_returnReturns the actual number of font names.│__ The XListFonts function returns an array of available fontnames (as controlled by the font search path; seeXSetFontPath) that match the string you passed to thepattern argument. The pattern string can contain anycharacters, but each asterisk (*) is a wildcard for anynumber of characters, and each question mark (?) is awildcard for a single character. If the pattern string isnot in the Host Portable Character Encoding, the result isimplementation-dependent. Use of uppercase or lowercasedoes not matter. Each returned string is null-terminated.If the data returned by the server is in the Latin PortableCharacter Encoding, then the returned strings are in theHost Portable Character Encoding. Otherwise, the result isimplementation-dependent. If there are no matching fontnames, XListFonts returns NULL. The client should callXFreeFontNames when finished with the result to free thememory.To free a font name array, use XFreeFontNames.__│ XFreeFontNames(list)char *list[];list Specifies the array of strings you want to free.│__ The XFreeFontNames function frees the array and stringsreturned by XListFonts or XListFontsWithInfo.To obtain the names and information about available fonts,use XListFontsWithInfo.__│ char **XListFontsWithInfo(display, pattern, maxnames, count_return, info_return)Display *display;char *pattern;int maxnames;int *count_return;XFontStruct **info_return;display Specifies the connection to the X server.pattern Specifies the null-terminated pattern string thatcan contain wildcard characters.maxnames Specifies the maximum number of names to bereturned.count_returnReturns the actual number of matched font names.info_returnReturns the font information.│__ The XListFontsWithInfo function returns a list of font namesthat match the specified pattern and their associated fontinformation. The list of names is limited to size specifiedby maxnames. The information returned for each font isidentical to what XLoadQueryFont would return except thatthe per-character metrics are not returned. The patternstring can contain any characters, but each asterisk (*) isa wildcard for any number of characters, and each questionmark (?) is a wildcard for a single character. If thepattern string is not in the Host Portable CharacterEncoding, the result is implementation-dependent. Use ofuppercase or lowercase does not matter. Each returnedstring is null-terminated. If the data returned by theserver is in the Latin Portable Character Encoding, then thereturned strings are in the Host Portable CharacterEncoding. Otherwise, the result isimplementation-dependent. If there are no matching fontnames, XListFontsWithInfo returns NULL.To free only the allocated name array, the client shouldcall XFreeFontNames. To free both the name array and thefont information array or to free just the font informationarray, the client should call XFreeFontInfo.To free font structures and font names, use XFreeFontInfo.__│ XFreeFontInfo(names, free_info, actual_count)char **names;XFontStruct *free_info;int actual_count;names Specifies the list of font names.free_info Specifies the font information.actual_countSpecifies the actual number of font names.│__ The XFreeFontInfo function frees a font structure or anarray of font structures and optionally an array of fontnames. If NULL is passed for names, no font names arefreed. If a font structure for an open font (returned byXLoadQueryFont) is passed, the structure is freed, but thefont is not closed; use XUnloadFont to close the font.8.5.3. Computing Character String SizesXlib provides functions that you can use to compute thewidth, the logical extents, and the server information about8-bit and 2-byte text strings. The width is computed byadding the character widths of all the characters. It doesnot matter if the font is an 8-bit or 2-byte font. Thesefunctions return the sum of the character metrics in pixels.To determine the width of an 8-bit character string, useXTextWidth.__│ int XTextWidth(font_struct, string, count)XFontStruct *font_struct;char *string;int count;font_structSpecifies the font used for the width computation.string Specifies the character string.count Specifies the character count in the specifiedstring.│__ To determine the width of a 2-byte character string, useXTextWidth16.__│ int XTextWidth16(font_struct, string, count)XFontStruct *font_struct;XChar2b *string;int count;font_structSpecifies the font used for the width computation.string Specifies the character string.count Specifies the character count in the specifiedstring.│__ 8.5.4. Computing Logical ExtentsTo compute the bounding box of an 8-bit character string ina given font, use XTextExtents.__│ XTextExtents(font_struct, string, nchars, direction_return, font_ascent_return,font_descent_return, overall_return)XFontStruct *font_struct;char *string;int nchars;int *direction_return;int *font_ascent_return, *font_descent_return;XCharStruct *overall_return;font_structSpecifies the XFontStruct structure.string Specifies the character string.nchars Specifies the number of characters in thecharacter string.direction_returnReturns the value of the direction hint(FontLeftToRight or FontRightToLeft).font_ascent_returnReturns the font ascent.font_descent_returnReturns the font descent.overall_returnReturns the overall size in the specifiedXCharStruct structure.│__ To compute the bounding box of a 2-byte character string ina given font, use XTextExtents16.__│ XTextExtents16(font_struct, string, nchars, direction_return, font_ascent_return,font_descent_return, overall_return)XFontStruct *font_struct;XChar2b *string;int nchars;int *direction_return;int *font_ascent_return, *font_descent_return;XCharStruct *overall_return;font_structSpecifies the XFontStruct structure.string Specifies the character string.nchars Specifies the number of characters in thecharacter string.direction_returnReturns the value of the direction hint(FontLeftToRight or FontRightToLeft).font_ascent_returnReturns the font ascent.font_descent_returnReturns the font descent.overall_returnReturns the overall size in the specifiedXCharStruct structure.│__ The XTextExtents and XTextExtents16 functions perform thesize computation locally and, thereby, avoid the round-tripoverhead of XQueryTextExtents and XQueryTextExtents16. Bothfunctions return an XCharStruct structure, whose members areset to the values as follows.The ascent member is set to the maximum of the ascentmetrics of all characters in the string. The descent memberis set to the maximum of the descent metrics. The widthmember is set to the sum of the character-width metrics ofall characters in the string. For each character in thestring, let W be the sum of the character-width metrics ofall characters preceding it in the string. Let L be theleft-side-bearing metric of the character plus W. Let R bethe right-side-bearing metric of the character plus W. Thelbearing member is set to the minimum L of all characters inthe string. The rbearing member is set to the maximum R.For fonts defined with linear indexing rather than 2-bytematrix indexing, each XChar2b structure is interpreted as a16-bit number with byte1 as the most significant byte. Ifthe font has no defined default character, undefinedcharacters in the string are taken to have all zero metrics.8.5.5. Querying Character String SizesTo query the server for the bounding box of an 8-bitcharacter string in a given font, use XQueryTextExtents.__│ XQueryTextExtents(display, font_ID, string, nchars, direction_return, font_ascent_return,font_descent_return, overall_return)Display *display;XID font_ID;char *string;int nchars;int *direction_return;int *font_ascent_return, *font_descent_return;XCharStruct *overall_return;display Specifies the connection to the X server.font_ID Specifies either the font ID or the GContext IDthat contains the font.string Specifies the character string.nchars Specifies the number of characters in thecharacter string.direction_returnReturns the value of the direction hint(FontLeftToRight or FontRightToLeft).font_ascent_returnReturns the font ascent.font_descent_returnReturns the font descent.overall_returnReturns the overall size in the specifiedXCharStruct structure.│__ To query the server for the bounding box of a 2-bytecharacter string in a given font, use XQueryTextExtents16.__│ XQueryTextExtents16(display, font_ID, string, nchars, direction_return, font_ascent_return,font_descent_return, overall_return)Display *display;XID font_ID;XChar2b *string;int nchars;int *direction_return;int *font_ascent_return, *font_descent_return;XCharStruct *overall_return;display Specifies the connection to the X server.font_ID Specifies either the font ID or the GContext IDthat contains the font.string Specifies the character string.nchars Specifies the number of characters in thecharacter string.direction_returnReturns the value of the direction hint(FontLeftToRight or FontRightToLeft).font_ascent_returnReturns the font ascent.font_descent_returnReturns the font descent.overall_returnReturns the overall size in the specifiedXCharStruct structure.│__ The XQueryTextExtents and XQueryTextExtents16 functionsreturn the bounding box of the specified 8-bit and 16-bitcharacter string in the specified font or the font containedin the specified GC. These functions query the X serverand, therefore, suffer the round-trip overhead that isavoided by XTextExtents and XTextExtents16. Both functionsreturn a XCharStruct structure, whose members are set to thevalues as follows.The ascent member is set to the maximum of the ascentmetrics of all characters in the string. The descent memberis set to the maximum of the descent metrics. The widthmember is set to the sum of the character-width metrics ofall characters in the string. For each character in thestring, let W be the sum of the character-width metrics ofall characters preceding it in the string. Let L be theleft-side-bearing metric of the character plus W. Let R bethe right-side-bearing metric of the character plus W. Thelbearing member is set to the minimum L of all characters inthe string. The rbearing member is set to the maximum R.For fonts defined with linear indexing rather than 2-bytematrix indexing, each XChar2b structure is interpreted as a16-bit number with byte1 as the most significant byte. Ifthe font has no defined default character, undefinedcharacters in the string are taken to have all zero metrics.Characters with all zero metrics are ignored. If the fonthas no defined default_char, the undefined characters in thestring are also ignored.XQueryTextExtents and XQueryTextExtents16 can generateBadFont and BadGC errors.8.6. Drawing TextThis section discusses how to draw:• Complex text• Text characters• Image text charactersThe fundamental text functions XDrawText and XDrawText16 usethe following structures:__│ typedef struct {char *chars; /* pointer to string */int nchars; /* number of characters */int delta; /* delta between strings */Font font; /* Font to print it in, None don’t change */} XTextItem;typedef struct {XChar2b *chars; /* pointer to two-byte characters */int nchars; /* number of characters */int delta; /* delta between strings */Font font; /* font to print it in, None don’t change */} XTextItem16;│__ If the font member is not None, the font is changed beforeprinting and also is stored in the GC. If an error wasgenerated during text drawing, the previous items may havebeen drawn. The baseline of the characters are drawnstarting at the x and y coordinates that you pass in thetext drawing functions.For example, consider the background rectangle drawn byXDrawImageString. If you want the upper-left corner of thebackground rectangle to be at pixel coordinate (x,y), passthe (x,y + ascent) as the baseline origin coordinates to thetext functions. The ascent is the font ascent, as given inthe XFontStruct structure. If you want the lower-leftcorner of the background rectangle to be at pixel coordinate(x,y), pass the (x,y − descent + 1) as the baseline origincoordinates to the text functions. The descent is the fontdescent, as given in the XFontStruct structure.8.6.1. Drawing Complex TextTo draw 8-bit characters in a given drawable, use XDrawText.__│ XDrawText(display, d, gc, x, y, items, nitems)Display *display;Drawable d;GC gc;int x, y;XTextItem *items;int nitems;display Specifies the connection to the X server.d Specifies the drawable.gc Specifies the GC.xy Specify the x and y coordinates, which arerelative to the origin of the specified drawableand define the origin of the first character.items Specifies an array of text items.nitems Specifies the number of text items in the array.│__ To draw 2-byte characters in a given drawable, useXDrawText16.__│ XDrawText16(display, d, gc, x, y, items, nitems)Display *display;Drawable d;GC gc;int x, y;XTextItem16 *items;int nitems;display Specifies the connection to the X server.d Specifies the drawable.gc Specifies the GC.xy Specify the x and y coordinates, which arerelative to the origin of the specified drawableand define the origin of the first character.items Specifies an array of text items.nitems Specifies the number of text items in the array.│__ The XDrawText16 function is similar to XDrawText except thatit uses 2-byte or 16-bit characters. Both functions allowcomplex spacing and font shifts between counted strings.Each text item is processed in turn. A font member otherthan None in an item causes the font to be stored in the GCand used for subsequent text. A text element deltaspecifies an additional change in the position along the xaxis before the string is drawn. The delta is always addedto the character origin and is not dependent on anycharacteristics of the font. Each character image, asdefined by the font in the GC, is treated as an additionalmask for a fill operation on the drawable. The drawable ismodified only where the font character has a bit set to 1.If a text item generates a BadFont error, the previous textitems may have been drawn.For fonts defined with linear indexing rather than 2-bytematrix indexing, each XChar2b structure is interpreted as a16-bit number with byte1 as the most significant byte.Both functions use these GC components: function,plane-mask, fill-style, font, subwindow-mode, clip-x-origin,clip-y-origin, and clip-mask. They also use these GCmode-dependent components: foreground, background, tile,stipple, tile-stipple-x-origin, and tile-stipple-y-origin.XDrawText and XDrawText16 can generate BadDrawable, BadFont,BadGC, and BadMatch errors.8.6.2. Drawing Text CharactersTo draw 8-bit characters in a given drawable, useXDrawString.__│ XDrawString(display, d, gc, x, y, string, length)Display *display;Drawable d;GC gc;int x, y;char *string;int length;display Specifies the connection to the X server.d Specifies the drawable.gc Specifies the GC.xy Specify the x and y coordinates, which arerelative to the origin of the specified drawableand define the origin of the first character.string Specifies the character string.length Specifies the number of characters in the stringargument.│__ To draw 2-byte characters in a given drawable, useXDrawString16.__│ XDrawString16(display, d, gc, x, y, string, length)Display *display;Drawable d;GC gc;int x, y;XChar2b *string;int length;display Specifies the connection to the X server.d Specifies the drawable.gc Specifies the GC.xy Specify the x and y coordinates, which arerelative to the origin of the specified drawableand define the origin of the first character.string Specifies the character string.length Specifies the number of characters in the stringargument.│__ Each character image, as defined by the font in the GC, istreated as an additional mask for a fill operation on thedrawable. The drawable is modified only where the fontcharacter has a bit set to 1. For fonts defined with 2-bytematrix indexing and used with XDrawString16, each byte isused as a byte2 with a byte1 of zero.Both functions use these GC components: function,plane-mask, fill-style, font, subwindow-mode, clip-x-origin,clip-y-origin, and clip-mask. They also use these GCmode-dependent components: foreground, background, tile,stipple, tile-stipple-x-origin, and tile-stipple-y-origin.XDrawString and XDrawString16 can generate BadDrawable,BadGC, and BadMatch errors.8.6.3. Drawing Image Text CharactersSome applications, in particular terminal emulators, need toprint image text in which both the foreground and backgroundbits of each character are painted. This prevents annoyingflicker on many displays.To draw 8-bit image text characters in a given drawable, useXDrawImageString.__│ XDrawImageString(display, d, gc, x, y, string, length)Display *display;Drawable d;GC gc;int x, y;char *string;int length;display Specifies the connection to the X server.d Specifies the drawable.gc Specifies the GC.xy Specify the x and y coordinates, which arerelative to the origin of the specified drawableand define the origin of the first character.string Specifies the character string.length Specifies the number of characters in the stringargument.│__ To draw 2-byte image text characters in a given drawable,use XDrawImageString16.__│ XDrawImageString16(display, d, gc, x, y, string, length)Display *display;Drawable d;GC gc;int x, y;XChar2b *string;int length;display Specifies the connection to the X server.d Specifies the drawable.gc Specifies the GC.xy Specify the x and y coordinates, which arerelative to the origin of the specified drawableand define the origin of the first character.string Specifies the character string.length Specifies the number of characters in the stringargument.│__ The XDrawImageString16 function is similar toXDrawImageString except that it uses 2-byte or 16-bitcharacters. Both functions also use both the foreground andbackground pixels of the GC in the destination.The effect is first to fill a destination rectangle with thebackground pixel defined in the GC and then to paint thetext with the foreground pixel. The upper-left corner ofthe filled rectangle is at:[x, y − font-ascent]The width is:overall-widthThe height is:font-ascent + font-descentThe overall-width, font-ascent, and font-descent are aswould be returned by XQueryTextExtents using gc and string.The function and fill-style defined in the GC are ignoredfor these functions. The effective function is GXcopy, andthe effective fill-style is FillSolid.For fonts defined with 2-byte matrix indexing and used withXDrawImageString, each byte is used as a byte2 with a byte1of zero.Both functions use these GC components: plane-mask,foreground, background, font, subwindow-mode, clip-x-origin,clip-y-origin, and clip-mask.XDrawImageString and XDrawImageString16 can generateBadDrawable, BadGC, and BadMatch errors.8.7. Transferring Images between Client and ServerXlib provides functions that you can use to transfer imagesbetween a client and the server. Because the server mayrequire diverse data formats, Xlib provides an image objectthat fully describes the data in memory and that providesfor basic operations on that data. You should reference thedata through the image object rather than referencing thedata directly. However, some implementations of the Xliblibrary may efficiently deal with frequently used dataformats by replacing functions in the procedure vector withspecial case functions. Supported operations includedestroying the image, getting a pixel, storing a pixel,extracting a subimage of an image, and adding a constant toan image (see section 16.8).All the image manipulation functions discussed in thissection make use of the XImage structure, which describes animage as it exists in the client’s memory.__│ typedef struct _XImage {int width, height; /* size of image */int xoffset; /* number of pixels offset in X direction */int format; /* XYBitmap, XYPixmap, ZPixmap */char *data; /* pointer to image data */int byte_order; /* data byte order, LSBFirst, MSBFirst */int bitmap_unit; /* quant. of scanline 8, 16, 32 */int bitmap_bit_order; /* LSBFirst, MSBFirst */int bitmap_pad; /* 8, 16, 32 either XY or ZPixmap */int depth; /* depth of image */int bytes_per_line; /* accelerator to next scanline */int bits_per_pixel; /* bits per pixel (ZPixmap) */unsigned long red_mask; /* bits in z arrangement */unsigned long green_mask;unsigned long blue_mask;XPointer obdata; /* hook for the object routines to hang on */struct funcs { /* image manipulation routines */struct _XImage *(*create_image)();int (*destroy_image)();unsigned long (*get_pixel)();int (*put_pixel)();struct _XImage *(*sub_image)();int (*add_pixel)();} f;} XImage;│__ To initialize the image manipulation routines of an imagestructure, use XInitImage.__│ Status XInitImage(image)XImage *image;ximage Specifies the image.│__ The XInitImage function initializes the internal imagemanipulation routines of an image structure, based on thevalues of the various structure members. All fields otherthan the manipulation routines must already be initialized.If the bytes_per_line member is zero, XInitImage will assumethe image data is contiguous in memory and set thebytes_per_line member to an appropriate value based on theother members; otherwise, the value of bytes_per_line is notchanged. All of the manipulation routines are initializedto functions that other Xlib image manipulation functionsneed to operate on the type of image specified by the restof the structure.This function must be called for any image constructed bythe client before passing it to any other Xlib function.Image structures created or returned by Xlib do not need tobe initialized in this fashion.This function returns a nonzero status if initialization ofthe structure is successful. It returns zero if it detectedsome error or inconsistency in the structure, in which casethe image is not changed.To combine an image with a rectangle of a drawable on thedisplay, use XPutImage.__│ XPutImage(display, d, gc, image, src_x, src_y, dest_x, dest_y, width, height)Display *display;Drawable d;GC gc;XImage *image;int src_x, src_y;int dest_x, dest_y;unsigned int width, height;display Specifies the connection to the X server.d Specifies the drawable.gc Specifies the GC.image Specifies the image you want combined with therectangle.src_x Specifies the offset in X from the left edge ofthe image defined by the XImage structure.src_y Specifies the offset in Y from the top edge of theimage defined by the XImage structure.dest_xdest_y Specify the x and y coordinates, which arerelative to the origin of the drawable and are thecoordinates of the subimage.widthheight Specify the width and height of the subimage,which define the dimensions of the rectangle.│__ The XPutImage function combines an image with a rectangle ofthe specified drawable. The section of the image defined bythe src_x, src_y, width, and height arguments is drawn onthe specified part of the drawable. If XYBitmap format isused, the depth of the image must be one, or a BadMatcherror results. The foreground pixel in the GC defines thesource for the one bits in the image, and the backgroundpixel defines the source for the zero bits. For XYPixmapand ZPixmap, the depth of the image must match the depth ofthe drawable, or a BadMatch error results.If the characteristics of the image (for example, byte_orderand bitmap_unit) differ from what the server requires,XPutImage automatically makes the appropriate conversions.This function uses these GC components: function,plane-mask, subwindow-mode, clip-x-origin, clip-y-origin,and clip-mask. It also uses these GC mode-dependentcomponents: foreground and background.XPutImage can generate BadDrawable, BadGC, BadMatch, andBadValue errors.To return the contents of a rectangle in a given drawable onthe display, use XGetImage. This function specificallysupports rudimentary screen dumps.__│ XImage *XGetImage(display, d, x, y, width, height, plane_mask, format)Display *display;Drawable d;int x, y;unsigned int width, height;unsigned long plane_mask;int format;display Specifies the connection to the X server.d Specifies the drawable.xy Specify the x and y coordinates, which arerelative to the origin of the drawable and definethe upper-left corner of the rectangle.widthheight Specify the width and height of the subimage,which define the dimensions of the rectangle.plane_maskSpecifies the plane mask.format Specifies the format for the image. You can passXYPixmap or ZPixmap.│__ The XGetImage function returns a pointer to an XImagestructure. This structure provides you with the contents ofthe specified rectangle of the drawable in the format youspecify. If the format argument is XYPixmap, the imagecontains only the bit planes you passed to the plane_maskargument. If the plane_mask argument only requests a subsetof the planes of the display, the depth of the returnedimage will be the number of planes requested. If the formatargument is ZPixmap, XGetImage returns as zero the bits inall planes not specified in the plane_mask argument. Thefunction performs no range checking on the values inplane_mask and ignores extraneous bits.XGetImage returns the depth of the image to the depth memberof the XImage structure. The depth of the image is asspecified when the drawable was created, except when gettinga subset of the planes in XYPixmap format, when the depth isgiven by the number of bits set to 1 in plane_mask.If the drawable is a pixmap, the given rectangle must bewholly contained within the pixmap, or a BadMatch errorresults. If the drawable is a window, the window must beviewable, and it must be the case that if there were noinferiors or overlapping windows, the specified rectangle ofthe window would be fully visible on the screen and whollycontained within the outside edges of the window, or aBadMatch error results. Note that the borders of the windowcan be included and read with this request. If the windowhas backing-store, the backing-store contents are returnedfor regions of the window that are obscured by noninferiorwindows. If the window does not have backing-store, thereturned contents of such obscured regions are undefined.The returned contents of visible regions of inferiors of adifferent depth than the specified window’s depth are alsoundefined. The pointer cursor image is not included in thereturned contents. If a problem occurs, XGetImage returnsNULL.XGetImage can generate BadDrawable, BadMatch, and BadValueerrors.To copy the contents of a rectangle on the display to alocation within a preexisting image structure, useXGetSubImage.__│ XImage *XGetSubImage(display, d, x, y, width, height, plane_mask, format, dest_image, dest_x,dest_y)Display *display;Drawable d;int x, y;unsigned int width, height;unsigned long plane_mask;int format;XImage *dest_image;int dest_x, dest_y;display Specifies the connection to the X server.d Specifies the drawable.xy Specify the x and y coordinates, which arerelative to the origin of the drawable and definethe upper-left corner of the rectangle.widthheight Specify the width and height of the subimage,which define the dimensions of the rectangle.plane_maskSpecifies the plane mask.format Specifies the format for the image. You can passXYPixmap or ZPixmap.dest_imageSpecifies the destination image.dest_xdest_y Specify the x and y coordinates, which arerelative to the origin of the destinationrectangle, specify its upper-left corner, anddetermine where the subimage is placed in thedestination image.│__ The XGetSubImage function updates dest_image with thespecified subimage in the same manner as XGetImage. If theformat argument is XYPixmap, the image contains only the bitplanes you passed to the plane_mask argument. If the formatargument is ZPixmap, XGetSubImage returns as zero the bitsin all planes not specified in the plane_mask argument. Thefunction performs no range checking on the values inplane_mask and ignores extraneous bits. As a convenience,XGetSubImage returns a pointer to the same XImage structurespecified by dest_image.The depth of the destination XImage structure must be thesame as that of the drawable. If the specified subimagedoes not fit at the specified location on the destinationimage, the right and bottom edges are clipped. If thedrawable is a pixmap, the given rectangle must be whollycontained within the pixmap, or a BadMatch error results.If the drawable is a window, the window must be viewable,and it must be the case that if there were no inferiors oroverlapping windows, the specified rectangle of the windowwould be fully visible on the screen and wholly containedwithin the outside edges of the window, or a BadMatch errorresults. If the window has backing-store, then thebacking-store contents are returned for regions of thewindow that are obscured by noninferior windows. If thewindow does not have backing-store, the returned contents ofsuch obscured regions are undefined. The returned contentsof visible regions of inferiors of a different depth thanthe specified window’s depth are also undefined. If aproblem occurs, XGetSubImage returns NULL.XGetSubImage can generate BadDrawable, BadGC, BadMatch, andBadValue errors. 8
9.1. Changing the Parent of a WindowTo change a window’s parent to another window on the samescreen, use XReparentWindow. There is no way to move awindow between screens.__│ XReparentWindow(display, w, parent, x, y)Display *display;Window w;Window parent;int x, y;display Specifies the connection to the X server.w Specifies the window.parent Specifies the parent window.xy Specify the x and y coordinates of the position inthe new parent window.│__ If the specified window is mapped, XReparentWindowautomatically performs an UnmapWindow request on it, removesit from its current position in the hierarchy, and insertsit as the child of the specified parent. The window isplaced in the stacking order on top with respect to siblingwindows.After reparenting the specified window, XReparentWindowcauses the X server to generate a ReparentNotify event. Theoverride_redirect member returned in this event is set tothe window’s corresponding attribute. Window managerclients usually should ignore this window if this member isset to True. Finally, if the specified window wasoriginally mapped, the X server automatically performs aMapWindow request on it.The X server performs normal exposure processing on formerlyobscured windows. The X server might not generate Exposeevents for regions from the initial UnmapWindow request thatare immediately obscured by the final MapWindow request. ABadMatch error results if:• The new parent window is not on the same screen as theold parent window.• The new parent window is the specified window or aninferior of the specified window.• The new parent is InputOnly, and the window is not.• The specified window has a ParentRelative background,and the new parent window is not the same depth as thespecified window.XReparentWindow can generate BadMatch and BadWindow errors.9.2. Controlling the Lifetime of a WindowThe save-set of a client is a list of other clients’ windowsthat, if they are inferiors of one of the client’s windowsat connection close, should not be destroyed and should beremapped if they are unmapped. For further informationabout close-connection processing, see section 2.6. Toallow an application’s window to survive when a windowmanager that has reparented a window fails, Xlib providesthe save-set functions that you can use to control thelongevity of subwindows that are normally destroyed when theparent is destroyed. For example, a window manager thatwants to add decoration to a window by adding a frame mightreparent an application’s window. When the frame isdestroyed, the application’s window should not be destroyedbut be returned to its previous place in the windowhierarchy.The X server automatically removes windows from the save-setwhen they are destroyed.To add or remove a window from the client’s save-set, useXChangeSaveSet.__│ XChangeSaveSet(display, w, change_mode)Display *display;Window w;int change_mode;display Specifies the connection to the X server.w Specifies the window that you want to add to ordelete from the client’s save-set.change_modeSpecifies the mode. You can pass SetModeInsert orSetModeDelete.│__ Depending on the specified mode, XChangeSaveSet eitherinserts or deletes the specified window from the client’ssave-set. The specified window must have been created bysome other client, or a BadMatch error results.XChangeSaveSet can generate BadMatch, BadValue, andBadWindow errors.To add a window to the client’s save-set, use XAddToSaveSet.__│ XAddToSaveSet(display, w)Display *display;Window w;display Specifies the connection to the X server.w Specifies the window that you want to add to theclient’s save-set.│__ The XAddToSaveSet function adds the specified window to theclient’s save-set. The specified window must have beencreated by some other client, or a BadMatch error results.XAddToSaveSet can generate BadMatch and BadWindow errors.To remove a window from the client’s save-set, useXRemoveFromSaveSet.__│ XRemoveFromSaveSet(display, w)Display *display;Window w;display Specifies the connection to the X server.w Specifies the window that you want to delete fromthe client’s save-set.│__ The XRemoveFromSaveSet function removes the specified windowfrom the client’s save-set. The specified window must havebeen created by some other client, or a BadMatch errorresults.XRemoveFromSaveSet can generate BadMatch and BadWindowerrors.9.3. Managing Installed ColormapsThe X server maintains a list of installed colormaps.Windows using these colormaps are guaranteed to display withcorrect colors; windows using other colormaps may or may notdisplay with correct colors. Xlib provides functions thatyou can use to install a colormap, uninstall a colormap, andobtain a list of installed colormaps.At any time, there is a subset of the installed maps that isviewed as an ordered list and is called the required list.The length of the required list is at most M, where M is theminimum number of installed colormaps specified for thescreen in the connection setup. The required list ismaintained as follows. When a colormap is specified toXInstallColormap, it is added to the head of the list; thelist is truncated at the tail, if necessary, to keep itslength to at most M. When a colormap is specified toXUninstallColormap and it is in the required list, it isremoved from the list. A colormap is not added to therequired list when it is implicitly installed by the Xserver, and the X server cannot implicitly uninstall acolormap that is in the required list.To install a colormap, use XInstallColormap.__│ XInstallColormap(display, colormap)Display *display;Colormap colormap;display Specifies the connection to the X server.colormap Specifies the colormap.│__ The XInstallColormap function installs the specifiedcolormap for its associated screen. All windows associatedwith this colormap immediately display with true colors.You associated the windows with this colormap when youcreated them by calling XCreateWindow, XCreateSimpleWindow,XChangeWindowAttributes, or XSetWindowColormap.If the specified colormap is not already an installedcolormap, the X server generates a ColormapNotify event oneach window that has that colormap. In addition, for everyother colormap that is installed as a result of a call toXInstallColormap, the X server generates a ColormapNotifyevent on each window that has that colormap.XInstallColormap can generate a BadColor error.To uninstall a colormap, use XUninstallColormap.__│ XUninstallColormap(display, colormap)Display *display;Colormap colormap;display Specifies the connection to the X server.colormap Specifies the colormap.│__ The XUninstallColormap function removes the specifiedcolormap from the required list for its screen. As aresult, the specified colormap might be uninstalled, and theX server might implicitly install or uninstall additionalcolormaps. Which colormaps get installed or uninstalled isserver dependent except that the required list must remaininstalled.If the specified colormap becomes uninstalled, the X servergenerates a ColormapNotify event on each window that hasthat colormap. In addition, for every other colormap thatis installed or uninstalled as a result of a call toXUninstallColormap, the X server generates a ColormapNotifyevent on each window that has that colormap.XUninstallColormap can generate a BadColor error.To obtain a list of the currently installed colormaps for agiven screen, use XListInstalledColormaps.__│ Colormap *XListInstalledColormaps(display, w, num_return)Display *display;Window w;int *num_return;display Specifies the connection to the X server.w Specifies the window that determines the screen.num_returnReturns the number of currently installedcolormaps.│__ The XListInstalledColormaps function returns a list of thecurrently installed colormaps for the screen of thespecified window. The order of the colormaps in the list isnot significant and is no explicit indication of therequired list. When the allocated list is no longer needed,free it by using XFree.XListInstalledColormaps can generate a BadWindow error.9.4. Setting and Retrieving the Font Search PathThe set of fonts available from a server depends on a fontsearch path. Xlib provides functions to set and retrievethe search path for a server.To set the font search path, use XSetFontPath.__│ XSetFontPath(display, directories, ndirs)Display *display;char **directories;int ndirs;display Specifies the connection to the X server.directoriesSpecifies the directory path used to look for afont. Setting the path to the empty list restoresthe default path defined for the X server.ndirs Specifies the number of directories in the path.│__ The XSetFontPath function defines the directory search pathfor font lookup. There is only one search path per Xserver, not one per client. The encoding and interpretationof the strings are implementation-dependent, but typicallythey specify directories or font servers to be searched inthe order listed. An X server is permitted to cache fontinformation internally; for example, it might cache anentire font from a file and not check on subsequent opens ofthat font to see if the underlying font file has changed.However, when the font path is changed, the X server isguaranteed to flush all cached information about fonts forwhich there currently are no explicit resource IDsallocated. The meaning of an error from this request isimplementation-dependent.XSetFontPath can generate a BadValue error.To get the current font search path, use XGetFontPath.__│ char **XGetFontPath(display, npaths_return)Display *display;int *npaths_return;display Specifies the connection to the X server.npaths_returnReturns the number of strings in the font patharray.│__ The XGetFontPath function allocates and returns an array ofstrings containing the search path. The contents of thesestrings are implementation-dependent and are not intended tobe interpreted by client applications. When it is no longerneeded, the data in the font path should be freed by usingXFreeFontPath.To free data returned by XGetFontPath, use XFreeFontPath.__│ XFreeFontPath(list)char **list;list Specifies the array of strings you want to free.│__ The XFreeFontPath function frees the data allocated byXGetFontPath.9.5. Grabbing the ServerXlib provides functions that you can use to grab and ungrabthe server. These functions can be used to controlprocessing of output on other connections by the windowsystem server. While the server is grabbed, no processingof requests or close downs on any other connection willoccur. A client closing its connection automaticallyungrabs the server. Although grabbing the server is highlydiscouraged, it is sometimes necessary.To grab the server, use XGrabServer.__│ XGrabServer(display)Display *display;display Specifies the connection to the X server.│__ The XGrabServer function disables processing of requests andclose downs on all other connections than the one thisrequest arrived on. You should not grab the X server anymore than is absolutely necessary.To ungrab the server, use XUngrabServer.__│ XUngrabServer(display)Display *display;display Specifies the connection to the X server.│__ The XUngrabServer function restarts processing of requestsand close downs on other connections. You should avoidgrabbing the X server as much as possible.9.6. Killing ClientsXlib provides a function to cause the connection to a clientto be closed and its resources to be destroyed. To destroya client, use XKillClient.__│ XKillClient(display, resource)Display *display;XID resource;display Specifies the connection to the X server.resource Specifies any resource associated with the clientthat you want to destroy or AllTemporary.│__ The XKillClient function forces a close down of the clientthat created the resource if a valid resource is specified.If the client has already terminated in eitherRetainPermanent or RetainTemporary mode, all of the client’sresources are destroyed. If AllTemporary is specified, theresources of all clients that have terminated inRetainTemporary are destroyed (see section 2.5). Thispermits implementation of window manager facilities that aiddebugging. A client can set its close-down mode toRetainTemporary. If the client then crashes, its windowswould not be destroyed. The programmer can then inspect theapplication’s window tree and use the window manager todestroy the zombie windows.XKillClient can generate a BadValue error.9.7. Controlling the Screen SaverXlib provides functions that you can use to set or reset themode of the screen saver, to force or activate the screensaver, or to obtain the current screen saver values.To set the screen saver mode, use XSetScreenSaver.__│ XSetScreenSaver(display, timeout, interval, prefer_blanking, allow_exposures)Display *display;int timeout, interval;int prefer_blanking;int allow_exposures;display Specifies the connection to the X server.timeout Specifies the timeout, in seconds, until thescreen saver turns on.interval Specifies the interval, in seconds, between screensaver alterations.prefer_blankingSpecifies how to enable screen blanking. You canpass DontPreferBlanking, PreferBlanking, orDefaultBlanking.allow_exposuresSpecifies the screen save control values. You canpass DontAllowExposures, AllowExposures, orDefaultExposures.│__ Timeout and interval are specified in seconds. A timeout of0 disables the screen saver (but an activated screen saveris not deactivated), and a timeout of −1 restores thedefault. Other negative values generate a BadValue error.If the timeout value is nonzero, XSetScreenSaver enables thescreen saver. An interval of 0 disables the random-patternmotion. If no input from devices (keyboard, mouse, and soon) is generated for the specified number of timeout secondsonce the screen saver is enabled, the screen saver isactivated.For each screen, if blanking is preferred and the hardwaresupports video blanking, the screen simply goes blank.Otherwise, if either exposures are allowed or the screen canbe regenerated without sending Expose events to clients, thescreen is tiled with the root window background tilerandomly re-origined each interval seconds. Otherwise, thescreens’ state do not change, and the screen saver is notactivated. The screen saver is deactivated, and all screenstates are restored at the next keyboard or pointer input orat the next call to XForceScreenSaver with modeScreenSaverReset.If the server-dependent screen saver method supportsperiodic change, the interval argument serves as a hintabout how long the change period should be, and zero hintsthat no periodic change should be made. Examples of ways tochange the screen include scrambling the colormapperiodically, moving an icon image around the screenperiodically, or tiling the screen with the root windowbackground tile, randomly re-origined periodically.XSetScreenSaver can generate a BadValue error.To force the screen saver on or off, use XForceScreenSaver.__│ XForceScreenSaver(display, mode)Display *display;int mode;display Specifies the connection to the X server.mode Specifies the mode that is to be applied. You canpass ScreenSaverActive or ScreenSaverReset.│__ If the specified mode is ScreenSaverActive and the screensaver currently is deactivated, XForceScreenSaver activatesthe screen saver even if the screen saver had been disabledwith a timeout of zero. If the specified mode isScreenSaverReset and the screen saver currently is enabled,XForceScreenSaver deactivates the screen saver if it wasactivated, and the activation timer is reset to its initialstate (as if device input had been received).XForceScreenSaver can generate a BadValue error.To activate the screen saver, use XActivateScreenSaver.__│ XActivateScreenSaver(display)Display *display;display Specifies the connection to the X server.│__ To reset the screen saver, use XResetScreenSaver.__│ XResetScreenSaver(display)Display *display;display Specifies the connection to the X server.│__ To get the current screen saver values, use XGetScreenSaver.__│ XGetScreenSaver(display, timeout_return, interval_return, prefer_blanking_return,allow_exposures_return)Display *display;int *timeout_return, *interval_return;int *prefer_blanking_return;int *allow_exposures_return;display Specifies the connection to the X server.timeout_returnReturns the timeout, in seconds, until the screensaver turns on.interval_returnReturns the interval between screen saverinvocations.prefer_blanking_returnReturns the current screen blanking preference(DontPreferBlanking, PreferBlanking, orDefaultBlanking).allow_exposures_returnReturns the current screen save control value(DontAllowExposures, AllowExposures, orDefaultExposures).│__ 9.8. Controlling Host AccessThis section discusses how to:• Add, get, or remove hosts from the access control list• Change, enable, or disable accessX does not provide any protection on a per-window basis. Ifyou find out the resource ID of a resource, you canmanipulate it. To provide some minimal level of protection,however, connections are permitted only from machines youtrust. This is adequate on single-user workstations butobviously breaks down on timesharing machines. Althoughprovisions exist in the X protocol for proper connectionauthentication, the lack of a standard authentication serverleaves host-level access control as the only commonmechanism.The initial set of hosts allowed to open connectionstypically consists of:• The host the window system is running on.• On POSIX-conformant systems, each host listed in the/etc/X?.hosts file. The ? indicates the number of thedisplay. This file should consist of host namesseparated by newlines. DECnet nodes must terminate in:: to distinguish them from Internet hosts.If a host is not in the access control list when the accesscontrol mechanism is enabled and if the host attempts toestablish a connection, the server refuses the connection.To change the access list, the client must reside on thesame host as the server and/or must have been grantedpermission in the initial authorization at connection setup.Servers also can implement other access control policies inaddition to or in place of this host access facility. Forfurther information about other access controlimplementations, see ‘‘X Window System Protocol.’’9.8.1. Adding, Getting, or Removing HostsXlib provides functions that you can use to add, get, orremove hosts from the access control list. All the hostaccess control functions use the XHostAddress structure,which contains:__│ typedef struct {int family; /* for example FamilyInternet */int length; /* length of address, in bytes */char *address; /* pointer to where to find the address */} XHostAddress;│__ The family member specifies which protocol address family touse (for example, TCP/IP or DECnet) and can beFamilyInternet, FamilyInternet6, FamilyDECnet, orFamilyChaos. The length member specifies the length of theaddress in bytes. The address member specifies a pointer tothe address.For TCP/IP, the address should be in network byte order.For IP version 4 addresses, the family should beFamilyInternet and the length should be 4 bytes. For IPversion 6 addresses, the family should be FamilyInternet6and the length should be 16 bytes.For the DECnet family, the server performs no automaticswapping on the address bytes. A Phase IV address is 2bytes long. The first byte contains the least significant 8bits of the node number. The second byte contains the mostsignificant 2 bits of the node number in the leastsignificant 2 bits of the byte and the area in the mostsignificant 6 bits of the byte.To add a single host, use XAddHost.__│ XAddHost(display, host)Display *display;XHostAddress *host;display Specifies the connection to the X server.host Specifies the host that is to be added.│__ The XAddHost function adds the specified host to the accesscontrol list for that display. The server must be on thesame host as the client issuing the command, or a BadAccesserror results.XAddHost can generate BadAccess and BadValue errors.To add multiple hosts at one time, use XAddHosts.__│ XAddHosts(display, hosts, num_hosts)Display *display;XHostAddress *hosts;int num_hosts;display Specifies the connection to the X server.hosts Specifies each host that is to be added.num_hosts Specifies the number of hosts.│__ The XAddHosts function adds each specified host to theaccess control list for that display. The server must be onthe same host as the client issuing the command, or aBadAccess error results.XAddHosts can generate BadAccess and BadValue errors.To obtain a host list, use XListHosts.__│ XHostAddress *XListHosts(display, nhosts_return, state_return)Display *display;int *nhosts_return;Bool *state_return;display Specifies the connection to the X server.nhosts_returnReturns the number of hosts currently in theaccess control list.state_returnReturns the state of the access control.│__ The XListHosts function returns the current access controllist as well as whether the use of the list at connectionsetup was enabled or disabled. XListHosts allows a programto find out what machines can make connections. It alsoreturns a pointer to a list of host structures that wereallocated by the function. When no longer needed, thismemory should be freed by calling XFree.To remove a single host, use XRemoveHost.__│ XRemoveHost(display, host)Display *display;XHostAddress *host;display Specifies the connection to the X server.host Specifies the host that is to be removed.│__ The XRemoveHost function removes the specified host from theaccess control list for that display. The server must be onthe same host as the client process, or a BadAccess errorresults. If you remove your machine from the access list,you can no longer connect to that server, and this operationcannot be reversed unless you reset the server.XRemoveHost can generate BadAccess and BadValue errors.To remove multiple hosts at one time, use XRemoveHosts.__│ XRemoveHosts(display, hosts, num_hosts)Display *display;XHostAddress *hosts;int num_hosts;display Specifies the connection to the X server.hosts Specifies each host that is to be removed.num_hosts Specifies the number of hosts.│__ The XRemoveHosts function removes each specified host fromthe access control list for that display. The X server mustbe on the same host as the client process, or a BadAccesserror results. If you remove your machine from the accesslist, you can no longer connect to that server, and thisoperation cannot be reversed unless you reset the server.XRemoveHosts can generate BadAccess and BadValue errors.9.8.2. Changing, Enabling, or Disabling Access ControlXlib provides functions that you can use to enable, disable,or change access control.For these functions to execute successfully, the clientapplication must reside on the same host as the X serverand/or have been given permission in the initialauthorization at connection setup.To change access control, use XSetAccessControl.__│ XSetAccessControl(display, mode)Display *display;int mode;display Specifies the connection to the X server.mode Specifies the mode. You can pass EnableAccess orDisableAccess.│__ The XSetAccessControl function either enables or disablesthe use of the access control list at each connection setup.XSetAccessControl can generate BadAccess and BadValueerrors.To enable access control, use XEnableAccessControl.__│ XEnableAccessControl(display)Display *display;display Specifies the connection to the X server.│__ The XEnableAccessControl function enables the use of theaccess control list at each connection setup.XEnableAccessControl can generate a BadAccess error.To disable access control, use XDisableAccessControl.__│ XDisableAccessControl(display)Display *display;display Specifies the connection to the X server.│__ The XDisableAccessControl function disables the use of theaccess control list at each connection setup.XDisableAccessControl can generate a BadAccess error.9
10.1. Event TypesAn event is data generated asynchronously by the X server asa result of some device activity or as side effects of arequest sent by an Xlib function. Device-related eventspropagate from the source window to ancestor windows untilsome client application has selected that event type oruntil the event is explicitly discarded. The X servergenerally sends an event to a client application only if theclient has specifically asked to be informed of that eventtype, typically by setting the event-mask attribute of thewindow. The mask can also be set when you create a windowor by changing the window’s event-mask. You can also maskout events that would propagate to ancestor windows bymanipulating the do-not-propagate mask of the window’sattributes. However, MappingNotify events are always sentto all clients.An event type describes a specific event generated by the Xserver. For each event type, a corresponding constant nameis defined in <X11/X.h>, which is used when referring to anevent type. The following table lists the event categoryand its associated event type or types. The processingassociated with these events is discussed in section 10.5.10.2. Event StructuresFor each event type, a corresponding structure is declaredin <X11/Xlib.h>. All the event structures have thefollowing common members:__│ typedef struct {int type;unsigned long serial; /* # of last request processed by server */Bool send_event; /* true if this came from a SendEvent request */Display *display; /* Display the event was read from */Window window;} XAnyEvent;│__ The type member is set to the event type constant name thatuniquely identifies it. For example, when the X serverreports a GraphicsExpose event to a client application, itsends an XGraphicsExposeEvent structure with the type memberset to GraphicsExpose. The display member is set to apointer to the display the event was read on. Thesend_event member is set to True if the event came from aSendEvent protocol request. The serial member is set fromthe serial number reported in the protocol but expanded fromthe 16-bit least-significant bits to a full 32-bit value.The window member is set to the window that is most usefulto toolkit dispatchers.The X server can send events at any time in the inputstream. Xlib stores any events received while waiting for areply in an event queue for later use. Xlib also providesfunctions that allow you to check events in the event queue(see section 11.3).In addition to the individual structures declared for eachevent type, the XEvent structure is a union of theindividual structures declared for each event type.Depending on the type, you should access members of eachevent by using the XEvent union.__│ typedef union _XEvent {int type; /* must not be changed */XAnyEvent xany;XKeyEvent xkey;XButtonEvent xbutton;XMotionEvent xmotion;XCrossingEvent xcrossing;XFocusChangeEvent xfocus;XExposeEvent xexpose;XGraphicsExposeEvent xgraphicsexpose;XNoExposeEvent xnoexpose;XVisibilityEvent xvisibility;XCreateWindowEvent xcreatewindow;XDestroyWindowEvent xdestroywindow;XUnmapEvent xunmap;XMapEvent xmap;XMapRequestEvent xmaprequest;XReparentEvent xreparent;XConfigureEvent xconfigure;XGravityEvent xgravity;XResizeRequestEvent xresizerequest;XConfigureRequestEvent xconfigurerequest;XCirculateEvent xcirculate;XCirculateRequestEvent xcirculaterequest;XPropertyEvent xproperty;XSelectionClearEvent xselectionclear;XSelectionRequestEvent xselectionrequest;XSelectionEvent xselection;XColormapEvent xcolormap;XClientMessageEvent xclient;XMappingEvent xmapping;XErrorEvent xerror;XKeymapEvent xkeymap;long pad[24];} XEvent;│__ An XEvent structure’s first entry always is the type member,which is set to the event type. The second member always isthe serial number of the protocol request that generated theevent. The third member always is send_event, which is aBool that indicates if the event was sent by a differentclient. The fourth member always is a display, which is thedisplay that the event was read from. Except for keymapevents, the fifth member always is a window, which has beencarefully selected to be useful to toolkit dispatchers. Toavoid breaking toolkits, the order of these first fiveentries is not to change. Most events also contain a timemember, which is the time at which an event occurred. Inaddition, a pointer to the generic event must be cast beforeit is used to access any other information in the structure.10.3. Event MasksClients select event reporting of most events relative to awindow. To do this, pass an event mask to an Xlibevent-handling function that takes an event_mask argument.The bits of the event mask are defined in <X11/X.h>. Eachbit in the event mask maps to an event mask name, whichdescribes the event or events you want the X server toreturn to a client application.Unless the client has specifically asked for them, mostevents are not reported to clients when they are generated.Unless the client suppresses them by settinggraphics-exposures in the GC to False, GraphicsExpose andNoExpose are reported by default as a result of XCopyPlaneand XCopyArea. SelectionClear, SelectionRequest,SelectionNotify, or ClientMessage cannot be masked.Selection-related events are only sent to clientscooperating with selections (see section 4.5). When thekeyboard or pointer mapping is changed, MappingNotify isalways sent to clients.The following table lists the event mask constants you canpass to the event_mask argument and the circumstances inwhich you would want to specify the event mask:10.4. Event Processing OverviewThe event reported to a client application during eventprocessing depends on which event masks you provide as theevent-mask attribute for a window. For some event masks,there is a one-to-one correspondence between the event maskconstant and the event type constant. For example, if youpass the event mask ButtonPressMask, the X server sends backonly ButtonPress events. Most events contain a time member,which is the time at which an event occurred.In other cases, one event mask constant can map to severalevent type constants. For example, if you pass the eventmask SubstructureNotifyMask, the X server can send backCirculateNotify, ConfigureNotify, CreateNotify,DestroyNotify, GravityNotify, MapNotify, ReparentNotify, orUnmapNotify events.In another case, two event masks can map to one event type.For example, if you pass either PointerMotionMask orButtonMotionMask, the X server sends back a MotionNotifyevent.The following table lists the event mask, its associatedevent type or types, and the structure name associated withthe event type. Some of these structures actually aretypedefs to a generic structure that is shared between twoevent types. Note that N.A. appears in columns for whichthe information is not applicable.The sections that follow describe the processing that occurswhen you select the different event masks. The sections areorganized according to these processing categories:• Keyboard and pointer events• Window crossing events• Input focus events• Keymap state notification events• Exposure events• Window state notification events• Structure control events• Colormap state notification events• Client communication events10.5. Keyboard and Pointer EventsThis section discusses:• Pointer button events• Keyboard and pointer events10.5.1. Pointer Button EventsThe following describes the event processing that occurswhen a pointer button press is processed with the pointer insome window w and when no active pointer grab is inprogress.The X server searches the ancestors of w from the root down,looking for a passive grab to activate. If no matchingpassive grab on the button exists, the X serverautomatically starts an active grab for the client receivingthe event and sets the last-pointer-grab time to the currentserver time. The effect is essentially equivalent to anXGrabButton with these client passed arguments:The active grab is automatically terminated when the logicalstate of the pointer has all buttons released. Clients canmodify the active grab by calling XUngrabPointer andXChangeActivePointerGrab.10.5.2. Keyboard and Pointer EventsThis section discusses the processing that occurs for thekeyboard events KeyPress and KeyRelease and the pointerevents ButtonPress, ButtonRelease, and MotionNotify. Forinformation about the keyboard event-handling utilities, seechapter 11.The X server reports KeyPress or KeyRelease events toclients wanting information about keys that logically changestate. Note that these events are generated for all keys,even those mapped to modifier bits. The X server reportsButtonPress or ButtonRelease events to clients wantinginformation about buttons that logically change state.The X server reports MotionNotify events to clients wantinginformation about when the pointer logically moves. The Xserver generates this event whenever the pointer is movedand the pointer motion begins and ends in the window. Thegranularity of MotionNotify events is not guaranteed, but aclient that selects this event type is guaranteed to receiveat least one event when the pointer moves and then rests.The generation of the logical changes lags the physicalchanges if device event processing is frozen.To receive KeyPress, KeyRelease, ButtonPress, andButtonRelease events, set KeyPressMask, KeyReleaseMask,ButtonPressMask, and ButtonReleaseMask bits in theevent-mask attribute of the window.To receive MotionNotify events, set one or more of thefollowing event masks bits in the event-mask attribute ofthe window.• Button1MotionMask − Button5MotionMaskThe client application receives MotionNotify eventsonly when one or more of the specified buttons ispressed.• ButtonMotionMaskThe client application receives MotionNotify eventsonly when at least one button is pressed.• PointerMotionMaskThe client application receives MotionNotify eventsindependent of the state of the pointer buttons.• PointerMotionHintMaskIf PointerMotionHintMask is selected in combinationwith one or more of the above masks, the X server isfree to send only one MotionNotify event (with theis_hint member of the XPointerMovedEvent structure setto NotifyHint) to the client for the event window,until either the key or button state changes, thepointer leaves the event window, or the client callsXQueryPointer or XGetMotionEvents. The server stillmay send MotionNotify events without is_hint set toNotifyHint.The source of the event is the viewable window that thepointer is in. The window used by the X server to reportthese events depends on the window’s position in the windowhierarchy and whether any intervening window prohibits thegeneration of these events. Starting with the sourcewindow, the X server searches up the window hierarchy untilit locates the first window specified by a client as havingan interest in these events. If one of the interveningwindows has its do-not-propagate-mask set to prohibitgeneration of the event type, the events of those types willbe suppressed. Clients can modify the actual window usedfor reporting by performing active grabs and, in the case ofkeyboard events, by using the focus window.The structures for these event types contain:__│ typedef struct {int type; /* ButtonPress or ButtonRelease */unsigned long serial; /* # of last request processed by server */Bool send_event; /* true if this came from a SendEvent request */Display *display; /* Display the event was read from */Window window; /* ‘‘event’’ window it is reported relative to */Window root; /* root window that the event occurred on */Window subwindow; /* child window */Time time; /* milliseconds */int x, y; /* pointer x, y coordinates in event window */int x_root, y_root; /* coordinates relative to root */unsigned int state; /* key or button mask */unsigned int button; /* detail */Bool same_screen; /* same screen flag */} XButtonEvent;typedef XButtonEvent XButtonPressedEvent;typedef XButtonEvent XButtonReleasedEvent;typedef struct {int type; /* KeyPress or KeyRelease */unsigned long serial; /* # of last request processed by server */Bool send_event; /* true if this came from a SendEvent request */Display *display; /* Display the event was read from */Window window; /* ‘‘event’’ window it is reported relative to */Window root; /* root window that the event occurred on */Window subwindow; /* child window */Time time; /* milliseconds */int x, y; /* pointer x, y coordinates in event window */int x_root, y_root; /* coordinates relative to root */unsigned int state; /* key or button mask */unsigned int keycode; /* detail */Bool same_screen; /* same screen flag */} XKeyEvent;typedef XKeyEvent XKeyPressedEvent;typedef XKeyEvent XKeyReleasedEvent;typedef struct {int type; /* MotionNotify */unsigned long serial; /* # of last request processed by server */Bool send_event; /* true if this came from a SendEvent request */Display *display; /* Display the event was read from */Window window; /* ‘‘event’’ window reported relative to */Window root; /* root window that the event occurred on */Window subwindow; /* child window */Time time; /* milliseconds */int x, y; /* pointer x, y coordinates in event window */int x_root, y_root; /* coordinates relative to root */unsigned int state; /* key or button mask */char is_hint; /* detail */Bool same_screen; /* same screen flag */} XMotionEvent;typedef XMotionEvent XPointerMovedEvent;│__ These structures have the following common members: window,root, subwindow, time, x, y, x_root, y_root, state, andsame_screen. The window member is set to the window onwhich the event was generated and is referred to as theevent window. As long as the conditions previouslydiscussed are met, this is the window used by the X serverto report the event. The root member is set to the sourcewindow’s root window. The x_root and y_root members are setto the pointer’s coordinates relative to the root window’sorigin at the time of the event.The same_screen member is set to indicate whether the eventwindow is on the same screen as the root window and can beeither True or False. If True, the event and root windowsare on the same screen. If False, the event and rootwindows are not on the same screen.If the source window is an inferior of the event window, thesubwindow member of the structure is set to the child of theevent window that is the source window or the child of theevent window that is an ancestor of the source window.Otherwise, the X server sets the subwindow member to None.The time member is set to the time when the event wasgenerated and is expressed in milliseconds.If the event window is on the same screen as the rootwindow, the x and y members are set to the coordinatesrelative to the event window’s origin. Otherwise, thesemembers are set to zero.The state member is set to indicate the logical state of thepointer buttons and modifier keys just prior to the event,which is the bitwise inclusive OR of one or more of thebutton or modifier key masks: Button1Mask, Button2Mask,Button3Mask, Button4Mask, Button5Mask, ShiftMask, LockMask,ControlMask, Mod1Mask, Mod2Mask, Mod3Mask, Mod4Mask, andMod5Mask.Each of these structures also has a member that indicatesthe detail. For the XKeyPressedEvent and XKeyReleasedEventstructures, this member is called a keycode. It is set to anumber that represents a physical key on the keyboard. Thekeycode is an arbitrary representation for any key on thekeyboard (see sections 12.7 and 16.1).For the XButtonPressedEvent and XButtonReleasedEventstructures, this member is called button. It represents thepointer button that changed state and can be the Button1,Button2, Button3, Button4, or Button5 value. For theXPointerMovedEvent structure, this member is called is_hint.It can be set to NotifyNormal or NotifyHint.Some of the symbols mentioned in this section have fixedvalues, as follows:10.6. Window Entry/Exit EventsThis section describes the processing that occurs for thewindow crossing events EnterNotify and LeaveNotify. If apointer motion or a window hierarchy change causes thepointer to be in a different window than before, the Xserver reports EnterNotify or LeaveNotify events to clientswho have selected for these events. All EnterNotify andLeaveNotify events caused by a hierarchy change aregenerated after any hierarchy event (UnmapNotify, MapNotify,ConfigureNotify, GravityNotify, CirculateNotify) caused bythat change; however, the X protocol does not constrain theordering of EnterNotify and LeaveNotify events with respectto FocusOut, VisibilityNotify, and Expose events.This contrasts with MotionNotify events, which are alsogenerated when the pointer moves but only when the pointermotion begins and ends in a single window. An EnterNotifyor LeaveNotify event also can be generated when some clientapplication calls XGrabPointer and XUngrabPointer.To receive EnterNotify or LeaveNotify events, set theEnterWindowMask or LeaveWindowMask bits of the event-maskattribute of the window.The structure for these event types contains:__│ typedef struct {int type; /* EnterNotify or LeaveNotify */unsigned long serial; /* # of last request processed by server */Bool send_event; /* true if this came from a SendEvent request */Display *display; /* Display the event was read from */Window window; /* ‘‘event’’ window reported relative to */Window root; /* root window that the event occurred on */Window subwindow; /* child window */Time time; /* milliseconds */int x, y; /* pointer x, y coordinates in event window */int x_root, y_root; /* coordinates relative to root */int mode; /* NotifyNormal, NotifyGrab, NotifyUngrab */int detail; /** NotifyAncestor, NotifyVirtual, NotifyInferior,* NotifyNonlinear,NotifyNonlinearVirtual*/Bool same_screen; /* same screen flag */Bool focus; /* boolean focus */unsigned int state; /* key or button mask */} XCrossingEvent;typedef XCrossingEvent XEnterWindowEvent;typedef XCrossingEvent XLeaveWindowEvent;│__ The window member is set to the window on which theEnterNotify or LeaveNotify event was generated and isreferred to as the event window. This is the window used bythe X server to report the event, and is relative to theroot window on which the event occurred. The root member isset to the root window of the screen on which the eventoccurred.For a LeaveNotify event, if a child of the event windowcontains the initial position of the pointer, the subwindowcomponent is set to that child. Otherwise, the X serversets the subwindow member to None. For an EnterNotifyevent, if a child of the event window contains the finalpointer position, the subwindow component is set to thatchild or None.The time member is set to the time when the event wasgenerated and is expressed in milliseconds. The x and ymembers are set to the coordinates of the pointer positionin the event window. This position is always the pointer’sfinal position, not its initial position. If the eventwindow is on the same screen as the root window, x and y arethe pointer coordinates relative to the event window’sorigin. Otherwise, x and y are set to zero. The x_root andy_root members are set to the pointer’s coordinates relativeto the root window’s origin at the time of the event.The same_screen member is set to indicate whether the eventwindow is on the same screen as the root window and can beeither True or False. If True, the event and root windowsare on the same screen. If False, the event and rootwindows are not on the same screen.The focus member is set to indicate whether the event windowis the focus window or an inferior of the focus window. TheX server can set this member to either True or False. IfTrue, the event window is the focus window or an inferior ofthe focus window. If False, the event window is not thefocus window or an inferior of the focus window.The state member is set to indicate the state of the pointerbuttons and modifier keys just prior to the event. The Xserver can set this member to the bitwise inclusive OR ofone or more of the button or modifier key masks:Button1Mask, Button2Mask, Button3Mask, Button4Mask,Button5Mask, ShiftMask, LockMask, ControlMask, Mod1Mask,Mod2Mask, Mod3Mask, Mod4Mask, Mod5Mask.The mode member is set to indicate whether the events arenormal events, pseudo-motion events when a grab activates,or pseudo-motion events when a grab deactivates. The Xserver can set this member to NotifyNormal, NotifyGrab, orNotifyUngrab.The detail member is set to indicate the notify detail andcan be NotifyAncestor, NotifyVirtual, NotifyInferior,NotifyNonlinear, or NotifyNonlinearVirtual.10.6.1. Normal Entry/Exit EventsEnterNotify and LeaveNotify events are generated when thepointer moves from one window to another window. Normalevents are identified by XEnterWindowEvent orXLeaveWindowEvent structures whose mode member is set toNotifyNormal.• When the pointer moves from window A to window B and Ais an inferior of B, the X server does the following:− It generates a LeaveNotify event on window A, withthe detail member of the XLeaveWindowEventstructure set to NotifyAncestor.− It generates a LeaveNotify event on each windowbetween window A and window B, exclusive, with thedetail member of each XLeaveWindowEvent structureset to NotifyVirtual.− It generates an EnterNotify event on window B,with the detail member of the XEnterWindowEventstructure set to NotifyInferior.• When the pointer moves from window A to window B and Bis an inferior of A, the X server does the following:− It generates a LeaveNotify event on window A, withthe detail member of the XLeaveWindowEventstructure set to NotifyInferior.− It generates an EnterNotify event on each windowbetween window A and window B, exclusive, with thedetail member of each XEnterWindowEvent structureset to NotifyVirtual.− It generates an EnterNotify event on window B,with the detail member of the XEnterWindowEventstructure set to NotifyAncestor.• When the pointer moves from window A to window B andwindow C is their least common ancestor, the X serverdoes the following:− It generates a LeaveNotify event on window A, withthe detail member of the XLeaveWindowEventstructure set to NotifyNonlinear.− It generates a LeaveNotify event on each windowbetween window A and window C, exclusive, with thedetail member of each XLeaveWindowEvent structureset to NotifyNonlinearVirtual.− It generates an EnterNotify event on each windowbetween window C and window B, exclusive, with thedetail member of each XEnterWindowEvent structureset to NotifyNonlinearVirtual.− It generates an EnterNotify event on window B,with the detail member of the XEnterWindowEventstructure set to NotifyNonlinear.• When the pointer moves from window A to window B ondifferent screens, the X server does the following:− It generates a LeaveNotify event on window A, withthe detail member of the XLeaveWindowEventstructure set to NotifyNonlinear.− If window A is not a root window, it generates aLeaveNotify event on each window above window A upto and including its root, with the detail memberof each XLeaveWindowEvent structure set toNotifyNonlinearVirtual.− If window B is not a root window, it generates anEnterNotify event on each window from window B’sroot down to but not including window B, with thedetail member of each XEnterWindowEvent structureset to NotifyNonlinearVirtual.− It generates an EnterNotify event on window B,with the detail member of the XEnterWindowEventstructure set to NotifyNonlinear.10.6.2. Grab and Ungrab Entry/Exit EventsPseudo-motion mode EnterNotify and LeaveNotify events aregenerated when a pointer grab activates or deactivates.Events in which the pointer grab activates are identified byXEnterWindowEvent or XLeaveWindowEvent structures whose modemember is set to NotifyGrab. Events in which the pointergrab deactivates are identified by XEnterWindowEvent orXLeaveWindowEvent structures whose mode member is set toNotifyUngrab (see XGrabPointer).• When a pointer grab activates after any initial warpinto a confine_to window and before generating anyactual ButtonPress event that activates the grab, G isthe grab_window for the grab, and P is the window thepointer is in, the X server does the following:− It generates EnterNotify and LeaveNotify events(see section 10.6.1) with the mode members of theXEnterWindowEvent and XLeaveWindowEvent structuresset to NotifyGrab. These events are generated asif the pointer were to suddenly warp from itscurrent position in P to some position in G.However, the pointer does not warp, and the Xserver uses the pointer position as both theinitial and final positions for the events.• When a pointer grab deactivates after generating anyactual ButtonRelease event that deactivates the grab, Gis the grab_window for the grab, and P is the windowthe pointer is in, the X server does the following:− It generates EnterNotify and LeaveNotify events(see section 10.6.1) with the mode members of theXEnterWindowEvent and XLeaveWindowEvent structuresset to NotifyUngrab. These events are generatedas if the pointer were to suddenly warp from someposition in G to its current position in P.However, the pointer does not warp, and the Xserver uses the current pointer position as boththe initial and final positions for the events.10.7. Input Focus EventsThis section describes the processing that occurs for theinput focus events FocusIn and FocusOut. The X server canreport FocusIn or FocusOut events to clients wantinginformation about when the input focus changes. Thekeyboard is always attached to some window (typically, theroot window or a top-level window), which is called thefocus window. The focus window and the position of thepointer determine the window that receives keyboard input.Clients may need to know when the input focus changes tocontrol highlighting of areas on the screen.To receive FocusIn or FocusOut events, set theFocusChangeMask bit in the event-mask attribute of thewindow.The structure for these event types contains:__│ typedef struct {int type; /* FocusIn or FocusOut */unsigned long serial; /* # of last request processed by server */Bool send_event; /* true if this came from a SendEvent request */Display *display; /* Display the event was read from */Window window; /* window of event */int mode; /* NotifyNormal, NotifyGrab, NotifyUngrab */int detail; /** NotifyAncestor, NotifyVirtual, NotifyInferior,* NotifyNonlinear,NotifyNonlinearVirtual, NotifyPointer,* NotifyPointerRoot, NotifyDetailNone*/} XFocusChangeEvent;typedef XFocusChangeEvent XFocusInEvent;typedef XFocusChangeEvent XFocusOutEvent;│__ The window member is set to the window on which the FocusInor FocusOut event was generated. This is the window used bythe X server to report the event. The mode member is set toindicate whether the focus events are normal focus events,focus events while grabbed, focus events when a grabactivates, or focus events when a grab deactivates. The Xserver can set the mode member to NotifyNormal,NotifyWhileGrabbed, NotifyGrab, or NotifyUngrab.All FocusOut events caused by a window unmap are generatedafter any UnmapNotify event; however, the X protocol doesnot constrain the ordering of FocusOut events with respectto generated EnterNotify, LeaveNotify, VisibilityNotify, andExpose events.Depending on the event mode, the detail member is set toindicate the notify detail and can be NotifyAncestor,NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual, NotifyPointer, NotifyPointerRoot, orNotifyDetailNone.10.7.1. Normal Focus Events and Focus Events While GrabbedNormal focus events are identified by XFocusInEvent orXFocusOutEvent structures whose mode member is set toNotifyNormal. Focus events while grabbed are identified byXFocusInEvent or XFocusOutEvent structures whose mode memberis set to NotifyWhileGrabbed. The X server processes normalfocus and focus events while grabbed according to thefollowing:• When the focus moves from window A to window B, A is aninferior of B, and the pointer is in window P, the Xserver does the following:− It generates a FocusOut event on window A, withthe detail member of the XFocusOutEvent structureset to NotifyAncestor.− It generates a FocusOut event on each windowbetween window A and window B, exclusive, with thedetail member of each XFocusOutEvent structure setto NotifyVirtual.− It generates a FocusIn event on window B, with thedetail member of the XFocusOutEvent structure setto NotifyInferior.− If window P is an inferior of window B but windowP is not window A or an inferior or ancestor ofwindow A, it generates a FocusIn event on eachwindow below window B, down to and includingwindow P, with the detail member of eachXFocusInEvent structure set to NotifyPointer.• When the focus moves from window A to window B, B is aninferior of A, and the pointer is in window P, the Xserver does the following:− If window P is an inferior of window A but P isnot an inferior of window B or an ancestor of B,it generates a FocusOut event on each window fromwindow P up to but not including window A, withthe detail member of each XFocusOutEvent structureset to NotifyPointer.− It generates a FocusOut event on window A, withthe detail member of the XFocusOutEvent structureset to NotifyInferior.− It generates a FocusIn event on each windowbetween window A and window B, exclusive, with thedetail member of each XFocusInEvent structure setto NotifyVirtual.− It generates a FocusIn event on window B, with thedetail member of the XFocusInEvent structure setto NotifyAncestor.• When the focus moves from window A to window B, windowC is their least common ancestor, and the pointer is inwindow P, the X server does the following:− If window P is an inferior of window A, itgenerates a FocusOut event on each window fromwindow P up to but not including window A, withthe detail member of the XFocusOutEvent structureset to NotifyPointer.− It generates a FocusOut event on window A, withthe detail member of the XFocusOutEvent structureset to NotifyNonlinear.− It generates a FocusOut event on each windowbetween window A and window C, exclusive, with thedetail member of each XFocusOutEvent structure setto NotifyNonlinearVirtual.− It generates a FocusIn event on each windowbetween C and B, exclusive, with the detail memberof each XFocusInEvent structure set toNotifyNonlinearVirtual.− It generates a FocusIn event on window B, with thedetail member of the XFocusInEvent structure setto NotifyNonlinear.− If window P is an inferior of window B, itgenerates a FocusIn event on each window belowwindow B down to and including window P, with thedetail member of the XFocusInEvent structure setto NotifyPointer.• When the focus moves from window A to window B ondifferent screens and the pointer is in window P, the Xserver does the following:− If window P is an inferior of window A, itgenerates a FocusOut event on each window fromwindow P up to but not including window A, withthe detail member of each XFocusOutEvent structureset to NotifyPointer.− It generates a FocusOut event on window A, withthe detail member of the XFocusOutEvent structureset to NotifyNonlinear.− If window A is not a root window, it generates aFocusOut event on each window above window A up toand including its root, with the detail member ofeach XFocusOutEvent structure set toNotifyNonlinearVirtual.− If window B is not a root window, it generates aFocusIn event on each window from window B’s rootdown to but not including window B, with thedetail member of each XFocusInEvent structure setto NotifyNonlinearVirtual.− It generates a FocusIn event on window B, with thedetail member of each XFocusInEvent structure setto NotifyNonlinear.− If window P is an inferior of window B, itgenerates a FocusIn event on each window belowwindow B down to and including window P, with thedetail member of each XFocusInEvent structure setto NotifyPointer.• When the focus moves from window A to PointerRoot(events sent to the window under the pointer) or None(discard), and the pointer is in window P, the X serverdoes the following:− If window P is an inferior of window A, itgenerates a FocusOut event on each window fromwindow P up to but not including window A, withthe detail member of each XFocusOutEvent structureset to NotifyPointer.− It generates a FocusOut event on window A, withthe detail member of the XFocusOutEvent structureset to NotifyNonlinear.− If window A is not a root window, it generates aFocusOut event on each window above window A up toand including its root, with the detail member ofeach XFocusOutEvent structure set toNotifyNonlinearVirtual.− It generates a FocusIn event on the root window ofall screens, with the detail member of eachXFocusInEvent structure set to NotifyPointerRoot(or NotifyDetailNone).− If the new focus is PointerRoot, it generates aFocusIn event on each window from window P’s rootdown to and including window P, with the detailmember of each XFocusInEvent structure set toNotifyPointer.• When the focus moves from PointerRoot (events sent tothe window under the pointer) or None to window A, andthe pointer is in window P, the X server does thefollowing:− If the old focus is PointerRoot, it generates aFocusOut event on each window from window P up toand including window P’s root, with the detailmember of each XFocusOutEvent structure set toNotifyPointer.− It generates a FocusOut event on all root windows,with the detail member of each XFocusOutEventstructure set to NotifyPointerRoot (orNotifyDetailNone).− If window A is not a root window, it generates aFocusIn event on each window from window A’s rootdown to but not including window A, with thedetail member of each XFocusInEvent structure setto NotifyNonlinearVirtual.− It generates a FocusIn event on window A, with thedetail member of the XFocusInEvent structure setto NotifyNonlinear.− If window P is an inferior of window A, itgenerates a FocusIn event on each window belowwindow A down to and including window P, with thedetail member of each XFocusInEvent structure setto NotifyPointer.• When the focus moves from PointerRoot (events sent tothe window under the pointer) to None (or vice versa),and the pointer is in window P, the X server does thefollowing:− If the old focus is PointerRoot, it generates aFocusOut event on each window from window P up toand including window P’s root, with the detailmember of each XFocusOutEvent structure set toNotifyPointer.− It generates a FocusOut event on all root windows,with the detail member of each XFocusOutEventstructure set to either NotifyPointerRoot orNotifyDetailNone.− It generates a FocusIn event on all root windows,with the detail member of each XFocusInEventstructure set to NotifyDetailNone orNotifyPointerRoot.− If the new focus is PointerRoot, it generates aFocusIn event on each window from window P’s rootdown to and including window P, with the detailmember of each XFocusInEvent structure set toNotifyPointer.10.7.2. Focus Events Generated by GrabsFocus events in which the keyboard grab activates areidentified by XFocusInEvent or XFocusOutEvent structureswhose mode member is set to NotifyGrab. Focus events inwhich the keyboard grab deactivates are identified byXFocusInEvent or XFocusOutEvent structures whose mode memberis set to NotifyUngrab (see XGrabKeyboard).• When a keyboard grab activates before generating anyactual KeyPress event that activates the grab, G is thegrab_window, and F is the current focus, the X serverdoes the following:− It generates FocusIn and FocusOut events, with themode members of the XFocusInEvent andXFocusOutEvent structures set to NotifyGrab.These events are generated as if the focus were tochange from F to G.• When a keyboard grab deactivates after generating anyactual KeyRelease event that deactivates the grab, G isthe grab_window, and F is the current focus, the Xserver does the following:− It generates FocusIn and FocusOut events, with themode members of the XFocusInEvent andXFocusOutEvent structures set to NotifyUngrab.These events are generated as if the focus were tochange from G to F.10.8. Key Map State Notification EventsThe X server can report KeymapNotify events to clients thatwant information about changes in their keyboard state.To receive KeymapNotify events, set the KeymapStateMask bitin the event-mask attribute of the window. The X servergenerates this event immediately after every EnterNotify andFocusIn event.The structure for this event type contains:__│ /* generated on EnterWindow and FocusIn when KeymapState selected */typedef struct {int type; /* KeymapNotify */unsigned long serial; /* # of last request processed by server */Bool send_event; /* true if this came from a SendEvent request */Display *display; /* Display the event was read from */Window window;char key_vector[32];} XKeymapEvent;│__ The window member is not used but is present to aid sometoolkits. The key_vector member is set to the bit vector ofthe keyboard. Each bit set to 1 indicates that thecorresponding key is currently pressed. The vector isrepresented as 32 bytes. Byte N (from 0) contains the bitsfor keys 8N to 8N + 7 with the least significant bit in thebyte representing key 8N.10.9. Exposure EventsThe X protocol does not guarantee to preserve the contentsof window regions when the windows are obscured orreconfigured. Some implementations may preserve thecontents of windows. Other implementations are free todestroy the contents of windows when exposed. X expectsclient applications to assume the responsibility forrestoring the contents of an exposed window region. (Anexposed window region describes a formerly obscured windowwhose region becomes visible.) Therefore, the X serversends Expose events describing the window and the region ofthe window that has been exposed. A naive clientapplication usually redraws the entire window. A moresophisticated client application redraws only the exposedregion.10.9.1. Expose EventsThe X server can report Expose events to clients wantinginformation about when the contents of window regions havebeen lost. The circumstances in which the X servergenerates Expose events are not as definite as those forother events. However, the X server never generates Exposeevents on windows whose class you specified as InputOnly.The X server can generate Expose events when no validcontents are available for regions of a window and eitherthe regions are visible, the regions are viewable and theserver is (perhaps newly) maintaining backing store on thewindow, or the window is not viewable but the server is(perhaps newly) honoring the window’s backing-storeattribute of Always or WhenMapped. The regions decomposeinto an (arbitrary) set of rectangles, and an Expose eventis generated for each rectangle. For any given window, theX server guarantees to report contiguously all of theregions exposed by some action that causes Expose events,such as raising a window.To receive Expose events, set the ExposureMask bit in theevent-mask attribute of the window.The structure for this event type contains:__│ typedef struct {int type; /* Expose */unsigned long serial; /* # of last request processed by server */Bool send_event; /* true if this came from a SendEvent request */Display *display; /* Display the event was read from */Window window;int x, y;int width, height;int count; /* if nonzero, at least this many more */} XExposeEvent;│__ The window member is set to the exposed (damaged) window.The x and y members are set to the coordinates relative tothe window’s origin and indicate the upper-left corner ofthe rectangle. The width and height members are set to thesize (extent) of the rectangle. The count member is set tothe number of Expose events that are to follow. If count iszero, no more Expose events follow for this window.However, if count is nonzero, at least that number of Exposeevents (and possibly more) follow for this window. Simpleapplications that do not want to optimize redisplay bydistinguishing between subareas of its window can justignore all Expose events with nonzero counts and performfull redisplays on events with zero counts.10.9.2. GraphicsExpose and NoExpose EventsThe X server can report GraphicsExpose events to clientswanting information about when a destination region couldnot be computed during certain graphics requests: XCopyAreaor XCopyPlane. The X server generates this event whenever adestination region could not be computed because of anobscured or out-of-bounds source region. In addition, the Xserver guarantees to report contiguously all of the regionsexposed by some graphics request (for example, copying anarea of a drawable to a destination drawable).The X server generates a NoExpose event whenever a graphicsrequest that might produce a GraphicsExpose event does notproduce any. In other words, the client is really askingfor a GraphicsExpose event but instead receives a NoExposeevent.To receive GraphicsExpose or NoExpose events, you must firstset the graphics-exposure attribute of the graphics contextto True. You also can set the graphics-expose attributewhen creating a graphics context using XCreateGC or bycalling XSetGraphicsExposures.The structures for these event types contain:__│ typedef struct {int type; /* GraphicsExpose */unsigned long serial; /* # of last request processed by server */Bool send_event; /* true if this came from a SendEvent request */Display *display; /* Display the event was read from */Drawable drawable;int x, y;int width, height;int count; /* if nonzero, at least this many more */int major_code; /* core is CopyArea or CopyPlane */int minor_code; /* not defined in the core */} XGraphicsExposeEvent;typedef struct {int type; /* NoExpose */unsigned long serial; /* # of last request processed by server */Bool send_event; /* true if this came from a SendEvent request */Display *display; /* Display the event was read from */Drawable drawable;int major_code; /* core is CopyArea or CopyPlane */int minor_code; /* not defined in the core */} XNoExposeEvent;│__ Both structures have these common members: drawable,major_code, and minor_code. The drawable member is set tothe drawable of the destination region on which the graphicsrequest was to be performed. The major_code member is setto the graphics request initiated by the client and can beeither X_CopyArea or X_CopyPlane. If it is X_CopyArea, acall to XCopyArea initiated the request. If it isX_CopyPlane, a call to XCopyPlane initiated the request.These constants are defined in <X11/Xproto.h>. Theminor_code member, like the major_code member, indicateswhich graphics request was initiated by the client.However, the minor_code member is not defined by the core Xprotocol and will be zero in these cases, although it may beused by an extension.The XGraphicsExposeEvent structure has these additionalmembers: x, y, width, height, and count. The x and ymembers are set to the coordinates relative to thedrawable’s origin and indicate the upper-left corner of therectangle. The width and height members are set to the size(extent) of the rectangle. The count member is set to thenumber of GraphicsExpose events to follow. If count iszero, no more GraphicsExpose events follow for this window.However, if count is nonzero, at least that number ofGraphicsExpose events (and possibly more) are to follow forthis window.10.10. Window State Change EventsThe following sections discuss:• CirculateNotify events• ConfigureNotify events• CreateNotify events• DestroyNotify events• GravityNotify events• MapNotify events• MappingNotify events• ReparentNotify events• UnmapNotify events• VisibilityNotify events10.10.1. CirculateNotify EventsThe X server can report CirculateNotify events to clientswanting information about when a window changes its positionin the stack. The X server generates this event typewhenever a window is actually restacked as a result of aclient application calling XCirculateSubwindows,XCirculateSubwindowsUp, or XCirculateSubwindowsDown.To receive CirculateNotify events, set theStructureNotifyMask bit in the event-mask attribute of thewindow or the SubstructureNotifyMask bit in the event-maskattribute of the parent window (in which case, circulatingany child generates an event).The structure for this event type contains:__│ typedef struct {int type; /* CirculateNotify */unsigned long serial; /* # of last request processed by server */Bool send_event; /* true if this came from a SendEvent request */Display *display; /* Display the event was read from */Window event;Window window;int place; /* PlaceOnTop, PlaceOnBottom */} XCirculateEvent;│__ The event member is set either to the restacked window or toits parent, depending on whether StructureNotify orSubstructureNotify was selected. The window member is setto the window that was restacked. The place member is setto the window’s position after the restack occurs and iseither PlaceOnTop or PlaceOnBottom. If it is PlaceOnTop,the window is now on top of all siblings. If it isPlaceOnBottom, the window is now below all siblings.10.10.2. ConfigureNotify EventsThe X server can report ConfigureNotify events to clientswanting information about actual changes to a window’sstate, such as size, position, border, and stacking order.The X server generates this event type whenever one of thefollowing configure window requests made by a clientapplication actually completes:• A window’s size, position, border, and/or stackingorder is reconfigured by calling XConfigureWindow.• The window’s position in the stacking order is changedby calling XLowerWindow, XRaiseWindow, orXRestackWindows.• A window is moved by calling XMoveWindow.• A window’s size is changed by calling XResizeWindow.• A window’s size and location is changed by callingXMoveResizeWindow.• A window is mapped and its position in the stackingorder is changed by calling XMapRaised.• A window’s border width is changed by callingXSetWindowBorderWidth.To receive ConfigureNotify events, set theStructureNotifyMask bit in the event-mask attribute of thewindow or the SubstructureNotifyMask bit in the event-maskattribute of the parent window (in which case, configuringany child generates an event).The structure for this event type contains:__│ typedef struct {int type; /* ConfigureNotify */unsigned long serial; /* # of last request processed by server */Bool send_event; /* true if this came from a SendEvent request */Display *display; /* Display the event was read from */Window event;Window window;int x, y;int width, height;int border_width;Window above;Bool override_redirect;} XConfigureEvent;│__ The event member is set either to the reconfigured window orto its parent, depending on whether StructureNotify orSubstructureNotify was selected. The window member is setto the window whose size, position, border, and/or stackingorder was changed.The x and y members are set to the coordinates relative tothe parent window’s origin and indicate the position of theupper-left outside corner of the window. The width andheight members are set to the inside size of the window, notincluding the border. The border_width member is set to thewidth of the window’s border, in pixels.The above member is set to the sibling window and is usedfor stacking operations. If the X server sets this memberto None, the window whose state was changed is on the bottomof the stack with respect to sibling windows. However, ifthis member is set to a sibling window, the window whosestate was changed is placed on top of this sibling window.The override_redirect member is set to the override-redirectattribute of the window. Window manager clients normallyshould ignore this window if the override_redirect member isTrue.10.10.3. CreateNotify EventsThe X server can report CreateNotify events to clientswanting information about creation of windows. The X servergenerates this event whenever a client application creates awindow by calling XCreateWindow or XCreateSimpleWindow.To receive CreateNotify events, set theSubstructureNotifyMask bit in the event-mask attribute ofthe window. Creating any children then generates an event.The structure for the event type contains:__│ typedef struct {int type; /* CreateNotify */unsigned long serial; /* # of last request processed by server */Bool send_event; /* true if this came from a SendEvent request */Display *display; /* Display the event was read from */Window parent; /* parent of the window */Window window; /* window id of window created */int x, y; /* window location */int width, height; /* size of window */int border_width; /* border width */Bool override_redirect; /* creation should be overridden */} XCreateWindowEvent;│__ The parent member is set to the created window’s parent.The window member specifies the created window. The x and ymembers are set to the created window’s coordinates relativeto the parent window’s origin and indicate the position ofthe upper-left outside corner of the created window. Thewidth and height members are set to the inside size of thecreated window (not including the border) and are alwaysnonzero. The border_width member is set to the width of thecreated window’s border, in pixels. The override_redirectmember is set to the override-redirect attribute of thewindow. Window manager clients normally should ignore thiswindow if the override_redirect member is True.10.10.4. DestroyNotify EventsThe X server can report DestroyNotify events to clientswanting information about which windows are destroyed. TheX server generates this event whenever a client applicationdestroys a window by calling XDestroyWindow orXDestroySubwindows.The ordering of the DestroyNotify events is such that forany given window, DestroyNotify is generated on allinferiors of the window before being generated on the windowitself. The X protocol does not constrain the orderingamong siblings and across subhierarchies.To receive DestroyNotify events, set the StructureNotifyMaskbit in the event-mask attribute of the window or theSubstructureNotifyMask bit in the event-mask attribute ofthe parent window (in which case, destroying any childgenerates an event).The structure for this event type contains:__│ typedef struct {int type; /* DestroyNotify */unsigned long serial; /* # of last request processed by server */Bool send_event; /* true if this came from a SendEvent request */Display *display; /* Display the event was read from */Window event;Window window;} XDestroyWindowEvent;│__ The event member is set either to the destroyed window or toits parent, depending on whether StructureNotify orSubstructureNotify was selected. The window member is setto the window that is destroyed.10.10.5. GravityNotify EventsThe X server can report GravityNotify events to clientswanting information about when a window is moved because ofa change in the size of its parent. The X server generatesthis event whenever a client application actually moves achild window as a result of resizing its parent by callingXConfigureWindow, XMoveResizeWindow, or XResizeWindow.To receive GravityNotify events, set the StructureNotifyMaskbit in the event-mask attribute of the window or theSubstructureNotifyMask bit in the event-mask attribute ofthe parent window (in which case, any child that is movedbecause its parent has been resized generates an event).The structure for this event type contains:__│ typedef struct {int type; /* GravityNotify */unsigned long serial; /* # of last request processed by server */Bool send_event; /* true if this came from a SendEvent request */Display *display; /* Display the event was read from */Window event;Window window;int x, y;} XGravityEvent;│__ The event member is set either to the window that was movedor to its parent, depending on whether StructureNotify orSubstructureNotify was selected. The window member is setto the child window that was moved. The x and y members areset to the coordinates relative to the new parent window’sorigin and indicate the position of the upper-left outsidecorner of the window.10.10.6. MapNotify EventsThe X server can report MapNotify events to clients wantinginformation about which windows are mapped. The X servergenerates this event type whenever a client applicationchanges the window’s state from unmapped to mapped bycalling XMapWindow, XMapRaised, XMapSubwindows,XReparentWindow, or as a result of save-set processing.To receive MapNotify events, set the StructureNotifyMask bitin the event-mask attribute of the window or theSubstructureNotifyMask bit in the event-mask attribute ofthe parent window (in which case, mapping any childgenerates an event).The structure for this event type contains:__│ typedef struct {int type; /* MapNotify */unsigned long serial; /* # of last request processed by server */Bool send_event; /* true if this came from a SendEvent request */Display *display; /* Display the event was read from */Window event;Window window;Bool override_redirect; /* boolean, is override set... */} XMapEvent;│__ The event member is set either to the window that was mappedor to its parent, depending on whether StructureNotify orSubstructureNotify was selected. The window member is setto the window that was mapped. The override_redirect memberis set to the override-redirect attribute of the window.Window manager clients normally should ignore this window ifthe override-redirect attribute is True, because theseevents usually are generated from pop-ups, which overridestructure control.10.10.7. MappingNotify EventsThe X server reports MappingNotify events to all clients.There is no mechanism to express disinterest in this event.The X server generates this event type whenever a clientapplication successfully calls:• XSetModifierMapping to indicate which KeyCodes are tobe used as modifiers• XChangeKeyboardMapping to change the keyboard mapping• XSetPointerMapping to set the pointer mappingThe structure for this event type contains:__│ typedef struct {int type; /* MappingNotify */unsigned long serial; /* # of last request processed by server */Bool send_event; /* true if this came from a SendEvent request */Display *display; /* Display the event was read from */Window window; /* unused */int request; /* one of MappingModifier, MappingKeyboard,MappingPointer */int first_keycode; /* first keycode */int count; /* defines range of change w. first_keycode*/} XMappingEvent;│__ The request member is set to indicate the kind of mappingchange that occurred and can be MappingModifier,MappingKeyboard, or MappingPointer. If it isMappingModifier, the modifier mapping was changed. If it isMappingKeyboard, the keyboard mapping was changed. If it isMappingPointer, the pointer button mapping was changed. Thefirst_keycode and count members are set only if the requestmember was set to MappingKeyboard. The number infirst_keycode represents the first number in the range ofthe altered mapping, and count represents the number ofkeycodes altered.To update the client application’s knowledge of thekeyboard, you should call XRefreshKeyboardMapping.10.10.8. ReparentNotify EventsThe X server can report ReparentNotify events to clientswanting information about changing a window’s parent. The Xserver generates this event whenever a client applicationcalls XReparentWindow and the window is actually reparented.To receive ReparentNotify events, set theStructureNotifyMask bit in the event-mask attribute of thewindow or the SubstructureNotifyMask bit in the event-maskattribute of either the old or the new parent window (inwhich case, reparenting any child generates an event).The structure for this event type contains:__│ typedef struct {int type; /* ReparentNotify */unsigned long serial; /* # of last request processed by server */Bool send_event; /* true if this came from a SendEvent request */Display *display; /* Display the event was read from */Window event;Window window;Window parent;int x, y;Bool override_redirect;} XReparentEvent;│__ The event member is set either to the reparented window orto the old or the new parent, depending on whetherStructureNotify or SubstructureNotify was selected. Thewindow member is set to the window that was reparented. Theparent member is set to the new parent window. The x and ymembers are set to the reparented window’s coordinatesrelative to the new parent window’s origin and define theupper-left outer corner of the reparented window. Theoverride_redirect member is set to the override-redirectattribute of the window specified by the window member.Window manager clients normally should ignore this window ifthe override_redirect member is True.10.10.9. UnmapNotify EventsThe X server can report UnmapNotify events to clientswanting information about which windows are unmapped. The Xserver generates this event type whenever a clientapplication changes the window’s state from mapped tounmapped.To receive UnmapNotify events, set the StructureNotifyMaskbit in the event-mask attribute of the window or theSubstructureNotifyMask bit in the event-mask attribute ofthe parent window (in which case, unmapping any child windowgenerates an event).The structure for this event type contains:__│ typedef struct {int type; /* UnmapNotify */unsigned long serial; /* # of last request processed by server */Bool send_event; /* true if this came from a SendEvent request */Display *display; /* Display the event was read from */Window event;Window window;Bool from_configure;} XUnmapEvent;│__ The event member is set either to the unmapped window or toits parent, depending on whether StructureNotify orSubstructureNotify was selected. This is the window used bythe X server to report the event. The window member is setto the window that was unmapped. The from_configure memberis set to True if the event was generated as a result of aresizing of the window’s parent when the window itself had awin_gravity of UnmapGravity.10.10.10. VisibilityNotify EventsThe X server can report VisibilityNotify events to clientswanting any change in the visibility of the specifiedwindow. A region of a window is visible if someone lookingat the screen can actually see it. The X server generatesthis event whenever the visibility changes state. However,this event is never generated for windows whose class isInputOnly.All VisibilityNotify events caused by a hierarchy change aregenerated after any hierarchy event (UnmapNotify, MapNotify,ConfigureNotify, GravityNotify, CirculateNotify) caused bythat change. Any VisibilityNotify event on a given windowis generated before any Expose events on that window, but itis not required that all VisibilityNotify events on allwindows be generated before all Expose events on allwindows. The X protocol does not constrain the ordering ofVisibilityNotify events with respect to FocusOut,EnterNotify, and LeaveNotify events.To receive VisibilityNotify events, set theVisibilityChangeMask bit in the event-mask attribute of thewindow.The structure for this event type contains:__│ typedef struct {int type; /* VisibilityNotify */unsigned long serial; /* # of last request processed by server */Bool send_event; /* true if this came from a SendEvent request */Display *display; /* Display the event was read from */Window window;int state;} XVisibilityEvent;│__ The window member is set to the window whose visibilitystate changes. The state member is set to the state of thewindow’s visibility and can be VisibilityUnobscured,VisibilityPartiallyObscured, or VisibilityFullyObscured.The X server ignores all of a window’s subwindows whendetermining the visibility state of the window and processesVisibilityNotify events according to the following:• When the window changes state from partially obscured,fully obscured, or not viewable to viewable andcompletely unobscured, the X server generates the eventwith the state member of the XVisibilityEvent structureset to VisibilityUnobscured.• When the window changes state from viewable andcompletely unobscured or not viewable to viewable andpartially obscured, the X server generates the eventwith the state member of the XVisibilityEvent structureset to VisibilityPartiallyObscured.• When the window changes state from viewable andcompletely unobscured, viewable and partially obscured,or not viewable to viewable and fully obscured, the Xserver generates the event with the state member of theXVisibilityEvent structure set toVisibilityFullyObscured.10.11. Structure Control EventsThis section discusses:• CirculateRequest events• ConfigureRequest events• MapRequest events• ResizeRequest events10.11.1. CirculateRequest EventsThe X server can report CirculateRequest events to clientswanting information about when another client initiates acirculate window request on a specified window. The Xserver generates this event type whenever a client initiatesa circulate window request on a window and a subwindowactually needs to be restacked. The client initiates acirculate window request on the window by callingXCirculateSubwindows, XCirculateSubwindowsUp, orXCirculateSubwindowsDown.To receive CirculateRequest events, set theSubstructureRedirectMask in the event-mask attribute of thewindow. Then, in the future, the circulate window requestfor the specified window is not executed, and thus, anysubwindow’s position in the stack is not changed. Forexample, suppose a client application callsXCirculateSubwindowsUp to raise a subwindow to the top ofthe stack. If you had selected SubstructureRedirectMask onthe window, the X server reports to you a CirculateRequestevent and does not raise the subwindow to the top of thestack.The structure for this event type contains:__│ typedef struct {int type; /* CirculateRequest */unsigned long serial; /* # of last request processed by server */Bool send_event; /* true if this came from a SendEvent request */Display *display; /* Display the event was read from */Window parent;Window window;int place; /* PlaceOnTop, PlaceOnBottom */} XCirculateRequestEvent;│__ The parent member is set to the parent window. The windowmember is set to the subwindow to be restacked. The placemember is set to what the new position in the stacking ordershould be and is either PlaceOnTop or PlaceOnBottom. If itis PlaceOnTop, the subwindow should be on top of allsiblings. If it is PlaceOnBottom, the subwindow should bebelow all siblings.10.11.2. ConfigureRequest EventsThe X server can report ConfigureRequest events to clientswanting information about when a different client initiatesa configure window request on any child of a specifiedwindow. The configure window request attempts toreconfigure a window’s size, position, border, and stackingorder. The X server generates this event whenever adifferent client initiates a configure window request on awindow by calling XConfigureWindow, XLowerWindow,XRaiseWindow, XMapRaised, XMoveResizeWindow, XMoveWindow,XResizeWindow, XRestackWindows, or XSetWindowBorderWidth.To receive ConfigureRequest events, set theSubstructureRedirectMask bit in the event-mask attribute ofthe window. ConfigureRequest events are generated when aConfigureWindow protocol request is issued on a child windowby another client. For example, suppose a clientapplication calls XLowerWindow to lower a window. If youhad selected SubstructureRedirectMask on the parent windowand if the override-redirect attribute of the window is setto False, the X server reports a ConfigureRequest event toyou and does not lower the specified window.The structure for this event type contains:__│ typedef struct {int type; /* ConfigureRequest */unsigned long serial; /* # of last request processed by server */Bool send_event; /* true if this came from a SendEvent request */Display *display; /* Display the event was read from */Window parent;Window window;int x, y;int width, height;int border_width;Window above;int detail; /* Above, Below, TopIf, BottomIf, Opposite */unsigned long value_mask;} XConfigureRequestEvent;│__ The parent member is set to the parent window. The windowmember is set to the window whose size, position, borderwidth, and/or stacking order is to be reconfigured. Thevalue_mask member indicates which components were specifiedin the ConfigureWindow protocol request. The correspondingvalues are reported as given in the request. The remainingvalues are filled in from the current geometry of thewindow, except in the case of above (sibling) and detail(stack-mode), which are reported as None and Above,respectively, if they are not given in the request.10.11.3. MapRequest EventsThe X server can report MapRequest events to clients wantinginformation about a different client’s desire to mapwindows. A window is considered mapped when a map windowrequest completes. The X server generates this eventwhenever a different client initiates a map window requeston an unmapped window whose override_redirect member is setto False. Clients initiate map window requests by callingXMapWindow, XMapRaised, or XMapSubwindows.To receive MapRequest events, set theSubstructureRedirectMask bit in the event-mask attribute ofthe window. This means another client’s attempts to map achild window by calling one of the map window requestfunctions is intercepted, and you are sent a MapRequestinstead. For example, suppose a client application callsXMapWindow to map a window. If you (usually a windowmanager) had selected SubstructureRedirectMask on the parentwindow and if the override-redirect attribute of the windowis set to False, the X server reports a MapRequest event toyou and does not map the specified window. Thus, this eventgives your window manager client the ability to control theplacement of subwindows.The structure for this event type contains:__│ typedef struct {int type; /* MapRequest */unsigned long serial; /* # of last request processed by server */Bool send_event; /* true if this came from a SendEvent request */Display *display; /* Display the event was read from */Window parent;Window window;} XMapRequestEvent;│__ The parent member is set to the parent window. The windowmember is set to the window to be mapped.10.11.4. ResizeRequest EventsThe X server can report ResizeRequest events to clientswanting information about another client’s attempts tochange the size of a window. The X server generates thisevent whenever some other client attempts to change the sizeof the specified window by calling XConfigureWindow,XResizeWindow, or XMoveResizeWindow.To receive ResizeRequest events, set the ResizeRedirect bitin the event-mask attribute of the window. Any attempts tochange the size by other clients are then redirected.The structure for this event type contains:__│ typedef struct {int type; /* ResizeRequest */unsigned long serial; /* # of last request processed by server */Bool send_event; /* true if this came from a SendEvent request */Display *display; /* Display the event was read from */Window window;int width, height;} XResizeRequestEvent;│__ The window member is set to the window whose size anotherclient attempted to change. The width and height membersare set to the inside size of the window, excluding theborder.10.12. Colormap State Change EventsThe X server can report ColormapNotify events to clientswanting information about when the colormap changes and whena colormap is installed or uninstalled. The X servergenerates this event type whenever a client application:• Changes the colormap member of the XSetWindowAttributesstructure by calling XChangeWindowAttributes,XFreeColormap, or XSetWindowColormap• Installs or uninstalls the colormap by callingXInstallColormap or XUninstallColormapTo receive ColormapNotify events, set the ColormapChangeMaskbit in the event-mask attribute of the window.The structure for this event type contains:__│ typedef struct {int type; /* ColormapNotify */unsigned long serial; /* # of last request processed by server */Bool send_event; /* true if this came from a SendEvent request */Display *display; /* Display the event was read from */Window window;Colormap colormap; /* colormap or None */Bool new;int state; /* ColormapInstalled, ColormapUninstalled */} XColormapEvent;│__ The window member is set to the window whose associatedcolormap is changed, installed, or uninstalled. For acolormap that is changed, installed, or uninstalled, thecolormap member is set to the colormap associated with thewindow. For a colormap that is changed by a call toXFreeColormap, the colormap member is set to None. The newmember is set to indicate whether the colormap for thespecified window was changed or installed or uninstalled andcan be True or False. If it is True, the colormap waschanged. If it is False, the colormap was installed oruninstalled. The state member is always set to indicatewhether the colormap is installed or uninstalled and can beColormapInstalled or ColormapUninstalled.10.13. Client Communication EventsThis section discusses:• ClientMessage events• PropertyNotify events• SelectionClear events• SelectionNotify events• SelectionRequest events10.13.1. ClientMessage EventsThe X server generates ClientMessage events only when aclient calls the function XSendEvent.The structure for this event type contains:__│ typedef struct {int type; /* ClientMessage */unsigned long serial; /* # of last request processed by server */Bool send_event; /* true if this came from a SendEvent request */Display *display; /* Display the event was read from */Window window;Atom message_type;int format;union {char b[20];short s[10];long l[5];} data;} XClientMessageEvent;│__ The message_type member is set to an atom that indicates howthe data should be interpreted by the receiving client. Theformat member is set to 8, 16, or 32 and specifies whetherthe data should be viewed as a list of bytes, shorts, orlongs. The data member is a union that contains the membersb, s, and l. The b, s, and l members represent data oftwenty 8-bit values, ten 16-bit values, and five 32-bitvalues. Particular message types might not make use of allthese values. The X server places no interpretation on thevalues in the window, message_type, or data members.10.13.2. PropertyNotify EventsThe X server can report PropertyNotify events to clientswanting information about property changes for a specifiedwindow.To receive PropertyNotify events, set the PropertyChangeMaskbit in the event-mask attribute of the window.The structure for this event type contains:__│ typedef struct {int type; /* PropertyNotify */unsigned long serial; /* # of last request processed by server */Bool send_event; /* true if this came from a SendEvent request */Display *display; /* Display the event was read from */Window window;Atom atom;Time time;int state; /* PropertyNewValue or PropertyDelete */} XPropertyEvent;│__ The window member is set to the window whose associatedproperty was changed. The atom member is set to theproperty’s atom and indicates which property was changed ordesired. The time member is set to the server time when theproperty was changed. The state member is set to indicatewhether the property was changed to a new value or deletedand can be PropertyNewValue or PropertyDelete. The statemember is set to PropertyNewValue when a property of thewindow is changed using XChangeProperty orXRotateWindowProperties (even when adding zero-length datausing XChangeProperty) and when replacing all or part of aproperty with identical data using XChangeProperty orXRotateWindowProperties. The state member is set toPropertyDelete when a property of the window is deletedusing XDeleteProperty or, if the delete argument is True,XGetWindowProperty.10.13.3. SelectionClear EventsThe X server reports SelectionClear events to the clientlosing ownership of a selection. The X server generatesthis event type when another client asserts ownership of theselection by calling XSetSelectionOwner.The structure for this event type contains:__│ typedef struct {int type; /* SelectionClear */unsigned long serial; /* # of last request processed by server */Bool send_event; /* true if this came from a SendEvent request */Display *display; /* Display the event was read from */Window window;Atom selection;Time time;} XSelectionClearEvent;│__ The selection member is set to the selection atom. The timemember is set to the last change time recorded for theselection. The window member is the window that wasspecified by the current owner (the owner losing theselection) in its XSetSelectionOwner call.10.13.4. SelectionRequest EventsThe X server reports SelectionRequest events to the owner ofa selection. The X server generates this event whenever aclient requests a selection conversion by callingXConvertSelection for the owned selection.The structure for this event type contains:__│ typedef struct {int type; /* SelectionRequest */unsigned long serial; /* # of last request processed by server */Bool send_event; /* true if this came from a SendEvent request */Display *display; /* Display the event was read from */Window owner;Window requestor;Atom selection;Atom target;Atom property;Time time;} XSelectionRequestEvent;│__ The owner member is set to the window that was specified bythe current owner in its XSetSelectionOwner call. Therequestor member is set to the window requesting theselection. The selection member is set to the atom thatnames the selection. For example, PRIMARY is used toindicate the primary selection. The target member is set tothe atom that indicates the type the selection is desiredin. The property member can be a property name or None.The time member is set to the timestamp or CurrentTime valuefrom the ConvertSelection request.The owner should convert the selection based on thespecified target type and send a SelectionNotify event backto the requestor. A complete specification for usingselections is given in the X Consortium standardInter-Client Communication Conventions Manual.10.13.5. SelectionNotify EventsThis event is generated by the X server in response to aConvertSelection protocol request when there is no owner forthe selection. When there is an owner, it should begenerated by the owner of the selection by using XSendEvent.The owner of a selection should send this event to arequestor when a selection has been converted and stored asa property or when a selection conversion could not beperformed (which is indicated by setting the property memberto None).If None is specified as the property in the ConvertSelectionprotocol request, the owner should choose a property name,store the result as that property on the requestor window,and then send a SelectionNotify giving that actual propertyname.The structure for this event type contains:__│ typedef struct {int type; /* SelectionNotify */unsigned long serial; /* # of last request processed by server */Bool send_event; /* true if this came from a SendEvent request */Display *display; /* Display the event was read from */Window requestor;Atom selection;Atom target;Atom property; /* atom or None */Time time;} XSelectionEvent;│__ The requestor member is set to the window associated withthe requestor of the selection. The selection member is setto the atom that indicates the selection. For example,PRIMARY is used for the primary selection. The targetmember is set to the atom that indicates the converted type.For example, PIXMAP is used for a pixmap. The propertymember is set to the atom that indicates which property theresult was stored on. If the conversion failed, theproperty member is set to None. The time member is set tothe time the conversion took place and can be a timestamp orCurrentTime. 10
11.1. Selecting EventsThere are two ways to select the events you want reported toyour client application. One way is to set the event_maskmember of the XSetWindowAttributes structure when you callXCreateWindow and XChangeWindowAttributes. Another way isto use XSelectInput.__│ XSelectInput(display, w, event_mask)Display *display;Window w;long event_mask;display Specifies the connection to the X server.w Specifies the window whose events you areinterested in.event_maskSpecifies the event mask.│__ The XSelectInput function requests that the X server reportthe events associated with the specified event mask.Initially, X will not report any of these events. Eventsare reported relative to a window. If a window is notinterested in a device event, it usually propagates to theclosest ancestor that is interested, unless thedo_not_propagate mask prohibits it.Setting the event-mask attribute of a window overrides anyprevious call for the same window but not for other clients.Multiple clients can select for the same events on the samewindow with the following restrictions:• Multiple clients can select events on the same windowbecause their event masks are disjoint. When the Xserver generates an event, it reports it to allinterested clients.• Only one client at a time can select CirculateRequest,ConfigureRequest, or MapRequest events, which areassociated with the event maskSubstructureRedirectMask.• Only one client at a time can select a ResizeRequestevent, which is associated with the event maskResizeRedirectMask.• Only one client at a time can select a ButtonPressevent, which is associated with the event maskButtonPressMask.The server reports the event to all interested clients.XSelectInput can generate a BadWindow error.11.2. Handling the Output BufferThe output buffer is an area used by Xlib to store requests.The functions described in this section flush the outputbuffer if the function would block or not return an event.That is, all requests residing in the output buffer thathave not yet been sent are transmitted to the X server.These functions differ in the additional tasks they mightperform.To flush the output buffer, use XFlush.__│ XFlush(display)Display *display;display Specifies the connection to the X server.│__ The XFlush function flushes the output buffer. Most clientapplications need not use this function because the outputbuffer is automatically flushed as needed by calls toXPending, XNextEvent, and XWindowEvent. Events generated bythe server may be enqueued into the library’s event queue.To flush the output buffer and then wait until all requestshave been processed, use XSync.__│ XSync(display, discard)Display *display;Bool discard;display Specifies the connection to the X server.discard Specifies a Boolean value that indicates whetherXSync discards all events on the event queue.│__ The XSync function flushes the output buffer and then waitsuntil all requests have been received and processed by the Xserver. Any errors generated must be handled by the errorhandler. For each protocol error received by Xlib, XSynccalls the client application’s error handling routine (seesection 11.8.2). Any events generated by the server areenqueued into the library’s event queue.Finally, if you passed False, XSync does not discard theevents in the queue. If you passed True, XSync discards allevents in the queue, including those events that were on thequeue before XSync was called. Client applications seldomneed to call XSync.11.3. Event Queue ManagementXlib maintains an event queue. However, the operatingsystem also may be buffering data in its network connectionthat is not yet read into the event queue.To check the number of events in the event queue, useXEventsQueued.__│ int XEventsQueued(display, mode)Display *display;int mode;display Specifies the connection to the X server.mode Specifies the mode. You can pass QueuedAlready,QueuedAfterFlush, or QueuedAfterReading.│__ If mode is QueuedAlready, XEventsQueued returns the numberof events already in the event queue (and never performs asystem call). If mode is QueuedAfterFlush, XEventsQueuedreturns the number of events already in the queue if thenumber is nonzero. If there are no events in the queue,XEventsQueued flushes the output buffer, attempts to readmore events out of the application’s connection, and returnsthe number read. If mode is QueuedAfterReading,XEventsQueued returns the number of events already in thequeue if the number is nonzero. If there are no events inthe queue, XEventsQueued attempts to read more events out ofthe application’s connection without flushing the outputbuffer and returns the number read.XEventsQueued always returns immediately without I/O ifthere are events already in the queue. XEventsQueued withmode QueuedAfterFlush is identical in behavior to XPending.XEventsQueued with mode QueuedAlready is identical to theXQLength function.To return the number of events that are pending, useXPending.__│ int XPending(display)Display *display;display Specifies the connection to the X server.│__ The XPending function returns the number of events that havebeen received from the X server but have not been removedfrom the event queue. XPending is identical toXEventsQueued with the mode QueuedAfterFlush specified.11.4. Manipulating the Event QueueXlib provides functions that let you manipulate the eventqueue. This section discusses how to:• Obtain events, in order, and remove them from the queue• Peek at events in the queue without removing them• Obtain events that match the event mask or thearbitrary predicate procedures that you provide11.4.1. Returning the Next EventTo get the next event and remove it from the queue, useXNextEvent.__│ XNextEvent(display, event_return)Display *display;XEvent *event_return;display Specifies the connection to the X server.event_returnReturns the next event in the queue.│__ The XNextEvent function copies the first event from theevent queue into the specified XEvent structure and thenremoves it from the queue. If the event queue is empty,XNextEvent flushes the output buffer and blocks until anevent is received.To peek at the event queue, use XPeekEvent.__│ XPeekEvent(display, event_return)Display *display;XEvent *event_return;display Specifies the connection to the X server.event_returnReturns a copy of the matched event’s associatedstructure.│__ The XPeekEvent function returns the first event from theevent queue, but it does not remove the event from thequeue. If the queue is empty, XPeekEvent flushes the outputbuffer and blocks until an event is received. It thencopies the event into the client-supplied XEvent structurewithout removing it from the event queue.11.4.2. Selecting Events Using a Predicate ProcedureEach of the functions discussed in this section requires youto pass a predicate procedure that determines if an eventmatches what you want. Your predicate procedure must decideif the event is useful without calling any Xlib functions.If the predicate directly or indirectly causes the state ofthe event queue to change, the result is not defined. IfXlib has been initialized for threads, the predicate iscalled with the display locked and the result of a call bythe predicate to any Xlib function that locks the display isnot defined unless the caller has first called XLockDisplay.The predicate procedure and its associated arguments are:__│ Bool (*predicate)(display, event, arg)Display *display;XEvent *event;XPointer arg;display Specifies the connection to the X server.event Specifies the XEvent structure.arg Specifies the argument passed in from theXIfEvent, XCheckIfEvent, or XPeekIfEvent function.│__ The predicate procedure is called once for each event in thequeue until it finds a match. After finding a match, thepredicate procedure must return True. If it did not find amatch, it must return False.To check the event queue for a matching event and, if found,remove the event from the queue, use XIfEvent.__│ XIfEvent(display, event_return, predicate, arg)Display *display;XEvent *event_return;Bool (*predicate)();XPointer arg;display Specifies the connection to the X server.event_returnReturns the matched event’s associated structure.predicate Specifies the procedure that is to be called todetermine if the next event in the queue matcheswhat you want.arg Specifies the user-supplied argument that will bepassed to the predicate procedure.│__ The XIfEvent function completes only when the specifiedpredicate procedure returns True for an event, whichindicates an event in the queue matches. XIfEvent flushesthe output buffer if it blocks waiting for additionalevents. XIfEvent removes the matching event from the queueand copies the structure into the client-supplied XEventstructure.To check the event queue for a matching event withoutblocking, use XCheckIfEvent.__│ Bool XCheckIfEvent(display, event_return, predicate, arg)Display *display;XEvent *event_return;Bool (*predicate)();XPointer arg;display Specifies the connection to the X server.event_returnReturns a copy of the matched event’s associatedstructure.predicate Specifies the procedure that is to be called todetermine if the next event in the queue matcheswhat you want.arg Specifies the user-supplied argument that will bepassed to the predicate procedure.│__ When the predicate procedure finds a match, XCheckIfEventcopies the matched event into the client-supplied XEventstructure and returns True. (This event is removed from thequeue.) If the predicate procedure finds no match,XCheckIfEvent returns False, and the output buffer will havebeen flushed. All earlier events stored in the queue arenot discarded.To check the event queue for a matching event withoutremoving the event from the queue, use XPeekIfEvent.__│ XPeekIfEvent(display, event_return, predicate, arg)Display *display;XEvent *event_return;Bool (*predicate)();XPointer arg;display Specifies the connection to the X server.event_returnReturns a copy of the matched event’s associatedstructure.predicate Specifies the procedure that is to be called todetermine if the next event in the queue matcheswhat you want.arg Specifies the user-supplied argument that will bepassed to the predicate procedure.│__ The XPeekIfEvent function returns only when the specifiedpredicate procedure returns True for an event. After thepredicate procedure finds a match, XPeekIfEvent copies thematched event into the client-supplied XEvent structurewithout removing the event from the queue. XPeekIfEventflushes the output buffer if it blocks waiting foradditional events.11.4.3. Selecting Events Using a Window or Event MaskThe functions discussed in this section let you selectevents by window or event types, allowing you to processevents out of order.To remove the next event that matches both a window and anevent mask, use XWindowEvent.__│ XWindowEvent(display, w, event_mask, event_return)Display *display;Window w;long event_mask;XEvent *event_return;display Specifies the connection to the X server.w Specifies the window whose events you areinterested in.event_maskSpecifies the event mask.event_returnReturns the matched event’s associated structure.│__ The XWindowEvent function searches the event queue for anevent that matches both the specified window and event mask.When it finds a match, XWindowEvent removes that event fromthe queue and copies it into the specified XEvent structure.The other events stored in the queue are not discarded. Ifa matching event is not in the queue, XWindowEvent flushesthe output buffer and blocks until one is received.To remove the next event that matches both a window and anevent mask (if any), use XCheckWindowEvent. This functionis similar to XWindowEvent except that it never blocks andit returns a Bool indicating if the event was returned.__│ Bool XCheckWindowEvent(display, w, event_mask, event_return)Display *display;Window w;long event_mask;XEvent *event_return;display Specifies the connection to the X server.w Specifies the window whose events you areinterested in.event_maskSpecifies the event mask.event_returnReturns the matched event’s associated structure.│__ The XCheckWindowEvent function searches the event queue andthen the events available on the server connection for thefirst event that matches the specified window and eventmask. If it finds a match, XCheckWindowEvent removes thatevent, copies it into the specified XEvent structure, andreturns True. The other events stored in the queue are notdiscarded. If the event you requested is not available,XCheckWindowEvent returns False, and the output buffer willhave been flushed.To remove the next event that matches an event mask, useXMaskEvent.__│ XMaskEvent(display, event_mask, event_return)Display *display;long event_mask;XEvent *event_return;display Specifies the connection to the X server.event_maskSpecifies the event mask.event_returnReturns the matched event’s associated structure.│__ The XMaskEvent function searches the event queue for theevents associated with the specified mask. When it finds amatch, XMaskEvent removes that event and copies it into thespecified XEvent structure. The other events stored in thequeue are not discarded. If the event you requested is notin the queue, XMaskEvent flushes the output buffer andblocks until one is received.To return and remove the next event that matches an eventmask (if any), use XCheckMaskEvent. This function issimilar to XMaskEvent except that it never blocks and itreturns a Bool indicating if the event was returned.__│ Bool XCheckMaskEvent(display, event_mask, event_return)Display *display;long event_mask;XEvent *event_return;display Specifies the connection to the X server.event_maskSpecifies the event mask.event_returnReturns the matched event’s associated structure.│__ The XCheckMaskEvent function searches the event queue andthen any events available on the server connection for thefirst event that matches the specified mask. If it finds amatch, XCheckMaskEvent removes that event, copies it intothe specified XEvent structure, and returns True. The otherevents stored in the queue are not discarded. If the eventyou requested is not available, XCheckMaskEvent returnsFalse, and the output buffer will have been flushed.To return and remove the next event in the queue thatmatches an event type, use XCheckTypedEvent.__│ Bool XCheckTypedEvent(display, event_type, event_return)Display *display;int event_type;XEvent *event_return;display Specifies the connection to the X server.event_typeSpecifies the event type to be compared.event_returnReturns the matched event’s associated structure.│__ The XCheckTypedEvent function searches the event queue andthen any events available on the server connection for thefirst event that matches the specified type. If it finds amatch, XCheckTypedEvent removes that event, copies it intothe specified XEvent structure, and returns True. The otherevents in the queue are not discarded. If the event is notavailable, XCheckTypedEvent returns False, and the outputbuffer will have been flushed.To return and remove the next event in the queue thatmatches an event type and a window, useXCheckTypedWindowEvent.__│ Bool XCheckTypedWindowEvent(display, w, event_type, event_return)Display *display;Window w;int event_type;XEvent *event_return;display Specifies the connection to the X server.w Specifies the window.event_typeSpecifies the event type to be compared.event_returnReturns the matched event’s associated structure.│__ The XCheckTypedWindowEvent function searches the event queueand then any events available on the server connection forthe first event that matches the specified type and window.If it finds a match, XCheckTypedWindowEvent removes theevent from the queue, copies it into the specified XEventstructure, and returns True. The other events in the queueare not discarded. If the event is not available,XCheckTypedWindowEvent returns False, and the output bufferwill have been flushed.11.5. Putting an Event Back into the QueueTo push an event back into the event queue, useXPutBackEvent.__│ XPutBackEvent(display, event)Display *display;XEvent *event;display Specifies the connection to the X server.event Specifies the event.│__ The XPutBackEvent function pushes an event back onto thehead of the display’s event queue by copying the event intothe queue. This can be useful if you read an event and thendecide that you would rather deal with it later. There isno limit to the number of times in succession that you cancall XPutBackEvent.11.6. Sending Events to Other ApplicationsTo send an event to a specified window, use XSendEvent.This function is often used in selection processing. Forexample, the owner of a selection should use XSendEvent tosend a SelectionNotify event to a requestor when a selectionhas been converted and stored as a property.__│ Status XSendEvent(display, w, propagate, event_mask, event_send)Display *display;Window w;Bool propagate;long event_mask;XEvent *event_send;display Specifies the connection to the X server.w Specifies the window the event is to be sent to,or PointerWindow, or InputFocus.propagate Specifies a Boolean value.event_maskSpecifies the event mask.event_sendSpecifies the event that is to be sent.│__ The XSendEvent function identifies the destination window,determines which clients should receive the specifiedevents, and ignores any active grabs. This functionrequires you to pass an event mask. For a discussion of thevalid event mask names, see section 10.3. This functionuses the w argument to identify the destination window asfollows:• If w is PointerWindow, the destination window is thewindow that contains the pointer.• If w is InputFocus and if the focus window contains thepointer, the destination window is the window thatcontains the pointer; otherwise, the destination windowis the focus window.To determine which clients should receive the specifiedevents, XSendEvent uses the propagate argument as follows:• If event_mask is the empty set, the event is sent tothe client that created the destination window. Ifthat client no longer exists, no event is sent.• If propagate is False, the event is sent to everyclient selecting on destination any of the event typesin the event_mask argument.• If propagate is True and no clients have selected ondestination any of the event types in event-mask, thedestination is replaced with the closest ancestor ofdestination for which some client has selected a typein event-mask and for which no intervening window hasthat type in its do-not-propagate-mask. If no suchwindow exists or if the window is an ancestor of thefocus window and InputFocus was originally specified asthe destination, the event is not sent to any clients.Otherwise, the event is reported to every clientselecting on the final destination any of the typesspecified in event_mask.The event in the XEvent structure must be one of the coreevents or one of the events defined by an extension (or aBadValue error results) so that the X server can correctlybyte-swap the contents as necessary. The contents of theevent are otherwise unaltered and unchecked by the X serverexcept to force send_event to True in the forwarded eventand to set the serial number in the event correctly;therefore these fields and the display field are ignored byXSendEvent.XSendEvent returns zero if the conversion to wire protocolformat failed and returns nonzero otherwise.XSendEvent can generate BadValue and BadWindow errors.11.7. Getting Pointer Motion HistorySome X server implementations will maintain a more completehistory of pointer motion than is reported by eventnotification. The pointer position at each pointer hardwareinterrupt may be stored in a buffer for later retrieval.This buffer is called the motion history buffer. Forexample, a few applications, such as paint programs, want tohave a precise history of where the pointer traveled.However, this historical information is highly excessive formost applications.To determine the approximate maximum number of elements inthe motion buffer, use XDisplayMotionBufferSize.__│ unsigned long XDisplayMotionBufferSize(display)Display *display;display Specifies the connection to the X server.│__ The server may retain the recent history of the pointermotion and do so to a finer granularity than is reported byMotionNotify events. The XGetMotionEvents function makesthis history available.To get the motion history for a specified window and time,use XGetMotionEvents.__│ XTimeCoord *XGetMotionEvents(display, w, start, stop, nevents_return)Display *display;Window w;Time start, stop;int *nevents_return;display Specifies the connection to the X server.w Specifies the window.startstop Specify the time interval in which the events arereturned from the motion history buffer. You canpass a timestamp or CurrentTime.nevents_returnReturns the number of events from the motionhistory buffer.│__ The XGetMotionEvents function returns all events in themotion history buffer that fall between the specified startand stop times, inclusive, and that have coordinates thatlie within the specified window (including its borders) atits present placement. If the server does not supportmotion history, if the start time is later than the stoptime, or if the start time is in the future, no events arereturned; XGetMotionEvents returns NULL. If the stop timeis in the future, it is equivalent to specifyingCurrentTime. The return type for this function is astructure defined as follows:__│ typedef struct {Time time;short x, y;} XTimeCoord;│__ The time member is set to the time, in milliseconds. The xand y members are set to the coordinates of the pointer andare reported relative to the origin of the specified window.To free the data returned from this call, use XFree.XGetMotionEvents can generate a BadWindow error.11.8. Handling Protocol ErrorsXlib provides functions that you can use to enable ordisable synchronization and to use the default errorhandlers.11.8.1. Enabling or Disabling SynchronizationWhen debugging X applications, it often is very convenientto require Xlib to behave synchronously so that errors arereported as they occur. The following function lets youdisable or enable synchronous behavior. Note that graphicsmay occur 30 or more times more slowly when synchronizationis enabled. On POSIX-conformant systems, there is also aglobal variable _Xdebug that, if set to nonzero beforestarting a program under a debugger, will force synchronouslibrary behavior.After completing their work, all Xlib functions thatgenerate protocol requests call what is known as an afterfunction. XSetAfterFunction sets which function is to becalled.__│ int (*XSetAfterFunction(display, procedure))()Display *display;int (*procedure)();display Specifies the connection to the X server.procedure Specifies the procedure to be called.│__ The specified procedure is called with only a displaypointer. XSetAfterFunction returns the previous afterfunction.To enable or disable synchronization, use XSynchronize.__│ int (*XSynchronize(display, onoff))()Display *display;Bool onoff;display Specifies the connection to the X server.onoff Specifies a Boolean value that indicates whetherto enable or disable synchronization.│__ The XSynchronize function returns the previous afterfunction. If onoff is True, XSynchronize turns onsynchronous behavior. If onoff is False, XSynchronize turnsoff synchronous behavior.11.8.2. Using the Default Error HandlersThere are two default error handlers in Xlib: one to handletypically fatal conditions (for example, the connection to adisplay server dying because a machine crashed) and one tohandle protocol errors from the X server. These errorhandlers can be changed to user-supplied routines if youprefer your own error handling and can be changed as oftenas you like. If either function is passed a NULL pointer,it will reinvoke the default handler. The action of thedefault handlers is to print an explanatory message andexit.To set the error handler, use XSetErrorHandler.__│ int (*XSetErrorHandler(handler))()int (*handler)(Display *, XErrorEvent *)handler Specifies the program’s supplied error handler.│__ Xlib generally calls the program’s supplied error handlerwhenever an error is received. It is not called on BadNameerrors from OpenFont, LookupColor, or AllocNamedColorprotocol requests or on BadFont errors from a QueryFontprotocol request. These errors generally are reflected backto the program through the procedural interface. Becausethis condition is not assumed to be fatal, it is acceptablefor your error handler to return; the returned value isignored. However, the error handler should not call anyfunctions (directly or indirectly) on the display that willgenerate protocol requests or that will look for inputevents. The previous error handler is returned.The XErrorEvent structure contains:typedef struct {int type;Display *display; /* Display the event was read from */unsigned long serial;/* serial number of failed request */unsigned char error_code;/* error code of failed request */unsigned char request_code;/* Major op-code of failed request */unsigned char minor_code;/* Minor op-code of failed request */XID resourceid; /* resource id */} XErrorEvent;The serial member is the number of requests, starting fromone, sent over the network connection since it was opened.It is the number that was the value of NextRequestimmediately before the failing call was made. Therequest_code member is a protocol request of the procedurethat failed, as defined in <X11/Xproto.h>. The followingerror codes can be returned by the functions described inthis chapter: NoteThe BadAtom, BadColor, BadCursor, BadDrawable,BadFont, BadGC, BadPixmap, and BadWindow errorsare also used when the argument type is extendedby a set of fixed alternatives.To obtain textual descriptions of the specified error code,use XGetErrorText.__│ XGetErrorText(display, code, buffer_return, length)Display *display;int code;char *buffer_return;int length;display Specifies the connection to the X server.code Specifies the error code for which you want toobtain a description.buffer_returnReturns the error description.length Specifies the size of the buffer.│__ The XGetErrorText function copies a null-terminated stringdescribing the specified error code into the specifiedbuffer. The returned text is in the encoding of the currentlocale. It is recommended that you use this function toobtain an error description because extensions to Xlib maydefine their own error codes and error strings.To obtain error messages from the error database, useXGetErrorDatabaseText.__│ XGetErrorDatabaseText(display, name, message, default_string, buffer_return, length)Display *display;char *name, *message;char *default_string;char *buffer_return;int length;display Specifies the connection to the X server.name Specifies the name of the application.message Specifies the type of the error message.default_stringSpecifies the default error message if none isfound in the database.buffer_returnReturns the error description.length Specifies the size of the buffer.│__ The XGetErrorDatabaseText function returns a null-terminatedmessage (or the default message) from the error messagedatabase. Xlib uses this function internally to look up itserror messages. The text in the default_string argument isassumed to be in the encoding of the current locale, and thetext stored in the buffer_return argument is in the encodingof the current locale.The name argument should generally be the name of yourapplication. The message argument should indicate whichtype of error message you want. If the name and message arenot in the Host Portable Character Encoding, the result isimplementation-dependent. Xlib uses three predefined‘‘application names’’ to report errors. In these names,uppercase and lowercase matter.XProtoErrorThe protocol error number is used as a string forthe message argument.XlibMessageThese are the message strings that are usedinternally by the library.XRequest For a core protocol request, the major requestprotocol number is used for the message argument.For an extension request, the extension name (asgiven by InitExtension) followed by a period (.)and the minor request protocol number is used forthe message argument. If no string is found inthe error database, the default_string is returnedto the buffer argument.To report an error to the user when the requested displaydoes not exist, use XDisplayName.__│ char *XDisplayName(string)char *string;string Specifies the character string.│__ The XDisplayName function returns the name of the displaythat XOpenDisplay would attempt to use. If a NULL string isspecified, XDisplayName looks in the environment for thedisplay and returns the display name that XOpenDisplay wouldattempt to use. This makes it easier to report to the userprecisely which display the program attempted to open whenthe initial connection attempt failed.To handle fatal I/O errors, use XSetIOErrorHandler.__│ int (*XSetIOErrorHandler(handler))()int (*handler)(Display *);handler Specifies the program’s supplied error handler.│__ The XSetIOErrorHandler sets the fatal I/O error handler.Xlib calls the program’s supplied error handler if any sortof system call error occurs (for example, the connection tothe server was lost). This is assumed to be a fatalcondition, and the called routine should not return. If theI/O error handler does return, the client process exits.Note that the previous error handler is returned.11
12.1. Pointer GrabbingXlib provides functions that you can use to control inputfrom the pointer, which usually is a mouse. Usually, assoon as keyboard and mouse events occur, the X serverdelivers them to the appropriate client, which is determinedby the window and input focus. The X server providessufficient control over event delivery to allow windowmanagers to support mouse ahead and various other styles ofuser interface. Many of these user interfaces depend onsynchronous delivery of events. The delivery of pointerand keyboard events can be controlled independently.When mouse buttons or keyboard keys are grabbed, events willbe sent to the grabbing client rather than the normal clientwho would have received the event. If the keyboard orpointer is in asynchronous mode, further mouse and keyboardevents will continue to be processed. If the keyboard orpointer is in synchronous mode, no further events areprocessed until the grabbing client allows them (seeXAllowEvents). The keyboard or pointer is considered frozenduring this interval. The event that triggered the grab canalso be replayed.Note that the logical state of a device (as seen by clientapplications) may lag the physical state if device eventprocessing is frozen.There are two kinds of grabs: active and passive. An activegrab occurs when a single client grabs the keyboard and/orpointer explicitly (see XGrabPointer and XGrabKeyboard). Apassive grab occurs when clients grab a particular keyboardkey or pointer button in a window, and the grab willactivate when the key or button is actually pressed.Passive grabs are convenient for implementing reliablepop-up menus. For example, you can guarantee that thepop-up is mapped before the up pointer button event occursby grabbing a button requesting synchronous behavior. Thedown event will trigger the grab and freeze furtherprocessing of pointer events until you have the chance tomap the pop-up window. You can then allow further eventprocessing. The up event will then be correctly processedrelative to the pop-up window.For many operations, there are functions that take a timeargument. The X server includes a timestamp in variousevents. One special time, called CurrentTime, representsthe current server time. The X server maintains the timewhen the input focus was last changed, when the keyboard waslast grabbed, when the pointer was last grabbed, or when aselection was last changed. Your application may be slowreacting to an event. You often need some way to specifythat your request should not occur if another applicationhas in the meanwhile taken control of the keyboard, pointer,or selection. By providing the timestamp from the event inthe request, you can arrange that the operation not takeeffect if someone else has performed an operation in themeanwhile.A timestamp is a time value, expressed in milliseconds. Ittypically is the time since the last server reset.Timestamp values wrap around (after about 49.7 days). Theserver, given its current time is represented by timestampT, always interprets timestamps from clients by treatinghalf of the timestamp space as being later in time than T.One timestamp value, named CurrentTime, is never generatedby the server. This value is reserved for use in requeststo represent the current server time.For many functions in this section, you pass pointer eventmask bits. The valid pointer event mask bits are:ButtonPressMask, ButtonReleaseMask, EnterWindowMask,LeaveWindowMask, PointerMotionMask, PointerMotionHintMask,Button1MotionMask, Button2MotionMask, Button3MotionMask,Button4MotionMask, Button5MotionMask, ButtonMotionMask, andKeyMapStateMask. For other functions in this section, youpass keymask bits. The valid keymask bits are: ShiftMask,LockMask, ControlMask, Mod1Mask, Mod2Mask, Mod3Mask,Mod4Mask, and Mod5Mask.To grab the pointer, use XGrabPointer.__│ int XGrabPointer(display, grab_window, owner_events, event_mask, pointer_mode,keyboard_mode, confine_to, cursor, time)Display *display;Window grab_window;Bool owner_events;unsigned int event_mask;int pointer_mode, keyboard_mode;Window confine_to;Cursor cursor;Time time;display Specifies the connection to the X server.grab_windowSpecifies the grab window.owner_eventsSpecifies a Boolean value that indicates whetherthe pointer events are to be reported as usual orreported with respect to the grab window ifselected by the event mask.event_maskSpecifies which pointer events are reported to theclient. The mask is the bitwise inclusive OR ofthe valid pointer event mask bits.pointer_modeSpecifies further processing of pointer events.You can pass GrabModeSync or GrabModeAsync.keyboard_modeSpecifies further processing of keyboard events.You can pass GrabModeSync or GrabModeAsync.confine_toSpecifies the window to confine the pointer in orNone.cursor Specifies the cursor that is to be displayedduring the grab or None.time Specifies the time. You can pass either atimestamp or CurrentTime.│__ The XGrabPointer function actively grabs control of thepointer and returns GrabSuccess if the grab was successful.Further pointer events are reported only to the grabbingclient. XGrabPointer overrides any active pointer grab bythis client. If owner_events is False, all generatedpointer events are reported with respect to grab_window andare reported only if selected by event_mask. Ifowner_events is True and if a generated pointer event wouldnormally be reported to this client, it is reported asusual. Otherwise, the event is reported with respect to thegrab_window and is reported only if selected by event_mask.For either value of owner_events, unreported events arediscarded.If the pointer_mode is GrabModeAsync, pointer eventprocessing continues as usual. If the pointer is currentlyfrozen by this client, the processing of events for thepointer is resumed. If the pointer_mode is GrabModeSync,the state of the pointer, as seen by client applications,appears to freeze, and the X server generates no furtherpointer events until the grabbing client calls XAllowEventsor until the pointer grab is released. Actual pointerchanges are not lost while the pointer is frozen; they aresimply queued in the server for later processing.If the keyboard_mode is GrabModeAsync, keyboard eventprocessing is unaffected by activation of the grab. If thekeyboard_mode is GrabModeSync, the state of the keyboard, asseen by client applications, appears to freeze, and the Xserver generates no further keyboard events until thegrabbing client calls XAllowEvents or until the pointer grabis released. Actual keyboard changes are not lost while thepointer is frozen; they are simply queued in the server forlater processing.If a cursor is specified, it is displayed regardless of whatwindow the pointer is in. If None is specified, the normalcursor for that window is displayed when the pointer is ingrab_window or one of its subwindows; otherwise, the cursorfor grab_window is displayed.If a confine_to window is specified, the pointer isrestricted to stay contained in that window. The confine_towindow need have no relationship to the grab_window. If thepointer is not initially in the confine_to window, it iswarped automatically to the closest edge just before thegrab activates and enter/leave events are generated asusual. If the confine_to window is subsequentlyreconfigured, the pointer is warped automatically, asnecessary, to keep it contained in the window.The time argument allows you to avoid certain circumstancesthat come up if applications take a long time to respond orif there are long network delays. Consider a situationwhere you have two applications, both of which normally grabthe pointer when clicked on. If both applications specifythe timestamp from the event, the second application maywake up faster and successfully grab the pointer before thefirst application. The first application then will get anindication that the other application grabbed the pointerbefore its request was processed.XGrabPointer generates EnterNotify and LeaveNotify events.Either if grab_window or confine_to window is not viewableor if the confine_to window lies completely outside theboundaries of the root window, XGrabPointer fails andreturns GrabNotViewable. If the pointer is actively grabbedby some other client, it fails and returns AlreadyGrabbed.If the pointer is frozen by an active grab of anotherclient, it fails and returns GrabFrozen. If the specifiedtime is earlier than the last-pointer-grab time or laterthan the current X server time, it fails and returnsGrabInvalidTime. Otherwise, the last-pointer-grab time isset to the specified time (CurrentTime is replaced by thecurrent X server time).XGrabPointer can generate BadCursor, BadValue, and BadWindowerrors.To ungrab the pointer, use XUngrabPointer.__│ XUngrabPointer(display, time)Display *display;Time time;display Specifies the connection to the X server.time Specifies the time. You can pass either atimestamp or CurrentTime.│__ The XUngrabPointer function releases the pointer and anyqueued events if this client has actively grabbed thepointer from XGrabPointer, XGrabButton, or from a normalbutton press. XUngrabPointer does not release the pointerif the specified time is earlier than the last-pointer-grabtime or is later than the current X server time. It alsogenerates EnterNotify and LeaveNotify events. The X serverperforms an UngrabPointer request automatically if the eventwindow or confine_to window for an active pointer grabbecomes not viewable or if window reconfiguration causes theconfine_to window to lie completely outside the boundariesof the root window.To change an active pointer grab, useXChangeActivePointerGrab.__│ XChangeActivePointerGrab(display, event_mask, cursor, time)Display *display;unsigned int event_mask;Cursor cursor;Time time;display Specifies the connection to the X server.event_maskSpecifies which pointer events are reported to theclient. The mask is the bitwise inclusive OR ofthe valid pointer event mask bits.cursor Specifies the cursor that is to be displayed orNone.time Specifies the time. You can pass either atimestamp or CurrentTime.│__ The XChangeActivePointerGrab function changes the specifieddynamic parameters if the pointer is actively grabbed by theclient and if the specified time is no earlier than thelast-pointer-grab time and no later than the current Xserver time. This function has no effect on the passiveparameters of an XGrabButton. The interpretation ofevent_mask and cursor is the same as described inXGrabPointer.XChangeActivePointerGrab can generate BadCursor and BadValueerrors.To grab a pointer button, use XGrabButton.__│ XGrabButton(display, button, modifiers, grab_window, owner_events, event_mask,pointer_mode, keyboard_mode, confine_to, cursor)Display *display;unsigned int button;unsigned int modifiers;Window grab_window;Bool owner_events;unsigned int event_mask;int pointer_mode, keyboard_mode;Window confine_to;Cursor cursor;display Specifies the connection to the X server.button Specifies the pointer button that is to be grabbedor AnyButton.modifiers Specifies the set of keymasks or AnyModifier. Themask is the bitwise inclusive OR of the validkeymask bits.grab_windowSpecifies the grab window.owner_eventsSpecifies a Boolean value that indicates whetherthe pointer events are to be reported as usual orreported with respect to the grab window ifselected by the event mask.event_maskSpecifies which pointer events are reported to theclient. The mask is the bitwise inclusive OR ofthe valid pointer event mask bits.pointer_modeSpecifies further processing of pointer events.You can pass GrabModeSync or GrabModeAsync.keyboard_modeSpecifies further processing of keyboard events.You can pass GrabModeSync or GrabModeAsync.confine_toSpecifies the window to confine the pointer in orNone.cursor Specifies the cursor that is to be displayed orNone.│__ The XGrabButton function establishes a passive grab. In thefuture, the pointer is actively grabbed (as forXGrabPointer), the last-pointer-grab time is set to the timeat which the button was pressed (as transmitted in theButtonPress event), and the ButtonPress event is reported ifall of the following conditions are true:• The pointer is not grabbed, and the specified button islogically pressed when the specified modifier keys arelogically down, and no other buttons or modifier keysare logically down.• The grab_window contains the pointer.• The confine_to window (if any) is viewable.• A passive grab on the same button/key combination doesnot exist on any ancestor of grab_window.The interpretation of the remaining arguments is as forXGrabPointer. The active grab is terminated automaticallywhen the logical state of the pointer has all buttonsreleased (independent of the state of the logical modifierkeys).Note that the logical state of a device (as seen by clientapplications) may lag the physical state if device eventprocessing is frozen.This request overrides all previous grabs by the same clienton the same button/key combinations on the same window. Amodifiers of AnyModifier is equivalent to issuing the grabrequest for all possible modifier combinations (includingthe combination of no modifiers). It is not required thatall modifiers specified have cu