turbo-debug-console 0.5.0

Turbo Vision monitor that renders a model-token stream over a socket
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
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
// Copyright (c) 2026 Enzo Lombardi
// SPDX-License-Identifier: MIT

//! A scrollback view over styled cells, one `Vec<Cell>` per line.

use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};

use turbo_vision::core::draw::{Cell, DrawBuffer};
use turbo_vision::core::event::{
    Event, EventType, KB_DOWN, KB_END, KB_ESC, KB_HOME, KB_PGDN, KB_PGUP, KB_UP, MB_LEFT_BUTTON,
};
use turbo_vision::core::geometry::{Point, Rect};
use turbo_vision::core::palette::{Attr, TvColor};
use turbo_vision::core::state::{GF_GROW_HI_X, GF_GROW_HI_Y, GrowFlags};
use turbo_vision::terminal::Terminal;
use turbo_vision::views::view::{View, write_line_to_terminal};

/// A caret position in the wrapped scrollback: an absolute display-row index
/// (into `iter_rows()`, so it survives scrolling) and a column, where the
/// column is a cell index in that row (`draw` maps cell index 1:1 to screen
/// column). A caret at `col` sits just before the cell at `col`.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
struct SelPos {
    row: usize,
    col: usize,
}

/// The shape a selection takes.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum SelMode {
    /// Everything between the two carets in reading order, wrapping at the
    /// end of each row.
    Stream,
    /// The rectangular column band between the two carets, taken from every
    /// row they span.
    Block,
}

/// An active selection between two carets.
///
/// The shape is fixed when the selection starts, the way `Editor` fixes its
/// own `selection_mode`: toggling Edit > Block mode mid-drag would otherwise
/// change what is already highlighted under the pointer.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
struct Selection {
    anchor: SelPos,
    head: SelPos,
    mode: SelMode,
}

impl SelMode {
    /// The shape implied by the global block-edit mode (Edit > Block mode).
    fn from_global() -> Self {
        if turbo_vision::core::state::block_edit_mode() {
            Self::Block
        } else {
            Self::Stream
        }
    }
}

/// Swaps foreground and background, preserving text style — the highlight for
/// a selected cell.
fn reverse(attr: Attr) -> Attr {
    Attr::new(attr.bg, attr.fg).with_style(attr.style)
}

/// The two carets in reading order (top-to-bottom, left-to-right).
fn order(a: SelPos, b: SelPos) -> (SelPos, SelPos) {
    if (a.row, a.col) <= (b.row, b.col) {
        (a, b)
    } else {
        (b, a)
    }
}

/// The row span and half-open column band of a rectangular selection, as
/// `(top, bottom, left, right)`. Either caret may be the top-left one.
fn block_bounds(sel: Selection) -> (usize, usize, usize, usize) {
    let (a, b) = (sel.anchor, sel.head);
    (
        a.row.min(b.row),
        a.row.max(b.row),
        a.col.min(b.col),
        a.col.max(b.col),
    )
}

/// A base character immediately followed by U+FE0F (the emoji presentation
/// selector, VS-16) or U+FE0E (the text presentation selector, VS-15) forms
/// one *presentation sequence* whose combined width can differ from the
/// base character's own width in isolation. This is exactly the shape of
/// plank's tool-call banner glyph (`🛠️` = U+1F6E0 + U+FE0F): the bare
/// wrench is East-Asian-Width `Neutral` (width 1), but the fully-qualified
/// emoji sequence the model actually emits is double-width. `unicode_width`
/// only resolves this at the *string* level (`UnicodeWidthStr`), not per
/// `char`, so a two-character lookahead is required to catch it — this is
/// still the crate doing the Unicode-correctness work; nothing here is a
/// hand-rolled codepoint table.
const PRESENTATION_SELECTORS: [char; 2] = ['\u{FE0F}', '\u{FE0E}'];

/// Normalizes a naive, one-`Cell`-per-`char` line into one `Cell` per
/// terminal *column* — the invariant every other method in this module
/// relies on (row width, wrapping's column-accurate break points, and
/// `draw`'s column count).
///
/// A double-width character (an emoji, a CJK glyph) keeps its real `char`
/// in the first cell and gets a filler cell for each additional column,
/// mirroring `turbo_vision`'s own `DrawBuffer::move_str` convention: the
/// terminal's cell-diffing flush already knows to skip a `'\0'` when
/// encoding output, so an invented filler paints as blank if ever exposed
/// (e.g. wrapping is careful never to cut a wide character in half, but if
/// it ever did, this is what would be exposed) rather than emitting half a
/// glyph. When the second column instead comes from a real
/// trailing presentation selector, that selector's own character is kept
/// as the filler — it is a genuine, zero-advance character, not a padding
/// artifact, so `plain_text` must still hand it back on Save As.
///
/// A zero-width character (a combining mark, a selector whose sequence
/// collapses to width 0) occupies no column and is dropped — again
/// matching `move_str`, and this module's only way to keep the stored
/// column count equal to the true rendered width without a codepoint-range
/// table of our own.
///
/// Idempotent: a spacer cell (`ch == '\0'`) already produced by a previous
/// call passes through unchanged, so re-normalizing already-normalized
/// cells (e.g. lines rebuilt from `styled_lines()`) is harmless.
fn normalize_line(cells: &[Cell]) -> Vec<Cell> {
    let mut out = Vec::with_capacity(cells.len());
    let mut i = 0;
    while i < cells.len() {
        let cell = cells[i];
        if cell.ch == '\0' {
            out.push(cell);
            i += 1;
            continue;
        }

        let next = cells.get(i + 1).copied();
        let selector = next.filter(|n| PRESENTATION_SELECTORS.contains(&n.ch));

        let width = if let Some(sel) = selector {
            let mut seq = String::with_capacity(cell.ch.len_utf8() + sel.ch.len_utf8());
            seq.push(cell.ch);
            seq.push(sel.ch);
            seq.width()
        } else {
            cell.ch.width().unwrap_or(0)
        };

        if width == 0 {
            i += if selector.is_some() { 2 } else { 1 };
            continue;
        }

        out.push(cell);
        if let Some(sel) = selector {
            out.push(sel);
            for _ in 2..width {
                out.push(Cell::new('\0', cell.attr));
            }
            i += 2;
        } else {
            for _ in 1..width {
                out.push(Cell::new('\0', cell.attr));
            }
            i += 1;
        }
    }
    out
}

/// Rows scrolled per mouse-wheel notch.
const WHEEL_STEP: usize = 3;

/// Columns reserved at the right edge of the view for the vertical scrollbar.
const SCROLLBAR_WIDTH: usize = 1;

/// Default scrollback depth.
pub const DEFAULT_MAX_LINES: usize = 10_000;

/// Splits one width-normalized logical line (one `Cell` per terminal column,
/// per `normalize_line`'s invariant) into the display rows it wraps to at
/// `width` columns.
///
/// Breaks at the last whitespace cell at or before the width boundary when
/// one exists in the row being filled; otherwise breaks exactly at `width`.
/// Because `cells` is already column-normalized, a wrap point chosen this
/// way always falls on a column boundary and never between a double-width
/// character's leading cell and its filler, since a filler cell (`ch ==
/// '\0'`) is never itself whitespace and so is never chosen as, or split
/// from, a break point ahead of its owner.
///
/// An empty line still yields one (empty) row, matching a real terminal:
/// a blank logical line occupies one blank display row, not zero.
fn wrap_cells(cells: &[Cell], width: usize) -> Vec<Vec<Cell>> {
    if width == 0 || cells.is_empty() {
        return vec![cells.to_vec()];
    }

    let mut rows = Vec::new();
    let mut rest = cells;
    while rest.len() > width {
        // Search for a break point: the last whitespace cell whose index is
        // < width, scanning backwards from width - 1. A filler cell ('\0')
        // is skipped as a candidate break (it is never whitespace) but does
        // not stop the scan.
        let mut break_at = None;
        for i in (0..width).rev() {
            if rest[i].ch.is_whitespace() {
                break_at = Some(i);
                break;
            }
        }
        if let Some(i) = break_at {
            rows.push(rest[..i].to_vec());
            rest = &rest[i + 1..]; // drop the whitespace cell itself
        } else {
            // A plain character-break cut at `width` could land between a
            // double-width character's leading cell and its filler ('\0');
            // if so, pull the cut back one column so the whole glyph moves
            // to the next row instead of splitting it.
            let mut cut = width;
            if cut > 1 && rest.get(cut).is_some_and(|c| c.ch == '\0') {
                cut -= 1;
            }
            rows.push(rest[..cut].to_vec());
            rest = &rest[cut..];
        }
    }
    rows.push(rest.to_vec());
    rows
}

/// A scrollback of styled lines, with autoscroll that releases when the user
/// scrolls back and re-arms at the bottom.
#[derive(Debug)]
pub struct StreamView {
    bounds: Rect,
    /// How this view follows its parent when the terminal is resized.
    ///
    /// `View`'s default is 0, meaning fixed, and a fixed view is skipped by
    /// the desktop's resize cascade: the window frame would resize around a
    /// scrollback still wrapped for the old width. `HI_X | HI_Y` pins the
    /// top-left and moves the bottom-right edge, which is what a view that
    /// fills its window wants.
    grow_mode: GrowFlags,
    /// Completed lines, oldest first. This is the source of truth: the log
    /// text as the producer sent it, one entry per logical line, never
    /// baked with this window's current wrap points. `plain_text()` reads
    /// from here, not from `wrapped`.
    lines: Vec<Vec<Cell>>,
    /// The line currently streaming in, not yet terminated by a newline.
    partial: Option<Vec<Cell>>,
    /// Display rows for `lines`, in order, each logical line's rows
    /// contiguous. `draw` and all scroll arithmetic read only from here (and
    /// from `partial_wrapped` below), never from `lines` directly.
    wrapped: Vec<Vec<Cell>>,
    /// How many display rows in `wrapped` each entry of `lines` currently
    /// occupies, parallel to `lines`. Lets `trim` drop exactly the rows a
    /// dropped logical line contributed without re-wrapping everything.
    row_counts: Vec<usize>,
    /// Display rows for the in-progress `partial` line, wrapped the same
    /// way; kept separate from `wrapped` because `set_partial` replaces
    /// rather than appends.
    partial_wrapped: Vec<Vec<Cell>>,
    /// Bounds by logical lines, not display rows: a narrower window wraps
    /// the same history into more rows, and bounding by rows would make a
    /// narrow window silently forget more history than a wide one for the
    /// same underlying stream. Logical-line count is the stable, resize-
    /// independent budget.
    max_lines: usize,
    /// Index of the topmost displayed row, in `wrapped`.
    top: usize,
    /// True while the view follows the tail.
    follow: bool,
    fill: Attr,
    /// The active text selection, if any. Positions are in absolute
    /// wrapped-row coordinates (see [`SelPos`]). Dropped whenever the buffer
    /// mutates, since row indices would otherwise dangle.
    selection: Option<Selection>,
    /// True while the scrollbar thumb is being dragged with the mouse.
    dragging_thumb: bool,
}

impl StreamView {
    #[must_use]
    pub fn new(bounds: Rect) -> Self {
        Self {
            bounds,
            grow_mode: GF_GROW_HI_X | GF_GROW_HI_Y,
            lines: Vec::new(),
            partial: None,
            wrapped: Vec::new(),
            row_counts: Vec::new(),
            partial_wrapped: Vec::new(),
            max_lines: DEFAULT_MAX_LINES,
            top: 0,
            follow: true,
            fill: Attr::new(TvColor::LightGray, TvColor::Black),
            selection: None,
            dragging_thumb: false,
        }
    }

    /// Width of the text area: the view minus the scrollbar column.
    fn width(&self) -> usize {
        usize::try_from(self.bounds.width())
            .unwrap_or(0)
            .saturating_sub(SCROLLBAR_WIDTH)
    }

    /// Screen column of the scrollbar.
    fn scrollbar_x(&self) -> i16 {
        self.bounds.b.x - 1
    }

    pub fn set_max_lines(&mut self, n: usize) {
        self.max_lines = n.max(1);
        self.trim();
    }

    /// Appends a completed line.
    pub fn push_line(&mut self, cells: &[Cell]) {
        // Row indices shift when the buffer grows/trims, so a held selection
        // would dangle; drop it.
        self.selection = None;
        let normalized = normalize_line(cells);
        let rows = wrap_cells(&normalized, self.width());
        self.row_counts.push(rows.len());
        self.wrapped.extend(rows);
        self.lines.push(normalized);
        self.trim();
        if self.follow {
            self.scroll_to_bottom();
        }
    }

    /// Replaces the in-progress line. Called on every repaint while a line is
    /// still streaming, so it must overwrite rather than append.
    pub fn set_partial(&mut self, cells: &[Cell]) {
        let cells = normalize_line(cells);
        if cells.is_empty() {
            self.partial = None;
            self.partial_wrapped.clear();
        } else {
            self.partial_wrapped = wrap_cells(&cells, self.width());
            self.partial = Some(cells);
        }
        if self.follow {
            self.scroll_to_bottom();
        }
    }

    pub fn clear(&mut self) {
        self.lines.clear();
        self.partial = None;
        self.wrapped.clear();
        self.row_counts.clear();
        self.partial_wrapped.clear();
        self.top = 0;
        self.follow = true;
        self.selection = None;
    }

    /// Total displayed lines, including the in-progress one.
    #[must_use]
    pub fn line_count(&self) -> usize {
        self.lines.len() + usize::from(self.partial.is_some())
    }

    /// Total display rows currently shown, including the in-progress line's
    /// wrapped rows. This is what scroll arithmetic (`page`, `max_top`, and
    /// the keyboard handlers) counts, so scrolling lands correctly wherever
    /// a wrapped long line pushes rows out of alignment with logical lines.
    #[must_use]
    pub fn row_count(&self) -> usize {
        self.wrapped.len() + self.partial_wrapped.len()
    }

    /// Visible rows, i.e. the view height.
    fn page(&self) -> usize {
        usize::try_from(self.bounds.height()).unwrap_or(0).max(1)
    }

    fn max_top(&self) -> usize {
        self.row_count().saturating_sub(self.page())
    }

    /// Rewraps every logical line and the in-progress partial at the current
    /// width, rebuilding `wrapped`, `row_counts` and `partial_wrapped` from
    /// scratch. Needed whenever the width itself changes (a resize), since
    /// every existing wrap point can be stale in either direction.
    fn rewrap(&mut self) {
        let width = self.width();
        self.wrapped.clear();
        self.row_counts.clear();
        for line in &self.lines {
            let rows = wrap_cells(line, width);
            self.row_counts.push(rows.len());
            self.wrapped.extend(rows);
        }
        self.partial_wrapped = match &self.partial {
            Some(cells) => wrap_cells(cells, width),
            None => Vec::new(),
        };
    }

    pub fn scroll_to_bottom(&mut self) {
        self.top = self.max_top();
        self.follow = true;
    }

    pub fn scroll_to_top(&mut self) {
        self.top = 0;
        self.follow = false;
    }

    pub fn scroll_up(&mut self, n: usize) {
        self.top = self.top.saturating_sub(n);
        self.follow = false;
    }

    pub fn scroll_down(&mut self, n: usize) {
        self.set_top(self.top + n);
    }

    /// Scrolls so that `top` is the first visible row, clamped to the
    /// scrollback; re-arms autoscroll when that lands on the last page.
    pub fn set_top(&mut self, top: usize) {
        self.top = top.min(self.max_top());
        self.follow = self.top == self.max_top();
    }

    /// Index of the topmost visible row.
    #[must_use]
    pub fn top(&self) -> usize {
        self.top
    }

    // ---- scrollbar ----

    /// Track cells between the two arrows (the arrows are dropped when the
    /// view is too short to hold them).
    fn track_len(&self) -> usize {
        let page = self.page();
        if page >= 3 { page - 2 } else { page }
    }

    /// Row offset of the first track cell from the top of the view.
    fn track_start(&self) -> usize {
        usize::from(self.page() >= 3)
    }

    /// `(thumb_start, thumb_len)` in track cells, or `None` when everything
    /// fits and there is nothing to scroll.
    fn thumb(&self) -> Option<(usize, usize)> {
        let rows = self.row_count();
        let page = self.page();
        let track = self.track_len();
        if rows <= page || track == 0 {
            return None;
        }
        let len = (track * page / rows).clamp(1, track);
        let usable = track - len;
        let start = if usable == 0 {
            0
        } else {
            (self.top * usable).div_ceil(self.max_top()).min(usable)
        };
        Some((start, len))
    }

    /// Maps a screen row on the scrollbar track to a `top`, for thumb drags.
    fn top_for_track_row(&self, y: i16) -> usize {
        let Some((_, len)) = self.thumb() else {
            return self.top;
        };
        let usable = self.track_len() - len;
        if usable == 0 {
            return self.top;
        }
        let rel = usize::try_from(y - self.bounds.a.y)
            .unwrap_or(0)
            .saturating_sub(self.track_start())
            .min(usable);
        rel * self.max_top() / usable
    }

    fn in_scrollbar(&self, pos: Point) -> bool {
        pos.x == self.scrollbar_x()
            && pos.y >= self.bounds.a.y
            && pos.y < self.bounds.b.y
            && self.bounds.width() > 0
    }

    fn in_view(&self, pos: Point) -> bool {
        pos.x >= self.bounds.a.x
            && pos.x < self.bounds.b.x
            && pos.y >= self.bounds.a.y
            && pos.y < self.bounds.b.y
    }

    /// A left click on the scrollbar: arrows step a row, the track pages,
    /// the thumb starts a drag.
    fn scrollbar_click(&mut self, y: i16) {
        let rel = usize::try_from(y - self.bounds.a.y).unwrap_or(0);
        let page = self.page();
        if page >= 3 && rel == 0 {
            self.scroll_up(1);
        } else if page >= 3 && rel == page - 1 {
            self.scroll_down(1);
        } else if let Some((start, len)) = self.thumb() {
            let track_row = rel - self.track_start();
            if track_row < start {
                self.scroll_up(page);
            } else if track_row >= start + len {
                self.scroll_down(page);
            } else {
                self.dragging_thumb = true;
            }
        }
    }

    fn draw_scrollbar(&self, terminal: &mut Terminal) {
        if self.bounds.width() <= 0 {
            return;
        }
        let track_attr = Attr::new(TvColor::DarkGray, self.fill.bg);
        let thumb_attr = Attr::new(TvColor::LightGray, self.fill.bg);
        let page = self.page();
        let thumb = self.thumb();
        let track_start = self.track_start();
        let x = self.scrollbar_x();
        for row in 0..page {
            let (ch, attr) = if page >= 3 && row == 0 {
                ('', thumb_attr)
            } else if page >= 3 && row == page - 1 {
                ('', thumb_attr)
            } else {
                match thumb {
                    Some((start, len))
                        if row - track_start >= start && row - track_start < start + len =>
                    {
                        ('', thumb_attr)
                    }
                    _ => ('', track_attr),
                }
            };
            let mut buf = DrawBuffer::new(1);
            buf.put_char(0, ch, attr);
            let y = self.bounds.a.y + i16::try_from(row).unwrap_or(i16::MAX);
            write_line_to_terminal(terminal, x, y, &buf);
        }
    }

    #[must_use]
    pub fn is_at_bottom(&self) -> bool {
        self.follow
    }

    // ---- selection ----

    /// Selects the entire scrollback in stream mode. Leaves no selection if
    /// the buffer is empty.
    pub fn select_all(&mut self) {
        let rows = self.row_count();
        if rows == 0 {
            self.selection = None;
            return;
        }
        let last = rows - 1;
        let last_len = self.row_at(last).map_or(0, Vec::len);
        self.selection = Some(Selection {
            anchor: SelPos { row: 0, col: 0 },
            head: SelPos {
                row: last,
                col: last_len,
            },
            // Select All means the whole scrollback, never a column band.
            mode: SelMode::Stream,
        });
    }

    /// Sets a selection between two carets `(row, col)`. Order-independent:
    /// anchor and head may be given in either order.
    pub fn set_selection(&mut self, anchor: (usize, usize), head: (usize, usize)) {
        self.selection = Some(Selection {
            anchor: SelPos {
                row: anchor.0,
                col: anchor.1,
            },
            head: SelPos {
                row: head.0,
                col: head.1,
            },
            mode: SelMode::from_global(),
        });
    }

    pub fn clear_selection(&mut self) {
        self.selection = None;
    }

    #[must_use]
    pub fn has_selection(&self) -> bool {
        self.selection.is_some()
    }

    /// The selected text, or `None` when there is no selection. Logical lines
    /// are reconstructed: a soft wrap within a line does not become a newline.
    #[must_use]
    pub fn selected_text(&self) -> Option<String> {
        let sel = self.selection?;
        if sel.mode == SelMode::Block {
            return Some(self.block_text(sel));
        }
        let (start, end) = order(sel.anchor, sel.head);
        let mut out = String::new();
        for row in start.row..=end.row {
            let Some(cells) = self.row_at(row) else {
                continue;
            };
            let from = if row == start.row { start.col } else { 0 }.min(cells.len());
            let to = if row == end.row { end.col } else { cells.len() }.min(cells.len());
            if row > start.row && self.row_is_logical_start(row) {
                out.push('\n');
            }
            out.extend(
                cells[from..to.max(from)]
                    .iter()
                    .map(|c| c.ch)
                    .filter(|&ch| ch != '\0'),
            );
        }
        Some(out)
    }

    /// The text of a rectangular selection: the column band `[left, right)`
    /// taken from every row the two carets span, one line per row. Rows
    /// shorter than `left` contribute an empty line, so the block keeps its
    /// shape when it is pasted elsewhere.
    fn block_text(&self, sel: Selection) -> String {
        let (top, bottom, left, right) = block_bounds(sel);
        let mut out = String::new();
        for row in top..=bottom {
            if row > top {
                out.push('\n');
            }
            let Some(cells) = self.row_at(row) else {
                continue;
            };
            let from = left.min(cells.len());
            let to = right.min(cells.len());
            out.extend(
                cells[from..to.max(from)]
                    .iter()
                    .map(|c| c.ch)
                    .filter(|&ch| ch != '\0'),
            );
        }
        out
    }

    fn row_at(&self, idx: usize) -> Option<&Vec<Cell>> {
        self.iter_rows().nth(idx)
    }

    /// Maps a screen position to a caret in the scrollback, or `None` if it
    /// falls outside the view or below the last row.
    ///
    /// In stream mode the column is clamped to the hit row's length, so
    /// dragging past a line's end caps at its end. A block selection keeps
    /// the raw column instead: its column band is the same on every row it
    /// spans, including rows too short to reach it.
    fn hit(&self, pos: Point, mode: SelMode) -> Option<SelPos> {
        let x = usize::try_from(pos.x - self.bounds.a.x).ok()?;
        let y = usize::try_from(pos.y - self.bounds.a.y).ok()?;
        if y >= self.page() || x >= self.width() {
            return None;
        }
        let abs_row = self.top + y;
        let len = self.row_at(abs_row)?.len();
        let col = match mode {
            SelMode::Stream => x.min(len),
            SelMode::Block => x,
        };
        Some(SelPos { row: abs_row, col })
    }

    /// Whether the cell at absolute wrapped-row `abs_row`, column `col` (a cell
    /// index) lies inside the current selection.
    fn is_selected(&self, abs_row: usize, col: usize) -> bool {
        let Some(sel) = self.selection else {
            return false;
        };
        if sel.mode == SelMode::Block {
            let (top, bottom, left, right) = block_bounds(sel);
            return (top..=bottom).contains(&abs_row) && (left..right).contains(&col);
        }
        let (s, e) = order(sel.anchor, sel.head);
        (abs_row, col) >= (s.row, s.col) && (abs_row, col) < (e.row, e.col)
    }

    /// Whether absolute wrapped-row `abs_row` is the first row of a logical
    /// line (as opposed to a soft-wrap continuation of the one above).
    fn row_is_logical_start(&self, abs_row: usize) -> bool {
        let mut offset = 0;
        for &count in &self.row_counts {
            if abs_row == offset {
                return true;
            }
            offset += count;
        }
        // `offset` now equals `wrapped.len()`, where the partial line begins.
        abs_row == offset
    }

    /// The whole scrollback with attributes stripped, for File > Save As.
    #[must_use]
    pub fn plain_text(&self) -> String {
        let mut out = String::new();
        for (i, line) in self.iter_lines().enumerate() {
            if i > 0 {
                out.push('\n');
            }
            // Spacer cells (the second column of a wide char) carry no
            // text of their own; skip them so the saved text round-trips
            // the original characters with no padding artifacts.
            out.extend(line.iter().map(|c| c.ch).filter(|&ch| ch != '\0'));
        }
        out
    }

    /// The whole scrollback with attributes intact, for tests and golden files.
    #[must_use]
    pub fn styled_lines(&self) -> Vec<Vec<Cell>> {
        self.iter_lines().cloned().collect()
    }

    fn iter_lines(&self) -> impl Iterator<Item = &Vec<Cell>> {
        self.lines.iter().chain(self.partial.iter())
    }

    /// Display rows currently on screen or scrolled to, in order: the wrapped
    /// completed lines followed by the wrapped in-progress line.
    fn iter_rows(&self) -> impl Iterator<Item = &Vec<Cell>> {
        self.wrapped.iter().chain(self.partial_wrapped.iter())
    }

    /// Bounds the scrollback by logical lines (see `max_lines`'s doc
    /// comment), dropping the oldest ones and exactly the display rows they
    /// contributed to `wrapped`.
    fn trim(&mut self) {
        if self.lines.len() > self.max_lines {
            let drop = self.lines.len() - self.max_lines;
            self.lines.drain(..drop);
            let dropped_rows: usize = self.row_counts.drain(..drop).sum();
            self.wrapped.drain(..dropped_rows);
            self.top = self.top.saturating_sub(dropped_rows);
        }
    }
}

impl View for StreamView {
    fn bounds(&self) -> Rect {
        self.bounds
    }

    fn set_bounds(&mut self, bounds: Rect) {
        let width_changed = self.bounds.width() != bounds.width();
        self.bounds = bounds;
        if width_changed {
            self.rewrap();
        }
        if self.follow {
            self.scroll_to_bottom();
        } else {
            self.top = self.top.min(self.max_top());
        }
    }

    fn draw(&mut self, terminal: &mut Terminal) {
        if self.bounds.height() <= 0 {
            return;
        }
        let width = self.width();
        let page = self.page();
        let rows: Vec<&Vec<Cell>> = self.iter_rows().skip(self.top).take(page).collect();

        for row in 0..page {
            let mut buf = DrawBuffer::new(width);
            for i in 0..width {
                buf.put_char(i, ' ', self.fill);
            }
            if let Some(line) = rows.get(row) {
                let abs_row = self.top + row;
                for (i, cell) in line.iter().take(width).enumerate() {
                    let attr = if self.is_selected(abs_row, i) {
                        reverse(cell.attr)
                    } else {
                        cell.attr
                    };
                    buf.put_char(i, cell.ch, attr);
                }
            }
            let y = self.bounds.a.y + i16::try_from(row).unwrap_or(i16::MAX);
            write_line_to_terminal(terminal, self.bounds.a.x, y, &buf);
        }
        self.draw_scrollbar(terminal);
    }

    fn handle_event(&mut self, event: &mut Event) {
        match event.what {
            EventType::Keyboard => {
                let page = self.page();
                match event.key_code {
                    KB_UP => self.scroll_up(1),
                    KB_DOWN => self.scroll_down(1),
                    KB_PGUP => self.scroll_up(page),
                    KB_PGDN => self.scroll_down(page),
                    KB_HOME => self.scroll_to_top(),
                    KB_END => self.scroll_to_bottom(),
                    KB_ESC if self.selection.is_some() => self.clear_selection(),
                    _ => return,
                }
                event.clear();
            }
            EventType::MouseWheelUp if self.in_view(event.mouse.pos) => {
                self.scroll_up(WHEEL_STEP);
                event.clear();
            }
            EventType::MouseWheelDown if self.in_view(event.mouse.pos) => {
                self.scroll_down(WHEEL_STEP);
                event.clear();
            }
            EventType::MouseDown
                if event.mouse.buttons & MB_LEFT_BUTTON != 0
                    && self.in_scrollbar(event.mouse.pos) =>
            {
                self.scrollbar_click(event.mouse.pos.y);
                event.clear();
            }
            EventType::MouseMove | EventType::MouseAuto if self.dragging_thumb => {
                let top = self.top_for_track_row(event.mouse.pos.y);
                self.set_top(top);
                event.clear();
            }
            EventType::MouseDown if event.mouse.buttons & MB_LEFT_BUTTON != 0 => {
                let mode = SelMode::from_global();
                let Some(pos) = self.hit(event.mouse.pos, mode) else {
                    return;
                };
                self.selection = Some(Selection {
                    anchor: pos,
                    head: pos,
                    mode,
                });
                event.clear();
            }
            EventType::MouseMove | EventType::MouseAuto
                if event.mouse.buttons & MB_LEFT_BUTTON != 0 =>
            {
                if let Some(mut sel) = self.selection
                    && let Some(pos) = self.hit(event.mouse.pos, sel.mode)
                {
                    sel.head = pos;
                    self.selection = Some(sel);
                    event.clear();
                }
            }
            EventType::MouseUp => {
                self.dragging_thumb = false;
                // A press with no drag (anchor == head) is a plain click: it
                // selects nothing, so drop the empty selection.
                if let Some(sel) = self.selection
                    && sel.anchor == sel.head
                {
                    self.selection = None;
                }
                event.clear();
            }
            _ => {}
        }
    }

    fn grow_mode(&self) -> GrowFlags {
        self.grow_mode
    }

    fn set_grow_mode(&mut self, grow_mode: GrowFlags) {
        self.grow_mode = grow_mode;
    }

    fn can_focus(&self) -> bool {
        true
    }

    fn get_palette(&self) -> Option<turbo_vision::core::palette::Palette> {
        // Cells already carry resolved `Attr`s (from `AnsiLineAssembler`), so
        // there is no logical-color index for a palette to remap.
        None
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io;
    use std::time::Duration;
    use turbo_vision::core::palette::TvColor;
    use turbo_vision::terminal::Backend;

    fn line(s: &str) -> Vec<Cell> {
        s.chars()
            .map(|c| Cell::new(c, Attr::new(TvColor::LightGray, TvColor::Black)))
            .collect()
    }

    /// Test views are sized one column wider than the text they are meant to
    /// hold: the rightmost column is the scrollbar, not text.
    fn view() -> StreamView {
        StreamView::new(Rect::new(0, 0, 41, 10))
    }

    #[test]
    fn select_all_extracts_logical_lines_without_soft_wrap_newlines() {
        let mut v = StreamView::new(Rect::new(0, 0, 11, 10));
        v.push_line(&line("hello"));
        v.push_line(&line("abcdefghijABCDEFGHIJ")); // 20 cols wraps at width 10
        v.select_all();
        assert_eq!(
            v.selected_text().unwrap(),
            "hello\nabcdefghijABCDEFGHIJ",
            "soft wraps within a logical line must not become newlines"
        );
    }

    #[test]
    fn stream_selection_spans_from_anchor_to_head_across_a_line_break() {
        let mut v = view();
        v.push_line(&line("hello"));
        v.push_line(&line("world"));
        // caret before col 2 of row 0 to caret before col 3 of row 1
        v.set_selection((0, 2), (1, 3));
        assert_eq!(v.selected_text().unwrap(), "llo\nwor");
    }

    #[test]
    fn stream_selection_is_order_independent() {
        let mut v = view();
        v.push_line(&line("hello"));
        v.push_line(&line("world"));
        v.set_selection((1, 3), (0, 2)); // reversed
        assert_eq!(v.selected_text().unwrap(), "llo\nwor");
    }

    #[test]
    fn no_selection_yields_no_text() {
        let mut v = view();
        v.push_line(&line("hello"));
        assert!(v.selected_text().is_none());
        assert!(!v.has_selection());
    }

    #[test]
    fn selected_cells_render_reverse_video() {
        let mut v = StreamView::new(Rect::new(0, 0, 8, 4));
        v.push_line(&line("abcd"));
        v.set_selection((0, 1), (0, 3)); // 'b','c'
        let mut terminal = fake_terminal(20, 10);
        v.draw(&mut terminal);
        let a = terminal.read_cell(0, 0).unwrap(); // unselected 'a'
        let b = terminal.read_cell(1, 0).unwrap(); // selected 'b'
        assert_eq!(b.ch, 'b');
        assert_eq!(b.attr.fg, a.attr.bg, "selected fg is the normal bg");
        assert_eq!(b.attr.bg, a.attr.fg, "selected bg is the normal fg");
        // The cell just past the selection ('d' region, col 3) is normal.
        let d = terminal.read_cell(3, 0).unwrap();
        assert_eq!(d.attr.fg, a.attr.fg, "col 3 is outside [1,3), so normal");
    }

    #[test]
    fn mouse_drag_creates_a_stream_selection() {
        let mut v = view();
        v.push_line(&line("hello"));
        v.push_line(&line("world"));
        let mut down = Event::mouse(
            EventType::MouseDown,
            Point::new(2, 0),
            MB_LEFT_BUTTON,
            false,
        );
        v.handle_event(&mut down);
        let mut mv = Event::mouse(
            EventType::MouseMove,
            Point::new(3, 1),
            MB_LEFT_BUTTON,
            false,
        );
        v.handle_event(&mut mv);
        let mut up = Event::mouse(EventType::MouseUp, Point::new(3, 1), 0, false);
        v.handle_event(&mut up);
        assert_eq!(v.selected_text().unwrap(), "llo\nwor");
    }

    /// Serializes the tests that flip the process-wide block-edit mode, and
    /// clears it again when the guard drops.
    struct BlockModeGuard(#[allow(dead_code)] std::sync::MutexGuard<'static, ()>);

    impl BlockModeGuard {
        fn on() -> Self {
            static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
            let guard = LOCK
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            turbo_vision::core::state::set_block_edit_mode(true);
            Self(guard)
        }
    }

    impl Drop for BlockModeGuard {
        fn drop(&mut self) {
            turbo_vision::core::state::set_block_edit_mode(false);
        }
    }

    #[test]
    fn block_mode_selects_a_column_band_from_every_row_it_spans() {
        let _guard = BlockModeGuard::on();
        let mut v = view();
        v.push_line(&line("abcdef"));
        v.push_line(&line("gh"));
        v.push_line(&line("klmnop"));
        // Cols 2..5 of rows 0..=2. "gh" is too short to reach the band.
        v.set_selection((0, 2), (2, 5));
        assert_eq!(
            v.selected_text().unwrap(),
            "cde

mno"
        );
    }

    #[test]
    fn a_block_drag_keeps_its_column_band_over_a_short_row() {
        let _guard = BlockModeGuard::on();
        let mut v = view();
        v.push_line(&line("abcdef"));
        v.push_line(&line("gh"));
        v.push_line(&line("klmnop"));
        let mut down = Event::mouse(
            EventType::MouseDown,
            Point::new(2, 0),
            MB_LEFT_BUTTON,
            false,
        );
        v.handle_event(&mut down);
        // The drag passes over "gh", whose length would clamp a stream caret
        // to column 2 and collapse the band.
        let mut mv = Event::mouse(
            EventType::MouseMove,
            Point::new(5, 1),
            MB_LEFT_BUTTON,
            false,
        );
        v.handle_event(&mut mv);
        let mut mv = Event::mouse(
            EventType::MouseMove,
            Point::new(5, 2),
            MB_LEFT_BUTTON,
            false,
        );
        v.handle_event(&mut mv);
        let mut up = Event::mouse(EventType::MouseUp, Point::new(5, 2), 0, false);
        v.handle_event(&mut up);
        assert_eq!(
            v.selected_text().unwrap(),
            "cde

mno"
        );
    }

    #[test]
    fn block_mode_highlights_only_the_column_band() {
        let _guard = BlockModeGuard::on();
        let mut v = view();
        v.push_line(&line("abcdef"));
        v.push_line(&line("klmnop"));
        v.set_selection((0, 2), (1, 5));
        assert!(v.is_selected(0, 3), "cols 2..5 of row 0 are in the band");
        assert!(!v.is_selected(0, 5), "col 5 is past the band");
        assert!(!v.is_selected(1, 1), "col 1 is before the band");
        assert!(
            !v.is_selected(0, 1),
            "a stream selection would have taken the whole tail of row 0"
        );
    }

    #[test]
    fn select_all_stays_a_stream_selection_in_block_mode() {
        let _guard = BlockModeGuard::on();
        let mut v = view();
        v.push_line(&line("abcdef"));
        v.push_line(&line("gh"));
        v.select_all();
        assert_eq!(
            v.selected_text().unwrap(),
            "abcdef
gh"
        );
    }

    #[test]
    fn a_plain_click_clears_any_selection() {
        let mut v = view();
        v.push_line(&line("hello"));
        v.select_all();
        assert!(v.has_selection());
        let mut down = Event::mouse(
            EventType::MouseDown,
            Point::new(2, 0),
            MB_LEFT_BUTTON,
            false,
        );
        v.handle_event(&mut down);
        let mut up = Event::mouse(EventType::MouseUp, Point::new(2, 0), 0, false);
        v.handle_event(&mut up);
        assert!(!v.has_selection(), "click without drag deselects");
    }

    #[test]
    fn esc_clears_the_selection() {
        let mut v = view();
        v.push_line(&line("hello"));
        v.select_all();
        let mut esc = Event::keyboard(KB_ESC);
        v.handle_event(&mut esc);
        assert!(!v.has_selection());
    }

    #[test]
    fn mutating_the_buffer_clears_the_selection() {
        let mut v = view();
        v.push_line(&line("hello"));
        v.select_all();
        assert!(v.has_selection());
        v.push_line(&line("more"));
        assert!(
            !v.has_selection(),
            "new content must drop a stale selection"
        );
    }

    /// An in-memory `Backend` for tests: no real TTY, fixed size, no I/O.
    /// `Terminal::write_line`/`write_cell` write straight into `Terminal`'s
    /// own in-memory buffer, so this stub only needs to satisfy
    /// initialization and size queries for `Terminal::with_backend`.
    struct FakeBackend {
        width: u16,
        height: u16,
    }

    impl Backend for FakeBackend {
        fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
            self
        }

        fn init(&mut self) -> io::Result<()> {
            Ok(())
        }

        fn cleanup(&mut self) -> io::Result<()> {
            Ok(())
        }

        fn size(&self) -> io::Result<(u16, u16)> {
            Ok((self.width, self.height))
        }

        fn poll_event(&mut self, _timeout: Duration) -> io::Result<Option<Event>> {
            Ok(None)
        }

        fn write_raw(&mut self, _data: &[u8]) -> io::Result<()> {
            Ok(())
        }

        fn flush(&mut self) -> io::Result<()> {
            Ok(())
        }

        fn show_cursor(&mut self, _x: u16, _y: u16) -> io::Result<()> {
            Ok(())
        }

        fn hide_cursor(&mut self) -> io::Result<()> {
            Ok(())
        }
    }

    fn fake_terminal(width: u16, height: u16) -> Terminal {
        Terminal::with_backend(Box::new(FakeBackend { width, height }))
            .expect("fake backend never fails to init")
    }

    /// A `Backend` that records every byte `Terminal::flush` actually sends
    /// downstream, via a shared buffer -- the write-through path
    /// `FakeBackend` above stubs out. `Terminal::flush` is the one place
    /// that decides what physically reaches a real terminal (it does a
    /// diffed, escape-coded re-encode of the cell buffer, and knowingly
    /// skips `'\0'` filler cells), so a bug specific to *that* encoding is
    /// invisible to any test that only inspects `Terminal::read_cell`,
    /// which reflects the in-memory cell buffer `write_line` always
    /// updates unconditionally.
    #[derive(Clone, Default)]
    struct RecordingBackend {
        width: u16,
        height: u16,
        output: std::sync::Arc<std::sync::Mutex<Vec<u8>>>,
    }

    impl Backend for RecordingBackend {
        fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
            self
        }

        fn init(&mut self) -> io::Result<()> {
            Ok(())
        }

        fn cleanup(&mut self) -> io::Result<()> {
            Ok(())
        }

        fn size(&self) -> io::Result<(u16, u16)> {
            Ok((self.width, self.height))
        }

        fn poll_event(&mut self, _timeout: Duration) -> io::Result<Option<Event>> {
            Ok(None)
        }

        fn write_raw(&mut self, data: &[u8]) -> io::Result<()> {
            self.output.lock().unwrap().extend_from_slice(data);
            Ok(())
        }

        fn flush(&mut self) -> io::Result<()> {
            Ok(())
        }

        fn show_cursor(&mut self, _x: u16, _y: u16) -> io::Result<()> {
            Ok(())
        }

        fn hide_cursor(&mut self) -> io::Result<()> {
            Ok(())
        }
    }

    /// Builds a `Terminal` whose every `flush`-emitted byte lands in the
    /// returned buffer, so a test can inspect what actually reaches a real
    /// terminal rather than only the in-memory cell buffer.
    fn recording_terminal(
        width: u16,
        height: u16,
    ) -> (Terminal, std::sync::Arc<std::sync::Mutex<Vec<u8>>>) {
        let output = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
        let backend = RecordingBackend {
            width,
            height,
            output: output.clone(),
        };
        let terminal =
            Terminal::with_backend(Box::new(backend)).expect("fake backend never fails to init");
        (terminal, output)
    }

    /// Replays `flush`'s escape-coded byte stream onto a plain grid the way
    /// a real terminal would: `ESC[row;colH` repositions the cursor
    /// (1-indexed), an SGR color sequence is consumed and ignored, and every
    /// other character is placed at the cursor and advances it by its own
    /// display width -- 2 for a double-width glyph, 0 for a combining or
    /// selector character, exactly as a real terminal renders it (not by
    /// our internal one-`Cell`-per-logical-column bookkeeping, which is
    /// precisely what could drift from physical reality). Bytes from
    /// successive flushes are replayed in order onto the same grid, since a
    /// real terminal's screen persists across flushes the same way.
    fn replay_onto_grid(bytes: &[u8], grid: &mut [Vec<char>]) {
        let text = std::str::from_utf8(bytes).expect("flush emits valid UTF-8");
        let mut chars = text.chars().peekable();
        let mut row = 0usize;
        let mut col = 0usize;
        while let Some(c) = chars.next() {
            if c == '\u{1b}' && chars.peek() == Some(&'[') {
                chars.next(); // consume '['
                let mut params = String::new();
                let mut final_byte = ' ';
                for pc in chars.by_ref() {
                    if pc.is_ascii_digit() || pc == ';' {
                        params.push(pc);
                    } else {
                        final_byte = pc;
                        break;
                    }
                }
                if final_byte == 'H' {
                    let mut parts = params.split(';');
                    let r: usize = parts.next().and_then(|p| p.parse().ok()).unwrap_or(1);
                    let cix: usize = parts.next().and_then(|p| p.parse().ok()).unwrap_or(1);
                    row = r.saturating_sub(1);
                    col = cix.saturating_sub(1);
                }
                // An SGR ('m') sequence carries no cursor movement.
                continue;
            }
            let width = c.width().unwrap_or(0);
            if row < grid.len() && col < grid[row].len() {
                grid[row][col] = c;
            }
            col += width;
        }
    }

    #[test]
    fn scrollback_cap_drops_oldest_lines() {
        let mut v = view();
        v.set_max_lines(3);
        for i in 0..5 {
            v.push_line(&line(&i.to_string()));
        }
        assert_eq!(v.line_count(), 3);
        assert_eq!(v.plain_text(), "2\n3\n4");
    }

    #[test]
    fn autoscroll_holds_at_bottom_while_lines_arrive() {
        let mut v = view();
        for i in 0..50 {
            v.push_line(&line(&i.to_string()));
        }
        assert!(v.is_at_bottom());
    }

    #[test]
    fn scrolling_up_releases_autoscroll_and_end_rearms_it() {
        let mut v = view();
        for i in 0..50 {
            v.push_line(&line(&i.to_string()));
        }
        v.scroll_up(5);
        assert!(!v.is_at_bottom());
        v.push_line(&line("new"));
        assert!(
            !v.is_at_bottom(),
            "a new line must not yank a scrolled-back reader to the bottom"
        );
        v.scroll_to_bottom();
        assert!(v.is_at_bottom());
    }

    #[test]
    fn partial_line_is_replaced_not_appended() {
        let mut v = view();
        v.set_partial(&line("par"));
        v.set_partial(&line("part"));
        assert_eq!(v.plain_text(), "part");
        assert_eq!(v.line_count(), 1);
    }

    #[test]
    fn plain_text_strips_attributes() {
        let mut v = view();
        v.push_line(&[Cell::new('x', Attr::new(TvColor::LightRed, TvColor::Blue))]);
        assert_eq!(v.plain_text(), "x");
    }

    #[test]
    fn resize_larger_while_scrolled_back_reclamps_top_to_show_a_full_page() {
        let mut v = StreamView::new(Rect::new(0, 0, 40, 5));
        for i in 0..50 {
            v.push_line(&line(&i.to_string()));
        }
        // Scroll back so `top` sits well below the current max_top()
        // (line_count 50, page 5 -> max_top 45).
        v.scroll_to_top();
        v.scroll_down(40);
        assert!(!v.is_at_bottom());
        let old_top = v.top;
        assert!(old_top < v.max_top());

        // Grow the view a lot: max_top() shrinks to line_count - new_page
        // (50 - 48 = 2), which is now well below the old `top` (40). Left
        // unclamped, that would leave blank rows at the bottom of the
        // viewport even though unshown history sits above.
        v.set_bounds(Rect::new(0, 0, 40, 48));

        assert!(
            v.top <= v.max_top(),
            "top ({}) must not exceed max_top ({}) after growing",
            v.top,
            v.max_top()
        );
        let rows: Vec<&Vec<Cell>> = v.iter_rows().skip(v.top).take(v.page()).collect();
        assert_eq!(
            rows.len(),
            v.page().min(v.row_count()),
            "a full page of content should be visible after growing"
        );
    }

    #[test]
    fn draw_clips_to_bounds_width() {
        let mut v = StreamView::new(Rect::new(2, 1, 9, 4));
        v.push_line(&line("short")); // shorter than the 6-wide text area

        let mut terminal = fake_terminal(20, 10);
        v.draw(&mut terminal);

        // Row 0 (bounds.a.y == 1): "short", padded with the fill space for
        // the remaining column.
        for (i, expected) in "short ".chars().enumerate() {
            let cell = terminal
                .read_cell(2 + i16::try_from(i).unwrap_or(i16::MAX), 1)
                .expect("cell within terminal bounds");
            assert_eq!(cell.ch, expected);
        }
        // The last column of the view is the scrollbar (its up arrow on the
        // top row); nothing is drawn past the view's width (x == 9).
        assert_eq!(terminal.read_cell(8, 1).unwrap().ch, '');
        assert_eq!(terminal.read_cell(9, 1).unwrap().ch, ' ');

        // Nothing above the view's rows was touched.
        assert_eq!(terminal.read_cell(2, 0).unwrap().ch, ' ');
    }

    /// The exact banner glyph plank emits: U+1F6E0 HAMMER AND WRENCH followed
    /// by U+FE0F VARIATION SELECTOR-16 (the emoji presentation selector).
    /// The base character alone is East-Asian-Width `Neutral` (width 1 per
    /// `unicode-width`'s plain per-`char` rule) -- it is only the
    /// *emoji presentation sequence* (base + U+FE0F) that is double-width,
    /// which is exactly the sequence a real tool-call banner sends and the
    /// case this fix targets. `line()` builds one `Cell` per `char` here
    /// too, since `.chars()` splits the base and the selector into two
    /// separate `char`s -- the same shape `tracefmt`'s `cells()` produces.
    const WRENCH: &str = "\u{1F6E0}\u{FE0F}";

    #[test]
    fn wide_character_row_paints_the_correct_total_number_of_columns() {
        // wrench (2 columns) + space + x = 4 columns total.
        let mut v = StreamView::new(Rect::new(0, 0, 11, 4));
        v.push_line(&line(&format!("{WRENCH} x")));
        let mut terminal = fake_terminal(20, 10);
        v.draw(&mut terminal);

        // Column 0 holds the wrench glyph itself.
        assert_eq!(terminal.read_cell(0, 0).unwrap().ch, '\u{1F6E0}');
        // Column 1 is the wrench's second column: the trailing presentation
        // selector itself, kept (not an invented '\0') because it is a real
        // character.
        assert_eq!(terminal.read_cell(1, 0).unwrap().ch, '\u{FE0F}');
        // The rest of the row lands at its true, width-aware columns.
        assert_eq!(terminal.read_cell(2, 0).unwrap().ch, ' ');
        assert_eq!(terminal.read_cell(3, 0).unwrap().ch, 'x');
        // And the row is blank-padded for the remaining columns of the view.
        for x in 4..10 {
            assert_eq!(terminal.read_cell(x, 0).unwrap().ch, ' ');
        }
    }

    #[test]
    fn text_after_a_wide_character_lands_at_the_right_column() {
        let mut v = StreamView::new(Rect::new(0, 0, 30, 4));
        v.push_line(&line(&format!("{WRENCH} Reading src/dsml.rs")));
        let mut terminal = fake_terminal(30, 10);
        v.draw(&mut terminal);

        let expected = "\u{1F6E0}\u{FE0F} Reading src/dsml.rs";
        for (i, expected_ch) in expected.chars().enumerate() {
            let cell = terminal
                .read_cell(i16::try_from(i).unwrap(), 0)
                .expect("cell within terminal bounds");
            assert_eq!(cell.ch, expected_ch, "column {i} mismatch");
        }
    }

    #[test]
    fn short_row_is_blank_padded_so_nothing_shows_through_from_beneath() {
        let mut v = StreamView::new(Rect::new(0, 0, 11, 4));
        // First paint a row that fills the whole text width...
        v.push_line(&line("XXXXXXXXXX"));
        let mut terminal = fake_terminal(20, 10);
        v.draw(&mut terminal);
        // ...then a shorter, width-shrinking row should overwrite every
        // column the first row touched, leaving nothing behind.
        v.clear();
        v.push_line(&line(&format!("{WRENCH}hi")));
        v.draw(&mut terminal);

        assert_eq!(terminal.read_cell(0, 0).unwrap().ch, '\u{1F6E0}');
        assert_eq!(terminal.read_cell(1, 0).unwrap().ch, '\u{FE0F}');
        assert_eq!(terminal.read_cell(2, 0).unwrap().ch, 'h');
        assert_eq!(terminal.read_cell(3, 0).unwrap().ch, 'i');
        for x in 4..10 {
            assert_eq!(
                terminal.read_cell(x, 0).unwrap().ch,
                ' ',
                "column {x} must be blanked, not left over from the previous row"
            );
        }
    }

    #[test]
    fn a_double_width_character_straddling_a_wrap_boundary_is_never_split() {
        // Columns: a b [中 col0] [中 col1: a '\0' filler cell] c d -- 6
        // columns, wrapped at width 3. A naive character-break cut at column
        // 3 would land squarely on the filler cell, splitting the glyph in
        // half; the wrap must instead push the whole character to the next
        // row.
        let mut v = StreamView::new(Rect::new(0, 0, 4, 4));
        v.push_line(&line("ab中cd"));

        assert_eq!(v.row_count(), 3, "the 6-column line wraps to three rows");

        let mut terminal = fake_terminal(20, 10);
        v.draw(&mut terminal);

        // Row 0 holds only "ab": the wide character was pushed whole to the
        // next row rather than being split across the boundary.
        assert_eq!(terminal.read_cell(0, 0).unwrap().ch, 'a');
        assert_eq!(terminal.read_cell(1, 0).unwrap().ch, 'b');

        // Row 1 holds the wide character (both its columns) followed by "c".
        assert_eq!(terminal.read_cell(0, 1).unwrap().ch, '');
        assert_eq!(terminal.read_cell(1, 1).unwrap().ch, '\0');
        assert_eq!(terminal.read_cell(2, 1).unwrap().ch, 'c');

        // Row 2 holds the remaining "d".
        assert_eq!(terminal.read_cell(0, 2).unwrap().ch, 'd');
    }

    #[test]
    fn plain_text_round_trips_a_wide_character_with_no_padding_artifacts() {
        let mut v = view();
        v.push_line(&line(&format!("{WRENCH} Reading src/dsml.rs")));
        assert_eq!(v.plain_text(), format!("{WRENCH} Reading src/dsml.rs"));
    }

    /// Reproduces the real, two-window bug: a lower window paints a row
    /// containing plank's real tool-call banner glyph and *flushes* it (not
    /// just `draw`s it -- the defect lives in what `Terminal::flush` sends
    /// downstream, invisible to any test that only checks
    /// `Terminal::read_cell`, since `write_line` updates the in-memory cell
    /// buffer unconditionally regardless of what flush later encodes). A
    /// second, unrelated window then opens on top with the same bounds and
    /// paints an all-blank row over the identical region, and flushes too.
    /// A real terminal's screen must show nothing left over from the first
    /// window afterwards.
    #[test]
    fn a_covering_window_s_flush_fully_blanks_a_row_that_held_a_wide_character() {
        let (mut terminal, output) = recording_terminal(31, 4);
        let mut grid = vec![vec![' '; 31]; 4];

        // Lower window: the real banner line at row 0, drawn and flushed.
        let mut lower = StreamView::new(Rect::new(0, 0, 31, 4));
        lower.push_line(&line(&format!("{WRENCH} Reading src/dsml.rs 1:500...")));
        lower.draw(&mut terminal);
        terminal
            .flush()
            .expect("flush never fails against a fake backend");
        replay_onto_grid(&output.lock().unwrap(), &mut grid);
        output.lock().unwrap().clear();

        // Upper window: same bounds, no content of its own at all -- opens
        // on top and must blank every column of row 0 that the lower
        // window's banner occupied.
        let mut upper = StreamView::new(Rect::new(0, 0, 31, 4));
        upper.draw(&mut terminal);
        terminal
            .flush()
            .expect("flush never fails against a fake backend");
        replay_onto_grid(&output.lock().unwrap(), &mut grid);

        // Row 0 must now be fully blank -- nothing from the lower window's
        // banner may still show through. (Column 30 is the scrollbar.)
        for (col, &ch) in grid[0].iter().take(30).enumerate() {
            assert_eq!(
                ch, ' ',
                "row 0 column {col} still shows a leftover character from \
                 the window underneath: {grid:?}"
            );
        }
    }

    #[test]
    fn a_line_longer_than_the_width_wraps_across_the_right_number_of_rows_with_complete_content() {
        let mut v = StreamView::new(Rect::new(0, 0, 11, 20));
        // 25 non-space characters at width 10 -> ceil(25/10) = 3 rows.
        let text = "abcdefghijklmnopqrstuvwxy";
        v.push_line(&line(text));

        assert_eq!(v.row_count(), 3);
        assert_eq!(
            v.plain_text(),
            text,
            "wrapping must not drop or duplicate any character"
        );

        // Also verify via the rendered rows that content is complete and in
        // order across them.
        let mut terminal = fake_terminal(20, 20);
        v.draw(&mut terminal);
        let mut rendered = String::new();
        for row in 0..3 {
            for col in 0..10 {
                rendered.push(terminal.read_cell(col, row).unwrap().ch);
            }
        }
        assert_eq!(rendered, "abcdefghijklmnopqrstuvwxy     ");
    }

    #[test]
    fn a_wrap_breaks_at_a_space_rather_than_mid_word_when_one_is_available() {
        let mut v = StreamView::new(Rect::new(0, 0, 11, 20));
        v.push_line(&line("hello world"));

        // "hello world" is 11 columns wide; wrapping at 10 without a
        // space-aware break would cut mid-word ("hello worl" / "d"). The
        // break must instead land on the space, dropping it, and produce
        // "hello" / "world".
        assert_eq!(v.row_count(), 2);
        let mut terminal = fake_terminal(20, 20);
        v.draw(&mut terminal);
        for (i, expected) in "hello     ".chars().enumerate() {
            assert_eq!(
                terminal.read_cell(i16::try_from(i).unwrap(), 0).unwrap().ch,
                expected
            );
        }
        for (i, expected) in "world     ".chars().enumerate() {
            assert_eq!(
                terminal.read_cell(i16::try_from(i).unwrap(), 1).unwrap().ch,
                expected
            );
        }
    }

    #[test]
    fn a_single_token_longer_than_the_width_is_broken_rather_than_truncated() {
        let mut v = StreamView::new(Rect::new(0, 0, 5, 20));
        // A 12-character token with no whitespace at all -- a long path,
        // say -- must still be fully visible, broken mid-token instead of
        // truncated.
        v.push_line(&line("abcdefghijkl"));

        assert_eq!(v.row_count(), 3); // ceil(12/5) = 3
        assert_eq!(
            v.plain_text(),
            "abcdefghijkl",
            "the logical text is preserved even though it had to be broken mid-token"
        );
    }

    #[test]
    fn plain_text_returns_the_original_unwrapped_logical_lines() {
        let mut v = StreamView::new(Rect::new(0, 0, 5, 20));
        v.push_line(&line("a much longer line than the five-column view"));
        v.push_line(&line("short"));

        assert_eq!(
            v.plain_text(),
            "a much longer line than the five-column view\nshort",
            "Save As must get the original logical lines, not this window's wrap points"
        );
    }

    #[test]
    fn resizing_narrower_then_wider_rewraps_and_content_survives_both() {
        let mut v = StreamView::new(Rect::new(0, 0, 21, 20));
        let text = "abcdefghijklmnopqrstuvwxyz";
        v.push_line(&line(text));
        assert_eq!(v.row_count(), 2); // ceil(26/20)

        v.set_bounds(Rect::new(0, 0, 6, 20));
        assert_eq!(v.row_count(), 6); // ceil(26/5)
        assert_eq!(v.plain_text(), text);

        v.set_bounds(Rect::new(0, 0, 31, 20));
        assert_eq!(v.row_count(), 1); // fits on one row now
        assert_eq!(v.plain_text(), text);
    }

    #[test]
    fn scrolling_by_page_lands_correctly_when_wrapped_rows_are_present() {
        // One long line that wraps to 20 rows, in a 5-row-tall view.
        let mut v = StreamView::new(Rect::new(0, 0, 5, 5));
        let text: String = (0..80).map(|i| char::from(b'a' + (i % 26))).collect();
        v.push_line(&line(&text));
        assert_eq!(v.row_count(), 20);

        v.scroll_to_top();
        assert_eq!(v.top, 0);
        v.scroll_down(v.page()); // one page down: page() == 5
        assert_eq!(
            v.top, 5,
            "paging must move by display rows, not logical lines"
        );

        v.scroll_to_bottom();
        assert_eq!(v.top, v.row_count() - v.page());
    }

    fn mouse(what: EventType, x: i16, y: i16, buttons: u8) -> Event {
        Event::mouse(what, Point::new(x, y), buttons, false)
    }

    /// A 41x10 view with 50 one-row lines: page 10, `max_top` 40.
    fn scrollable_view() -> StreamView {
        let mut v = view();
        for i in 0..50 {
            v.push_line(&line(&i.to_string()));
        }
        v
    }

    #[test]
    fn mouse_wheel_scrolls_by_a_few_rows_and_releases_autoscroll() {
        let mut v = scrollable_view();
        assert!(v.is_at_bottom());
        let mut ev = mouse(EventType::MouseWheelUp, 5, 5, 0);
        v.handle_event(&mut ev);
        assert_eq!(ev.what, EventType::Nothing, "the wheel event is consumed");
        assert_eq!(v.top(), 40 - WHEEL_STEP);
        assert!(!v.is_at_bottom());

        v.handle_event(&mut mouse(EventType::MouseWheelDown, 5, 5, 0));
        assert_eq!(v.top(), 40);
        assert!(
            v.is_at_bottom(),
            "wheeling back to the end re-arms autoscroll"
        );
    }

    #[test]
    fn mouse_wheel_outside_the_view_is_ignored() {
        let mut v = scrollable_view();
        let mut ev = mouse(EventType::MouseWheelUp, 60, 5, 0);
        v.handle_event(&mut ev);
        assert_eq!(ev.what, EventType::MouseWheelUp);
        assert_eq!(v.top(), 40);
    }

    #[test]
    fn scrollbar_arrows_step_one_row_and_track_pages() {
        let mut v = scrollable_view();
        let x = v.scrollbar_x();
        assert_eq!(x, 40);

        v.handle_event(&mut mouse(EventType::MouseDown, x, 0, MB_LEFT_BUTTON));
        assert_eq!(v.top(), 39, "up arrow steps one row");
        v.handle_event(&mut mouse(EventType::MouseDown, x, 9, MB_LEFT_BUTTON));
        assert_eq!(v.top(), 40, "down arrow steps one row");

        // Thumb sits at the bottom of the track; clicking the track above
        // it pages up.
        v.handle_event(&mut mouse(EventType::MouseDown, x, 1, MB_LEFT_BUTTON));
        assert_eq!(v.top(), 30, "track above the thumb pages up");
        v.scroll_to_top();
        v.handle_event(&mut mouse(EventType::MouseDown, x, 8, MB_LEFT_BUTTON));
        assert_eq!(v.top(), 10, "track below the thumb pages down");
    }

    #[test]
    fn dragging_the_thumb_scrolls_and_a_click_on_the_scrollbar_never_selects() {
        let mut v = scrollable_view();
        let x = v.scrollbar_x();
        v.scroll_to_top();
        let (start, len) = v.thumb().expect("50 rows in a 10-row view scroll");
        assert_eq!((start, len), (0, 1));

        // Press on the thumb (track row 0 -> screen row 1), drag to the
        // bottom of the track, release.
        v.handle_event(&mut mouse(EventType::MouseDown, x, 1, MB_LEFT_BUTTON));
        assert!(v.dragging_thumb);
        assert!(
            v.selection.is_none(),
            "a scrollbar press must not start a selection"
        );
        v.handle_event(&mut mouse(EventType::MouseMove, x, 8, MB_LEFT_BUTTON));
        assert_eq!(v.top(), 40);
        assert!(v.is_at_bottom());
        v.handle_event(&mut mouse(EventType::MouseMove, x, 4, MB_LEFT_BUTTON));
        assert!(v.top() > 0 && v.top() < 40);
        v.handle_event(&mut mouse(EventType::MouseUp, x, 4, 0));
        assert!(!v.dragging_thumb);
        assert!(v.selection.is_none());
    }

    #[test]
    fn scrollbar_draws_arrows_and_a_thumb_that_tracks_the_position() {
        let mut v = scrollable_view();
        let x = v.scrollbar_x();
        let mut terminal = fake_terminal(50, 10);
        v.draw(&mut terminal);
        assert_eq!(terminal.read_cell(x, 0).unwrap().ch, '');
        assert_eq!(terminal.read_cell(x, 9).unwrap().ch, '');
        // At the bottom the thumb is the last track cell.
        assert_eq!(terminal.read_cell(x, 8).unwrap().ch, '');
        assert_eq!(terminal.read_cell(x, 1).unwrap().ch, '');

        v.scroll_to_top();
        v.draw(&mut terminal);
        assert_eq!(terminal.read_cell(x, 1).unwrap().ch, '');
        assert_eq!(terminal.read_cell(x, 8).unwrap().ch, '');
    }

    #[test]
    fn scrollbar_has_no_thumb_when_everything_fits() {
        let mut v = view();
        v.push_line(&line("one"));
        assert!(v.thumb().is_none());
        let mut terminal = fake_terminal(50, 10);
        v.draw(&mut terminal);
        for y in 1..9 {
            assert_eq!(terminal.read_cell(v.scrollbar_x(), y).unwrap().ch, '');
        }
    }

    #[test]
    fn draw_on_zero_height_view_writes_nothing() {
        let mut v = StreamView::new(Rect::new(0, 0, 10, 0));
        v.push_line(&line("hello"));
        let mut terminal = fake_terminal(20, 10);
        v.draw(&mut terminal);
        for y in 0..10 {
            for x in 0..20 {
                assert_eq!(
                    terminal.read_cell(x, y).unwrap().ch,
                    ' ',
                    "zero-height view must not write any cell"
                );
            }
        }
    }
}