Event Loop with Xlib on Linux

References

This time we'll use the slightly less "Simple" function to create a window and run an event processing loop.

Build with:

gcc main.c -lX11

The above code opens a window with more specificity, then processes events, printing information about those events to the console until it receives one of two "quit" events.

XVisualInfo visual = {}; { const auto result = XMatchVisualInfo (display, screen, 24, TrueColor, &visual); assert (result); }

In order to draw graphics to an X window, X11 needs some "visual" information. Here we just ask for a 24-bit RGB visual. We won't actually be doing any pixel drawing with Xlib directly, but if you were, these days, that's what you'd use. Other visual types include grayscale, colour-mapping, etc., but they aren't usually used anymore.

XSetWindowAttributes attributes = { .background_pixel = 0x403a4d, .colormap = XCreateColormap (display, root_window, visual.visual, AllocNone), .event_mask = StructureNotifyMask | KeyPressMask | KeyReleaseMask | FocusChangeMask | PointerMotionMask | ButtonPressMask | ButtonReleaseMask, };

The background color from before has moved into this structure. We create a colour map, which is mostly apocryphal since these days every display uses an RGB representation rather than colour indices. The event mask tells Xlib what kinds of events we want to be sent - see the documentation for all the possibilities.

IMPORTANT NOTE: It's important to initialize unused members of XSetWindowAttributes to zero, as I have here, rather than making an uninitialized XSetWindowAttributes struct and then manually assigning individual members their values. There are some members which, if left with junk values, can cause your window creation to randomly fail.

const auto window = XCreateWindow(display, root_window, 0, 0, 640, 480, 0, visual.depth, InputOutput, visual.visual, CWBackPixel | CWColormap | CWEventMask, &attributes);

XCreateWindow is the slightly more complex version of what we used last time. This allows us to specify more information, as above.

#define WINDOW_TITLE "Golden Path" XChangeProperty (display, window, XInternAtom (display, "_NET_WM_NAME", False), XInternAtom (display, "UTF8_STRING", False), 8, 0, (const unsigned char*)WINDOW_TITLE, sizeof (WINDOW_TITLE)-1);

This XInternAtom function is used to get or add an "atom" to a window. XAtoms are just data associated with your window. The atoms we need, in this case, are, "_NET_WM_NAME", and "UTF8_STRING" - indicating which atom we're modifying and the type of data we're storing. Note that, because the window title is stored as a UTF8 string, it supports both ASCII and unicode characters; you can include symbols from any language, and emojis, if you like.

Atom WM_DELETE_WINDOW = XInternAtom (display, "WM_DELETE_WINDOW", False); { const auto result = XSetWMProtocols (display, window, &WM_DELETE_WINDOW, 1); assert (result); }

WM_DELETE_WINDOW is the atom used to represent the event the Window Manager sends to us when our window is destroyed (say, by the user pressing ALT+F4).

XMapWindow (display, window); XFlush (display);

Once the window is fully setup, we map it and flush all pending X11 commands.

bool quit = false; while (!quit) { XEvent e; XNextEvent (display, &e); printf ("Event: "); bool pressed = true; switch (e.type) {

This is the event loop. XNextEvent blocks until the next event is received, and puts the result in the variable passed to it. If you want to check whether there are any events available without blocking, use XPending. The XEvent structure is a tagged union, so we switch on the type and access the subtype based on the tag. For this example code, I've handled all the events you're likely to need in a game. I print the event to the console and have demonstrated a few ways of handling the events. Most of them are self-explanatory, but I'll explain a few important ones. For more information about these and other events, check the Xlib documentation.

case KeyRelease: pressed = false; case KeyPress: { const auto k = &e.xkey; char c; KeySym sym; const auto length = XLookupString (k, &c, 1, &sym, NULL); const auto unmodified_sym = XLookupKeysym (k, 0); if (length && c >= 33 && c <= 126) printf ("Key%s [%c]\n", pressed ? "Press" : "Release", c); else { const char *symstr = "Unknown"; switch (sym) { case XK_Return: symstr = "Enter"; break; case XK_space: symstr = "Space"; break; case XK_Escape: symstr = "Escape"; break; case XK_Left: symstr = "Left"; break; case XK_Right: symstr = "Right"; break; case XK_Up: symstr = "Up"; break; case XK_Down: symstr = "Down"; break; } printf ("Key%s symbol [%s]\n", pressed ? "Press" : "Release", symstr); } } break;

We use the pressed variable to reuse the code for presses and releases. The key event needs some reinterpretation before it's usable. XLookupString applies modifiers (like shift, alt, ctrl, etc.) and gives you a printable character (or string, if you provide a bigger buffer) based on the key press. I check if it's in the printable ASCII range before printing it, since printing certain control characters can mess up the terminal output. It also returns a key symbol, which, if you're not printing the event to the console, is likely more useful. Check <X11/keysymdef.h> for more key codes. Since this function takes into account the status of other keys, if you are holding shift, for example, and press the '1' key, this function gives you '!' as the character and key symbol. Good for typing, but not so good for games, I find. You likely should just use XLookupKeysym, which I also included.

case ConfigureNotify: { const auto c = &e.xconfigure; printf ("ConfigureNotify: x[%d] y[%d] w[%d] h[%d]\n", c->x, c->y, c->width, c->height); } break;

ConfigureNotify is the event passed whenever any of several window properties are changed. It doesn't tell you specifically which one is changed, so if you want to respond to resizing and such you can store the previous size and check if it's changed here.

case MotionNotify: { const auto m = &e.xmotion; printf ("MotionNotify: x[%d] y[%d]\n", m->x, m->y); } break;

This event is sent for mouse movement.

case DestroyNotify: { puts ("DestroyNotify"); const auto d = &e.xdestroywindow; if (d->window == window) quit = true; } break;

This event is sent when a window started by your process is destroyed. If you're sure you'll only ever have one window, you can skip the check. However, I recommend leaving the check in to avoid unexpected bugs later on. At one point, my game spawned an extra window for a workaround, and, when launched with the Steam overlay, that window got destroyed by the overlay somehow and sent my game a DestroyNotify event. I had to check whether it was the main window before deciding to quit the program to avoid instantly closing my game on launch.