---
name: rust-readable-design
description: Design, implement, or review Rust code for this DWM rewrite with clarity as the main goal. Use for Rust architecture, X11 boundaries, state and types, event handling, errors, and code review. Prefer explicit ownership and understandable control flow over compressed code or abstractions for their own sake.
---

# 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.

| Operation | Owner | Why |
| --- | --- | --- |
| Select, toggle or restore a view | `TagView` | Owns current/previous selections and the nonempty-view rule. |
| Enter or leave fullscreen | `Client` or presentation value | Owns normal placement, geometry and border to restore. |
| Add, remove or transfer a client | `State` | Updates client storage, lookup maps and monitor ID lists together. |
| Calculate layout | Pure layout function or `Layout` method | Returns placements; does not issue X11 requests. |
| Read properties, configure/map/focus | `X11Backend` | Owns the connection and translates protocol requests/replies/errors. |
| Handle one event across policy and X11 | `WindowManager` | Coordinates 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 `ClientId`s; 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

- [Rust Style Guide](https://doc.rust-lang.org/style-guide/)
- [Rust API Guidelines and checklist](https://rust-lang.github.io/api-guidelines/)
- [Clippy lint categories](https://doc.rust-lang.org/clippy/lints.html)
- [The Rust Programming Language: ownership](https://doc.rust-lang.org/book/ch04-00-understanding-ownership.html)
- [The Rust Programming Language: enums and pattern matching](https://doc.rust-lang.org/book/ch06-00-enums.html)
- [The Rust Programming Language: recoverable errors](https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html)
