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