termlens-cli 0.11.12

The termlens command: run a program in a PTY and print its screen, diff two saved screens, render one as SVG, HTML, ANSI, the text format or JSON
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
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
//! `termlens` — the harness at a shell prompt (#255): `inspect` runs a
//! program in a PTY and prints its screen, `diff` compares two saved
//! screens cell by cell, `render` turns one into SVG, HTML, ANSI, the text
//! format or JSON.
//!
//! A saved screen is the snapshot text format of `docs/DESIGN.md` §3 — an
//! insta `.snap` with or without its header, the block a wait error prints,
//! a `TERMLENS_ARTIFACT_DIR` file — or the JSON the crate's `serde` feature
//! writes. `Screen::parse` reads the first back; this binary only decides
//! which of the two a file is. `diff` and `render` take `-` for standard
//! input, and `render --out PATH` writes there instead of to stdout.
//!
//! Exit codes: 0 ran; `diff` exits 1 when the screens differ; 2 means the
//! command itself could not run — bad arguments, an unreadable file, a
//! program that could not be spawned. `inspect` is a viewer, not a gate:
//! the program's own exit status is reported on stderr under the screen,
//! not propagated — and the screen alone goes to stdout, so `inspect … >
//! file` is a saved screen `diff` and `render` read back (#340).

use std::borrow::Cow;
use std::collections::HashSet;
use std::ffi::{OsStr, OsString};
use std::io::{self, IsTerminal, Read, Write};
use std::path::Path;
use std::process::ExitCode;
use std::time::{Duration, Instant};

use termlens::{Screen, ScreenDiff, Terminal};

const USAGE: &str = "\
usage: termlens <command> [options]

commands:
  inspect [options] <program> [args…]  run a program in a PTY and print its screen
  diff [--color WHEN] [--] <a> <b>     compare two saved screens; exit 1 when they differ
  render --svg|--html|--ansi|--text|--json [--out PATH] [--] <a>  render a saved screen

A saved screen is the snapshot text format termlens prints — what `inspect`
writes to stdout, an insta .snap with or without its header, the block a
wait error prints, a TERMLENS_ARTIFACT_DIR file — or the JSON the crate's
`serde` feature writes. `diff` and `render` read `-` as standard input; only
one of diff's two operands can be, since stdin is read once. Either refuses
a screen in the text format larger than 1 GiB; JSON has no size limit.

Exit code 0: the command ran (diff: the screens are the same picture).
Exit code 1: diff found a difference. Exit code 2: termlens itself could not
run — bad arguments, an unreadable file, a program that could not be spawned.

  -h, --help     print this text (also after a command)
      --version  print the version";

const INSPECT_USAGE: &str = "\
usage: termlens inspect [--size COLSxROWS] [--timeout SECONDS] [--idle MILLIS]
                        [--cwd DIR] [--inherit-env] [--ansi]
                        [--env KEY=VALUE]... [--] <program> [args…]

Runs <program> in an 80x24 pseudo-terminal (or --size) and prints the
rendered screen. The wait ends on whichever comes first: the program
exits, or, once it has drawn something, its output has been silent for
--idle milliseconds (default 300). --timeout (default 5 seconds) bounds
both, and a program still running when the wait ends is killed.
The child environment is cleared except for PATH, and gets
TERM=xterm-256color and SHELL=/bin/sh; --inherit-env keeps the caller's
environment instead, but for TERM, COLUMNS and LINES, and repeatable
--env sets selected values, those three included.
--cwd runs the program in DIR, which must be an existing directory. A
relative DIR is taken from where inspect runs, and a relative program
path such as ./myapp is then found inside DIR.
--ansi paints the screen in colour on a terminal.
-- ends the options; the program name follows. Options already stop at
the first argument that does not begin with `-`, so this matters only for
a program whose name does. Every option that takes a value also accepts
it attached with `=`, as in --size=100x30 or --env=KEY=VALUE.

What goes to stdout depends on where stdout goes. A terminal gets what
you came to look at: the plain text, or the painted screen with --ansi.
Anything else — a redirect, a pipe — gets a saved screen with its
styles: block, because that is the rendering that carries colour and the
one `termlens diff` and `termlens render` read back. So a redirect never
loses a style, and never writes an escape those two would refuse.

The screen goes to stdout and nothing else does, so `inspect … > file`
saves a screen that `termlens diff` and `termlens render` read back. The
trailer that says what the program did — its exit status, or that it was
still running when the wait ended — goes to stderr. Exit code 2 means inspect
itself could not run: bad arguments, or a program that could not be spawned.";

const DIFF_USAGE: &str = "\
usage: termlens diff [--color auto|always|never] [--] <a> <b>

Either <a> or <b> may be `-`, meaning standard input — not both, since
stdin is read once. -- ends the options, so a file whose name begins with
`-` can follow it; a `-` after it is still standard input. A text-format
input larger than 1 GiB is refused, since no screen in that format is that
large; JSON has no size limit.

Parses two saved screens and prints what changed from <a> to <b>: the rows
that differ side by side, the size and cursor deltas, the style runs before
and after. On a terminal the changed cells are coloured (red in <a>, green
in <b>) unless --color never or NO_COLOR is set; in a pipe the rendering is
the plain one Screen::diff prints in a CI log. Every option that takes a
value also accepts it attached with `=`, as in --color=never.

Exit code 0 when the two are the same picture, 1 when they differ, 2 when
diff itself could not run — bad arguments, or a file that is missing or not
a saved screen.";

const RENDER_USAGE: &str = "\
usage: termlens render (--svg | --html | --ansi | --text | --json) [--out PATH] [--] <a>

Prints a saved screen as an SVG image, an HTML fragment, the screen in ANSI
colour for a terminal, the plain text format with its styles: block, or the
format-1 JSON document the crate's `serde` feature writes.

<a> may be `-`, meaning standard input. -- ends the options, so a file
whose name begins with `-` can follow it; a `-` after it is still standard
input. A text-format input larger than 1 GiB is refused, since no screen in
that format is that large; JSON has no size limit. --out writes to PATH
instead of stdout; `--out -` is standard output, and a file named `-` is
still `./-`.
--out creates nothing when the render fails — unlike a shell redirect,
which truncates the file before termlens runs. Every option that takes a
value also accepts it attached with `=`, as in --out=screen.svg.

Exit code 0: the screen was rendered. Exit code 2: render itself could not
run — bad arguments, a file that is missing or not a saved screen, or an
--out path that cannot be written.";

/// Where a rendering goes, so a reader that closed early (`termlens … |
/// head`) is a clean exit rather than a panic on a broken pipe.
fn print(out: &str) -> ExitCode {
    emit(|stdout| stdout.write_all(out.as_bytes()))
}

/// [`print`] for a rendering made as it is written: `write` writes it to
/// stdout through a buffer, so none is held whole first. A screen's JSON
/// grows with its history past any bound (#777), and `to_string_pretty`
/// then `format!` held it twice and more: `render --json` of a 1.25 GiB
/// screen needed some 3.6 times its output, and aborted under a cap that
/// read the screen.
fn emit(write: impl FnOnce(&mut dyn Write) -> io::Result<()>) -> ExitCode {
    let mut stdout = io::BufWriter::new(io::stdout().lock());
    match write(&mut stdout).and_then(|()| stdout.flush()) {
        Ok(()) => ExitCode::SUCCESS,
        Err(e) if e.kind() == io::ErrorKind::BrokenPipe => ExitCode::SUCCESS,
        Err(e) => fail(&format!("writing the output failed: {e}")),
    }
}

/// One diagnostic shape for every failure of the tool itself.
fn fail(message: &str) -> ExitCode {
    // Best effort: a closed or full stderr loses the message, not the
    // exit code (#594).
    let _ = report(&format!("termlens: {message}"));
    ExitCode::from(2)
}

/// Write one line to stderr. `eprintln!` panics when the write fails — a
/// stderr piped into `true` or redirected to `/dev/full` — and a panic is
/// exit 101, a code this CLI does not promise (#594). The caller decides
/// whether a lost line matters.
fn report(line: &str) -> io::Result<()> {
    let mut stderr = io::stderr().lock();
    writeln!(stderr, "{line}").and_then(|()| stderr.flush())
}

/// The usage text on stderr and exit code 2, for a command line that is
/// missing what it needs.
fn usage_error(usage: &str) -> ExitCode {
    let _ = report(usage);
    ExitCode::from(2)
}

/// termlens's own options and operands, which must be UTF-8. Only the
/// program `inspect` runs and its arguments may be anything the OS allows,
/// and those never pass through here (#594).
fn utf8(arg: OsString) -> Result<String, String> {
    arg.into_string()
        .map_err(|arg| format!("{arg:?} is not valid UTF-8; termlens's own arguments must be"))
}

/// The one-line string every `--version` flag prints.
fn version() -> String {
    format!("termlens {}\n", env!("CARGO_PKG_VERSION"))
}

fn main() -> ExitCode {
    // `args_os`, not `args`, which panics on an argument that is not UTF-8
    // (#594): `inspect` passes the program's arguments through untouched,
    // and everything else is checked and refused with exit code 2.
    let mut args = std::env::args_os().skip(1);
    let Some(command) = args.next() else {
        return usage_error(USAGE);
    };
    let command = match utf8(command) {
        Ok(command) => command,
        Err(e) => return fail(&e),
    };
    let rest: Vec<OsString> = args.collect();
    if command == "inspect" {
        return inspect(rest);
    }
    let rest = match rest.into_iter().map(utf8).collect::<Result<Vec<_>, _>>() {
        Ok(rest) => rest,
        Err(e) => return fail(&e),
    };
    match command.as_str() {
        "-h" | "--help" => print(&format!("{USAGE}\n")),
        "--version" => print(&version()),
        "diff" => diff(&rest),
        "render" => render(&rest),
        // A leading `-` is a flag, not a command name. Calling `--verbose`
        // an unknown command sent people to the subcommand list for the
        // two guesses this CLI does not have (#475). A bare `-` is not a
        // flag anywhere in this CLI — every subcommand reads it as standard
        // input — so it stays an unknown command.
        other if other.starts_with('-') && other != STDIN => {
            fail(&format!("unknown option {other:?} (try --help)"))
        }
        other => fail(&format!("unknown command {other:?} (try --help)")),
    }
}

// ---------------------------------------------------------------- saved screens

/// Read a saved screen: an insta `.snap` (its `---` header dropped), the
/// text format (an `inspect` trailer from before 0.11 dropped), or JSON.
///
/// The two decorations this skips are the two termlens itself writes
/// around a screen, and `Screen::parse` accepts neither — the library
/// reads the format, the tool knows its own wrappers (`docs/DESIGN.md` §3).
///
/// `-` is standard input, the universal convention (#317): a saved screen
/// most often arrives on a pipe, out of a CI log or from the tool that made
/// it a moment earlier. Only the reading changes; the parser already took a
/// `&str` rather than a path.
fn load(path: &str) -> Result<Screen, String> {
    read(open(path, MAX_INPUT)?, MAX_INPUT)
}

/// An operand that has been opened and measured and not yet read: the
/// first half of [`load`]. The halves are apart so that `diff` can learn
/// that one operand will never be read before it waits on the other (#715).
struct Source<'a> {
    /// What a diagnostic calls it.
    name: &'a str,
    input: Box<dyn Read + 'a>,
    /// A regular file's length; 0 for standard input, a pipe or a device
    /// (`/dev/zero`), which are bounded by the read itself.
    len: usize,
    /// A regular file's first bytes, read by [`open`]; anything else's are
    /// read by [`read`].
    head: Option<Head>,
}

/// The refusal of a text-format input past `limit` ([`MAX_INPUT`] outside
/// the tests), for an operand named `name`.
fn too_large(name: &str, limit: usize, as_utf8: &str) -> String {
    format!(
        "{name}: larger than {}{as_utf8}, which no screen in the text format is",
        size(limit)
    )
}

/// A limit in the unit [`too_large`] names it in.
fn size(limit: usize) -> String {
    if limit % (1 << 30) == 0 {
        format!("{} GiB", limit >> 30)
    } else {
        format!("{limit} bytes")
    }
}

/// Open the operand at `path` and find what can be known of it before the
/// read: that it is there, that it is not a directory, how long it is, and,
/// for a regular file, whether it is JSON, which no length bounds (#777).
fn open(path: &str, limit: usize) -> Result<Source<'_>, String> {
    if path == STDIN {
        return Ok(Source {
            name: STDIN_NAME,
            input: Box::new(io::stdin().lock()),
            len: 0,
            head: None,
        });
    }
    let mut file = std::fs::File::open(path).map_err(|e| format!("{path}: {e}"))?;
    let (len, head) = match file.metadata() {
        // A regular file's head is read here: the read waits on nobody, and
        // it says whether the length is a bound. A text-format file past the
        // bound is then refused before the rest is read, and one inside it
        // is read into a buffer of its own size.
        Ok(meta) if meta.is_file() => {
            let head = Head::read(&mut file).map_err(|e| format!("{path}: {e}"))?;
            (meta.len(), Some(head))
        }
        // A directory opens like a file on Unix and refuses its first read.
        // That read waits on nobody, so it is made here and the error is the
        // operating system's own, the one `render --text /` has always
        // printed. Where a directory can be read, it is no screen either way.
        Ok(meta) if meta.is_dir() => match (&file).read(&mut [0; 1]) {
            Ok(_) => (0, None),
            Err(e) => return Err(format!("{path}: {e}")),
        },
        _ => (0, None),
    };
    if len > limit as u64 && head.as_ref().is_some_and(|head| head.json().is_none()) {
        return Err(too_large(path, limit, ""));
    }
    Ok(Source {
        name: path,
        input: Box::new(file),
        len: usize::try_from(len).unwrap_or(usize::MAX),
        head,
    })
}

/// Read an opened operand to its end and parse it: the second half of
/// [`load`]. JSON is parsed as it is read; the text format is read whole,
/// to at most `limit` bytes ([`MAX_INPUT`] outside the tests).
fn read(source: Source<'_>, limit: usize) -> Result<Screen, String> {
    let Source {
        name,
        mut input,
        len,
        head,
    } = source;
    let head = match head {
        Some(head) => head,
        None => Head::read(&mut input).map_err(|e| format!("{name}: {e}"))?,
    };
    if let Some((encoding, skip)) = head.json() {
        return read_json(name, head.bytes, encoding, skip, input);
    }
    let raw = read_bounded(io::Cursor::new(head.bytes).chain(input), len, limit);
    let Some(raw) = raw.map_err(|e| format!("{name}: {e}"))? else {
        return Err(too_large(name, limit, ""));
    };
    let text = decode(raw, limit).map_err(|e| match e {
        // The words `read_to_string` used, which this read replaced.
        NotText::Utf8 => format!("{name}: stream did not contain valid UTF-8"),
        NotText::Utf16 => format!("{name}: stream did not contain valid UTF-16"),
        NotText::Utf32 => format!(
            "{name}: the byte-order mark says UTF-32, which termlens does not read \
             (it reads UTF-8 and UTF-16)"
        ),
        NotText::TooLarge => too_large(name, limit, " as UTF-8"),
        // As a refused reservation reads when the bytes are read.
        NotText::Memory => format!("{name}: {}", io::Error::from(io::ErrorKind::OutOfMemory)),
    })?;
    // A byte-order mark says how the file was encoded and is no part of the
    // screen. Left in, it made the header's first word `\u{feff}size:` and
    // hid the `{` that tells JSON from the text format (#716).
    let text = text.strip_prefix('\u{feff}').unwrap_or(&text);
    // A checkout on Windows may have given the file CRLF endings; the
    // formats are line-based and neither cares. Only copied when there is
    // one, since the input may be hundreds of megabytes.
    let text = if text.contains("\r\n") {
        Cow::Owned(text.replace("\r\n", "\n"))
    } else {
        Cow::Borrowed(text)
    };
    let body = strip_insta_header(&text).trim_start_matches('\n');
    if body.trim_start().starts_with('{') {
        return serde_json::from_str(body)
            .map_err(|e| format!("{name}: not a termlens Screen: {e}"));
    }
    Screen::parse(strip_inspect_trailer(body)).map_err(|e| format!("{name}: {e}"))
}

/// Why an input's bytes are not text.
#[derive(Debug, PartialEq, Eq)]
enum NotText {
    /// Not UTF-8, with no UTF-16 byte-order mark in front.
    Utf8,
    /// A UTF-16 byte-order mark, then half a code unit or a lone surrogate.
    Utf16,
    /// A UTF-32 byte-order mark (#784).
    Utf32,
    /// UTF-16 inside the bound as bytes and past it as UTF-8.
    TooLarge,
    /// The allocator refused the room the text needs.
    Memory,
}

/// The text of an input's bytes: UTF-8, or UTF-16 behind its byte-order
/// mark, in either byte order (#716). Windows PowerShell 5.1 re-encodes
/// what a program prints, so `termlens inspect app > a.snap` there writes
/// UTF-16LE with a mark, and the CLI could not read back its own output
/// from the default Windows shell. The mark stays at the head of the text
/// for the caller to strip, as a UTF-8 file's own mark does.
///
/// Nothing is read as UTF-16 without the mark: `FF` is in no UTF-8 text,
/// so the mark cannot be mistaken, and anything else would be a guess.
///
/// UTF-16 grows by half when its characters are three bytes of UTF-8, so
/// the bound on the bytes read is not a bound on the text. The text is
/// measured before any room is reserved for it and refused past `limit`
/// ([`MAX_INPUT`] outside the tests), and the room is the measured size,
/// reserved fallibly: a refusal is an error to report, as in
/// [`read_bounded`].
fn decode(raw: Vec<u8>, limit: usize) -> Result<String, NotText> {
    let big_endian = match encoding(&raw) {
        Encoding::Utf8 => return String::from_utf8(raw).map_err(|_| NotText::Utf8),
        Encoding::Utf16 { big_endian } => big_endian,
        Encoding::Utf32 => return Err(NotText::Utf32),
    };
    if raw.len() % 2 != 0 {
        return Err(NotText::Utf16);
    }
    let units = || {
        raw.chunks_exact(2).map(|unit| {
            let unit = [unit[0], unit[1]];
            if big_endian {
                u16::from_be_bytes(unit)
            } else {
                u16::from_le_bytes(unit)
            }
        })
    };
    let mut len = 0;
    for decoded in char::decode_utf16(units()) {
        len += decoded.map_err(|_| NotText::Utf16)?.len_utf8();
        if len > limit {
            return Err(NotText::TooLarge);
        }
    }
    let mut text = String::new();
    text.try_reserve_exact(len).map_err(|_| NotText::Memory)?;
    // Every unit decoded in the pass above, so nothing is replaced here.
    text.extend(char::decode_utf16(units()).map(|c| c.unwrap_or(char::REPLACEMENT_CHARACTER)));
    Ok(text)
}

/// How an input's bytes are text, by the byte-order mark in front (#716).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Encoding {
    Utf8,
    Utf16 {
        big_endian: bool,
    },
    /// Not read, and named in the refusal (#784).
    Utf32,
}

/// The encoding the first bytes of an input name: UTF-16 behind its mark,
/// in either byte order, UTF-32 behind its own, and UTF-8 otherwise.
///
/// UTF-32 is what PowerShell's `Out-File -Encoding utf32` writes. Its
/// little-endian mark, `FF FE 00 00`, begins with UTF-16LE's, so it is
/// looked for first; read as UTF-16 it was a header full of NULs. A
/// UTF-16 file cannot begin that way, since no saved screen begins with
/// U+0000.
fn encoding(bytes: &[u8]) -> Encoding {
    if let Some([0xff, 0xfe, 0, 0] | [0, 0, 0xfe, 0xff]) = bytes.get(..4) {
        return Encoding::Utf32;
    }
    match bytes.get(..2) {
        Some([0xff, 0xfe]) => Encoding::Utf16 { big_endian: false },
        Some([0xfe, 0xff]) => Encoding::Utf16 { big_endian: true },
        _ => Encoding::Utf8,
    }
}

/// How much of an input is read before the rest to tell JSON from the text
/// format. What comes before a document — a byte-order mark, an insta
/// header, whitespace — is a few hundred bytes in anything termlens, insta
/// or a shell writes; an input this cannot decide is read the way the text
/// format is.
const HEAD: usize = 64 * 1024;

/// The first bytes of an input, read to tell JSON from the text format.
struct Head {
    bytes: Vec<u8>,
    /// The input ended inside them.
    ended: bool,
}

impl Head {
    fn read(input: &mut impl Read) -> io::Result<Head> {
        let mut bytes = Vec::new();
        input.take(HEAD as u64).read_to_end(&mut bytes)?;
        Ok(Head {
            ended: bytes.len() < HEAD,
            bytes,
        })
    }

    /// Where the JSON document begins, when the input is one: its encoding,
    /// and how many bytes of its text as UTF-8 come before the document.
    /// `None` for the text format, and for a head that cannot say, which is
    /// read as the text format is — whole and bounded — and still parsed as
    /// JSON if it turns out to be ([`read`]).
    fn json(&self) -> Option<(Encoding, usize)> {
        let encoding = encoding(&self.bytes);
        let (text, whole) = match encoding {
            // A head that stops inside a character, or at a byte that is
            // not UTF-8, is read as far as it decodes.
            Encoding::Utf8 => match std::str::from_utf8(&self.bytes) {
                Ok(text) => (Cow::Borrowed(text), self.ended),
                Err(e) => (
                    Cow::Borrowed(std::str::from_utf8(&self.bytes[..e.valid_up_to()]).ok()?),
                    false,
                ),
            },
            // Read as the text format is, where it is refused by name.
            Encoding::Utf32 => return None,
            Encoding::Utf16 { big_endian } => {
                let units = self.bytes.chunks_exact(2).map(|unit| {
                    let unit = [unit[0], unit[1]];
                    if big_endian {
                        u16::from_be_bytes(unit)
                    } else {
                        u16::from_le_bytes(unit)
                    }
                });
                let mut text = String::new();
                let mut whole = self.ended && self.bytes.len() % 2 == 0;
                for decoded in char::decode_utf16(units) {
                    let Ok(ch) = decoded else {
                        whole = false;
                        break;
                    };
                    text.push(ch);
                }
                (Cow::Owned(text), whole)
            }
        };
        json_body(&text, whole).map(|skip| (encoding, skip))
    }
}

/// The byte at which [`read`] hands a JSON document in `text` to the parser
/// — past a byte-order mark, an insta header and the newlines after them,
/// as the text format's reading strips them — when what follows is JSON.
/// `text` is the head of a decoded input, the whole of it when `whole`; a
/// head that ends before the answer is known is `None`.
///
/// The rules are the text reading's, kept apart from it so that JSON is
/// recognised from a head: the header found as `strip_insta_header` finds it
/// once CRLF is LF, and the document wherever the body begins with `{`
/// after Unicode whitespace (#786). What whitespace the parser is handed is
/// its to judge, as it was: CRLF is whitespace to JSON, and a no-break space
/// is still refused.
fn json_body(text: &str, whole: bool) -> Option<usize> {
    let mut rest = text.strip_prefix('\u{feff}').unwrap_or(text);
    if let Some(header) = rest
        .strip_prefix("---\n")
        .or_else(|| rest.strip_prefix("---\r\n"))
    {
        let close = header.match_indices("\n---").find_map(|(at, _)| {
            let after = &header[at + 4..];
            after
                .strip_prefix('\n')
                .or_else(|| after.strip_prefix("\r\n"))
        });
        match close {
            Some(body) => rest = body,
            // A header that never closes is no header; the text reading
            // keeps it as content.
            None if whole => {}
            None => return None,
        }
    }
    let body = rest.trim_start_matches('\n');
    let first = body.trim_start();
    if first.is_empty() && !whole {
        return None;
    }
    first.starts_with('{').then_some(text.len() - body.len())
}

/// Parse a JSON saved screen as it is read (#777): `head`, the first bytes
/// read, then `rest`, after the `skip` bytes of text before the document.
///
/// Nothing holds the input: the parser takes it a buffer at a time, its
/// strings and its nesting are bounded ([`JsonText`]), and the screen it
/// builds is bounded by what the file declares (#713, #778). So no length
/// is refused, which is what reads back the JSON termlens writes at any
/// length — history and images grow without a bound of their own.
fn read_json(
    name: &str,
    head: Vec<u8>,
    encoding: Encoding,
    skip: usize,
    rest: impl Read,
) -> Result<Screen, String> {
    let input = io::Cursor::new(head).chain(rest);
    let mut text: Box<dyn Read + '_> = match encoding {
        Encoding::Utf8 | Encoding::Utf32 => Box::new(Utf8Text::new(input)),
        Encoding::Utf16 { big_endian } => Box::new(Utf16Text::new(input, big_endian)),
    };
    io::copy(&mut text.by_ref().take(skip as u64), &mut io::sink())
        .map_err(|e| format!("{name}: {e}"))?;
    let document = io::BufReader::with_capacity(HEAD, JsonText::new(text));
    serde_json::from_reader(document).map_err(|e| {
        if e.is_io() {
            format!("{name}: {e}")
        } else {
            format!("{name}: not a termlens Screen: {e}")
        }
    })
}

/// The longest string [`JsonText`] passes: 1 MiB. The longest a saved
/// screen holds is a title, a clipboard or a link's address, each at most
/// the 64 KiB a terminal keeps of an OSC string, six times that escaped; a
/// row of history is at most 22,000 bytes (#778).
const MAX_STRING: usize = 1 << 20;

/// The deepest [`JsonText`] passes: `serde_json`'s own limit for what it
/// builds. A saved screen nests seven deep.
const MAX_DEPTH: usize = 128;

/// A JSON document on its way to the parser, held to strings of at most
/// [`MAX_STRING`] bytes and nesting of at most [`MAX_DEPTH`] (#777).
///
/// `serde_json` gathers a string whole before handing it on, and keeps a
/// byte for each array or object it skips inside a field it does not know,
/// so an endless string or an endless `[[[[` grew its buffers as an endless
/// file grew the reader's before #653. Counting them as they pass bounds
/// those buffers by a constant, whatever the length of the input.
struct JsonText<R> {
    inner: R,
    in_string: bool,
    escaped: bool,
    run: usize,
    depth: usize,
}

impl<R> JsonText<R> {
    fn new(inner: R) -> Self {
        Self {
            inner,
            in_string: false,
            escaped: false,
            run: 0,
            depth: 0,
        }
    }

    fn refuse(what: String) -> io::Error {
        io::Error::new(io::ErrorKind::InvalidData, what)
    }
}

impl<R: Read> Read for JsonText<R> {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        let read = self.inner.read(buf)?;
        for &byte in &buf[..read] {
            if self.in_string {
                if self.escaped {
                    self.escaped = false;
                } else if byte == b'\\' {
                    self.escaped = true;
                } else if byte == b'"' {
                    self.in_string = false;
                    continue;
                }
                self.run += 1;
                if self.run > MAX_STRING {
                    return Err(Self::refuse(format!(
                        "a string in the JSON runs past {} MiB, longer than any a saved screen holds",
                        MAX_STRING >> 20
                    )));
                }
                continue;
            }
            match byte {
                b'"' => {
                    self.in_string = true;
                    self.run = 0;
                }
                b'[' | b'{' => {
                    self.depth += 1;
                    if self.depth > MAX_DEPTH {
                        return Err(Self::refuse(format!(
                            "the JSON nests deeper than {MAX_DEPTH}, which no saved screen does"
                        )));
                    }
                }
                b']' | b'}' => self.depth = self.depth.saturating_sub(1),
                _ => {}
            }
        }
        Ok(read)
    }
}

/// UTF-8 checked as it streams to the parser, a buffer at a time, and
/// refused in the words [`decode`]'s refusal is reported in, as every input
/// was before JSON streamed (#777). serde_json checks only what it reads as
/// a string, and names what is not UTF-8 there "invalid unicode code
/// point", after which the CLI called the input "not a termlens Screen";
/// a byte after the document it calls "trailing characters". A saved
/// screen in a code page — Windows PowerShell's `Set-Content` writes ANSI,
/// so `é` is the byte `E9` — is told apart as text is, by its encoding.
struct Utf8Text<R> {
    inner: R,
    /// The start of a character the last read ended inside: at most three
    /// bytes, handed on with the bytes that finish it.
    carry: [u8; 3],
    carried: usize,
    /// Checked text not yet handed out, and how much of it has been.
    out: Vec<u8>,
    at: usize,
}

impl<R: Read> Utf8Text<R> {
    fn new(inner: R) -> Self {
        Self {
            inner,
            carry: [0; 3],
            carried: 0,
            out: Vec::new(),
            at: 0,
        }
    }

    fn invalid() -> io::Error {
        io::Error::new(
            io::ErrorKind::InvalidData,
            "stream did not contain valid UTF-8",
        )
    }

    /// Read and check the next bytes of `inner` into `out`; `false` at its
    /// end.
    fn fill(&mut self) -> io::Result<bool> {
        let mut raw = [0; 8 * 1024];
        let mut have = self.carried;
        raw[..have].copy_from_slice(&self.carry[..have]);
        loop {
            let read = loop {
                match self.inner.read(&mut raw[have..]) {
                    Ok(read) => break read,
                    Err(e) if e.kind() == io::ErrorKind::Interrupted => {}
                    Err(e) => return Err(e),
                }
            };
            if read == 0 {
                // The input ended inside a character.
                return if have > 0 {
                    Err(Self::invalid())
                } else {
                    Ok(false)
                };
            }
            have += read;
            let valid = match std::str::from_utf8(&raw[..have]) {
                Ok(_) => have,
                // A character the read split: the rest is in the next one.
                Err(e) if e.error_len().is_none() => e.valid_up_to(),
                Err(_) => return Err(Self::invalid()),
            };
            if valid == 0 {
                continue;
            }
            self.carried = have - valid;
            self.carry[..self.carried].copy_from_slice(&raw[valid..have]);
            self.out.clear();
            self.out.extend_from_slice(&raw[..valid]);
            self.at = 0;
            return Ok(true);
        }
    }
}

impl<R: Read> Read for Utf8Text<R> {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        while self.at == self.out.len() {
            if !self.fill()? {
                return Ok(0);
            }
        }
        let n = buf.len().min(self.out.len() - self.at);
        buf[..n].copy_from_slice(&self.out[self.at..self.at + n]);
        self.at += n;
        Ok(n)
    }
}

/// UTF-16 behind its byte-order mark read as UTF-8 (#716), a buffer at a
/// time, so a JSON saved screen a Windows shell re-encoded streams as the
/// UTF-8 one does. Half a code unit or a lone surrogate is an error, in the
/// words [`decode`]'s refusal is reported in.
struct Utf16Text<R> {
    inner: R,
    big_endian: bool,
    /// A byte of a code unit the last read split.
    odd: Option<u8>,
    /// A high surrogate waiting for its low half.
    high: Option<u16>,
    /// Decoded text not yet handed out, and how much of it has been.
    out: Vec<u8>,
    at: usize,
}

impl<R: Read> Utf16Text<R> {
    fn new(inner: R, big_endian: bool) -> Self {
        Self {
            inner,
            big_endian,
            odd: None,
            high: None,
            out: Vec::new(),
            at: 0,
        }
    }

    fn invalid() -> io::Error {
        io::Error::new(
            io::ErrorKind::InvalidData,
            "stream did not contain valid UTF-16",
        )
    }

    /// Decode the next bytes of `inner` into `out`; `false` at its end.
    fn fill(&mut self) -> io::Result<bool> {
        let mut raw = [0; 8 * 1024];
        let mut have = 0;
        if let Some(byte) = self.odd.take() {
            raw[0] = byte;
            have = 1;
        }
        let read = loop {
            match self.inner.read(&mut raw[have..]) {
                Ok(read) => break read,
                Err(e) if e.kind() == io::ErrorKind::Interrupted => {}
                Err(e) => return Err(e),
            }
        };
        if read == 0 {
            return if have > 0 || self.high.is_some() {
                Err(Self::invalid())
            } else {
                Ok(false)
            };
        }
        have += read;
        if have % 2 == 1 {
            have -= 1;
            self.odd = Some(raw[have]);
        }
        self.out.clear();
        self.at = 0;
        for unit in raw[..have].chunks_exact(2) {
            let unit = [unit[0], unit[1]];
            let unit = if self.big_endian {
                u16::from_be_bytes(unit)
            } else {
                u16::from_le_bytes(unit)
            };
            let ch = match (self.high.take(), unit) {
                (None, 0xd800..=0xdbff) => {
                    self.high = Some(unit);
                    continue;
                }
                (Some(high), 0xdc00..=0xdfff) => {
                    let code =
                        0x10000 + ((u32::from(high) - 0xd800) << 10) + (u32::from(unit) - 0xdc00);
                    char::from_u32(code).ok_or_else(Self::invalid)?
                }
                (None, unit) => char::from_u32(u32::from(unit)).ok_or_else(Self::invalid)?,
                (Some(_), _) => return Err(Self::invalid()),
            };
            let mut encoded = [0; 4];
            self.out
                .extend_from_slice(ch.encode_utf8(&mut encoded).as_bytes());
        }
        Ok(true)
    }
}

impl<R: Read> Read for Utf16Text<R> {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        while self.at == self.out.len() {
            if !self.fill()? {
                return Ok(0);
            }
        }
        let n = buf.len().min(self.out.len() - self.at);
        buf[..n].copy_from_slice(&self.out[self.at..self.at + n]);
        self.at += n;
        Ok(n)
    }
}

/// The dash operand: standard input where a screen is read, standard
/// output where one is written (`render --out -`, #469). One constant,
/// because it is one convention — a reader who meets `-` in either
/// position should not have to ask which stream is meant.
const STDIN: &str = "-";
/// What a diagnostic calls it, since `-: ...` reads as a stray flag.
const STDIN_NAME: &str = "<stdin>";

/// The most `diff` and `render` read of an input in the text format, in
/// bytes (#653). Without a bound, `render --text /dev/zero` or `yes |
/// render --text -` grew until the allocator or the OOM killer stopped it.
///
/// The text format holds a grid and nothing else, at most 1000x1000 cells
/// since #583, so the bound can sit above the largest such file termlens
/// writes and refuse nothing a release wrote: 1000x1000 cells, each as full
/// as vt100 fills one (21 bytes) and styled unlike its neighbours with every
/// token a `styles:` span carries, come to about 110 MB.
///
/// JSON has no such ceiling and is not held to this (#777). Its history
/// grows with `scrollback(n)` and its images with `capture_graphics(n)`,
/// neither bounded: 50,000 rows of styled history on 120x40 are 1.25 GiB of
/// the compact JSON `TERMLENS_ARTIFACT_DIR` writes, which the 1 GiB bound
/// once held to both formats refused. JSON is parsed as it is read instead
/// ([`read_json`]), holding what the file declares (#713, #778) rather than
/// the file.
const MAX_INPUT: usize = 1 << 30;

/// Read all of `reader`, or `None` once it holds more than `limit` bytes
/// ([`MAX_INPUT`] outside the tests). `hint` is the expected length (a
/// regular file's size, else 0).
///
/// The buffer never grows past `limit + 1` bytes: each round reads at
/// most what the buffer already has room for, and the room is doubled up to
/// that cap, so the refusal costs the bound and not the next power of two a
/// plain `read_to_end` would have reserved for the extra byte. A reservation
/// the allocator refuses is an error to report, not an abort.
fn read_bounded(mut reader: impl Read, hint: usize, limit: usize) -> io::Result<Option<Vec<u8>>> {
    let cap = limit + 1;
    let mut buf: Vec<u8> = Vec::new();
    // One more than the hint, so a file read in full is seen to end
    // without growing the buffer for the probe.
    buf.try_reserve_exact(hint.saturating_add(1).max(8 * 1024).min(cap))?;
    loop {
        let room = buf.capacity() - buf.len();
        let read = (&mut reader).take(room as u64).read_to_end(&mut buf)?;
        if buf.len() > limit {
            return Ok(None);
        }
        if read < room {
            return Ok(Some(buf));
        }
        let grown = buf.capacity().saturating_mul(2).min(cap);
        buf.try_reserve_exact(grown - buf.len())?;
    }
}

/// How long `inspect` gives the reap to land after the wait ends, so the
/// trailer says exited when the program did exit. Only ever paid in full by
/// a child that is genuinely still running, and only after the wait itself
/// has ended.
///
/// On Unix the exit closes the terminal, the EOF ends the wait, and the
/// kernel can report that close a scheduling hair before the child's status
/// is collectable — the stress run caught the gap (#374, iteration 3 of 25
/// on a loaded 16-thread runner). 500 ms, the width the library gives its
/// own post-reap drain, covers it.
///
/// Windows needs longer (#501). ConPTY never reports the terminal closing,
/// so a program that has just exited ends the wait by the silence window,
/// not an EOF, and the reap then has to cover everything between the
/// program's last byte and its exit status: an MSYS `sh` under load took
/// more than the 300 + 500 ms that left it, and was reported still running.
const REAP_GRACE: Duration = if cfg!(windows) {
    Duration::from_secs(2)
} else {
    Duration::from_millis(500)
};

/// insta writes `---\n<metadata>\n---\n` above the content; the content is
/// what was snapshotted.
fn strip_insta_header(text: &str) -> &str {
    text.strip_prefix("---\n")
        .and_then(|rest| rest.find("\n---\n").map(|end| &rest[end + 5..]))
        .unwrap_or(text)
}

/// `inspect` before 0.11 wrote its `--- exited: … ---` trailer to stdout,
/// so a screen saved with `> file` then carried it (#340). The trailer now
/// goes to stderr, and a file saved that way still reads: the last
/// non-blank line is dropped when it is one of the trailers `inspect`
/// writes — exactly those, so a grid row that happens to start with `---`
/// is left alone. `--- still running` is matched as a prefix so that both
/// of the two still-running trailers (#374) and the single one every
/// release up to 0.11.2 wrote are all stripped from a saved screen.
fn strip_inspect_trailer(text: &str) -> &str {
    let trimmed = text.trim_end_matches('\n');
    let start = trimmed.rfind('\n').map_or(0, |at| at + 1);
    let last = &trimmed[start..];
    let is_trailer = last.ends_with(" ---")
        && [
            "--- exited: ",
            "--- still running",
            "--- waiting for the program failed: ",
        ]
        .iter()
        .any(|prefix| last.starts_with(prefix));
    if is_trailer {
        &trimmed[..start]
    } else {
        text
    }
}

// ------------------------------------------------------------------------ diff

/// When `diff` colours its output.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ColorWhen {
    Auto,
    Always,
    Never,
}

impl ColorWhen {
    fn enabled(self) -> bool {
        match self {
            ColorWhen::Always => true,
            ColorWhen::Never => false,
            ColorWhen::Auto => {
                io::stdout().is_terminal()
                    && std::env::var_os("NO_COLOR").is_none_or(|v| v.is_empty())
            }
        }
    }
}

/// The WHEN word `--color` takes, in either spelling of the flag, or the
/// diagnostic naming anything else — one list of three words, so the two
/// spellings cannot drift apart (#452).
fn color_when(word: &str) -> Result<ColorWhen, String> {
    match word {
        "auto" => Ok(ColorWhen::Auto),
        "always" => Ok(ColorWhen::Always),
        "never" => Ok(ColorWhen::Never),
        other => Err(format!(
            "--color takes auto, always or never, got {other:?}"
        )),
    }
}

fn diff(args: &[String]) -> ExitCode {
    let mut color = ColorWhen::Auto;
    let mut files = Vec::new();
    let mut args = args.iter();
    while let Some(arg) = args.next() {
        match arg.as_str() {
            "-h" | "--help" => return print(&format!("{DIFF_USAGE}\n")),
            "--version" => return print(&version()),
            "--color" => {
                // A WHEN that is not there is its own diagnostic, in the
                // shape every other flag's missing value takes — not the
                // `Some("before.snap")`/`None` the raw Option printed while
                // quietly eating the operand (#452).
                let Some(word) = args.next() else {
                    return fail("--color needs a WHEN argument");
                };
                match color_when(word) {
                    Ok(when) => color = when,
                    Err(e) => return fail(&e),
                }
            }
            other if other.starts_with("--color=") => {
                match color_when(&other["--color=".len()..]) {
                    Ok(when) => color = when,
                    Err(e) => return fail(&e),
                }
            }
            // The end of the options (#650), as for `inspect`: everything
            // after it is an operand, so a file whose name begins with `-`
            // can be named. A `-` after it is still standard input.
            "--" => {
                files.extend(args.by_ref());
                break;
            }
            other if other.starts_with('-') && other != STDIN => {
                return fail(&format!(
                    "unknown option {other:?} (try `termlens diff --help`)"
                ));
            }
            _ => files.push(arg),
        }
    }
    let [a, b] = files.as_slice() else {
        return usage_error(DIFF_USAGE);
    };
    // Standard input can be consumed once, so it can be one operand and not
    // both — said plainly here rather than left to look like an empty second
    // screen further down (#317).
    if a.as_str() == STDIN && b.as_str() == STDIN {
        return fail("only one of the two screens can be `-`: stdin is read once");
    }
    // Left first, so `diff a.snap -` and `diff - b.snap` both read the pipe
    // at the point the argument order says they do — and a left operand
    // that cannot be read is reported before the right one is touched, so
    // `diff missing.snap -` does not sit waiting for a stdin it will never
    // use (#651).
    //
    // The mirror takes one step out of that order (#715). With `-` on the
    // left, the right operand is opened and measured before standard input
    // is read, so `diff - missing.snap` does not wait either; the two are
    // then read in argument order all the same.
    let right = if a.as_str() == STDIN {
        match open(b, MAX_INPUT) {
            Ok(source) => Some(source),
            Err(e) => return fail(&e),
        }
    } else {
        None
    };
    let before = match load(a) {
        Ok(screen) => screen,
        Err(e) => return fail(&e),
    };
    let after = match right.map_or_else(|| load(b), |source| read(source, MAX_INPUT)) {
        Ok(screen) => screen,
        Err(e) => return fail(&e),
    };
    let diff = before.diff(&after);
    let rendered = if color.enabled() {
        colored(&before, &after, &diff)
    } else {
        diff.to_string()
    };
    // Exactly one newline at the end, whichever rendering this is: the
    // plain one already ends its last line, "no difference" and the
    // coloured one do not. Adding one regardless left a blank line after
    // every plain diff, in a pipe and in the report action's summary (#652).
    let code = emit(|out| {
        out.write_all(rendered.as_bytes())?;
        if rendered.ends_with('\n') {
            Ok(())
        } else {
            out.write_all(b"\n")
        }
    });
    if code != ExitCode::SUCCESS {
        return code;
    }
    if diff.is_empty() {
        ExitCode::SUCCESS
    } else {
        ExitCode::from(1)
    }
}

/// Whether `line` is one of the plain rendering's changed-row lines, the
/// `{row:>3} │…│…` shape `ScreenDiff`'s `Display` writes
/// (`crates/termlens/src/screen/diff.rs`). The row number is right-aligned,
/// so before the first frame there are only digits and spaces and at least
/// one digit — which no header or trailer line is, so the shape is where
/// the colour rendering's body begins.
fn is_row_line(line: &str) -> bool {
    let Some((number, _)) = line.split_once('│') else {
        return false;
    };
    let Some(number) = number.strip_suffix(' ') else {
        return false;
    };
    number.chars().any(|c| c.is_ascii_digit())
        && number.chars().all(|c| c.is_ascii_digit() || c == ' ')
}

/// The diff for a terminal: the plain rendering's header and trailer, and
/// each changed row side by side with its changed cells painted — red for
/// what `before` showed, green for what `after` shows — in place of the
/// `^` marker line, which colour makes redundant.
///
/// This owns the body — rows are rebuilt from the screens, painted cell by
/// cell, and the marker lines dropped with them — and passes everything
/// else through as printed: the header (every line before the first row,
/// so the overlap note of a differently sized comparison is carried too,
/// #365) and the trailer (the unchanged-row count and the style runs).
fn colored(before: &Screen, after: &Screen, diff: &ScreenDiff) -> String {
    let plain = diff.to_string();
    if diff.is_empty() {
        return plain;
    }
    let mut lines = plain.lines();
    let mut out = String::new();
    // The header is every line before the first row: one today, two when
    // the sizes differ and the second says what was clipped. Found by the
    // row's shape rather than a line count, so a header line added later
    // is passed through without touching this. The row line itself is
    // consumed here and rebuilt below.
    for line in lines.by_ref() {
        if is_row_line(line) {
            break;
        }
        if !out.is_empty() {
            out.push('\n');
        }
        out.push_str(line);
    }
    let mut changed_rows: Vec<u16> = diff.cells().map(|(row, _, _, _)| row).collect();
    changed_rows.dedup();
    // Collected once: asking the diff about every painted cell made a
    // full-screen change quadratic (#595).
    let changed: HashSet<(u16, u16)> = diff.cells().map(|(row, col, _, _)| (row, col)).collect();
    // The overlap's columns, as the plain rendering clips its rows to them
    // (#649): painting each screen across its own width printed the wider
    // side whole, past the note saying the rest is clipped.
    let cols = before.cols().min(after.cols());
    for row in changed_rows {
        // The row's cells in the overlap, each as `(text, changed)`. A wide
        // character whose second column falls past the overlap does not fit
        // in it and is one blank, as in the plain rendering — and so is one
        // with no second column at all, stranded by a resize in a file
        // 0.11.6 or earlier wrote (#781).
        let cells = |screen: &Screen| -> Vec<(String, bool)> {
            let mut cells = Vec::new();
            for col in 0..cols {
                let Some(cell) = screen.cell(row, col) else {
                    continue;
                };
                if cell.is_wide_continuation() {
                    continue;
                }
                let stranded = cell.is_wide()
                    && (col + 1 >= cols
                        || !screen
                            .cell(row, col + 1)
                            .is_some_and(termlens::Cell::is_wide_continuation));
                let text = if cell.contents().is_empty() || stranded {
                    " "
                } else {
                    cell.contents()
                };
                cells.push((text.to_owned(), changed.contains(&(row, col))));
            }
            cells
        };
        let paint = |cells: &[(String, bool)], sgr: &str| -> String {
            cells
                .iter()
                .map(|(text, changed)| {
                    if *changed {
                        format!("\x1b[{sgr}m{text}\x1b[0m")
                    } else {
                        text.clone()
                    }
                })
                .collect()
        };
        // The before side keeps the overlap's full width so the separator
        // stays in one column down the listing. The after side is trimmed
        // like a row, by cell: a trailing blank is trimmed painted or not,
        // since a coloured blank shows nothing, and trimming the painted
        // string instead left its `\x1b[32m \x1b[0m` runs behind.
        let mut after_cells = cells(after);
        while after_cells.last().is_some_and(|(text, _)| text == " ") {
            after_cells.pop();
        }
        out.push_str(&format!(
            "\n{row:>3} │{}│{}",
            paint(&cells(before), "31"),
            paint(&after_cells, "32")
        ));
    }
    // The trailer: the unchanged-row count and the style runs, as printed.
    for line in lines.filter(|l| l.starts_with('…') || l.starts_with("styles:")) {
        out.push('\n');
        out.push_str(line);
    }
    out
}

// ---------------------------------------------------------------------- render

/// A contradictory `render` request: the reason on one line, then the usage,
/// and exit 2 — what a second operand already gets, with the conflict named
/// so the reader does not have to find it in their own command line.
/// Returned before anything is opened, so `--out` creates no file.
fn render_usage_error(reason: &str) -> ExitCode {
    let _ = report(&format!("termlens: {reason}\n\n{RENDER_USAGE}"));
    ExitCode::from(2)
}

fn render(args: &[String]) -> ExitCode {
    let mut format: Option<&str> = None;
    let mut files = Vec::new();
    let mut out_path: Option<&str> = None;
    let mut args = args.iter();
    while let Some(arg) = args.next() {
        match arg.as_str() {
            "-h" | "--help" => return print(&format!("{RENDER_USAGE}\n")),
            "--version" => return print(&version()),
            // One format and one `--out`, for the reason a second operand is
            // refused below (#364): the last one winning is silent, and in a
            // script the two usually come from two variables, so the loser
            // is the one somebody meant (#450). A repeat of the *same* flag
            // is refused too — it is harmless on its own, but it is the same
            // shape as the mistake, and one rule is easier to state.
            "--svg" | "--html" | "--ansi" | "--text" | "--json" => {
                if let Some(first) = format {
                    return render_usage_error(&if first == arg {
                        format!("{arg} is given twice; render writes one format")
                    } else {
                        format!("{first} and {arg} are two formats; render writes one")
                    });
                }
                format = Some(arg.as_str());
            }
            "--out" => match args.next() {
                // The same refusal as the `--out=` spelling below (#451):
                // an empty PATH is a missing one, not a file named "" (#594).
                Some(path) if path.is_empty() => return fail("--out needs a PATH argument"),
                Some(path) => {
                    if out_path.is_some() {
                        return render_usage_error("--out is given twice; render writes one file");
                    }
                    out_path = Some(path.as_str());
                }
                None => return fail("--out needs a PATH argument"),
            },
            other if other.starts_with("--out=") => {
                let path = &other["--out=".len()..];
                if path.is_empty() {
                    return fail("--out needs a PATH argument");
                }
                if out_path.is_some() {
                    return render_usage_error("--out is given twice; render writes one file");
                }
                out_path = Some(path);
            }
            // The end of the options (#650); see `diff`.
            "--" => {
                files.extend(args.by_ref());
                break;
            }
            other if other.starts_with('-') && other != STDIN => {
                return fail(&format!(
                    "unknown option {other:?} (try `termlens render --help`)"
                ));
            }
            _ => files.push(arg),
        }
    }
    // The operand is the whole input: two of them are ambiguous, and letting
    // the last win is how a stale path renders a screen nobody named (#364).
    let (Some(format), [file]) = (format, files.as_slice()) else {
        return usage_error(RENDER_USAGE);
    };
    let screen = match load(file) {
        Ok(screen) => screen,
        Err(e) => return fail(&e),
    };
    // Each rendering is written as it is made (#777): the text and the JSON
    // straight to the output, through a buffer, and the SVG, HTML and ANSI
    // from the one string the library makes of each.
    let write = |out: &mut dyn Write| -> io::Result<()> {
        match format {
            "--svg" => out.write_all(screen.to_svg().as_bytes()),
            "--html" => out.write_all(screen.to_html().as_bytes()),
            "--ansi" => out.write_all(screen.to_ansi().as_bytes()),
            // Pretty-printed and newline-terminated, the shape the corpus
            // commits: a saved screen a human diffs, and one `load` reads
            // back.
            "--json" => {
                serde_json::to_writer_pretty(&mut *out, &screen)?;
                out.write_all(b"\n")
            }
            _ => writeln!(out, "{}", screen.with_styles()),
        }
    };
    // The file is created here, after the screen parsed, and not before
    // (#313): `termlens render … > out.svg` truncates out.svg in the shell
    // before the process runs, so a failing render leaves an empty file
    // behind. --out cannot, because nothing is opened until the screen is
    // read. `--out -` is stdout, the same stream every other `-` operand
    // already is (#469). Treating it as a filename wrote `./-` and printed
    // nothing.
    match out_path {
        Some(STDIN) | None => emit(write),
        Some(path) => {
            let written = std::fs::File::create(path).and_then(|file| {
                let mut file = io::BufWriter::new(file);
                write(&mut file)?;
                file.flush()
            });
            match written {
                Ok(()) => ExitCode::SUCCESS,
                Err(e) => fail(&format!("{path}: {e}")),
            }
        }
    }
}

// --------------------------------------------------------------------- inspect

/// The value after `flag`, or the one-line diagnostic every flag shares.
fn take<T>(
    args: &mut impl Iterator<Item = OsString>,
    flag: &str,
    kind: &str,
    example: &str,
    parse: impl Fn(&str) -> Option<T>,
) -> Result<T, String> {
    let Some(raw) = args.next() else {
        return Err(format!("{flag} needs a {kind} argument"));
    };
    let raw = utf8(raw)?;
    parse(&raw).ok_or_else(|| format!("bad {flag} {raw:?}, expected e.g. {example}"))
}

/// The `--timeout` a deadline can be built from. `Instant + Duration`
/// panics on overflow, so a value the clock cannot add — `u64::MAX` seconds
/// — is refused here, naming the flag, rather than panicking after the
/// program was spawned (#594). The hour of headroom covers the grace
/// periods added on top of it later.
fn timeout_secs(spec: &str) -> Option<Duration> {
    let timeout = Duration::from_secs(spec.parse().ok()?);
    Instant::now().checked_add(timeout.checked_add(Duration::from_secs(3600))?)?;
    Some(timeout)
}

/// Whether an argument is an option: it begins with `-` and is not `-`.
fn is_option(arg: &OsStr) -> bool {
    arg.as_encoded_bytes().starts_with(b"-") && arg != STDIN
}

/// What `inspect` writes to stdout, which is two different jobs.
///
/// A terminal is a person looking: the plain text they already read, or
/// with `--ansi` the header over the screen painted in colour. Anything
/// else — a redirect, a pipe — is a saved screen somebody means to read
/// back, so it gets `with_styles`: the text format *with* its `styles:`
/// block, which is the only one of the two that carries colour.
///
/// That split is what #454 and #478 each asked for from one side.
/// Without the block a redirect lost every style, so `diff` called bold
/// red and bold green the same picture (#454). With `to_ansi` a redirect
/// wrote C0 controls the snapshot format refuses, so `render` and `diff`
/// would not read back what `inspect --ansi > file` had just written
/// (#478). Both are the same mistake — writing the *viewing* rendering
/// to a file — and `is_terminal` is what tells the two jobs apart.
fn inspect_render(screen: &Screen, ansi: bool) -> String {
    if !io::stdout().is_terminal() {
        screen.with_styles().to_string()
    } else if ansi {
        let header = screen.to_string();
        let header = header.lines().next().unwrap_or_default();
        format!("{header}\n{}", screen.to_ansi())
    } else {
        screen.to_string()
    }
}

/// Whether the program has put anything on the grid yet: a visible
/// character, or a cursor that has moved. A blank screen with the cursor at
/// the origin is what a PTY looks like before its program writes a byte —
/// and it is also what a program that clears and homes without painting
/// looks like, which is why that case waits for the exit or the deadline,
/// exactly as every release up to 0.11.2 did.
fn shows_something(screen: &termlens::Screen) -> bool {
    let (row, col, _) = screen.cursor();
    (row, col) != (0, 0) || !screen.text().trim().is_empty()
}

fn inspect(args: Vec<OsString>) -> ExitCode {
    // The library writes every screen-carrying error to
    // `TERMLENS_ARTIFACT_DIR`, which is right for a failing test. Here a
    // program that exits (`Eof`) or is still running at the deadline
    // (`Timeout`) is a run that ended normally, so the variable is taken
    // out of this process's environment before anything reads it — no
    // thread exists yet — and handed to the program itself when it
    // inherits the environment (#596).
    let artifact_dir = std::env::var_os("TERMLENS_ARTIFACT_DIR");
    std::env::remove_var("TERMLENS_ARTIFACT_DIR");
    let mut args = args.into_iter().peekable();
    let mut size = (80u16, 24u16);
    let mut timeout = Duration::from_secs(5);
    let mut idle = Duration::from_millis(300);
    let mut inherit_env = false;
    let mut ansi = false;
    let mut env = Vec::new();
    let mut cwd: Option<String> = None;

    // Options come before the program; everything after it is the
    // program's own, however flag-like it looks.
    while args.peek().is_some_and(|a| is_option(a)) {
        let flag = match utf8(args.next().unwrap_or_default()) {
            Ok(flag) => flag,
            Err(e) => return fail(&e),
        };
        // `--flag=value` is split only for the flags that take a value, so
        // each keeps its own diagnostic for the spelling and the whole token
        // stays in `flag` for the unknown-option message. A value attached
        // to a flag that takes none (`--inherit-env=nonsense`) falls through
        // to the catch-all and is refused there, as `render` refuses
        // `--svg=1`; splitting it would apply the flag and drop the value.
        let (name, inline) = match flag.split_once('=') {
            Some((name, value))
                if matches!(name, "--size" | "--timeout" | "--idle" | "--cwd" | "--env") =>
            {
                (name, Some(value))
            }
            _ => (flag.as_str(), None),
        };
        // The inline value first, then the next argument: `take` reads one
        // stream, so both spellings parse and diagnose identically.
        let mut args = inline.map(OsString::from).into_iter().chain(args.by_ref());
        let parsed = match name {
            "-h" | "--help" => return print(&format!("{INSPECT_USAGE}\n")),
            "--version" => return print(&version()),
            "--" => break,
            "--size" => take(&mut args, "--size", "COLSxROWS", "120x40", |spec| {
                let (c, r) = spec.split_once('x')?;
                Some((c.parse().ok()?, r.parse().ok()?))
            })
            .map(|s| size = s),
            "--timeout" => {
                take(&mut args, "--timeout", "SECONDS", "30", timeout_secs).map(|t| timeout = t)
            }
            "--idle" => take(&mut args, "--idle", "MILLIS", "1000", |s| s.parse().ok())
                .map(|millis| idle = Duration::from_millis(millis)),
            "--inherit-env" => {
                inherit_env = true;
                Ok(())
            }
            "--ansi" => {
                ansi = true;
                Ok(())
            }
            // Checked here rather than left to the builder so the diagnostic
            // names the flag the user typed; the builder refuses it too, with
            // a message about `current_dir` the caller never wrote (#312).
            "--cwd" => {
                take(&mut args, "--cwd", "DIR", "/tmp", |s| Some(s.to_owned())).and_then(|dir| {
                    if Path::new(&dir).is_dir() {
                        cwd = Some(dir);
                        Ok(())
                    } else {
                        Err(format!("bad --cwd {dir:?}, not an existing directory"))
                    }
                })
            }
            "--env" => take(&mut args, "--env", "KEY=VALUE", "NO_COLOR=1", |s| {
                let (key, value) = s.split_once('=')?;
                (!key.is_empty()).then(|| (key.to_owned(), value.to_owned()))
            })
            .map(|pair| env.push(pair)),
            _ => Err(format!(
                "unknown option {flag:?} (try `termlens inspect --help`)"
            )),
        };
        if let Err(message) = parsed {
            return fail(&message);
        }
    }

    let Some(program) = args.next() else {
        return usage_error(INSPECT_USAGE);
    };

    // A bare name is looked up on PATH, and the child has one only if this
    // process does or `--env` gives one: PATH is passed through when the
    // environment is cleared, and inherited with it under `--inherit-env`.
    // Without one the builder refuses the name with advice for code that
    // called `env_clear()` and `.env(…)`, which a user of the CLI never
    // wrote, so the refusal is made here, naming what that user can do
    // (#785) — as `--cwd` is checked above, for the same reason (#312).
    // "Bare" is the builder's own test: no directory part.
    let bare = Path::new(&program)
        .parent()
        .is_none_or(|dir| dir.as_os_str().is_empty());
    if bare && std::env::var_os("PATH").is_none() && !env.iter().any(|(key, _)| key == "PATH") {
        return fail(&format!(
            "`{}` is a bare program name and there is no PATH to find it in, \
             since termlens has none to pass on, with --inherit-env or without; \
             give the program's absolute path, or a PATH with --env PATH=DIR",
            program.to_string_lossy()
        ));
    }

    let mut builder = Terminal::builder()
        .size(size.0, size.1)
        .timeout(timeout)
        .args(args);
    if !inherit_env {
        builder = builder.env_clear();
        if let Some(path) = std::env::var_os("PATH") {
            builder = builder.env("PATH", path);
        }
    } else if let Some(dir) = artifact_dir {
        builder = builder.env("TERMLENS_ARTIFACT_DIR", dir);
    }
    for (key, value) in env {
        builder = builder.env(key, value);
    }
    if let Some(dir) = cwd {
        builder = builder.current_dir(dir);
    }

    let mut t = match builder.spawn(&program) {
        Ok(t) => t,
        Err(e) => return fail(&e.to_string()),
    };

    // The screen to stdout, the trailer to stderr (#340): `inspect … > file`
    // then saves exactly a screen, which `diff` and `render` read back,
    // while a human at a terminal still sees both. Before 0.11 the trailer
    // followed the screen on stdout and no CLI route produced a file the
    // CLI would accept.
    //
    // Resolve on whichever comes first — the program exits, or its output
    // has been silent for `idle` — under the one deadline (#374). Waiting
    // for the exit first charged the full `--timeout` to every TUI that
    // never exits, however complete the screen already was. `wait_idle_for`
    // is that race, not half of it: it also resolves on the EOF that says
    // the child is gone, and its deadline is applied once. The reaping
    // probe then says which arm fired; it only reaps (and drains the final
    // bytes) when the child is already gone, so an exit lands on its own
    // trailer with the finished screen.
    // Two trailers for a child that outlived the wait, because the wait can
    // now end two ways and "at the deadline" is only true of one of them.
    // `wait_idle_for` returning `Ok` means the output went quiet *or* the
    // terminal reached EOF; neither is the deadline, and a TUI snapshotted
    // 200ms into a 30s budget must not claim otherwise.
    let still_running = "--- still running (killed on exit) ---";
    let at_the_deadline = "--- still running at the deadline (killed on exit) ---";
    let reap = |t: &mut termlens::Terminal| match t.wait_exit_for(REAP_GRACE) {
        Ok(status) => format!("--- exited: {status} ---"),
        Err(termlens::Error::Timeout { .. }) => still_running.to_owned(),
        Err(e) => format!("--- waiting for the program failed: {e} ---"),
    };
    // The silence window starts at the program's first output, not at its
    // spawn. `wait_idle_for` measures silence from the last byte, and before
    // the first byte that is the spawn — so a program slower than `idle` to
    // print anything (a cold `sh` under ConPTY, a JVM, anything that works
    // before it paints) came back as a blank screen at exit 0, killed. That
    // is the one outcome that reads as "this program shows nothing", and
    // 0.11.2, which waited for the exit, never produced it. So wait first
    // for something to be silent *after* — or for the program to go, which
    // is `Eof` and keeps `inspect true` instant — and only then race the
    // exit against the silence, in whatever is left of the one deadline.
    let deadline = Instant::now() + timeout;
    let trailer = match t.wait_until_for(shows_something, timeout) {
        Ok(()) => {
            let remaining = deadline.saturating_duration_since(Instant::now());
            match t.wait_idle_for(idle, remaining) {
                Ok(()) => reap(&mut t),
                // Output never went silent for `idle`: the deadline ended it.
                Err(termlens::Error::Timeout { .. }) => at_the_deadline.to_owned(),
                Err(e) => format!("--- waiting for the program failed: {e} ---"),
            }
        }
        // The program went without painting anything, as `true` does.
        Err(termlens::Error::Eof { .. }) => reap(&mut t),
        // Nothing appeared before the deadline.
        Err(termlens::Error::Timeout { .. }) => at_the_deadline.to_owned(),
        Err(e) => format!("--- waiting for the program failed: {e} ---"),
    };
    let code = emit(|out| writeln!(out, "{}", inspect_render(&t.screen(), ansi)));
    // The trailer is what inspect reports about the program; if stderr
    // cannot take it, say so with the exit code rather than a panic (#594).
    if report(&trailer).is_err() {
        return ExitCode::from(2);
    }
    code
}

#[cfg(test)]
mod tests {
    use std::io::Read as _;

    use super::{
        decode, json_body, open, read, read_bounded, Encoding, Head, JsonText, NotText, Source,
        Utf16Text, Utf8Text, MAX_DEPTH, MAX_STRING,
    };
    use termlens::Screen;

    /// `text` as UTF-16 behind its byte-order mark.
    fn utf16(text: &str, big_endian: bool) -> Vec<u8> {
        std::iter::once(0xfeff)
            .chain(text.encode_utf16())
            .flat_map(|unit| {
                if big_endian {
                    unit.to_be_bytes()
                } else {
                    unit.to_le_bytes()
                }
            })
            .collect()
    }

    /// UTF-16 is read behind its mark in either byte order, surrogate pairs
    /// included, and comes back with the mark for the caller to strip, as
    /// marked UTF-8 does. Without a mark the bytes are UTF-8 or nothing
    /// (#716).
    #[test]
    fn decode_reads_utf8_and_utf16_behind_its_mark() {
        let text = "size: 4x1  cursor: 0,0\n汉字 \u{1f600}";
        assert_eq!(
            decode(text.as_bytes().to_vec(), 1 << 20).as_deref(),
            Ok(text)
        );
        let marked = format!("\u{feff}{text}");
        assert_eq!(
            decode(marked.as_bytes().to_vec(), 1 << 20).as_deref(),
            Ok(marked.as_str())
        );
        for big_endian in [false, true] {
            assert_eq!(
                decode(utf16(text, big_endian), 1 << 20).as_deref(),
                Ok(marked.as_str()),
                "big-endian: {big_endian}"
            );
        }
        // The same units without the mark are not UTF-8, and are not guessed at.
        assert_eq!(
            decode(utf16(text, false)[2..].to_vec(), 1 << 20),
            Err(NotText::Utf8)
        );
        assert_eq!(decode(vec![b'a', 0xff], 1 << 20), Err(NotText::Utf8));
        assert_eq!(decode(Vec::new(), 1 << 20).as_deref(), Ok(""));
        assert_eq!(decode(vec![0xff, 0xfe], 1 << 20).as_deref(), Ok("\u{feff}"));
        // UTF-32's marks, little-endian's beginning with UTF-16LE's, are
        // named and not decoded as something else (#784), from the head
        // that tells JSON apart too.
        for mark in [[0xff, 0xfe, 0, 0], [0, 0, 0xfe, 0xff]] {
            let bytes = [&mark[..], b"s\0\0\0"].concat();
            assert_eq!(super::encoding(&bytes), Encoding::Utf32);
            assert_eq!(decode(bytes.clone(), 1 << 20), Err(NotText::Utf32));
            let head = Head { bytes, ended: true };
            assert_eq!(head.json(), None);
        }
        assert_eq!(
            super::encoding(&[0xff, 0xfe, b's', 0]),
            Encoding::Utf16 { big_endian: false }
        );
    }

    /// Half a code unit, or a surrogate without its other half, is not
    /// UTF-16, and is refused rather than read as U+FFFD (#716).
    #[test]
    fn decode_refuses_broken_utf16() {
        let mut odd = utf16("ok", false);
        odd.push(b'!');
        assert_eq!(decode(odd, 1 << 20), Err(NotText::Utf16));
        for lone in [[0x3d, 0xd8], [0x00, 0xde]] {
            let mut bytes = utf16("ok", false);
            bytes.extend(lone);
            bytes.extend(utf16("ok", false).split_off(2));
            assert_eq!(decode(bytes, 1 << 20), Err(NotText::Utf16), "{lone:02x?}");
        }
    }

    /// The bound is on the text as UTF-8, not only on the bytes read: ten
    /// Han characters are 22 bytes of UTF-16 with the mark and 33 of UTF-8,
    /// so a limit between the two refuses them, and one byte more reads
    /// them (#716).
    #[test]
    fn decode_bounds_utf16_by_its_utf8_length() {
        let bytes = utf16(&"汉".repeat(10), false);
        assert_eq!(bytes.len(), 22);
        assert_eq!(decode(bytes.clone(), 32), Err(NotText::TooLarge));
        let text = decode(bytes, 33).expect("exactly the limit is read");
        assert_eq!(text.len(), 33);
        // The room is what the text measured, not the half again that the
        // bytes could have come to: 18 bytes of ASCII need 11, not 27.
        let ascii = decode(utf16("abcdefgh", false), 1 << 20).expect("ASCII");
        assert!(ascii.capacity() <= 11, "{}", ascii.capacity());
    }

    /// A reader that hands out at most `chunk` bytes per call, so the
    /// bounded read is exercised across many short reads, as a pipe gives.
    struct Trickle<'a> {
        data: &'a [u8],
        chunk: usize,
    }

    impl std::io::Read for Trickle<'_> {
        fn read(&mut self, out: &mut [u8]) -> std::io::Result<usize> {
            let n = self.data.len().min(self.chunk).min(out.len());
            out[..n].copy_from_slice(&self.data[..n]);
            self.data = &self.data[n..];
            Ok(n)
        }
    }

    /// The bound is inclusive, one byte past it is refused, and the buffer
    /// never reserves more than one byte past it on the way (#653).
    #[test]
    fn read_bounded_takes_the_limit_and_refuses_one_byte_more() {
        let limit = 100_000;
        let data = vec![b'x'; limit + 1];
        for chunk in [1, 7, 4096, limit + 1] {
            for hint in [0, limit, limit + 1, usize::MAX] {
                let whole = read_bounded(
                    Trickle {
                        data: &data[..limit],
                        chunk,
                    },
                    hint,
                    limit,
                )
                .expect("an in-memory read")
                .expect("exactly the limit is read");
                assert_eq!(whole.len(), limit);
                assert!(
                    whole.capacity() <= limit + 1,
                    "{} for {hint}",
                    whole.capacity()
                );
                let over = read_bounded(Trickle { data: &data, chunk }, hint, limit)
                    .expect("an in-memory read");
                assert!(over.is_none(), "{chunk}/{hint}");
            }
        }
        let empty = read_bounded(&b""[..], 0, limit).unwrap().unwrap();
        assert!(empty.is_empty());
        let small = read_bounded(&b"size"[..], 4, limit).unwrap().unwrap();
        assert_eq!(small, b"size");
    }

    /// A saved screen's JSON, pretty as `render --json` writes it.
    fn screen_json() -> String {
        let screen = Screen::parse("size: 6x2  cursor: 1,2\nab 汉\ncd").expect("a screen");
        serde_json::to_string_pretty(&screen).expect("the JSON")
    }

    /// An in-memory operand for [`read`], handed out `chunk` bytes a read.
    fn source(bytes: Vec<u8>, chunk: usize) -> Source<'static> {
        struct Owned {
            data: Vec<u8>,
            at: usize,
            chunk: usize,
        }
        impl std::io::Read for Owned {
            fn read(&mut self, out: &mut [u8]) -> std::io::Result<usize> {
                let n = (self.data.len() - self.at).min(self.chunk).min(out.len());
                out[..n].copy_from_slice(&self.data[self.at..self.at + n]);
                self.at += n;
                Ok(n)
            }
        }
        Source {
            name: "t",
            input: Box::new(Owned {
                data: bytes,
                at: 0,
                chunk,
            }),
            len: 0,
            head: None,
        }
    }

    /// JSON is told from the text format by its head, past a byte-order
    /// mark, an insta header (CRLF or not) and the newlines after it, and
    /// is handed to the parser from there: the whitespace left is the
    /// parser's to judge, so a no-break space is passed on and refused
    /// there. A head that ends before the answer is known says nothing,
    /// and is read as the text format is (#777).
    #[test]
    fn json_is_told_from_its_head() {
        assert_eq!(json_body("{\"format\":1}", true), Some(0));
        assert_eq!(json_body("\u{feff}\n\n {}", true), Some(5));
        assert_eq!(json_body(" \t\r\n{}", true), Some(0));
        assert_eq!(json_body("\u{a0}{}", true), Some(0));
        let snap = "---\nsource: tests/a.rs\nexpression: screen\n---\n{}";
        assert_eq!(json_body(snap, true), Some(snap.len() - 2));
        let crlf = "---\r\nsource: a\r\n---x\r\n---\r\n\r\n{}";
        assert_eq!(json_body(crlf, true), Some(crlf.len() - 4));
        assert_eq!(json_body("size: 2x1  cursor: 0,0\n{}", true), None);
        assert_eq!(
            json_body("---\n{}", true),
            None,
            "a header that never closes"
        );
        // Undecided: the head ends inside the header, or in whitespace.
        assert_eq!(json_body("---\nsource: a\n", false), None);
        assert_eq!(json_body("\n\n  ", false), None);
        assert_eq!(json_body("\n\n  {", false), Some(2));

        let head = |bytes: &[u8]| Head {
            bytes: bytes.to_vec(),
            ended: true,
        };
        assert_eq!(head(b"{}").json(), Some((Encoding::Utf8, 0)));
        assert_eq!(head(b"\xef\xbb\xbf{}").json(), Some((Encoding::Utf8, 3)));
        assert_eq!(
            head(&utf16("\n{}", false)).json(),
            Some((Encoding::Utf16 { big_endian: false }, 4))
        );
        assert_eq!(
            head(&utf16("{}", true)).json(),
            Some((Encoding::Utf16 { big_endian: true }, 3))
        );
        assert_eq!(head(b"size: 1x1  cursor: 0,0\nx").json(), None);
        // Bytes that are not UTF-8 before a document: not JSON by its head,
        // and read whole, where the text reading names them.
        assert_eq!(head(b"\xff\n{}").json(), None);
    }

    /// The text format is held to the limit and JSON is not (#777): a
    /// document ten times the limit reads, from a pipe a few bytes at a
    /// time as from a file, and a text-format input one byte past it is
    /// refused. A regular file in the text format is refused by its length
    /// before it is read; a JSON one past the limit is not.
    #[test]
    fn json_is_not_held_to_the_text_limit() {
        let limit = 16 * 1024;
        let json = screen_json();
        assert!(json.len() < limit);
        let padded = format!("{json}{}", " \n".repeat(5 * limit));
        let expected = Screen::parse("size: 6x2  cursor: 1,2\nab 汉\ncd").unwrap();
        for chunk in [1, 7, 4096] {
            let screen = read(source(padded.clone().into_bytes(), chunk), limit)
                .expect("JSON past the limit reads");
            assert_eq!(screen, expected, "chunk {chunk}");
            let marked = [&[0xef, 0xbb, 0xbf][..], padded.as_bytes()].concat();
            assert_eq!(read(source(marked, chunk), limit), Ok(expected.clone()));
            let wide = utf16(&padded, chunk % 2 == 0);
            assert_eq!(read(source(wide, chunk), limit), Ok(expected.clone()));
        }

        let text = format!("size: 6x2  cursor: 1,2\nab 汉\ncd\n{}", "\n".repeat(limit));
        assert_eq!(
            read(source(text.clone().into_bytes(), 7), limit).unwrap_err(),
            "t: larger than 16384 bytes, which no screen in the text format is"
        );
        let fits = &text[..limit];
        assert!(read(source(fits.as_bytes().to_vec(), 7), limit).is_ok());

        let dir = std::env::temp_dir().join(format!("termlens-unit-limit-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let (big_text, big_json) = (dir.join("big.txt"), dir.join("big.json"));
        std::fs::write(&big_text, &text).unwrap();
        std::fs::write(&big_json, &padded).unwrap();
        let path = big_text.to_str().unwrap();
        let refused = open(path, limit).err().expect("refused by its length");
        assert_eq!(
            refused,
            format!("{path}: larger than 16384 bytes, which no screen in the text format is")
        );
        let source = open(big_json.to_str().unwrap(), limit).expect("JSON opens");
        assert_eq!(read(source, limit), Ok(expected));
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// Run `input` through [`JsonText`] to its end.
    fn pass(input: &[u8]) -> std::io::Result<Vec<u8>> {
        let mut out = Vec::new();
        JsonText::new(input).read_to_end(&mut out).map(|_| out)
    }

    /// The parser's buffers are bounded whatever the input's length
    /// (#777): a string is passed to [`MAX_STRING`] bytes and refused a
    /// byte past it, escapes counted and an escaped quote not ending it,
    /// and nesting is passed to [`MAX_DEPTH`] and refused a level past.
    /// Bytes outside strings — whitespace, numbers — are not counted.
    #[test]
    fn json_text_bounds_strings_and_nesting() {
        let string = |len: usize| format!("{{\"title\":\"{}\"}}", "a".repeat(len));
        assert_eq!(
            pass(string(MAX_STRING).as_bytes()).unwrap().len(),
            MAX_STRING + 12
        );
        let err = pass(string(MAX_STRING + 1).as_bytes()).unwrap_err();
        assert_eq!(
            err.to_string(),
            "a string in the JSON runs past 1 MiB, longer than any a saved screen holds"
        );
        let escaped = format!("\"{}\\\"\"", "a".repeat(MAX_STRING - 2));
        assert!(
            pass(escaped.as_bytes()).is_ok(),
            "the escape is two bytes of the string"
        );
        let escaped = format!("\"{}\\\"a\"", "a".repeat(MAX_STRING - 2));
        assert!(
            pass(escaped.as_bytes()).is_err(),
            "and the quote it escapes does not end it"
        );
        let many = "\"aaaa\",".repeat(MAX_STRING);
        assert!(
            pass(format!("[{many}\"\"]").as_bytes()).is_ok(),
            "each string counts alone"
        );
        let outside = format!("[{}0]", " ".repeat(3 * MAX_STRING));
        assert!(pass(outside.as_bytes()).is_ok());

        let nested = |depth: usize| format!("{}{}", "[".repeat(depth), "]".repeat(depth));
        assert!(pass(nested(MAX_DEPTH).as_bytes()).is_ok());
        let err = pass(nested(MAX_DEPTH + 1).as_bytes()).unwrap_err();
        assert_eq!(
            err.to_string(),
            "the JSON nests deeper than 128, which no saved screen does"
        );
        assert!(
            pass(format!("\"{}\"", "[".repeat(1000)).as_bytes()).is_ok(),
            "inside a string"
        );

        // Through `read`, a refusal is named as what it is, not as a screen
        // that does not parse; the parser adds where it stopped.
        let long = format!("{{\"title\":\"{}\"}}", "a".repeat(MAX_STRING + 1));
        let err = read(source(long.into_bytes(), 4096), 1 << 30).unwrap_err();
        assert!(
            err.starts_with(
                "t: a string in the JSON runs past 1 MiB, longer than any a saved screen holds"
            ),
            "{err}"
        );
    }

    /// UTF-16 streams as the UTF-8 it reads as, a surrogate pair or a code
    /// unit split across reads included, and half a unit or a lone
    /// surrogate is the error [`decode`] gives it (#716, #777).
    #[test]
    fn utf16_text_streams_as_utf8() {
        let text = "{\"汉字\": \"\u{1f600} ok\"}";
        for big_endian in [false, true] {
            let bytes = utf16(text, big_endian);
            for chunk in [1, 2, 3, 5, 4096] {
                let mut out = Vec::new();
                let mut reader =
                    Utf16Text::new(super::tests::source(bytes.clone(), chunk).input, big_endian);
                reader.read_to_end(&mut out).expect("valid UTF-16");
                assert_eq!(
                    String::from_utf8(out).unwrap(),
                    format!("\u{feff}{text}"),
                    "big-endian {big_endian}, chunk {chunk}"
                );
            }
        }
        let mut odd = utf16("ok", false);
        odd.push(b'!');
        let mut lone = utf16("ok", false);
        lone.extend([0x3d, 0xd8, b'!', 0]);
        let mut unpaired = utf16("ok", false);
        unpaired.extend([0x3d, 0xd8]);
        for bytes in [odd, lone, unpaired] {
            let err = Utf16Text::new(&bytes[..], false)
                .read_to_end(&mut Vec::new())
                .unwrap_err();
            assert_eq!(err.to_string(), "stream did not contain valid UTF-16");
        }
        // A JSON document is refused in the words a text one is.
        let mut json = utf16(&screen_json(), false);
        json.extend([0x3d, 0xd8]);
        assert_eq!(
            read(source(json, 4096), 1 << 30),
            Err("t: stream did not contain valid UTF-16".into())
        );
    }

    /// UTF-8 streams to the parser as it is checked, a character split
    /// across reads carried whole to the next, and bytes that are not
    /// UTF-8 anywhere in the input — inside a string, after the document,
    /// cut off by its end — are the error a text-format input gets, as
    /// they were before JSON streamed (#777): serde_json named one inside a
    /// string "invalid unicode code point" and called the input "not a
    /// termlens Screen", and named one after the document "trailing
    /// characters".
    #[test]
    fn utf8_text_streams_checked() {
        let text = "{\"汉字\": \"\u{1f600} é ok\"}";
        for chunk in [1, 2, 3, 5, 4096] {
            let mut out = Vec::new();
            Utf8Text::new(source(text.as_bytes().to_vec(), chunk).input)
                .read_to_end(&mut out)
                .expect("valid UTF-8");
            assert_eq!(out, text.as_bytes(), "chunk {chunk}");
        }
        let emoji = "\u{1f600}".as_bytes();
        for bytes in [
            // Latin-1's é, a lone continuation byte, an overlong `/`, a
            // surrogate, and an emoji cut off by the end of the input.
            &b"{\"t\": \"caf\xe9\"}"[..],
            &b"{\"t\": \"\x80\"}"[..],
            &b"{\"t\": \"\xc0\xaf\"}"[..],
            &b"{\"t\": \"\xed\xa0\x80\"}"[..],
            &[b"{} ".as_slice(), &emoji[..3]].concat(),
        ] {
            for chunk in [1, 4096] {
                let err = Utf8Text::new(source(bytes.to_vec(), chunk).input)
                    .read_to_end(&mut Vec::new())
                    .unwrap_err();
                assert_eq!(err.kind(), std::io::ErrorKind::InvalidData);
                assert_eq!(err.to_string(), "stream did not contain valid UTF-8");
            }
        }
        for tail in [&b"\xe9\n"[..], b""] {
            let json = screen_json().replacen("\"title\": \"\"", "\"title\": \"caf\u{e9}\"", 1);
            let mut bytes = json.into_bytes();
            if tail.is_empty() {
                // The é, recoded as Latin-1, inside the document.
                let at = bytes.windows(2).position(|w| w == b"\xc3\xa9").unwrap();
                bytes.splice(at..at + 2, [0xe9]);
            } else {
                bytes.extend_from_slice(tail);
            }
            assert_eq!(
                read(source(bytes, 4096), 1 << 30),
                Err("t: stream did not contain valid UTF-8".into())
            );
        }
    }
}