This is a request to build a minimalistic reparenting window manager for X11 in C using Xlib. This is a complex topic but very educational. Let me break down what needs to be done:
- Connect to X server
- Set up event handling with SubstructureRedirectMask
- Handle CreateNotify events to detect new windows
- For each new window, create a frame window (parent)
- Reparent the window to the frame
- Add title bar and borders
- Handle basic window management events
Here's what I need to implement:
- Main structure to track windows
- X11 connection and setup
- Event loop
- Window frame creation
- Reparenting logic
- Event handlers for:
- CreateNotify (new windows)
- ConfigureRequest (window size changes)
- UnmapNotify (window destruction)
- MapRequest (window mapping)
- Expose (redraw title bar)
- ButtonPress (window dragging, resizing)
Let me create a comprehensive implementation:
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <signal.h>
#include <unistd.h>
#define FRAME_BORDER_WIDTH 2
#define TITLE_BAR_HEIGHT 25
#define BUTTON_SIZE 20
typedef struct {
Window window;
Window frame;
} ClientWindow;
typedef struct {
Window *clients;
Window *frames;
int client_count;
} WindowManager;
Display *display;
int screen;
Window root;
WindowManager wm;
void setup_wm(void);
void frame_window(Window window);
void unframe_window(Window window);
void handle_events(void);
void draw_title_bar(Window frame, const char *title);
void on_create_notify(XCreateWindowEvent *e);
void on_reparent_notify(XReparentEvent *e);
void on_map_request(XMapRequestEvent *e);
void on_configure_request(XConfigureRequestEvent *e);
void on_unmap_notify(XUnmapEvent *e);
void on_expose(XExposeEvent *e);
void on_button_press(XButtonPressedEvent *e);
void on_button_release(XButtonReleasedEvent *e);
void on_motion_notify(XMotionEvent *e);
I need to declare the event handler functions for managing window interactions like title bar rendering, window creation detection, reparenting, mapping requests, configuration changes, unmapping, expose events for redrawing, and mouse button and motion events for dragging and resizing operations. window
Window frame = XCreateSimpleWindow(display, root,
wa.x, wa.y,
wa.width + 2 * FRAME_BORDER_WIDTH,
wa.height + TITLE_BAR_HEIGHT + 2 * FRAME_BORDER_WIDTH,
FRAME_BORDER_WIDTH,
BlackPixel(display, screen),
WhitePixel(display, screen));
// Select events on frame
XSelectInput(display, frame,
SubstructureRedirectMask |
SubstructureNotifyMask |
ButtonPressMask |
ButtonReleaseMask |
PointerMotionMask |
ExposureMask);
// Reparent the
I'm creating a frame window with dimensions that account for the border and title bar, then setting up event handling on it before reparenting the client window into this frame.
XReparentWindow(display, window, frame,
FRAME_BORDER_WIDTH,
TITLE_BAR_HEIGHT + FRAME_BORDER_WIDTH);
// Store client and frame
wm.clients[wm.client_count] = window;
wm.frames[wm.client_count] = frame;
wm.client_count++;
// Map frame
XMapWindow(display, frame);
printf("Framed window 0x%lx with frame 0x%lx\n", window, frame);
The client window gets reparented into the frame at the appropriate offset, then I'm tracking both the client and its frame in the window manager's arrays before displaying the frame and logging the operation.
When unframing, I locate the window in my client list, get the frame's current position, unmap and destroy the frame, then reparent the window back to the root. I shift the remaining entries in both arrays to fill the gap and decrement the count. For drawing the title bar, I clear the designated area and render either the provided title or a default label using a graphics context. The event handlers check for create and reparent notifications—ignoring windows already processed through map requests and detecting when windows are unframed by checking if they're reparented to root.
When a map request arrives, I first check if the window is already in my client list to avoid duplicate framing. If it's new, I frame it, then map it to make it visible. For configure requests, I find the corresponding frame and apply the requested geometry changes to both the frame (accounting for decorations) and the client window itself.
If the window isn't tracked, I pass the configure request through directly. When a window unmaps, I locate it in my list and remove its frame. For expose events on frames, I need to redraw the title bar by fetching the window name and rendering it.
I'm tracking button state with static variables to handle window dragging. When the user presses a button on a frame's title bar, I capture the initial position and mark which frame is being dragged.
On button release, I simply clear the pressed state. During motion events, if a frame is actively being dragged, I calculate the delta between the current and previous cursor positions, then move the window accordingly while updating the last known coordinates.
The event loop continuously processes X events and dispatches them to their respective handlers based on type—create, reparent, map, configure, unmap, expose, and button/motion events all route to their corresponding functions.
In main, signal handlers are registered for SIGINT and SIGTERM to trigger cleanup. The display connection is established and validated, then the default screen and root window are retrieved. After printing startup information and initializing the window manager, the event handling loop begins.
Several issues need addressing: the struct initialization should be more explicit for compatibility, error handling could be improved, and the SubstructureRedirect mask setup requires better handling for cases where it can't be grabbed. The title bar rendering also needs refinement.
Minimalistic X11 Reparenting Window Manager
Here's a complete implementation of a minimalistic window manager with frame windows, title bars, and basic window management:
main.c
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/cursorfont.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <signal.h>
#include <unistd.h>
/* Configuration */
#define FRAME_BORDER_WIDTH 2
#define FRAME_BORDER_COLOR 0x1a1a1a
#define TITLE_BAR_HEIGHT 24
#define TITLE_BAR_COLOR 0x2a2a2a
#define TITLE_TEXT_COLOR 0xffffff
/* Client window structure */
typedef struct {
Window window;
Window frame;
} ClientWindow;
/* Window manager state */
typedef struct {
ClientWindow *windows;
int count;
int capacity;
Window active_frame;
int drag_x;
int drag_y;
} WindowManager;
/* Global state */
Display *display;
int screen;
Window root;
WindowManager wm;
Atom wm_protocols;
Atom wm_delete_window;
/* Function prototypes */
void setup_wm(void);
void cleanup(int sig);
void frame_window(Window window);
void unframe_window(Window window);
void handle_events(void);
void draw_title_bar(Window frame, Window client);
Window find_frame_by_window(Window window);
Window find_frame_by_frame(Window frame);
int window_is_managed(Window window);
void configure_frame(Window window, XConfigureRequestEvent *e);
/* Event handlers */
void on_map_request(XMapRequestEvent *e);
void on_configure_request(XConfigureRequestEvent *e);
void on_unmap_notify(XUnmapEvent *e);
void on_button_press(XButtonPressedEvent *e);
void on_button_release(XButtonReleasedEvent *e);
void on_motion_notify(XMotionEvent *e);
void on_expose(XExposeEvent *e);
/**
* Fatal error handler
*/
int x_error_handler(Display *d, XErrorEvent *e) {
if (e->error_code == BadAccess) {
fprintf(stderr, "Fatal: Another window manager is running\n");
exit(1);
}
fprintf(stderr, "X11 Error: request=%d, error=%d\n", e->request_code, e->error_code);
return 0;
}
/**
* Cleanup on exit
*/
void cleanup(int sig) {
printf("Cleaning up...\n");
/* Unframe all windows */
for (int i = wm.count - 1; i >= 0; i--) {
unframe_window(wm.windows[i].window);
}
free(wm.windows);
XCloseDisplay(display);
exit(0);
}
/**
* Initialize window manager
*/
void setup_wm(void) {
/* Allocate window list */
wm.capacity = 100;
wm.windows = malloc(sizeof(ClientWindow) * wm.capacity);
wm.count = 0;
wm.active_frame = None;
/* Set error handler */
XSetErrorHandler(x_error_handler);
/* Request substructure events on root */
XSelectInput(display, root,
SubstructureRedirectMask |
SubstructureNotifyMask |
ButtonPressMask |
ButtonReleaseMask |
PointerMotionMask);
/* Query atoms */
wm_protocols = XInternAtom(display, "WM_PROTOCOLS", False);
wm_delete_window = XInternAtom(display, "WM_DELETE_WINDOW", False);
/* Reparent existing windows */
Window root_return, parent_return;
Window *children;
unsigned int child_count;
XQueryTree(display, root, &root_return, &parent_return, &children, &child_count);
for (unsigned int i = 0; i < child_count; i++) {
XWindowAttributes wa;
XGetWindowAttributes(display, children[i], &wa);
if (!wa.override_redirect && wa.map_state == IsViewable) {
frame_window(children[i]);
}
}
XFree(children);
printf("Window Manager initialized. Found %d windows.\n", wm.count);
}
/**
* Frame a window with decorations
*/
void frame_window(Window window) {
if (window_is_managed(window)) {
return;
}
XWindowAttributes wa;
XGetWindowAttributes(display, window, &wa);
/* Ignore override_redirect windows */
if (wa.override_redirect) {
return;
}
/* Create frame window */
Window frame = XCreateSimpleWindow(
display, root,
wa.x, wa.y,
wa.width + 2 * FRAME_BORDER_WIDTH,
wa.height + TITLE_BAR_HEIGHT + 2 * FRAME_BORDER_WIDTH,
0,
FRAME_BORDER_COLOR,
FRAME_BORDER_COLOR
);
/* Set window properties */
XSelectInput(display, frame,
SubstructureRedirectMask |
SubstructureNotifyMask |
ButtonPressMask |
ButtonReleaseMask |
PointerMotionMask |
ExposureMask);
/* Select for window close events */
XSelectInput(display, window,
PropertyChangeMask |
StructureNotifyMask |
FocusChangeMask);
/* Reparent the window */
XReparentWindow(display, window, frame,
FRAME_BORDER_WIDTH,
TITLE_BAR_HEIGHT + FRAME_BORDER_WIDTH);
/* Store client window info */
if (wm.count >= wm.capacity) {
wm.capacity *= 2;
wm.windows = realloc(wm.windows, sizeof(ClientWindow) * wm.capacity);
}
wm.windows[wm.count].window = window;
wm.windows[wm.count].frame = frame;
wm.count++;
/* Map frame and window */
XMapWindow(display, frame);
XMapWindow(display, window);
/* Focus the new frame */
XSetInputFocus(display, window, RevertToPointerRoot, CurrentTime);
printf("Framed window 0x%lx (frame: 0x%lx)\n", window, frame);
}
/**
* Unframe a window and restore it to root
*/
void unframe_window(Window window) {
for (int i = 0; i < wm.count; i++) {
if (wm.windows[i].window == window) {
Window frame = wm.windows[i].frame;
XWindowAttributes wa;
XGetWindowAttributes(display, frame, &wa);
/* Unmap and reparent back to root */
XUnmapWindow(display, frame);
XReparentWindow(display, window, root, wa.x, wa.y);
XDestroyWindow(display, frame);
/* Remove from list */
for (int j = i; j < wm.count - 1; j++) {
wm.windows[j] = wm.windows[j + 1];
}
wm.count--;
printf("Unframed window 0x%lx\n", window);
return;
}
}
}
/**
* Check if window is managed
*/
int window_is_managed(Window window) {
for (int i = 0; i < wm.count; i++) {
if (wm.windows[i].window == window) {
return 1;
}
}
return 0;
}
/**
* Find frame window for given client window
*/
Window find_frame_by_window(Window window) {
for (int i = 0; i < wm.count; i++) {
if (wm.windows[i].window == window) {
return wm.windows[i].frame;
}
}
return None;
}
/**
* Find client window for given frame window
*/
Window find_frame_by_frame(Window frame) {
for (int i = 0; i < wm.count; i++) {
if (wm.windows[i].frame == frame) {
return wm.windows[i].window;
}
}
return None;
}
/**
* Draw window title bar
*/
void draw_title_bar(Window frame, Window client) {
XWindowAttributes wa;
XGetWindowAttributes(display, frame, &wa);
/* Get window title */
char *title = NULL;
XFetchName(display, client, &title);
if (!title) {
title = malloc(8);
strcpy(title, "Window");
}
/* Create GC */
XGCValues gc_values;
gc_values.foreground = TITLE_BAR_COLOR;
gc_values.background = FRAME_BORDER_COLOR;
GC gc = XCreateGC(display, frame, GCForeground | GCBackground, &gc_values);
/* Draw title bar background */
XFillRectangle(display, frame, gc, 0, 0, wa.width, TITLE_BAR_HEIGHT);
/* Draw title text */
XSetForeground(display, gc, TITLE_TEXT_COLOR);
XDrawString(display, frame, gc, 6, 16, title, strlen(title));
/* Draw close button area */
XSetForeground(display, gc, FRAME_BORDER_COLOR);
int btn_x = wa.width - 24;
XDrawRectangle(display, frame, gc, btn_x, 2, 20, 20);
XDrawString(display, frame, gc, btn_x + 6, 16, "X", 1);
XFreeGC(display, gc);
if (title) XFree(title);
}
/**
* Handle MapRequest event
*/
void on_map_request(XMapRequestEvent *e) {
if (!window_is_managed(e->window)) {
frame_window(e->window);
}
XMapWindow(display, e->window);
}
/**
* Handle ConfigureRequest event
*/
void on_configure_request(XConfigureRequestEvent *e) {
Window frame = find_frame_by_window(e->window);
if (frame != None) {
/* Configure frame */
XWindowChanges wc;
memset(&wc, 0, sizeof(wc));
wc.x = e->x;
wc.y = e->y;
wc.width = e->width + 2 * FRAME_BORDER_WIDTH;
wc.height = e->height + TITLE_BAR_HEIGHT + 2 * FRAME_BORDER_WIDTH;
wc.border_width = 0;
unsigned int mask = 0;
if (e->value_mask & CWX) mask |= CWX;
if (e->value_mask & CWY) mask |= CWY;
if (e->value_mask & CWWidth) mask |= CWWidth;
if (e->value_mask & CWHeight) mask |= CWHeight;
XConfigureWindow(display, frame, mask, &wc);
/* Configure client window */
memset(&wc, 0, sizeof(wc));
wc.width = e->width;
wc.height = e->height;
wc.border_width = 0;
XConfigureWindow(display, e->window, CWWidth | CWHeight | CWBorderWidth, &wc);
} else {
/* Not managed, pass through */
XWindowChanges wc;
memset(&wc, 0, sizeof(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(display, e->window, e->value_mask, &wc);
}
}
/**
* Handle UnmapNotify event
*/
void on_unmap_notify(XUnmapEvent *e) {
if (e->event == e->window) { /* Real unmap */
unframe_window(e->window);
}
}
/**
* Handle mouse button press
*/
void on_button_press(XButtonPressedEvent *e) {
Window client = find_frame_by_frame(e->window);
if (client == None) {
return;
}
XWindowAttributes wa;
XGetWindowAttributes(display, e->window, &wa);
if (e->y < TITLE_BAR_HEIGHT) {
/* Click on title bar */
if (e->button == Button1) {
/* Drag window */
wm.active_frame = e->window;
wm.drag_x = e->x_root - wa.x;
wm.drag_y = e->y_root - wa.y;
XRaiseWindow(display, e->window);
XSetInputFocus(display, client, RevertToPointerRoot, CurrentTime);
/* Check for close button click */
if (e->x > wa.width - 25) {
/* Close window */
XEvent close_event;
memset(&close_event, 0, sizeof(close_event));
close_event.xclient.type = ClientMessage;
close_event.xclient.window = client;
close_event.xclient.message_type = wm_protocols;
close_event.xclient.format = 32;
close_event.xclient.data.l[0] = wm_delete_window;
close_event.xclient.data.l[1] = CurrentTime;
XSendEvent(display, client, False, NoEventMask, &close_event);
}
} else if (e->button == Button3) {
/* Right click - resize from corner */
wm.active_frame = e->window;
wm.drag_x = e->x_root;
wm.drag_y = e->y_root;
}
}
}
/**
* Handle mouse button release
*/
void on_button_release(XButtonReleasedEvent *e) {
wm.active_frame = None;
}
/**
* Handle mouse motion
*/
void on_motion_notify(XMotionEvent *e) {
if (wm.active_frame == None) {
return;
}
XWindowAttributes wa;
XGetWindowAttributes(display, wm.active_frame, &wa);
/* Check which button is pressed */
if (e->state & Button1Mask) {
/* Drag window - left button */
int new_x = e->x_root - wm.drag_x;
int new_y = e->y_root - wm.drag_y;
XMoveWindow(display, wm.active_frame, new_x, new_y);
} else if (e->state & Button3Mask) {
/* Resize window - right button */
int new_width = e->x_root - wm.drag_x;
int new_height = e->y_root - wm.drag_y;
new_width = (new_width > 100) ? new_width : 100;
new_height = (new_height > 50) ? new_height : 50;
XWindowChanges wc;
wc.width = new_width;
wc.height = new_height;
XConfigureWindow(display, wm.active_frame,
CWWidth | CWHeight, &wc);
/* Resize client */
wc.width = new_width - 2 * FRAME_BORDER_WIDTH;
wc.height = new_height - TITLE_BAR_HEIGHT - 2 * FRAME_BORDER_WIDTH;
Window client = find_frame_by_frame(wm.active_frame);
if (client != None) {
XConfigureWindow(display, client, CWWidth | CWHeight, &wc);
}
}
}
/**
* Handle Expose event (window needs redraw)
*/
void on_expose(XExposeEvent *e) {
if (e->count > 0) return; /* Only redraw on last exposure */
Window client = find_frame_by_frame(e->window);
if (client != None) {
draw_title_bar(e->window, client);
}
}
/**
* Main event loop
*/
void handle_events(void) {
XEvent event;
while (1) {
XNextEvent(display, &event);
switch (event.type) {
case MapRequest:
on_map_request(&event.xmaprequest);
break;
case ConfigureRequest:
on_configure_request(&event.xconfigurerequest);
break;
case UnmapNotify:
on_unmap_notify(&event.xunmap);
break;
case ButtonPress:
on_button_press(&event.xbutton);
break;
case ButtonRelease:
on_button_release(&event.xbutton);
break;
case MotionNotify:
on_motion_notify(&event.xmotion);
break;
case Expose:
on_expose(&event.xexpose);
break;
}
}
}
/**
* Main entry point
*/
int main(int argc, char *argv[]) {
signal(SIGINT, cleanup);
signal(SIGTERM, cleanup);
/* Connect to X server */
display = XOpenDisplay(NULL);
if (!display) {
fprintf(stderr, "Error: Cannot open X11 display\n");
return 1;
}
screen = DefaultScreen(display);
root = RootWindow(display, screen);
printf("=== Minimalistic X11 Window Manager ===\n");
printf("Display: %s\n", DisplayString(display));
printf("Screen: %d\n", screen);
printf("Root: 0x%lx\n", root);
printf("Press Ctrl+C to exit\n");
printf("Commands:\n");
printf(" - Left click + drag title bar: Move window\n");
printf(" - Right click + drag: Resize window\n");
printf(" - Click X button: Close window\n\n");
setup_wm();
handle_events();
return 0;
}
Makefile
CC = gcc
CFLAGS = -Wall -Wextra -O2 -std=c99
LDFLAGS = -lX11
TARGET = wm
SOURCES = main.c
OBJECTS = $(SOURCES:.c=.o)
all: $(TARGET)
$(TARGET): $(OBJECTS)
$(CC) $(CFLAGS) -o $@ $^ $(LDFLAGS)
%.o: %.c
$(CC) $(CFLAGS) -c $< -o $@
run: $(TARGET)
./$(TARGET)
clean:
rm -f $(OBJECTS) $(TARGET)
.PHONY: all run clean
Features
✅ Window Framing: Creates decorative frames around windows
✅ Title Bars: Displays window titles with close buttons
✅ Mouse Control:
- Left-click drag: Move windows
- Right-click drag: Resize windows
- Close button: Gracefully close windows
✅ Event Handling: Properly manages MapRequest, ConfigureRequest, UnmapNotify
✅ Window Discovery: Automatically frames existing windows on startup
✅ Error Handling: Detects if another WM is running
Compilation & Usage
# Compile
make
# Run
./wm
# Or with Xephyr (nested X server for testing)
Xephyr :1 -screen 1024x768 &
DISPLAY=:1 ./wm &
DISPLAY=:1 xterm &
Key Concepts
- SubstructureRedirectMask: Intercepts window creation/configuration
- Reparenting: Moves client windows into frame containers
- Event Handling: Responds to MapRequest, ConfigureRequest, ExposureMask
- Window List: Maintains mapping between client and frame windows
- Title Bar: Custom rendering for decorations
This is a minimal but functional window manager suitable for learning!