eger 1.2.0

A high-level, parallel ASCII-art media pipeline built on top of iascii: images, video, GIFs, dithering, animated text/banners, and procedural illusions, all rendered to ANSI.
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
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
//! Output targets for rendered ASCII art: stdout, a file, an owned `String`,
//! or a `Vec<String>` — plus terminal playback for frame sequences.

#[cfg(feature = "video")]
use crate::error::EgerError;
use crate::error::Result;
use crate::fast_ansi;
use iascii::grid::Grid;
use iascii::render::ColorDepth;
use std::io::Write;
use std::path::PathBuf;
#[cfg(feature = "video")]
use std::time::Duration;
#[cfg(feature = "video")]
use tokio::io::AsyncWriteExt;

/// Where a rendered frame/image should be delivered.
#[derive(Debug, Clone)]
pub enum RenderTarget {
    Stdout,
    File(PathBuf),
    String,
    Lines,
}

/// The materialized result of a render, mirroring [`RenderTarget`].
#[derive(Debug)]
pub enum RenderOutput {
    Displayed,
    Written(PathBuf),
    Text(String),
    Lines(Vec<String>),
}

/// Renders a completed `Grid` to a string.
pub fn grid_to_string(grid: &Grid, depth: Option<ColorDepth>) -> String {
    match depth {
        Some(depth) => fast_ansi::render_ansi_fast(grid, depth),
        None => plain_string(grid),
    }
}

/// Renders a `Grid` without any color escape codes.
pub fn plain_string(grid: &Grid) -> String {
    let mut out = String::with_capacity((grid.width() as usize + 1) * grid.height() as usize);
    for row in grid.rows() {
        for cell in row {
            out.push(cell.ch);
        }
        out.push('\n');
    }
    out
}

/// Renders a `Grid` into one `String` per row.
pub fn grid_to_lines(grid: &Grid, depth: Option<ColorDepth>) -> Vec<String> {
    match depth {
        None => grid
            .rows()
            .map(|row| row.iter().map(|cell| cell.ch).collect())
            .collect(),
        Some(depth) => fast_ansi::render_ansi_fast_lines(grid, depth),
    }
}

/// Picks a [`ColorDepth`] appropriate for the current environment.
pub fn detect_render_depth() -> Option<ColorDepth> {
    use std::io::IsTerminal;
    detect_render_depth_from(
        std::env::var_os("NO_COLOR").is_some(),
        std::env::var("COLORTERM").ok(),
        std::env::var("TERM").ok(),
        std::io::stdout().is_terminal(),
    )
}

fn detect_render_depth_from(
    no_color: bool,
    colorterm: Option<String>,
    term: Option<String>,
    is_tty: bool,
) -> Option<ColorDepth> {
    if no_color || !is_tty {
        return None;
    }
    if term.as_deref() == Some("dumb") {
        return None;
    }
    if colorterm
        .as_deref()
        .is_some_and(|c| c == "truecolor" || c == "24bit")
    {
        return Some(ColorDepth::TrueColor);
    }
    if term.as_deref().is_some_and(|t| t.contains("256color")) {
        return Some(ColorDepth::Ansi256);
    }
    Some(ColorDepth::Ansi16)
}

/// Queries the current terminal's size in columns/rows, if stdout is
/// attached to one. Returns `None` when output is piped/redirected or the
/// size can't be determined (e.g. no controlling terminal, as in most CI
/// environments).
///
/// Backed by the `terminal_size` crate (`terminal_size::terminal_size`),
/// which reads the size via the platform's own mechanism (`ioctl(TIOCGWINSZ)`
/// on Unix, the console API on Windows) rather than environment variables,
/// so it stays correct across resizes without needing `SIGWINCH` handling.
pub fn terminal_size() -> Option<(u16, u16)> {
    terminal_size::terminal_size().map(|(terminal_size::Width(w), terminal_size::Height(h))| (w, h))
}

/// Controls how finely [`diff_frame`] repaints one frame over another.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DiffGranularity {
    /// Redraw an entire line whenever any byte in it changed, after
    /// comparing lines byte-wise (a whole-frame `memcmp`, ~150 µs for a
    /// large frame). Always correct — an entire line is self-contained —
    /// and cheap in CPU regardless of how colored the frame is. The right
    /// default for **dense** frames (video/GIF, where nearly every cell
    /// carries its own color escape and most rows change anyway).
    Line,
    /// Redraw only the character cells that changed within a line,
    /// located by parsing both lines into (glyph, color) cells and
    /// re-emitting the changed spans with fresh, well-formed SGR escapes.
    /// Correct for SGR-colored frames (what every renderer in this crate
    /// emits) — a color-only change re-emits whole escapes instead of
    /// slicing them in half — and emits the fewest bytes when damage is
    /// **sparse** (a HUD updating, a sprite moving). Parsing costs
    /// ~180 ns per changed cell, so prefer [`DiffGranularity::Line`] for
    /// dense full-frame color (a 4K-grid frame is ~65k cells per frame).
    /// Assumes one glyph = one terminal column (true for the built-in
    /// Latin/block/Braille/shade ramps; use [`DiffGranularity::Line`] for
    /// double-width script ramps or foreign escape sequences).
    Cell,
}

/// Computes the minimal set of cursor-addressed writes needed to repaint
/// `next` over a terminal currently showing `prev`, instead of clearing and
/// redrawing the whole frame (as `play_terminal`/[`dispatch`]'s `Stdout`
/// target and `video::play_video` do). Returns an empty string
/// when the two frames are identical.
///
/// Both frames are compared line by line (via `str::lines`); see
/// [`DiffGranularity`] for the tradeoff between the two granularities this
/// accepts.
pub fn diff_frame(prev: &str, next: &str, granularity: DiffGranularity) -> String {
    let mut out = String::new();
    diff_frame_into(prev, next, granularity, &mut out);
    out
}

/// [`diff_frame`] appending into a caller-owned buffer — the zero-allocation
/// form for frame loops: `buf.clear(); diff_frame_into(prev, next, g, &mut buf)`.
pub fn diff_frame_into(prev: &str, next: &str, granularity: DiffGranularity, out: &mut String) {
    let prev_lines: Vec<&str> = prev.lines().collect();
    let next_lines: Vec<&str> = next.lines().collect();
    let max_lines = prev_lines.len().max(next_lines.len());

    // Cell-granularity scratch space, allocated once and reused for every
    // row of the frame.
    let mut prev_cells: Vec<fast_ansi::ParsedCell> = Vec::new();
    let mut next_cells: Vec<fast_ansi::ParsedCell> = Vec::new();

    for row in 0..max_lines {
        let prev_line = prev_lines.get(row).copied().unwrap_or("");
        let next_line = next_lines.get(row).copied().unwrap_or("");
        if prev_line == next_line {
            continue;
        }
        match granularity {
            DiffGranularity::Line => {
                // \x1B[<row>;1H moves the cursor to the start of the row
                // (1-based); \x1B[K clears from the cursor to end-of-line
                // first so a next_line shorter than prev_line doesn't leave
                // stale trailing characters behind.
                use std::fmt::Write as _;
                let _ = write!(out, "\x1B[{};1H\x1B[K{next_line}", row + 1);
            }
            DiffGranularity::Cell => {
                fast_ansi::parse_sgr_cells(prev_line, &mut prev_cells);
                fast_ansi::parse_sgr_cells(next_line, &mut next_cells);
                fast_ansi::diff_cells_into(out, row + 1, &prev_cells, &next_cells);
            }
        }
    }
}

/// Deadline-based frame pacer for playback loops: sleeps until the next
/// frame deadline instead of sleeping a fixed delay *after* each frame's
/// work. Sleeping after the work makes the real frame interval `decode +
/// render + sleep`, so playback silently runs slower than the requested
/// FPS; pacing to a deadline keeps the schedule absolute. When more than a
/// frame behind (a decode hitch), it resyncs to now instead of trying to
/// catch up — the standard anti-spiral guard.
#[cfg(feature = "video")]
pub(crate) struct FramePacer {
    next: tokio::time::Instant,
    step: Duration,
}

#[cfg(feature = "video")]
impl FramePacer {
    pub(crate) fn new(step: Duration) -> Self {
        Self {
            next: tokio::time::Instant::now() + step,
            step,
        }
    }

    /// Changes the frame interval (GIF playback carries a per-frame delay).
    pub(crate) fn set_step(&mut self, step: Duration) {
        self.step = step;
    }

    /// Waits until the next frame deadline and schedules the one after it.
    pub(crate) async fn wait(&mut self) {
        let now = tokio::time::Instant::now();
        if self.next + self.step < now {
            self.next = now; // >1 frame behind: drop the backlog
        }
        tokio::time::sleep_until(self.next).await;
        self.next += self.step;
    }
}

/// Plays back a sequence of already-rendered frames using cursor-addressed
/// diffing instead of [`play_terminal`]'s clear-and-redraw-every-frame
/// approach — much less flicker for animations where most of the frame is
/// unchanged between steps (a spinner, a status line, a slowly-panning
/// image). The first frame is always drawn in full; every frame after that
/// is patched in via [`diff_frame`].
///
/// Frames are paced to absolute deadlines (a deadline pacer, not a
/// sleep-after-work delay) so the requested
/// FPS doesn't drift by the render time, and the cursor is hidden for the
/// duration of playback.
#[cfg(feature = "video")]
pub async fn play_terminal_diffed(
    frames: &[String],
    fps: f64,
    granularity: DiffGranularity,
) -> Result<()> {
    if !(fps > 0.0) {
        return Err(EgerError::Render("fps must be positive".into()));
    }
    let Some((first, rest)) = frames.split_first() else {
        return Ok(());
    };

    let mut pacer = FramePacer::new(Duration::from_secs_f64(1.0 / fps));
    let mut stdout = tokio::io::stdout();
    stdout.write_all(b"\x1B[?25l\x1B[H\x1B[2J").await?;
    let result: Result<()> = async {
        stdout.write_all(first.as_bytes()).await?;
        stdout.flush().await?;
        pacer.wait().await;

        let mut prev = first;
        let mut patch = String::new();
        for next in rest {
            patch.clear();
            diff_frame_into(prev, next, granularity, &mut patch);
            if !patch.is_empty() {
                stdout.write_all(patch.as_bytes()).await?;
                stdout.flush().await?;
            }
            prev = next;
            pacer.wait().await;
        }
        Ok(())
    }
    .await;
    // Restore the cursor even if playback failed.
    let restore = stdout.write_all(b"\x1B[?25h").await;
    stdout.flush().await?;
    result?;
    restore?;
    Ok(())
}

/// Dispatches an already-rendered ANSI/plain string to `target` — the
/// string-based counterpart of [`dispatch`] for render paths that produce
/// their own text directly instead of going through a plain [`Grid`]
/// render, such as [`crate::dither::render_ansi_dithered`] or
/// [`crate::segment::render_segments`].
pub fn dispatch_text(target: &RenderTarget, text: String) -> Result<RenderOutput> {
    match target {
        RenderTarget::Stdout => {
            let mut stdout = std::io::stdout().lock();
            stdout.write_all(text.as_bytes())?;
            stdout.write_all(b"\n")?;
            Ok(RenderOutput::Displayed)
        }
        RenderTarget::File(path) => {
            std::fs::write(path, &text)?;
            Ok(RenderOutput::Written(path.clone()))
        }
        RenderTarget::String => Ok(RenderOutput::Text(text)),
        RenderTarget::Lines => Ok(RenderOutput::Lines(
            text.lines().map(str::to_owned).collect(),
        )),
    }
}

/// Dispatches a rendered `Grid` to `target`, synchronously.
pub fn dispatch(
    target: &RenderTarget,
    grid: &Grid,
    depth: Option<ColorDepth>,
) -> Result<RenderOutput> {
    match target {
        RenderTarget::Stdout => {
            let text = grid_to_string(grid, depth);
            let mut stdout = std::io::stdout().lock();
            stdout.write_all(text.as_bytes())?;
            stdout.write_all(b"\n")?;
            Ok(RenderOutput::Displayed)
        }
        RenderTarget::File(path) => {
            let text = grid_to_string(grid, depth);
            std::fs::write(path, &text)?;
            Ok(RenderOutput::Written(path.clone()))
        }
        RenderTarget::String => Ok(RenderOutput::Text(grid_to_string(grid, depth))),
        RenderTarget::Lines => Ok(RenderOutput::Lines(grid_to_lines(grid, depth))),
    }
}

/// Async counterpart of [`dispatch`].
#[cfg(feature = "video")]
pub async fn dispatch_async(
    target: &RenderTarget,
    grid: &Grid,
    depth: Option<ColorDepth>,
) -> Result<RenderOutput> {
    match target {
        RenderTarget::Stdout => {
            let text = grid_to_string(grid, depth);
            let mut stdout = tokio::io::stdout();
            stdout.write_all(text.as_bytes()).await?;
            stdout.write_all(b"\n").await?;
            stdout.flush().await?;
            Ok(RenderOutput::Displayed)
        }
        RenderTarget::File(path) => {
            let text = grid_to_string(grid, depth);
            tokio::fs::write(path, &text).await?;
            Ok(RenderOutput::Written(path.clone()))
        }
        RenderTarget::String => Ok(RenderOutput::Text(grid_to_string(grid, depth))),
        RenderTarget::Lines => Ok(RenderOutput::Lines(grid_to_lines(grid, depth))),
    }
}

/// Plays back a sequence of already-rendered ASCII frames in the terminal,
/// clearing and redrawing each frame in full (use [`play_terminal_diffed`]
/// to patch only what changed). Frames are paced to absolute deadlines and
/// the cursor is hidden for the duration.
#[cfg(feature = "video")]
pub async fn play_terminal(frames: &[String], fps: f64) -> Result<()> {
    if !(fps > 0.0) {
        return Err(EgerError::Render("fps must be positive".into()));
    }
    let mut pacer = FramePacer::new(Duration::from_secs_f64(1.0 / fps));
    let mut stdout = tokio::io::stdout();
    stdout.write_all(b"\x1B[?25l").await?;
    let result: Result<()> = async {
        for frame in frames {
            stdout.write_all(b"\x1B[H\x1B[2J").await?;
            stdout.write_all(frame.as_bytes()).await?;
            stdout.flush().await?;
            pacer.wait().await;
        }
        Ok(())
    }
    .await;
    let restore = stdout.write_all(b"\x1B[?25h").await;
    stdout.flush().await?;
    result?;
    restore?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use iascii::config::{ConfigBuilder as AsciiConfigBuilder, OutputSizing};
    use iascii::convert::convert_image;

    fn sample_grid() -> Grid {
        let ascii_config = AsciiConfigBuilder::new()
            .output_sizing(OutputSizing::Explicit {
                width: 2,
                height: 2,
            })
            .build()
            .expect("ascii config should build with defaults");

        #[rustfmt::skip]
        let pixels: [u8; 2 * 2 * 3] = [
            0, 0, 0,        255, 255, 255,
            255, 255, 255,  0, 0, 0,
        ];
        convert_image(2, 2, &pixels, &ascii_config)
            .expect("conversion of a valid buffer should succeed")
    }

    #[test]
    fn plain_string_has_no_escape_codes_and_expected_shape() {
        let grid = sample_grid();
        let s = plain_string(&grid);
        assert!(!s.contains('\x1b'));
        let lines: Vec<&str> = s.lines().collect();
        assert_eq!(lines.len(), grid.height() as usize);
        for line in &lines {
            assert_eq!(line.chars().count(), grid.width() as usize);
        }
    }

    #[test]
    fn checkerboard_pixels_map_to_two_distinct_characters() {
        let grid = sample_grid();
        let s = plain_string(&grid);
        let distinct: std::collections::HashSet<char> = s.chars().filter(|c| *c != '\n').collect();
        assert!(distinct.len() >= 2);
    }

    #[test]
    fn grid_to_lines_none_depth_matches_row_by_row_plain_reconstruction() {
        let grid = sample_grid();
        let expected: Vec<String> = plain_string(&grid).lines().map(str::to_owned).collect();
        assert_eq!(grid_to_lines(&grid, None), expected);
    }

    #[test]
    fn grid_to_lines_some_depth_splits_colored_output_by_row() {
        let grid = sample_grid();
        let lines = grid_to_lines(&grid, Some(ColorDepth::TrueColor));
        assert_eq!(lines.len(), grid.height() as usize);
        for line in &lines {
            assert!(line.contains('\x1b'));
        }
    }

    #[test]
    fn no_color_env_var_forces_plain_even_on_a_rich_terminal() {
        assert_eq!(
            detect_render_depth_from(
                true,
                Some("truecolor".into()),
                Some("xterm-256color".into()),
                true
            ),
            None
        );
    }

    #[test]
    fn non_terminal_stdout_forces_plain_regardless_of_env() {
        assert_eq!(
            detect_render_depth_from(
                false,
                Some("truecolor".into()),
                Some("xterm-256color".into()),
                false
            ),
            None
        );
    }

    #[test]
    fn dumb_terminal_forces_plain() {
        assert_eq!(
            detect_render_depth_from(false, None, Some("dumb".into()), true),
            None
        );
    }

    #[test]
    fn colorterm_truecolor_picked_over_lesser_term_signals() {
        assert_eq!(
            detect_render_depth_from(false, Some("truecolor".into()), Some("xterm".into()), true),
            Some(ColorDepth::TrueColor)
        );
    }

    #[test]
    fn term_256color_picked_when_colorterm_absent() {
        assert_eq!(
            detect_render_depth_from(false, None, Some("screen-256color".into()), true),
            Some(ColorDepth::Ansi256)
        );
    }

    #[test]
    fn falls_back_to_universally_supported_ansi16() {
        assert_eq!(
            detect_render_depth_from(false, None, Some("xterm".into()), true),
            Some(ColorDepth::Ansi16)
        );
    }

    #[test]
    fn diff_frame_is_empty_for_identical_frames() {
        let a = "line one\nline two\n";
        assert_eq!(diff_frame(a, a, DiffGranularity::Line), "");
        assert_eq!(diff_frame(a, a, DiffGranularity::Cell), "");
    }

    #[test]
    fn diff_frame_line_granularity_only_touches_changed_rows() {
        let prev = "same\nold\nsame";
        let next = "same\nnew\nsame";
        let patch = diff_frame(prev, next, DiffGranularity::Line);
        assert!(patch.contains("new"));
        assert!(!patch.contains("old"));
        // Only row 2 (1-based) should have been addressed.
        assert!(patch.contains("\x1B[2;1H"));
        assert!(!patch.contains("\x1B[1;1H"));
        assert!(!patch.contains("\x1B[3;1H"));
    }

    #[test]
    fn diff_frame_cell_granularity_only_rewrites_the_changed_span() {
        let prev = "abcXXXghi";
        let next = "abcYYYghi";
        let patch = diff_frame(prev, next, DiffGranularity::Cell);
        assert!(patch.contains("YYY"));
        // The unchanged prefix/suffix characters should not be re-sent.
        assert!(!patch.contains("abcYYY"));
        assert!(!patch.contains("YYYghi"));
    }

    #[test]
    fn diff_frame_cell_granularity_clears_a_shrunk_line_tail() {
        let prev = "hello world";
        let next = "hello";
        let patch = diff_frame(prev, next, DiffGranularity::Cell);
        // Should clear starting right after "hello" (column 6).
        assert!(patch.contains("\x1B[1;6H\x1B[K"));
    }

    #[test]
    fn diff_frame_handles_frames_with_different_line_counts() {
        let prev = "a\nb\nc";
        let next = "a\nb";
        let patch = diff_frame(prev, next, DiffGranularity::Line);
        // Row 3 existed in prev but not next; next_line is "" there, so it
        // should be cleared via the line-granularity path.
        assert!(patch.contains("\x1B[3;1H\x1B[K"));
    }

    #[test]
    fn diff_frame_cell_granularity_survives_a_color_only_change() {
        // The raw bytes differ *inside* the escape sequence; byte-level
        // diffing would emit a fragment like "0;255;0m" as visible text.
        let prev = "\x1b[38;2;255;0;0mAB\x1b[0m\n";
        let next = "\x1b[38;2;0;255;0mAB\x1b[0m\n";
        let patch = diff_frame(prev, next, DiffGranularity::Cell);
        assert!(
            patch.contains("\x1b[38;2;0;255;0mAB"),
            "whole escape re-emitted: {patch:?}"
        );
        let residue = patch.replace("\x1b[38;2;0;255;0m", "");
        assert!(
            !residue.contains('8'),
            "no escape fragment leaked: {patch:?}"
        );
    }

    #[test]
    fn diff_frame_cell_granularity_shrinks_a_colored_row_to_a_patch() {
        let prev = "\x1b[38;2;1;2;3m..hello world\x1b[0m\n";
        let next = "\x1b[38;2;1;2;3m..hello\x1b[0m\n";
        let patch = diff_frame(prev, next, DiffGranularity::Cell);
        // Only the removed tail is cleared; the shared prefix isn't re-sent.
        assert!(patch.contains("\x1B[K"), "{patch:?}");
        assert!(
            !patch.contains("hello"),
            "prefix must not be re-sent: {patch:?}"
        );
    }

    #[test]
    fn diff_frame_into_matches_the_allocating_variant() {
        let prev = "same\n\x1b[31mold\x1b[0m\nsame\n";
        let next = "same\n\x1b[32mnew\x1b[0m\nsame\n";
        for g in [DiffGranularity::Line, DiffGranularity::Cell] {
            let mut buf = String::from("PREFIX");
            diff_frame_into(prev, next, g, &mut buf);
            assert_eq!(buf, format!("PREFIX{}", diff_frame(prev, next, g)));
        }
    }

    #[test]
    fn diff_frame_cell_granularity_recolors_a_single_dirty_cell() {
        // One ASCII cell changed in a colored row: single span, one move.
        let prev = "\x1b[38;5;9mabcdef\x1b[0m\n";
        let next = "\x1b[38;5;9mabcdXf\x1b[0m\n";
        let patch = diff_frame(prev, next, DiffGranularity::Cell);
        assert_eq!(patch.matches("\x1B[1;").count(), 1, "{patch:?}");
        assert!(patch.contains("X\x1b[0m"), "{patch:?}");
    }

    #[test]
    fn terminal_size_does_not_panic_without_a_real_terminal() {
        // In a headless test runner stdout usually isn't a TTY, so this
        // should return None rather than erroring.
        let _ = terminal_size();
    }

    #[test]
    fn dispatch_file_target_writes_and_returns_path() {
        let mut path = std::env::temp_dir();
        path.push(format!("eger-render-test-{}.txt", std::process::id()));
        let grid = sample_grid();

        let out = dispatch(&RenderTarget::File(path.clone()), &grid, None).unwrap();
        match out {
            RenderOutput::Written(p) => assert_eq!(p, path),
            other => panic!("expected Written, got {other:?}"),
        }
        std::fs::remove_file(&path).ok();
    }
}