Page: 1 2 3 4 5 6 7 8 9 10 11 12 13

Chapter 16


Application Utility Functions

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

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.

16.1. 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 XLookupKeysym.

KeySym XLookupKeysym(key_event, index)
    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 XLookupKeysym 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, XLookupKeysym returns NoSymbol.

To obtain a KeySym for a specific KeyCode, use XKeycodeToKeysym.

KeySym XKeycodeToKeysym(display, keycode, index)
    Display *display;
    KeyCode keycode;
    int index;
display
Specifies the connection to the X server.
keycode
Specities the KeyCode.
index
Specifies the element of KeyCode vector.

The XKeycodeToKeysym 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, XKeycodeToKeysym returns NoSymbol.

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

KeyCode XKeysymToKeycode(display, keysym)
    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, XKeysymToKeycode 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.

XRefreshKeyboardMapping(event_map)
    XMappingEvent *event_map;
event_map
Specifies the mapping event that is to be used.

The XRefreshKeyboardMapping 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 XConvertCase.

void XConvertCase(keysym, lower_return, upper_return)
    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 XConvertCase 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. Suppon for conversion of other than Latin and Cyrillic KeySyms is implementaion dependent.

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

KeySym XStringToKeysym (string)
    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.

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, XStringToKeysym returns NoSymbol.

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

char *XKeysymToString (keysym)
    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, XKeysymToString returns a NULL.

Home


16.1.1. KeySym Classification Macros

You may want to test if a KeySym is, for example, on the keypad or on one of the funcion 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.

IsFunctionKey(keysym)
keysym
Specifies the KeySym that is to be tested.

Returns True if the specified KeySym is a function key.

IsKeypadKey(keysym)
keysym
Specifies the KeySym that is to be tested.

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

IsPrivateKeypadKey(keysym)
keysym
Specifies the KeySym that is to be tested.

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

IsMiscFunctionKey(keysym)
keysym
Specifies the KeySym that is to be tested.

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

IsModifierKey(keysym)
keysym
Specifies the KeySym that is to be tested.

Returns True if the specified KeySym is a modifier key.

IsPFKey(keysym)
keysym
Specifies the KeySym that is to be tested.

Returns True if the specified KeySym is a PF key.

Home


16.2. 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. XLookupString 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 XLookupString.

int XLookupString(event_struct, buffer_return, bytes_buffer, keysym_return, status_in_out)
    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.
buffier_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 XLookupString 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 XRebindKeysym), 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. XLookupString 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 XLookupString to implement compose processing. The creation of XComposeStatus structures is implementation dependent; a portable program must pass NULL for this argument.

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

To rebind the meaning of a KeySym for XLookupString, use XRebindKeysym.

XRebindKeysym(display, keysym, list, mod_count, string, num_bytes)
    Display *display;
    KeySym keysym;
    KeySym list[];
    int mod_count;
    unsigned char *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 XLookupString.
num_bytes
Specifies the number of bytes in the string argument.

The XRebindKeysym 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. XLookupString 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.

Home


16.3. Allocating Permanent Storage

To allocate some memory you will never give back, use Xpermalloc.

char *Xpermalloc(size)
    unsigned int size;

The Xpermalloc 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.

Home


16.4. Parsing the Window Geometry

To parse standard window geometry strings, use XParseGeometry.

int XParseGeometry(parsestring, x_return, y_return, width_return, height_return)
    char *parsestring;
    int *x_return, *y_relurn;
    unsigned int *width_return, *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. XParseGeometry 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>] [{+- }<xoffser>{+-}<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 XParseGeometry 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.

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 XWMGeometry.

int XWMGeometry (display, screen, user_geom, def_geom, bwidth, hints, x_return, y_return,
	 width_return, height_return, gravity_return)
    Display *display;
    int screen;
    char *user_geom;
    char *def_geom;
    unsigned int bwidth;
    XSizeHints *hints;
    int *x_return, *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 XWMGeometry function combines any geometry information (given in the format used by XParseGeometry) 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 XParseGeometry) 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.

Home


16.5. 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:

16.5.1. Creating, Copying, or Destroying Regions

To create a new empty region, use XCreateRegion.

Region XCreateRegion()

To generate a region from a polygon, use XPolygonRegion.

Region XPolygonRegion(points, n, fill_rule)
    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 XPolygonRegion function returns a region for the polygon defined by the points array. For an explanation of fill_rule, see XCreateGC.

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

XSetRegion(display, gc, r)
    Display *dispiay;
    GC gc;
    Region r;
display
Specifies the connection to the X server.
gc
Specifies the GC.
r
Specifies the region.

The XSetRegion 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.

XDestroyRegion(r)
    Region r;
r
Specifies the region.

Home


16.5.2. Moving or Shrinking Regions

To move a region by a specified amount, use XOffsetRegion.

XOffsetRegion(r, dx, dy)
    Region r;
    int dx, 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.

XShrinkRegion(r, dx, dy)
    Region r;
    int dx, 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.

16.5.3. Computing with Regions

To generate the smallest rectangle enclosing a region, use XClipBox.

XClipBox(r, rect_return)
    Region r;
    XRectangle *rect_return;
r
Specifies the region.
rect_return
Returns the smallest enclosing rectangle.

The XClipBox function returns the smallest rectangle enclosing the specified region.

To compute the intersection of two regions, use XIntersectRegion.

XIntersectRegion(sra, srb, dr_return)
    Region sra, srb, 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.

XUnionRegion(sra, srb, dr_return)
    Region sra, srb, 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.

XUnionRectWithRegion(rectangle, src_region, dest_region_return)
    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 XUnionRectWithRegion function updates the destination region from a union of the specified rectangle and the specified source region.

To subtract two regions, use XSubtractRegion.

XSubtractRegion(sra, srb, dr_return)
    Region sra, srb, 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 XSubtractRegion 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.

XXorRegion(sra, srb, dr_return)
    Region sra, srb, dr_return;
sra, srb
Specify the two regions with which you want to perform the computation.
dr_return
Returns the result of the computation.

Home


16.5.4. Determining if Regions Are Empty or Equal

To determine if the specified region is empty, use XEmptyRegion.

Bool XEmptyRegion(r)
    Region r;
r
Specifies the region.

The XEmptyRegion function returns True if the region is empty.

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

Bool XEqualRegion(r1, r2)
    Region r1, r2;
r1, r2
Specify the two regions.

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

16.5.5. Locating a Point or a Rectangle in a Region

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

Bool XPointInRegion(r, x, y)
    Region r;
    int x, y;
r
Specifies the region.
x, y
Specify the x and y coordinates, which define the point.

The XPointInRegion 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 XRectInRegion.

int XRectlnRegion(r, x, y, width, height)
    Region r;
    int x, y;
    unsigned int width, 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 XRectInRegion 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.

Home


16.6. 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 clients (see section 4.5), and generally should be used instead of 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.

XStoreBytes(display, bytes, nbytes)
    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 XFetchBytes.

XStoreBytes can generate a BadAlloc error.

To store data in a specified cut buffer, use XStoreBuffer.

XStoreBuffer(display, bytes, nbytes, buffer)
    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.

XStoreBuffer can generate a BadAlloc error.

To return data from cut buffer 0, use XFetchBytes.

char *XFetchBytes(display, nbytes_return)
    Display *display;
    int *nbytes_return;
display
Specifies the connection to the X server.
nbytes_return
Returns the number of bytes in the buffer.

The XFetchBytes 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 XFree.

To return data from a specified cut buffer, use XFetchBuffer.

char *XFetchBuffer(display, nbytes_return, buffer)
    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 XFetchBuffer 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.

XRotateBuffers(display, rotate )
    Display *display;
    int rotate;
display
Specifies the connection to the X server.
rotate
Specifies how much to rotate the cut buffers.

The XRotateBuffers 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 XRotateBuffers generates BadMatch errors if any of the eight buffers have not been created.

Home


16.7. 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:

/* Visual information mask bits */
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
VisualNoMask
VisualIDMask
VisualScreenMask
VisualDepthMask
VisualClassMask
VisualRedMaskMask
VisualGreenMaskMask
VisualBlueMaskMask
VisualColormapSizeMask
VisualBitsPerRGBMask
VisualAllMask
0x0
0x1
0x2
0x4
0x8
0x10
0x20
0x40
0x80
0x100
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 math a specified template, use XGetVisualInfo.

XVisualInfo *XGetVisualInfo(display, vinfo_mask, vinfo_template, nitems_ return)
    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 XGetVisualInfo 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, XGetVisualInfo returns a NULL. To free the data returned by this function use XFree.

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

Status XMatchVisualInfo(display, screen, depth, class, vinfo_return)
    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 XMatchVisualInfo 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, XMatchVisualInfo returns nonzero and the information on the visual to vinfo_return. Otherwise, when a visual is not found, XMatchVisualInfo returns zero.

Home


16.8. 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.

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 XGetImage and XPutImage.

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, XPutImage 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 XCreateImage.

XImage *XCreateImage(display, visual, depth, formar, offset, data, width, height, bitmap_pad,
          bytes_per_line )
    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 XCreateImage 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 XCreateImage, XGetImage, or XSubImage, the destroy procedure that the XDestroyImage 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>.

To obtain a pixel value in an image, use XGetPixel.

unsigned long XGetPixel(ximage, x, y)
    XImage *ximage;
    int x;
    int y;
ximage
Specifies the image.
x, y
Specify the x and y coordinates.

The XGetPixel 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.

XPutPixel(ximage, x, y, pixel)
    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 XPutPixel 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 XSubImage.

XImage *XSubImage(ximage, x, y, subimage_width, subimage_height)
    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 XSubImage 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.

XAddPixel(ximage, value)
    XImage *ximage;
    long value;
ximage
Specifies the image.
value
Specifies the constant value that is to be added.

The XAddPixel 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 XCreateImage, use XDestroyImage.

XDestroyImage (ximage)
    XImage *ximage;
ximage
Specifies the image.

The XDestroyImage function deallocates the memory associated with the XImage structure.

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

Home


16.9. 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 eight.

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

int XReadBitmapFile(display, d, filename, width_return, height_return, bitmap_return, x_hot_return,
            y_hot_return)
    Display *display;
    Drawable d;
    char *filename;
    unsigned int *width_return, *height_return;
    Pixmap *bitmap_return;
    int *x_hot_return, *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.

4A NAME="BitmapSuccess__01"> The XReadBitmapFile 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, XReadBitmapFile 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.

XReadBitmapFile 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 XFreePixmap when finished. If name_x_hot and name_y_hot exist, XReadBitmapFile returns them to x_hot_return and y_hot_return; otherwise, it returns -1,-1.

XReadBitmapFile can generate BadAlloc, BadDrawable, and BadGC errors.

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

int XReadBitmapFileData(filename, width_return, height_return, data _return, x_hot_return,
	y_hot_return)
    char *filename;
    unsigned int *width_return, *height_return;
    unsigned char *data_return;
    int *x_hot_return, *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 XReadBitmapFileData function reads in a file containing a bitmap, in the same manner as XReadBitmapFile, 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 XFree. The status and other return values are the same as for XReadBitmapFile.

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

int XWriteBitmapFile(display, filename, bitmap, width, height, x_hot, y_hot)
    Display *display;
    char *filename;
    Pixmap bitmap;
    unsigned int width, height;
    int x_hot, 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 XWriteBitmapFile 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, XWriteBitmapFile returns BitmapNoMemory; otherwise, on no error, it returns BitmapSuccess. If x_hot and y_hot are not -1, -1, XWriteBitmapFile writes them out as the hotspot coordinates for the bitmap.

XWriteBitmapFile can generate BadDrawable and BadMatch errors.

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

Pixmap XCreatePixmapFromBitmapData(display, d, data, width, height,fg, bg, depth)
    Display *display;
    Drawable d;
    char *data;
    unsigned int width, height;
    unsigned long fg, 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 XCreatePixmapFromBitmapData function creates a pixmap of the given depth and then does a bitmap-format XPutImage of the data into it. The depth must be supported by the screen of the specified drawable, or a BadMatch error results.

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

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

Pixmap XCreateBitmapFromData(display, d, data, width, height)
    Display *display;
    Drawable d;
    char *data;
    unsigned int width, 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 XCreateBitmapFromData function allows you to include in your C program (using #include) a bitmap file that was written out by XWriteBitmapFile (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, XCreateBitmapFromData returns None. It is your responsibility to free the bitmap using XFreePixmap when finished.

XCreateBitmapFromData can generate a BadAlloc and BadGC errors.

Home


16.10. 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 prograrm; 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>.

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

int XSaveContext(display, rid, context, data)
    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, XSaveContext overrides it with the specified context. The XSaveContext 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 XFindContext.

int XFindContext(display, rid, context, data_return)
    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 XFindContext function returns a nonzero error code if an error has occurred and zero otherwise. Possible errors are XCNOENT (contextnot-found).

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

int XDeleteContext(display, rid, context)
    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 XDeleteContext function deletes the entry for the given resource ID and type from the data structure. This function returns the same error codes that XFindContext returns if called with the same arguments. XDeleteContext does not free the data whose address was saved.

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

XContext XUniqueContext()

Home

Contents Previous Chapter Next Chapter