termproof 0.4.1

Evidence-first verification for TUI and terminal applications: recipe model, schema, steps, assertions, orchestration, terminal sessions and the evidence pipeline
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
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
//! A terminal screen with per-cell attributes, and SVG rendering.
//!
//! [`TerminalScreen`](crate::terminal::screen::TerminalScreen) answers "what text is on
//! screen". This answers "what does the screen *look* like": every cell with
//! its foreground, background, bold, italic, underline, reverse and display
//! width, plus a renderer that turns that into SVG.
//!
//! # Why attributes are worth carrying
//!
//! Evidence is the point of this crate, and a monochrome transcript is weak
//! evidence. A recipe asserting that an error rendered in red, or that the
//! selected row was highlighted, has nothing to point at without this. It is
//! also what lets two screens with identical text but a different highlight be
//! recognised as *different* screens — see
//! [`AttributedScreen::render_fingerprint`].
//!
//! # Sources
//!
//! - [`TerminalScreen::attributed`](crate::terminal::screen::TerminalScreen::attributed)
//!   — bytes fed to a parser this crate owns. The usual path, and the only
//!   public one that goes through `vt100`.
//! - [`attributed_screen_from_ansi_text`] — a captured string that still has
//!   its escape sequences, e.g. `tmux capture-pane -e`.
//! - [`attributed_screen_from_text`] — plain text, rendered in default colours.
//!
//! `from_vt100`, which took a caller's own live `vt100::Screen`, was public
//! until 0.4.0 and is now crate-internal. There is no public replacement that
//! takes one: a caller holding its own parser has to replay the bytes through
//! `TerminalScreen`. That is a real capability removed, and the reason is in
//! the note on the function.
//!
//! # One fidelity gap, stated plainly
//!
//! `vt100` does not model strikethrough, so [`AttributedCell::strikethrough`]
//! is always `false` on the `from_vt100` path. The ANSI-text path parses
//! SGR 9 and does set it. The field is kept rather than removed because the
//! SVG renderer honours it and the ANSI path produces it.
//!
//! Dim *is* modelled, from `vt100` 0.16 onwards. Note that `vt100` treats
//! SGR 1 and SGR 2 as one three-valued intensity, so bold and dim are mutually
//! exclusive on the `from_vt100` path; the ANSI-text path carries them as
//! independent flags, as `tmux` emits them.
//!
//! # Both paths must measure width with one table
//!
//! `from_vt100` inherits whatever column layout `vt100` chose, and the
//! ANSI-text path re-derives it with [`cell_width`]. If those two consult
//! different `unicode-width` majors they disagree about real code points —
//! U+1FA89 is one column under 0.1 and two under 0.2, and 458 code points
//! differ in total. The same byte then lands in a different column depending
//! on which path read it, which moves glyphs in the SVG and changes
//! [`AttributedScreen::render_fingerprint`], so evidence dedup stops
//! recognising two identical screens as identical.
//!
//! The workspace therefore pins `unicode-width` to the major `vt100` depends
//! on, and that pin carries a comment saying so. `evidence::cast_video` is the
//! one place this cannot be enforced: it replays through `avt`, which brings
//! its own table. See `cell_from_avt` there.

use std::sync::OnceLock;

use serde::Serialize;
use sha2::Digest;
use sha2::Sha256;
use unicode_normalization::char::canonical_combining_class;
use unicode_normalization::UnicodeNormalization;
use unicode_width::UnicodeWidthChar;

/// Default grid width, in columns.
pub const DEFAULT_COLUMNS: usize = 120;
/// Default grid height, in rows.
pub const DEFAULT_ROWS: usize = 40;
/// Cell width in SVG units. With [`DEFAULT_CELL_H`] this gives a ~1:2.2 cell,
/// which is the aspect a real terminal font has.
pub const DEFAULT_CELL_W: f64 = 10.0;
/// Cell height in SVG units. See [`DEFAULT_CELL_W`].
pub const DEFAULT_CELL_H: f64 = 22.0;
/// Font size in SVG units.
pub const DEFAULT_FONT_PX: u32 = 16;
/// Margin around the grid, in SVG units.
pub const DEFAULT_PADDING: u32 = 10;
/// Linux-first monospace stack; the boxes render on a CI host that has
/// neither Menlo nor Consolas, so naming them first just wastes a lookup.
pub const FONT_STACK: &str = "Noto Sans Mono, Liberation Mono, monospace";
/// Foreground used for a cell with no explicit colour.
pub const DEFAULT_FG: &str = "#e6edf3";
/// Background used for a cell with no explicit colour, and for the page.
pub const DEFAULT_BG: &str = "#0b0f14";

/// Named palette entries, tuned to read against [`DEFAULT_BG`].
const COLORS: [(&str, &str); 16] = [
    ("black", "#0b0f14"),
    ("red", "#ff7b72"),
    ("green", "#7ee787"),
    ("brown", "#d29922"),
    ("blue", "#79c0ff"),
    ("magenta", "#d2a8ff"),
    ("cyan", "#56d4dd"),
    ("white", "#e6edf3"),
    ("brightblack", "#6e7681"),
    ("brightred", "#ffa198"),
    ("brightgreen", "#aff5b4"),
    ("brightbrown", "#f2cc60"),
    ("brightblue", "#a5d6ff"),
    ("brightmagenta", "#d2a8ff"),
    ("brightcyan", "#79c0ff"),
    ("brightwhite", "#ffffff"),
];

/// SGR code -> palette name, for the 8 standard and 8 bright foregrounds.
fn ansi_fg(code: u16) -> Option<&'static str> {
    let name = match code {
        30 => "black",
        31 => "red",
        32 => "green",
        33 => "brown",
        34 => "blue",
        35 => "magenta",
        36 => "cyan",
        37 => "white",
        90 => "brightblack",
        91 => "brightred",
        92 => "brightgreen",
        93 => "brightbrown",
        94 => "brightblue",
        95 => "brightmagenta",
        96 => "brightcyan",
        97 => "brightwhite",
        _ => return None,
    };
    Some(name)
}

/// SGR code -> palette name, for the 8 standard and 8 bright backgrounds.
fn ansi_bg(code: u16) -> Option<&'static str> {
    match code {
        40..=47 => ansi_fg(code - 10),
        100..=107 => ansi_fg(code - 10),
        _ => None,
    }
}

const XTERM_256_BASE: [&str; 16] = [
    "000000", "cd0000", "00cd00", "cdcd00", "0000ee", "cd00cd", "00cdcd", "e5e5e5", "7f7f7f",
    "ff0000", "00ff00", "ffff00", "5c5cff", "ff00ff", "00ffff", "ffffff",
];

fn xterm_256_colors() -> &'static [String] {
    static COLORS_256: OnceLock<Vec<String>> = OnceLock::new();
    COLORS_256.get_or_init(|| {
        let mut colors: Vec<String> = XTERM_256_BASE.iter().map(|s| (*s).to_string()).collect();
        const LEVELS: [u32; 6] = [0x00, 0x5F, 0x87, 0xAF, 0xD7, 0xFF];
        for red in LEVELS {
            for green in LEVELS {
                for blue in LEVELS {
                    colors.push(format!("{:02x}{:02x}{:02x}", red, green, blue));
                }
            }
        }
        for index in 0..24 {
            let value = 8 + index * 10;
            colors.push(format!("{:02x}{:02x}{:02x}", value, value, value));
        }
        colors
    })
}

/// Mutable SGR state, carried across a `capture-pane` line boundary because a
/// colour opened on one row stays open on the next.
#[derive(Debug, Clone, PartialEq, Eq)]
struct AnsiAttrs {
    fg: String,
    bg: String,
    bold: bool,
    dim: bool,
    italic: bool,
    underline: bool,
    strikethrough: bool,
    reverse: bool,
}

impl Default for AnsiAttrs {
    fn default() -> Self {
        AnsiAttrs {
            fg: "default".to_string(),
            bg: "default".to_string(),
            bold: false,
            dim: false,
            italic: false,
            underline: false,
            strikethrough: false,
            reverse: false,
        }
    }
}

impl AnsiAttrs {
    fn reset(&mut self) {
        *self = AnsiAttrs::default();
    }

    fn cell(&self, text: &str, width: u8) -> AttributedCell {
        AttributedCell {
            text: text.to_string(),
            fg: self.fg.clone(),
            bg: self.bg.clone(),
            bold: self.bold,
            dim: self.dim,
            italic: self.italic,
            underline: self.underline,
            strikethrough: self.strikethrough,
            reverse: self.reverse,
            width,
        }
    }
}

/// One terminal cell with its display attributes.
///
/// `fg`/`bg` hold the *unresolved* colour: `"default"`, a palette name such as
/// `"brightred"`, or a bare 6-digit hex string. [`cell_colors`] resolves them.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AttributedCell {
    /// The glyph in this cell; a single space when the cell is blank, and
    /// empty for the filler cell that follows a wide glyph.
    pub text: String,
    /// Unresolved foreground colour. See the type-level docs.
    pub fg: String,
    /// Unresolved background colour. See the type-level docs.
    pub bg: String,
    /// SGR 1.
    pub bold: bool,
    /// SGR 2.
    pub dim: bool,
    /// SGR 3.
    pub italic: bool,
    /// SGR 4.
    pub underline: bool,
    /// SGR 9. Always `false` on the `from_vt100` path; see the module docs.
    pub strikethrough: bool,
    /// SGR 7 — foreground and background swap when rendered.
    pub reverse: bool,
    /// Display columns: 2 for a wide glyph, 0 for the filler cell that follows
    /// it, 1 otherwise.
    pub width: u8,
}

impl Default for AttributedCell {
    fn default() -> Self {
        AttributedCell {
            text: " ".to_string(),
            fg: "default".to_string(),
            bg: "default".to_string(),
            bold: false,
            dim: false,
            italic: false,
            underline: false,
            strikethrough: false,
            reverse: false,
            width: 1,
        }
    }
}

impl AttributedCell {
    /// A plain cell holding `text`, with default attributes.
    pub fn plain(text: &str) -> Self {
        AttributedCell {
            text: text.to_string(),
            ..Default::default()
        }
    }
}

/// Serializes as a JSON array, matching the Python fingerprint payload.
#[derive(Serialize)]
struct CellFingerprint<'a>(
    &'a str,
    &'a str,
    &'a str,
    bool,
    bool,
    bool,
    bool,
    bool,
    bool,
    u8,
);

/// A rectangular terminal grid plus cursor metadata.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct AttributedScreen {
    /// Cells in row-major order. Rows are not required to be equal length;
    /// [`column_count`](Self::column_count) reports the widest.
    pub rows: Vec<Vec<AttributedCell>>,
    /// Zero-based cursor row.
    pub cursor_row: usize,
    /// Zero-based cursor column.
    pub cursor_column: usize,
    /// Whether the cursor is hidden (DECTCEM reset).
    pub cursor_hidden: bool,
}

impl AttributedScreen {
    /// Number of rows in the grid.
    pub fn row_count(&self) -> usize {
        self.rows.len()
    }

    /// Width of the widest row, in cells.
    pub fn column_count(&self) -> usize {
        self.rows.iter().map(|r| r.len()).max().unwrap_or(0)
    }

    /// The grid as one string per row, dropping attributes.
    ///
    /// `trim_right` strips trailing whitespace from each line, which is what
    /// you want when comparing against expected text: a terminal pads every
    /// row out to the full width.
    pub fn text_lines(&self, trim_right: bool) -> Vec<String> {
        self.rows
            .iter()
            .map(|row| {
                let line: String = row
                    .iter()
                    .filter(|c| c.width > 0)
                    .map(|c| c.text.as_str())
                    .collect();
                if trim_right {
                    line.trim_end().to_string()
                } else {
                    line
                }
            })
            .collect()
    }

    /// [`text_lines`](Self::text_lines) joined with newlines.
    pub fn to_text(&self, trim_right: bool) -> String {
        self.text_lines(trim_right).join("\n")
    }

    /// A digest of every cell *including its attributes*.
    ///
    /// Evidence uses this to skip re-rendering a step whose screen is identical
    /// to the previous one. Attributes are part of the payload because two
    /// screens with the same text but a different highlight are different
    /// screenshots.
    pub fn render_fingerprint(&self) -> String {
        let payload: Vec<Vec<CellFingerprint<'_>>> = self
            .rows
            .iter()
            .map(|row| {
                row.iter()
                    .map(|c| {
                        CellFingerprint(
                            &c.text,
                            &c.fg,
                            &c.bg,
                            c.bold,
                            c.dim,
                            c.italic,
                            c.underline,
                            c.strikethrough,
                            c.reverse,
                            c.width,
                        )
                    })
                    .collect()
            })
            .collect();
        let encoded = serde_json::to_string(&payload).unwrap_or_default();
        format!("{:x}", Sha256::digest(encoded.as_bytes()))
    }
}

/// A screen from plain text lines, with default attributes throughout.
///
/// Characters are laid out by the same rules as
/// [`attributed_screen_from_ansi_text`] — display width, wide-glyph filler,
/// combining marks, tab stops — so the two constructors put the same glyph in
/// the same column. Only the attributes differ, because plain text carries
/// none. Escape sequences are *not* interpreted here: this is verbatim text,
/// and an escape in it occupies cells like any other character.
pub fn attributed_screen_from_lines(
    lines: &[&str],
    columns: usize,
    rows: usize,
) -> AttributedScreen {
    let screen_rows = lines
        .iter()
        .take(rows)
        .map(|line| cells_from_plain_line(line, columns))
        .collect();
    AttributedScreen {
        rows: screen_rows,
        ..Default::default()
    }
}

/// A screen from a plain-text blob, with default attributes throughout.
pub fn attributed_screen_from_text(
    screen_text: &str,
    columns: usize,
    rows: usize,
) -> AttributedScreen {
    let lines: Vec<&str> = screen_text.lines().collect();
    attributed_screen_from_lines(&lines, columns, rows)
}

/// A screen from `tmux capture-pane -e` output: laid-out text plus SGR escapes.
pub fn attributed_screen_from_ansi_text(
    ansi_text: &str,
    columns: usize,
    rows: usize,
) -> AttributedScreen {
    let mut attrs = AnsiAttrs::default();
    let mut lines: Vec<&str> = ansi_text.split('\n').collect();
    if lines.last() == Some(&"") {
        lines.pop();
    }
    let screen_rows = lines
        .iter()
        .take(rows)
        .map(|line| cells_from_ansi_line(line.trim_end_matches('\r'), &mut attrs, columns))
        .collect();
    AttributedScreen {
        rows: screen_rows,
        ..Default::default()
    }
}

/// Build an attributed screen from a live `vt100` screen.
///
/// The usual path: a session feeds bytes to `vt100`, and this reads the grid
/// back out with attributes intact.
///
/// Crate-internal since 0.4.0, because [`vt100::Screen`] is a third-party type
/// in an *argument* position: a `Screen` from a consumer's own `vt100` was only
/// accepted here when cargo handed both sides one copy, which made the `vt100`
/// requirement a source-compatibility surface.
///
/// Unlike a return type this could not be wrapped, because the caller is what
/// builds the argument. **So the capability was removed, not relocated.** A
/// caller that already holds a live `vt100::Screen` has no public way to turn
/// it into an [`AttributedScreen`]; it has to replay the bytes through
/// [`TerminalScreen`](crate::terminal::screen::TerminalScreen), which owns its
/// own parser, and pay for the second parse. For text rather than a live parser
/// there are still [`attributed_screen_from_text`] and
/// [`attributed_screen_from_ansi_text`], which never had the problem.
///
/// Keeping it public would have meant keeping the `vt100` requirement in the
/// API for the one caller shape that supplies its own parser. That trade went
/// the other way. See "Dependencies in the public API" in the crate docs
/// (#177).
pub(crate) fn from_vt100(screen: &vt100::Screen) -> AttributedScreen {
    let (rows, cols) = screen.size();
    let grid = (0..rows)
        .map(|row| {
            (0..cols)
                .map(|col| match screen.cell(row, col) {
                    Some(cell) => cell_from_vt100(cell),
                    None => AttributedCell::default(),
                })
                .collect()
        })
        .collect();
    let (cursor_row, cursor_column) = screen.cursor_position();
    AttributedScreen {
        rows: grid,
        cursor_row: cursor_row as usize,
        cursor_column: cursor_column as usize,
        cursor_hidden: screen.hide_cursor(),
    }
}

fn cell_from_vt100(cell: &vt100::Cell) -> AttributedCell {
    // A wide glyph occupies two columns; the second is a continuation that
    // carries no text of its own, matching what the SGR parser produces.
    let width: u8 = if cell.is_wide_continuation() {
        0
    } else if cell.is_wide() {
        2
    } else {
        1
    };
    AttributedCell {
        text: if width == 0 {
            String::new()
        } else if cell.has_contents() {
            cell.contents().to_string()
        } else {
            " ".to_string()
        },
        fg: vt100_color(cell.fgcolor()),
        bg: vt100_color(cell.bgcolor()),
        bold: cell.bold(),
        dim: cell.dim(),
        italic: cell.italic(),
        underline: cell.underline(),
        // `vt100` does not model strikethrough; see the module docs.
        strikethrough: false,
        reverse: cell.inverse(),
        width,
    }
}

fn vt100_color(color: vt100::Color) -> String {
    match color {
        vt100::Color::Default => "default".to_string(),
        vt100::Color::Idx(index) => palette_color(index as u16),
        vt100::Color::Rgb(r, g, b) => rgb_color(r, g, b),
    }
}

/// Name a palette index: the first 16 are named colours, the rest are hex.
///
/// Public so a caller emulating with something other than `vt100` can build
/// [`AttributedCell`]s without this crate taking a dependency on their
/// emulator. [`crate::terminal::attributed`] stays `vt100`-only for that reason.
pub fn palette_color(index: u16) -> String {
    if (index as usize) < COLORS.len() {
        COLORS[index as usize].0.to_string()
    } else {
        xterm_256_color(index)
    }
}

/// Format a true-colour triple the way [`AttributedCell::fg`] expects.
pub fn rgb_color(r: u8, g: u8, b: u8) -> String {
    format!("{r:02x}{g:02x}{b:02x}")
}

/// Resolve a cell's `(foreground, background)` to CSS colours.
pub fn cell_colors(cell: &AttributedCell) -> (String, String) {
    let fg = css_color(&cell.fg, DEFAULT_FG);
    let bg = css_color(&cell.bg, DEFAULT_BG);
    if cell.reverse {
        (bg, fg)
    } else {
        (fg, bg)
    }
}

/// Escape `&`, `<`, `>` for XML text content (mirrors `xml.sax.saxutils.escape`).
pub fn xml_escape(s: &str) -> String {
    s.replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
}

/// Canvas geometry for [`screen_svg`].
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct SvgMetrics {
    /// Grid width, in cells.
    pub columns: usize,
    /// Grid height, in cells.
    pub rows: usize,
    /// Cell width, in SVG units.
    pub cell_w: f64,
    /// Cell height, in SVG units.
    pub cell_h: f64,
    /// Font size, in SVG units.
    pub font_px: u32,
    /// Margin around the grid, in SVG units.
    pub padding: u32,
    /// Canvas width, in SVG units.
    ///
    /// Cached, not computed on read: mutating `columns`, `cell_w` or `padding`
    /// leaves this stale until [`recompute`](Self::recompute) is called. It is
    /// a field rather than a method so a caller can override the canvas —
    /// video encoders want a fixed frame size regardless of the grid.
    pub width: usize,
    /// Canvas height, in SVG units. Cached; see [`width`](Self::width).
    pub height: usize,
}

impl Default for SvgMetrics {
    fn default() -> Self {
        let mut metrics = SvgMetrics {
            columns: DEFAULT_COLUMNS,
            rows: DEFAULT_ROWS,
            cell_w: DEFAULT_CELL_W,
            cell_h: DEFAULT_CELL_H,
            font_px: DEFAULT_FONT_PX,
            padding: DEFAULT_PADDING,
            width: 0,
            height: 0,
        };
        metrics.recompute();
        metrics
    }
}

impl SvgMetrics {
    /// Recompute the cached [`width`](Self::width) and [`height`](Self::height)
    /// from the grid and cell metrics.
    ///
    /// Call this after changing `columns`, `rows`, `cell_w`, `cell_h` or
    /// `padding` — including after a `..Default::default()` struct update,
    /// which copies the *default* canvas rather than deriving a new one.
    pub fn recompute(&mut self) {
        self.width = self.derived_width();
        self.height = self.derived_height();
    }

    /// Canvas width implied by the grid and cell metrics.
    pub fn derived_width(&self) -> usize {
        (self.columns as f64 * self.cell_w) as usize + 2 * self.padding as usize
    }

    /// Canvas height implied by the grid and cell metrics.
    pub fn derived_height(&self) -> usize {
        (self.rows as f64 * self.cell_h) as usize + 2 * self.padding as usize
    }
}

/// Render `screen` as an SVG document.
///
/// One `<text>` per cell at `x = column * cell_w`, so a glyph's column is
/// structural rather than dependent on whatever font fontconfig resolves. The
/// previous whole-line `<tspan>` approach let a single substituted glyph shift
/// the rest of the row, which is exactly the fidelity a reviewer is looking at.
pub fn screen_svg(screen: &AttributedScreen, metrics: &SvgMetrics) -> String {
    let mut backgrounds = String::new();
    let mut glyphs = String::new();
    let baseline = metrics.cell_h * 0.72;

    for (r, row) in screen.rows.iter().take(metrics.rows).enumerate() {
        for (c, cell) in row.iter().take(metrics.columns).enumerate() {
            // The filler behind a wide glyph paints nothing of its own.
            if cell.width == 0 {
                continue;
            }
            let (fg, bg) = cell_colors(cell);
            let x = metrics.padding as f64 + c as f64 * metrics.cell_w;
            let y = metrics.padding as f64 + r as f64 * metrics.cell_h;
            // The page already has the default background painted under it.
            if bg != DEFAULT_BG {
                backgrounds.push_str(&format!(
                    "<rect x=\"{:.1}\" y=\"{:.1}\" width=\"{:.1}\" height=\"{:.1}\" fill=\"{}\"/>",
                    x,
                    y,
                    metrics.cell_w * cell.width.max(1) as f64,
                    metrics.cell_h,
                    bg,
                ));
            }
            let text = printable(&cell.text);
            if text == " " || text.is_empty() {
                continue;
            }
            glyphs.push_str(&glyph_svg(cell, &text, x, y + baseline, &fg));
        }
    }

    format!(
        "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"{w}\" height=\"{h}\" \
viewBox=\"0 0 {w} {h}\"><rect width=\"100%\" height=\"100%\" fill=\"{page_bg}\"/>\
{backgrounds}<g font-family=\"{font}\" font-size=\"{font_px}\" \
xml:space=\"preserve\">{glyphs}</g></svg>",
        w = metrics.width,
        h = metrics.height,
        page_bg = DEFAULT_BG,
        font = FONT_STACK,
        font_px = metrics.font_px,
    )
}

fn glyph_svg(cell: &AttributedCell, text: &str, x: f64, y: f64, fg: &str) -> String {
    let mut attrs = format!("x=\"{:.1}\" y=\"{:.1}\" fill=\"{}\"", x, y, fg);
    if cell.bold {
        attrs.push_str(" font-weight=\"700\"");
    }
    if cell.italic {
        attrs.push_str(" font-style=\"italic\"");
    }
    let mut decorations: Vec<&str> = Vec::new();
    if cell.underline {
        decorations.push("underline");
    }
    if cell.strikethrough {
        decorations.push("line-through");
    }
    if !decorations.is_empty() {
        attrs.push_str(&format!(" text-decoration=\"{}\"", decorations.join(" ")));
    }
    if cell.dim {
        attrs.push_str(" opacity=\"0.65\"");
    }
    format!("<text {}>{}</text>", attrs, xml_escape(text))
}

/// Cell text with everything an XML document cannot carry removed.
///
/// A control character is not a valid XML character at all, and one of them
/// makes `rsvg-convert` reject the whole file — which surfaces as a zero-byte
/// PNG rather than as an error, so a run produces a directory of empty
/// screenshots and says nothing about it.
///
/// A cell should never hold one: `vt100` consumes control bytes rather than
/// storing them. But [`attributed_screen_from_text`] builds a grid straight
/// from a string, escapes and all, and a caller emulating with something other
/// than `vt100` builds [`AttributedCell`]s by hand. The guarantee is therefore
/// enforced here, at the document boundary, where nothing can route around it.
fn printable(text: &str) -> String {
    text.chars().filter(|c| !c.is_control()).collect()
}

// -- Internals ---------------------------------------------------------------

fn cells_from_ansi_line(line: &str, attrs: &mut AnsiAttrs, columns: usize) -> Vec<AttributedCell> {
    // Indexed by character, not byte: the escape grammar is ASCII but the text
    // around it is not.
    let chars: Vec<char> = line.chars().collect();
    let mut cells: Vec<AttributedCell> = Vec::new();
    let mut index = 0;
    while index < chars.len() && cells.len() < columns {
        if chars[index] == '\x1b' {
            index = consume_ansi_sequence(&chars, index, attrs);
            continue;
        }
        push_char(&mut cells, chars[index], attrs, columns);
        index += 1;
    }
    cells
}

/// The same line, with no escape grammar: every character is content.
fn cells_from_plain_line(line: &str, columns: usize) -> Vec<AttributedCell> {
    let attrs = AnsiAttrs::default();
    let mut cells: Vec<AttributedCell> = Vec::new();
    for ch in line.chars() {
        if cells.len() >= columns {
            break;
        }
        push_char(&mut cells, ch, &attrs, columns);
    }
    cells
}

/// Place one character on the grid.
///
/// The layout rules live here, in one place, because both constructors have to
/// agree on them: a wide glyph that occupies two columns on the ANSI path and
/// one on the plain-text path means the same screen renders differently
/// depending on which transport captured it, which is the whole thing
/// `evidence::render` and `evidence::screenshot` sharing a renderer is meant to
/// rule out.
fn push_char(cells: &mut Vec<AttributedCell>, ch: char, attrs: &AnsiAttrs, columns: usize) {
    if ch == '\t' {
        append_tab(cells, attrs, columns);
        return;
    }
    if canonical_combining_class(ch) != 0 && !cells.is_empty() {
        let previous = cells.last_mut().expect("checked non-empty");
        previous.text = format!("{}{}", previous.text, ch).nfc().collect();
        return;
    }
    let width = cell_width(ch);
    cells.push(attrs.cell(&ch.to_string(), width));
    if width == 2 && cells.len() < columns {
        // Filler so the grid stays rectangular; skipped when reading text.
        cells.push(attrs.cell("", 0));
    }
}

/// Advance past the escape sequence at `index`, applying it if it is an SGR.
fn consume_ansi_sequence(chars: &[char], index: usize, attrs: &mut AnsiAttrs) -> usize {
    if index + 2 >= chars.len() || chars[index + 1] != '[' {
        return index + 1;
    }
    let mut end = index + 2;
    while end < chars.len() && !chars[end].is_alphabetic() {
        end += 1;
    }
    if end >= chars.len() {
        return index + 1;
    }
    if chars[end] == 'm' {
        let params: String = chars[index + 2..end].iter().collect();
        apply_sgr(&parse_sgr_params(&params), attrs);
    }
    end + 1
}

fn parse_sgr_params(params: &str) -> Vec<u16> {
    if params.is_empty() {
        return vec![0];
    }
    let parsed: Vec<u16> = params
        .split([';', ':'])
        .filter(|p| !p.is_empty())
        .filter_map(|p| p.parse::<u16>().ok())
        .collect();
    if parsed.is_empty() {
        vec![0]
    } else {
        parsed
    }
}

fn apply_sgr(params: &[u16], attrs: &mut AnsiAttrs) {
    let mut index = 0;
    while index < params.len() {
        let code = params[index];
        if let Some(name) = ansi_fg(code) {
            attrs.fg = name.to_string();
        } else if let Some(name) = ansi_bg(code) {
            attrs.bg = name.to_string();
        } else if code == 38 || code == 48 {
            index = apply_extended_color(params, index, attrs);
        } else {
            apply_basic_sgr(code, attrs);
        }
        index += 1;
    }
}

fn apply_basic_sgr(code: u16, attrs: &mut AnsiAttrs) {
    match code {
        0 => attrs.reset(),
        1 => attrs.bold = true,
        2 => attrs.dim = true,
        3 => attrs.italic = true,
        4 => attrs.underline = true,
        7 => attrs.reverse = true,
        9 => attrs.strikethrough = true,
        22 => {
            attrs.bold = false;
            attrs.dim = false;
        }
        23 => attrs.italic = false,
        24 => attrs.underline = false,
        27 => attrs.reverse = false,
        29 => attrs.strikethrough = false,
        39 => attrs.fg = "default".to_string(),
        49 => attrs.bg = "default".to_string(),
        _ => {}
    }
}

/// Apply a `38;…`/`48;…` extended colour and return the index of its last
/// consumed parameter (the caller advances one past).
fn apply_extended_color(params: &[u16], index: usize, attrs: &mut AnsiAttrs) -> usize {
    if index + 1 >= params.len() {
        return index;
    }
    let is_fg = params[index] == 38;
    let mode = params[index + 1];
    if mode == 5 && index + 2 < params.len() {
        let color = xterm_256_color(params[index + 2]);
        if is_fg {
            attrs.fg = color
        } else {
            attrs.bg = color
        }
        return index + 2;
    }
    if mode == 2 && index + 4 < params.len() {
        let color = format!(
            "{:02x}{:02x}{:02x}",
            params[index + 2].min(255),
            params[index + 3].min(255),
            params[index + 4].min(255),
        );
        if is_fg {
            attrs.fg = color
        } else {
            attrs.bg = color
        }
        return index + 4;
    }
    // Truncated sequence: not enough sub-parameters for the declared mode.
    // Consume the rest so the mode indicator is not reinterpreted as a fresh
    // top-level SGR code by the caller's loop.
    params.len() - 1
}

fn append_tab(cells: &mut Vec<AttributedCell>, attrs: &AnsiAttrs, columns: usize) {
    let target = (((cells.len() / 8) + 1) * 8).min(columns);
    while cells.len() < target {
        cells.push(attrs.cell(" ", 1));
    }
}

fn xterm_256_color(index: u16) -> String {
    xterm_256_colors()
        .get(index as usize)
        .cloned()
        .unwrap_or_else(|| "default".to_string())
}

/// Display columns for one character, from the same table `vt100` lays cells
/// out with.
///
/// "Same table" is a constraint, not a coincidence: the workspace pins
/// `unicode-width` to the major `vt100` depends on precisely so this agrees
/// with `from_vt100`. See the width-table note in the module docs for what
/// goes wrong when they drift.
fn cell_width(ch: char) -> u8 {
    match ch.width() {
        Some(2) => 2,
        _ => 1,
    }
}

fn css_color(value: &str, default: &str) -> String {
    if value == "default" {
        return default.to_string();
    }
    let lowered = value.to_lowercase();
    if let Some((_, hex)) = COLORS.iter().find(|(name, _)| *name == lowered) {
        return (*hex).to_string();
    }
    if value.len() == 6 && value.chars().all(|c| c.is_ascii_hexdigit()) {
        return format!("#{}", lowered);
    }
    default.to_string()
}

#[cfg(test)]
mod tests {
    use super::*;

    fn screen(ansi: &str) -> AttributedScreen {
        attributed_screen_from_ansi_text(ansi, DEFAULT_COLUMNS, DEFAULT_ROWS)
    }

    #[test]
    fn plain_text_keeps_default_attributes() {
        let s = screen("hi\n");
        assert_eq!(s.to_text(true), "hi");
        assert_eq!(s.rows[0][0], AttributedCell::plain("h"));
    }

    #[test]
    fn sgr_sets_named_foreground() {
        let s = screen("\x1b[31mred\x1b[0m!");
        assert_eq!(s.rows[0][0].fg, "red");
        assert_eq!(s.rows[0][3].fg, "default");
        assert_eq!(s.to_text(true), "red!");
    }

    #[test]
    fn sgr_sets_bright_background() {
        let s = screen("\x1b[103mx");
        assert_eq!(s.rows[0][0].bg, "brightbrown");
    }

    #[test]
    fn attributes_carry_across_lines() {
        // tmux closes a colour on the row it ends, not at the line break.
        let s = screen("\x1b[32mgreen\nstill");
        assert_eq!(s.rows[1][0].fg, "green");
    }

    #[test]
    fn style_codes_toggle() {
        let s = screen("\x1b[1;3;4;9;7mx\x1b[22;23;24;27;29my");
        let styled = &s.rows[0][0];
        assert!(styled.bold && styled.italic && styled.underline);
        assert!(styled.strikethrough && styled.reverse);
        let plain = &s.rows[0][1];
        assert!(!plain.bold && !plain.italic && !plain.underline);
        assert!(!plain.strikethrough && !plain.reverse);
        // 22 clears dim along with bold, and neither survives.
        assert!(!plain.dim);
    }

    #[test]
    fn xterm_256_indexed_color() {
        // 196 is the pure red of the 6x6x6 cube.
        let s = screen("\x1b[38;5;196mx");
        assert_eq!(s.rows[0][0].fg, "ff0000");
        assert_eq!(cell_colors(&s.rows[0][0]).0, "#ff0000");
    }

    #[test]
    fn xterm_256_grayscale_ramp_is_last() {
        assert_eq!(xterm_256_colors().len(), 256);
        assert_eq!(xterm_256_colors()[255], "eeeeee");
    }

    #[test]
    fn truecolor_rgb() {
        let s = screen("\x1b[48;2;1;2;3mx");
        assert_eq!(s.rows[0][0].bg, "010203");
    }

    #[test]
    fn truncated_extended_color_does_not_leak_into_next_code() {
        // "38;5" with no index: the 5 must not be read as a fresh SGR code, and
        // the 1 that follows must not turn the cell bold.
        let s = screen("\x1b[38;5mx");
        assert_eq!(s.rows[0][0].fg, "default");
        let s = screen("\x1b[48;2;9mx");
        assert_eq!(s.rows[0][0].bg, "default");
    }

    #[test]
    fn empty_sgr_params_reset() {
        let s = screen("\x1b[31ma\x1b[mb");
        assert_eq!(s.rows[0][0].fg, "red");
        assert_eq!(s.rows[0][1].fg, "default");
    }

    #[test]
    fn non_sgr_escapes_are_skipped_without_emitting_cells() {
        let s = screen("\x1b[2Kab");
        assert_eq!(s.to_text(true), "ab");
    }

    #[test]
    fn wide_char_gets_a_zero_width_filler() {
        let s = screen("\u{4f60}x");
        assert_eq!(s.rows[0][0].width, 2);
        assert_eq!(s.rows[0][1].width, 0);
        assert_eq!(s.rows[0][2].text, "x");
        // The filler is dropped when reading text back.
        assert_eq!(s.to_text(true), "\u{4f60}x");
    }

    #[test]
    fn combining_mark_merges_into_the_previous_cell() {
        let s = screen("e\u{0301}");
        assert_eq!(s.rows[0].len(), 1);
        assert_eq!(s.rows[0][0].text, "\u{00e9}");
    }

    #[test]
    fn tab_advances_to_the_next_eight_column_stop() {
        let s = screen("ab\tc");
        assert_eq!(s.rows[0].len(), 9);
        assert_eq!(s.rows[0][8].text, "c");
    }

    #[test]
    fn columns_and_rows_are_clipped() {
        let s = attributed_screen_from_ansi_text("abcdef\nghi\njkl", 3, 2);
        assert_eq!(s.row_count(), 2);
        assert_eq!(s.column_count(), 3);
        assert_eq!(s.to_text(false), "abc\nghi");
    }

    #[test]
    fn trailing_newline_does_not_add_a_row() {
        assert_eq!(screen("a\nb\n").row_count(), 2);
    }

    #[test]
    fn from_lines_has_no_attributes() {
        let s = attributed_screen_from_lines(&["ab", "c"], 10, 10);
        assert_eq!(s.to_text(false), "ab\nc");
        assert!(s.rows[0].iter().all(|c| c.fg == "default"));
    }

    #[test]
    fn from_text_splits_lines() {
        assert_eq!(
            attributed_screen_from_text("a\nb", 10, 10).to_text(false),
            "a\nb"
        );
    }

    #[test]
    fn trim_right_strips_padding() {
        let s = screen("hi   ");
        assert_eq!(s.to_text(false), "hi   ");
        assert_eq!(s.to_text(true), "hi");
    }

    #[test]
    fn fingerprint_is_stable_and_attribute_sensitive() {
        let a = screen("\x1b[31mhi");
        let b = screen("\x1b[31mhi");
        let c = screen("\x1b[32mhi");
        let d = screen("ho");
        assert_eq!(a.render_fingerprint(), b.render_fingerprint());
        // Same text, different colour — a different screenshot.
        assert_ne!(a.render_fingerprint(), c.render_fingerprint());
        assert_ne!(a.render_fingerprint(), d.render_fingerprint());
    }

    #[test]
    fn reverse_swaps_resolved_colors() {
        let s = screen("\x1b[7mx");
        let (fg, bg) = cell_colors(&s.rows[0][0]);
        assert_eq!(fg, DEFAULT_BG);
        assert_eq!(bg, DEFAULT_FG);
    }

    #[test]
    fn unknown_color_name_falls_back_to_the_default() {
        assert_eq!(css_color("chartreuse", DEFAULT_FG), DEFAULT_FG);
        assert_eq!(css_color("abcdef", DEFAULT_FG), "#abcdef");
        assert_eq!(css_color("abcde", DEFAULT_FG), DEFAULT_FG);
    }

    // -- The vt100 path -----------------------------------------------------
    //
    // These drive a real `vt100::Parser` rather than building cells by hand.
    // The defect these guard against was plumbing: the parser held the
    // attribute and `cell_from_vt100` dropped it, so only a test that reads
    // back through the parser can see it come loose again.

    fn vt100_screen(bytes: &str) -> AttributedScreen {
        let mut parser = vt100::Parser::new(3, 10, 0);
        parser.process(bytes.as_bytes());
        from_vt100(parser.screen())
    }

    #[test]
    fn vt100_path_carries_dim() {
        let s = vt100_screen("\x1b[2md\x1b[22mn");
        assert!(s.rows[0][0].dim, "SGR 2 did not reach the cell");
        assert!(!s.rows[0][1].dim, "SGR 22 did not clear dim");
    }

    #[test]
    fn vt100_path_dim_is_distinct_from_bold() {
        // vt100 models SGR 1/2/22 as one intensity, so the two are exclusive:
        // the point is that each lands in its own field, not in the other's.
        let bold = vt100_screen("\x1b[1mb");
        assert!(bold.rows[0][0].bold && !bold.rows[0][0].dim);
        let dim = vt100_screen("\x1b[2md");
        assert!(dim.rows[0][0].dim && !dim.rows[0][0].bold);
    }

    #[test]
    fn vt100_path_dim_changes_the_fingerprint() {
        // Same text, same colour — the highlight is the only difference, and
        // evidence skips re-rendering a step whose fingerprint is unchanged.
        assert_ne!(
            vt100_screen("\x1b[2mx").render_fingerprint(),
            vt100_screen("x").render_fingerprint()
        );
    }

    #[test]
    fn vt100_path_dim_reaches_the_svg() {
        let mut metrics = SvgMetrics {
            columns: 10,
            rows: 3,
            ..Default::default()
        };
        metrics.recompute();
        let out = screen_svg(&vt100_screen("\x1b[2mx"), &metrics);
        assert!(out.contains("opacity=\"0.65\""), "dim not rendered: {out}");
    }

    /// U+1FA89 is one column under `unicode-width` 0.1 and two under 0.2, so
    /// it is a live detector for the two paths drifting onto different tables.
    const WIDTH_SPLIT_CHAR: char = '\u{1FA89}';

    #[test]
    fn both_paths_measure_width_with_the_same_table() {
        let text = format!("{WIDTH_SPLIT_CHAR}x");
        let via_vt100 = vt100_screen(&text);
        let via_ansi = screen(&text);

        let widths = |s: &AttributedScreen| -> Vec<u8> {
            s.rows[0].iter().take(3).map(|c| c.width).collect()
        };
        assert_eq!(
            widths(&via_vt100),
            widths(&via_ansi),
            "the vt100 and ANSI-text paths disagree about column layout, which \
             means `unicode-width` has drifted off the major vt100 uses"
        );
        // Not just equal — equal at the value 0.2 reports, so this fails if
        // both paths regress onto the old table together.
        assert_eq!(widths(&via_vt100), vec![2, 0, 1]);
    }

    #[test]
    fn both_paths_place_the_following_glyph_in_the_same_column() {
        // The consequence that matters: a width disagreement shifts every
        // glyph after it, so the SVG draws `x` at a different x coordinate.
        // Compared as a column index rather than a whole-screen fingerprint,
        // because the vt100 grid is padded to its full size and the ANSI-text
        // grid is not — that difference is real but is not this one.
        let text = format!("{WIDTH_SPLIT_CHAR}x");
        let column_of_x = |s: &AttributedScreen| {
            s.rows[0]
                .iter()
                .position(|c| c.text == "x")
                .expect("x drawn")
        };
        assert_eq!(
            column_of_x(&vt100_screen(&text)),
            column_of_x(&screen(&text)),
            "the glyph after a wide character lands in a different column \
             depending on which path built the screen"
        );
    }

    #[test]
    fn the_text_path_lays_out_wide_glyphs_like_the_ansi_path() {
        // Both stills are drawn by `screen_svg`, so the only way they can still
        // disagree is upstream of it, in how a character is placed on the grid.
        // Escape-free input is the fair comparison: the text path takes an
        // escape as content, and that difference is deliberate.
        for text in [
            format!("{WIDTH_SPLIT_CHAR}x"),
            "ä½ x".to_string(),
            "a\u{1100}b\tc".to_string(),
            "wide 中文 mixed".to_string(),
        ] {
            assert_eq!(
                attributed_screen_from_text(&text, 40, 3).rows,
                screen(&text).rows,
                "the text and ANSI paths built different grids for {text:?}"
            );
        }
    }

    #[test]
    fn the_text_path_reads_the_same_width_table() {
        // The failure this pins: a constructor that hard-codes width 1 puts the
        // next glyph one column over where every other path puts it, and no
        // amount of sharing the renderer hides that. Asserted at the value 0.2
        // reports, not merely as agreement, so it also fails if both paths
        // regress onto the old table together — the drift #21 flagged.
        let text = format!("{WIDTH_SPLIT_CHAR}x");
        let cells = attributed_screen_from_text(&text, 40, 3);
        let widths: Vec<u8> = cells.rows[0].iter().take(3).map(|c| c.width).collect();
        assert_eq!(widths, vec![2, 0, 1]);
        assert_eq!(
            cells.rows[0].iter().position(|c| c.text == "x"),
            Some(2),
            "the glyph after a wide character landed in the wrong column"
        );
    }

    #[test]
    fn vt100_path_leaves_strikethrough_unset() {
        // vt100 still has no SGR 9; the module docs say so, and this is what
        // makes that claim checkable.
        assert!(!vt100_screen("\x1b[9mx").rows[0][0].strikethrough);
    }

    // -- SVG rendering ------------------------------------------------------

    fn svg(ansi: &str) -> String {
        let mut metrics = SvgMetrics {
            columns: 10,
            rows: 3,
            ..Default::default()
        };
        metrics.recompute();
        screen_svg(&attributed_screen_from_ansi_text(ansi, 10, 3), &metrics)
    }

    #[test]
    fn escapes_xml_specials() {
        assert_eq!(xml_escape("a<b>&c"), "a&lt;b&gt;&amp;c");
        assert!(svg("a<b").contains("&lt;"));
    }

    #[test]
    fn control_characters_never_reach_the_document() {
        // One of these makes `rsvg-convert` reject the file, and a rejected
        // file surfaces as a zero-byte PNG rather than as an error. The
        // plain-text constructor takes its characters verbatim, so an
        // unparsed escape in the text a caller hands over lands in a cell.
        let screen = attributed_screen_from_text("a\x1b[31mb\x07c", 10, 3);
        let out = screen_svg(&screen, &SvgMetrics::default());
        assert!(
            !out.chars().any(char::is_control),
            "control character survived into the SVG"
        );
        // The printable characters around it are still drawn.
        for glyph in ["a", "b", "c", "3", "1", "m"] {
            assert!(out.contains(&format!(">{glyph}</text>")), "{glyph} missing");
        }
    }

    #[test]
    fn metrics_derive_the_canvas_from_the_grid() {
        let m = SvgMetrics::default();
        assert_eq!(m.width, 120 * 10 + 20);
        assert_eq!(m.height, (40.0 * 22.0) as usize + 20);
    }

    #[test]
    fn each_glyph_is_positioned_by_column() {
        let out = svg("ab");
        // padding 10, cell_w 10 -> columns land on 10.0 and 20.0.
        assert!(out.contains("<text x=\"10.0\" y=\"25.8\" fill=\"#e6edf3\">a</text>"));
        assert!(out.contains("<text x=\"20.0\" y=\"25.8\" fill=\"#e6edf3\">b</text>"));
    }

    #[test]
    fn rows_advance_by_cell_height() {
        let out = svg("a\nb");
        // Both rows sit in column 0; only the baseline moves, by cell_h.
        assert!(out.contains("<text x=\"10.0\" y=\"25.8\" fill=\"#e6edf3\">a</text>"));
        assert!(out.contains("<text x=\"10.0\" y=\"47.8\" fill=\"#e6edf3\">b</text>"));
    }

    #[test]
    fn spaces_emit_no_glyph() {
        let out = svg("a b");
        assert_eq!(out.matches("<text").count(), 2);
        assert!(!out.contains("> </text>"));
    }

    #[test]
    fn default_background_paints_no_per_cell_rect() {
        // Only the full-page background rect.
        assert_eq!(svg("abc").matches("<rect").count(), 1);
    }

    #[test]
    fn non_default_background_paints_a_cell_rect() {
        let out = svg("\x1b[41mx");
        assert_eq!(out.matches("<rect").count(), 2);
        assert!(out.contains("width=\"10.0\" height=\"22.0\" fill=\"#ff7b72\""));
    }

    #[test]
    fn wide_glyph_background_spans_both_columns() {
        let out = svg("\x1b[41m\u{4f60}");
        assert!(out.contains("width=\"20.0\""));
        // The filler cell contributes neither a rect nor a glyph.
        assert_eq!(out.matches("<rect").count(), 2);
        assert_eq!(out.matches("<text").count(), 1);
    }

    #[test]
    fn text_attributes_reach_the_glyph() {
        let out = svg("\x1b[1;2;3;4;9mx");
        assert!(out.contains("font-weight=\"700\""));
        assert!(out.contains("font-style=\"italic\""));
        assert!(out.contains("text-decoration=\"underline line-through\""));
        assert!(out.contains("opacity=\"0.65\""));
    }

    #[test]
    fn reverse_video_swaps_the_painted_colors() {
        let out = svg("\x1b[7mx");
        // Background becomes the default foreground, and the glyph inverts.
        assert!(out.contains(&format!("height=\"22.0\" fill=\"{}\"", DEFAULT_FG)));
        assert!(out.contains(&format!("fill=\"{}\">x</text>", DEFAULT_BG)));
    }

    #[test]
    fn grid_is_clipped_to_the_metrics() {
        let mut metrics = SvgMetrics {
            columns: 2,
            rows: 1,
            ..Default::default()
        };
        metrics.recompute();
        let screen = attributed_screen_from_ansi_text("abcd\nefgh", 10, 5);
        let out = screen_svg(&screen, &metrics);
        assert_eq!(out.matches("<text").count(), 2);
    }
}