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