Contemplating the Core
I'm now zeroing in on the fundamental needs of this window manager. Connecting to the X server is a given. I'm also considering the bare minimum for window management – how windows are created, placed, and handled. I'm prioritizing the essential components to start small and iterate.
Prioritizing the Essentials
I've outlined the essential building blocks. Connecting to X, event handling, and basic window manipulation are the immediate priorities. The goal is to get a functional, albeit basic, system up and running quickly. I'm focusing on the "what" before the "how." Now I'm preparing to make a simple, clean architecture.
Mapping the Events
I'm now focusing on the event loop and how to handle incoming requests. I'm prioritizing MapRequest to manage new windows and ConfigureRequest to handle size/position changes. I plan to use XMapWindow to display the windows and potentially add borders. I'm also considering the implications of handling KeyPress and ButtonPress events, and setting up the grabs.
Designing the Architecture
I'm now sketching the core structure, focusing on initialization, event handling, and key/button grabs. The goal is to separate concerns and make the code readable. I'm considering using an event structure with handlers for each event type to promote maintainability. The "TinyWM" is an excellent example, and I plan to build upon its simplicity.
Planning the Implementation
Now I'm breaking down the code, first sketching the event handling structure to ensure that different interactions (mouse clicks, key presses) can be processed effectively. I plan to use a straightforward switch statement to direct different event types to their respective handlers, such as OnKey and OnButton, for increased readability. The example of TinyWM provides a good foundation for this.
Defining the Structure
Now, I'm defining the basic structure of the application. The use of key/button grabs for user interactions is crucial. I will focus on the event loop, and incorporate handlers for various event types, particularly MapRequest, ConfigureRequest, and KeyPress, and how I will integrate these with a switch statement for processing. The TinyWM example serves as a reference.
This is a guide to building a functioning, minimalistic stacking Window Manager (WM) for X11 using C and the Xlib library.
This WM (let's call it minwm) will be fewer than 200 lines of code and will support:
- Opening windows.
- Moving windows (Alt + Left Click Drag).
- Resizing windows (Alt + Right Click Drag).
- Focusing windows (Click).
- Killing windows (Alt + F4).
- Spawning a terminal (Alt + F1).
Prerequisites
On Linux, you need the X11 development headers.
- Debian/Ubuntu:
sudo apt install libx11-dev
- Arch:
sudo pacman -S libx11
- Fedora:
sudo dnf install libX11-devel
The Code
Save the following code as wm.c.
/* wm.c - A minimalistic X11 Window Manager */
#include <X11/Xlib.h>
#include <X11/keysym.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
// The modifier key used for WM actions (Mod1Mask is usually the 'Alt' key)
#define MOD_KEY Mod1Mask
// Global variables
Display *dpy;
Window root;
XWindowAttributes attr;
XButtonEvent start;
// Function prototypes
void grab_input(Window w);
// Error handler to prevent the WM from crashing if a window disappears unexpectedly
int on_x_error(Display *d, XErrorEvent *e) { return 0; }
int main(void) {
XEvent ev;
// 1. Open connection to the X server
if (!(dpy = XOpenDisplay(NULL))) {
fprintf(stderr, "Cannot open display\n");
return 1;
}
// 2. Set error handler and get the root window (the background)
XSetErrorHandler(on_x_error);
root = DefaultRootWindow(dpy);
// 3. Subscribe to root window events
// SubstructureRedirectMask: Let us intercept Map/Configure requests from children
XSelectInput(dpy, root, SubstructureRedirectMask);
// 4. Grab Global Keys (Alt + F1 to spawn terminal)
XGrabKey(dpy, XKeysymToKeycode(dpy, XK_F1), MOD_KEY, root,
True, GrabModeAsync, GrabModeAsync);
// 5. The Main Event Loop
while (1) {
XNextEvent(dpy, &ev);
// EVENT: A new window requests to be shown
if (ev.type == MapRequest) {
XMapWindow(dpy, ev.xmaprequest.window);
// Give the window a border (1px width, red color)
XSetWindowBorderWidth(dpy, ev.xmaprequest.window, 2);
XSetWindowBorder(dpy, ev.xmaprequest.window, 0xff0000);
// Setup mouse button listeners for this specific window
grab_input(ev.xmaprequest.window);
}
// EVENT: Keyboard Key Press
else if (ev.type == KeyPress) {
// Alt+F1: Spawn terminal (xterm)
if (ev.xkey.keycode == XKeysymToKeycode(dpy, XK_F1)) {
if (fork() == 0) {
execlp("xterm", "xterm", NULL);
exit(0);
}
}
// Alt+F4: Close Window
else if (ev.xkey.keycode == XKeysymToKeycode(dpy, XK_F4)) {
// We grab the key on Root, but we need to kill the focused window.
// For simplicity in this minimal example, we infer focus or
// add logic here. However, simpler: Let's grab F4 on the *window*
// in grab_input function to make targeting easier.
}
}
// EVENT: Mouse Button Press
else if (ev.type == ButtonPress) {
// Save the window attributes (position/size) and cursor start position
// This is needed to calculate the relative movement later
XGetWindowAttributes(dpy, ev.xbutton.subwindow, &attr);
start = ev.xbutton;
// Bring window to front and give it focus
XRaiseWindow(dpy, ev.xbutton.subwindow);
XSetInputFocus(dpy, ev.xbutton.subwindow, RevertToParent, CurrentTime);
}
// EVENT: Mouse Motion (Dragging)
else if (ev.type == MotionNotify) {
int diff_x = ev.xbutton.x_root - start.x_root;
int diff_y = ev.xbutton.y_root - start.y_root;
// Alt + Left Click (Button1): Move Window
if (start.button == Button1) {
XMoveWindow(dpy, start.subwindow,
attr.x + diff_x,
attr.y + diff_y);
}
// Alt + Right Click (Button3): Resize Window
else if (start.button == Button3) {
// Ensure width/height don't go below 1
int w = attr.width + diff_x;
int h = attr.height + diff_y;
if (w < 1) w = 1;
if (h < 1) h = 1;
XResizeWindow(dpy, start.subwindow, w, h);
}
}
// EVENT: Key Press inside a specific window (handled via key grab)
else if (ev.type == KeyPress && ev.xkey.subwindow != None) {
if (ev.xkey.keycode == XKeysymToKeycode(dpy, XK_F4)) {
XKillClient(dpy, ev.xkey.subwindow);
}
}
}
XCloseDisplay(dpy);
return 0;
}
// Helper: Grab mouse buttons and keys for a specific window
void grab_input(Window w) {
// Move: Alt + Left Button
XGrabButton(dpy, Button1, MOD_KEY, w, False,
ButtonPressMask | ButtonMotionMask,
GrabModeAsync, GrabModeAsync, None, None);
// Resize: Alt + Right Button
XGrabButton(dpy, Button3, MOD_KEY, w, False,
ButtonPressMask | ButtonMotionMask,
GrabModeAsync, GrabModeAsync, None, None);
// Kill: Alt + F4 (Grab specific to the window)
XGrabKey(dpy, XKeysymToKeycode(dpy, XK_F4), MOD_KEY, w,
True, GrabModeAsync, GrabModeAsync);
}
How to Compile
Run the following command in your terminal:
gcc wm.c -o minwm -lX11
How to Test (Safely)
You do not need to log out of your current desktop environment to test this. You can run it nested inside a window using Xephyr.
- Install Xephyr (usually part of
xserver-xephyr package).
- Launch Xephyr (this creates a window representing a new screen):
Xephyr -br -ac -noreset -screen 800x600 :1 &
- Run your WM inside Xephyr:
DISPLAY=:1 ./minwm
How to Use
Once minwm is running inside the Xephyr window:
- Spawn Terminal: Press
Alt + F1. (Note: ensure xterm is installed, or change the code to gnome-terminal, st, or kitty).
- Move Window: Hold
Alt, Click and drag with the Left Mouse Button.
- Resize Window: Hold
Alt, Click and drag with the Right Mouse Button.
- Focus/Raise: Simply Click anywhere on a window (while holding Alt simplifies the logic in this minimal code, usually clicking the content works too depending on application support, but Alt+Click is guaranteed here).
- Close Window: Press
Alt + F4 while the mouse is over a window.
How it Works (Code Explanation)
XOpenDisplay: Connects C to the X Server via a socket.
SubstructureRedirectMask: This is the magic flag. It tells X11, "If any application tries to draw a window or change its size, stop! Ask me (the WM) first."
MapRequest: When you launch xterm, X11 sends this event. Our code explicitly calls XMapWindow (allows it to be seen) and adds a red border.
XGrabButton: We bind Alt+Click to the window frames.
MotionNotify: While holding the mouse button, we calculate the difference between where the mouse started (start.x_root) and where it is now, then update the window position/size accordingly.
Next Steps
To expand this into a usable daily driver, you would need to implement:
- Window Decorations: Draw rectangles above the window for title bars.
- Layouts: Algorithms to automatically tile windows instead of stacking them.
- ** ICCCM/EWMH Standards:** Protocols so taskbars and pagers know which windows exist (this is the hardest part of writing a compliant WM).