Xlib

From ArticleWorld


Xlib is a C library that provides support for X Window System protocol client applications, allowing the programmer to concentrate on the operations, regardless of the actual implementation of the protocol. It is a standard library on most Unix system, and is several years old (appeared in 1985). Although some consider it to be old and useless (and trying to replace it with XCB), it is still widely used, although mostly not directly, but as a base for more high-level libraries.

Data types

Xlib implements the basic data types defined by the X Windows protocol: Display, Windows, Pixmap etc. These are complete abstractions over the underlying hardware and protocol, allowing programs to be ported quite easily.

Xlib also implements an event queue. The programming model is asynchronous, meaning that the requests sent to the server are queued and processed as possible, and the requests can be sent and received at any time. However, although sending requests is asynchronous, applications using Xlib must explicitly call Xlib functions to access the data in the event queue.

Limitations

Although Xlib provides a full implementation of the X Window protocol, it does have its limitations. Xlib does not provide its own GUI widget set, meaning that, if the programmer wants to have a usable interface, he or she will often have to resort to another library.

Xlib is also quite large and very verbose with the programmer, making it difficult to use for larger programs.

Example

The following program is demonstrating the Xlib capabilities. It allows the user to quickly position the mouse in the middle of the screen, thus demonstrating capabilities such as quick and transparent interaction with peripherals (mouse, keyboard), and full transparency on computers with more than one monitor (which is actually very common on Unix systems, since this has been supported ever since the late '80s).


#include <stdio.h>
#include <unistd.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>

int main(int argc, char *argv[]) {
    Display *display;
    Screen *screen;
    Window win;
    int head=0;
    int x,y;

    if(argc == 2) {
        head = atoi(argv[1]);
    }
    display = XOpenDisplay(NULL);
    if(!display) {
        printf("Couldn't open display %s\n",display);
    }
    screen = ScreenOfDisplay(display,head);
    x = WidthOfScreen(screen) / 2;
    y = HeightOfScreen(screen) / 2;
    win = RootWindowOfScreen(screen);
    XWarpPointer(display,None,win,0,0,0,0,x,y);
    XSync(display,0);
    return(0);
}