rust-dwm
A guided map of the rewrite

Understand the desktop.
Then design the types.

X11 provides the machinery. DWM chooses how windows behave. The Rust rewrite makes those decisions and their ownership explicit.

01
The mental model

Windows, tags and monitors: start here.

Start with an ordinary desktop

You have a laptop display and an external display. A terminal and a browser are running. Each application creates a rectangular window. DWM decides where those rectangles go, which ones you can see and which one receives your typing. It does not draw the terminal’s text or the browser’s page.

1

Monitor = one display area

A monitor record describes a rectangle in the desktop’s shared coordinate space. Example: laptop (x=0, y=0, w=1920, h=1080); external display (1920, 0, 2560, 1440). The external display starts to the right of the laptop.

Each has its own visible tags, layout and selected window. A 24-pixel top bar leaves the laptop’s work area at (0, 24, 1920, 1056). Tiling uses this work area; fullscreen uses the entire display rectangle.

2

Tag = a label attached to windows

Tags group windows so you can choose what to see. Name tag 1 “code”, tag 2 “web” and tag 3 “chat”. A window can have several labels. A monitor’s view is the set of labels currently selected for display.

For a window assigned to that monitor, it is visible when at least one of its labels is selected. Switching the view changes this selection; it does not change the window’s labels or move it to another monitor.

3

State = remembered facts

“State” means values kept between events: which monitor owns a window, its tags, the selected view, the layout and the selected window. Without these records, the next key press would have no context.

C DWM keeps these facts in global variables and Client/Monitor records. The proposed Rust State is the owner of those records, so methods can update them together.

Try the tag rule on four windows

All four windows below belong to the laptop monitor. The external monitor has a separate view and its own assigned windows.

Window and its tagsView {1}: codeView {2}: webView {1, 2}: both
Terminal: {1}VisibleHiddenVisible
Browser: {2}HiddenVisibleVisible
Documentation: {1, 2}VisibleVisibleVisible
Chat: {3}HiddenHiddenHidden

A bit mask stores this set compactly: tag 1 is 001, tag 2 is 010, and both are 011. Visibility tests window_tags & view_tags != 0. Rust’s TagSet wraps this number to prevent accidentally using a window ID or an empty set where tags are required.

Placement and focus are separate choices

Tiled
DWM calculates the window’s position and size as part of a group.
Floating
The window keeps an individual position and size; you can move or resize it.
Monocle
A layout that gives each visible tiled window the entire work area; overlapping windows cover one another.
Focus
The window receiving keyboard input. Selecting a tag may require choosing a new focused window.
Stacking
The front-to-back order of overlapping windows. Raising a window brings it in front.

Two places remember different facts

The X server remembers actual window rectangles, borders, parent relationships, properties and input focus. DWM remembers its own choices: tags, layout order, previous view and what to restore after fullscreen.

For example, tag numbers are DWM’s local bookkeeping. The server does not calculate whether tag 2 should be shown. DWM checks its records and sends requests that implement that decision.

In this C baseline, “hidden by tags” means moved offscreen. The window remains mapped (enabled for display by X11); hidden does not necessarily mean unmapped.

What “X11” actually names

X11 is a protocol: defined messages exchanged with an X server, usually the Xorg process. The server manages display resources and input. Xlib is the C library DWM uses to send those messages. x11rb is the proposed Rust library for the same conversation. Neither library supplies DWM’s tag or tiling rules.

An application connected to the server is called an X client. DWM is one too. Confusingly, DWM’s C Client struct means its local record for one managed application window, not the application’s connection.

An application and DWM each connect to an X server. DWM is itself an X client with permission to manage other windows.

Protocol model: Xlib overview. The application renders its content; DWM does not draw terminal text or browser pages. A separate compositor, if present, handles compositing effects.

A

A window is a resource

A window exists in the server and has a numeric ID. DWM’s Client is an additional local record containing policy state for a managed window.

WindowIdserver resourceClientIdlocal managed record
B

The root is the parent

The root window represents an X screen’s top-level window tree. Ordinary application windows are children. DWM selects management events there.

An X screen is not necessarily one physical monitor. DWM discovers monitor rectangles separately.

C

Showing is a request

A newly created window is initially unmapped. The application requests mapping. With root redirection selected, the server asks DWM to handle eligible map requests.

override_redirect is a flag an application sets to bypass the WM, commonly for menus or tooltips. Those windows bypass this management path.

The key handoff

SubstructureRedirectMask lets the WM intercept eligible map/configure requests on the root’s children. Only one client can select it on that root. That is why a second WM cannot simply take over the same screen.

Four things travelling over the connection

Request
Client → server: map, configure, focus or read a property.
Reply
Server → requesting client: requested data, such as attributes.
Event
Server → interested client: something happened, or policy is needed.
Error
A request failed; for example, the target window disappeared.

Metadata gives the WM context

Properties are typed data attached to windows. An atom is a numeric handle for a name such as WM_NAME. It identifies the property; it is not the property’s value.

  • WM_NORMAL_HINTSSize limits, increments and aspect constraints
  • WM_TRANSIENT_FORWhich window a dialog belongs to
  • WM_PROTOCOLSSupported messages such as graceful close
  • _NET_WM_STATEExtended states such as fullscreen

ICCCM (Inter-Client Communication Conventions Manual) and EWMH (Extended Window Manager Hints) define property names and messages applications and window managers agree to understand. The rewrite targets the subset DWM 6.8 supports.

The concrete API boundary

DWM keeps a connection named dpy. X11 resources have numeric identifiers; root identifies the desktop’s root window. One X screen can span several physical monitors, so “screen” and “monitor” are not interchangeable. The table follows real calls in the downloaded C source.

What needs to happenC Xlib APIRust x11rb equivalentResponsibility
Connect to the server selected by DISPLAYXOpenDisplay(NULL)x11rb::connect(None)Backend establishes a connection; it does not choose a layout.
Find the root windowRootWindow(dpy, screen)conn.setup().roots[screen].rootGet the server’s existing desktop parent resource.
Ask to intercept child-window requestsXSelectInput, XChangeWindowAttributes with SubstructureRedirectMaskchange_window_attributes with SUBSTRUCTURE_REDIRECTServer grants this to one WM per root; failure means another WM owns it.
Inspect existing windowsXQueryTree, XGetWindowAttributesquery_tree(...).reply(), get_window_attributes(...).reply()Manager decides which returned children to adopt.
Wait for the next eventXNextEventwait_for_event()Backend receives a message; manager selects the handler.
Apply a calculated rectangle and borderXConfigureWindow, XMoveResizeWindowconfigure_windowLayout calculates coordinates; backend sends them; server applies them.
Allow a new window to be displayedXMapWindowmap_windowManager admits the window; server maps it.
Route keyboard input to a windowXSetInputFocusset_input_focusManager picks an eligible window and respects its focus conventions.
Reserve a keyboard shortcutXGrabKeygrab_keyInput setup asks the server to deliver matching key presses to DWM.
Read or publish window metadataXGetWindowProperty, XChangeProperty, XInternAtomget_property, change_property, intern_atomBackend validates protocol data; manager interprets title, hints and fullscreen requests.
Ask an application to close gracefullyXSendEvent carrying WM_DELETE_WINDOWsend_event carrying a ClientMessageEventApplication handles the message if it advertises support.

A small Rust example: claim the root and receive requests

This demonstrates the real library calls, rather than implementing a complete window manager. A production handler must first read attributes and hints, create its local record, arrange windows and handle failures. Run such experiments in a separate test X server; a normal desktop already has a WM.

Real x11rb API calls · incomplete WM demonstrationRUST
use x11rb::{connection::Connection, protocol::{Event, xproto::{
    ConnectionExt, ChangeWindowAttributesAux, EventMask,
}}};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let (conn, screen) = x11rb::connect(None)?;
    let root = conn.setup().roots[screen].root;
    let events = EventMask::SUBSTRUCTURE_REDIRECT
        | EventMask::SUBSTRUCTURE_NOTIFY;
    conn.change_window_attributes(root,
        &ChangeWindowAttributesAux::new().event_mask(events)
    )?.check()?; // Fail if another WM owns this root.
    conn.flush()?;

    loop {
        match conn.wait_for_event()? {
            Event::MapRequest(request) => {
                let attrs = conn.get_window_attributes(
                    request.window
                )?.reply()?;
                if !attrs.override_redirect {
                    // Next: create Client, calculate layout,
                    // configure_window, map_window, choose focus.
                }
            }
            _ => {} // Full WM handles other events too.
        }
    }
}

.reply() waits for query data. .check() checks whether a request failed. Claiming the root must fail startup when another WM already owns it. Later, a window may disappear between an event and a query; that failure should remove stale local records rather than terminate the desktop.

Follow one rectangle through the layers

Geometry means position and size: (x, y, width, height). DWM’s tile layout has a master area for the first windows and a second column for the rest. “Master count” is how many windows occupy the first area; “master width fraction” is its share of the monitor’s work-area width. Size hints are application preferences such as minimum dimensions or resizing in whole character cells.

MapRequest: window 42→Read attributes→Client { tags: {1}, monitor: laptop }→Layout computes (0,24,1054,1054)→Configure + map + focus

For a concrete calculation, suppose the work area is 1920 × 1056, there are two unconstrained tiled windows, master count is 1, master width fraction is 0.55, and borders are 1 pixel. The master’s outer width is floor(1920 × 0.55) = 1056; its content is 1054 × 1054 because borders occupy two pixels in each dimension. The second window starts at x=1056, with content 862 × 1054. These are layout decisions, then arguments to X11 configure requests. Size hints can alter this result.

A tag switch: the exact records that change

Remembered factBefore pressing the shortcutAfter selecting tag 2
Laptop current view{1}{2}
Laptop previous view{3}{1}
Terminal’s tags / monitor{1} / laptop{1} / laptop
Browser’s tags / monitor{2} / laptop{2} / laptop
Selected clientTerminalA visible client chosen from focus history, for example Browser

C flow: keypress → view → focus → arrange → showhide / arrangemon → restack. Rust flow: handle_key → Action::ViewTags → State::apply_action → reconcile_monitor. The changed selection is a local record update. Moving the terminal offscreen and configuring/focusing the browser are separate X11 requests. The previous-view shortcut can return to {1} because we kept that set.

Find each responsibility in the actual C source

Read dwm.c by function: main / setup / checkotherwm connect and claim management; updategeom / updatebarpos discover display rectangles and work areas; maprequest / manage / unmanage add and remove records; view / toggleview / tag change views or memberships; tile / monocle / applysizehints calculate placement; resizeclient / showhide / focus / restack issue geometry, visibility, focus and stacking requests; drawbar paints the bar. C combines these responsibilities in one file; the proposed Rust owners in the next table separate them explicitly.

Exactly where each responsibility lives

OwnerWhat it does, and whyExample
ApplicationCreates its windows, paints their content and publishes preferences.Terminal requests character-sized resize increments.
X serverStores resources, applies requests and routes input/events.Moves window 42 when it receives a configure request.
X11BackendOwns the connection and atom IDs; translates typed operations into protocol messages.Reads a size-hints property and validates its format.
StateOwns client/monitor records and keeps their relationships consistent.Removing a client also removes its IDs from monitor lists.
ClientRemembers one managed window’s tags, placement and fullscreen restoration.Save normal geometry once when entering fullscreen.
Monitor and TagViewRemember one display’s current selection and layout settings.View {2} replaces {1}; previous view remains available.
Layout calculationTurns visible windows, work area and size constraints into rectangles.Calculate the two rectangles above.
WindowManagerCoordinates an event across records, layout and server requests.MapRequest → adopt → arrange → map → focus.
Bar renderer and configurationRenderer draws tags/title/status; configuration supplies names, rules and shortcuts.Highlight tag 2 after its view is selected.
Two terms used later

Reconcile means “make the server reflect our updated records”: move hidden windows, calculate visible rectangles, choose focus and redraw the bar. An invariant is a rule that must always hold, such as “every client’s monitor ID identifies an existing monitor”. Methods preserve these rules so callers cannot accidentally leave broken relationships.

Sending is not completion

Requests may be buffered. flush() sends pending requests; it does not prove another client has processed its events. Replies, checked errors and observable conditions matter for reliable tests.

02
From an event to a visible result

Follow the code, one change at a time.

Connect→Claim root events→Set up monitors & bar→Scan existing windows→Run event loop

The startup path is main → setup → scan → run. The scan adopts eligible windows that already exist. After that, the event loop waits for changes rather than repeatedly polling every application.

The actual C loop

dwm.c · run()C
void
run(void)
{
	XEvent ev;
	/* main event loop */
	XSync(dpy, False);
	while (running && !XNextEvent(dpy, &ev))
		if (handler[ev.type])
			handler[ev.type](&ev); /* call handler */
}

handler[ev.type] chooses a callback. State such as mons, selmon and dpy lives in globals.

The Rust shape

Proposed event dispatch · illustrativeRUST
fn run(&mut self) -> Result<(), WmError> {
    while self.running {
        let event = self.backend.next_event()?;
        match event {
            Event::MapRequest(request) =>
                self.manage_window(request.window)?,
            Event::KeyPress(key) =>
                self.handle_key(key)?,
            other => self.handle_other(other)?,
        }
        self.backend.flush()?;
    }
    Ok(())
}

Illustrative integration sketch: methods own their dependencies; an enum match makes event dispatch explicit. This snippet is not a complete implementation.

LifecycleYou open a terminalMapRequest
  1. Application creates and asks to map

    The server resource exists, but DWM does not yet have a managed-client record.

    application → X server
  2. Server redirects the request

    DWM receives MapRequest. It checks attributes and ignores override-redirect or already-managed cases.

    run → maprequest
  3. Build the client’s policy state

    Read title, hints and transient parent. Inherit a managed parent’s tags/monitor, or apply ordered rules. Decide floating placement.

    manage → Client
  4. Attach and arrange

    Insert into the monitor’s layout order and focus history. Calculate visible window geometry and apply hints.

    attach → arrange → tile → resize
  5. Issue management requests

    Configure geometry and borders, publish state, map the window and negotiate focus. The application draws its own content.

    DWM → X server → application
InputYou switch to tag 2KeyPress
  1. Resolve a grabbed binding

    The X server delivers the matching key event to DWM. Normalize lock modifiers and look up its binding.

    keypress → view
  2. Change the monitor’s view

    view changes the selected tag slot and preserves the other slot. Clients keep their existing tag memberships.

    TagView::select(tags)
  3. Reconcile focus and visibility

    Choose an eligible visible client. C DWM moves hidden windows offscreen while leaving them mapped.

    focus → arrange → showhide
  4. Place the visible clients

    Apply the current layout, update stacking and redraw the bar.

    arrangemon → tile/monocle → restack
ProtocolAn application enters fullscreenClientMessage
  1. Decode the requested state

    The application sends an EWMH state message through the X server. Validate its format and target.

    clientmessage → setfullscreen
  2. Preserve normal state

    Save placement, geometry and border once. A repeated entry must not overwrite the saved state.

    Client::enter_fullscreen
  3. Use the full screen rectangle

    Set zero border, resize to the monitor’s full area, publish fullscreen state and raise the window.

    _NET_WM_STATE → resizeclient
  4. Restore and arrange on exit

    Recover saved normal state. A tiled client can then receive newly calculated tiled geometry.

    Client::leave_fullscreen → arrange
CleanupA window disappearsDestroyNotify
  1. Resolve the window ID

    An unknown or already-removed window must be handled safely.

    destroynotify → wintoclient
  2. Remove all local relationships

    Clear lookup, layout membership and focus-history entries. Cancel an active drag for that client.

    unmanage → detach → detachstack
  3. Repair focus and layout

    Choose remaining focus, update the client list and rearrange. Do not send restoration requests to a destroyed window.

    focus → updateclientlist → arrange

A quick event map

ConfigureRequestApplication asks for geometryRespect floating requests or enforce managed layout
PropertyNotifyMetadata changesUpdate the relevant title, hints or state
ExposeA region needs repaintingRedraw DWM’s bar
MappingNotifyKeyboard mapping changesRefresh key translation and grabs
03
Make ownership visible

The server has windows. The WM has policy.

Rust structs represent the decisions DWM remembers between events. They do not replace the server’s window resources.

Read the original C structsClient and Monitor from the frozen baseline
dwm.c · ClientC
struct Client {
	char name[256];
	float mina, maxa;
	int x, y, w, h;
	int oldx, oldy, oldw, oldh;
	int basew, baseh, incw, inch, maxw, maxh, minw, minh, hintsvalid;
	int bw, oldbw;
	unsigned int tags;
	int isfixed, isfloating, isurgent, neverfocus, oldstate, isfullscreen;
	Client *next;
	Client *snext;
	Monitor *mon;
	Window win;
};
dwm.c · MonitorC
struct Monitor {
	char ltsymbol[16];
	float mfact;
	int nmaster;
	int num;
	int by;               /* bar geometry */
	int mx, my, mw, mh;   /* screen size */
	int wx, wy, ww, wh;   /* window area  */
	unsigned int seltags;
	unsigned int sellt;
	unsigned int tagset[2];
	int showbar;
	int topbar;
	Client *clients;
	Client *sel;
	Client *stack;
	Monitor *next;
	Window barwin;
	const Layout *lt[2];
};

next and snext are different linked orders. mon is a back pointer. In Rust, stores own the values and typed IDs express these relationships.

Identity

WindowId / ClientId

A server window ID can be reused. A managed-client ID names this local lifetime. Use distinct types so the compiler catches accidental mixing.

Distinct identity typesRUST
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct WindowId(u32);
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct ClientId(u64);
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct MonitorId(u64);
InvariantRemove the window lookup when the client is removed.
Local state

Client

Remembers one window’s tags, monitor and presentation. Its methods protect local transitions; the manager coordinates effects. This compact sketch omits title and size-hint fields.

Client · compiled policy sketchRUST
#[derive(Debug)]
pub struct Client {
    window: WindowId,
    monitor: MonitorId,
    tags: TagSet,
    presentation: Presentation,
    urgent: bool,
}
Owns behavioris_visible_on, enter_fullscreen, leave_fullscreen
Per-monitor policy

Monitor

Owns a view and two distinct orders: tiling order and focus history. A monitor-wide floating layout does not change every client’s saved placement.

Monitor · compiled policy sketchRUST
#[derive(Debug)]
pub struct Monitor {
    screen: Rect,
    work_area: Rect,
    view: TagView,
    layouts: LayoutSelection,
    layout_order: Vec<ClientId>,
    focus_history: Vec<ClientId>,
    selected_client: Option<ClientId>,
}
InvariantEvery listed client belongs to this live monitor; lists have no duplicate IDs.
Transitions

TagView

Owns the current and previous nonempty tag sets. Selecting a view preserves the old one; toggling edits only the current view.

TagView · compiled transitionsRUST
/// Mirrors dwm's two tag slots. Toggle edits the current slot in place.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct TagView {
    current: TagSet,
    previous: TagSet,
}
impl TagView {
    pub fn new(tags: TagSet) -> Self {
        Self {
            current: tags,
            previous: tags,
        }
    }
    pub fn current(&self) -> TagSet {
        self.current
    }
    pub fn select(&mut self, tags: TagSet) -> bool {
        if tags == self.current {
            return false;
        }
        self.previous = self.current;
        self.current = tags;
        true
    }
    pub fn toggle(&mut self, tags: TagSet) -> bool {
        match self.current.toggled(tags) {
            Some(next) => {
                self.current = next;
                true
            }
            None => false,
        }
    }
    pub fn restore_previous(&mut self) {
        std::mem::swap(&mut self.current, &mut self.previous);
    }
}
InvariantToggling away the last visible tag is rejected.

Turn an argument union into intent

C bindings pair a callback with a generic Arg. The callback must interpret the right union member. An enum makes each action’s input explicit.

Arg · current C representationC
typedef union {
	int i;
	unsigned int ui;
	float f;
	const void *v;
} Arg;

Read the action at the call site

Action · typed variantsRUST
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Action {
    ViewTags(TagSet),
    ToggleView(TagSet),
    PreviousView,
    SetLayout(Layout),
}

PreviousView directly expresses the special behavior represented by a zero-valued argument in C.

Methods protect local rules. The manager coordinates shared work.

Client::enter_fullscreen() saves state. WindowManager updates geometry, focus and protocol properties. Pure helpers remain useful when an algorithm has no natural receiver.

Encode restoration in the type

Presentation · state carries restorationRUST
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Placement {
    Tiled,
    Floating,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct NormalState {
    placement: Placement,
    geometry: Rect,
    border: BorderWidth,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Presentation {
    Normal(NormalState),
    Fullscreen {
        restore: NormalState,
        geometry: Rect,
    },
}

Fullscreen carries its restore state. Urgency stays independent; it is not another exclusive presentation mode.

Use named reconciliation

Orchestration · illustrativeRUST
fn handle_action(&mut self, action: Action)
    -> Result<(), WmError>
{
    if let Some(monitor) =
        self.state.apply_action(action)?
    {
        self.reconcile_monitor(monitor)?;
    }
    self.backend.flush()?;
    Ok(())
}
Why this shape reads well

The action names intent, the state method names the mutation, and reconciliation names the effects. The call path is visible without searching mutable globals.

The project’s reusable Rust readability skill turns these ownership, naming, error and protocol rules into a code-review checklist.

A subtle dependency inside tiling

Ideal size→Apply size hints→Actual outer height→Next client’s Y position

C DWM advances the tile cursor using the size after constraints. Applying hints only after calculating every rectangle changes placement. Keep this dependency explicit and test it.

04
Build confidence before replacing the desktop

Port behavior in verifiable slices.

0–1

Baseline & model

Freeze C 6.8, record behavior, implement tags, geometry, state and pure layouts.

2–3

A working vertical slice

Connect, adopt a terminal, tile, focus, close and exit. Add rules and input.

4–5

Protocols & presentation

Fullscreen, dialogs, monitors, bar drawing and validated configuration.

6

Release candidate

Differential tests, real applications and recorded session trials pass.

Shared input

One scenario

Same windows, properties, input and configuration.

C DWM 6.8fresh X server
Rust WMfresh X server
Observable result

Compare behavior

Geometry, focus, visibility, stacking and protocol properties.

Start with characterization

The C archive has no automated suite. Convert transient.c into a bounded, asserted external scenario first.

Keep expectations independent

Use the actual C functions for policy fixtures and an external Xlib client for integration. Keep the baseline unchanged.

Prove the tests can fail

Inject wrong previous-view handling, fullscreen restore and hint placement. Each relevant assertion must catch its defect.

Four Rust policy-sketch tests currently pass. The runnable Rust WM and full X11 regression harness are planned work.

05
Develop without replacing your desktop

Use a nested desktop; add a VM only when needed.

The lightweight default is Xephyr for visible experiments and Xvfb for automatic tests, both connected to a separate X server. Neither requires a virtual machine. Keep QEMU/KVM as an optional stronger boundary for guest-session and system-change testing.

Xephyr is the light choice

Xephyr is an X server that draws a separate desktop inside a window on an existing X display. DWM connects to Xephyr, so it can arrange windows inside that test desktop without becoming your normal desktop’s WM. Xephyr is not a VM or hypervisor. It isolates window trees and keyboard routing; its programs still have the filesystem privileges of the user running them.

What is Xephyr?

Xephyr is the name of a nested X server. It runs as a program on your current graphical desktop, opens a window, and uses that window to display a second, independent X desktop. Start test DWM with DISPLAY=:100 and it manages the second desktop inside Xephyr. The host desktop still manages the Xephyr window.

It is not a VM or hypervisor, and the name does not expand to a project acronym. The X.Org manual describes how it draws to a window on an existing X display.

VM provider, if you need one

A hypervisor runs a separate guest computer. On Linux, the light practical choice is QEMU + KVM: QEMU builds the virtual machine; KVM uses CPU virtualization support. Libvirt and virt-manager can manage it but add another management layer.

This host reports VT-x but has no visible /dev/kvm, QEMU, or libvirt installation. The VM can come later; Xephyr is enough for the normal edit-and-try loop.

What happens if the Rust WM crashes?

The windows in Xephyr may remain on its unmanaged test desktop. Close or restart the test. The outer desktop still has its normal WM. Because Xephyr runs on the same Linux host, its programs can still access files allowed to your user. Use the optional VM when you need a separate guest disk and operating system.

1

Pure Rust tests

Run tags, view history, geometry and layout calculations without X11. Fast feedback on every change.

2

Xvfb: automatic checks

A test X server with its display stored in memory. Run the same scenario against C and Rust on fresh servers; compare rectangles, focus and properties.

3

Xephyr: watch the result

A nested X server displayed in a window on your current desktop. Open dialogs, switch tags and debug drag/resize while seeing the result.

DISPLAY picks the server

DISPLAY=:100 tells a program to connect to local X server number 100; it is not monitor number 100. Every test application and WM must use the allocated test server. The runner sets this per process rather than changing your whole shell environment.

XAUTHORITY names the file containing that server’s authorization credential. Each run gets its own credential and private run directory.

The runner owns the experiment

  1. Start a fresh authenticated test X server.
  2. Check it is ready and has required extensions.
  3. Start exactly one WM and verify it claimed management.
  4. Run the scenario and save observations and logs.
  5. Stop only that run’s processes, including on crashes and timeouts.
  6. Repeat with the other WM and compare results.
Add VM only if needed→Build C baseline→Validate runner cleanup→C-only scenarios→C / Rust comparison

Later, test the WM as the guest’s actual Xorg session. Real physical monitor and GPU behavior needs separately scoped hardware trials; two Xvfb screens are not automatically two DWM monitors.

What is prepared now

The current host has Rust/C tools and Xorg; Xephyr and Xvfb were not found, so the light workflow needs those server packages before it can run. Intel VT-x is present, but `/dev/kvm`, QEMU and libvirt are not; the optional VM is not ready here. Nothing has been installed. The runner and Rust WM remain planned work.

References: X.Org Xephyr manual, QEMU and supported hypervisors. Expand the complete environment plan for provisioning, example server commands, credentials, CI and milestones. Download the editable Markdown.

06
Keep the runtime small

X11 dependencies, with clear boundaries.

The active design has one native display target: X11. Keep the policy crate free of external runtime dependencies and put the protocol library only in the X11 executable.

AreaDependency or toolPurpose and status
dwm-coreRust standard libraryRequired. Tags, state transitions, rules and layout calculation; no third-party runtime crates.
dwm-x11x11rb (RustConnection)Candidate X11 protocol client. Pin after the startup/event-loop spike; enable only extensions the chosen baseline requires.
Status bar renderingXft FFI or Cairo/PangoUndecided. Run the rendering spike first; system libraries depend on that decision.
Regression testsXephyr and XvfbSystem test servers for isolated visible and automated X11 scenarios; not Cargo dependencies.
Dependency reviewcargo-deny; optionally cargo-vetDevelopment/CI tools for advisories, licenses, package sources and audit policy; not runtime dependencies.
Dependency rule

Commit Cargo.lock, use locked builds, review the complete feature tree, and prefer official crates.io releases over unreviewed Git sources. Enable only the X11 protocol extensions the implementation actually uses.

Read the complete X11 rewrite plan and isolated development environment for package and test details.

07
Keep the complete specification close

The full plan and source reference.

Use the guided sections above for the mental model. Expand these documents for the complete design decisions, compatibility matrix and test execution strategy.

Complete rewrite planExpand the full specification

DWM rewrite in Rust

The goal is a small X11 window manager with DWM's familiar behavior, implemented in readable, idiomatic Rust. Optimize for understanding ownership and behavior before minimizing line count. This is a rewrite guided by observable behavior, rather than a function-by-function translation.

The local C baseline is now DWM 6.8 in reference/dwm-6.8/, unpacked unchanged from the user-provided download and identified by archive and file checksums. No local AGENTS.md was found. Record any personal patches and configuration separately before implementation. The project skill at .agents/skills/rust-readable-design/SKILL.md applies the Rust Style Guide, API Guidelines and Clippy to this codebase.

1. Scope and compatibility baseline

Scope: an X11 window manager with DWM’s tagging, tiled/monocle/floating layouts, keyboard and mouse actions, rules, focus, fullscreen, multiple monitors, and status bar. Preserve relevant ICCCM and EWMH behavior supported by the pinned baseline. Browser/WebAssembly and Wayland compositor targets are deferred; this plan and its dependencies cover X11 only.

Write a compatibility matrix before coding. Cover startup with existing windows, transient/dialog handling, override-redirect windows, focus history, layout order, current/previous tag views, current/previous layouts, window size hints, fullscreen restoration, urgency, status text, bar clicks, spawning, and clean shutdown. Mark intentional changes explicitly.

DWM tags must remain sets: a client can belong to multiple tags and a monitor can show multiple tags. Do not replace this with one workspace per window. Record rule matching and precedence, geometry rounding, and focus behavior as examples that can become tests.

2. Architecture: two crates, one X11 path

Use a small Cargo workspace with dwm-core and dwm-x11. This gives policy and protocol I/O clear owners without creating a crate for every module. There is one native target and no alternate backend in the current scope.

Source exampleTEXT
Cargo.toml            workspace and shared lint/profile policy
Cargo.lock            reviewed dependency resolution
crates/
  dwm-core/            library: domain types, state transitions and layouts
  dwm-x11/             binary: X11 connection, event loop and native effects

The event path should be easy to trace:

Source exampleTEXT
X11 event → dwm-x11 decodes protocol data → typed core action or lifecycle update
          → dwm-core changes state and calculates placements
          → dwm-x11 reconciles the affected monitor with X11 requests

Keep X11-generated types near the protocol boundary. Convert them into project-owned values such as WindowId, ClientMetadata, Rect and SizeHints before policy decisions. Layout calculation returns placements and never talks to X11. The manager then applies those placements through x11rb.

Do not add a broad Backend trait for a single X11 implementation. Keep X11Backend concrete in dwm-x11. Use a small trait only if a real test seam or a second in-scope implementation later demonstrates that substitution improves the code.

Keep OS effects such as spawning a process in dwm-x11. A shortcut resolves either to a policy action (ViewTags, Focus, SetLayout) or a native command (Spawn, exit); the core does not pretend these effects are portable.

The core exposes typed policy operations such as Policy::apply(Action) -> Result<ChangeSet, PolicyError> and a layout/snapshot query when the manager needs calculated placements. ChangeSet identifies affected monitors; it contains no X11 requests.

dwm-core must not depend on x11rb or system libraries. Check this boundary with cargo tree -p dwm-core; inspect the native graph with cargo tree -p dwm-x11 -e features.

Begin with a single-threaded synchronous event loop. Track pointer drags as explicit interaction state so destruction and other X11 events continue to be handled during a drag.

3. Types and the behavior they own

TypeResponsibility and useful methods
WindowId, ClientId, MonitorIdDistinguish X11 resources, managed clients, and monitor identities.
Tag, TagSetValidate configured tag bounds; contains, intersects, union, toggle.
TagViewMaintain current and previous nonempty selections; select, toggle, restore_previous.
Rect, Size, BorderWidthExpress geometry; intersection_area, outer_size, checked protocol conversion.
SizeHintsApply base size, increments, aspect and min/max constraints through constrain.
ClientOwn title, metadata, tags, placement and hints; is_visible_on, enter_fullscreen, leave_fullscreen.
MonitorOwn screen/work areas, client order, focus history, tag view and layout selection.
LayoutClosed enum for Tile, Monocle, Floating; placements returns computed geometry.
MasterRatioValidate finite supported ratios; expose intentional adjustment behavior.
ActionCore policy variants such as ViewTags(TagSet), Focus(Direction), SetLayout(Layout); no OS or protocol commands.
NativeCommandNative-only requests such as Spawn(CommandSpec) or exit, handled by dwm-x11 after key-binding resolution.
RuleMatch window metadata and describe intended changes. Preserve baseline rule combination semantics.
X11BackendOwn connection and protocol resources; query metadata, configure, focus, publish properties.
WindowManagerCoordinate manage, unmanage, focus_client, move_client_to_monitor, dispatch_action.

Prefer methods when a type owns the behavior or invariant. A client may update its fullscreen state, but the manager coordinates resulting monitor layout and X11 requests. Free functions remain appropriate for stateless algorithms without a natural receiver.

Use descriptive names: master_count, master_ratio, selected_client, work_area. Replace the C Arg union and function-pointer bindings with Action variants carrying their actual argument types.

Use enums where alternatives exclude each other. Represent normal placement as tiled or floating and fullscreen as a state carrying the previous placement, geometry and border width. Keep independent facts such as urgency as independent fields. Do not combine unrelated flags into one enormous enum.

Keep fields private where mutation could break an invariant. Use Option<ClientId> for absent focus, rather than a zero identifier. Validate configuration at startup. A rule may have no tag override; a managed client and active view must have a nonempty valid tag set. Model DWM's zero-argument “previous view” operation as a distinct action.

Start with concrete types and exhaustive matches. Introduce a trait only for a real interchangeable behavior or a useful test boundary. A trait for every struct, broad dyn dispatch, or a generic backend threaded through every type would increase reading effort without a demonstrated benefit.

4. Ownership and collections

WindowManager owns the client store, monitor store and selected monitor. Monitors contain client IDs rather than references; clients identify their monitor by ID. Keep layout order and focus history as separate ID vectors, because they serve different behaviors.

Start with a typed ID and standard map plus a window-to-client lookup. Never use unordered map iteration to determine layout or focus. Allocate client IDs independently from reusable X11 window IDs. Add a generational arena only if stale references or complexity justify it.

Maintain these invariants through manager methods:

  • Every managed client belongs to exactly one live monitor.
  • Monitor orders contain no duplicate or missing client IDs.
  • Removing a client removes all membership and focus-history entries.
  • The selected client belongs to its monitor and is eligible under the focus policy.
  • Removing a monitor migrates its clients before deleting its state.

Avoid self-referential structures, mutable globals, and routine Rc<RefCell<_>>. Resolve borrowing conflicts by splitting fields, narrowing borrow scopes, or collecting IDs before mutation. Copying a small ID or geometry value is reasonable; cloning the entire manager to bypass borrowing is not.

5. X11 and rendering decisions

Use x11rb with its pure-Rust RustConnection as the first backend candidate. Pin the dependency after a small startup/event-loop spike. Check extension availability and provide a single-monitor fallback. Begin with monitor discovery compatible with the chosen DWM baseline; treat RandR hotplug support as an explicit addition if it exceeds that baseline.

For the bar, time-box a rendering spike comparing retaining Xft behind a narrow FFI wrapper with Cairo/Pango rendering uploaded to the X11 bar window. Decide using Unicode rendering, fallback fonts, dependency footprint, and code readability. Do not promise pixel-identical text rendering before this spike. Keep unsafe code, if needed, contained and documented.

6. Error handling and shutdown

Classify errors deliberately: another window manager owning root redirection is a startup failure; a client disappearing during a request is an expected race; a broken X connection ends the session. Surface checked request errors and asynchronous errors. Validate property types, formats and lengths. Do not use blanket error suppression or unwrap() on external input.

Use explicit shutdown for restoring windows and best-effort cleanup. Resource wrappers can use Drop for local cleanup, but shutdown requests that can fail should have an explicit path. Spawn argument vectors without implicit shell interpolation, and reap children.

7. Implementation milestones

StageDeliverableAcceptance gate
0. BaselinePinned upstream source, patch inventory, compatibility matrix and design decisions.Every required behavior has a scenario; scope differences are recorded.
1. ModelGeometry, tags/views, client/monitor state, layouts and typed actions. Keep this library target-neutral.Pure tests cover invariants, tag transitions, layout ordering, borders and rounding.
2. X11 lifecycleConnect, claim root, scan existing windows, manage/map/unmanage, clean exit.Nested X server scenarios pass; competing WM and disappearing clients are handled.
3. Daily interactionFocus, bindings, rules, spawning, tile/monocle/floating, size hints, dragging.Deterministic scenarios match the pinned baseline; event handling continues during dragging.
4. Protocol and monitorsRelevant ICCCM/EWMH behavior, fullscreen, transients, monitor transfer and topology updates.Real applications, fullscreen restore, focus negotiation and monitor changes behave correctly.
5. Bar and configurationUnicode bar, status updates, click regions, validated typed config.Drawing and hit testing agree; malformed configuration has useful diagnostics.
6. Release candidateDocumentation, session entry, build instructions and compatibility report.Required tests pass; extended nested and real-session trials reveal no outstanding critical failures.

The first runnable milestone is startup → manage a terminal → tile it → focus it → close it → exit cleanly. Build that vertical slice before completing every abstraction.

Keep configuration in readable Rust initially: Config::default() plus explicit binding/rule constructors. Recompilation preserves DWM's customization approach. Add a file format only if users need it; keep policy and validation independent of the format.

7. Verification and readability gates

Use pure unit tests for tags, views, rules, fullscreen transitions, geometry and layouts. Add property tests where they catch meaningful invariant failures, such as arbitrary tag toggles or client removal sequences.

Run integration scenarios under Xephyr or Xvfb with small controlled X clients. Compare behavior with the pinned C baseline: window geometry, visibility, focus, stacking and published properties. Compare observable outcomes, not internal structures. Check hidden-window behavior carefully: changing visibility implementation can alter client lifecycle events.

Exercise real terminals, browsers, dialogs and fullscreen applications. Include keyboard mapping changes, lock modifiers, Unicode titles, rapid map/unmap/destroy sequences, negative monitor coordinates and a window disappearing during dragging.

Before accepting each milestone, run cargo fmt --check, appropriate tests and Clippy. Review readability separately: can a reader trace an event to its outcome, find who owns an invariant, and understand a public method without consulting distant global state? Explain protocol quirks in comments; avoid comments that merely restate the code.

Success means the agreed DWM behaviors pass the compatibility matrix, state invariants survive lifecycle races, and policy code can be understood without learning X11 request encoding. Performance should be measured for event handling and layout before adding caching or concurrency.

References

Detailed design and validation

The detailed documents use the downloaded 6.8 source as the reference. Browser/WebAssembly and Wayland research has been moved under docs/deferred/ and is outside this plan. The sketches demonstrate policy only; they are not a runnable window manager.

Development and test environment

Use Xephyr and Xvfb directly on Linux for the lightest isolated development loop; add QEMU/KVM only when testing guest startup or system changes. See the development environment plan for the host findings, hypervisor option, runner, debugging and acceptance checks. No tools have been installed or launched for that plan.

Detailed Rust designExpand the full specification

Types and flow, grounded in DWM 6.8

Read alongside ../reference/dwm-6.8/dwm.c, the compilable ../examples/type_sketch.rs, and the reusable project skill at ../.agents/skills/rust-readable-design/SKILL.md. The reference is unchanged. The Rust code is a policy sketch, not the beginning of a runnable WM. Unused-field warnings are expected because protocol integration, constructors and many operations are deliberately absent.

Ownership graph

The ownership diagram describes where values live; cross-object relationships use ID lookups, not Rust references. State has no X connection, so its transitions can be tested directly.

Ownership: values live in their owner; relationships use ID lookupsWindowManager owns State, X11Backend, Config, InteractionState owns Client and Monitor stores; indexes use typed IDsMonitor owns TagView, LayoutSelection and ordered client IDsClient owns tags, SizeHints and PresentationClient ↔ Monitor relationships use IDs, not borrowed references
Ownership: values live in their owner; relationships use ID lookups

screen includes the full monitor; work_area excludes the bar. Fullscreen uses screen; tiling uses work_area. Rect coordinates are signed because monitors may sit left of the origin. Use wider intermediates for intersection and border arithmetic; convert to X11's wire ranges only at the backend boundary.

Preserve two independent lists from C Client.next and Client.snext: layout order and focus history. New clients are prepended in the baseline. HashMap traversal must never decide either order. monitor_order also makes keyboard monitor traversal deterministic. Fresh internal client IDs prevent accidental confusion with reused X window IDs; remove pending interaction state when a client disappears.

A production State constructor establishes at least one monitor and validates tag sets against one configured mask. The sketch's TagSet construction enforces valid bits, but values created with different TagMask instances can still be mixed: production accepts only the startup configuration's mask and validates configuration/actions at that boundary. This is a runtime invariant, not a claim of compile-time proof.

Behavior belongs where its inputs and invariants live

C locationRust responsibilityWhy
view at dwm.c:2054; toggleview:1754TagView::select, toggle, restore_previousOwn both view slots and nonempty-view behavior.
setlayout:1511LayoutSelection::select, restore_previousPreserve both layout slots without pointer comparisons.
setfullscreen:1483Client transition, followed by manager reconciliationSaved client state is local; arranging and X requests involve other objects.
applysizehints:314SizeHints::constrainReturn geometry instead of four mutable output parameters.
tile:1688; monocle:1114Layout::placements plus hint-aware geometry calculationPure computation is inspectable and testable.
applyrules:278Rule::matches, ordered rule applicationMatch metadata locally; choose monitor/tags through state.
manage:1032; unmanage:1779Manager lifecycle orchestration plus State membership methodsMembership spans client store, lookup and monitor lists.
focus:789State selects a candidate; backend performs focus negotiationFocus history and X11 input protocol are separate concerns.
showhide:1630Manager visibility reconciliationBaseline moves hidden clients offscreen rather than unmapping them.

Do not move every C function into one giant impl WindowManager. Use methods for meaningful receivers and keep plain algorithm helpers when no receiver is natural. Do not make Client::focus() reach into global monitor state or issue X11 requests.

Event and action graph

Event flow; pointer interaction uses the same loopX11 event → exhaustive handler matchRead metadata OR resolve binding to typed ActionState lifecycle update OR State.apply_actionReconcile affected monitor: visibility and focus candidateCalculate layout with size hintsSend visibility, geometry, stacking, focus and bar requestsHandle errors and flush → next event
Event flow; pointer interaction uses the same loop

Reconciliation is a named sequence with explicit ordering, not a magical full-state diff. Map/startup operations may need requests before and after insertion. Retain those phases instead of forcing every lifecycle operation through the same generic pipeline. Release mutable state borrows before protocol I/O; collect small IDs/placements, not clones of the entire state.

An illustrative integration outline (not part of the compiled sketch):

Source exampleRUST
fn handle_action(&mut self, action: Action) -> Result<(), WmError> {
    if let Some(monitor) = self.state.apply_action(action)? {
        self.reconcile_monitor(monitor)?;
    }
    self.backend.flush()?;
    Ok(())
}

The sketch's PolicyError::MissingMonitor must become a structured WmError conversion. Recover an expected client-disappearance race at the lifecycle boundary; do not silently swallow all protocol errors. State and server are not one atomic transaction: partial requests require cleanup or another reconciliation.

Managing a new window

The baseline maprequest queries attributes, ignores override-redirect, then calls manage only for unknown windows. manage performs an ordered mix of metadata, state and protocol work. The Rust implementation should make those phases explicit.

New-window lifecycle; vanished or already-managed clients branch out before insertionApplication requests mapping → X server sends MapRequestRead attributes and metadata; skip unmanaged override-redirectResolve transient parent or apply ordered rulesConstruct client; configure border, events and button grabsInsert membership; publish client list and NormalStateArrange → map window → negotiate focus → flush
New-window lifecycle; vanished or already-managed clients branch out before insertion

A known managed transient inherits its parent's monitor and tags before ordinary rules; transient/fixed-size behavior affects floating placement. Fullscreen metadata also participates during management. Track these cases as separate tests rather than reducing all metadata to a single is_floating rule.

Rules use substring matches. Matching rules accumulate tag bits, while later matches overwrite floating status and valid monitor choice. An invalid monitor target does not erase an earlier valid choice. No resulting tag bits means use the chosen monitor's active view. An idiomatic rewrite must preserve this order explicitly.

Fullscreen state graph

Fullscreen transitions are idempotent; restoration survives repeated requestsNormal: tiled or floating, with geometry and borderEnter fullscreen: save NormalState; use screen geometryRepeated enter: keep the original restore stateLeave fullscreen: restore NormalState, then arrangeRepeated leave: no change
Fullscreen transitions are idempotent; restoration survives repeated requests

Use Presentation::Fullscreen { restore: NormalState, geometry: Rect } so saved state exists exactly when needed. Keep urgency and input-focus eligibility separate. Floating layout at monitor level does not mean every client's persistent placement should become floating.

For monitor resizing while fullscreen, update current fullscreen geometry without overwriting the saved normal state. On leave, a tiled client may immediately receive new tiled geometry during arrangement; the saved rectangle is not a promise of its final tiled position.

Layout flow and code quality

Hint-aware layout: each constrained height affects the following clientMonitor layout_orderFilter visible clients eligible for tilingCompute widths and remaining-height sharesConstrain each size using its hints and borderAdvance cursor using actual outer height → next clientConfigure placements through X11Backend
Hint-aware layout: each constrained height affects the following client

The C tile advances offsets using actual HEIGHT(c) after resize, which can apply size hints. Computing all ideal rectangles and constraining them only afterward can produce different placement. Either integrate pure hint calculation into the layout pass or return placements iteratively with actual constrained sizes. Preserve float ratio rounding/truncation before considering a different numeric representation.

Readable code should express this dependency in names such as remaining_height, clients_remaining, constrained_size, and outer_height. Use explicit loops where each result feeds the next iteration. A long iterator chain would hide that dependency.

The standalone sketch below supplies working definitions for validated tags, view transitions, IDs, presentation state, typed actions and the ownership container. It deliberately omits layout algorithms, X11, rules and bar drawing. It is a design example, not evidence of WM compatibility.

Compilable Rust examples

These excerpts are copied from examples/type_sketch.rs; run its tests using the commands at the end.

Tag view owns its transitions

Source exampleRUST
/// Mirrors dwm's two tag slots. Toggle edits the current slot in place.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct TagView {
    current: TagSet,
    previous: TagSet,
}
impl TagView {
    pub fn new(tags: TagSet) -> Self {
        Self {
            current: tags,
            previous: tags,
        }
    }
    pub fn current(&self) -> TagSet {
        self.current
    }
    pub fn select(&mut self, tags: TagSet) -> bool {
        if tags == self.current {
            return false;
        }
        self.previous = self.current;
        self.current = tags;
        true
    }
    pub fn toggle(&mut self, tags: TagSet) -> bool {
        match self.current.toggled(tags) {
            Some(next) => {
                self.current = next;
                true
            }
            None => false,
        }
    }
    pub fn restore_previous(&mut self) {
        std::mem::swap(&mut self.current, &mut self.previous);
    }
}

Client owns fullscreen state

Source exampleRUST
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Presentation {
    Normal(NormalState),
    Fullscreen {
        restore: NormalState,
        geometry: Rect,
    },
}
#[derive(Debug)]
pub struct Client {
    window: WindowId,
    monitor: MonitorId,
    tags: TagSet,
    presentation: Presentation,
    urgent: bool,
}
impl Client {
    pub fn is_visible_on(&self, view: &TagView) -> bool {
        self.tags.intersects(view.current())
    }
    /// Repeated fullscreen requests do not overwrite the saved state.
    pub fn enter_fullscreen(&mut self, screen: Rect) -> bool {
        match self.presentation {
            Presentation::Normal(restore) => {
                self.presentation = Presentation::Fullscreen {
                    restore,
                    geometry: screen,
                };
                true
            }
            Presentation::Fullscreen { .. } => false,
        }
    }
    pub fn leave_fullscreen(&mut self) -> bool {
        match self.presentation {
            Presentation::Fullscreen { restore, .. } => {
                self.presentation = Presentation::Normal(restore);
                true
            }
            Presentation::Normal(_) => false,
        }
    }
}

Typed action dispatch returns affected monitor

Source exampleRUST
impl State {
    /// Returns the monitor whose focus/layout/bar must be reconciled.
    /// No X11 calls occur while this method holds a mutable monitor borrow.
    pub fn apply_action(&mut self, action: Action) -> Result<Option<MonitorId>, PolicyError> {
        let monitor = self
            .monitors
            .get_mut(&self.selected_monitor)
            .ok_or(PolicyError::MissingMonitor)?;
        let changed = match action {
            Action::ViewTags(tags) => monitor.view.select(tags),
            Action::ToggleView(tags) => monitor.view.toggle(tags),
            Action::PreviousView => {
                monitor.view.restore_previous();
                true
            }
            Action::SetLayout(layout) => {
                monitor.layouts.select(layout);
                true
            }
        };
        Ok(changed.then_some(self.selected_monitor))
    }
}
Source exampleSH
rustfmt --edition 2021 --check examples/type_sketch.rs
rustc --edition=2021 --test examples/type_sketch.rs -o /tmp/dwm-type-tests
/tmp/dwm-type-tests

Four tests exercise tag validation, previous-view semantics, fullscreen restoration/idempotence, and layout selection. They validate only the sketches. Full regression validation is described in REGRESSION_PLAN.md.

Crate boundary for the X11 rewrite

Use two packages: dwm-core owns protocol-neutral policy and layout calculations; dwm-x11 owns x11rb, event decoding, X11 resources, native commands and reconciliation. The event loop translates X11 events to typed core operations, receives changes/placements, and applies them through the backend.

Keep the core dependency-free and keep generated x11rb types inside the native adapter. With only one backend in scope, use concrete X11 types and direct methods; add a trait only for a demonstrated test seam or a real second implementation. Browser/WebAssembly and Wayland notes are deferred under docs/deferred/.

Full regression strategyExpand the full specification

Regression validation and migrating C tests

Existing tests and limits

DWM 6.8 has no automated test suite, test directory, assertions or Makefile test target. transient.c is a manual Xlib exerciser with no assertions or bounded termination. There is therefore no suite to directly translate into Rust tests.

Establish executable characterization tests against the frozen C implementation first. Then run identical fixtures and external scenarios against Rust. Passing establishes compatibility for covered scenarios, not proof that every possible application/event ordering is regression-free.

The current repository has four standalone Rust sketch tests only. The C oracle, X11 clients, runners, CI and Rust WM below are planned deliverables. No WM regression result is claimed yet.

Shared test architecture

Source exampleTEXT
tests/fixtures/                 inputs and explicit expected observations
tests/scenarios/                language-independent external scenarios
tests/support/xclient.c         controllable Xlib client
tests/support/c_oracle.c        test-only access to actual C policy
tests/support/reference.patch  minimal observation hooks if required
tests/runner/                   isolated-server lifecycle and comparison
build/reference/               disposable baseline build copy
artifacts/regressions/          logs, snapshots, seeds and failure images
Differential validation: the same scenario drives both implementationsShared scenario + identical configurationRun C DWM and Rust WM on separate fresh X serversCapture logical geometry, visibility, focus, stacking, propertiesNormalize only resource IDs and timestampsCompare → pass / reviewed difference / failure reproduction
Differential validation: the same scenario drives both implementations

Keep reference sources unchanged and retain their license. Build copies under build/reference/; record source hashes, compiler options, scenario configuration and server/font versions. Test-hook patches need review: changing the oracle can hide a regression.

1. Build a reproducible C baseline

Verify SHA256SUMS from the reference directory, copy the source into build/reference/, and generate a fixed test config.h there. Match Rust tag count, bindings, borders, master ratio/count, resize hints, rules, bar position and fonts.

The C build needs a compiler, Xlib, Xft, fontconfig, FreeType and Xinerama development files. Build using the original Makefile in the copy; build the manual client separately if useful:

Source exampleSH
make -C build/reference
cc build/reference/transient.c -o build/reference/transient -lX11

These are future commands after creating the build copy. Do not install the baseline or run it on the desktop display. A runner owns a dedicated nested display. Xvfb and Xephyr were not found on PATH in this planning pass; no C build or nested-X suite was run. Missing environment support must be reported, not counted as passing.

2. Port the intent of transient.c

Leave the original intact. Create a controlled client in tests/support/xclient.c reproducing these operations:

  1. Create a parent titled floating, size 400×400, with min/max size hints fixed at 400×400.
  2. Wait for mapping and observed expected geometry.
  3. Move its tag/monitor through normal bindings, then create a 100×100 child with WM_TRANSIENT_FOR=parent.
  4. Wait for mapping and settled lifecycle behavior; assert floating placement and inherited tag/monitor behavior through visible outcomes.
  5. Switch tags away and back; verify parent and child leave/return to the visible area without recreation.
  6. Destroy child and parent; verify managed-list/focus cleanup and bounded exit.

Use a pipe/socket command protocol with acknowledgements and logical window names. Replace the original five-second sleep with event-driven conditions and deadlines. The tags are internal: do not infer them from _NET_WM_DESKTOP, which is not the baseline's tagging model. Use a policy hook for exact internal assertions when necessary.

Run the scenario against C first and review its observations, then run unchanged against Rust. Add cases for an unmanaged parent, parent destruction during metadata lookup, a non-fixed parent, and a transient hint changed after mapping. Follow actual C handler behavior instead of assuming all property changes reapply rules.

The test client can stay in C. Keeping an independent Xlib driver avoids testing the Rust backend solely through itself.

3. Characterize and port policy tests

Target view, toggleview, setlayout, rule precedence, fullscreen, size hints and tiling first. Use actual C functions as the oracle, not a second rewritten algorithm.

A test-only harness can rename main, include the copied dwm.c in its translation unit, restore main, construct Client/Monitor globals, call static functions and serialize results. This alone does not make the functions pure: they may issue X requests. Use a nested display or narrow documented hooks to suppress unrelated drawing and capture requests. Keep real hint application and cursor advancement. Check harness results against external C scenarios to ensure hooks preserve behavior.

Feed the same fixture schema to C and Rust:

Source exampleJSON
{
  "case": "view-toggle-keeps-other-slot",
  "tag_count": 9,
  "initial_slots": [1, 1],
  "operations": [{"view": 2}, {"toggle_view": 1}, {"previous_view": true}],
  "expected_current": 1,
  "expected_previous": 3
}

Fixtures retain both view/layout slots, selected slot, ordering, geometry, hints and relevant flags. Compare logical values, not raw memory or pointer addresses. Translate stable pure assertions to Rust #[test] functions while retaining fixture IDs and expected outputs.

If later patches include real C tests: inventory inputs/assertions/dependencies/licenses, run them on C before translation, port pure assertions, keep black-box tests shared, and translate pointer identity to logical IDs. Existing failures must be distinguished from new migration failures.

4. Required comparison matrix

AreaCases and assertions
TagsMultiple/all tags, same-view no-op, previous alternation, empty toggle rejection; both slots, visible/offscreen clients and focus.
Layouts0/1/many clients, master count 0/1/above count, odd dimensions, borders, hints/aspect/increments; exact rectangles, order and both layout slots.
FocusMap/cycle order, hidden selected window, pointer entry, urgency, never-focus/WM_TAKE_FOCUS; input focus and active-window property.
RulesSubstring matches, tag union, later floating overwrite, valid then invalid monitor target, no match; monitor/tags/placement.
LifecycleStartup scan, duplicate map, override-redirect, real/synthetic unmap, destruction races; client list, WM_STATE, restored borders and no stale membership.
FullscreenTiled/floating, repeated add/remove/toggle, resize and destruction; zero border, full-screen geometry, restored normal state and rearrangement.
MonitorsNegative origin, transfer/cycling order, removal migration, resize, missing extension; membership, geometry, focus and bar area.
InputLock/NumLock, mapping changes, grabs, bar click edges, move/resize interrupted by destroy; correct actions and no stuck pointer grabs.
BarUnicode/fallback, title/status, urgency and selection, show/hide; semantic content and hit regions, with separate visual checks.
Process/exitArgument vectors, failed exec, child reaping, competing WM, clean shutdown; exit status, diagnostics, restored windows and no zombies.

Match geometry exactly under equal configuration. The C layout uses actual size-hint-constrained height to place the next client and truncates float-derived master width; a general pixel tolerance can hide real defects. Use a fixed bar height for policy tests if font metrics differ, and validate typography separately. Intended differences require explicit approval and specific expectations.

5. Deterministic X11 execution

Use fresh separate servers for C and Rust with identical screen, extensions, locale, fonts and keyboard settings. Wait for WM readiness through ownership/root-property observations rather than fixed sleeps.

Normalize server-specific XIDs to logical names and remove irrelevant timestamps. Preserve geometry, borders, map state, logical stacking, focus and protocol contents. Map state alone cannot prove visibility: C hides clients by moving them offscreen while keeping them mapped.

Drive bindings with real input injection such as XTEST where supported; synthetic XSendEvent is not universally equivalent. Script metadata/protocol changes through the support client. Observer-side XSync does not guarantee the WM processed another connection's events. Use condition-based waits with deadlines, stable observations and, when required, a narrow test-only acknowledgement. Retain traces on timeout.

Verify the server actually supports the multi-monitor topology under test. Xvfb screen configuration is not automatically equivalent to Xinerama monitor changes. Use a verified Xephyr/Xorg environment for real topology tests and a protocol fixture backend for policy tests. Report unsupported cases explicitly; required scenarios cannot silently skip.

6. Check that the tests detect regressions

On a disposable implementation copy, inject these defects and require the relevant test to fail:

  • Toggle overwrites previous view.
  • Layout order is substituted for focus history.
  • Hints are applied only after computing all rectangles.
  • Repeated fullscreen entry overwrites restore state.
  • Hidden windows are unmapped.
  • Removal leaves a stale ID in one list.

A passing test after its intended defect means its assertions need strengthening. Add a permanent fixture for every bug fixed during migration.

After deterministic tests pass, use seeded random lifecycle/action sequences. Compare defined policy outcomes to C and assert independent Rust invariants. Save seeds and minimize failures into short fixtures. C is a compatibility oracle, not a correctness proof: inherited defects or undefined behavior need a reviewed compatibility decision, not blind reproduction.

7. Milestones and release gate

  1. Build C and automate the transient scenario before implementing complex Rust behavior.
  2. Establish fixtures for views, layouts/hints, rules and fullscreen.
  3. Port policy incrementally and run fixtures/invariants with each change.
  4. Add shared lifecycle/input/protocol integration once the Rust vertical slice runs.
  5. Add real application trials and verified multi-monitor cases.
  6. Require formatting/lint checks, all required differential scenarios, race cases and recorded real-session trials before release.

Future Cargo gates: cargo fmt --check, cargo clippy --all-targets -- -D warnings, and cargo test. The standalone sketch is not a Cargo WM project yet. Implement a runner with explicit executable/scenario arguments so the same scenarios select C or Rust.

Publish pass/fail/skip per scenario, baseline identity, environment, intended differences and failure artifacts. Failures block promotion until fixed or explicitly reviewed. Never automatically accept new golden output.

Checks completed now

Both archives have identical SHA-256; every extracted regular file matches its archive bytes; all 13 reference file checksums pass. Four standalone Rust tests compile and pass on Rust 1.82.0. No automated C tests existed to port. No C build, X11 differential validation or WM regression suite has run.

Environment setup

Development environment plan specifies the VM, nested/virtual X servers, credentials, runner lifecycle and staged acceptance checks used by this regression strategy.

Development environment and isolated testingExpand the full specification

Development environment: test a desktop without replacing yours

Recommendation and scope

Start with a separate X server on the existing Linux desktop: Xephyr for visible experiments and Xvfb for automated tests. Neither needs a VM or a full guest desktop. The WM manages only the windows on that test server, so a WM crash cannot rearrange the ordinary desktop. Use a disposable VM as an optional stronger boundary when testing installation, login sessions, packages, or broad filesystem changes. Keep Rust policy tests independent of any display server.

This is an environment plan, not an installed environment. The repository has a compiled policy sketch, not a runnable Rust window manager. On the host inspected on 3 October 2026, Arch Linux has cargo, rustc, cc, pkg-config, xauth and Xorg; Xephyr, Xvfb and xdpyinfo were not found on PATH. The CPU reports Intel VT-x, but /dev/kvm is absent and QEMU/libvirt executables were not found; a hardware feature alone does not make a VM runnable. Guest provisioning, server runners and regression suites below remain to be implemented.

1. Pick the lightest environment that answers the question

Default for this project: Xephyr and Xvfb directly on Linux. This is a small X11 development setup: no VM provider, hypervisor, virtual disk, guest OS or VM viewer. Xephyr provides an independent desktop rendered inside one window on the existing graphical desktop. DWM connects to Xephyr's display ID (for example, :100) and can manage only windows on that nested X server. The existing desktop's window manager still manages the Xephyr window. If test DWM crashes, it loses control of the inner desktop; it cannot take over or rearrange the outer desktop.

Xephyr is a real nested X server, not a VM, window manager, package manager or acronym that the project needs to expand. It implements a separate X server and draws its framebuffer through a window on an already-running X display. The upstream manual describes it as an “X server outputting to a window on a pre-existing X display”; it supports extensions including Composite, Damage and RandR. Xephyr manual

Xvfb is another real X server, with a virtual framebuffer in memory and no visible window or physical display device. Use it for event-driven tests and C/Rust comparisons. X.Org Xvfb manual

A separate X server isolates window trees and input routing. It does not isolate program files, processes or privileges: a test program still runs as your Linux user. This is usually suitable for developing DWM's window-management code because the experiment is which server receives X requests. Use a disposable VM when the experiment changes a whole session, system packages or startup configuration. A normal unprivileged process can still write any files permitted to its user account.

VM provider and hypervisor, if the stronger boundary is needed

A hypervisor runs and controls a guest computer. QEMU creates the virtual machine; on Linux, KVM uses the CPU's hardware virtualization support to run it efficiently. Libvirt can manage the QEMU/KVM machine; virt-manager is an optional graphical front end. QEMU, KVM, libvirt and virt-manager are related pieces, not four competing VM providers. See the QEMU overview and QEMU hypervisor glossary.

This host's CPU reports VT-x, but there is no visible /dev/kvm device and no QEMU/libvirt commands installed. So QEMU/KVM is a sensible future VM choice, but is not available as-is and is unnecessary for normal WM iteration. Docker is installed, but a container shares the host Linux kernel; it is not the same isolation boundary as a VM and is not needed for the light Xephyr workflow.

If you later install VM software, use QEMU/KVM with a small stable Linux guest, a minimal Xfce desktop, 2 virtual CPUs, 3 GiB RAM and a dynamically growing 16 GiB disk as a starting point. Xfce gives Xephyr a graphical guest display without a heavier desktop. Take a guest snapshot before experimenting with guest startup or packages. Keep a private guest checkout instead of sharing your host home directory. A VM viewer shows the guest screen in a host window.

2. Understand what DISPLAY selects

An X server process owns its own window tree, input focus and connection endpoint. DWM can manage only the server to which it connects. It does not become the operating system's window manager just because its binary is running.

DISPLAY tells X11 programs which server to connect to. For example, :100 means local server number 100; :100.0 explicitly names that server's X screen 0. This number does not mean monitor 100. XAUTHORITY points to a file containing authorization credentials for that server. In the ordinary Xephyr workflow, Xephyr connects to the existing graphical display, while DWM and its test applications connect to Xephyr's separate display. Do not launch DWM with the outer desktop's DISPLAY.

Source exampleTEXT
Existing desktop's X server
  └── one window: Xephyr, independent test X server :100
        ├── either C DWM or Rust WM
        └── terminal, dialog, controllable test client

Automated job: Xvfb :101, independent test server in memory
  ├── either C DWM or Rust WM
  └── scenario driver and observer

Optional later: QEMU/KVM guest OS → guest display → Xephyr

Xephyr requires an existing graphical desktop on which to draw its window. On a Wayland desktop this may be the desktop's XWayland compatibility server. If no graphical display is available, use Xvfb for automated tests. For visible testing, start a minimal graphical guest in the optional VM.

3. Four test levels

EnvironmentWhat it checksWhen to use itLimits
No X serverTag sets, view history, geometry, layout, state relationshipsOn every change; debugger and ordinary Rust unit testsDoes not exercise protocol requests or real events
Xvfb on Linux or inside optional VMMapping, configure requests, properties, focus, lifecycle and event handlingAutomated scenarios and C/Rust comparisonNo visible desktop; no assumption of real monitor hotplug or GPU behavior
Xephyr on host (or inside optional VM)Visible tiling, dialogs, shortcuts, bar, drag and resizeInteractive debugging and reproducing a failed scenarioOuter shortcuts can interfere; nested input and extensions differ from a normal session
Guest's own Xorg sessionFull WM startup/exit and real application session behaviorLater release checks, after nested tests passVirtual display topology still differs from physical hardware

A small final real-hardware trial may be needed for physical monitor changes and device-specific issues. Record that as a separate release check; a VM result is not evidence for every GPU or monitor setup.

Sources: Xephyr manual from X.Org, X.Org Xvfb manual, QEMU system emulation. Check installed server manuals and extension probes as part of provisioning.

4. Optional VM setup for full guest-session checks

If the VM profile becomes necessary, use QEMU/KVM on Linux and optionally manage it with libvirt/virt-manager. That stack is currently unavailable on this host. Choose a stable Linux guest supported by the project; Debian stable is a reasonable reference guest even though the host is Arch. Record the exact guest image identity and package versions rather than relying on an unrecorded rolling installation.

Suggested starting allocation: 2 virtual CPUs, 3 GiB RAM and a 16 GiB expandable disk with a minimal Xfce desktop. This leaves room for the guest GUI without choosing a full GNOME/KDE session. Adjust after measuring builds. Use an ordinary unprivileged development user. The guest needs:

  • Rust toolchain, rustfmt and Clippy; choose and pin a toolchain when the actual Cargo package is introduced. Commit Cargo.lock for the WM executable.
  • C compiler, make and pkg-config; Xlib, Xft, fontconfig, FreeType and Xinerama development files for the unchanged C baseline.
  • Xephyr, Xvfb, xauth, xdpyinfo, xprop, xwininfo and a terminal such as xterm.
  • XTEST support and its driver dependencies for real injected input; Xinerama querying support for the monitor cases DWM actually uses.
  • A known font set, a fixed locale and keyboard mapping; record them alongside test results.
  • A debugger and logging tools. Start with GDB for both binaries; add optional tooling only when it helps reproduce a specific problem.

Create a clean snapshot after provisioning. A snapshot is a restore point for the VM disk/state. Test installation and session changes after taking it, then restore when necessary. Keep personal accounts and real documents out of the guest. Use a cloned checkout or transfer a source archive; avoid a writable host-home share. If a shared checkout is used, its file changes affect the host, so it is not part of the isolation boundary. Store important result artifacts outside snapshots before reverting.

Record provisioning in a script and an environment manifest: optional guest image checksum, packages/versions, Rust toolchain, compiler flags, fonts, locale, keyboard mapping and X server options. Fetch dependencies during provisioning; run scenario jobs without external network dependencies where possible. Do not treat WMS Cloud's nginx documentation page as the WM execution environment.

5. Interactive loop in Xephyr

First build both implementations into local directories; do not run make install, replace the login session, or launch the WM with an inherited outer-desktop DISPLAY.

The C baseline build is a copy of reference/dwm-6.8/ under build/reference/, with the test config written into the copy. Keep reference checksums intact. The future Rust debug executable will be target/debug/rust-dwm after its Cargo package exists.

The following are example commands for a future runner, not commands executed in this planning pass. In the light profile they run on the host and use its existing graphical display only as Xephyr’s drawing surface. The runner must allocate an unused nested display and create the matching private authorization file first:

Source exampleSH
# Run on Linux. Xephyr inherits the existing desktop connection for its outer window.
# :100 is illustrative: the runner must choose an unused server number.
Xephyr :100 -screen 1280x800 -resizeable -nolisten tcp \
  -auth /tmp/rust-dwm-run/authority

# A second terminal on the same machine, after the test server is ready:
env DISPLAY=:100 XAUTHORITY=/tmp/rust-dwm-run/authority \
  RUST_BACKTRACE=1 ./target/debug/rust-dwm

# Launch an application on that same inner server, not the outer desktop:
env DISPLAY=:100 XAUTHORITY=/tmp/rust-dwm-run/authority xterm

The Xephyr process uses the current desktop authorization to draw its outer window and the -auth credential for clients connecting to the nested server. The runner must preserve the current desktop DISPLAY for Xephyr, then set DISPLAY/XAUTHORITY only for DWM and test applications. Do not globally export a test DISPLAY and hope every process inherited the right one.

Watch a terminal open, resize and disappear. Break in manage_window to inspect a MapRequest; compare the local client record with xwininfo geometry on the same test server. Inspect properties with xprop. Pause or crash the WM deliberately: its test applications should remain confined to the nested display, and the outer desktop should remain usable. Restarting/adopting existing windows is a separate startup-scan test.

Use a debugging configuration whose shortcut modifier does not conflict with the outer desktop. Use identical configurations for actual C/Rust comparisons. Keep the test desktop windowed at first, and document how to leave an input grab for the installed Xephyr version. Stop processes through the runner; avoid broad commands that kill every X server or WM with the same name.

6. Automated loop in Xvfb

Xvfb runs a real X server with its framebuffer in memory. Tests still create server windows and exchange X11 messages; they simply need no physical screen or visible nested window.

A future runner creates a new server for each case/implementation. Illustrative server invocation:

Source exampleSH
Xvfb :101 -screen 0 1280x800x24 -nolisten tcp \
  -auth /tmp/rust-dwm-run/authority

Do not assume creating two Xvfb screens creates two DWM monitors. Probe the Xinerama information DWM consumes. Use simulated monitor-policy fixtures for unit tests and an explicitly verified server/VM topology for integration tests; required topology tests fail setup when their environment is missing.

Runner sequence:

  1. Create a private run directory with permissions 0700; allocate an unused display and fresh random MIT-MAGIC-COOKIE-1 authorization data. Do not use -ac, xhost +, or the host display socket/credentials.
  2. Launch the test server as an unprivileged child with TCP listening disabled. Check connection readiness using its credential and a bounded deadline; verify dimensions, depth and required extensions.
  3. Launch exactly one WM on that display. Confirm it actually claimed management through a dedicated probe or test acknowledgement; _NET_SUPPORTING_WM_CHECK alone does not prove redirection ownership.
  4. Launch the controllable scenario client and observer on that same display. Wait for observable conditions rather than fixed sleeps.
  5. Save logical window IDs, geometry, borders, focus, stacking, map state and relevant properties. Visibility also checks coordinates because C DWM hides tagged-out windows offscreen.
  6. Record stdout/stderr, event traces, environment manifest, scenario seed, exit status and framebuffer screenshot where useful.
  7. On success, failure or timeout, terminate only this run's known child process groups, wait for them to exit, and clean up only owned resources. Never delete another server's lock/socket. Keep failure artifacts.
  8. Run the same scenario with a fresh identically configured server and the other WM. Normalize resource IDs and timestamps, then compare the semantic observations.

Run C and Rust sequentially first to simplify debugging. Parallel runs later require independent displays, credentials, process groups and output directories. A timeout, crashed server or unsupported required extension is an explicit failure/setup result, never a pass.

7. Runner interface and repository layout

Use Python's standard library for process supervision initially; no JavaScript libraries are needed. Proposed commands are interface specifications, not existing scripts:

Source exampleSH
python3 tools/dev_session.py --server xephyr --wm build/reference/dwm
python3 tools/dev_session.py --server xephyr --wm target/debug/rust-dwm
python3 tools/compare_wms.py --server xvfb --scenario transient \
  --reference build/reference/dwm --candidate target/debug/rust-dwm

dev_session.py owns server allocation, credentials, readiness, child environments, logs and cleanup. compare_wms.py uses the same lifecycle code and shared scenarios; it adds normalization and assertions. Keep the environment runner separate from WM code so a WM defect does not invalidate the observations.

Source exampleTEXT
tools/dev_session.py         interactive runner entry point (planned)
tools/compare_wms.py         differential runner entry point (planned)
tools/xsession.py            shared server/process lifecycle (planned)
dev/environment.md          provisioned versions and optional VM rebuild procedure
build/reference/            disposable C baseline build
artifacts/regressions/       per-run logs, snapshots and environment identity

No runnable runner or guest provisioning has been added yet. The first implementation should be a small host Xephyr/Xvfb runner and C-only transient scenario; do not wait for a finished Rust WM to start environment validation.

8. Debugging, CI and promotion

Every change: format/lint and pure policy tests. Changes touching X11: run focused Xvfb scenarios. Before merging an implementation slice: required C/Rust comparisons. Before release: Xephyr application trials, then an optional optional guest Xorg session, then explicitly scoped real-hardware checks if required.

For CI, a container can package build tools and Xvfb, provided the X server runs inside that job. Never forward the host X socket or host authorization into the test container. Containers share the host kernel; a VM is reserved for interactive guest-session and install testing. Use bounded job resources and retain failure artifacts.

Use debug builds with backtraces for Rust and symbols for C. Preserve ordinary optimized C behavior for the compatibility baseline. Optional sanitizer builds are separate diagnostic jobs; do not silently substitute them for the reference binary. Keep logs focused on event type, logical window name, local decision and outgoing operation so you can follow the cause of a bad rectangle.

9. Implementation milestones and acceptance checks

  1. Check for a graphical X11/XWayland display; add Xephyr and Xvfb and record server extensions. Acceptance: open an isolated nested desktop and run a no-display test. Provision QEMU/KVM guest only when session/system-change checks are needed.
  2. Implement server lifecycle runner. Acceptance: intentionally crash the WM, time out a scenario and interrupt the runner; child cleanup completes and the outer desktop remains usable.
  3. Build unchanged C baseline and automate the transient test. Acceptance: bounded successful run with assertions and saved failure evidence after an injected defect.
  4. Add Rust vertical slice. Acceptance: open a terminal, adopt it, tile/focus it, destroy it and exit; shared C/Rust observations agree.
  5. Add monitor, input, fullscreen and real-application cases. Acceptance: every required scenario has a supported environment and meaningful pass/fail result.
  6. Test installation/startup/exit in a guest snapshot. Acceptance: WM can be stopped, previous guest session restored, and evidence retained before reverting.

Xephyr validates window behavior without replacing the host desktop. It does not contain ordinary process or filesystem changes. The optional VM adds a separate guest OS and disk. Neither profile fully reproduces every physical GPU or hot-plug topology.

Rust readability skillExpand the full specification

Readable Rust for rust-dwm

Goal

Write code that a developer new to Rust and window managers can follow. A reader should be able to answer: who owns this value, what can this operation change, what happens when it fails, and which X11 message follows?

Follow standard Rust conventions first. Idiomatic Rust means using the language to express this program's actual model; it does not mean using every language feature or shortening every function.

Before editing

  1. Read the nearby code, docs/RUST_DESIGN.md, and the corresponding behavior in reference/dwm-6.8/dwm.c when preserving baseline behavior.
  2. Identify the owner and invariant before choosing a type, method, field, or module.
  3. Describe the path: event/input → validated domain value → policy/state change → calculated effects → X11 request.
  4. Keep the existing architecture unless the task requires a boundary change. Do not add a framework, crate, trait, macro, async runtime, or generic abstraction to make a small operation look reusable.

Names and types

  • Use standard casing: types, traits and enum variants UpperCamelCase; functions, methods, modules and locals snake_case; constants SCREAMING_SNAKE_CASE.
  • Choose names that state the unit and responsibility: work_area, master_ratio, selected_client, remaining_height. Avoid single-letter names except conventional short loop indices or math where surrounding code is clear.
  • Use newtypes when equal representations have different meanings. Keep WindowId, ClientId, MonitorId, TagSet, BorderWidth and X11 atom IDs distinct. Do not add newtypes just to rename a local.
  • Represent absence with Option<T>, failure with Result<T, E>, and mutually exclusive modes with an enum. Avoid zero IDs, magic numbers and unrelated booleans as substitutes.
  • Make invalid states unrepresentable when a small type makes the rule clearer. For example, Fullscreen { restore: NormalState, geometry } stores restoration only while fullscreen. Validate relationships that require live State at that boundary; do not claim the compiler proves them.
  • Keep fields private when arbitrary mutation could break an invariant. Expose a named method that validates and changes the value.
  • Derive Debug for useful project data. Add Copy, ordering, hashing, serialization and other traits only when their semantics and actual use justify them.
  • Follow conversion naming: as_... for cheap borrowed views, to_... for conversions with cost, into_... when consuming self. Use standard From/TryFrom; check numeric conversions to X11 field widths instead of truncating.

Put behavior with its owner

Use a method when there is a clear receiver: the type owns the data or invariant needed. Use a free function for a pure algorithm with no natural owner.

OperationOwnerWhy
Select, toggle or restore a viewTagViewOwns current/previous selections and the nonempty-view rule.
Enter or leave fullscreenClient or presentation valueOwns normal placement, geometry and border to restore.
Add, remove or transfer a clientStateUpdates client storage, lookup maps and monitor ID lists together.
Calculate layoutPure layout function or Layout methodReturns placements; does not issue X11 requests.
Read properties, configure/map/focusX11BackendOwns the connection and translates protocol requests/replies/errors.
Handle one event across policy and X11WindowManagerCoordinates state, layout and protocol effects.

Do not put every C function into one huge impl WindowManager. Do not let Client reach into unrelated clients, globals or the X11 connection. Keep local transitions on a value; put operations spanning multiple values on State; coordinate policy and I/O in the manager.

Ownership and borrowing

  • Give each mutable fact one owner. State owns clients and monitors; monitors store ordered ClientIds; each client stores a MonitorId. Use IDs for cross-links instead of reference cycles.
  • Preserve distinct orderings for tiling, focus history and monitor traversal. Never rely on HashMap iteration for visible behavior.
  • Keep borrows short and scoped. Read/update policy, collect needed IDs or placements, end the borrow, then send protocol requests. Do not clone the whole model to satisfy the borrow checker.
  • Prefer slices, iterators and borrowed parameters for read-only input. Take ownership when storing or consuming a value. Prefer &str to &String when either works.
  • Avoid Arc<Mutex<_>>, Rc<RefCell<_>> and threads without a real concurrency/sharing need. Start with the planned single-threaded event loop.

Control flow and behavior

  • Dispatch X11 events with an exhaustive match. Keep distinct event behavior visible.
  • Use a typed Action enum, such as ViewTags(TagSet) or PreviousView, instead of C's argument union, a magic zero, or boolean-meaning arguments.
  • Use straightforward if, match and loops when steps mutate state or depend on prior results. Iterator chains are good for simple transformations; do not use them to hide ordering, mutation or failure paths.
  • Name lifecycle phases. Example: read attributes → validate/adopt → classify → insert memberships → arrange → configure/map → focus. Preserve required ordering; do not force every operation through an invented generic reconciliation framework.
  • Separate calculation from effects: layout returns named rectangles; the backend applies them. Avoid positional numeric tuples when named coordinate/size fields are clearer.
  • Scope reconciliation to the affected monitor. State mutation and X11 requests are not atomic; handle partial failures at the operation that can recover.

Errors, panics and unsafe

  • Return Result from fallible boundaries: connection setup, queries, property decoding, checked conversions, process startup and X requests. Include context that says which operation/window failed.
  • Convert low-level protocol failures to a small domain error when callers need to choose whether to exit, retry or forget a window. A window disappearing between event and query is an expected lifecycle case; do not swallow unrelated protocol errors.
  • Use ? for propagation. Do not .unwrap() or .expect() on configuration, properties or runtime events. Use expect only for a proven internal invariant and explain the proof in its message.
  • Do not add unsafe to work around a borrow problem. If a binding requires it, confine it to the smallest boundary and explain its safety conditions.
  • Keep Drop free of important fallible or blocking work. Provide explicit shutdown that can return an error; destructors can remain best-effort.

X11 boundary

  • Keep generated x11rb types, wire integers, atom IDs and protocol-size limits in x11/. Convert them to named domain values before policy decisions.
  • Keep tags, layout, focus order and monitor ownership in Rust state. The server stores windows and applies requests; it does not decide DWM policy.
  • Name protocol direction: read_window_metadata, configure_window, map_window, set_input_focus, send_delete_request. show is vague when mapping and tag visibility differ.
  • Validate a property's type, format and item count before decoding it.
  • Flush at clear event/lifecycle boundaries. Distinguish sending a request from receiving a checked reply or observing its result.

Comments and documentation

  • Explain why protocol behavior, ordering, compatibility or arithmetic is necessary. Do not narrate the next line.
  • Use focused comments and rustdoc for project concepts. Define unfamiliar vocabulary at first use in user-facing docs.
  • Document non-obvious invariants next to the owner and name the method that preserves them.
  • Keep functions small enough to show their stages. Do not split a visible three-line operation into tiny helpers without meaningful reuse or an independent invariant.

Review checklist

Before finishing, ask:

  • Can a reader follow event/input → policy → state → layout/effects → request without searching for hidden globals?
  • Does each value have a clear owner, with IDs for cross-links?
  • Are invalid combinations excluded by types or checked at a named boundary?
  • Do method names reveal what they mutate? Do arguments communicate intent?
  • Are expected and unexpected protocol failures handled at the layer that can respond?
  • Does the change preserve DWM 6.8 ordering and behavior, or explain an intentional difference?
  • Do comments explain why? Is an abstraction truly clearer than direct Rust?

Tooling guidance

Use default formatting: cargo fmt --check. Once the Cargo crate exists, use cargo clippy --all-targets -- -D warnings, then review suggestions rather than applying them blindly. Clippy's default correctness, suspicious, style, complexity and performance groups are useful signals. Do not enable every pedantic, restriction, nursery or cargo lint globally by default. Select extra lints when they help, and allow intentional exceptions locally with a reason. Lints prompt review; they do not replace understanding the event and state flow.

References

Complete compilable Rust policy sketchAll types and four focused tests
examples/type_sketch.rs · complete sourceRUST
//! Standalone policy sketch, not a window manager or protocol implementation.
//! Run: rustc --edition=2021 --test examples/type_sketch.rs -o /tmp/dwm-type-tests
use std::collections::HashMap;

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct WindowId(u32);
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct ClientId(u64);
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct MonitorId(u64);

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct TagSet(u32);
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct TagMask(u32);
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TagError {
    InvalidCount,
    Empty,
    OutsideConfiguredTags,
}
impl TagMask {
    pub fn new(count: u8) -> Result<Self, TagError> {
        if !(1..=31).contains(&count) {
            return Err(TagError::InvalidCount);
        }
        Ok(Self((1u32 << count) - 1))
    }
    pub fn set(self, bits: u32) -> Result<TagSet, TagError> {
        if bits == 0 {
            return Err(TagError::Empty);
        }
        if bits & !self.0 != 0 {
            return Err(TagError::OutsideConfiguredTags);
        }
        Ok(TagSet(bits))
    }
}
impl TagSet {
    pub fn intersects(self, other: Self) -> bool {
        self.0 & other.0 != 0
    }
    pub fn toggled(self, other: Self) -> Option<Self> {
        let bits = self.0 ^ other.0;
        (bits != 0).then_some(Self(bits))
    }
}

/// Mirrors dwm's two tag slots. Toggle edits the current slot in place.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct TagView {
    current: TagSet,
    previous: TagSet,
}
impl TagView {
    pub fn new(tags: TagSet) -> Self {
        Self {
            current: tags,
            previous: tags,
        }
    }
    pub fn current(&self) -> TagSet {
        self.current
    }
    pub fn select(&mut self, tags: TagSet) -> bool {
        if tags == self.current {
            return false;
        }
        self.previous = self.current;
        self.current = tags;
        true
    }
    pub fn toggle(&mut self, tags: TagSet) -> bool {
        match self.current.toggled(tags) {
            Some(next) => {
                self.current = next;
                true
            }
            None => false,
        }
    }
    pub fn restore_previous(&mut self) {
        std::mem::swap(&mut self.current, &mut self.previous);
    }
}

/// Coordinates may be negative. Construction checks positive dimensions.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Rect {
    x: i32,
    y: i32,
    width: u32,
    height: u32,
}
impl Rect {
    pub fn new(x: i32, y: i32, width: u32, height: u32) -> Option<Self> {
        (width > 0 && height > 0).then_some(Self {
            x,
            y,
            width,
            height,
        })
    }
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct BorderWidth(u16);
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Placement {
    Tiled,
    Floating,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct NormalState {
    placement: Placement,
    geometry: Rect,
    border: BorderWidth,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Presentation {
    Normal(NormalState),
    Fullscreen {
        restore: NormalState,
        geometry: Rect,
    },
}
#[derive(Debug)]
pub struct Client {
    window: WindowId,
    monitor: MonitorId,
    tags: TagSet,
    presentation: Presentation,
    urgent: bool,
}
impl Client {
    pub fn is_visible_on(&self, view: &TagView) -> bool {
        self.tags.intersects(view.current())
    }
    /// Repeated fullscreen requests do not overwrite the saved state.
    pub fn enter_fullscreen(&mut self, screen: Rect) -> bool {
        match self.presentation {
            Presentation::Normal(restore) => {
                self.presentation = Presentation::Fullscreen {
                    restore,
                    geometry: screen,
                };
                true
            }
            Presentation::Fullscreen { .. } => false,
        }
    }
    pub fn leave_fullscreen(&mut self) -> bool {
        match self.presentation {
            Presentation::Fullscreen { restore, .. } => {
                self.presentation = Presentation::Normal(restore);
                true
            }
            Presentation::Normal(_) => false,
        }
    }
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Layout {
    Tile,
    Monocle,
    Floating,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct LayoutSelection {
    current: Layout,
    previous: Layout,
}
impl LayoutSelection {
    pub fn select(&mut self, layout: Layout) {
        if layout != self.current {
            std::mem::swap(&mut self.current, &mut self.previous);
        }
        self.current = layout;
    }
    pub fn restore_previous(&mut self) {
        std::mem::swap(&mut self.current, &mut self.previous);
    }
}
#[derive(Debug)]
pub struct Monitor {
    screen: Rect,
    work_area: Rect,
    view: TagView,
    layouts: LayoutSelection,
    layout_order: Vec<ClientId>,
    focus_history: Vec<ClientId>,
    selected_client: Option<ClientId>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Action {
    ViewTags(TagSet),
    ToggleView(TagSet),
    PreviousView,
    SetLayout(Layout),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PolicyError {
    MissingMonitor,
}
#[derive(Debug)]
pub struct State {
    clients: HashMap<ClientId, Client>,
    monitors: HashMap<MonitorId, Monitor>,
    monitor_order: Vec<MonitorId>,
    window_to_client: HashMap<WindowId, ClientId>,
    selected_monitor: MonitorId,
}
impl State {
    /// Returns the monitor whose focus/layout/bar must be reconciled.
    /// No X11 calls occur while this method holds a mutable monitor borrow.
    pub fn apply_action(&mut self, action: Action) -> Result<Option<MonitorId>, PolicyError> {
        let monitor = self
            .monitors
            .get_mut(&self.selected_monitor)
            .ok_or(PolicyError::MissingMonitor)?;
        let changed = match action {
            Action::ViewTags(tags) => monitor.view.select(tags),
            Action::ToggleView(tags) => monitor.view.toggle(tags),
            Action::PreviousView => {
                monitor.view.restore_previous();
                true
            }
            Action::SetLayout(layout) => {
                monitor.layouts.select(layout);
                true
            }
        };
        Ok(changed.then_some(self.selected_monitor))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn toggling_view_preserves_the_other_slot_and_rejects_empty() {
        let mask = TagMask::new(9).unwrap();
        let first = mask.set(1).unwrap();
        let second = mask.set(2).unwrap();
        let mut view = TagView::new(first);
        assert!(view.select(second));
        assert!(view.toggle(first));
        assert_eq!(view.current(), mask.set(3).unwrap());
        assert!(!view.toggle(mask.set(3).unwrap()));
        view.restore_previous();
        assert_eq!(view.current(), first);
        view.restore_previous();
        assert_eq!(view.current(), mask.set(3).unwrap());
    }
    #[test]
    fn fullscreen_is_idempotent_and_restores_floating_geometry_and_border() {
        let original = NormalState {
            placement: Placement::Floating,
            geometry: Rect::new(-100, 30, 400, 300).unwrap(),
            border: BorderWidth(2),
        };
        let mut client = Client {
            window: WindowId(10),
            monitor: MonitorId(1),
            tags: TagMask::new(9).unwrap().set(1).unwrap(),
            presentation: Presentation::Normal(original),
            urgent: false,
        };
        assert!(client.enter_fullscreen(Rect::new(-1920, 0, 1920, 1080).unwrap()));
        assert!(!client.enter_fullscreen(Rect::new(0, 0, 800, 600).unwrap()));
        assert!(client.leave_fullscreen());
        assert_eq!(client.presentation, Presentation::Normal(original));
        assert!(!client.leave_fullscreen());
    }
    #[test]
    fn selecting_current_layout_does_not_replace_previous_layout() {
        let mut selection = LayoutSelection {
            current: Layout::Tile,
            previous: Layout::Monocle,
        };
        selection.select(Layout::Tile);
        selection.restore_previous();
        assert_eq!(selection.current, Layout::Monocle);
    }
    #[test]
    fn tag_boundaries_are_validated() {
        assert_eq!(TagMask::new(0), Err(TagError::InvalidCount));
        let mask = TagMask::new(9).unwrap();
        assert_eq!(mask.set(0), Err(TagError::Empty));
        assert_eq!(mask.set(1 << 9), Err(TagError::OutsideConfiguredTags));
        assert!(mask.set(1 << 8).is_ok());
    }
}