Status: proposed first-edition design and stage contracts, not an implemented framework or finished book. The learner owns the C++ implementation. The course execution plan governs how the book and checker are produced; this document governs what the framework builds. Mentoring takes one stage at a time even though the finished book will contain all stages.
1. Definition of done
On a supported Linux desktop, the learner can build a reusable C++20 library and link two separate applications against it:
- Counter: opens a titled, resizable window; displays a count and
−/+controls (ASCII-in this edition); starts at0; a completed pointer click or keyboard activation changes the count exactly once; Tab and Shift+Tab move a visible focus indicator; the counter survives resize and redraw. Blank clicks and irrelevant keys don’t change the model. The application waits when idle and exits cleanly from a window-manager close. - Toggle: uses the same public library to display an on/off label and a single independent control. Its build must not patch the framework or reuse the counter’s model. Neither application includes XCB or FreeType headers, reads native handles, indexes a pixel buffer, or implements its own event loop.
- Verification: the same layout, dispatch, state, and paint logic runs headlessly with controlled events; an isolated X11 run independently checks the native lifecycle and a real rendered interaction. A clean build, negative checks, and a second application are part of completion, not optional polish.
What “from scratch” means: implement the window adapter, event loop, frame scheduling, pixel rasterizer, scene, layout, composition, interaction, state, and application API. Use XCB for X11 messaging and FreeType for font parsing and glyph rasterization. Do not implement the X11 protocol encoding or a font engine. Normal build: CMake, Unix Makefiles, build/ metadata and binaries under target/, with CMAKE_BUILD_TYPE unset.
Boundary of the edition: one native window per process, one UI thread, X11 including Xwayland where its tested capabilities match, 1× integer device coordinates, bounded CPU rendering, ASCII one-line text, fixed and content sizes, row/column/overlay layout, basic pointer and keyboard activation. No Wayland backend, GPU renderer, multiwindow, fractional DPI, flex grow/shrink, arbitrary transforms, scrolling, IME/rich text, async tasks, or accessibility parity. The design leaves room for extensions but does not advertise them as implemented.
The post-capstone roadmap covers web-like native capabilities and when embedding an actual web engine makes more sense. It does not change the requirements of the first edition.
Capstone acceptance trace: Start at 0 with no focused control. Click + → 1 and focus +. Press Tab → focus -, count unchanged. Press Space → 0. Resize → count still 0 and focus still on - if it remains visible. Click blank space → no count change, then close → clean exit. Verify the same trace headlessly and an observable subset natively. The toggle app must start independently and change from Off to On through the same path.
2. Architecture to earn, not scaffold on day one
X11 server ↔ native window adapter ── normalized events ──┐
↑ ↓
│ runtime + event routing
│ ↓ action
│ app-owned persistent state
│ ↓ describe UI
│ transient element tree
│ ↓ layout
│ hit/focus records ← resolved bounds
│ ↓ scene commands
└── native upload ← CPU pixel surface ← software rasterizer
| Boundary | Inputs → outputs | Ownership and invariants |
|---|---|---|
| Native adapter | Window options → native window; server events → resize, expose, close, pointer, key, or activation events; completed pixels → native upload | Connection outlives window, graphics context, and pending requests. Native replies/events are released by the adapter. Close or connection loss stops the loop; no rendering after close. No native types in app-facing headers. |
| Runtime and scheduler | Event batch + dirty flags → zero or one new frame per turn | Single UI thread, no recursive frame construction. Distinguish rebuild (state, geometry, or focus changed) from present again (exposure with a usable frame). Drain a bounded batch so a continuous event stream cannot starve rendering. Wait for work when clean. |
| App and elements | Stable app state → fresh elements; semantic action → state mutation and change result | Session owns the model. Tree is per-build data; nodes use values and owned child collections. An interactive element has an app-provided stable ID, unique within the current tree. A handler stored past a build cannot borrow a transient node. |
| Layout and frame snapshot | Element tree + viewport → ordered boxes, clip regions, paint commands, and hit/focus records | Bounds are in one coordinate space: window-local, x right, y down, right/bottom exclusive. Use checked arithmetic when deriving extents. The latest successfully prepared frame is the source of truth for both what can be hit and what is painted. |
| Paint and presentation | Commands → owned CPU pixel buffer → native transfer | Renderer borrows writable storage, validates extent/stride, clips before writes, and preserves command order. X11 visible pixels are serialized separately from the in-memory format. Borrowed views cannot survive the buffer or resize. |
| Text | ASCII string + font/size → line metrics and positioned glyph masks | Font service owns the library/face; copy glyph data that must survive loading another glyph. Measure and paint with the same advance/baseline rules. Test with an identified font; don’t compare driver-dependent screenshots. |
Decisions and contracts that prevent rework
- Event ordering: process native input in order. Before a later pointer/key event that needs current hit/focus data, rebuild any geometry or interaction records invalidated by an earlier event in the same batch. Commit the frame snapshot atomically; if a new layout was needed for dispatch, accrue paint work and present once at the end of the turn. Multiple necessary layout preparations do not promise multiple presentations. Do not synthesize a click from a release alone: press and release must match a live control ID. Losing OS focus or removing the target cancels the pending press.
- Interaction identity: hit-test the topmost eligible control using visible clipped bounds, not the original unbounded rectangle; leaf target only in this edition. Tab traverses the ordered eligible controls and wraps (Shift+Tab reverses). Presses that arrive without an active window do not activate controls; on deactivation clear pending input, hide the focus indicator, and restore the remembered ID on activation only if still eligible. No capture/bubble or global shortcut system in the first edition.
- Redraw: initial startup and a changed viewport request a full frame. Expose may reuse pixels at the matching size. An action that does not change state or focus must not cause a redraw. Repeated invalidations coalesce; use presentation counts and traces, not a machine-dependent FPS threshold. Never combine an old hit snapshot and a new visual frame.
- Layout subset: a viewport supplies finite constraints. Leaves have fixed or intrinsic desired dimensions. Row/column place children in declaration order with padding/gap; explicit sizes are requests bounded by incoming constraints. When desired content does not fit, it is clipped, not redistributed; later children may become invisible and non-hittable. Overlay places children in the same content origin; later children paint above earlier ones. Keep tests for exact small layouts separate from policy discussions about Flexbox.
- Pixel transport: use an opaque RGB surface, with a documented 4-byte internal pixel representation (define ordering without assuming host endianness). The native adapter reads the server screen/visual masks, depth, bits per pixel, scanline pad, and image byte order. To keep the edition bounded, support only the tested 24-bit TrueColor profile with 32 bits per pixel and conventional RGB masks; reject unsupported profiles explicitly rather than silently swapping channels. Validate dimensions and allocation products. Budget frame memory; size native upload chunks within the negotiated request limit, using a checked path in the prototype and verifying that resize cannot upload a stale-sized frame. See the X11 protocol and ICCCM window-manager conventions.
- Keyboard subset: resolve X11 key events through the server’s current keyboard and modifier mapping.
xkbcommon-x11is discoverable in this workspace; verify the server path before committing to it. Never hard-code hardware keycodes or assume Shift is a fixed bit without validating the mapping. Normalize only Tab/Shift+Tab (includingISO_Left_Tabwhere mapped), Return, and Space for the course’s app. Activate once on a non-repeat key press for a focused eligible control; verify repeat suppression on the native adapter before promising it. - Text subset: printable ASCII, one explicit font at a caller-selected integer pixel size; no wrapping, kerning, shaping, or fallback. Out-of-contract input is rejected or replaced per a single documented rule before writing the stage contract. Measure with advances, paint using bearings and baseline, blend grayscale coverage over the opaque pixel target. Start with a licensed identified font asset and lock it before writing fixture expectations. The FreeType glyph guide distinguishes metrics, raster images, and glyph-slot lifetime.
- Build structure: start with
src/main.cpp. Extract native code as soon as the lifecycle behavior is established; split core and native at the first headless rendering check; extract/include the app-facing API only once there is a real consumer. Target shape by the capstone:gpui_cc_core, one X11 adapter/host target, counter and toggle executables, and separate test targets. Names and file layout are provisional until their stage; no huge directory scaffold. - Toolchain floor: the existing
CMakeLists.txtrequires CMake 4.0 and this workspace has a compatible version. The book must test installation or state that minimum explicitly; it must not assume every distribution ships it. Treat a lower minimum as a separate compatibility decision, not an implicit project edit.
Public and test surfaces
The public surface should be just large enough for the two apps: run with window options and an application; construct a row, column, overlay, panel, label, or button; give an interactive node a stable ID and an action; build the UI from current state; report whether handling the action changed anything. It must not prescribe a Rust entity clone or force a particular C++ inheritance/template style. Lock names and signatures when the first two consumers prove the shape; document the old-to-new migration if an early seam changes.
Test the library at three layers: pure geometry, scene and glyph-mask composition; runtime integration with injected normalized events and a recording/headless presenter using the same core; native smoke against a private X server with external protocol observations. The headless tests inspect state/frame properties at a narrow documented seam; no custom JSON debug protocol or special user-facing CLI unless the grader genuinely needs one. Build and probe modes introduced early can be superseded or kept as explicit modes—never require a stale startup print from the finished app.
3. Ordered implementation stages
These are implementation contracts, not lesson text. Each check must fail against its immediate predecessor for the stated reason and pass after the stage. C0 is already accepted in this workspace; in the book it also covers starting from an empty directory. Names in the course execution plan use the same stage IDs for the pilot.
| Stage · prerequisites | Increment and concept | Acceptance check; plausible wrong version to reject |
|---|---|---|
C0 setup-build · none |
Create Git baseline, one C++20 target, output separation, ignored generated paths. | Clean configure/build/run succeeds and prints the agreed greeting at this stage; a broken source with a stale binary must not pass. |
N1 display-connect · C0 |
Acquire the XCB connection; separate a handle from successful acquisition; release on both outcomes. | An unavailable default display yields stderr and nonzero; a verified available isolated display yields zero. Reject an always-success probe. Review cleanup on both branches. |
N2 window-map · N1 |
Create, title, map, flush, and keep one native top-level window alive for inspection. Learn server resources and mapping. The checker owns teardown before close handling exists. | Observe the process’s actual titled, viewable window on the isolated server at the requested initial size. Reject a printed title, a created-but-unmapped window, or a window removed by early process exit. |
N3 window-close · N2 |
Wait for native events, register WM_DELETE_WINDOW, close correctly; distinguish a request to close from a broken connection. Extract the adapter after this stage. |
Verify protocol registration; an unrelated message does not quit, matching close exits 0, lost test server exits without hanging. Reject an event loop that busy-spins, exits on any client message, or ignores close. |
R1 present-frame · N3 |
Establish the drawing target: own a CPU image, clear to a supplied color, and upload to the native window. No shape primitive yet. | Launch two fixture configurations with distinct surface colors and a fixed, different native background; inspect native pixels at multiple positions. Include unequal R/B channels. Reject only setting a window background or writing color to CPU memory without uploading. Confirm CPU buffer creation and use in review. Validate supported format during setup. |
R2 resize-frame · R1 |
Give the surface a lifecycle: resize safely, handle exposure and invalid extents, cap memory and per-request uploads. | Positive checks at different sizes include one image larger than a single allowed request; expose restores content at current size. Headless invalid/overflow extents fail cleanly. Reject stale bottom/right pixels or repeated allocation on unchanged extent. |
R3 raster-rect · R2 |
Add point/size/bounds, row stride, clear and clipped solid fills. Use the first pure rendering check to split out core code. | Exact small fixtures cover all four edges, empty/offscreen rectangles, exclusive right/bottom, padded rows, and untouched sentinel storage. Reject an inclusive edge or wrong stride. |
R4 scene-order · R3 |
Record ordered paints separate from execution. Carry an effective clip on commands; do not introduce a retained GPU scene. | Two overlapping commands in opposite orders produce opposite final overlap colors; nested clips intersect and do not leak to siblings. Reject sorting by color or clipping against only the window. |
L1 layout-box · R4 |
Measure/place one leaf against finite constraints. Paint with the resulting bounds instead of authored pixel coordinates. | Same declared element fits two viewport sizes; exact output includes nonzero origin and clipped narrow case. Reject keeping the first computed width. |
L2 layout-tree · L1 |
Compose nested rows, columns and overlays using padding, gap, and declaration order. Establish a small owned element tree. | Exact fixture checks nested translations, empty containers, gaps, and clipping when a viewport is too small. Paint and frame bounds agree. Reject applying local origins twice or allowing a child to paint outside ancestor clip. |
I1 hit-target · L2 |
Collect a frame-local input map from the layout and select the topmost visible eligible target. Guard stable ID uniqueness. | Check overlap, clipped region, right/bottom edge, blank area, and a resize followed by a pointer event in the same batch. Reject stale or unclipped hit boxes. |
I2 pointer-action · I1 |
Normalize native pointer input and route matching press/release to one semantic action. | Press/release on same live ID fires once; drag outside, blank clicks, target removal, OS deactivation, unrelated buttons, or a bare release fire none. Reject activation on press and release. |
S1 state-update · I2 |
Get state out of the transient tree. Render fresh elements from persistent app state and update via actions. | Inject actions, rebuild repeatedly, and resize; count remains correct and updated content reaches the frame. A focus-independent fixture exercises two model instances; reject globals and state stored in new elements. |
S2 redraw-coalesce · S1, R2 |
Replace opportunistic draw with explicit dirty work and a bounded event turn. | Burst of effective actions gives correct final state and one presentation for that turn; no-op/idle produce none; exposed unchanged content can re-present without rebuilding; close wins over dirty work. Reject an unconditional frame/tick loop. |
I3 focus-traverse · I1, S2 |
Stable focus identity, visible focus, traversal, and deactivation. Dispatch only to eligible controls in the active frame. | Tab and Shift+Tab traverse and wrap; removing or hiding the focused node leaves no stale pointer; resizing a still-visible focused control preserves identity. Reject traversal by memory address or using an invisible target. |
I4 key-activate · I3, I2 |
Translate native key/mapping data; feed keyboard actions through the same action path as pointer input. | Isolated X11 probe plus headless traces: Return/Space activate focused control once, unrelated keys and repeats do not; Shift+Tab works with remapped modifier state. Reject hard-coded physical keycodes or separate keyboard model mutation. |
T1 text-measure · L2 |
Load a fixed font, measure one ASCII line, use its metrics for intrinsic label size. | Different strings and sizes give expected invariant advances; spaces advance without ink, missing font is diagnosed. Reject measuring from bitmap width alone. |
T2 text-paint · T1, R4 |
Convert glyphs to owned/reusable masks, place relative to baseline, composite and clip using the same text layout. | Headless synthetic masks test blend and clipping exactly; a real font test checks visible ink, reused origin/advances, and that later glyph loads don’t replace earlier masks. No whole-desktop capture threshold. |
A1 counter-app · I4, S2, T2 |
Link an app against the extracted interface and assemble the first complete UI. | Headless deterministic state/interaction trace and native smoke: count transitions, focus visibility, resize, idle and close. Reject accidental bypass of runtime or renderer in the demo. |
A2 reuse-api · A1 |
Build and document a second app on the same library. Stabilize the small public API. | Build the second consumer without native/render headers, app-specific framework code, or public-contract changes; repeat the shared interaction/lifecycle checks. Release gate requires a clean end-to-end rehearsal. |
Dependency checkpoints: N3 proves platform lifecycle; R2 proves pixels reach a native window; L2 makes layout the source of geometry; I4 + S2 closes the interaction/state/frame loop; A2 proves the separation between application and framework. An earlier stage that is unsupported or incorrect blocks the dependent checkpoint unless scope is explicitly revised.
4. Test and failure plan
| Layer | Coverage target | Evidence to keep |
|---|---|---|
| Pure tests | Every geometry edge and clip policy; image-size overflow and padded stride; scene order; exact synthetic glyph blend; bounded text measurement invariants. | Named input/output fixtures with an enabled assertion mechanism that does not disappear in release builds; optional sanitizer run (ASan/UBSan) for surface/indexing and lifetime checks. |
| Runtime integration | Every normalized event class introduced by the course; resize-before-hit ordering; stable focus across a rebuild; press cancellation; idle, coalescing, and close order. | Deterministic replay with snapshots of model state, hit IDs, and presentation counts. No sleep-based success assertions; keep counts at the observable boundary. |
| Native smoke | Real display acquired, viewable window, actual uploaded pixels, resize/expose, close protocol, at least one physical-style pointer/keyboard sequence, recovery on connection loss. | Private X server, bounded waits with diagnostics, restricted environment and runner-owned cleanup. Try Xvfb first; ensure local-only transport and private authorization/access where supported, and prove the runner never uses the session DISPLAY for injection. Bare Xvfb needs an explicit synthetic WM_DELETE_WINDOW probe; representative window-manager behavior is a separate lane. |
| Checker QA | Each stage has a preceding red checkpoint and green reference evidence; reject at least one plausible shortcut for high-risk contracts. No infrastructure failures reported as pass. | Show selected prerequisites, executable path, exact probes/inputs, expected versus actual, replay seed when applicable, and statuses PASS, FAIL, BLOCKED. Use isolated fixtures, not learner source edits. |
| Acceptance | Both apps build from the same unmodified library; at least one end-to-end native smoke and one clean rebuild from empty-project instructions; no unresolved defect violating a promised contract. | Release report tied to revisions, supported environment, exclusions, manual observations, and remaining blocked lanes. No percentage coverage target as a proxy for these proofs. |
Risk and fallback decisions
- Isolated display unavailable.
Xvfbwas not found in this workspace. Document a provisioned test environment or a proven equivalent before GUI stages are authored at scale. Pure tests can still run; manual display observations are not automated passes. Do not use an unrestricted real desktop as the fallback. - X11 format or upload assumptions break. Run a tiny diagnostic in an isolated technical spike; record the negotiated format, supported size budget, and proof of upload larger than one request. Narrow the advertised environment if necessary; do not silently add a rendering backend or copy native pixels as if they were internal colors.
- Keyboard translation is unavailable in a test environment. Check
xkbcommon-x11, not only basexkbcommon, and verify a real mapping. If unavailable, choose documented setup or a bounded XCB core-keymap implementation with an explicit supported subset. Do not skip native keyboard verification or silently use raw keycodes. - State/input abstractions grow too early. Defer entity stores, focus managers, generic backend registries, and diffing until a stage proves the need. The second app is the checkpoint for API extraction; headless tests are the checkpoint for what needs an internal seam.
- An original assumption fails. Record what test or learner observation forced the change, affected stage IDs, replacement test, and migration path in the decision log. Update the book, checker, and fixtures together. If a stage has several independent failure causes, split it instead of weakening the check.
5. Authority and execution order
- Source companion: FRAMEWORK-REFERENCES.md traces the pinned GPUI-CE checkout. Use its sections 1–2 for N/R/L, 3 for I, 4 for S, 5 for T, and 6 for headless validation and native smoke assumptions.
- What we are not copying: GPUI-CE uses a periodic X11 refresh source (it can request work without drawing or presenting), Taffy for layout, entity-based invalidation, and WGPU for native presentation. Our on-demand CPU path is a course design. GPUI’s mouse dispatch uses the committed hit map; dirty keyboard dispatch can synchronously draw first. Our R/L/I contracts deliberately specify fresh interaction records after an invalidating event without requiring an extra presentation in the same turn.
- Book status: the HTML handbook contains all stages through A2. The verification guide separates independent X11 checks from the CTest fixtures the learner adds in later chapters. Full release evidence still requires a clean capstone run and learner rehearsal.
- Current learner checkpoint: C0 accepted at
4c2a788; N1 not implemented or graded. Only N1 is assigned now even though the later chapters are readable.