# Application Utility Functions

Once you have initialized the X system, you can use the Xlib utility functions to:

- Use keyboard utility functions

- Use Latin-1 keyboard event functions

- Allocate permanent storage

- Parse the window geometry

- Manipulate regions

- Use cut buffers

- Determine the appropriate visual type

- Manipulate images

- Manipulate bitmaps

- Use the context manager

As a group, the functions discussed in this chapter provide the functionality that is frequently needed and that spans toolkits. Many of these functions do not generate actual protocol requests to the server.

## Using Keyboard Utility Functions

This section discusses mapping between KeyCodes and KeySyms, classifying KeySyms, and mapping between KeySyms and string names. The first three functions in this section operate on a cached copy of the server keyboard mapping. The first four KeySyms for each KeyCode are modified according to the rules given in section 12.7. To obtain the untransformed KeySyms defined for a key, use the functions described in section 12.7.

To obtain a KeySym for the KeyCode of an event, use .

KeySym `XLookupKeysym` XKeyEvent *key_event int index

key_event

  Specifies the KeyPress or KeyRelease event.

index

  Specifies the index into the KeySyms list for the event's KeyCode.

The function uses a given keyboard event and the index you specified to return the KeySym from the list that corresponds to the KeyCode member in the XKeyPressedEvent or XKeyReleasedEvent structure. If no KeySym is defined for the KeyCode of the event, returns NoSymbol.

To obtain a KeySym for a specific KeyCode, use .

KeySym `XKeycodeToKeysym` Display *display KeyCode keycode int index

display

  Specifies the connection to the X server.

keycode

  Specifies the KeyCode.

index

  Specifies the element of KeyCode vector.

The function uses internal Xlib tables and returns the KeySym defined for the specified KeyCode and the element of the KeyCode vector. If no symbol is defined, returns NoSymbol.

To obtain a KeyCode for a key having a specific KeySym, use .

KeyCode `XKeysymToKeycode` Display *display KeySym keysym

display

  Specifies the connection to the X server.

keysym

  Specifies the KeySym that is to be searched for.

If the specified KeySym is not defined for any KeyCode, returns zero.

The mapping between KeyCodes and KeySyms is cached internal to Xlib. When this information is changed at the server, an Xlib function must be called to refresh the cache. To refresh the stored modifier and keymap information, use .

`XRefreshKeyboardMapping` XMappingEvent *event_map

event_map

  Specifies the mapping event that is to be used.

The function refreshes the stored modifier and keymap information. You usually call this function when a MappingNotify event with a request member of MappingKeyboard or MappingModifier occurs. The result is to update Xlib's knowledge of the keyboard.

To obtain the uppercase and lowercase forms of a KeySym, use .

void `XConvertCase` KeySym keysym KeySym *lower_return KeySym *upper_return

keysym

  Specifies the KeySym that is to be converted.

lower_return

  Returns the lowercase form of keysym, or keysym.

upper_return

  Returns the uppercase form of keysym, or keysym.

The function returns the uppercase and lowercase forms of the specified Keysym, if the KeySym is subject to case conversion; otherwise, the specified KeySym is returned to both lower_return and upper_return. Support for conversion of other than Latin and Cyrillic KeySyms is implementation-dependent.

KeySyms have string names as well as numeric codes. To convert the name of the KeySym to the KeySym code, use .

KeySym `XStringToKeysym` char *string

string

  Specifies the name of the KeySym that is to be converted.

Standard KeySym names are obtained from `<X11/keysymdef.h>` by removing the XK_ prefix from each name. KeySyms that are not part of the Xlib standard also may be obtained with this function. The set of KeySyms that are available in this manner and the mechanisms by which Xlib obtains them is implementation-dependent.

X11/keysymdef.h
Files <X11/keysymdef.h>
Headers <X11/keysymdef.h>

If the KeySym name is not in the Host Portable Character Encoding, the result is implementation-dependent. If the specified string does not match a valid KeySym, returns NoSymbol.

To convert a KeySym code to the name of the KeySym, use .

char *`XKeysymToString` KeySym keysym

keysym

  Specifies the KeySym that is to be converted.

The returned string is in a static area and must not be modified. The returned string is in the Host Portable Character Encoding. If the specified KeySym is not defined, returns a NULL.

### KeySym Classification Macros

You may want to test if a KeySym is, for example, on the keypad or on one of the function keys. You can use KeySym macros to perform the following tests.

IsCursorKey(keysym)

keysym

  Specifies the KeySym that is to be tested.

Returns True if the specified KeySym is a cursor key.

IsCursorKey

IsFunctionKey(keysym)

keysym

  Specifies the KeySym that is to be tested.

Returns True if the specified KeySym is a function key.

IsFunctionKey

IsKeypadKey(keysym)

keysym

  Specifies the KeySym that is to be tested.

Returns True if the specified KeySym is a standard keypad key.

IsKeypadKey

IsPrivateKeypadKey(keysym)

keysym

  Specifies the KeySym that is to be tested.

Returns True if the specified KeySym is a vendor-private keypad key.

IsPrivateKeypadKey

IsMiscFunctionKey(keysym)

keysym

  Specifies the KeySym that is to be tested.

Returns True if the specified KeySym is a miscellaneous function key.

IsMiscFunctionKey

IsModifierKey(keysym)

keysym

  Specifies the KeySym that is to be tested.

Returns True if the specified KeySym is a modifier key.

IsModifierKey

IsPFKey(keysym)

keysym

  Specifies the KeySym that is to be tested.

Returns True if the specified KeySym is a PF key.

IsPFKey
XLookupKeysym
XKeycodeToKeysym
XKeysymToKeycode
XRefreshKeyboardMapping
XConvertCase
XStringToKeysym
XKeysymToString

## Using Latin-1 Keyboard Event Functions

Chapter 13 describes internationalized text input facilities, but sometimes it is expedient to write an application that only deals with Latin-1 characters and ASCII controls, so Xlib provides a simple function for that purpose. handles the standard modifier semantics described in section 12.7. This function does not use any of the input method facilities described in chapter 13 and does not depend on the current locale.

To map a key event to an ISO Latin-1 string, use .

int `XLookupString` XKeyEvent *event_struct char *buffer_return int bytes_buffer KeySym *keysym_return XComposeStatus *status_in_out

event_struct

  Specifies the key event structure to be used. You can pass XKeyPressedEvent or XKeyReleasedEvent.

buffer_return

  Returns the translated characters.

bytes_buffer

  Specifies the length of the buffer. No more than bytes_buffer of translation are returned.

keysym_return

  Returns the KeySym computed from the event if this argument is not NULL.

status_in_out

  Specifies or returns the XComposeStatus structure or NULL.

The function translates a key event to a KeySym and a string. The KeySym is obtained by using the standard interpretation of the Shift, Lock, group, and numlock modifiers as defined in the X Protocol specification. If the KeySym has been rebound (see ), the bound string will be stored in the buffer. Otherwise, the KeySym is mapped, if possible, to an ISO Latin-1 character or (if the Control modifier is on) to an ASCII control character, and that character is stored in the buffer. returns the number of characters that are stored in the buffer.

If present (non-NULL), the XComposeStatus structure records the state, which is private to Xlib, that needs preservation across calls to to implement compose processing. The creation of XComposeStatus structures is implementation-dependent; a portable program must pass NULL for this argument.

depends on the cached keyboard information mentioned in the previous section, so it is necessary to use to keep this information up-to-date.

To rebind the meaning of a KeySym for , use .

`XRebindKeysym` Display *display KeySym keysym KeySym list[ ] int mod_count unsignedchar *string int num_bytes

display

  Specifies the connection to the X server.

keysym

  Specifies the KeySym that is to be rebound.

list

  Specifies the KeySyms to be used as modifiers.

mod_count

  Specifies the number of modifiers in the modifier list.

string

  Specifies the string that is copied and will be returned by .

num_bytes

  Specifies the number of bytes in the string argument.

The function can be used to rebind the meaning of a KeySym for the client. It does not redefine any key in the X server but merely provides an easy way for long strings to be attached to keys. returns this string when the appropriate set of modifier keys are pressed and when the KeySym would have been used for the translation. No text conversions are performed; the client is responsible for supplying appropriately encoded strings. Note that you can rebind a KeySym that may not exist.

XLookupString
XRebindKeysym

## Allocating Permanent Storage

To allocate some memory you will never give back, use . char *`Xpermalloc` unsigned int size

Xpermalloc

The function allocates storage that can never be freed for the life of the program. The memory is allocated with alignment for the C type double. This function may provide some performance and space savings over the standard operating system memory allocator.

## Parsing the Window Geometry

To parse standard window geometry strings, use .

Window determining location
XParseGeometry
int `XParseGeometry` char *parsestring int *x_return int *y_return unsigned int *width_return unsigned int *height_return

parsestring

  Specifies the string you want to parse.

x_return

y_return

  Return the x and y offsets.

width_return

height_return

  Return the width and height determined.

By convention, X applications use a standard string to indicate window size and placement. makes it easier to conform to this standard because it allows you to parse the standard window geometry. Specifically, this function lets you parse strings of the form:

    [=][<width>{xX}<height>][{+-}<xoffset>{+-}<yoffset>]

The fields map into the arguments associated with this function. (Items enclosed in < > are integers, items in [ ] are optional, and items enclosed in { } indicate ``choose one of.'' Note that the brackets should not appear in the actual string.) If the string is not in the Host Portable Character Encoding, the result is implementation-dependent.

The function returns a bitmask that indicates which of the four values (width, height, xoffset, and yoffset) were actually found in the string and whether the x and y values are negative. By convention, −0 is not equal to +0, because the user needs to be able to say ``position the window relative to the right or bottom edge.'' For each value found, the corresponding argument is updated. For each value not found, the argument is left unchanged. The bits are represented by XValue, YValue, WidthValue, HeightValue, XNegative, or YNegative and are defined in `<X11/Xutil.h>`. They will be set whenever one of the values is defined or one of the signs is set.

X11/Xutil.h
Files <X11/Xutil.h>
Headers <X11/Xutil.h>

If the function returns either the XValue or YValue flag, you should place the window at the requested position.

To construct a window's geometry information, use .

int `XWMGeometry` Display *display int screen char *user_geom char *def_geom unsigned int bwidth XSizeHints *hints int *x_return int *y_return int *width_return int *height_return int *gravity_return

display

  Specifies the connection to the X server.

screen

  Specifies the screen.

user_geom

  Specifies the user-specified geometry or NULL.

def_geom

  Specifies the application's default geometry or NULL.

bwidth

  Specifies the border width.

hints

  Specifies the size hints for the window in its normal state.

x_return

y_return

  Return the x and y offsets.

width_return

height_return

  Return the width and height determined.

gravity_return

  Returns the window gravity.

The function combines any geometry information (given in the format used by ) specified by the user and by the calling program with size hints (usually the ones to be stored in WM_NORMAL_HINTS) and returns the position, size, and gravity (NorthWestGravity, NorthEastGravity, SouthEastGravity, or SouthWestGravity) that describe the window. If the base size is not set in the XSizeHints structure, the minimum size is used if set. Otherwise, a base size of zero is assumed. If no minimum size is set in the hints structure, the base size is used. A mask (in the form returned by ) that describes which values came from the user specification and whether or not the position coordinates are relative to the right and bottom edges is returned. Note that these coordinates will have already been accounted for in the x_return and y_return values.

Note that invalid geometry specifications can cause a width or height of zero to be returned. The caller may pass the address of the hints win_gravity field as gravity_return to update the hints directly.

XWMGeometry

## Manipulating Regions

Regions are arbitrary sets of pixel locations. Xlib provides functions for manipulating regions. The opaque type Region is defined in `<X11/Xutil.h>`. Xlib provides functions that you can use to manipulate regions. This section discusses how to:

X11/Xutil.h
Files <X11/Xutil.h>
Headers <X11/Xutil.h>

- Create, copy, or destroy regions

- Move or shrink regions

- Compute with regions

- Determine if regions are empty or equal

- Locate a point or rectangle in a region

### Creating, Copying, or Destroying Regions

To create a new empty region, use `XCreateRegion`.

Region `XCreateRegion`

To generate a region from a polygon, use .

Region `XPolygonRegion` XPoint points[] int n int fill_rule

points

  Specifies an array of points.

n

  Specifies the number of points in the polygon.

fill_rule

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

The function returns a region for the polygon defined by the points array. For an explanation of fill_rule, see .

To set the clip-mask of a GC to a region, use .

`XSetRegion` Display *display GC gc Region r

display

  Specifies the connection to the X server.

gc

  Specifies the GC.

r

  Specifies the region.

The function sets the clip-mask in the GC to the specified region. The region is specified relative to the drawable's origin. The resulting GC clip origin is implementation-dependent. Once it is set in the GC, the region can be destroyed.

To deallocate the storage associated with a specified region, use .

`XDestroyRegion` Region r

r

  Specifies the region.

XPolygonRegion
XSetRegion
XDestroyRegion

### Moving or Shrinking Regions

To move a region by a specified amount, use .

`XOffsetRegion` Region r int dx int dy

r

  Specifies the region.

dx

dy

  Specify the x and y coordinates, which define the amount you want to move the specified region.

To reduce a region by a specified amount, use .

`XShrinkRegion` Region r int dx int dy

r

  Specifies the region.

dx

dy

  Specify the x and y coordinates, which define the amount you want to shrink the specified region.

Positive values shrink the size of the region, and negative values expand the region.

XOffsetRegion
XShrinkRegion

### Computing with Regions

To generate the smallest rectangle enclosing a region, use .

`XClipBox` Region r XRectangle *rect_return

r

  Specifies the region.

rect_return

  Returns the smallest enclosing rectangle.

The function returns the smallest rectangle enclosing the specified region.

To compute the intersection of two regions, use .

`XIntersectRegion` Region sra Region srb Region dr_return

sra

srb

  Specify the two regions with which you want to perform the computation.

dr_return

  Returns the result of the computation.

To compute the union of two regions, use .

`XUnionRegion` Region sra Region srb Region dr_return

sra

srb

  Specify the two regions with which you want to perform the computation.

dr_return

  Returns the result of the computation.

To create a union of a source region and a rectangle, use .

`XUnionRectWithRegion` XRectangle *rectangle Region src_region Region dest_region_return

rectangle

  Specifies the rectangle.

src_region

  Specifies the source region to be used.

dest_region_return

  Returns the destination region.

The function updates the destination region from a union of the specified rectangle and the specified source region.

To subtract two regions, use .

`XSubtractRegion` Region sra Region srb Region dr_return

sra

srb

  Specify the two regions with which you want to perform the computation.

dr_return

  Returns the result of the computation.

The function subtracts srb from sra and stores the results in dr_return.

To calculate the difference between the union and intersection of two regions, use .

`XXorRegion` Region sra Region srb Region dr_return

sra

srb

  Specify the two regions with which you want to perform the computation.

dr_return

  Returns the result of the computation.

XClipBox
XIntersectRegion
XUnionRegion
XUnionRectWithRegion
XSubtractRegion
XXorRegion

### Determining if Regions Are Empty or Equal

To determine if the specified region is empty, use .

Bool `XEmptyRegion` Region r

r

  Specifies the region.

The function returns True if the region is empty.

To determine if two regions have the same offset, size, and shape, use .

Bool `XEqualRegion` Region r1 Region r2

r1

r2

  Specify the two regions.

The function returns True if the two regions have the same offset, size, and shape.

XEmptyRegion
XEqualRegion

### Locating a Point or a Rectangle in a Region

To determine if a specified point resides in a specified region, use .

Bool `XPointInRegion` Region r int x int y

r

  Specifies the region.

x

y

  Specify the x and y coordinates, which define the point.

The function returns True if the point (x, y) is contained in the region r.

To determine if a specified rectangle is inside a region, use .

int `XRectInRegion` Region r int x int y unsigned int width unsigned int height

r

  Specifies the region.

x

y

  Specify the x and y coordinates, which define the coordinates of the upper-left corner of the rectangle.

width

height

  Specify the width and height, which define the rectangle.

The function returns RectangleIn if the rectangle is entirely in the specified region, RectangleOut if the rectangle is entirely out of the specified region, and RectanglePart if the rectangle is partially in the specified region.

XPointInRegion
XRectInRegion

## Using Cut Buffers

Xlib provides functions to manipulate cut buffers, a very simple form of cut-and-paste inter-client communication. Selections are a much more powerful and useful mechanism for interchanging data between client (see section 4.5) and generally should be used instead of cut buffers.

Cut Buffers

Cut buffers are implemented as properties on the first root window of the display. The buffers can only contain text, in the STRING encoding. The text encoding is not changed by Xlib when fetching or storing. Eight buffers are provided and can be accessed as a ring or as explicit buffers (numbered 0 through 7).

To store data in cut buffer 0, use .

`XStoreBytes` Display *display char *bytes int nbytes

display

  Specifies the connection to the X server.

bytes

  Specifies the bytes, which are not necessarily ASCII or null-terminated.

nbytes

  Specifies the number of bytes to be stored.

The data can have embedded null characters and need not be null-terminated. The cut buffer's contents can be retrieved later by any client calling .

can generate a BadAlloc error.

To store data in a specified cut buffer, use .

`XStoreBuffer` Display *display char *bytes int nbytes int buffer

display

  Specifies the connection to the X server.

bytes

  Specifies the bytes, which are not necessarily ASCII or null-terminated.

nbytes

  Specifies the number of bytes to be stored.

buffer

  Specifies the buffer in which you want to store the bytes.

If an invalid buffer is specified, the call has no effect. The data can have embedded null characters and need not be null-terminated.

can generate a BadAlloc error.

To return data from cut buffer 0, use .

char *`XFetchBytes` Display *display int *nbytes_return

display

  Specifies the connection to the X server.

nbytes_return

  Returns the number of bytes in the buffer.

The function returns the number of bytes in the nbytes_return argument, if the buffer contains data. Otherwise, the function returns NULL and sets nbytes to 0. The appropriate amount of storage is allocated and the pointer returned. The client must free this storage when finished with it by calling .

To return data from a specified cut buffer, use .

char *`XFetchBuffer` Display *display int *nbytes_return int buffer

display

  Specifies the connection to the X server.

nbytes_return

  Returns the number of bytes in the buffer.

buffer

  Specifies the buffer from which you want the stored data returned.

The function returns zero to the nbytes_return argument if there is no data in the buffer or if an invalid buffer is specified.

To rotate the cut buffers, use .

`XRotateBuffers` Display *display int rotate

display

  Specifies the connection to the X server.

rotate

  Specifies how much to rotate the cut buffers.

The function rotates the cut buffers, such that buffer 0 becomes buffer n, buffer 1 becomes n + 1 mod 8, and so on. This cut buffer numbering is global to the display. Note that generates BadMatch errors if any of the eight buffers have not been created.

XStoreBytes
XStoreBuffer
XFetchBytes
XFetchBuffer
XRotateBuffers

## Determining the Appropriate Visual Type

A single display can support multiple screens. Each screen can have several different visual types supported at different depths. You can use the functions described in this section to determine which visual to use for your application.

The functions in this section use the visual information masks and the XVisualInfo structure, which is defined in `<X11/Xutil.h>` and contains:

X11/Xutil.h
Files <X11/Xutil.h>
Headers <X11/Xutil.h>

    /* Visual information mask bits */

    #define   VisualNoMask                 0x0
    #define   VisualIDMask                 0x1
    #define   VisualScreenMask             0x2
    #define   VisualDepthMask              0x4
    #define   VisualClassMask              0x8
    #define   VisualRedMaskMask            0x10
    #define   VisualGreenMaskMask          0x20
    #define   VisualBlueMaskMask           0x40
    #define   VisualColormapSizeMask       0x80
    #define   VisualBitsPerRGBMask         0x100
    #define   VisualAllMask                0x1FF

    /* Values */

    typedef struct {
         Visual *visual;
         VisualID visualid;
         int screen;
         unsigned int depth;
         int class;
         unsigned long red_mask;
         unsigned long green_mask;
         unsigned long blue_mask;
         int colormap_size;
         int bits_per_rgb;
    } XVisualInfo;

To obtain a list of visual information structures that match a specified template, use .

XVisualInfo *`XGetVisualInfo` Display *display long vinfo_mask XVisualInfo *vinfo_template int *nitems_return

display

  Specifies the connection to the X server.

vinfo_mask

  Specifies the visual mask value.

vinfo_template

  Specifies the visual attributes that are to be used in matching the visual structures.

nitems_return

  Returns the number of matching visual structures.

The function returns a list of visual structures that have attributes equal to the attributes specified by vinfo_template. If no visual structures match the template using the specified vinfo_mask, returns a NULL. To free the data returned by this function, use .

To obtain the visual information that matches the specified depth and class of the screen, use .

Status `XMatchVisualInfo` Display *display int screen int depth int class XVisualInfo *vinfo_return

display

  Specifies the connection to the X server.

screen

  Specifies the screen.

depth

  Specifies the depth of the screen.

class

  Specifies the class of the screen.

vinfo_return

  Returns the matched visual information.

The function returns the visual information for a visual that matches the specified depth and class for a screen. Because multiple visuals that match the specified depth and class can exist, the exact visual chosen is undefined. If a visual is found, returns nonzero and the information on the visual to vinfo_return. Otherwise, when a visual is not found, returns zero.

XGetVisualInfo
XMatchVisualInfo

## Manipulating Images

Xlib provides several functions that perform basic operations on images. All operations on images are defined using an XImage structure, as defined in `<X11/Xlib.h>`. Because the number of different types of image formats can be very large, this hides details of image storage properly from applications.

X11/Xlib.h
Files <X11/Xlib.h>
Headers <X11/Xlib.h>

This section describes the functions for generic operations on images. Manufacturers can provide very fast implementations of these for the formats frequently encountered on their hardware. These functions are neither sufficient nor desirable to use for general image processing. Rather, they are here to provide minimal functions on screen format images. The basic operations for getting and putting images are and .

Note that no functions have been defined, as yet, to read and write images to and from disk files.

The XImage structure describes an image as it exists in the client's memory. The user can request that some of the members such as height, width, and xoffset be changed when the image is sent to the server. Note that bytes_per_line in concert with offset can be used to extract a subset of the image. Other members (for example, byte order, bitmap_unit, and so forth) are characteristics of both the image and the server. If these members differ between the image and the server, makes the appropriate conversions. The first byte of the first line of plane n must be located at the address (data + (n * height * bytes_per_line)). For a description of the XImage structure, see section 8.7.

To allocate an XImage structure and initialize it with image format values from a display, use .

XImage *`XCreateImage` Display *display Visual *visual unsigned int depth int format int offset char *data unsigned int width unsigned int height int bitmap_pad int bytes_per_line

display

  Specifies the connection to the X server.

visual

  Specifies the Visual structure.

depth

  Specifies the depth of the image.

format

  Specifies the format for the image. You can pass XYBitmap, XYPixmap, or ZPixmap.

offset

  Specifies the number of pixels to ignore at the beginning of the scanline.

data

  Specifies the image data.

width

  Specifies the width of the image, in pixels.

height

  Specifies the height of the image, in pixels.

bitmap_pad

  Specifies the quantum of a scanline (8, 16, or 32). In other words, the start of one scanline is separated in client memory from the start of the next scanline by an integer multiple of this many bits.

bytes_per_line

  Specifies the number of bytes in the client image between the start of one scanline and the start of the next.

The function allocates the memory needed for an XImage structure for the specified display but does not allocate space for the image itself. Rather, it initializes the structure byte-order, bit-order, and bitmap-unit values from the display and returns a pointer to the XImage structure. The red, green, and blue mask values are defined for Z format images only and are derived from the Visual structure passed in. Other values also are passed in. The offset permits the rapid displaying of the image without requiring each scanline to be shifted into position. If you pass a zero value in bytes_per_line, Xlib assumes that the scanlines are contiguous in memory and calculates the value of bytes_per_line itself.

Note that when the image is created using , , or , the destroy procedure that the function calls frees both the image structure and the data pointed to by the image structure.

The basic functions used to get a pixel, set a pixel, create a subimage, and add a constant value to an image are defined in the image object. The functions in this section are really macro invocations of the functions in the image object and are defined in `<X11/Xutil.h>`.

X11/Xutil.h
Files <X11/Xutil.h>
Headers <X11/Xutil.h>

To obtain a pixel value in an image, use .

unsigned long `XGetPixel` XImage *ximage int x int y

ximage

  Specifies the image.

x

y

  Specify the x and y coordinates.

The function returns the specified pixel from the named image. The pixel value is returned in normalized format (that is, the least significant byte of the long is the least significant byte of the pixel). The image must contain the x and y coordinates.

To set a pixel value in an image, use .

`XPutPixel` XImage *ximage int x int y unsigned long pixel

ximage

  Specifies the image.

x

y

  Specify the x and y coordinates.

pixel

  Specifies the new pixel value.

The function overwrites the pixel in the named image with the specified pixel value. The input pixel value must be in normalized format (that is, the least significant byte of the long is the least significant byte of the pixel). The image must contain the x and y coordinates.

To create a subimage, use .

XImage *`XSubImage` XImage *ximage int x int y unsigned int subimage_width unsigned int subimage_height

ximage

  Specifies the image.

x

y

  Specify the x and y coordinates.

subimage_width

  Specifies the width of the new subimage, in pixels.

subimage_height

  Specifies the height of the new subimage, in pixels.

The function creates a new image that is a subsection of an existing one. It allocates the memory necessary for the new XImage structure and returns a pointer to the new image. The data is copied from the source image, and the image must contain the rectangle defined by x, y, subimage_width, and subimage_height.

To increment each pixel in an image by a constant value, use .

`XAddPixel` XImage *ximage long value

ximage

  Specifies the image.

value

  Specifies the constant value that is to be added.

The function adds a constant value to every pixel in an image. It is useful when you have a base pixel value from allocating color resources and need to manipulate the image to that form.

To deallocate the memory allocated in a previous call to , use .

`XDestroyImage` XImage *ximage

ximage

  Specifies the image.

The function deallocates the memory associated with the XImage structure.

Note that when the image is created using , , or , the destroy procedure that this macro calls frees both the image structure and the data pointed to by the image structure.

XCreateImage
XGetPixel
XPutPixel
XSubImage
XAddPixel
XDestroyImage

## Manipulating Bitmaps

Xlib provides functions that you can use to read a bitmap from a file, save a bitmap to a file, or create a bitmap. This section describes those functions that transfer bitmaps to and from the client's file system, thus allowing their reuse in a later connection (for example, from an entirely different client or to a different display or server).

The X version 11 bitmap file format is:

    #define name_width width
    #define name_height height
    #define name_x_hot x
    #define name_y_hot y
    static unsigned char name_bits[] = { 0xNN,... }

The lines for the variables ending with _x_hot and _y_hot suffixes are optional because they are present only if a hotspot has been defined for this bitmap. The lines for the other variables are required. The word ``unsigned'' is optional; that is, the type of the _bits array can be ``char'' or ``unsigned char''. The _bits array must be large enough to contain the size bitmap. The bitmap unit is 8.

To read a bitmap from a file and store it in a pixmap, use .

int `XReadBitmapFile` Display *display Drawable d char *filename unsigned int *width_return unsigned int *height_return Pixmap *bitmap_return int *x_hot_return int *y_hot_return

display

  Specifies the connection to the X server.

d

  Specifies the drawable that indicates the screen.

filename

  Specifies the file name to use. The format of the file name is operating-system dependent.

width_return

height_return

  Return the width and height values of the read in bitmap file.

bitmap_return

  Returns the bitmap that is created.

x_hot_return

y_hot_return

  Return the hotspot coordinates.

The function reads in a file containing a bitmap. The file is parsed in the encoding of the current locale. The ability to read other than the standard format is implementation-dependent. If the file cannot be opened, returns BitmapOpenFailed. If the file can be opened but does not contain valid bitmap data, it returns BitmapFileInvalid. If insufficient working storage is allocated, it returns BitmapNoMemory. If the file is readable and valid, it returns BitmapSuccess.

returns the bitmap's height and width, as read from the file, to width_return and height_return. It then creates a pixmap of the appropriate size, reads the bitmap data from the file into the pixmap, and assigns the pixmap to the caller's variable bitmap. The caller must free the bitmap using when finished. If name_x_hot and name_y_hot exist, returns them to x_hot_return and y_hot_return; otherwise, it returns −1,−1.

can generate BadAlloc, BadDrawable, and BadGC errors.

To read a bitmap from a file and return it as data, use .

int `XReadBitmapFileData` char *filename unsigned int *width_return unsigned int *height_return unsignedchar *data_return int *x_hot_return int *y_hot_return

filename

  Specifies the file name to use. The format of the file name is operating-system dependent.

width_return

height_return

  Return the width and height values of the read in bitmap file.

data_return

  Returns the bitmap data.

x_hot_return

y_hot_return

  Return the hotspot coordinates.

The function reads in a file containing a bitmap, in the same manner as , but returns the data directly rather than creating a pixmap in the server. The bitmap data is returned in data_return; the client must free this storage when finished with it by calling . The status and other return values are the same as for .

To write out a bitmap from a pixmap to a file, use .

int `XWriteBitmapFile` Display *display char *filename Pixmap bitmap unsigned int width unsigned int height int x_hot int y_hot

display

  Specifies the connection to the X server.

filename

  Specifies the file name to use. The format of the file name is operating-system dependent.

bitmap

  Specifies the bitmap.

width

height

  Specify the width and height.

x_hot

y_hot

  Specify where to place the hotspot coordinates (or −1,−1 if none are present) in the file.

The function writes a bitmap out to a file in the X Version 11 format. The name used in the output file is derived from the file name by deleting the directory prefix. The file is written in the encoding of the current locale. If the file cannot be opened for writing, it returns BitmapOpenFailed. If insufficient memory is allocated, returns BitmapNoMemory; otherwise, on no error, it returns BitmapSuccess. If x_hot and y_hot are not −1, −1, writes them out as the hotspot coordinates for the bitmap.

can generate BadDrawable and BadMatch errors.

To create a pixmap and then store bitmap-format data into it, use .

Pixmap `XCreatePixmapFromBitmapData` Display *display Drawable d char *data unsigned int width unsigned int height unsigned long fg unsigned long bg unsigned int depth

display

  Specifies the connection to the X server.

d

  Specifies the drawable that indicates the screen.

data

  Specifies the data in bitmap format.

width

height

  Specify the width and height.

fg

bg

  Specify the foreground and background pixel values to use.

depth

  Specifies the depth of the pixmap.

The function creates a pixmap of the given depth and then does a bitmap-format of the data into it. The depth must be supported by the screen of the specified drawable, or a BadMatch error results.

can generate BadAlloc, BadDrawable, BadGC, and BadValue errors.

To include a bitmap written out by in a program directly, as opposed to reading it in every time at run time, use .

XWriteBitmapFile
Pixmap `XCreateBitmapFromData` Display *display Drawable d char *data unsigned int width unsigned int height

display

  Specifies the connection to the X server.

d

  Specifies the drawable that indicates the screen.

data

  Specifies the location of the bitmap data.

width

height

  Specify the width and height.

The function allows you to include in your C program (using `#include`) a bitmap file that was written out by (X version 11 format only) without reading in the bitmap file. The following example creates a gray bitmap:

    #include "gray.bitmap"

    Pixmap bitmap;
    bitmap = XCreateBitmapFromData(display, window, gray_bits, gray_width, gray_height);

If insufficient working storage was allocated, returns None. It is your responsibility to free the bitmap using when finished.

can generate BadAlloc and BadGC errors.

XReadBitmapFile
XReadBitmapFileData
XWriteBitmapFile
XCreatePixmapFromBitmapData
XCreateBitmapFromData

## Using the Context Manager

The context manager provides a way of associating data with an X resource ID (mostly typically a window) in your program. Note that this is local to your program; the data is not stored in the server on a property list. Any amount of data in any number of pieces can be associated with a resource ID, and each piece of data has a type associated with it. The context manager requires knowledge of the resource ID and type to store or retrieve data.

Essentially, the context manager can be viewed as a two-dimensional, sparse array: one dimension is subscripted by the X resource ID and the other by a context type field. Each entry in the array contains a pointer to the data. Xlib provides context management functions with which you can save data values, get data values, delete entries, and create a unique context type. The symbols used are in `<X11/Xutil.h>`.

X11/Xutil.h
Files <X11/Xutil.h>
Headers <X11/Xutil.h>

To save a data value that corresponds to a resource ID and context type, use .

int `XSaveContext` Display *display XID rid XContext context XPointer data

display

  Specifies the connection to the X server.

rid

  Specifies the resource ID with which the data is associated.

context

  Specifies the context type to which the data belongs.

data

  Specifies the data to be associated with the window and type.

If an entry with the specified resource ID and type already exists, overrides it with the specified context. The function returns a nonzero error code if an error has occurred and zero otherwise. Possible errors are XCNOMEM (out of memory).

To get the data associated with a resource ID and type, use .

int `XFindContext` Display *display XID rid XContext context XPointer *data_return

display

  Specifies the connection to the X server.

rid

  Specifies the resource ID with which the data is associated.

context

  Specifies the context type to which the data belongs.

data_return

  Returns the data.

Because it is a return value, the data is a pointer. The function returns a nonzero error code if an error has occurred and zero otherwise. Possible errors are XCNOENT (context-not-found).

To delete an entry for a given resource ID and type, use .

int `XDeleteContext` Display *display XID rid XContext context

display

  Specifies the connection to the X server.

rid

  Specifies the resource ID with which the data is associated.

context

  Specifies the context type to which the data belongs.

The function deletes the entry for the given resource ID and type from the data structure. This function returns the same error codes that returns if called with the same arguments. does not free the data whose address was saved.

To create a unique context type that may be used in subsequent calls to and , use `XUniqueContext`.

XContext `XUniqueContext`
XSaveContext
XFindContext
XDeleteContext