termlens 0.11.0

Headless PTY test harness for CLI/TUI apps — spawn in a real PTY, assert on the rendered screen
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
//! The `vt100`-crate backend. Public types never leak from here: every
//! snapshot converts vt100's grid into termlens's own [`Screen`].

use std::borrow::Cow;
use std::collections::VecDeque;
use std::sync::Arc;
use std::time::{Duration, Instant};

use unicode_width::UnicodeWidthStr;

use super::seq::{SeqEvent, SeqTracker, TabOp};
use super::shadow::{AttrShadow, ColorNormalizer};
use super::unhandled::Unhandled;
use super::{Emulator, FrameSpan, InputModes, ModeState, MouseEncoding, Processed, Stop};
use crate::graphics::{GraphicsPayload, GraphicsSeen, HISTORY};
use crate::screen::{Cell, Color, MouseMode, Screen, Style, TermState};

pub(crate) struct Vt100Emulator {
    /// Built with the callback set that records what vt100 could not
    /// render, so a snapshot can say so (`emu/unhandled.rs`).
    parser: ::vt100::Parser<Unhandled>,
    tracker: SeqTracker,
    /// Carries blink, conceal and strikethrough, which vt100 drops. See
    /// `emu/shadow.rs` for why this is a second parser rather than
    /// hand-rolled attribute tracking.
    shadow: AttrShadow,
    colors: ColorNormalizer,
    /// How many rows of history to retain (0 disables it entirely).
    scrollback_len: usize,
    /// When the current synchronized update began, stamped at the byte that
    /// opened it. `None` outside a frame.
    frame_started: Option<Instant>,
    /// Rows that have scrolled off the top, oldest first, as text.
    ///
    /// Materialized here — once per read that scrolled — rather than in
    /// `snapshot`, which runs far more often (every wait evaluation on a
    /// chatty stream). A snapshot then costs one `Arc` clone per row
    /// instead of rebuilding the whole history.
    history: VecDeque<Arc<str>>,
    /// The same rows as cells, when the terminal was built to retain
    /// styles in history (#146); `None` otherwise, so a suite that never
    /// asks pays nothing. Kept in lockstep with `history`, one entry each.
    history_cells: Option<VecDeque<Arc<[Cell]>>>,
    /// Rows of vt100's own scrollback already copied into `history`, so a
    /// read that scrolled nothing costs one length check.
    captured: usize,
    /// Inline graphics payloads, oldest first, behind an `Arc` so a
    /// snapshot costs one refcount rather than a copy of every image.
    graphics: Arc<Vec<GraphicsPayload>>,
    /// Payload bytes currently retained, so eviction is a subtraction
    /// rather than a walk.
    graphics_bytes: usize,
    /// The retention budget, from `TerminalBuilder::capture_graphics`.
    capture: usize,
    /// Bytes rewritten on their way to the parsers and not yet handed over.
    /// Empty except while a DEC Special Graphics set is invoked: a byte the
    /// set redefines reaches the grid as the glyph it draws, so the stream
    /// the parsers see is then no longer a sub-slice of the read. Kept
    /// between calls only for its allocation.
    staged: Vec<u8>,
}

impl Vt100Emulator {
    /// Close out the frame that just ended: how long it ran between the
    /// application's own markers, and how much it drew.
    fn close_frame(&mut self) -> FrameSpan {
        let started = self.frame_started.take();
        debug_assert!(
            started.is_some(),
            "a frame only ends where a Begin was seen, so the start must exist"
        );
        FrameSpan {
            duration: started.map_or(Duration::ZERO, |at| at.elapsed()),
            printable: self.tracker.take_frame_printable(),
        }
    }

    pub(crate) fn new(
        rows: u16,
        cols: u16,
        scrollback_len: usize,
        capture: usize,
        styled_history: bool,
    ) -> Self {
        Self {
            parser: ::vt100::Parser::new_with_callbacks(
                rows,
                cols,
                scrollback_len,
                Unhandled::default(),
            ),
            tracker: SeqTracker::new(capture, cols),
            // The shadow keeps history only when its cells will be read.
            shadow: AttrShadow::new(rows, cols, if styled_history { scrollback_len } else { 0 }),
            history_cells: styled_history.then(VecDeque::new),
            colors: ColorNormalizer::new(),
            scrollback_len,
            frame_started: None,
            history: VecDeque::new(),
            captured: 0,
            graphics: Arc::new(Vec::new()),
            graphics_bytes: 0,
            capture,
            staged: Vec::new(),
        }
    }

    /// Hand the grid the bytes the tracker has already scanned.
    ///
    /// The tracker runs a byte ahead of the parser so it can stop the read
    /// at a frame end or a query; everything else is fed in bulk. Splitting
    /// the feed is what lets a graphics payload be stamped with the cursor
    /// position as of its terminator rather than as of the whole read.
    fn feed(&mut self, bytes: &[u8]) {
        if bytes.is_empty() {
            return;
        }
        // U+FFFD would be dropped on the way in — see `stand_in_for_replacement`.
        let bytes = stand_in_for_replacement(bytes);
        let normalized = self.colors.feed(&bytes);
        self.parser.process(&normalized);
        self.shadow.feed(&bytes);
        self.capture_scrolled_rows();
    }

    /// Hand the grid everything staged so far followed by `tail`, in order.
    ///
    /// The common case — nothing was rewritten — feeds `tail` straight
    /// through, so a stream that never designates a character set pays for
    /// none of this.
    fn feed_staged(&mut self, tail: &[u8]) {
        if self.staged.is_empty() {
            self.feed(tail);
            return;
        }
        let mut staged = std::mem::take(&mut self.staged);
        staged.extend_from_slice(tail);
        self.feed(&staged);
        staged.clear();
        self.staged = staged;
    }

    /// Carry out a tab-stop operation, given the bytes still owed to the
    /// grid: `before` is everything ahead of the one that completed the
    /// sequence, and `last` is that byte itself.
    ///
    /// Every one of the five is relative to the cursor column, so `before`
    /// has to reach the parser first — the position read otherwise belongs
    /// to wherever the last feed stopped, which on a chatty stream is an
    /// arbitrary number of characters back.
    ///
    /// The split is at the completing byte and not past it, which matters
    /// for plain `HT` alone: vt100 ignores the four escapes, but it acts on
    /// `HT`, so feeding that byte before the column is read would move the
    /// cursor to vt100's fixed eight and leave the computation working from
    /// the wrong base. Reading first is correct for all five, since no
    /// escape prefix moves the cursor either.
    ///
    /// The sequence is then fed rather than dropped. vt100 ignores `HTS`,
    /// `TBC`, `CHT` and `CBT` outright, and dropping a final byte would
    /// leave its parser sitting in a half-consumed escape that swallows
    /// whatever came next. `HT` it does act on, moving by its own fixed
    /// eight — which the `CHA` below then overrides, since `HT` draws
    /// nothing and only moves the cursor.
    fn apply_tabs(&mut self, op: TabOp, before: &[u8], last: &[u8]) {
        self.feed_staged(before);
        let col = self.parser.screen().cursor_position().1;
        let target = self.tracker.tab_op(op, col);
        self.feed_staged(last);
        if let Some(target) = target {
            // CHA counts from one. Both parsers are fed it, so the
            // attribute shadow moves with the primary grid and the two
            // stay the same shape — the invariant `snapshot` asserts.
            self.feed(format!("\x1b[{}G", target.saturating_add(1)).as_bytes());
        }
    }

    /// File a completed payload, stamped with where it landed.
    ///
    /// Neither protocol's escape moves the cursor, so the position once the
    /// terminator has been consumed *is* the image's top-left corner — the
    /// one fact about an image that lives in the grid rather than in the
    /// payload, and the one an application gets wrong when a picture drifts
    /// out from under its own labels.
    fn record_graphics(&mut self, mut payload: GraphicsPayload) {
        payload.place(self.parser.screen().cursor_position());
        let kept = payload.data().map_or(0, <[u8]>::len);
        let log = Arc::make_mut(&mut self.graphics);
        log.push(payload);
        self.graphics_bytes += kept;
        // Evict oldest-first, on both bounds. A snapshot already taken keeps
        // its own view: it holds an `Arc` to the vector as it stood.
        while log.len() > HISTORY || (self.graphics_bytes > self.capture && log.len() > 1) {
            let dropped = log.remove(0);
            self.graphics_bytes -= dropped.data().map_or(0, <[u8]>::len);
        }
    }

    /// Copy any rows that have scrolled off since the last call.
    ///
    /// vt100 models scrollback as a *stateful view*: `set_scrollback(n)`
    /// moves the offset so the same accessors read history rows. A
    /// `Screen` is an immutable snapshot and the whole crate's honesty
    /// rests on that, so the view is moved here — under `&mut self`, while
    /// bytes are being consumed — and always restored to 0 before anyone
    /// can observe the grid. No snapshot ever depends on parser state read
    /// later.
    fn capture_scrolled_rows(&mut self) {
        if self.scrollback_len == 0 {
            return;
        }
        let (rows, cols) = self.parser.screen().size();
        let screen = self.parser.screen_mut();

        // `set_scrollback` clamps to the real history length, so asking for
        // more than exists is how we learn how much exists.
        screen.set_scrollback(usize::MAX);
        let len = screen.scrollback();

        // Below the cap, history only grows: the new rows are exactly
        // `captured..len`, and an unchanged length means nothing scrolled.
        //
        // At the cap, vt100 evicts from the front and the length stops
        // changing, so it no longer reveals growth — and an unchanged
        // length is no longer evidence of an unchanged history. There is no
        // sound cheap test for "did it scroll?" either: consecutive
        // identical rows are ordinary output, so comparing the ends of the
        // history would miss real scrolls. So at the cap we re-read the
        // window vt100 still holds, which is by definition the newest `cap`
        // rows — exactly what we should be retaining. That costs O(cap) row
        // reads per chunk, and only for a run that has already overflowed
        // its history. Measured on 50,000 lines through an 80x24 screen:
        // 352ms with retention off, 327ms below the cap (free, within
        // noise), 639ms on this path — under 2x, for a workload well past
        // what a test drives.
        let at_cap = len == self.scrollback_len;
        if !at_cap && len == self.captured {
            screen.set_scrollback(0);
            return;
        }
        let from = if at_cap {
            self.history.clear();
            if let Some(cells) = &mut self.history_cells {
                cells.clear();
            }
            0
        } else {
            self.captured
        };

        // At offset `k` the visible window starts at history row `len - k`,
        // so `set_scrollback(len - i)` puts history row `i` at the top and
        // the next `rows` rows follow. `Screen::rows` walks the window once,
        // which matters: `Screen::cell` is O(row) per lookup.
        let mut i = from;
        while i < len {
            screen.set_scrollback(len - i);
            let take = (len - i).min(usize::from(rows));
            for line in screen.rows(0, cols).take(take) {
                self.history
                    .push_back(Arc::from(restore_replacement(line.trim_end()).as_ref()));
            }
            // Styled history: the same rows as cells, the shadow moved to
            // the same offset so blink, conceal and strikethrough come
            // along — the correspondence invariant extended from the grid
            // to history. Cell reads are O(row) each in vt100, so this is
            // the cost the builder's knob documents.
            if let Some(cells) = &mut self.history_cells {
                self.shadow.set_scrollback(len - i);
                for row in 0..u16::try_from(take).unwrap_or(u16::MAX) {
                    let mut converted: Vec<Cell> = Vec::with_capacity(usize::from(cols));
                    for col in 0..cols {
                        let mut cell = screen.cell(row, col).map_or_else(
                            || Cell::new(String::new(), Style::default(), false, false),
                            |cell| convert_cell(cell, self.shadow.cell(row, col)),
                        );
                        if col > 0 && cell.is_wide_continuation() {
                            if let Some(lead) = converted.last() {
                                cell = Cell::new(String::new(), *lead.style(), false, true);
                            }
                        }
                        converted.push(cell);
                    }
                    cells.push_back(converted.into());
                }
                self.shadow.set_scrollback(0);
            }
            i += take;
        }
        while self.history.len() > self.scrollback_len {
            self.history.pop_front();
        }
        if let Some(cells) = &mut self.history_cells {
            while cells.len() > self.scrollback_len {
                cells.pop_front();
            }
        }
        self.captured = len;
        screen.set_scrollback(0);
    }
}

impl Emulator for Vt100Emulator {
    fn process(&mut self, bytes: &[u8]) -> Processed {
        // How much of this segment the grid has already been given. A
        // graphics payload moves it mid-segment, and so does a byte the
        // invoked character set redefines: that byte is staged as the glyph
        // it draws instead of being sliced through, and everything else is
        // fed in one go, exactly as before.
        let mut fed = 0;
        // Where the current run of printable bytes ends while insert mode is
        // on, so the room is reserved once per run rather than per byte.
        let mut run_until = 0;
        for (i, &byte) in bytes.iter().enumerate() {
            // Insert mode: a printable run pushes the rest of the row right
            // instead of overwriting it. vt100 does not model IRM, so the
            // room is reserved with the `ICH` it does dispatch, sized in
            // columns — a wide character counts twice — and never past the
            // right margin (#261). The bytes owed to the grid go first, so
            // the cursor column the reservation is made at is current.
            if i >= run_until
                && self.tracker.insert_mode()
                && !self.tracker.mid_sequence()
                && is_printable(byte)
            {
                let end = bytes[i..]
                    .iter()
                    .position(|&b| !is_printable(b))
                    .map_or(bytes.len(), |p| i + p);
                run_until = end;
                let width = String::from_utf8_lossy(&bytes[i..end]).width();
                self.feed_staged(&bytes[fed..i]);
                fed = i;
                let screen = self.parser.screen();
                let (_, col) = screen.cursor_position();
                let room = usize::from(screen.size().1.saturating_sub(col));
                let reserve = width.min(room);
                if reserve > 0 {
                    self.feed(format!("\x1b[{reserve}@").as_bytes());
                }
            }
            // Asked before the step, because whether this byte is a character
            // at all depends on the state the tracker is in before it — and
            // a designation's own final byte must not be drawn.
            if let Some(glyph) = self.tracker.charset_glyph(byte) {
                self.staged.extend_from_slice(&bytes[fed..i]);
                self.staged.extend_from_slice(glyph.as_bytes());
                fed = i + 1;
            }
            let stop = match self.tracker.step(byte) {
                SeqEvent::SyncEnd => Some(Stop::FrameComplete(self.close_frame())),
                SeqEvent::Query(query) => Some(Stop::Query(query)),
                SeqEvent::Graphics(payload) => {
                    self.feed_staged(&bytes[fed..=i]);
                    fed = i + 1;
                    self.record_graphics(*payload);
                    None
                }
                SeqEvent::SoftReset => {
                    // The tracker has reset what it holds; the grid's
                    // modes are vt100's, which does not implement DECSTR,
                    // so it is handed the sequences that reset them one by
                    // one. The soft reset itself goes through first, in
                    // stream order, then the replay.
                    self.feed_staged(&bytes[fed..=i]);
                    fed = i + 1;
                    self.feed(SOFT_RESET_REPLAY);
                    None
                }
                SeqEvent::Tabs(op) => {
                    self.apply_tabs(op, &bytes[fed..i], &bytes[i..=i]);
                    fed = i + 1;
                    None
                }
                SeqEvent::None => None,
                SeqEvent::SyncBegin => {
                    // Stamped here, at the byte that opened the update,
                    // rather than when the read arrived: a read can carry a
                    // whole burst, and stamping per chunk would fold PTY
                    // scheduling into the measurement.
                    self.frame_started = Some(Instant::now());
                    None
                }
            };
            if let Some(stop) = stop {
                self.feed_staged(&bytes[fed..=i]);
                return Processed {
                    consumed: i + 1,
                    stop: Some(stop),
                };
            }
        }
        self.feed_staged(&bytes[fed..]);
        Processed {
            consumed: bytes.len(),
            stop: None,
        }
    }

    fn snapshot(&self) -> Screen {
        let unsupported = self.parser.callbacks().shapes();
        let unsupported_overflow = self.parser.callbacks().overflow();
        let visual_bells = self.parser.callbacks().visual_bells();
        let screen = self.parser.screen();
        let (rows, cols) = screen.size();
        let mut cells: Vec<Cell> = Vec::with_capacity(usize::from(rows) * usize::from(cols));
        // The shadow grid is the same shape as the primary — vt100's
        // attributes never influence geometry, and the two streams differ
        // only by rewritten SGR — so cell (row, col) means the same in both.
        debug_assert_eq!(
            screen.contents(),
            self.shadow.contents(),
            "the attribute shadow diverged from the primary grid"
        );
        for row in 0..rows {
            for col in 0..cols {
                // In-range lookups on vt100 are always Some; blank fallback
                // keeps this total rather than panicking inside a snapshot.
                let mut converted = screen.cell(row, col).map_or_else(
                    || Cell::new(String::new(), Style::default(), false, false),
                    |cell| convert_cell(cell, self.shadow.cell(row, col)),
                );
                // A wide character's second column is painted in the leading
                // cell's colours, so it carries the leading cell's style.
                // vt100 leaves the placeholder unstyled, which split every
                // highlight over CJK or emoji into two spans with a hole
                // (#218) — the same shape as the shadow recovery: upstream
                // drops it, the snapshot restores it.
                if col > 0 && converted.is_wide_continuation() {
                    if let Some(lead) = cells.last() {
                        converted = Cell::new(String::new(), *lead.style(), false, true);
                    }
                }
                cells.push(converted);
            }
        }
        let (cursor_row, cursor_col) = screen.cursor_position();
        let state = TermState {
            title: self.tracker.title(),
            alternate_screen: screen.alternate_screen(),
            bracketed_paste: screen.bracketed_paste(),
            application_cursor: screen.application_cursor(),
            mouse: convert_mouse(screen.mouse_protocol_mode()),
            mouse_modes: self.tracker.mouse_tracking(),
            clipboard: self.tracker.clipboard(),
            bells: self.tracker.bells(),
            focus_events: self.tracker.focus_events(),
            cursor_style: self.tracker.cursor_style(),
            links: self.tracker.links(),
            graphics: GraphicsSeen::new(self.tracker.graphics(), Arc::clone(&self.graphics)),
            // Filled in by the terminal, which owns the frame count.
            repaints: 0,
            scrollback: self.history.iter().cloned().collect(),
            scrollback_cells: self
                .history_cells
                .as_ref()
                .map(|cells| cells.iter().cloned().collect()),
            // The backend's own record of a soft wrap, per row (#265).
            wrapped: (0..rows).map(|row| screen.row_wrapped(row)).collect(),
            insert_mode: self.tracker.insert_mode(),
            unsupported,
            unsupported_overflow,
            visual_bells,
        };
        Screen::from_parts(
            cols,
            rows,
            cursor_row,
            cursor_col,
            !screen.hide_cursor(),
            cells,
            state,
        )
    }

    fn mid_sequence(&self) -> bool {
        self.tracker.mid_sequence()
    }

    fn in_sync_update(&self) -> bool {
        self.tracker.in_sync_update()
    }

    fn input_modes(&self) -> InputModes {
        let screen = self.parser.screen();
        InputModes {
            mouse: convert_mouse(screen.mouse_protocol_mode()),
            mouse_encoding: match screen.mouse_protocol_encoding() {
                ::vt100::MouseProtocolEncoding::Sgr => MouseEncoding::Sgr,
                ::vt100::MouseProtocolEncoding::Utf8 => MouseEncoding::Utf8,
                ::vt100::MouseProtocolEncoding::Default => MouseEncoding::Legacy,
            },
            bracketed_paste: screen.bracketed_paste(),
            application_cursor: screen.application_cursor(),
            focus_events: self.tracker.focus_events(),
        }
    }

    fn mode_state(&self, mode: u32) -> ModeState {
        let screen = self.parser.screen();
        let on = |set: bool| {
            if set {
                ModeState::Set
            } else {
                ModeState::Reset
            }
        };
        // Only modes whose state we hold exactly.
        match mode {
            // Synchronized output. Answering at all is the point: an
            // application that probes before bracketing its repaints can
            // then use it, which is what makes wait_frame work against
            // programs we haven't modified.
            2026 => on(self.tracker.in_sync_update()),
            1 => on(screen.application_cursor()),
            25 => on(!screen.hide_cursor()),
            47 | 1047 | 1049 => on(screen.alternate_screen()),
            2004 => on(screen.bracketed_paste()),
            // Tracked by termlens itself, so the state is exact — which is
            // what the honesty rule requires before answering.
            1004 => on(self.tracker.focus_events()),
            1006 => on(matches!(
                screen.mouse_protocol_encoding(),
                ::vt100::MouseProtocolEncoding::Sgr
            )),
            1005 => on(matches!(
                screen.mouse_protocol_encoding(),
                ::vt100::MouseProtocolEncoding::Utf8
            )),
            // The mouse tracking modes, each on its own evidence: the
            // tracker keeps the set the application asked for (#151). vt100
            // collapses the four into one value, so before this a probe for
            // `1002` while `1003` was also on had to answer "not
            // recognized" — the only honest reply to a question the state
            // could not answer, and one crossterm's three-at-once enable
            // provoked on every run.
            9 => on(self.tracker.mouse_tracking().contains(MouseMode::Press)),
            1000 => on(self
                .tracker
                .mouse_tracking()
                .contains(MouseMode::PressRelease)),
            1002 => on(self
                .tracker
                .mouse_tracking()
                .contains(MouseMode::ButtonMotion)),
            1003 => on(self.tracker.mouse_tracking().contains(MouseMode::AnyMotion)),
            _ => ModeState::NotRecognized,
        }
    }

    fn set_size(&mut self, rows: u16, cols: u16) {
        self.parser.screen_mut().set_size(rows, cols);
        self.shadow.set_size(rows, cols);
        self.tracker.set_cols(cols);
        // A resize can push rows into history on its own.
        self.capture_scrolled_rows();
    }
}

/// What `DECSTR` resets of the state vt100 holds, as the sequences vt100
/// understands: cursor keys back to normal (`DECCKM`), bracketed paste off,
/// every mouse tracking mode and encoding off, and the cursor visible
/// (`DECTCEM`). The rest of the specified list — attributes, margins,
/// origin and insert modes, the keypad — is deliberately not replayed:
/// none of it is observable through `Screen` today, and a replay nothing
/// can check is a claim nothing can catch. The alternate screen is left
/// alone, as the spec says.
const SOFT_RESET_REPLAY: &[u8] =
    b"\x1b[?1l\x1b[?2004l\x1b[?9l\x1b[?1000l\x1b[?1002l\x1b[?1003l\x1b[?1005l\x1b[?1006l\x1b[?25h";

fn convert_mouse(mode: ::vt100::MouseProtocolMode) -> MouseMode {
    match mode {
        ::vt100::MouseProtocolMode::None => MouseMode::None,
        ::vt100::MouseProtocolMode::Press => MouseMode::Press,
        ::vt100::MouseProtocolMode::PressRelease => MouseMode::PressRelease,
        ::vt100::MouseProtocolMode::ButtonMotion => MouseMode::ButtonMotion,
        ::vt100::MouseProtocolMode::AnyMotion => MouseMode::AnyMotion,
    }
}

/// Build a [`Cell`] from the primary grid cell and its shadow counterpart,
/// whose bold/italic/underline flags are this cell's
/// blink/conceal/strikethrough (see `emu/shadow.rs`).
fn convert_cell(cell: &::vt100::Cell, shadow: Option<&::vt100::Cell>) -> Cell {
    let style = Style {
        fg: convert_color(cell.fgcolor()),
        bg: convert_color(cell.bgcolor()),
        bold: cell.bold(),
        dim: cell.dim(),
        italic: cell.italic(),
        underline: cell.underline(),
        reverse: cell.inverse(),
        blink: shadow.is_some_and(::vt100::Cell::bold),
        conceal: shadow.is_some_and(::vt100::Cell::italic),
        strikethrough: shadow.is_some_and(::vt100::Cell::underline),
    };
    Cell::new(
        restore_replacement(cell.contents()).into_owned(),
        style,
        cell.is_wide(),
        cell.is_wide_continuation(),
    )
}

/// A byte that draws: not a C0 control, not DEL, not ESC. Continuation
/// bytes of a multi-byte character count, so a run is measured whole.
fn is_printable(b: u8) -> bool {
    b >= 0x20 && b != 0x7f
}

/// What the reader substitutes for a byte it could not decode (`utf8.rs`).
const REPLACEMENT: &str = "\u{FFFD}";
/// What the grid is fed in its place. vt100's `print` drops U+FFFD outright
/// (0.16, `perform.rs`), so the replacement would vanish exactly as the
/// invalid byte did (#217). U+FDD0 is a Unicode noncharacter — reserved for
/// internal use like this, never for interchange, so no application has any
/// business emitting one — and vt100 draws it as an ordinary width-1 cell.
/// The snapshot puts U+FFFD back wherever it appears.
const STAND_IN: &str = "\u{FDD0}";

/// `bytes` with every encoded U+FFFD swapped for the stand-in, allocating
/// only when there is one to swap. A stop never falls inside a character,
/// so the three bytes always arrive in one feed.
fn stand_in_for_replacement(bytes: &[u8]) -> Cow<'_, [u8]> {
    let from = REPLACEMENT.as_bytes();
    if !bytes.windows(from.len()).any(|window| window == from) {
        return Cow::Borrowed(bytes);
    }
    let to = STAND_IN.as_bytes();
    let mut out = Vec::with_capacity(bytes.len());
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i..].starts_with(from) {
            out.extend_from_slice(to);
            i += from.len();
        } else {
            out.push(bytes[i]);
            i += 1;
        }
    }
    Cow::Owned(out)
}

/// Grid text as the snapshot reports it: the stand-in reads as U+FFFD again.
fn restore_replacement(text: &str) -> Cow<'_, str> {
    if text.contains(STAND_IN) {
        Cow::Owned(text.replace(STAND_IN, REPLACEMENT))
    } else {
        Cow::Borrowed(text)
    }
}

fn convert_color(color: ::vt100::Color) -> Color {
    match color {
        ::vt100::Color::Default => Color::Default,
        ::vt100::Color::Idx(i) => Color::Indexed(i),
        ::vt100::Color::Rgb(r, g, b) => Color::Rgb(r, g, b),
    }
}

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

    /// Feed a whole stream, looping across frame-boundary stops.
    fn feed_all(emu: &mut Vt100Emulator, bytes: &[u8]) {
        let mut off = 0;
        while off < bytes.len() {
            off += emu.process(&bytes[off..]).consumed;
        }
    }

    fn emu_with(bytes: &[u8]) -> Vt100Emulator {
        let mut emu = Vt100Emulator::new(4, 10, 0, crate::graphics::DEFAULT_CAPTURE, false);
        feed_all(&mut emu, bytes);
        emu
    }

    #[test]
    fn renders_plain_text_into_the_grid() {
        let emu = emu_with(b"hi\r\nthere");
        let screen = emu.snapshot();
        assert_eq!(screen.size(), (10, 4));
        assert_eq!(screen.text(), "hi\nthere\n\n");
        assert_eq!(screen.cursor(), (1, 5, true));
    }

    #[test]
    fn positions_wide_characters_with_continuations() {
        let emu = emu_with("汉x".as_bytes());
        let screen = emu.snapshot();
        let wide = screen.cell(0, 0).unwrap();
        assert!(wide.is_wide());
        assert_eq!(wide.contents(), "");
        assert!(screen.cell(0, 1).unwrap().is_wide_continuation());
        assert_eq!(screen.find("x"), Some((0, 2)));
    }

    #[test]
    fn a_wide_characters_continuation_carries_the_leading_cells_style() {
        // `ab汉cd` on one background: six columns, one span, no hole at the
        // continuation column (#218).
        let screen = emu_with(b"\x1b[48;2;30;30;46mab\xe6\xb1\x89cd\x1b[0m").snapshot();
        let bg = Color::Rgb(30, 30, 46);
        assert!(screen.cell(0, 3).unwrap().is_wide_continuation());
        for col in 0..6 {
            assert_eq!(screen.cell(0, col).unwrap().style().bg, bg, "col {col}");
        }
        let styled = screen.with_styles().to_string();
        assert!(styled.contains("0: 0-5 bg=#1e1e2e"), "{styled}");
        assert_eq!(screen.cell(0, 6).unwrap().style(), &Style::default());
    }

    #[test]
    fn a_replacement_character_is_drawn_like_any_other() {
        // The reader turns invalid UTF-8 into U+FFFD (#217); the grid has to
        // show it, or the byte is as invisible as before.
        let screen = emu_with("caf\u{FFFD} done".as_bytes()).snapshot();
        assert_eq!(screen.row_text(0).trim_end(), "caf\u{FFFD} done");
        assert_eq!(screen.cell(0, 3).unwrap().contents(), "\u{FFFD}");
        assert_eq!(screen.find("done"), Some((0, 5)));

        // Scrolled into history, it is still U+FFFD — never the stand-in.
        let mut emu = Vt100Emulator::new(4, 10, 100, crate::graphics::DEFAULT_CAPTURE, false);
        feed_all(
            &mut emu,
            "caf\u{FFFD} done\r\n1\r\n2\r\n3\r\n4\r\n5".as_bytes(),
        );
        let screen = emu.snapshot();
        let history = screen.scrollback_text();
        assert!(history.contains("caf\u{FFFD} done"), "{history:?}");
        assert!(
            !screen.full_text().contains(STAND_IN),
            "{}",
            screen.full_text()
        );
    }

    #[test]
    fn captures_sgr_styles() {
        let emu = emu_with(b"\x1b[1;3;4;7;31mX\x1b[0m");
        let screen = emu.snapshot();
        let style = *screen.cell(0, 0).unwrap().style();
        assert!(style.bold && style.italic && style.underline && style.reverse);
        assert_eq!(style.fg, Color::Indexed(1));
        assert_eq!(screen.cell(0, 1).unwrap().style(), &Style::default());
    }

    #[test]
    fn bold_and_dim_are_one_intensity_state_and_the_last_write_wins() {
        // Documented on `Style::bold` and `Style::dim` (#225): the backend
        // keeps one intensity, so a cell never reports both, and SGR 22
        // clears whichever is set.
        let screen = emu_with(b"\x1b[1;2mA\x1b[0m\x1b[2;1mB\x1b[0m\x1b[1m\x1b[22mC").snapshot();
        let style = |col| *screen.cell(0, col).unwrap().style();
        assert!(!style(0).bold && style(0).dim, "ESC[1;2m: {:?}", style(0));
        assert!(style(1).bold && !style(1).dim, "ESC[2;1m: {:?}", style(1));
        assert!(
            !style(2).bold && !style(2).dim,
            "ESC[1m ESC[22m: {:?}",
            style(2)
        );
    }

    #[test]
    fn blink_conceal_and_strikethrough_reach_the_cells() {
        // The three attributes vt100 drops. Recovered via the shadow parser
        // (see `emu/shadow.rs`).
        let emu = emu_with(b"\x1b[5mB\x1b[0m\x1b[8mC\x1b[0m\x1b[9mS\x1b[0mp");
        let s = emu.snapshot();
        let style = |col| *s.cell(0, col).unwrap().style();

        assert!(style(0).blink && !style(0).conceal && !style(0).strikethrough);
        assert!(style(1).conceal && !style(1).blink && !style(1).strikethrough);
        assert!(style(2).strikethrough && !style(2).blink && !style(2).conceal);
        // And a plain cell after the reset carries none of them.
        assert_eq!(style(3), Style::default());
    }

    #[test]
    fn the_new_attributes_coexist_with_the_old_ones() {
        // A real bold must not read as a blink, and vice versa: the two
        // parsers must not leak into each other.
        let emu = emu_with(b"\x1b[1;31mA\x1b[0m\x1b[5mB\x1b[0m\x1b[1;5;4mC");
        let s = emu.snapshot();
        let a = *s.cell(0, 0).unwrap().style();
        assert!(a.bold && !a.blink);
        assert_eq!(a.fg, Color::Indexed(1));

        let b = *s.cell(0, 1).unwrap().style();
        assert!(b.blink && !b.bold);

        let c = *s.cell(0, 2).unwrap().style();
        assert!(c.bold && c.blink && c.underline && !c.strikethrough);
    }

    #[test]
    fn each_attribute_has_its_own_reset() {
        let emu = emu_with(b"\x1b[5;8;9mX\x1b[25mY\x1b[28mZ\x1b[29mW");
        let s = emu.snapshot();
        let style = |col| *s.cell(0, col).unwrap().style();

        let x = style(0);
        assert!(x.blink && x.conceal && x.strikethrough);
        let y = style(1);
        assert!(!y.blink && y.conceal && y.strikethrough);
        let z = style(2);
        assert!(!z.blink && !z.conceal && z.strikethrough);
        assert_eq!(style(3), Style::default());
    }

    #[test]
    fn a_palette_colour_is_never_mistaken_for_an_attribute() {
        // `38;5;196` selects palette entry 196. Reading its `5` as blink
        // would mark a whole run with an attribute the application never
        // set — and 256-colour output is everywhere.
        let emu = emu_with(b"\x1b[38;5;196mX\x1b[0m\x1b[38;2;0;8;9mY");
        let s = emu.snapshot();
        let x = *s.cell(0, 0).unwrap().style();
        assert_eq!(x.fg, Color::Indexed(196));
        assert!(!x.blink && !x.conceal && !x.strikethrough);

        let y = *s.cell(0, 1).unwrap().style();
        assert_eq!(y.fg, Color::Rgb(0, 8, 9));
        assert!(!y.conceal && !y.strikethrough);
    }

    #[test]
    fn colon_form_rgb_colours_match_semicolon_form() {
        let emu = emu_with(b"\x1b[38;2;10;20;30mA\x1b[0m\x1b[38:2::10:20:30mB");
        let s = emu.snapshot();
        assert_eq!(s.cell(0, 0).unwrap().style().fg, Color::Rgb(10, 20, 30));
        assert_eq!(s.cell(0, 1).unwrap().style().fg, Color::Rgb(10, 20, 30));
    }

    #[test]
    fn colon_form_colours_support_optional_colour_space_and_chunking() {
        let mut emu = Vt100Emulator::new(4, 10, 0, crate::graphics::DEFAULT_CAPTURE, false);
        emu.feed(b"\x1b[38:2:10:");
        emu.feed(b"20:30mA\x1b[48:5:196mB");
        let s = emu.snapshot();

        let foreground = s.cell(0, 0).unwrap().style();
        assert_eq!(foreground.fg, Color::Rgb(10, 20, 30));
        assert_eq!(foreground.bg, Color::Default);

        let background = s.cell(0, 1).unwrap().style();
        assert_eq!(background.fg, Color::Rgb(10, 20, 30));
        assert_eq!(background.bg, Color::Indexed(196));
    }

    #[test]
    fn attributes_survive_the_geometry_the_shadow_must_track() {
        // Erase fills cells with the current attributes, scrolling moves
        // rows, and the alternate screen swaps grids. The shadow follows the
        // same byte stream, so all three must line up — the snapshot's
        // debug assertion checks the grids match on every call here.
        let emu = emu_with(b"\x1b[8mmasked\r\nrow2\r\nrow3\r\nrow4\r\nrow5");
        let s = emu.snapshot();
        // "masked" scrolled off; every remaining cell is still concealed.
        assert!(s.cell(0, 0).unwrap().style().conceal, "{s}");
        assert!(s.cell(3, 0).unwrap().style().conceal, "{s}");

        let emu = emu_with(b"\x1b[9mstruck\x1b[?1049hALT");
        let s = emu.snapshot();
        assert!(s.cell(0, 0).unwrap().style().strikethrough, "{s}");
    }

    /// `ESC ( 0 l q q q k` is a box. Both parsers receive the translated
    /// stream — the snapshot's correspondence check would fail otherwise.
    #[test]
    fn dec_special_graphics_reaches_the_grid_as_the_glyphs_it_draws() {
        let emu = emu_with(b"\x1b(0lqqqk\x1b(B\r\nplain");
        let s = emu.snapshot();
        assert_eq!(
            s.text(),
            "\u{250c}\u{2500}\u{2500}\u{2500}\u{2510}\nplain\n\n"
        );
        assert_eq!(s.find("\u{2510}"), Some((0, 4)), "one cell per glyph");
        assert!(!s.contains("lqqqk"));

        // SO/SI with the set in G1, the vt100-terminfo shape.
        let emu = emu_with(b"\x1b)0\x0elqk\x0f ok");
        assert_eq!(
            emu.snapshot().row_text(0).trim_end(),
            "\u{250c}\u{2500}\u{2510} ok"
        );

        // G2 + SS2 and G3 + SS3: one graphic, then the locked set resumes.
        // `|` is itself a Special Graphics byte, so a stuck shift is `≠`.
        let emu = emu_with(b"\x1b*0\x1bNl\x1b(B|");
        assert_eq!(emu.snapshot().row_text(0).trim_end(), "\u{250c}|");
        let emu = emu_with(b"\x1b+0\x1bOl\x1b(B|");
        assert_eq!(emu.snapshot().row_text(0).trim_end(), "\u{250c}|");
    }

    /// A style set inside the graphics set travels with the glyph, and the
    /// attribute shadow stays in step: the rewrite happens before either
    /// parser, so the two grids are still the same shape.
    #[test]
    fn a_styled_line_drawing_run_keeps_its_style_and_the_shadow_in_step() {
        let emu = emu_with(b"\x1b(0\x1b[31;9mqq\x1b[0m\x1b(Bq");
        let s = emu.snapshot();
        assert_eq!(s.row_text(0).trim_end(), "\u{2500}\u{2500}q");
        let drawn = *s.cell(0, 0).unwrap().style();
        assert_eq!(drawn.fg, Color::Indexed(1));
        assert!(drawn.strikethrough, "the shadow-carried attribute too");
        assert_eq!(s.cell(0, 2).unwrap().style(), &Style::default());
    }

    /// A translated byte that also closes a frame, split across feeds: the
    /// staged glyph must reach the grid before the stop is reported, and a
    /// designation split across chunks must still apply.
    #[test]
    fn translation_survives_chunk_boundaries_and_frame_stops() {
        let mut emu = Vt100Emulator::new(4, 10, 0, crate::graphics::DEFAULT_CAPTURE, false);
        feed_all(&mut emu, b"\x1b(");
        feed_all(&mut emu, b"0\x1b[?2026hl");
        feed_all(&mut emu, b"q\x1b[?2026lk");
        let s = emu.snapshot();
        assert_eq!(s.row_text(0).trim_end(), "\u{250c}\u{2500}\u{2510}");
        assert!(!emu.in_sync_update());
    }

    #[test]
    fn hidden_cursor_is_reported() {
        let emu = emu_with(b"\x1b[?25l");
        assert_eq!(emu.snapshot().cursor(), (0, 0, false));
    }

    #[test]
    fn mid_sequence_tracks_partial_escape() {
        let mut emu = Vt100Emulator::new(4, 10, 0, crate::graphics::DEFAULT_CAPTURE, false);
        feed_all(&mut emu, b"text\x1b[3");
        assert!(emu.mid_sequence());
        feed_all(&mut emu, b"1m");
        assert!(!emu.mid_sequence());
    }

    #[test]
    fn process_stops_at_the_end_of_a_synchronized_update() {
        let mut emu = Vt100Emulator::new(4, 10, 0, crate::graphics::DEFAULT_CAPTURE, false);
        let stream = b"\x1b[?2026hframe1\x1b[?2026lnext";

        let first = emu.process(stream);
        assert!(
            matches!(first.stop, Some(Stop::FrameComplete(_))),
            "stop: {:?}",
            first.stop
        );
        // Everything through the ESU is consumed; "next" is not.
        assert_eq!(
            &stream[..first.consumed],
            b"\x1b[?2026hframe1\x1b[?2026l" as &[u8]
        );
        // The screen at the stop is the complete frame, untouched by "next".
        assert_eq!(emu.snapshot().text(), "frame1\n\n\n");
        assert!(!emu.in_sync_update());

        let rest = emu.process(&stream[first.consumed..]);
        assert!(rest.stop.is_none());
        assert!(emu.snapshot().contains("frame1next"));
    }

    #[test]
    fn in_sync_update_is_true_between_bsu_and_esu() {
        let mut emu = Vt100Emulator::new(4, 10, 0, crate::graphics::DEFAULT_CAPTURE, false);
        feed_all(&mut emu, b"\x1b[?2026hpartial");
        assert!(emu.in_sync_update());
        assert!(!emu.mid_sequence()); // the escape itself is finished
        feed_all(&mut emu, b"\x1b[?2026l");
        assert!(!emu.in_sync_update());
    }

    #[test]
    fn snapshot_carries_out_of_band_terminal_state() {
        let emu = emu_with(b"\x1b]0;my app\x07\x1b[?1049h\x1b[?2004h\x1b[?1h\x1b[?1002h");
        let s = emu.snapshot();
        assert_eq!(s.title(), "my app");
        assert!(s.alternate_screen());
        assert!(s.bracketed_paste());
        assert!(s.application_cursor());
        assert_eq!(s.mouse_mode(), MouseMode::ButtonMotion);
    }

    #[test]
    fn snapshot_state_defaults_until_the_app_sets_it() {
        let emu = emu_with(b"plain");
        let s = emu.snapshot();
        assert_eq!(s.title(), "");
        assert!(!s.alternate_screen());
        assert!(!s.bracketed_paste());
        assert!(!s.application_cursor());
        assert_eq!(s.mouse_mode(), MouseMode::None);
    }

    /// Feed a stream into an emulator with `scrollback` rows of history.
    fn emu_with_history(scrollback: usize, bytes: &[u8]) -> Vt100Emulator {
        let mut emu =
            Vt100Emulator::new(4, 10, scrollback, crate::graphics::DEFAULT_CAPTURE, false);
        feed_all(&mut emu, bytes);
        emu
    }

    #[test]
    fn rows_scrolled_off_the_top_are_retained_in_order() {
        // A 4-row screen fed 7 lines: three scroll off.
        let emu = emu_with_history(100, b"one\r\ntwo\r\nthree\r\nfour\r\nfive\r\nsix\r\nseven");
        let s = emu.snapshot();
        assert_eq!(s.scrollback_rows(), 3);
        assert_eq!(s.scrollback_text(), "one\ntwo\nthree");
        assert_eq!(s.text(), "four\nfive\nsix\nseven");
        // The assertion an author actually writes: content reached the
        // terminal, wherever it currently sits.
        assert_eq!(s.full_text(), "one\ntwo\nthree\nfour\nfive\nsix\nseven");
        // The visible-screen queries stay visible-screen queries.
        assert!(!s.contains("one"));
        assert!(s.contains("seven"));
    }

    #[test]
    fn history_is_bounded_and_drops_its_oldest_rows() {
        // Ten rows, each ending in a newline, on a 4-row screen: seven
        // scroll off (row1..row7) and the cap of 3 keeps the newest three.
        let mut emu = Vt100Emulator::new(4, 10, 3, crate::graphics::DEFAULT_CAPTURE, false);
        for n in 1..=10 {
            feed_all(&mut emu, format!("row{n}\r\n").as_bytes());
        }
        let s = emu.snapshot();
        assert_eq!(s.scrollback_rows(), 3);
        assert_eq!(s.scrollback_text(), "row5\nrow6\nrow7");
        assert_eq!(s.text(), "row8\nrow9\nrow10\n");
        // row1..row4 are past the bound and gone — the honest limit.
        assert!(!s.full_text().contains("row4"));
        assert!(s.full_text().contains("row5"));
    }

    #[test]
    fn a_history_kept_at_the_cap_keeps_advancing() {
        // The rebuild path: once at the cap vt100's length stops changing,
        // so a naive "did the length grow?" check would freeze the history
        // at its first full window.
        let mut emu = Vt100Emulator::new(4, 10, 2, crate::graphics::DEFAULT_CAPTURE, false);
        feed_all(&mut emu, b"a\r\nb\r\nc\r\nd\r\ne\r\nf\r\n");
        assert_eq!(emu.snapshot().scrollback_text(), "b\nc");
        feed_all(&mut emu, b"g\r\nh\r\n");
        assert_eq!(emu.snapshot().scrollback_text(), "d\ne");
    }

    #[test]
    fn retention_off_keeps_nothing() {
        let emu = emu_with_history(0, b"one\r\ntwo\r\nthree\r\nfour\r\nfive");
        let s = emu.snapshot();
        assert_eq!(s.scrollback_rows(), 0);
        assert_eq!(s.scrollback_text(), "");
        // full_text is then just the visible screen.
        assert_eq!(s.full_text(), s.text());
    }

    #[test]
    fn the_alternate_screen_accumulates_no_history() {
        // A full-screen TUI owns its viewport and should cost nothing for a
        // feature it does not use. vt100 gives the alternate grid zero
        // scrollback of its own, which is what makes retention safe to
        // default on.
        let emu = emu_with_history(
            100,
            b"\x1b[?1049h one\r\ntwo\r\nthree\r\nfour\r\nfive\r\nsix",
        );
        assert_eq!(emu.snapshot().scrollback_rows(), 0);
    }

    #[test]
    fn history_rows_keep_the_width_they_were_captured_at() {
        // Documented decision (`Terminal::resize`): history is not reflowed
        // and not discarded. Rows captured before a narrowing resize keep
        // their width; rows captured after it have the new one; both sit in
        // the same history.
        let mut emu = Vt100Emulator::new(2, 10, 100, crate::graphics::DEFAULT_CAPTURE, false);
        feed_all(&mut emu, b"0123456789\r\nabcdefghij\r\nnext");
        assert_eq!(emu.snapshot().scrollback_text(), "0123456789");
        emu.set_size(2, 4);
        assert_eq!(
            emu.snapshot().scrollback_text(),
            "0123456789",
            "a captured row keeps its width; narrowing the screen must not \
             retroactively rewrite history"
        );
        // Two more rows at the new width scroll off; the old row is still
        // there, still ten wide, above the four-wide ones.
        feed_all(&mut emu, b"\r\nwxyz\r\nlast");
        let history = emu.snapshot().scrollback_text();
        let rows: Vec<&str> = history.lines().collect();
        assert_eq!(rows[0], "0123456789", "captured at 10 columns: {history}");
        assert!(
            rows[1..].iter().all(|row| row.chars().count() <= 4),
            "captured at 4 columns: {history}"
        );
        assert!(rows.len() >= 3, "{history}");
    }

    #[test]
    fn mouse_tracking_modes_are_reset_until_one_is_enabled() {
        // The state every application is in when it probes at startup.
        // Nothing was collapsed, so "reset" is a fact rather than a guess —
        // and answering it is what lets capability detection succeed.
        let emu = emu_with(b"plain");
        for mode in [9, 1000, 1002, 1003] {
            assert_eq!(emu.mode_state(mode), ModeState::Reset, "mode {mode}");
        }
    }

    #[test]
    fn each_tracking_mode_is_answered_on_its_own_evidence() {
        // crossterm's EnableMouseCapture: three modes in one breath. vt100
        // keeps only the last, and before the tracker held the set (#151)
        // the other two had to be answered "not recognized" — the only
        // honest reply to a question the state could not answer.
        let emu = emu_with(b"\x1b[?1000h\x1b[?1002h\x1b[?1003h");
        for mode in [1000, 1002, 1003] {
            assert_eq!(emu.mode_state(mode), ModeState::Set, "mode {mode}");
        }
        assert_eq!(emu.mode_state(9), ModeState::Reset, "never asked for");
        // The set is what was asked for; the protocol is vt100's collapse.
        let screen = emu.snapshot();
        assert_eq!(screen.mouse_mode(), MouseMode::AnyMotion);
        assert_eq!(
            screen.mouse_modes().iter().collect::<Vec<_>>(),
            [
                MouseMode::PressRelease,
                MouseMode::ButtonMotion,
                MouseMode::AnyMotion
            ]
        );

        // Releasing one member releases that member alone in the set, while
        // vt100 — like xterm — turns reporting off, since the protocol it
        // was reporting in is gone. Both facts are true; each is reported
        // where it belongs.
        let emu = emu_with(b"\x1b[?1000h\x1b[?1002h\x1b[?1003h\x1b[?1003l");
        assert_eq!(emu.mode_state(1003), ModeState::Reset);
        assert_eq!(emu.mode_state(1002), ModeState::Set);
        let screen = emu.snapshot();
        assert_eq!(screen.mouse_mode(), MouseMode::None);
        assert!(screen.mouse_modes().contains(MouseMode::ButtonMotion));

        // A list sets or clears every member it names, and a hard reset
        // empties the set.
        let emu = emu_with(b"\x1b[?1000;1002;1003h\x1b[?1000;1002l");
        assert_eq!(
            emu.snapshot().mouse_modes().iter().collect::<Vec<_>>(),
            [MouseMode::AnyMotion]
        );
        assert!(emu_with(b"\x1b[?1003h\x1bc")
            .snapshot()
            .mouse_modes()
            .is_empty());
    }

    #[test]
    fn turning_tracking_off_returns_every_mode_to_reset() {
        let emu = emu_with(b"\x1b[?1002h\x1b[?1002l");
        for mode in [9, 1000, 1002, 1003] {
            assert_eq!(emu.mode_state(mode), ModeState::Reset, "mode {mode}");
        }
    }

    #[test]
    fn set_size_resizes_the_grid() {
        let mut emu = emu_with(b"hello");
        emu.set_size(2, 5);
        let screen = emu.snapshot();
        assert_eq!(screen.size(), (5, 2));
        assert_eq!(screen.text(), "hello\n");
    }

    /// A 24-column emulator, the width the issue's reproductions use.
    fn wide_emu(bytes: &[u8]) -> Vt100Emulator {
        let mut emu = Vt100Emulator::new(2, 24, 0, crate::graphics::DEFAULT_CAPTURE, false);
        feed_all(&mut emu, bytes);
        emu
    }

    /// Where the cursor ended up, which is the whole of what a tab does.
    fn cursor_col(bytes: &[u8]) -> u16 {
        wide_emu(bytes).snapshot().cursor().1
    }

    #[test]
    fn a_plain_tab_still_lands_on_the_default_eighth_column() {
        // The rewrite takes `HT` over from vt100 entirely, so the behaviour
        // that was already right has to keep being right.
        let s = wide_emu(b"a\tb").snapshot();
        assert_eq!(s.row_text(0).trim_end(), "a       b", "{s}");
        assert_eq!(s.find("b"), Some((0, 8)));
        assert_eq!(cursor_col(b"\t\t"), 16);
    }

    /// The scope note from the issue, and the one test that proves the two
    /// tab implementations are not disagreeing: `HTS` sets a stop and a
    /// *plain* `\t` — not `CHT` — is what honours it.
    #[test]
    fn a_plain_tab_honours_a_stop_set_by_hts() {
        // Column 4 (`CSI 4 G` is one-based), set a stop, back to column 1.
        let s = wide_emu(b"\x1b[4G\x1bH\x1b[1Ga\tb").snapshot();
        assert_eq!(s.row_text(0).trim_end(), "a  b", "{s}");
        assert_eq!(s.find("b"), Some((0, 3)));
    }

    #[test]
    fn tbc_clears_one_stop_and_csi_3_g_clears_them_all() {
        // Standing on the default stop at column 8 and clearing it sends the
        // next tab on to 16 instead.
        assert_eq!(cursor_col(b"\x1b[9G\x1b[g\x1b[1G\t"), 16);
        assert_eq!(cursor_col(b"\x1b[9G\x1b[0g\x1b[1G\t"), 16);
        // With every stop gone a tab runs to the last column and stays.
        assert_eq!(cursor_col(b"\x1b[3g\t"), 23);
        assert_eq!(cursor_col(b"\x1b[3g\t\t\t"), 23);
    }

    #[test]
    fn cht_and_cbt_move_by_whole_stops() {
        assert_eq!(cursor_col(b"\x1b[2I"), 16);
        assert_eq!(cursor_col(b"\x1b[I"), 8);
        // Back-tab from a stop goes to the one before it. Written without a
        // character in the way, because a character advances the cursor and
        // the back-tab would then return to the stop it was standing on —
        // which is what xterm and alacritty both do, and what the issue's
        // second reproduction reads past.
        assert_eq!(cursor_col(b"\t\t\x1b[1Z"), 8);
        assert_eq!(cursor_col(b"\t\tX\x1b[1Z"), 16);
        assert_eq!(cursor_col(b"\t\t\x1b[2Z"), 0);
        // Nowhere left to go is column 0, not a wrap.
        assert_eq!(cursor_col(b"\x1b[9Z"), 0);
    }

    #[test]
    fn ris_and_decstr_restore_the_default_stops() {
        for reset in [&b"\x1bc"[..], b"\x1b[!p"] {
            let mut stream = b"\x1b[3g\x1b[4G\x1bH".to_vec();
            stream.extend_from_slice(reset);
            stream.extend_from_slice(b"\x1b[1G\t");
            assert_eq!(
                cursor_col(&stream),
                8,
                "the custom stop must not survive {reset:?}"
            );
        }
    }

    #[test]
    fn a_resize_extends_the_stops_into_the_new_columns() {
        let mut emu = wide_emu(b"\x1b[4G\x1bH");
        emu.set_size(2, 40);
        // The stop set before the resize is still there …
        feed_all(&mut emu, b"\x1b[1G\t");
        assert_eq!(emu.snapshot().cursor().1, 3);
        // … and the columns the grid did not have get the default pattern.
        feed_all(&mut emu, b"\x1b[25G\t");
        assert_eq!(emu.snapshot().cursor().1, 32);
    }

    /// The rewrite is fed to both parsers, so the attribute shadow moves
    /// with the primary grid. `snapshot` debug-asserts they agree, which is
    /// what this drives — a tab inside a styled span is the shape that would
    /// break if only one of them were told.
    #[test]
    fn a_tab_inside_a_styled_span_keeps_the_shadow_in_step() {
        let s = wide_emu(b"\x1b[5m\x1b[4G\x1bH\x1b[1Ga\tb\x1b[0m").snapshot();
        assert_eq!(s.find("b"), Some((0, 3)));
        assert!(s.cell(0, 3).unwrap().style().blink, "{s}");
    }
}