Rendering engines

Mouser draws through a swappable GPU rendering engine. The Mouser engine (wgpu) is the default, Skia is built in as an option, and custom engines can be installed and removed. Engines only cover GPU rendering: the softbuffer CPU renderer (MOUSER_RENDERER=cpu, or when no GPU is available) is not an engine and is unchanged.

1. What an engine draws

The core already turns the terminal into a resolved frame before anything touches the GPU: render_frame lays out the cell grid, colours, cursor, selection highlight, underlines, box drawing, the tab bar, panels, the status line and images into a display list (mouser-render/src/text.rs, DisplayList):

op fields
clear colour (0xRRGGBB)
rect x, y, w, h, colour
glyph x, y (top-left of the bitmap), char, colour; the bitmap comes from the core's font stack (8-bit coverage, cached per char and size)
image x, y, drawn width/height, the RGBA8 image (already downscaled by the core when large), a source rect, a cache key; engines scale nearest-neighbour to the drawn size

So an engine never sees terminal state (grid, scrollback, Fuzzball/Kitty placements, selection): those are all resolved by the core into the ops above, which keeps every engine pixel-compatible and makes features (selection, images, new UI) work in all engines at once. The CPU replay of the same list is the reference image in tests.

Damage: v1 hands over the whole frame each time (the core redraws only when something changed, at most every 8 ms). A damage rectangle is reserved in the ABI (dirty, currently always the full surface) so engines can be told about partial updates later without an ABI bump.

The basic renderer

Mouser always has a basic renderer: its built-in CPU drawing presented with softbuffer. It is not an engine, isn't listed as one, and can never be removed (mouser engine uninstall basic refuses, and no engine may be named basic or cpu). It draws the terminal whenever no engine starts — on first run before an engine is installed, when every engine is skipped or failed, and after the last engine crashes. While it draws, the status bar says "basic renderer — no GPU engine running yet". When an engine becomes usable (installed, unskipped or moved in the priority list), the window switches to it live, keeping its tabs. MOUSER_RENDERER=cpu forces the basic renderer and turns the label and the live switch off. mouser engine list ends with "then the basic renderer". Tested in crates/mouser-app/tests/split_tests.rs (no engine, then an engine taking over live with the same shell and tabs; an engine crash moving to the next engine, and from mouser to the basic renderer).

2. Interface

In Rust (mouser-render/src/engine.rs):

pub trait Engine {
            fn name(&self) -> &str;
            fn description(&self) -> String;                 // e.g. adapter / backend
            fn resize(&mut self, width: u32, height: u32);
            /// Draw and present. Ok(false): surface was reset, draw again.
            fn draw(&mut self, list: &DisplayList, fonts: &mut FontStack) -> anyhow::Result<bool>;
        }
        

FontStack::glyph(ch) gives the coverage bitmap and metrics for a char at the current size; fonts.generation changes when the font or size changes, so atlases can be dropped. Every engine, Mouser's own mouser and skia included, is a library that sees this frame through the C ABI below (engine::FrameBuf converts a DisplayList); none is compiled into Mouser.

3. Lifecycle

4. Custom engines: C ABI dynamic libraries

Choice: a shared library with a stable, versioned C ABI (cdylib), loaded with libloading. Reasons:

The library exports one symbol:

const MouserEngineV1 *mouser_engine_v1(void);
        
        typedef struct {
            uint32_t abi;            /* MOUSER_ENGINE_ABI = 1 */
            uint32_t size;           /* sizeof(MouserEngineV1), for additive growth */
            const char *name;        /* engine name, must match the manifest */
            void *(*create)(const MouserSurface *surface, uint32_t w, uint32_t h,
                            char *err, size_t err_len);      /* NULL on failure */
            void  (*resize)(void *engine, uint32_t w, uint32_t h);
            int   (*draw)(void *engine, const MouserFrame *frame); /* 0 ok, 1 redraw, <0 error */
            void  (*destroy)(void *engine);
        } MouserEngineV1;
        
        typedef struct { uint32_t kind;  /* 1 Wayland, 2 Xlib, 3 Xcb, 4 AppKit, 5 Win32 */
                         void *display; void *window; } MouserSurface;
        
        typedef struct { int32_t x, y, w, h; uint32_t color; } MouserRect;
        typedef struct { int32_t x, y; uint32_t w, h, stride, color; const uint8_t *coverage;
                         uint64_t key; } MouserGlyph;        /* key: stable per (char, font generation) */
        typedef struct { int32_t x, y; uint32_t w, h;          /* drawn size */
                         uint32_t img_w, img_h, src_x, src_y, src_w, src_h;
                         const uint8_t *rgba; uint64_t key; } MouserImage; /* RGBA8, straight alpha */
        typedef struct { uint32_t kind; uint32_t index; } MouserOp; /* 0 rect, 1 glyph, 2 image */
        
        typedef struct {
            uint32_t width, height, clear;
            int32_t dirty_x, dirty_y, dirty_w, dirty_h;   /* v1: always the whole surface */
            const MouserOp *ops; size_t op_count;         /* painting order */
            const MouserRect *rects; size_t rect_count;
            const MouserGlyph *glyphs; size_t glyph_count;
            const MouserImage *images; size_t image_count;
        } MouserFrame;
        

All pointers in a frame are valid only during draw. Colours are 0xRRGGBB. The header is crates/mouser-engine-abi/mouser_engine.h; the Rust side of the ABI is the mouser-engine-abi crate, which engine authors can depend on.

ABI v2 (Mouser 1.4.0)

A v2 engine exports mouser_engine_v2, returning a MouserEngineV2 table that starts with a complete v1 table (base.abi = 2, base.size = sizeof(MouserEngineV2)), so the frame types and create/resize/draw/ destroy are unchanged. It adds:

typedef struct { uint32_t size, flags, formats, max_texture; } MouserCaps;
        typedef struct {
            MouserEngineV1 base;
            uint32_t abi_min, abi_max;                       /* the range it speaks */
            void (*caps)(void *engine, MouserCaps *caps);    /* optional (may be NULL) */
            void (*set_scale)(void *engine, float scale);    /* DPI change, optional */
            void (*evict)(void *engine, uint64_t key);       /* drop a cached upload, optional */
            void (*set_vsync)(void *engine, int on);         /* with MOUSER_CAP_VSYNC_CONTROL */
        } MouserEngineV2;
        const MouserEngineV2 *mouser_engine_v2(void);
        

In v2, rect and glyph colours keep their top byte: 255 - opacity (0 = opaque, so plain 0xRRGGBB colours stay opaque). v2 engines blend translucent fills like the built-in renderers; v1 engines get opaque colours.

Mouser tries mouser_engine_v2 first and picks the newest ABI both sides speak (it speaks 1–2); a null return or a missing symbol falls back to mouser_engine_v1, so v1 engines keep loading. Export both entry points to also load in Mouser builds older than 1.4.0 (the flat example does). The engine's description in Mouser shows the negotiated ABI ("custom, ABI 2").

Guards on the Mouser side: the ABI number must match and size must be at least the v1 table, the reported name must match the manifest (checked at install and at load), a negative draw result switches the window to the Mouser engine, and a crash sentinel: before calling create Mouser writes engines/.starting-<name>, and removes it after the first frames are presented. If Mouser finds the sentinel at the next start (the engine crashed the process), it skips that engine, uses the Mouser engine and says so (mouser engine list shows it too); mouser engine use <name> or reinstalling clears it.

Skipped and failed engines

mouser engine list shows a state per engine:

state meaning recorded in what Mouser does
ok nothing recorded uses it when selected
skipped crashed Mouser while starting (sentinel left behind), with when engines/.starting-<name> skips it at every start until restored
failed the last load/start/draw attempt failed, with when and why engines/.failed-<name> still tries it on each start (shown so you know why you got mouser)

mouser engine unskip <name> (alias restore; --all for every engine) clears both records without selecting the engine; mouser engine use <name> clears them and selects it; reinstalling clears them too. A successful start clears failed. Built-in skia is guarded the same way as custom engines (mouser never is: it is the fallback).

When Mouser falls back it prints and logs the reason and the restore command, and shows it in the window's status bar for 15 s, e.g. engine flat is skipped: it crashed Mouser while starting (2m ago). Restore it with mouser engine unskip flat; using mouser.

Why not XDG ($XDG_DATA_HOME/mouser/engines)? Mouser keeps all of its state under one directory, ~/.mouser or $MOUSER_HOME (docs/storage.md), so engines follow that rule; tests point MOUSER_HOME (and HOME) at a temporary directory.

5. Installing

Engines are plugins of kind engine (P6, docs/plugins.md): the built-in mouser and skia have compiled-in manifests, and mouser engine … is the same command as mouser plugin … --kind engine. Installed engines live in $MOUSER_HOME/engines/<name>/ (default ~/.mouser/engines), following Mouser's fixed storage rule (all state under ~/.mouser, MOUSER_HOME override; tests always use a temporary MOUSER_HOME). Each holds the library and a manifest: a plugin.toml with kind = "engine", transport = "library" and an [engine] table (abi, library), or the older engine.toml, which is read as the same plugin manifest:

name = "flat"
        version = "0.1.0"
        abi = 1
        library = "libmouser_engine_flat.so"
        description = "Example engine: solid rectangles and glyph boxes"
        

CLI (thin adapters over mouser_core::engines):

command does
mouser engine list shipped (mouser, skia) and installed engines, the active one marked, broken ones with the reason
mouser engine install <SRC> a folder, engine.toml, library or archive, an official name, gh: or https:// (Downloads); checks the manifest, probes the library in a separate process, installs into engines/<name>/<version>/
mouser engine uninstall <name> removes engines/<name>/ (shipped engines and the basic renderer cannot be removed); if it was in use, the config goes back to mouser
mouser engine use <name> moves it first in the order and unskips it
mouser engine priority <a> <b> ... sets the whole order (mouser appended if missing)
mouser engine move <name> first|last|up|down|<n> moves one engine (1 = first)
mouser engine unskip <name>|--all (alias restore) clears skip/failure records, order unchanged
mouser engine disable|enable <name> takes an engine out of (or back into) the walk, keeping its place; mouser can't be disabled; use refuses a disabled engine

Each of these is also mouser plugin <same> --kind engine.

install also takes an official name, gh:Owner/Repo[@tag] or an https:// URL, and update, rollback, retry and cancel work as for plugins. Every download is checked (sha256, minisign, a probe in a separate process) and goes into its own version folder; see Downloads.

Mouser's wgpu renderer as an engine library

crates/mouser-engine-wgpu (library mouser_engine_wgpu, engine name mouser, ABI v2 only) is Mouser's wgpu renderer on the C ABI: the same shaders, instanced quads, R8 glyph atlas (keyed by MouserGlyph::key), image textures and blending. It presents to the window surfaces (Wayland, Xlib, Xcb, AppKit, Win32) or, in the pixel host, renders offscreen and copies into MouserPixels. It also answers caps (max texture size) and evict.

Parity is tested, not assumed. While the renderer was still built in, crates/mouser-render/tests/wgpu_engine_parity.rs rendered a full frame (styled text, Unicode, the cursor, tabs, the sidebar, a status line, a scaled image and a translucent overlay) offscreen through both and required every channel of every pixel to be within 2. The built-in's frames were then saved as crates/mouser-render/tests/golden/wgpu-*.png (Mesa llvmpipe), and the test now holds the library to them on llvmpipe, cold and warm caches and after a resize; on other adapters (WARP, Metal) it checks that the scene is drawn and stable. CI on Linux installs Mesa and sets MOUSER_REQUIRE_GPU=1 so it can't be skipped there. crates/mouser-engine-wgpu/tests/c_abi.rs drives the C table on the pixel surface.

Mouser's Skia renderer as an engine library

crates/mouser-engine-skia (library mouser_engine_skia, engine name skia, ABI v2 only) is Mouser's Skia engine on the C ABI: Ganesh over OpenGL through glutin (EGL on Linux, CGL on macOS, WGL then EGL on Windows) for a window, or a Skia CPU raster surface for the pixel host. The drawing is the same: Skia rects, one A8 glyph atlas tinted per glyph, nearest-neighbour images, translucent fills. crates/mouser-render/tests/skia_engine_parity.rs paints the same full frame as the wgpu parity test on the CPU raster surface and requires every channel to be within 2 of golden/skia-900x520.png, the former built-in engine's frame (it matched the library before it was removed).

Engines shipped with Mouser

Besides $MOUSER_HOME/engines/<name>/ (what mouser engine install writes), Mouser finds engines shipped with it in engines/<name>/ beside its executable (and ../Resources/engines in a macOS app, ../lib/mouser/engines on Unix, as in /usr/lib/mouser/engines; mouser engine bundle builds that folder, see the release process), each with an engine.toml and the library. engines::stage(lib, out) writes that layout for Mouser's own libraries (mouser_engine_wgpu as mouser, mouser_engine_skia as skia). A development build also finds those libraries lying loose next to the executable, where cargo build leaves them. A user install of the same name wins; a shipped engine can't be uninstalled (move it down or disable it). MOUSER_ENGINE_DIRS (a path list) replaces the shipped locations, for packagers and tests; empty means none.

6. Mouser's own engines

Mouser has no engine compiled in. It ships two libraries in engines/ beside the executable (above) and draws with the basic renderer when neither starts:

cargo build --release -p mouser-engine-example
        mkdir flat && cp target/release/libmouser_engine_flat.so crates/mouser-engine-example/engine.toml flat/
        mouser engine install flat && mouser engine use flat
        

7. Switching live and surviving engine crashes (design, t141u)

Requirements

Switching engines must keep everything the user has (tabs, running programs and their PTYs, scrollback, cursor, selection, images). An engine that crashes must not take the user's shells with it: the window carries on with the next engine in the order and the crashed one is marked skipped (restorable with unskip).

Options considered

  1. In-process engines + signal handler. Catching SIGSEGV and continuing is UB; rejected.
  2. Holder process. A small process owns the PTYs; the UI (parser, scrollback, images, window, engine) is a separate process that reattaches after a crash. It protects against every crash, including the wgpu/Skia drivers, but the UI holds all terminal state, so after a crash it would have to rebuild that state by replaying a byte log of every PTY (bounded, slow for big scrollbacks, images re-decoded), or the holder would have to own the parser and stream screens to the UI (a tmux-style client/server split of the whole terminal). Too big and too risky for this phase; kept as the long-term option.
  3. Out-of-process custom engines (chosen). A custom engine runs in an engine host child process (mouser __engine-host). Mouser sends it each frame (ops, rects, glyph bitmaps and images, each bitmap/image sent once and cached by key) over a pipe; the engine draws into a pixel buffer (MOUSER_SURFACE_PIXELS, a new surface kind: window points to a MouserPixels { data, width, height, stride }); the host returns the pixels and Mouser presents them. If the host dies (segfault, abort, panic, exit), Mouser sees EOF on the pipe: the engine is marked skipped (with the reason), and the window switches to the next engine in the order on the same frame. All state lives in the main process, so nothing is lost.

Engines in the UI process

On a window, mouser and skia (like any engine not run in the engine host) are loaded into the UI process for direct GPU presentation. They are covered as far as is sound:

Switching

Engines are swapped on the same window: the old engine is dropped (its surface is released), the new one is created on the window, the window is redrawn. Sessions, PTYs and all terminal state are untouched because they never belonged to the engine; the window keeps its size and position (nothing for the compositor to redo). If the new engine cannot start on the existing window, the next one in the order is tried (mouser last, then the CPU renderer).

Running windows learn about a change by watching preferences.toml (checked twice a second): when the effective first engine of the priority order changes (mouser engine use, priority, move, unskip), each window switches. No socket is needed; an MOUSER_ENGINE override pins a window's order for its lifetime.

Pixel-buffer engines: costs

The pipe carries one frame of ops (tens of KB) and returns width x height x 4 bytes (3.3 MB at 1100x760); measured below. GPU custom engines must read back their image (the price of isolation). An engine that cannot draw into pixels fails create with that surface and is passed over. Windows has no engine host yet (custom engines stay in-process there).

As built

Limits: a native crash in the GPU driver, wgpu or Skia's C++ (built-ins are in-process) still ends Mouser (next start skips that engine); an engine host shows its output via softbuffer (one copy of each frame); the selection is kept by switching (it is core state) but nothing is preserved across a whole-Mouser crash.

8. Session/UI process split (design, t145u)

Goal: a native crash in any engine (GPU driver, wgpu, Skia's C++, a custom engine) never loses shells, scrollback, tabs or images. Rollback point: tag pre-session-split (adf349b).

Where the line is

Mouser already has a narrow, data-only boundary between the terminal and the window: RenderHooks (mouser-render/src/lib.rs). The renderer loop asks for the view (fetch_view, get_images, get_cursor, get_colors, get_font, get_tabs, get_ui_model, get_status, get_title, ...) and reports input (on_key_event, on_mouse, on_select, on_resize, on_ui_action, on_paste, ...). Everything behind the hooks (sessions, PTYs, parser, scrollback, graphics, selection, sidebar model, preferences) is the server; the winit loop + engine is the UI. The split turns the hooks into calls over a socket. No terminal code moves, so behaviour stays the same and the single-process mode (Windows, MOUSER_PROC_FORK=0) keeps working unchanged.

Processes and lifecycle

Protocol

Length-prefixed bincode messages.

State sync: there is no screen-state replication to keep in sync. The UI holds no terminal state, only per-window input state (scroll position, drag, hover) and caches (glyph atlas, image textures). A new UI starts empty and asks for the current view on its first frame, so "full snapshot on attach" is simply the first frame; afterwards every frame asks again (the view for the visible rows only, ~tens of KB). Damage tracking is still the full frame (as before the split).

Resize: the UI sends on_resize (cols, rows, pixels) as before; the server resizes the PTYs. Input: key/mouse/selection events are hook calls; their replies are immediate.

Latency budget

A frame makes ~12 calls; a socketpair round trip is ~10–30 µs, so ~0.3 ms per frame, well inside the 25 ms (40 fps) budget. Keystroke-to-frame adds one call for the key and the next frame's calls. Measured before/after (§9).

Engine host

Kept for custom engines: inside the UI it turns a custom-engine crash into an in-place switch (no window re-creation, no flash), which is nicer than a UI restart. The UI restart covers everything the host doesn't (built-in engines, the host itself).

Platforms

Linux and macOS: split by default. Windows: no socketpair/fd inheritance in std; stays single-process (custom engines still in-process). Known limitation in 1.0: on Windows an engine or GPU driver crash ends the window and its shells, and a crashing custom engine is not survived. A port would hand the UI child two anonymous pipe pairs (or a named pipe) instead of the socketpairs and needs testing on a Windows machine.

What a UI crash still loses

The window itself (it is re-created: the compositor decides the position; the size is kept), scroll-back position of the view (back at the bottom), an in-progress mouse drag, the glyph/image caches (rebuilt). Shells, programs, scrollback, tabs, images, selection, sidebar state and preferences are in the server and survive.

As built (t145u)

The bottom of the expanded right sidebar, above Appearance, lists the available engines (built-ins and installed ones) in priority order with their state: active (this window), ok, skipped or failed, with the reason on a second line. A click does mouser engine use <name> (unskip, move first); the window's preferences watcher then switches it live, like the CLI.

Drag to reorder: press on a row and move more than 5 px (ui::DRAG_THRESHOLD; less is a click). The row is outlined in place, a ghost follows the pointer and an accent insertion line shows where it will land (before the first row whose middle is below the pointer). Dropping saves the order with engines::set_priority, the same path as mouser engine priority; every running window applies it live and switches if a different usable engine is now first. Escape, a drop outside the section (half a row of slack above and below) or a drop in the same place cancels. mouser can be dragged anywhere and is never removed. The sidebar does not scroll, so there is no auto-scroll. Under a MOUSER_ENGINE override a click or drop still saves the order and the status bar notes that this window keeps its override until restarted. Logic: ui::{EngineDrag, EngineDrop, drop_index, drop_zone, reordered}; the window keeps the drag state and draws it via UiLayout::engine_drag. The sidebar has no keyboard focus navigation, so the section is mouse-only like the rest of the bar. Hit-testing: ui::add_engines, ui::hit_test -> UiAction::UseEngine (mouser-render/tests/sidebar_engines_tests.rs).

Rollback point for the split: the annotated tag pre-session-split (adf349b).

9. Performance

Measured on a Linux desktop (Hyprland, 1100x760, the multi-image screen, ~240 drag-resize steps), after isolation: mouser 62–63 fps (frame p95 7.0 ms), skia 63 fps (p95 12.4–13.4 ms), flat in the engine host 61.7 fps (p95 15 ms). The sweep issues one resize per ~16 ms, so ~60 fps is the ceiling of the test. Skia's output matches the CPU reference to a few hundred pixels (cursor/rounding); the wgpu engine differs slightly more (its blending was already a little different).

Source: docs/engines.md