Skip to content
TheChatArchiveThe Chat Archive
GPT 5.1· openaiHugging Face Frontier Reasoning Traces

Build a minimalistic window manager for X11 in C.

  1. User

    Build a minimalistic window manager for X11 in C.

  2. Assistant

    Designing a minimalistic window manager

    The user is asking for a minimalistic window manager for X11 in C, focusing on example code and explanations. I should implement basic functionalities: managing windows, handling events like MapRequest and Destroy, and enabling mouse interactions. The code should be around 200-400 lines, so I must be concise but still complete. I should include build instructions and issues related to window managers being complex. I'll organize the response with a brief introduction and a fully annotated example, avoiding unnecessary verbosity.Building a simple stacking window manager

    I’m planning to create a minimalist stacking window manager (WM) that handles essential events like MapRequest, ConfigureRequest, and ButtonPress. To keep it educational, I’ll avoid EWMH/ICCCM details. I should note that it must run in Xephyr or a separate X session to retain the environment. I’ll label the file "miniwm.c" and include necessary headers like <X11/Xlib.h>.

    In the main function, I’ll open the display, get the root window, and select inputs while primarily focusing on managing client windows instead of reparenting for simplicity.Managing window events in the WM

    I’m planning to handle several events for the window manager, starting with MapRequest, where I’ll use XMapWindow to map the window and optionally set its border width and color. Then, I’ll need to focus or raise the window. For ButtonPress events, I’ll allow movement if I've selected ButtonPressMask properly.

    However, since new windows don't initially have an event mask, I must call XSelectInput for each one I manage, ideally in the MapRequest handler before XMapWindow. I’ll also consider managing preset windows on startup using QueryTree but might opt to only manage newly created windows to avoid issues, such as displaying black windows in an existing session. Running it in Xephyr should ensure it works smoothly.Designing the client structure and movement

    I'm structuring a Client that includes a window and a pointer to the next client for managing windows. While a singly linked list is nice for raising windows, I can call XRaiseWindow directly on ButtonPress events. For focus, I’ll set the input focus using XSetInputFocus.

    Now, for the moving algorithm: when ButtonPress occurs with the right button and modifier, I’ll record the click position and window geometry. If moving is active, I’ll compute the movement on MotionNotify using XMoveWindow. I need to set the appropriate event masks and can skip pointer grabbing to keep things simpler by relying on per-window events instead.Implementing the basic event loop and error handling

    I’m outlining a basic event loop using XNextEvent to handle X events. It’s essential to include error management, particularly when selecting SubstructureRedirectMask, which can fail if a window manager is already running. I’ll set up an error handler to monitor for this specific case.

    Next, I’ll intercept ConfigureRequest events, allowing clients to resize themselves properly, and consider border settings during MapRequest. I should carefully plan the user instructions for building and running the window manager while highlighting its educational focus and limitations — particularly regarding multi-desktop support.Implementing the MapRequest handling and event management

    In the MapRequest handler, I need to manage the newly mapped window by calling the appropriate functions, like XMapWindow and setting the input focus. To prevent flickering, I could also set the border width beforehand.

    I’ll also manage existing windows by looping through children and selecting them for events. In my code, I must handle DestroyNotify to reset movement if a window is destroyed. I plan to create a minimal window manager example with about 250-300 lines of code, keeping comments at an appropriate level and ensuring I include necessary error handling and function calls. I’ll set event masks correctly based on what I've outlined to capture all relevant events. Below is a tiny, educational X11 window manager written in C using Xlib.
    It handles:

    • Becoming the WM (grabs SubstructureRedirect on the root)
    • Mapping new windows
    • Letting clients configure themselves (size/pos)
    • Click-to-focus
    • Drag to move a window with the left mouse button

    It deliberately ignores ICCCM/EWMH, decorations, workspaces, etc.


    miniwm.c

    /*
     * miniwm.c – a tiny, minimalistic X11 window manager.
     *
     * Features:
     *   - Takes control of the X server (SubstructureRedirect on root)
     *   - Maps new windows and lets them configure themselves
     *   - Click-to-focus
     *   - Drag windows with left mouse button
     *
     * Compile:
     *   gcc -std=c99 -Wall -Wextra -O2 miniwm.c -o miniwm -lX11
     *
     * Run (recommended inside Xephyr so you don't break your main session):
     *   Xephyr :1 -screen 800x600 &
     *   DISPLAY=:1 ./miniwm &
     *   DISPLAY=:1 xterm &
     */
    
    #include <X11/Xlib.h>
    #include <X11/Xutil.h>
    
    #include <stdio.h>
    #include <stdlib.h>
    #include <signal.h>
    
    static Display *dpy;
    static Window root;
    static int running = 1;
    
    /* State for window moving with the mouse */
    static int moving = 0;
    static Window moving_win = None;
    static int move_start_root_x, move_start_root_y;
    static int win_start_x, win_start_y;
    
    /* Handle Ctrl+C cleanly */
    static void
    sigint_handler(int sig)
    {
        (void)sig;
        running = 0;
    }
    
    /* Basic X error handler:
     * - Exit if another WM is already running (BadAccess on SubstructureRedirect)
     * - Otherwise just print the error and continue.
     */
    static int
    xerror_handler(Display *d, XErrorEvent *e)
    {
        char msg[256];
        XGetErrorText(d, e->error_code, msg, sizeof msg);
    
        if (e->error_code == BadAccess) {
            fprintf(stderr, "miniwm: another window manager is already running.\n");
            exit(1);
        }
    
        fprintf(stderr, "miniwm: X error: %s (request %d, minor %d, resource 0x%lx)\n",
                msg, e->request_code, e->minor_code, e->resourceid);
        return 0;
    }
    
    /* Select events on a client window we want to "manage". */
    static void
    manage_window(Window w)
    {
        /* Listen for button presses and motion to support moving,
           and structure notifications for cleanup if needed. */
        XSelectInput(dpy, w,
                     StructureNotifyMask |
                     ButtonPressMask |
                     ButtonReleaseMask |
                     PointerMotionMask);
    
        /* Give it a small border so we can see it. */
        XSetWindowBorderWidth(dpy, w, 2);
        unsigned long border = BlackPixel(dpy, DefaultScreen(dpy));
        XSetWindowBorder(dpy, w, border);
    }
    
    /* Handle MapRequest: client wants to be mapped.
     * We "manage" it and then map it. */
    static void
    handle_map_request(XEvent *ev)
    {
        XMapRequestEvent *e = &ev->xmaprequest;
    
        manage_window(e->window);
        XMapWindow(dpy, e->window);
    
        /* Focus and raise newly mapped windows. */
        XSetInputFocus(dpy, e->window, RevertToPointerRoot, CurrentTime);
        XRaiseWindow(dpy, e->window);
    }
    
    /* Handle ConfigureRequest: client wants to resize/move/stack itself.
     * As a minimal WM, we mostly honor the request. */
    static void
    handle_configure_request(XEvent *ev)
    {
        XConfigureRequestEvent *e = &ev->xconfigurerequest;
        XWindowChanges wc;
    
        wc.x            = e->x;
        wc.y            = e->y;
        wc.width        = e->width;
        wc.height       = e->height;
        wc.border_width = e->border_width;
        wc.sibling      = e->above;
        wc.stack_mode   = e->detail;
    
        XConfigureWindow(dpy, e->window, e->value_mask, &wc);
    }
    
    /* Begin moving a window when mouse button is pressed. */
    static void
    handle_button_press(XEvent *ev)
    {
        XButtonEvent *e = &ev->xbutton;
    
        /* Determine which window to act on.
         * If the event is on the root, subwindow may be the client.
         */
        Window w = e->subwindow ? e->subwindow : e->window;
        if (w == root || w == None)
            return;
    
        /* Only left button to move, but you could add more logic here. */
        if (e->button != Button1)
            return;
    
        /* Get current window position. */
        XWindowAttributes attr;
        if (!XGetWindowAttributes(dpy, w, &attr))
            return;
    
        moving = 1;
        moving_win = w;
        move_start_root_x = e->x_root;
        move_start_root_y = e->y_root;
        win_start_x = attr.x;
        win_start_y = attr.y;
    
        /* Focus and raise the clicked window. */
        XSetInputFocus(dpy, w, RevertToPointerRoot, CurrentTime);
        XRaiseWindow(dpy, w);
    }
    
    /* Stop moving when the mouse button is released. */
    static void
    handle_button_release(XEvent *ev)
    {
        (void)ev;
        moving = 0;
        moving_win = None;
    }
    
    /* While moving, update window position on pointer motion. */
    static void
    handle_motion_notify(XEvent *ev)
    {
        if (!moving || moving_win == None)
            return;
    
        XMotionEvent *e = &ev->xmotion;
    
        int dx = e->x_root - move_start_root_x;
        int dy = e->x_root - move_start_root_x; /* BUG! We'll fix below. */
    }
    

    The above has a small bug: we mistakenly used x_root twice.
    Here is the corrected and complete version (replace everything above with this full file):

    /*
     * miniwm.c – a tiny, minimalistic X11 window manager.
     *
     * Features:
     *   - Takes control of the X server (SubstructureRedirect on root)
     *   - Maps new windows and lets them configure themselves
     *   - Click-to-focus
     *   - Drag windows with left mouse button
     *
     * Compile:
     *   gcc -std=c99 -Wall -Wextra -O2 miniwm.c -o miniwm -lX11
     *
     * Run (recommended inside Xephyr so you don't break your main session):
     *   Xephyr :1 -screen 800x600 &
     *   DISPLAY=:1 ./miniwm &
     *   DISPLAY=:1 xterm &
     */
    
    #include <X11/Xlib.h>
    #include <X11/Xutil.h>
    
    #include <stdio.h>
    #include <stdlib.h>
    #include <signal.h>
    
    static Display *dpy;
    static Window root;
    static int running = 1;
    
    /* State for window moving with the mouse */
    static int moving = 0;
    static Window moving_win = None;
    static int move_start_root_x, move_start_root_y;
    static int win_start_x, win_start_y;
    
    /* Handle Ctrl+C cleanly */
    static void
    sigint_handler(int sig)
    {
        (void)sig;
        running = 0;
    }
    
    /* Basic X error handler:
     * - Exit if another WM is already running (BadAccess on SubstructureRedirect)
     * - Otherwise just print the error and continue.
     */
    static int
    xerror_handler(Display *d, XErrorEvent *e)
    {
        char msg[256];
        XGetErrorText(d, e->error_code, msg, sizeof msg);
    
        if (e->error_code == BadAccess) {
            fprintf(stderr, "miniwm: another window manager is already running.\n");
            exit(1);
        }
    
        fprintf(stderr, "miniwm: X error: %s (request %d, minor %d, resource 0x%lx)\n",
                msg, e->request_code, e->minor_code, e->resourceid);
        return 0;
    }
    
    /* Select events on a client window we want to "manage". */
    static void
    manage_window(Window w)
    {
        /* Listen for button presses and motion to support moving,
           and structure notifications for cleanup if needed. */
        XSelectInput(dpy, w,
                     StructureNotifyMask |
                     ButtonPressMask |
                     ButtonReleaseMask |
                     PointerMotionMask);
    
        /* Give it a small border so we can see it. */
        XSetWindowBorderWidth(dpy, w, 2);
        unsigned long border = BlackPixel(dpy, DefaultScreen(dpy));
        XSetWindowBorder(dpy, w, border);
    }
    
    /* At startup, "manage" existing top-level windows if any. */
    static void
    manage_existing_windows(void)
    {
        Window root_ret, parent_ret, *children = NULL;
        unsigned int nchildren = 0;
    
        if (!XQueryTree(dpy, root, &root_ret, &parent_ret, &children, &nchildren))
            return;
    
        for (unsigned int i = 0; i < nchildren; i++) {
            XWindowAttributes attr;
            if (!XGetWindowAttributes(dpy, children[i], &attr))
                continue;
            if (attr.map_state == IsViewable) {
                manage_window(children[i]);
            }
        }
    
        if (children)
            XFree(children);
    }
    
    /* Handle MapRequest: client wants to be mapped.
     * We "manage" it and then map it. */
    static void
    handle_map_request(XEvent *ev)
    {
        XMapRequestEvent *e = &ev->xmaprequest;
    
        manage_window(e->window);
        XMapWindow(dpy, e->window);
    
        /* Focus and raise newly mapped windows. */
        XSetInputFocus(dpy, e->window, RevertToPointerRoot, CurrentTime);
        XRaiseWindow(dpy, e->window);
    }
    
    /* Handle ConfigureRequest: client wants to resize/move/stack itself.
     * As a minimal WM, we mostly honor the request. */
    static void
    handle_configure_request(XEvent *ev)
    {
        XConfigureRequestEvent *e = &ev->xconfigurerequest;
        XWindowChanges wc;
    
        wc.x            = e->x;
        wc.y            = e->y;
        wc.width        = e->width;
        wc.height       = e->height;
        wc.border_width = e->border_width;
        wc.sibling      = e->above;
        wc.stack_mode   = e->detail;
    
        XConfigureWindow(dpy, e->window, e->value_mask, &wc);
    }
    
    /* Begin moving a window when mouse button is pressed. */
    static void
    handle_button_press(XEvent *ev)
    {
        XButtonEvent *e = &ev->xbutton;
    
        /* Determine which window to act on.
         * If the event is on the root, subwindow may be the client.
         */
        Window w = e->subwindow ? e->subwindow : e->window;
        if (w == root || w == None)
            return;
    
        /* Only left button to move, but you could add more logic here. */
        if (e->button != Button1)
            return;
    
        /* Get current window position. */
        XWindowAttributes attr;
        if (!XGetWindowAttributes(dpy, w, &attr))
            return;
    
        moving = 1;
        moving_win = w;
        move_start_root_x = e->x_root;
        move_start_root_y = e->y_root;
        win_start_x = attr.x;
        win_start_y = attr.y;
    
        /* Focus and raise the clicked window. */
        XSetInputFocus(dpy, w, RevertToPointerRoot, CurrentTime);
        XRaiseWindow(dpy, w);
    }
    
    /* Stop moving when the mouse button is released. */
    static void
    handle_button_release(XEvent *ev)
    {
        (void)ev;
        moving = 0;
        moving_win = None;
    }
    
    /* While moving, update window position on pointer motion. */
    static void
    handle_motion_notify(XEvent *ev)
    {
        if (!moving || moving_win == None)
            return;
    
        XMotionEvent *e = &ev->xmotion;
    
        int dx = e->x_root - move_start_root_x;
        int dy = e->y_root - move_start_root_y;
    
        int new_x = win_start_x + dx;
        int new_y = win_start_y + dy;
    
        XMoveWindow(dpy, moving_win, new_x, new_y);
    }
    
    /* Main event loop. */
    static void
    event_loop(void)
    {
        XEvent ev;
    
        while (running) {
            XNextEvent(dpy, &ev);
    
            switch (ev.type) {
            case MapRequest:
                handle_map_request(&ev);
                break;
            case ConfigureRequest:
                handle_configure_request(&ev);
                break;
            case ButtonPress:
                handle_button_press(&ev);
                break;
            case ButtonRelease:
                handle_button_release(&ev);
                break;
            case MotionNotify:
                handle_motion_notify(&ev);
                break;
            default:
                /* Ignore everything else for this minimal WM. */
                break;
            }
        }
    }
    
    int
    main(void)
    {
        /* Open display */
        dpy = XOpenDisplay(NULL);
        if (!dpy) {
            fprintf(stderr, "miniwm: cannot open display\n");
            return 1;
        }
    
        root = DefaultRootWindow(dpy);
    
        /* Catch SIGINT so Ctrl+C stops the WM cleanly. */
        signal(SIGINT, sigint_handler);
    
        /* Install error handler before asking for SubstructureRedirect. */
        XSetErrorHandler(xerror_handler);
    
        /* Become the window manager by selecting SubstructureRedirect on root.
         * If another WM is running, we'll get a BadAccess in xerror_handler.
         */
        XSelectInput(dpy, root,
                     SubstructureRedirectMask |
                     SubstructureNotifyMask |
                     ButtonPressMask |
                     ButtonReleaseMask |
                     PointerMotionMask);
    
        /* Force any errors to be processed now. */
        XSync(dpy, False);
    
        /* Optionally manage already-existing windows (useful in nested servers). */
        manage_existing_windows();
    
        /* Enter main loop. */
        event_loop();
    
        XCloseDisplay(dpy);
        return 0;
    }
    

    Building

    On a Debian/Ubuntu-like system:

    sudo apt-get install build-essential libx11-dev
    gcc -std=c99 -Wall -Wextra -O2 miniwm.c -o miniwm -lX11
    

    Running safely (nested X server)

    Use Xephyr so you don’t take over your main display:

    Xephyr :1 -screen 800x600 &
    DISPLAY=:1 ./miniwm &
    DISPLAY=:1 xterm &
    

    Now:

    • New windows (e.g. xterm) will appear with a thin border.
    • Click a window to focus and raise it.
    • Drag it with the left mouse button to move it around.

    If you’d like, I can extend this with simple keybindings, tiling, or a small bar while keeping it minimal.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.