abstracttui 0.6.0

A reactive, compositor-grade terminal UI engine: fine-grained signals, layered rendering with damage tracking, images (kitty/iTerm2/sixel/mosaic), software-rasterized 3D (GLB), themes and animation.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
//! capture — the deterministic screenshot pipeline for the docs cycle.
//!
//! Runs the shipped examples under a real pty at fixed sizes/themes,
//! interprets the emitted bytes with the testing rig's `VtScreen`, and
//! dumps two artifacts per shot into `docs/captures/`:
//!
//!   `<name>.txt`         plain-text screen render (fenced "screenshot")
//!   `<name>.styled.txt`  deterministic styled dump (text + style runs)
//!
//! Also produces `themes-table.md` (all registered themes with their
//! token hex values, straight from the registry) and in-process splash
//! frames (2D + 3D at t = 1.0 s) — no pty involved for those.
//!
//! A fourth family (`app_shots.rs`) renders the app-layer surfaces —
//! streaming transcript + composer + completion, an open Select popup,
//! a diff-tinted CodeView, a scrolled feed, a doc-vocabulary reader
//! still (table/tasks/strike) — fully IN PROCESS through
//! `Driver` + `CaptureTerm`: fixed data, scripted input, no clocks, no
//! pty — byte-deterministic.
//!
//! Usage:
//!   cargo build --workspace --examples        # shots run the built binaries
//!   cargo run --example capture               # everything published
//!   cargo run --example capture -- themes     # just themes-table.md
//!   cargo run --example capture -- splash     # just the splash frames
//!   cargo run --example capture -- shots      # just the pty captures
//!   cargo run --example capture -- apps       # just the in-process app shots
//!   cargo run --example capture -- review     # review sweep -> untracked/
//!
//! The `review` family (`review_shots.rs`) is the design-review sweep:
//! EVERY runnable example (root + extensions) in two or three staged
//! states, written to `untracked/review-shots/` — never published, so
//! wall-clock wobble is acceptable there.
//!
//! Determinism: sizes, themes, and demo data are fixed (the dashboard
//! honors `ABSTRACTTUI_FIXED_CLOCK`/`ABSTRACTTUI_START_THEME`); the one
//! honest wobble is wall-clock frame pacing — a tick more or fewer of
//! animated data between regenerations. Regenerate deliberately and
//! diff by eye; these are documentation stills, not golden tests. The
//! `apps` family has no wobble at all (headless, scripted, clockless).

mod app_shots;
mod review_shots;

use std::fs;
use std::path::Path;
// The pty half (and its bin-dir walk) is unix-only; keep the import
// with it so the windows cross-check stays warning-free.
#[cfg(unix)]
use std::path::PathBuf;

use abstracttui::base::Size;
use abstracttui::boot::{Brandmark3d, FallbackSplash, SplashFrameSource};
use abstracttui::render::{Cell, FrameDiff, PresentCaps, Presenter, Surface};
use abstracttui::testing::VtScreen;
use abstracttui::theme::{default_theme, themes, TokenSet};

/// One pty capture: which example, at what size, with which env, and a
/// paced key script. The captured frame is the LAST one painted before
/// the app leaves the alternate screen — so the final step must quit
/// WITHOUT disturbing the staged state (`\x03` = the default Ctrl+C
/// quit works from any state: modals, focus traps, composers where a
/// plain `q` would just type a letter).
// Fields are read by the unix pty path only; the non-unix stub keeps
// the table compiling without pretending to use it.
#[cfg_attr(not(unix), allow(dead_code))]
struct Shot {
    /// Artifact base name (in docs/captures/ or the review dir).
    name: &'static str,
    /// Example binary name under target/…/examples/.
    example: &'static str,
    cols: i32,
    rows: i32,
    /// Paced input: (settle delay in ms, then these bytes) per step.
    /// Each delay runs BEFORE its bytes — the first one covers boot.
    steps: &'static [(u64, &'static str)],
    /// Extra env for the child (TERM/COLORTERM are always set).
    env: &'static [(&'static str, &'static str)],
}

/// Fixed demo clock: 12:34:56 UTC — reads well in a screenshot.
const FIXED_CLOCK: (&str, &str) = ("ABSTRACTTUI_FIXED_CLOCK", "45296");

const SHOTS: &[Shot] = &[
    Shot {
        name: "hello",
        example: "hello",
        cols: 80,
        rows: 24,
        steps: &[(1500, "q")],
        env: &[],
    },
    Shot {
        name: "dashboard-dark",
        example: "dashboard",
        cols: 120,
        rows: 35,
        steps: &[(3500, "q")],
        env: &[FIXED_CLOCK],
    },
    Shot {
        name: "dashboard-dawn",
        example: "dashboard",
        cols: 120,
        rows: 35,
        steps: &[(3500, "q")],
        env: &[FIXED_CLOCK, ("ABSTRACTTUI_START_THEME", "abstract-dawn")],
    },
    Shot {
        name: "themes",
        example: "themes",
        cols: 110,
        rows: 30,
        steps: &[(1800, "q")],
        env: &[],
    },
    Shot {
        name: "widgets",
        example: "widgets",
        cols: 110,
        rows: 32,
        steps: &[(1800, "q")],
        env: &[],
    },
    Shot {
        name: "components",
        example: "components",
        cols: 100,
        rows: 30,
        steps: &[(1800, "q")],
        env: &[],
    },
    Shot {
        name: "grid",
        example: "grid",
        cols: 110,
        rows: 30,
        steps: &[(1800, "q")],
        env: &[],
    },
    Shot {
        name: "gallery",
        example: "gallery",
        cols: 112,
        rows: 38,
        steps: &[(1800, "q")],
        env: &[],
    },
    Shot {
        name: "viewer3d",
        example: "viewer3d",
        cols: 100,
        rows: 30,
        steps: &[(2000, "q")],
        env: &[],
    },
    Shot {
        name: "images",
        example: "images",
        cols: 100,
        rows: 30,
        steps: &[(1800, "q")],
        env: &[],
    },
];

fn main() {
    let what = std::env::args().nth(1).unwrap_or_else(|| "all".into());
    let out = Path::new(env!("CARGO_MANIFEST_DIR")).join("docs/captures");
    if let Err(e) = fs::create_dir_all(&out) {
        eprintln!("capture: cannot create {}: {e}", out.display());
        std::process::exit(1);
    }
    let mut produced: Vec<String> = Vec::new();
    let mut published = false;
    if matches!(what.as_str(), "all" | "themes") {
        produced.push(themes_table(&out));
        published = true;
    }
    if matches!(what.as_str(), "all" | "splash") {
        produced.extend(splash_frames(&out));
        published = true;
    }
    if matches!(what.as_str(), "all" | "shots") {
        produced.extend(pty_shots(&out, SHOTS));
        published = true;
    }
    if matches!(what.as_str(), "all" | "apps") {
        produced.extend(app_shots::app_shots(&out));
        published = true;
    }
    // The design-review sweep: never part of `all`, never published —
    // it writes to untracked/ so wall-clock wobble stays out of docs/.
    if what.as_str() == "review" {
        let review_out = Path::new(env!("CARGO_MANIFEST_DIR")).join("untracked/review-shots");
        if let Err(e) = fs::create_dir_all(&review_out) {
            eprintln!("capture: cannot create {}: {e}", review_out.display());
            std::process::exit(1);
        }
        produced.extend(pty_shots(&review_out, review_shots::REVIEW_SHOTS));
    }
    if produced.is_empty() {
        eprintln!(
            "capture: nothing produced (arg {what:?}; expected all|themes|splash|shots|apps|review)"
        );
        std::process::exit(1);
    }
    // The manifest indexes the DIRECTORY, not this run — partial runs
    // (`-- shots`) must not delist the other artifact families. Review
    // runs never touch it.
    if published {
        write_manifest(&out);
    }
    println!("capture: {} artifacts", produced.len());
}

// ---------------------------------------------------------------- themes

/// `themes-table.md`: a scannable summary row per theme (the headline
/// tokens), then a full per-theme token listing. Deterministic registry
/// walk — the docs embed this verbatim.
fn themes_table(out: &Path) -> String {
    let mut md = String::new();
    md.push_str("# Theme reference\n\n");
    md.push_str("Generated by `cargo run --example capture -- themes` — do not edit.\n\n");
    md.push_str("## Summary\n\n");
    md.push_str(
        "| id | label | polarity | bg | surface | text | accent | ok | warn | error | info |\n",
    );
    md.push_str("|---|---|---|---|---|---|---|---|---|---|---|\n");
    for th in themes() {
        let t = &th.tokens;
        md.push_str(&format!(
            "| `{}` | {} | {} | `{}` | `{}` | `{}` | `{}` | `{}` | `{}` | `{}` | `{}` |\n",
            th.id,
            th.label,
            if th.is_dark() { "dark" } else { "light" },
            t.bg.to_hex(),
            t.surface.to_hex(),
            t.text.to_hex(),
            t.accent.to_hex(),
            t.ok.to_hex(),
            t.warn.to_hex(),
            t.error.to_hex(),
            t.info.to_hex(),
        ));
    }
    md.push_str("\n## Full token values\n");
    for th in themes() {
        md.push_str(&format!(
            "\n### {} (`{}`, {})\n\n| token | hex |\n|---|---|\n",
            th.label,
            th.id,
            if th.is_dark() { "dark" } else { "light" }
        ));
        for (name, value) in token_rows(&th.tokens) {
            md.push_str(&format!("| {name} | `{value}` |\n"));
        }
    }
    let path = out.join("themes-table.md");
    fs::write(&path, md).expect("write themes-table.md");
    rel(&path)
}

/// Every token as (name, hex) — chart entries flattened. Order mirrors
/// `TokenId::ALL` for scannability.
fn token_rows(t: &TokenSet) -> Vec<(String, String)> {
    use abstracttui::theme::TokenId;
    TokenId::ALL
        .iter()
        .map(|id| (id.name().to_string(), t.get(*id).to_hex()))
        .collect()
}

// ---------------------------------------------------------------- splash

/// In-process splash stills: both frame sources render two beats — t =
/// 1.0 s (just after the alignment burst, sparks in flight) and t =
/// 1.95 s (wordmark settled, afterglow gone) — into a Surface;
/// a full diff against an empty surface plus the Presenter turns that
/// into the same bytes a terminal would receive, and `VtScreen` renders
/// them. History-dependent trails get a monotonic render walk.
fn splash_frames(out: &Path) -> Vec<String> {
    let size = Size::new(100, 30);
    let theme = default_theme();
    let mut produced = Vec::new();
    let mut sources: [(&str, Box<dyn SplashFrameSource>); 2] = [
        ("splash-2d", Box::new(FallbackSplash::new())),
        ("splash-3d", Box::new(Brandmark3d::new())),
    ];
    for (name, source) in sources.iter_mut() {
        for (t, suffix) in [(1.0f32, ""), (1.95, "-reveal")] {
            let surface = source.render(t, size, theme);
            let screen = surface_screen(surface, size);
            produced.extend(write_shot(out, &format!("{name}{suffix}"), &screen));
        }
    }
    produced
}

/// Surface -> terminal bytes -> interpreted screen.
fn surface_screen(surface: &Surface, size: Size) -> VtScreen {
    let empty = Surface::new(size, Cell::EMPTY);
    let mut diff = FrameDiff::new();
    let runs: Vec<_> = diff.compute_full(&empty, surface).to_vec();
    let mut presenter = Presenter::new();
    let mut bytes = Vec::new();
    presenter.emit(&runs, surface, &PresentCaps::FULL, &mut bytes);
    let mut screen = VtScreen::new(size);
    screen.feed(&bytes);
    screen
}

// ----------------------------------------------------------------- shots

/// Run each example binary under a real pty (`script`), interpret the
/// bytes it wrote, and dump the LAST alternate-screen frame (bytes are
/// truncated at the final `1049l` so the app's exit doesn't wipe the
/// capture back to the primary screen).
#[cfg(unix)]
fn pty_shots(out: &Path, shots: &[Shot]) -> Vec<String> {
    let mut produced = Vec::new();
    let bin_dir = example_bin_dir();
    for shot in shots {
        let bin = bin_dir.join(shot.example);
        if !bin.exists() {
            eprintln!(
                "capture: {} missing ({}) — run `cargo build --examples` first",
                shot.example,
                bin.display()
            );
            continue;
        }
        match run_pty(shot, &bin) {
            Ok(raw) => {
                if raw.is_empty() {
                    eprintln!("capture: {} produced no bytes — skipped", shot.name);
                    continue;
                }
                // Asset-guarded examples print a plain-text notice and
                // exit without entering the alternate screen.
                if !raw.windows(8).any(|w| w == b"\x1b[?1049h") {
                    let text = String::from_utf8_lossy(&raw);
                    eprintln!(
                        "capture: {} never entered the app screen — skipped ({})",
                        shot.name,
                        text.lines().next().unwrap_or("no output").trim()
                    );
                    continue;
                }
                let cut = raw
                    .windows(8)
                    .rposition(|w| w == b"\x1b[?1049l")
                    .unwrap_or(raw.len());
                let mut screen = VtScreen::new(Size::new(shot.cols, shot.rows));
                screen.feed(&raw[..cut]);
                produced.extend(write_shot(out, shot.name, &screen));
            }
            Err(e) => eprintln!("capture: {} failed: {e}", shot.name),
        }
    }
    produced
}

#[cfg(not(unix))]
fn pty_shots(_out: &Path, _shots: &[Shot]) -> Vec<String> {
    eprintln!("capture: pty shots need a unix `script`; themes/splash artifacts still work");
    Vec::new()
}

/// Drive one binary under `script -q` with the pty sized via `stty`,
/// each key step typed after its own settle delay. macOS and util-linux
/// `script` spell the command differently; both are handled.
#[cfg(unix)]
fn run_pty(shot: &Shot, bin: &Path) -> std::io::Result<Vec<u8>> {
    let raw_path = std::env::temp_dir().join(format!("abstracttui-capture-{}.raw", shot.name));
    let _ = fs::remove_file(&raw_path);
    let inner = format!(
        "stty rows {} cols {}; exec {}",
        shot.rows,
        shot.cols,
        sh_quote(&bin.to_string_lossy())
    );
    let script_cmd = if cfg!(target_os = "macos") {
        format!(
            "script -q {} sh -c {}",
            sh_quote(&raw_path.to_string_lossy()),
            sh_quote(&inner)
        )
    } else {
        format!(
            "script -q -c {} {}",
            sh_quote(&inner),
            sh_quote(&raw_path.to_string_lossy())
        )
    };
    let feeder = shot
        .steps
        .iter()
        .map(|(delay_ms, keys)| {
            format!(
                "sleep {}; printf '%s' {}",
                *delay_ms as f64 / 1000.0,
                sh_quote(keys)
            )
        })
        .collect::<Vec<_>>()
        .join("; ");
    let line = format!("({feeder}) | {script_cmd} >/dev/null 2>&1");
    let mut cmd = std::process::Command::new("sh");
    cmd.arg("-c").arg(&line);
    cmd.env("TERM", "xterm-256color");
    cmd.env("COLORTERM", "truecolor");
    cmd.env_remove("NO_COLOR");
    cmd.env("ABSTRACTTUI_NO_SPLASH", "1");
    for (k, v) in shot.env {
        cmd.env(k, v);
    }
    let status = cmd.status()?;
    if !status.success() {
        eprintln!(
            "capture: {} exited {status} (continuing — bytes may exist)",
            shot.name
        );
    }
    fs::read(&raw_path)
}

/// Minimal POSIX single-quote escaping.
#[cfg(unix)]
fn sh_quote(s: &str) -> String {
    format!("'{}'", s.replace('\'', "'\\''"))
}

#[cfg(unix)]
fn example_bin_dir() -> PathBuf {
    // capture itself lives in target/…/examples/ — siblings are there too.
    std::env::current_exe()
        .ok()
        .and_then(|p| p.parent().map(Path::to_path_buf))
        .unwrap_or_else(|| PathBuf::from("target/debug/examples"))
}

// ------------------------------------------------------------- artifacts

/// Write every view of a screen — plain text, styled dump, the
/// pixel-exact PNG, and the GitHub-renderable SVG — returning the
/// relative artifact names.
///
/// The PNG is the FAITHFUL one: every pixel is decided by the engine
/// (embedded bitmap glyphs, geometrically drawn box/block/braille
/// strokes), so it looks the same everywhere. The SVG is the
/// EMBEDDABLE one: GitHub renders it inline in a README, at the cost
/// of depending on whatever monospace font the viewer resolves.
fn write_shot(out: &Path, name: &str, screen: &VtScreen) -> Vec<String> {
    let text_path = out.join(format!("{name}.txt"));
    let styled_path = out.join(format!("{name}.styled.txt"));
    let png_path = out.join(format!("{name}.png"));
    let svg_path = out.join(format!("{name}.svg"));
    fs::write(&text_path, screen.to_text()).expect("write text capture");
    fs::write(&styled_path, screen.to_styled_dump()).expect("write styled capture");
    let shot = screen.screenshot();
    shot.write_png(&png_path).expect("write png capture");
    shot.write_svg(&svg_path).expect("write svg capture");
    vec![
        rel(&text_path),
        rel(&styled_path),
        rel(&png_path),
        rel(&svg_path),
    ]
}

fn rel(p: &Path) -> String {
    p.strip_prefix(Path::new(env!("CARGO_MANIFEST_DIR")))
        .unwrap_or(p)
        .display()
        .to_string()
}

/// `docs/captures/README.md`: what exists, how it was made, how to
/// regenerate — the docs cycle's index into this material. Lists the
/// directory contents so partial regenerations keep the index whole.
fn write_manifest(out: &Path) {
    let mut names: Vec<String> = fs::read_dir(out)
        .map(|it| {
            it.filter_map(|e| e.ok())
                .map(|e| e.file_name().to_string_lossy().into_owned())
                .filter(|n| n != "README.md")
                .collect()
        })
        .unwrap_or_default();
    names.sort();
    let mut md = String::new();
    md.push_str("# Captures\n\n");
    md.push_str(
        "Deterministic text \"screenshots\" of the shipped examples, generated by\n\
         `cargo build --examples && cargo run --example capture`. Each shot has a\n\
         plain render (`.txt`), a styled dump (`.styled.txt`: text plus style\n\
         runs), and a rendered `.svg` (the `Screenshot::to_svg` exporter —\n\
         GitHub-renderable). `themes-table.md` lists every registered theme's\n\
         token values.\n\n\
         Sizes and demo data are fixed; wall-clock frame pacing may shift animated\n\
         data by a tick between regenerations — regenerate deliberately, diff by eye.\n\
         The app-surface stills (`transcript-stream`, `select-open`, `code-diff`,\n\
         `feed-scrolled`, `reader-table`) render in-process with scripted input and\n\
         no clocks — those five are byte-deterministic.\n\n",
    );
    md.push_str("| artifact |\n|---|\n");
    for name in names {
        md.push_str(&format!("| `{name}` |\n"));
    }
    fs::write(out.join("README.md"), md).expect("write captures README");
}