By way of introduction
For this episode, you will need a compiler (gcc will do nicely), an X server running on either a local or a remote machine (with permission to connect to it), and the Xlib library along with its header files. And, of course, your favorite text editor (Emacs, right?), a terminal emulator, and a willingness to experiment.
Ladies and gentlemen, today we are going to write, build, and run our first graphical application, which will:
- open a window,
- display some text using a specified foreground and background color,
- respond favorably to a request to close the window and clean up after itself.
Let’s get to work!
Source code and compilation
The source code can be found right over here: hello-x11.c.
Compilation is remarkably simple:
gcc hello-x11.c -o x11-demo $(pkg-config --cflags --libs x11)
Without pkg-config, assuming the headers and library are in the compiler’s standard search paths:
gcc hello-x11.c -o x11-demo -lX11
The program should compile in the blink of an eye, without so much as a single warning.
After running it (via ./x11-demo), we should be greeted by the following window:

Where is the server?
The X Window System is built around a client-server architecture. Communication often takes place through a local Unix domain socket, but it can also take place over a TCP/IP network.
From a programmer’s perspective, a display is therefore not a physical monitor. A pointer to a Display structure represents a connection to a particular instance of an X server. An application can even maintain several such connections if necessary.
To make matters slightly more confusing, our particular server instance also provides access to input devices, such as keyboards and mice. For more information about the history, principles, and capabilities of the X Window System, this article is a good starting point.
For graphical applications to know which X server they should connect to, there is an environment variable called DISPLAY.
In line 22:
display = XOpenDisplay(NULL);
we attempt to establish a connection to the server specified by that variable.
The function declaration looks like this:
Display *XOpenDisplay(const char *display_name);
We can explicitly specify a display name if necessary. Passing NULL means that the function should obtain the name from the DISPLAY environment variable.
Chances are that you have a computer running Linux or one of the BSD systems. Once an X session has been started, either through a display manager or by invoking startx, the value of DISPLAY will quite often be :0, although other values are perfectly possible.
Applications running on your computer may connect to the server through a Unix domain socket located in /tmp/.X11-unix/. For display :0, the corresponding socket is normally named X0.
You might want to try a little experiment: open a new terminal window, remove the DISPLAY environment variable by typing:
unset DISPLAY
and try to launch a traditional X11 application.
Unless the application has some alternative way of determining the display name, it will fail to connect. It simply has no idea which server to talk to.
The usual syntax of the DISPLAY variable is:
[host]:display[.screen]
Apart from specifying a particular X server, we can also select an X screen. If the screen number is omitted, it defaults to 0.
The server itself may be running on a completely different machine, hence the optional hostname.
Traditionally, a remote display numbered :0 listens on TCP port 6000, display :1 on port 6001, and so on. However, modern X servers frequently disable TCP connections by default. SSH with X11 forwarding is generally a more convenient and secure way of running remote graphical applications.
When writing our own programs, it is usually better to rely on the DISPLAY environment variable and pass NULL to XOpenDisplay rather than hardcoding a particular value.
Of course, one can imagine a scenario in which a specific display name is stored in a configuration file, or an application needs to communicate with several X servers.
The XOpenDisplay function returns a pointer to a Display structure, representing the connection and providing access to information about the server, its screens, supported capabilities, and various other details.
Applications should treat the internal contents of this structure as private and use the appropriate Xlib functions and macros to access them.
A valid Display pointer is required by many Xlib functions. After all, most operations involving server-side resources need to know which server they are dealing with.
If the function returns NULL, the connection could not be established. There is little point in continuing at this stage, assuming that graphical operations are what we came here for.
We can simply print an appropriate message to the standard error stream and terminate the program with a non-zero exit status.
A screen is not a monitor?
Every X screen has its own root window. This window sits underneath the entire window hierarchy and is the ultimate ancestor of all other windows on that screen.
It is a perfectly usable window, something that desktop wallpaper utilities and screenshot applications are more than happy to take advantage of.
In line 27:
screen = DefaultScreen(display);
we obtain the default X screen number for our connection.
Now, this is where things get interesting.
Historically, multi-monitor workstations were often configured with separate X screens, sometimes with a separate graphics adapter for each monitor. Each screen had its own root window, coordinate system, and collection of windows.
Although the mouse pointer could travel from one screen to another, moving an existing window between those screens was not normally possible.
A window created on screen :0.0 belonged to that screen. Screen :0.1 was a different world altogether.
Technologies such as Xinerama and, later, the RandR (Resize and Rotate) extension made it possible to present multiple physical monitors as parts of a larger, unified desktop.
A typical modern X11 desktop therefore consists of a single X screen and a single root window spanning several physical monitors.
For example, two monitors with a resolution of 1920 × 1080 pixels each, arranged side by side, may form an X screen measuring 3840 × 1080 pixels.
As far as our application is concerned, there is one large coordinate space. The actual arrangement of the physical monitors can be obtained separately through the appropriate X11 extensions.
Separate X screens are still possible, however, so we should not assume that there will always be exactly one.
In short: a display, a screen, and a monitor are three different things.
Nobody promised it would be easy.
Life takes on some color
Our window will need some colors obtained from the server.
Yes, obtained, because a typical conversation goes something like this:
— I’d like a color with these RGB components, please.
— Certainly. Here you go. Happy painting.
Or:
— I’d like a color with these RGB components, please.
— I haven’t got that exact color, but I’ve got something close. Off you go.
To use a particular color, whether specified by its RGB components or by a name, we need a pixel value appropriate for the visual and colormap associated with our window.
One way of obtaining it is to ask the X server through the XAllocNamedColor function.
This function accepts a textual color specification, such as "red", "navy", or "#eaeeaf", and attempts to allocate a corresponding read-only color entry in the specified colormap.
On a modern TrueColor display, this does not necessarily mean reserving a scarce physical palette entry, as it might have done on older hardware.
What matters to us is that we receive a usable pixel value which can then be passed to drawing functions.
The XAllocNamedColor function requires:
- a pointer to a
Displaystructure, - a colormap,
- a textual color specification,
- a pointer to an
XColorstructure that will receive the color actually allocated, - a pointer to another
XColorstructure that will receive the exact color definition.
Since we also need to check whether the operation was successful, it is convenient to define a little helper function called color, as shown in lines 6–12 and used in lines 29–31.
Our function accepts:
- a pointer to a
Displaystructure, - the screen number,
- the color specification,
- an existing fallback pixel value, to be used if the requested color cannot be obtained.
static unsigned long color(Display *display, int screen, const char *name,
unsigned long fallback)
{
XColor found, exact;
return XAllocNamedColor(display, DefaultColormap(display, screen),
name, &found, &exact) ? found.pixel : fallback;
}
The DefaultColormap macro gives us the default colormap for the specified screen.
WhitePixel and BlackPixel are two handy macros that return readily available white and black pixel values for that screen.
We do not have to allocate them ourselves, which makes them particularly useful as fallback values.
Opening a window
Our window is finally created in lines 33–35.
window = XCreateSimpleWindow(display, RootWindow(display, screen),
100, 100, 250, 150,
0, border_color, bg);
The XCreateSimpleWindow function requires the following arguments:
- a pointer to a
Displaystructure, - the parent window — in our case, the root window,
- the
xandycoordinates relative to the upper-left corner of the parent window, - the width and height,
- the border width,
- the border pixel value,
- the background pixel value.
All dimensions and coordinates are expressed in pixels.
Now, what is the deal with that border?
In this particular case, the window manager will most likely draw its own decorations around our window (or none at all). It may also decide to position the window somewhere other than the coordinates we requested.
However, if we were creating another window to represent, say, a button inside an existing window, the border width and color could be quite useful.
Not every window in X11 has to be a top-level application window.
Also, although our window has now been created, it is not yet visible. We will deal with that minor inconvenience shortly.
Giving it an identity
The following function:
XStoreName(display, window, "Is it on?");
sets the window name, commonly used as its title.
It does not actually draw any text. Instead, it sets a window property called WM_NAME, which the window manager can read and make use of.
Most window managers do precisely that, displaying the name in the window’s title bar.
Properties are an important part of X11, but we will leave a more detailed discussion of them for another episode.
Keep us informed
In line 37, we tell the server what we would like the server to tell us about.
XSelectInput(display, window, ExposureMask | KeyPressMask);
We specify the types of events we are interested in by combining the appropriate event masks using the bitwise OR operator.
ExposureMask and KeyPressMask allow us to receive Expose and KeyPress events, respectively.
The former tells us that some part of our window needs to be redrawn. The latter informs us that a key has been pressed.
For now, we are not interested in mouse movements, mouse clicks, or any of the many other events that X11 can deliver.
Some events, such as ClientMessage, follow different delivery rules and do not require a corresponding event mask.
We are about to encounter one of them.
Negotiating the terms of divorce
In lines 39–41, we encounter atoms.
Atom wm_delete = XInternAtom(display, "WM_DELETE_WINDOW", False);
Atom wm_protocols = XInternAtom(display, "WM_PROTOCOLS", False);
XSetWMProtocols(display, window, &wm_delete, 1);
Atoms are numeric identifiers associated with strings. They are maintained by the X server and used in various places throughout the protocol, including window properties, selections, and client messages.
Instead of repeatedly exchanging potentially lengthy strings with the server, we can use their compact numeric equivalents.
XInternAtom obtains the identifier associated with a given name. Passing False as the final argument means that the atom should be created if it does not already exist.
WM_PROTOCOLS and WM_DELETE_WINDOW are part of the standard conventions followed by X11 window managers and applications.
WM_PROTOCOLSis a sort of noticeboard attached to our window. It contains a list of protocols that our application declares itself willing to support.WM_DELETE_WINDOWidentifies the protocol used to request that an application close one of its windows.
By calling XSetWMProtocols, we announce that our application understands the latter.
An example of handling such a request can be found in lines 63–68:
case ClientMessage:
if (e.xclient.message_type == wm_protocols &&
e.xclient.format == 32 &&
(Atom)e.xclient.data.l[0] == wm_delete)
running = 0;
break;
The ClientMessage event can carry 20 bytes of application-defined data. Its format field specifies whether those data are organized into elements of 8, 16, or 32 bits.
The WM_PROTOCOLS convention uses the 32-bit format, with the first element identifying the protocol in question.
And why do we need all this?
When the user attempts to close our window using a button in its decorations or a keyboard shortcut defined by the window manager, we want our application to receive a polite request to close.
It can then ask the user whether unsaved work should be discarded, save its current state, or simply clean up after itself and terminate.
These conventions are defined in the ICCCM, or Inter-Client Communication Conventions Manual, which describes how X clients, including window managers, should cooperate with one another.
If we do not advertise support for WM_DELETE_WINDOW, the window manager may resort to a rather less diplomatic solution: forcibly disconnecting our application from the X server.
In the case of a simple Xlib application, that will normally result in the termination of the entire process.
Better negotiate the terms beforehand.
Tools of the trade
To draw or write on the surface of a window, we need a graphics context, usually abbreviated to GC.
We create one in line 43:
gc = XCreateGC(display, window, 0, NULL);
A graphics context holds various drawing parameters, such as the foreground and background pixel values, line width, drawing style, font, and clipping settings.
The XCreateGC function takes four arguments, but for now the most important ones are the pointer to our Display structure (by now, hardly a surprise) and the identifier of our window.
The window tells Xlib which screen and drawable depth the graphics context needs to be compatible with.
The remaining two arguments allow us to specify which attributes should be initialized and what their values should be.
Passing 0 and NULL means that we are happy to start with the default settings.
In the very next line:
XSetForeground(display, gc, text_color);
we set the foreground pixel value to the color we intend to use for our text.
There is much more to graphics contexts, but this will suffice for our first window.
Let there be light
The request to make our window visible is issued in line 46:
XMapWindow(display, window);
In X11 terminology, we are mapping the window.
Creating a window and mapping it are two separate operations. This allows us to configure our window, set its properties, and prepare the necessary resources before it makes its public appearance.
On a desktop managed by a window manager, the mapping request will normally be handled in cooperation with that manager.
Our window is now ready to face the world.
Waiting for Godot
The window has come to life, and from now on we need to receive and handle events coming from the server.
This is the purpose of our main event loop:
while (running) {
XEvent e;
XNextEvent(display, &e);
switch (e.type) {
/* Event handlers go here. */
}
}
Events are retrieved by the XNextEvent function in line 53 and handled by the switch statement in lines 55–69.
If the event queue is empty, XNextEvent flushes any buffered outgoing requests and waits until an event becomes available.
Consequently, there is no need to keep checking whether something has happened. Our application can spend most of its time doing absolutely nothing without consuming an entire CPU core in the process.
A surprisingly useful skill.
Hello, cruel world!
The actual drawing takes place in response to an Expose event, in lines 56–58.
case Expose:
XDrawString(display, window, gc, 20, 50, text, (int)strlen(text));
break;
Unlike many modern graphical toolkits, Xlib does not maintain a collection of graphical objects that it can automatically redraw whenever necessary.
It is up to our application to restore the contents of its window when the server indicates that some part of it needs repainting.
The text itself is drawn using XDrawString.
In addition to a pointer to the Display structure, the window identifier, and the graphics context, we specify:
- the
xandycoordinates, - the text to be drawn,
- the length of the text in bytes.
The coordinates are relative to the upper-left corner of the window’s drawing area. There is one important detail, however: the y coordinate specifies the baseline of the text, rather than its upper edge.
The color of the text was previously established in line 44 using XSetForeground.
For our simple ASCII string, the traditional XDrawString function is perfectly adequate. More advanced text rendering, including Unicode and modern fonts, deserves an episode of its own.
Perhaps even two.
Please press Q
Our window receives keyboard events, so we can wait for the user to press the Q key and terminate the program when that happens.
The KeyPress event is handled in lines 59–62.
case KeyPress:
if (XLookupKeysym(&e.xkey, 0) == XK_q)
running = 0;
break;
The XLookupKeysym function translates an X11 keycode into its corresponding symbolic value, known as a KeySym.
The second argument selects an entry in the key’s symbol mapping. We use index 0, which normally corresponds to the base, unmodified symbol.
All that remains is to check whether the returned symbol is XK_q and, if so, terminate the event loop.
This is sufficient for our little application, although proper handling of keyboard layouts, modifiers, shortcuts, and text input is considerably more involved.
We will get there eventually.
Last one out, turn off the lights
Before terminating the program, it is good practice to release the resources that we have previously allocated:
XFreeGC(display, gc);
XDestroyWindow(display, window);
And finally, we close our connection to the X server:
XCloseDisplay(display);
Under normal circumstances, the X server will also release the remaining resources owned by our client when the connection is closed.
Nevertheless, explicitly releasing resources is a useful habit, particularly once our applications become more complicated and start creating and destroying resources throughout their lifetime.
And that concludes our first encounter with Xlib.
printf("That's all folks!\n");
Further reading
The manual pages are also well worth exploring:
man XOpenDisplay
man XAllocNamedColor
man XCreateSimpleWindow
man XSelectInput
man XSetWMProtocols
man XCreateGC
man XMapWindow
man XNextEvent
man XDrawString
man XLookupKeysym
man XCloseDisplay
