rs-rich-interact 0.0.13

Interactive terminal components for rs-rich: event loop, viewport, item model, headless testing
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
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
//! The terminal session: raw mode, the alternate screen, mouse and paste
//! modes, the kitty keyboard protocol, synchronized output, and their
//! restoration on every way out (#489).
//!
//! Everything a [`Session`] turns on is recorded in a process-wide flag
//! set, and undone by whichever comes first: [`Session::leave`], dropping
//! the session (an early return, `?`), or a panic, through a hook installed
//! on first use that restores the terminal before the panic message prints
//! (a panic caught by [`catch_panic`], which the session survives, leaves
//! it alone).
//! Ctrl+C arrives as a key in raw mode, so it ends the event loop the
//! ordinary way. On Unix, SIGTERM, SIGHUP and SIGQUIT restore the terminal
//! too, from a thread that then takes the signal's default action. Ctrl+Z
//! (a key in raw mode) and SIGTSTP suspend: the terminal is given back, the
//! process stops as the shell expects, and on `fg` the modes come back and
//! the view repaints. [`Session::handoff`] gives the terminal to another program
//! (`$EDITOR`, a pager) and takes it back.
//!
//! A session drives the terminal with one library, its
//! [`BackendKind`]: crossterm by default, or termion (#677) or termwiz
//! (#678) behind their features. The library reads keys, the mouse and
//! resizes, measures the terminal, and turns raw mode and the alternate
//! screen on and off; what is turned on, and how it is given back on every
//! way out above, is the same whichever it is.
//!
//! Where the terminal has synchronized output (DEC private mode 2026), each
//! frame is written as one synchronized update: between `CSI ? 2026 h` and
//! `CSI ? 2026 l`, so the terminal shows it whole, without tearing, and a
//! screen reader that follows the cursor does not see it jump across each
//! changed region. The terminal is asked in the start-up query that asks
//! for the kitty keyboard protocol, so detecting it costs no extra wait;
//! `RICH_SYNC_OUTPUT` and [`SessionOptions::synchronized_output`] override
//! what it answers.
//!
//! The terminal's modes are process-wide, so only one session exists at a
//! time: starting a second while the first is alive (a component that
//! calls [`run`](crate::run) from inside another) fails with
//! [`io::ErrorKind::ResourceBusy`] and changes nothing.

#[cfg(target_arch = "wasm32")]
use crate::crossterm_stub as crossterm;
use std::cell::Cell;
use std::fmt;
use std::io::{self, Write};
use std::panic::UnwindSafe;
use std::process::Command;
use std::sync::Once;
use std::sync::atomic::{AtomicBool, AtomicU8, Ordering};
use std::time::{Duration, Instant};

#[cfg(target_arch = "wasm32")]
use crate::crossterm_stub::{from_crossterm, from_crossterm_kitty};
use crate::event::Event;
#[cfg(not(target_arch = "wasm32"))]
use crate::event::{from_crossterm, from_crossterm_kitty};

#[cfg(all(unix, feature = "termion"))]
mod with_termion;
#[cfg(feature = "termwiz")]
mod with_termwiz;

const RAW: u8 = 1;
const ALTERNATE: u8 = 2;
const MOUSE: u8 = 4;
const PASTE: u8 = 8;
const KITTY: u8 = 16;
/// Frames are written as synchronized updates: the restore ends one a write
/// cut short left open.
const SYNC: u8 = 32;
/// The mouse is reported in pixels (SGR-Pixels, mode 1016; #819).
const PIXELS: u8 = 64;

/// The kitty keyboard protocol's flags a session pushes: disambiguate the
/// keys a legacy terminal sends alike (1) and report releases and repeats
/// (2). Not every key as an escape code (8): typed text would then arrive
/// as a base key and modifiers rather than the character the layout makes,
/// so plain text keys, Enter, Tab and Backspace report no release. The
/// terminal keeps a stack of flags for each screen, so they are pushed
/// after entering the alternate screen and popped before leaving it.
/// termwiz reads the first flag's keys but not the second's releases, so
/// a termwiz session pushes the first only.
const PUSH_KITTY: &str = "\x1b[>3u";
/// The flags [`SessionOptions::all_keys`] pushes: those two, every key as
/// an escape code (8), so text keys report releases and modifier keys
/// report themselves, and the alternate keys (4), so a shifted key still
/// arrives as the character the layout makes (`!`, not Shift and `1`).
const PUSH_KITTY_ALL: &str = "\x1b[>15u";
#[cfg(feature = "termwiz")]
const PUSH_KITTY_KEYS: &str = "\x1b[>1u";
const POP_KITTY: &str = "\x1b[<1u";

/// What the terminal answered the start-up query ([`Answers::encode`]): 0
/// not asked yet. Asked once a process, since asking can wait for a
/// terminal that does not answer.
static ANSWERS: AtomicU8 = AtomicU8::new(0);

/// Begins a synchronized update (DEC private mode 2026): the terminal holds
/// the screen until [`END_SYNCHRONIZED_UPDATE`].
pub const BEGIN_SYNCHRONIZED_UPDATE: &str = "\x1b[?2026h";
/// Ends a synchronized update: the terminal shows what was written since
/// [`BEGIN_SYNCHRONIZED_UPDATE`] in one go.
pub const END_SYNCHRONIZED_UPDATE: &str = "\x1b[?2026l";
/// Asks whether the terminal knows mode 2026 (DECRQM). Sent first, before
/// the kitty query and the device attributes: a reply arriving after the
/// session stopped waiting then runs into theirs, which crossterm's parser
/// reads as one answer of its own, never as keys.
#[cfg(unix)]
const ASK_SYNC: &str = "\x1b[?2026$p";
/// The environment variable that turns synchronized output off (`0`) or on
/// (`1`) whatever the terminal answers.
pub const SYNC_OUTPUT_ENV: &str = "RICH_SYNC_OUTPUT";
/// Asks whether the terminal knows SGR-Pixels mouse reports (mode 1016,
/// DECRQM), in the start-up query after synchronized output's question.
#[cfg(unix)]
const ASK_PIXELS: &str = "\x1b[?1016$p";
/// The environment variable that turns pixel-precise mouse reports off
/// (`0`) whatever the terminal answers. On by default where the terminal
/// knows mode 1016 and says how big its cells are.
pub const PIXEL_MOUSE_ENV: &str = "RICH_PIXEL_MOUSE";

/// Whether `RICH_PIXEL_MOUSE`'s `value` allows pixel reports: anything but
/// `0` (unset too).
fn pixels_allowed(value: Option<&str>) -> bool {
    value.map(str::trim) != Some("0")
}

/// `frame` as one synchronized update; nothing for an empty frame.
pub fn synchronized_update(frame: &str) -> String {
    if frame.is_empty() {
        return String::new();
    }
    let mut out = String::with_capacity(
        BEGIN_SYNCHRONIZED_UPDATE.len() + frame.len() + END_SYNCHRONIZED_UPDATE.len(),
    );
    out.push_str(BEGIN_SYNCHRONIZED_UPDATE);
    out.push_str(frame);
    out.push_str(END_SYNCHRONIZED_UPDATE);
    out
}

/// What `RICH_SYNC_OUTPUT`'s `value` forces: `0` off, `1` on; anything else,
/// or unset, leaves it to the terminal's answer.
fn sync_override(value: Option<&str>) -> Option<bool> {
    match value.map(str::trim) {
        Some("0") => Some(false),
        Some("1") => Some(true),
        _ => None,
    }
}

/// What the environment forces synchronized output to, if anything.
fn sync_from_env() -> Option<bool> {
    sync_override(std::env::var(SYNC_OUTPUT_ENV).ok().as_deref())
}

/// What is currently turned on, for the panic hook.
static ACTIVE: AtomicU8 = AtomicU8::new(0);
static HOOK: Once = Once::new();
/// Whether a [`Session`] is alive. Held from `start` until drop.
static OWNED: AtomicBool = AtomicBool::new(false);
/// Whether the live session paints to standard error, for the panic hook.
static ON_STDERR: AtomicBool = AtomicBool::new(false);
/// The library the live session drives the terminal with
/// ([`BackendKind::index`]), for the panic hook and the signal thread.
static LIBRARY: AtomicU8 = AtomicU8::new(0);

/// The library a [`Session`] drives the terminal with
/// ([`SessionOptions::backend`]).
///
/// Each reads keys, the mouse and resizes its own way and turns raw mode
/// and the alternate screen on and off itself; the modes a session turns
/// on, and their restoration on every way out, are the same for all of
/// them. termion and termwiz are behind the crate's features of the same
/// names, off by default.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum BackendKind {
    /// crossterm, on every platform: the default. With a terminal that has
    /// the kitty keyboard protocol, every key is
    /// [`exact`](crate::Key::exact) and releases arrive.
    #[default]
    Crossterm,
    /// termion (feature `termion`), on Unix. Keys arrive as a legacy
    /// terminal sends them, whatever the terminal: termion does not read
    /// the kitty keyboard protocol. The mouse comes without modifiers, and
    /// without movement while no button is held.
    #[cfg(all(unix, feature = "termion"))]
    Termion,
    /// termwiz (feature `termwiz`), on Unix and Windows. With a terminal
    /// that has the kitty keyboard protocol every key is exact, but releases
    /// do not arrive: termwiz does not read them. Its probe of the terminal
    /// (terminfo, `COLORTERM`) decides the colours an
    /// [`EventLoop`](crate::EventLoop) paints with.
    #[cfg(feature = "termwiz")]
    Termwiz,
}

impl BackendKind {
    /// Every backend this build has, crossterm first.
    pub const ALL: &'static [BackendKind] = &[
        BackendKind::Crossterm,
        #[cfg(all(unix, feature = "termion"))]
        BackendKind::Termion,
        #[cfg(feature = "termwiz")]
        BackendKind::Termwiz,
    ];

    /// The library's name: `crossterm`, `termion` or `termwiz`.
    pub fn name(self) -> &'static str {
        match self {
            BackendKind::Crossterm => "crossterm",
            #[cfg(all(unix, feature = "termion"))]
            BackendKind::Termion => "termion",
            #[cfg(feature = "termwiz")]
            BackendKind::Termwiz => "termwiz",
        }
    }

    /// The backend named `name` (any case), if this build has it.
    pub fn from_name(name: &str) -> Option<BackendKind> {
        BackendKind::ALL
            .iter()
            .copied()
            .find(|kind| kind.name().eq_ignore_ascii_case(name))
    }

    fn index(self) -> u8 {
        match self {
            BackendKind::Crossterm => 0,
            #[cfg(all(unix, feature = "termion"))]
            BackendKind::Termion => 1,
            #[cfg(feature = "termwiz")]
            BackendKind::Termwiz => 2,
        }
    }

    /// The library the live session uses.
    fn live() -> BackendKind {
        let index = LIBRARY.load(Ordering::SeqCst);
        BackendKind::ALL
            .iter()
            .copied()
            .find(|kind| kind.index() == index)
            .unwrap_or_default()
    }

    /// Turn raw mode on or off. `wait`: wait for the library's lock (off
    /// in the panic hook, whose thread may hold it).
    fn raw_mode(self, on: bool, wait: bool) -> io::Result<()> {
        let _ = wait;
        match self {
            BackendKind::Crossterm if on => crossterm::terminal::enable_raw_mode(),
            BackendKind::Crossterm => crossterm::terminal::disable_raw_mode(),
            #[cfg(all(unix, feature = "termion"))]
            BackendKind::Termion => with_termion::raw_mode(on, wait),
            #[cfg(feature = "termwiz")]
            BackendKind::Termwiz => with_termwiz::raw_mode(on, wait),
        }
    }

    /// Whether the library enters and leaves the alternate screen with a
    /// call of its own, keeping track of it (termwiz), rather than having
    /// the session write it with the other modes.
    fn owns_alternate_screen(self) -> bool {
        #[cfg(feature = "termwiz")]
        if self == BackendKind::Termwiz {
            return true;
        }
        false
    }

    /// Enter or leave the alternate screen through a library that
    /// [owns it](Self::owns_alternate_screen); `None` for one that has the
    /// session write it, as [`alternate_sequence`](Self::alternate_sequence)
    /// says.
    fn alternate_screen(self, on: bool, wait: bool) -> Option<io::Result<()>> {
        let _ = (on, wait);
        match self {
            #[cfg(feature = "termwiz")]
            BackendKind::Termwiz => Some(with_termwiz::alternate_screen(on, wait)),
            _ => None,
        }
    }

    /// The sequence that enters (`on`) or leaves the alternate screen, for
    /// a library without a call of its own: termion's
    /// `ToAlternateScreen` and `ToMainScreen`, and crossterm's same bytes.
    fn alternate_sequence(self, on: bool) -> String {
        match self {
            #[cfg(all(unix, feature = "termion"))]
            BackendKind::Termion if on => termion::screen::ToAlternateScreen.to_string(),
            #[cfg(all(unix, feature = "termion"))]
            BackendKind::Termion => termion::screen::ToMainScreen.to_string(),
            _ if on => "\x1b[?1049h".into(),
            _ => "\x1b[?1049l".into(),
        }
    }

    /// The kitty keyboard flags this library reads keys with.
    fn kitty_push(self) -> &'static str {
        match self {
            #[cfg(feature = "termwiz")]
            BackendKind::Termwiz => PUSH_KITTY_KEYS,
            _ => PUSH_KITTY,
        }
    }

    /// What to write once the library's raw mode is off, for what turning
    /// it off leaves on: termwiz's raw mode sets xterm's modifyOtherKeys to
    /// level 2 and its cooked mode to 1, and only dropping its terminal
    /// sets it back to 0, as a shell or a program handed the terminal
    /// expects.
    fn after_raw_mode(self) -> &'static str {
        match self {
            #[cfg(all(unix, feature = "termwiz"))]
            BackendKind::Termwiz => "\x1b[>4;0m",
            _ => "",
        }
    }

    /// Give back what the library holds once the session is over.
    fn release(self) {
        match self {
            #[cfg(all(unix, feature = "termion"))]
            BackendKind::Termion => with_termion::release(),
            #[cfg(feature = "termwiz")]
            BackendKind::Termwiz => with_termwiz::release(),
            _ => {}
        }
    }
}

impl fmt::Display for BackendKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.name())
    }
}

/// Where a session paints.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Output {
    /// Standard output.
    #[default]
    Stdout,
    /// Standard error, which leaves standard output to the answer a script
    /// captures: `choice=$(rich choose a b c)`. Keys still come from the
    /// terminal, which crossterm opens itself when standard input is a pipe.
    Stderr,
}

impl Output {
    /// Whether the stream is a terminal.
    pub fn is_terminal(self) -> bool {
        use std::io::IsTerminal;
        match self {
            Output::Stdout => io::stdout().is_terminal(),
            Output::Stderr => io::stderr().is_terminal(),
        }
    }

    fn write(self, text: &str) -> io::Result<()> {
        match self {
            Output::Stdout => {
                let mut out = io::stdout().lock();
                out.write_all(text.as_bytes())?;
                out.flush()
            }
            Output::Stderr => {
                let mut out = io::stderr().lock();
                out.write_all(text.as_bytes())?;
                out.flush()
            }
        }
    }

    /// The live session's stream.
    fn live() -> Output {
        if ON_STDERR.load(Ordering::SeqCst) {
            Output::Stderr
        } else {
            Output::Stdout
        }
    }
}

/// Whether keys can be read from a terminal: standard input, or the
/// process's controlling terminal when standard input is a pipe.
pub(crate) fn keys_available() -> bool {
    use std::io::IsTerminal;
    if io::stdin().is_terminal() {
        return true;
    }
    #[cfg(unix)]
    let terminal = "/dev/tty";
    #[cfg(windows)]
    let terminal = "CONIN$";
    #[cfg(any(unix, windows))]
    return std::fs::OpenOptions::new()
        .read(true)
        .write(true)
        .open(terminal)
        .is_ok();
    #[cfg(not(any(unix, windows)))]
    false
}

/// Undo whatever `ACTIVE` records. Safe to call twice. `wait`: as for
/// [`BackendKind::raw_mode`].
fn restore(wait: bool) -> io::Result<()> {
    let active = ACTIVE.swap(0, Ordering::SeqCst);
    if active == 0 {
        return Ok(());
    }
    let library = BackendKind::live();
    let out = undo(active, library);
    // Every step is tried, so a failed one leaves no other on; the first
    // error is the one returned.
    let written = Output::live().write(&out);
    let left = if active & ALTERNATE != 0 {
        library.alternate_screen(false, wait).unwrap_or(Ok(()))
    } else {
        Ok(())
    };
    let raw = if active & RAW != 0 {
        let off = library.raw_mode(false, wait);
        let after = match library.after_raw_mode() {
            "" => Ok(()),
            after => Output::live().write(after),
        };
        off.and(after)
    } else {
        Ok(())
    };
    written.and(left).and(raw)
}

/// The sequences that turn off what `active` records: all of it, but for
/// the alternate screen of a library that leaves it itself. A synchronized
/// update first, so a frame cut short (a panic, a signal mid-write) is
/// shown and the rest are not held.
fn undo(active: u8, library: BackendKind) -> String {
    let mut out = String::new();
    if active & SYNC != 0 {
        out.push_str(END_SYNCHRONIZED_UPDATE);
    }
    if active & KITTY != 0 {
        out.push_str(POP_KITTY);
    }
    if active & PIXELS != 0 {
        out.push_str("\x1b[?1016l");
    }
    if active & MOUSE != 0 {
        out.push_str("\x1b[?1006l\x1b[?1015l\x1b[?1003l\x1b[?1002l\x1b[?1000l");
    }
    if active & PASTE != 0 {
        out.push_str("\x1b[?2004l");
    }
    out.push_str("\x1b[?25h");
    if active & ALTERNATE != 0 && !library.owns_alternate_screen() {
        out.push_str(&library.alternate_sequence(false));
    }
    out
}

/// Raw mode is on for a line read without echo
/// ([`StdLineIo::read_secret`](crate::policy::StdLineIo)), outside any
/// session: the signal thread turns it off too.
static RAW_LINE: AtomicBool = AtomicBool::new(false);
#[cfg(unix)]
static SIGNALS: Once = Once::new();

/// Record that a line is being read in raw mode (`on`), or no longer is.
pub(crate) fn raw_line(on: bool) {
    if on {
        watch_signals();
    }
    RAW_LINE.store(on, Ordering::SeqCst);
}

/// SIGTERM, SIGHUP and SIGQUIT end the process without unwinding, so
/// neither `Drop` nor the panic hook would give the terminal back. From
/// the first session on, a thread waits for them: it restores whatever is
/// on, then takes the signal's default action (the process ends as it
/// would have). The handlers stay installed once the session ends, since
/// removing them would leave the signals ignored; with nothing on they
/// only take the default action.
fn watch_signals() {
    #[cfg(unix)]
    SIGNALS.call_once(|| {
        use signal_hook::consts::{SIGHUP, SIGQUIT, SIGTERM, SIGTSTP};
        let Ok(mut signals) =
            signal_hook::iterator::Signals::new([SIGTERM, SIGHUP, SIGQUIT, SIGTSTP])
        else {
            return;
        };
        let _ = std::thread::Builder::new()
            .name("rich-interact-signals".into())
            .spawn(move || {
                for signal in signals.forever() {
                    if signal == SIGTSTP {
                        suspend();
                        RESUMED.store(true, Ordering::SeqCst);
                    } else {
                        restore_for_signal();
                        run_teardowns();
                        let _ = signal_hook::low_level::emulate_default_handler(signal);
                    }
                }
            });
    });
}

/// What [`on_terminate`] registered.
type Teardown = Box<dyn Fn() + Send + Sync>;
static TEARDOWNS: std::sync::Mutex<Vec<Teardown>> = std::sync::Mutex::new(Vec::new());

/// Run `teardown` when SIGTERM, SIGHUP or SIGQUIT ends the process, from
/// the first session on: on the signal thread, after the terminal is given
/// back and before the signal's default action ends the process. Those
/// signals end it without unwinding, so a `Drop` that stops a child
/// process or removes temporary files never runs; this is where to do that
/// work. Keep it short: the process ends when it returns. Teardowns run in
/// the order they were registered, once each. Not on Windows, which has
/// none of those signals.
pub fn on_terminate(teardown: impl Fn() + Send + Sync + 'static) {
    TEARDOWNS
        .lock()
        .unwrap_or_else(|e| e.into_inner())
        .push(Box::new(teardown));
}

/// Run and forget every teardown [`on_terminate`] registered.
#[cfg(unix)]
fn run_teardowns() {
    let all = std::mem::take(&mut *TEARDOWNS.lock().unwrap_or_else(|e| e.into_inner()));
    for teardown in all {
        teardown();
    }
}

/// [`restore`] from the signal thread. The sequences go straight to the
/// terminal rather than through the standard stream's lock, which the
/// interrupted thread may hold.
#[cfg(unix)]
fn restore_for_signal() {
    let active = ACTIVE.swap(0, Ordering::SeqCst);
    let library = BackendKind::live();
    if active != 0 {
        write_direct(&undo(active, library));
    }
    if active & ALTERNATE != 0 {
        let _ = library.alternate_screen(false, true);
    }
    if active & RAW != 0 {
        let _ = library.raw_mode(false, true);
        write_direct(library.after_raw_mode());
    }
    if RAW_LINE.swap(false, Ordering::SeqCst) {
        let _ = crossterm::terminal::disable_raw_mode();
    }
}

/// Set when the process came back from a suspend it did not start itself
/// (SIGTSTP from outside): [`Session::read`] then asks for a repaint.
static RESUMED: AtomicBool = AtomicBool::new(false);

/// Give the terminal back, stop the process as a shell's job control
/// expects (Ctrl+Z, `kill -TSTP`), and when it continues (`fg`, SIGCONT)
/// turn back on what was on. SIGSTOP cannot be caught, so it still stops
/// with the modes on.
/// Held for the whole of a suspend, from giving the terminal back until its
/// modes are on again, and by [`Session::leave`]. A resume from an outside
/// SIGTSTP runs on the signal thread while the event loop runs on, so
/// without it a session that ended during the stop (a key queued, a timer
/// due) would have its modes turned back on after it restored them.
/// `enter` holds it while it marks the modes on and writes them.
static SUSPENDING: std::sync::Mutex<()> = std::sync::Mutex::new(());

#[cfg(unix)]
fn suspend() {
    let _suspending = SUSPENDING.lock().unwrap_or_else(|e| e.into_inner());
    let active = ACTIVE.load(Ordering::SeqCst);
    let raw_line = RAW_LINE.load(Ordering::SeqCst);
    let library = BackendKind::live();
    restore_for_signal();
    // Stops here until SIGCONT.
    let _ = signal_hook::low_level::emulate_default_handler(signal_hook::consts::SIGTSTP);
    if active & RAW != 0 {
        let _ = library.raw_mode(true, true);
    }
    if raw_line {
        let _ = crossterm::terminal::enable_raw_mode();
    }
    RAW_LINE.store(raw_line, Ordering::SeqCst);
    let mut out = String::new();
    if active & ALTERNATE != 0 {
        if library.alternate_screen(true, true).is_none() {
            out.push_str(&library.alternate_sequence(true));
        }
        out.push_str("\x1b[H");
    }
    if active & KITTY != 0 {
        out.push_str(library.kitty_push());
    }
    if active & MOUSE != 0 {
        out.push_str("\x1b[?1000h\x1b[?1002h\x1b[?1015h\x1b[?1006h");
    }
    if active & PIXELS != 0 {
        out.push_str("\x1b[?1016h");
    }
    if active & PASTE != 0 {
        out.push_str("\x1b[?2004h");
    }
    if active != 0 {
        out.push_str("\x1b[?25l");
    }
    ACTIVE.fetch_or(active, Ordering::SeqCst);
    write_direct(&out);
}

/// `text` straight to the terminal, else to the session's stream.
#[cfg(unix)]
fn write_direct(text: &str) {
    if text.is_empty() {
        return;
    }
    let direct = std::fs::OpenOptions::new()
        .write(true)
        .open("/dev/tty")
        .and_then(|mut tty| tty.write_all(text.as_bytes()));
    if direct.is_err() {
        let _ = Output::live().write(text);
    }
}

/// A library's lock, for a backend that keeps its terminal where the panic
/// hook and the signal thread reach it. With `wait` off it gives up at once
/// rather than wait for a holder, which may be the panicking thread itself.
#[cfg(any(all(unix, feature = "termion"), feature = "termwiz"))]
fn lock<T>(mutex: &std::sync::Mutex<T>, wait: bool) -> io::Result<std::sync::MutexGuard<'_, T>> {
    use std::sync::TryLockError;
    if wait {
        return Ok(mutex.lock().unwrap_or_else(|e| e.into_inner()));
    }
    match mutex.try_lock() {
        Ok(guard) => Ok(guard),
        Err(TryLockError::Poisoned(e)) => Ok(e.into_inner()),
        Err(TryLockError::WouldBlock) => Err(io::ErrorKind::WouldBlock.into()),
    }
}

/// How long the session waits for the terminal to answer a query: a
/// terminal that answers does so within a few milliseconds, even over a
/// slow link well inside this.
#[cfg(unix)]
const ANSWER_WAIT: Duration = Duration::from_secs(1);

/// How much longer it waits once keys come instead of an answer: someone
/// is typing, and a terminal that has not answered by then likely never
/// will. The keys are kept, not lost.
#[cfg(unix)]
const ANSWER_WAIT_TYPING: Duration = Duration::from_millis(250);

/// What [`ask_terminal`] read: everything, answer or not (keys typed
/// meanwhile among it), and whether `done` said the answer was complete.
#[cfg(unix)]
struct Asked {
    bytes: Vec<u8>,
    answered: bool,
}

/// Ask the terminal `query` through `/dev/tty`, and read until `done` says
/// the answer is complete, for [`ANSWER_WAIT`] at most (a terminal that
/// does not answer), or [`ANSWER_WAIT_TYPING`] after keys come. What it
/// returns holds anything else read meanwhile, such as keys typed, for
/// the reader; `None` only when the terminal cannot be opened or asked.
#[cfg(unix)]
fn ask_terminal(query: &str, done: impl Fn(&[u8]) -> bool) -> Option<Asked> {
    use std::io::Read;
    use std::os::unix::io::AsRawFd;
    let mut tty = std::fs::OpenOptions::new()
        .read(true)
        .write(true)
        .open("/dev/tty")
        .ok()?;
    tty.write_all(query.as_bytes()).ok()?;
    tty.flush().ok()?;
    let mut end = Instant::now() + ANSWER_WAIT;
    let mut typing = false;
    let mut bytes = Vec::new();
    loop {
        if done(&bytes) {
            return Some(Asked {
                bytes,
                answered: true,
            });
        }
        if !typing && !strip_answers(&bytes).is_empty() {
            typing = true;
            end = end.min(Instant::now() + ANSWER_WAIT_TYPING);
        }
        let left = end.saturating_duration_since(Instant::now());
        if left.is_zero() {
            break;
        }
        let mut ready = [filedescriptor::pollfd {
            fd: tty.as_raw_fd(),
            events: filedescriptor::POLLIN,
            revents: 0,
        }];
        match filedescriptor::poll(&mut ready, Some(left)) {
            Ok(0) => break,
            Ok(_) => {}
            Err(filedescriptor::Error::Poll(e)) if e.kind() == io::ErrorKind::Interrupted => {
                continue;
            }
            Err(_) => break,
        }
        let mut buffer = [0u8; 256];
        match tty.read(&mut buffer) {
            Ok(0) | Err(_) => break,
            Ok(read) => bytes.extend_from_slice(&buffer[..read]),
        }
    }
    Some(Asked {
        bytes,
        answered: false,
    })
}

/// `bytes` without the private answers in it (see [`private_answers`]),
/// nor one cut short at its end: what was typed meanwhile.
#[cfg(any(unix, test))]
fn strip_answers(bytes: &[u8]) -> Vec<u8> {
    let mut rest = Vec::new();
    let mut at = 0;
    while at < bytes.len() {
        if !bytes[at..].starts_with(b"\x1b[?") {
            rest.push(bytes[at]);
            at += 1;
            continue;
        }
        let mut end = at + 3;
        while end < bytes.len() && (0x20..=0x3f).contains(&bytes[end]) {
            end += 1;
        }
        match bytes.get(end) {
            // Cut short: it is not keys.
            None => break,
            Some(0x40..=0x7e) => at = end + 1,
            Some(_) => at = end,
        }
    }
    rest
}

/// One complete `ESC [ ? <parameters> <intermediates> <final>` in what the
/// terminal answered: the shape of the device attributes answer (`c`), the
/// kitty flags one (`u`) and DECRQM's (`$ y`).
#[cfg(any(unix, test))]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct PrivateAnswer<'a> {
    parameters: &'a [u8],
    intermediates: &'a [u8],
    last: u8,
}

/// Each complete private answer in `bytes`, in order. Anything else (keys
/// typed meanwhile, an answer cut short) is passed over.
#[cfg(any(unix, test))]
fn private_answers(bytes: &[u8]) -> impl Iterator<Item = PrivateAnswer<'_>> + '_ {
    let mut at = 0;
    std::iter::from_fn(move || {
        while at + 3 <= bytes.len() {
            if !bytes[at..].starts_with(b"\x1b[?") {
                at += 1;
                continue;
            }
            let start = at + 3;
            let mut end = start;
            while end < bytes.len() && (0x30..=0x3f).contains(&bytes[end]) {
                end += 1;
            }
            let middle = end;
            while end < bytes.len() && (0x20..=0x2f).contains(&bytes[end]) {
                end += 1;
            }
            match bytes.get(end) {
                None => return None,
                Some(&last @ 0x40..=0x7e) => {
                    at = end + 1;
                    return Some(PrivateAnswer {
                        parameters: &bytes[start..middle],
                        intermediates: &bytes[middle..end],
                        last,
                    });
                }
                // Not an answer: look again from the byte that broke it.
                Some(_) => at = end,
            }
        }
        None
    })
}

/// What the terminal answered the start-up query.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
struct Answers {
    /// It has the kitty keyboard protocol.
    kitty: bool,
    /// It knows synchronized output (mode 2026).
    sync: bool,
    /// It knows SGR-Pixels mouse reports (mode 1016).
    pixels: bool,
}

impl Answers {
    /// For [`ANSWERS`]: never 0.
    fn encode(self) -> u8 {
        1 | (u8::from(self.kitty) << 1) | (u8::from(self.sync) << 2) | (u8::from(self.pixels) << 3)
    }

    fn decode(bits: u8) -> Answers {
        Answers {
            kitty: bits & 2 != 0,
            sync: bits & 4 != 0,
            pixels: bits & 8 != 0,
        }
    }

    /// The answers in `bytes`, once the device attributes, which every
    /// terminal answers last, have come; `None` before. A DECRQM report of
    /// mode 2026 set, reset or permanently set (1, 2, 3) means the terminal
    /// knows it; not recognised (0) or permanently reset (4), or no report,
    /// means it does not.
    #[cfg(any(unix, test))]
    fn read(bytes: &[u8]) -> Option<Answers> {
        let mut answers = Answers::default();
        for answer in private_answers(bytes) {
            match (answer.last, answer.intermediates) {
                (b'c', b"") => return Some(answers),
                (b'u', b"") => answers.kitty = true,
                (b'y', b"$") => {
                    if let Some(state) = answer.parameters.strip_prefix(b"2026;") {
                        answers.sync = matches!(state, b"1" | b"2" | b"3");
                    }
                    if let Some(state) = answer.parameters.strip_prefix(b"1016;") {
                        answers.pixels = matches!(state, b"1" | b"2" | b"3");
                    }
                }
                _ => {}
            }
        }
        None
    }
}

/// The start-up query, asked directly: synchronized output, the kitty
/// keyboard protocol's flags, then the device attributes, which every
/// terminal answers, so a terminal without the others answers only the
/// last. One round trip for both questions. Also what was typed while the
/// session waited (keys pressed as the program opened), for the reader.
#[cfg(unix)]
fn ask_start() -> (Answers, Vec<u8>) {
    let query = format!("{ASK_SYNC}{ASK_PIXELS}\x1b[?u\x1b[c");
    match ask_terminal(&query, |bytes| Answers::read(bytes).is_some()) {
        Some(asked) => {
            let answers = match asked.answered {
                true => Answers::read(&asked.bytes).unwrap_or_default(),
                false => Answers::default(),
            };
            (answers, strip_answers(&asked.bytes))
        }
        None => (Answers::default(), Vec::new()),
    }
}

/// The first complete cursor position report (`ESC [ <row> ; <column> R`)
/// in `bytes`: its row (0-based), and where it is. Anything else (a key
/// typed meanwhile, a mouse report, an answer cut short) is passed over.
#[cfg(any(all(unix, any(feature = "termion", feature = "termwiz")), test))]
fn cursor_report(bytes: &[u8]) -> Option<(u16, std::ops::Range<usize>)> {
    let digits = |from: usize| {
        from + bytes[from..]
            .iter()
            .take_while(|b| b.is_ascii_digit())
            .count()
    };
    let mut at = 0;
    while let Some(found) = bytes[at..].windows(2).position(|w| w == b"\x1b[") {
        let start = at + found;
        let row_end = digits(start + 2);
        if row_end > start + 2 && bytes.get(row_end) == Some(&b';') {
            let end = digits(row_end + 1);
            if end > row_end + 1 && bytes.get(end) == Some(&b'R') {
                let row = std::str::from_utf8(&bytes[start + 2..row_end]).map(str::parse::<u16>);
                if let Ok(Ok(row)) = row {
                    return Some((row.saturating_sub(1), start..end + 1));
                }
            }
        }
        at = start + 1;
    }
    None
}

/// The cursor's row (0-based), asked directly (`CSI 6 n`), and the rest of
/// what was read with the answer (keys typed meanwhile), for the reader.
#[cfg(all(unix, any(feature = "termion", feature = "termwiz")))]
fn ask_cursor_row() -> (Option<u16>, Vec<u8>) {
    let Some(Asked { bytes, .. }) = ask_terminal("\x1b[6n", |bytes| cursor_report(bytes).is_some())
    else {
        return (None, Vec::new());
    };
    match cursor_report(&bytes) {
        Some((row, at)) => {
            let mut rest = bytes[..at.start].to_vec();
            rest.extend_from_slice(&bytes[at.end..]);
            (Some(row), rest)
        }
        None => (None, bytes),
    }
}

/// The terminal's cell size in pixels (width, height), from the window
/// size's pixel fields (`TIOCGWINSZ`); `None` where the terminal leaves
/// them 0 or there is none, and then the mouse stays in cells.
fn cell_size() -> Option<(u16, u16)> {
    let size = crossterm::terminal::window_size().ok()?;
    cell_of(size.columns, size.rows, size.width, size.height)
}

/// One cell's size for a window of `columns` by `rows` cells and `width`
/// by `height` pixels; `None` when any is 0.
fn cell_of(columns: u16, rows: u16, width: u16, height: u16) -> Option<(u16, u16)> {
    if columns == 0 || rows == 0 || width < columns || height < rows {
        return None;
    }
    Some((width / columns, height / rows))
}

thread_local! {
    /// How many [`catch_panic`] calls are running on this thread.
    static CATCHING: Cell<usize> = const { Cell::new(0) };
}

/// [`std::panic::catch_unwind`] for code that runs inside a live session
/// and carries on after a panic (a plugin component's
/// [`PluginView`](crate::plugin::PluginView)): the session's panic hook
/// neither gives the terminal back nor prints the panic message over the
/// view for a panic caught here, since the session goes on. A panic nothing
/// catches still restores the terminal before its message prints.
pub fn catch_panic<R>(f: impl FnOnce() -> R + UnwindSafe) -> std::thread::Result<R> {
    CATCHING.with(|depth| depth.set(depth.get() + 1));
    let result = std::panic::catch_unwind(f);
    CATCHING.with(|depth| depth.set(depth.get() - 1));
    result
}

fn install_hook() {
    HOOK.call_once(|| {
        let previous = std::panic::take_hook();
        std::panic::set_hook(Box::new(move |info| {
            // Caught on this thread while a session is live: the session
            // runs on, and the catcher reports the panic itself.
            if CATCHING.with(Cell::get) > 0 && ACTIVE.load(Ordering::SeqCst) != 0 {
                return;
            }
            let _ = restore(false);
            previous(info);
        }));
    });
}

/// What a session turns on.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct SessionOptions {
    /// Take over the whole screen, and give it back as it was on exit.
    /// Without it, components paint inline, below the cursor.
    pub alternate_screen: bool,
    /// Report mouse clicks and the wheel.
    pub mouse: bool,
    /// Deliver pasted text as one [`Event::Paste`].
    pub bracketed_paste: bool,
    /// Where to paint.
    pub output: Output,
    /// Read keys as a legacy terminal sends them, even from a terminal with
    /// the kitty keyboard protocol. Without it, a terminal that answers the
    /// protocol's query has it turned on: Ctrl+I and Tab are told apart
    /// (see [`Key::matches`](crate::Key::matches)), and key releases arrive
    /// as [`Event::KeyUp`] (with crossterm; see [`BackendKind`]).
    pub legacy_keys: bool,
    /// The library that drives the terminal: crossterm unless this says
    /// otherwise.
    pub backend: BackendKind,
    /// Write each frame as one synchronized update (DEC private mode 2026):
    /// `Some(true)` always, `Some(false)` never. `None`, the default, leaves
    /// it to `RICH_SYNC_OUTPUT` (`0` off, `1` on) and then to the terminal,
    /// which is asked in the kitty keyboard protocol's start-up query. A
    /// session that asks nothing ([`legacy_keys`](Self::legacy_keys), the
    /// termion backend, standard output not a terminal) leaves it off
    /// unless this or the environment turns it on.
    pub synchronized_output: Option<bool>,
    /// With the kitty keyboard protocol, have every key reported as an
    /// escape code: releases then arrive for text keys too (letters,
    /// Space, Enter), and modifier keys pressed on their own arrive as
    /// [`KeyCode::Modifier`](crate::KeyCode::Modifier), as a game wants
    /// them. Off by default: typed text then arrives as a base key and the
    /// modifiers held, which loses characters an input method composes.
    /// crossterm only (termwiz reads no releases); see
    /// [`Session::releases_reported`].
    pub all_keys: bool,
}

/// Ends a [`Backend::read`] under way early, from any thread: a value made
/// on another thread is then picked up at once, rather than when the read's
/// timeout runs out. Clones wake the same reads. A wake that comes while
/// no read is under way ends the next one at once, so none is lost; a
/// read woken returns `None`, as if its timeout had passed.
///
/// [`Session`] waits on it with the terminal (a self-pipe beside the
/// terminal in one `poll`, on Unix; elsewhere it looks between short
/// waits). Any other backend, or a loop of one's own, can wait on it with
/// [`wait`](Waker::wait).
///
/// ```
/// use rich_interact::Waker;
/// use std::time::Duration;
///
/// let waker = Waker::new();
/// let other = waker.clone();
/// std::thread::spawn(move || other.wake());
/// assert!(waker.wait(Duration::from_secs(5)));
/// // Taken: the next wait waits.
/// assert!(!waker.wait(Duration::from_millis(1)));
/// ```
#[derive(Clone)]
pub struct Waker(std::sync::Arc<WakeState>);

struct WakeState {
    woken: std::sync::Mutex<bool>,
    changed: std::sync::Condvar,
    /// A byte is written to the second end on a wake, so a `poll` on the
    /// first sees it.
    #[cfg(unix)]
    pipe: Option<(
        std::os::unix::net::UnixStream,
        std::os::unix::net::UnixStream,
    )>,
}

impl Default for Waker {
    fn default() -> Waker {
        Waker::new()
    }
}

impl fmt::Debug for Waker {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Waker")
            .field("woken", &*self.lock())
            .finish()
    }
}

impl Waker {
    pub fn new() -> Waker {
        #[cfg(unix)]
        let pipe = std::os::unix::net::UnixStream::pair()
            .ok()
            .filter(|(a, b)| a.set_nonblocking(true).is_ok() && b.set_nonblocking(true).is_ok());
        Waker(std::sync::Arc::new(WakeState {
            woken: std::sync::Mutex::new(false),
            changed: std::sync::Condvar::new(),
            #[cfg(unix)]
            pipe,
        }))
    }

    fn lock(&self) -> std::sync::MutexGuard<'_, bool> {
        self.0.woken.lock().unwrap_or_else(|e| e.into_inner())
    }

    /// End the read under way, or the next one.
    pub fn wake(&self) {
        let mut woken = self.lock();
        if std::mem::replace(&mut *woken, true) {
            // Woken already: the byte is there.
            return;
        }
        #[cfg(unix)]
        if let Some((_, writer)) = &self.0.pipe {
            use std::io::Write as _;
            let _ = (&*writer).write(&[1]);
        }
        self.0.changed.notify_all();
    }

    /// Whether it was woken since the last call (or [`wait`](Self::wait));
    /// it is not woken after.
    pub fn take(&self) -> bool {
        let mut woken = self.lock();
        #[cfg(unix)]
        if let Some((reader, _)) = &self.0.pipe {
            use std::io::Read as _;
            let mut drained = [0u8; 16];
            while matches!((&*reader).read(&mut drained), Ok(n) if n > 0) {}
        }
        std::mem::replace(&mut *woken, false)
    }

    /// Wait until woken, `timeout` at most; whether it was (and it is not
    /// woken after).
    pub fn wait(&self, timeout: Duration) -> bool {
        {
            let woken = self.lock();
            let _ = self
                .0
                .changed
                .wait_timeout_while(woken, timeout, |woken| !*woken)
                .unwrap_or_else(|e| e.into_inner());
        }
        self.take()
    }

    /// What a `poll` waits on to see a wake: readable once woken, until
    /// [`take`](Self::take).
    #[cfg(unix)]
    pub(crate) fn fd(&self) -> Option<std::os::unix::io::RawFd> {
        use std::os::unix::io::AsRawFd;
        self.0.pipe.as_ref().map(|(reader, _)| reader.as_raw_fd())
    }
}

/// How long a read waits between looks at its [`Waker`] where it cannot
/// wait on it with the terminal.
const WAKE_SLICE: Duration = Duration::from_millis(4);

/// The longest a read woken over and over goes without looking at the
/// terminal: a look on every wake costs a wake rate on some terminals
/// (macOS's), none starves the keys.
const KEYS_SLICE: Duration = Duration::from_millis(20);

/// What a read waits on to see a [`Waker`]'s wake: its pipe on Unix.
#[cfg(unix)]
pub(crate) type WakeFd = std::os::unix::io::RawFd;
#[cfg(not(unix))]
pub(crate) type WakeFd = ();

/// Wait up to `wait` for input on `tty` or a wake on `wake`; whether input
/// came, and no wake. A signal ends the wait early, as nothing.
#[cfg(unix)]
fn input_before_wake(
    tty: std::os::unix::io::RawFd,
    wake: std::os::unix::io::RawFd,
    wait: Duration,
) -> io::Result<bool> {
    use filedescriptor::{POLLIN, poll, pollfd};
    let mut ready = [
        pollfd {
            fd: tty,
            events: POLLIN,
            revents: 0,
        },
        pollfd {
            fd: wake,
            events: POLLIN,
            revents: 0,
        },
    ];
    match poll(&mut ready, Some(wait)) {
        Ok(_) => Ok(ready[0].revents != 0 && ready[1].revents == 0),
        Err(filedescriptor::Error::Poll(e)) if e.kind() == io::ErrorKind::Interrupted => Ok(false),
        Err(e) => Err(io::Error::other(e.to_string())),
    }
}

/// Where the event loop reads events and writes paints: the terminal, or
/// the [headless](crate::headless) driver.
pub trait Backend {
    /// (columns, rows).
    fn size(&self) -> (u16, u16);
    /// The next event, or `None` when `timeout` passes first. `None` for
    /// `timeout` waits as long as it takes.
    fn read(&mut self, timeout: Option<Duration>) -> io::Result<Option<Event>>;
    /// Write and flush.
    fn write(&mut self, text: &str) -> io::Result<()>;
    /// Whether [`write_frame`](Backend::write_frame) writes each frame as
    /// one synchronized update. The default: no.
    fn synchronized_output(&self) -> bool {
        false
    }
    /// Write a frame the painter made: nothing at all when it is empty,
    /// and with [`synchronized_output`](Backend::synchronized_output)
    /// between `CSI ? 2026 h` and `CSI ? 2026 l`, in the one write.
    fn write_frame(&mut self, frame: &str) -> io::Result<()> {
        if frame.is_empty() {
            Ok(())
        } else if self.synchronized_output() {
            self.write(&synchronized_update(frame))
        } else {
            self.write(frame)
        }
    }
    /// Time since the backend started (virtual in the headless driver).
    fn elapsed(&self) -> Duration;
    /// Run `command` with the terminal as it was before the session, then
    /// take the terminal back. Returns the exit code.
    fn handoff(&mut self, command: &mut Command) -> io::Result<Option<i32>>;
    /// Whether the region is the alternate screen (painted from the top).
    fn alternate_screen(&self) -> bool;
    /// The terminal row an inline region started on, for placing mouse
    /// events; 0 when unknown. The alternate screen always starts at 0.
    fn origin(&self) -> u16 {
        0
    }
    /// The plain text of a view just painted: the headless driver records
    /// it.
    fn painted(&mut self, text: &str) {
        let _ = text;
    }
    /// Whether Ctrl+Z suspends (a real terminal on Unix), rather than
    /// reaching the component as a key.
    fn can_suspend(&self) -> bool {
        false
    }
    /// Give the terminal back, stop until the shell continues the process,
    /// then take the terminal back. Only called when
    /// [`can_suspend`](Backend::can_suspend).
    fn suspend(&mut self) -> io::Result<()> {
        Ok(())
    }
    /// Whether the process was suspended from outside (SIGTSTP) and has
    /// continued since the last call: the screen is then the shell's.
    fn take_resumed(&mut self) -> bool {
        false
    }
    /// Whether [`copy`](Backend::copy) reaches a clipboard (#488): `Ok`
    /// when it does, or why not. The default: it does not.
    fn clipboard(&self) -> Result<(), String> {
        Err("this backend has no clipboard".into())
    }
    /// Put `text` on the clipboard. Only called when
    /// [`clipboard`](Backend::clipboard) is `Ok`.
    fn copy(&mut self, text: &str) -> io::Result<()> {
        let _ = text;
        Ok(())
    }
    /// A [`Waker`] that ends a [`read`](Backend::read) under way early,
    /// for another thread to call when it has something for the loop; the
    /// same one each time. The default: none, so what another thread sends
    /// waits for the read's timeout.
    fn waker(&mut self) -> Option<Waker> {
        None
    }
    /// Which key releases the backend reports (see
    /// [`Releases`](crate::Releases)). The default: none.
    fn releases_reported(&self) -> crate::Releases {
        crate::Releases::None
    }
}

/// How a session reads the terminal: the library's reader, opened on the
/// first [`Session::enter`] and kept across hand-offs and suspends.
enum Input {
    Crossterm,
    #[cfg(all(unix, feature = "termion"))]
    Termion(with_termion::Reader),
    #[cfg(feature = "termwiz")]
    Termwiz {
        held: crate::event::HeldButton,
        probed: with_termwiz::Probed,
    },
}

impl Input {
    fn open(kind: BackendKind, output: Output) -> io::Result<Input> {
        let _ = output;
        Ok(match kind {
            BackendKind::Crossterm => Input::Crossterm,
            #[cfg(all(unix, feature = "termion"))]
            BackendKind::Termion => Input::Termion(with_termion::Reader::open()?),
            #[cfg(feature = "termwiz")]
            BackendKind::Termwiz => Input::Termwiz {
                held: Default::default(),
                probed: with_termwiz::open(output)?,
            },
        })
    }
}

/// The real terminal: keys from it, paints to standard output or standard
/// error ([`SessionOptions::output`]), through the library
/// [`SessionOptions::backend`] names.
pub struct Session {
    options: SessionOptions,
    start: Instant,
    active: bool,
    /// The row the cursor was on when the session started (inline, with
    /// the mouse on).
    origin: u16,
    /// Whether the terminal takes OSC 52 copies, detected at the start.
    clipboard: rich_ext::clipboard::Clipboard,
    /// Whether keys are read with the kitty keyboard protocol.
    kitty: bool,
    /// Whether frames are written as synchronized updates.
    sync: bool,
    /// The cells' size in pixels while the mouse is reported in pixels
    /// (mode 1016): each report is read back into cells with it.
    cell: Option<(u16, u16)>,
    /// `None` until the first `enter`.
    input: Option<Input>,
    /// The [`Waker`] handed out, once one was.
    waker: Option<Waker>,
    /// Keys typed while the start-up query waited for its answer, read
    /// before anything else.
    typed: std::collections::VecDeque<Event>,
    /// When the terminal was last looked at, so a session woken over and
    /// over still reads its keys (see [`KEYS_SLICE`]).
    looked: Instant,
    /// The terminal crossterm reads, when it is not standard input, opened
    /// to wait on it beside the waker.
    #[cfg(unix)]
    tty: Option<std::fs::File>,
}

/// What the terminal answered the start-up query, asked once a process
/// with `ask` (with raw mode on), and the bytes typed while it was asked:
/// a terminal that answers none of it, not even the device attributes
/// query at its end, keeps the session waiting (a second, or a quarter
/// of one once keys come).
fn answered(ask: impl FnOnce() -> (Answers, Vec<u8>)) -> (Answers, Vec<u8>) {
    match ANSWERS.load(Ordering::SeqCst) {
        0 => {
            let (answers, typed) = if query_reaches_terminal() {
                ask()
            } else {
                (Answers::default(), Vec::new())
            };
            ANSWERS.store(answers.encode(), Ordering::SeqCst);
            (answers, typed)
        }
        bits => (Answers::decode(bits), Vec::new()),
    }
}

/// Whether the start-up query is asked. crossterm's own keyboard query
/// meant to write to `/dev/tty`, but opened it read-only, so it went to
/// standard output: in `answer=$(rich write)` it would have landed in the
/// answer, and the terminal's reply at the shell prompt afterwards. The
/// session asks directly now, but still only with standard output a
/// terminal, so a captured answer starts as it did; every backend asks the
/// same way, so a terminal is asked or not whichever drives it.
fn query_reaches_terminal() -> bool {
    use std::io::IsTerminal;
    io::stdout().is_terminal()
}

impl Session {
    /// Turn on raw mode and the options. Fails, changing nothing, when the
    /// terminal cannot do raw mode or another session is alive.
    pub fn start(options: SessionOptions) -> io::Result<Session> {
        if OWNED
            .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
            .is_err()
        {
            return Err(io::Error::new(
                io::ErrorKind::ResourceBusy,
                "a terminal session is already running",
            ));
        }
        install_hook();
        watch_signals();
        // From here on, dropping the session releases ownership, including
        // when `enter` fails part way.
        let mut session = Session {
            options,
            start: Instant::now(),
            active: false,
            origin: 0,
            clipboard: rich_ext::clipboard::Clipboard::detect(
                &crate::clipboard::SessionEnvironment,
            ),
            kitty: false,
            sync: false,
            cell: None,
            input: None,
            waker: None,
            typed: Default::default(),
            looked: Instant::now(),
            #[cfg(unix)]
            tty: None,
        };
        session.enter()?;
        Ok(session)
    }

    fn enter(&mut self) -> io::Result<()> {
        let library = self.options.backend;
        ON_STDERR.store(self.options.output == Output::Stderr, Ordering::SeqCst);
        LIBRARY.store(library.index(), Ordering::SeqCst);
        if self.input.is_none() {
            self.input = Some(Input::open(library, self.options.output)?);
        }
        library.raw_mode(true, true)?;
        ACTIVE.fetch_or(RAW, Ordering::SeqCst);
        // Active as soon as anything is on, so a failure below still
        // restores on drop.
        self.active = true;
        let mut out = String::new();
        if self.options.alternate_screen {
            ACTIVE.fetch_or(ALTERNATE, Ordering::SeqCst);
            match library.alternate_screen(true, true) {
                Some(entered) => entered?,
                None => out.push_str(&library.alternate_sequence(true)),
            }
            out.push_str("\x1b[H");
        }
        // The start-up query asks for the kitty keyboard protocol and
        // synchronized output in one round trip. With nothing to read the
        // protocol's keys (legacy keys, termion), it is not asked at all:
        // synchronized output then waits on being forced.
        let answers = if self.options.legacy_keys {
            Answers::default()
        } else {
            self.answered()
        };
        self.kitty = answers.kitty;
        if self.kitty {
            out.push_str(match (library, self.options.all_keys) {
                (BackendKind::Crossterm, true) => PUSH_KITTY_ALL,
                _ => library.kitty_push(),
            });
        }
        self.sync = self
            .options
            .synchronized_output
            .or_else(sync_from_env)
            .unwrap_or(answers.sync);
        if self.sync {
            ACTIVE.fetch_or(SYNC, Ordering::SeqCst);
        }
        let (mouse, paste) = self.capable();
        if self.options.mouse && mouse {
            out.push_str("\x1b[?1000h\x1b[?1002h\x1b[?1015h\x1b[?1006h");
            ACTIVE.fetch_or(MOUSE, Ordering::SeqCst);
            // Pixels where the terminal knows them and says how big its
            // cells are, else cells (1006) as ever (#819).
            self.cell = None;
            if answers.pixels
                && pixels_allowed(std::env::var(PIXEL_MOUSE_ENV).ok().as_deref())
                && let Some(cell) = cell_size()
            {
                out.push_str("\x1b[?1016h");
                ACTIVE.fetch_or(PIXELS, Ordering::SeqCst);
                self.cell = Some(cell);
            }
        }
        if self.options.bracketed_paste && paste {
            out.push_str("\x1b[?2004h");
            ACTIVE.fetch_or(PASTE, Ordering::SeqCst);
        }
        out.push_str("\x1b[?25l");
        {
            // The kitty flags are a stack: marked pushed with the write
            // that pushes them, under the suspend's lock, so a suspend
            // between the two neither pops flags not yet pushed nor
            // pushes them on `fg` before this pushes them again.
            let _suspending = SUSPENDING.lock().unwrap_or_else(|e| e.into_inner());
            if self.kitty {
                ACTIVE.fetch_or(KITTY, Ordering::SeqCst);
            }
            self.options.output.write(&out)?;
        }
        // Where an inline region starts, so clicks land on the right rows.
        // Asking writes a query to standard output, so only when that is
        // the terminal being painted.
        if self.options.mouse
            && !self.options.alternate_screen
            && self.options.output == Output::Stdout
        {
            self.origin = self.cursor_row().unwrap_or(0);
        }
        Ok(())
    }

    /// What the terminal answered the start-up query, for a library that
    /// reads the kitty keyboard protocol's keys; nothing asked for one that
    /// does not. Keys typed while it was asked go to the reader, so none
    /// is lost to a terminal slow to answer, or one that never does.
    fn answered(&mut self) -> Answers {
        let (answers, typed) = match self.options.backend {
            #[cfg(unix)]
            BackendKind::Crossterm => answered(ask_start),
            // Windows: crossterm's own answer, which reads no reply.
            #[cfg(not(unix))]
            BackendKind::Crossterm => answered(|| {
                let kitty = crossterm::terminal::supports_keyboard_enhancement().unwrap_or(false);
                (
                    Answers {
                        kitty,
                        ..Answers::default()
                    },
                    Vec::new(),
                )
            }),
            // termion's reader does not know the protocol's keys.
            #[cfg(all(unix, feature = "termion"))]
            BackendKind::Termion => (Answers::default(), Vec::new()),
            #[cfg(all(unix, feature = "termwiz"))]
            BackendKind::Termwiz => answered(ask_start),
            #[cfg(all(not(unix), feature = "termwiz"))]
            BackendKind::Termwiz => (Answers::default(), Vec::new()),
        };
        #[cfg(unix)]
        if !typed.is_empty() {
            match &mut self.input {
                #[cfg(feature = "termwiz")]
                Some(Input::Termwiz { probed, .. }) => with_termwiz::unread(probed, &typed),
                // crossterm reads only the terminal: what was typed is read
                // here, as the legacy terminal it still is before the
                // protocol is pushed.
                _ => self.typed.extend(crate::event::from_legacy_bytes(&typed)),
            }
        }
        // Elsewhere nothing is read before the library's reader opens.
        #[cfg(not(unix))]
        debug_assert!(typed.is_empty());
        answers
    }

    /// Whether the library's probe of the terminal allows the mouse and
    /// bracketed paste.
    fn capable(&self) -> (bool, bool) {
        match &self.input {
            #[cfg(feature = "termwiz")]
            Some(Input::Termwiz { probed, .. }) => (probed.mouse, probed.paste),
            _ => (true, true),
        }
    }

    /// The cursor's row, asked of the terminal. Keys that came with the
    /// answer go to the reader.
    fn cursor_row(&mut self) -> Option<u16> {
        match self.options.backend {
            BackendKind::Crossterm => crossterm::cursor::position().ok().map(|(_, row)| row),
            #[cfg(all(unix, any(feature = "termion", feature = "termwiz")))]
            #[allow(unreachable_patterns)]
            _ => {
                let (row, rest) = ask_cursor_row();
                match &mut self.input {
                    #[cfg(feature = "termion")]
                    Some(Input::Termion(reader)) => reader.unread(&rest),
                    #[cfg(feature = "termwiz")]
                    Some(Input::Termwiz { probed, .. }) => with_termwiz::unread(probed, &rest),
                    _ => {}
                }
                row
            }
            #[cfg(all(not(unix), feature = "termwiz"))]
            _ => None,
        }
    }

    /// The terminal's size, as the library measures it.
    fn measure(&self) -> io::Result<(u16, u16)> {
        match &self.input {
            #[cfg(all(unix, feature = "termion"))]
            Some(Input::Termion(reader)) => reader.size(),
            #[cfg(feature = "termwiz")]
            Some(Input::Termwiz { .. }) => with_termwiz::size(),
            _ => crossterm::terminal::size(),
        }
    }

    /// The next event within `wait`, or `None`: the wait passed, or the
    /// library read something components do not see (focus changes, a
    /// sequence it does not know).
    /// `event` with a pixel report read back into cells, while the mouse
    /// is reported in pixels; a resize measures the cells again.
    fn in_cells(&mut self, event: Event) -> Event {
        let Some(cell) = self.cell else {
            return event;
        };
        match event {
            Event::Mouse(mouse) => match mouse.reread_as_pixels(cell) {
                Some(read) => Event::Mouse(read),
                None => Event::Mouse(mouse),
            },
            Event::Resize { .. } => {
                if let Some(size) = cell_size() {
                    self.cell = Some(size);
                }
                event
            }
            event => event,
        }
    }

    fn next_event(&mut self, wait: Duration) -> io::Result<Option<Event>> {
        let kitty = self.kitty;
        #[cfg(unix)]
        let wake: Option<WakeFd> = self.waker.as_ref().and_then(Waker::fd);
        #[cfg(not(unix))]
        let wake: Option<WakeFd> = None;
        match &mut self.input {
            #[cfg(all(unix, feature = "termion"))]
            Some(Input::Termion(reader)) => reader.next(wait, wake),
            #[cfg(feature = "termwiz")]
            Some(Input::Termwiz { held, probed }) => Ok(with_termwiz::poll(probed, wait, wake)?
                .and_then(|event| {
                    if kitty {
                        crate::event::from_termwiz_kitty(event, held)
                    } else {
                        crate::event::from_termwiz(event, held)
                    }
                })),
            _ => {
                // With a waker: wait on the terminal and the waker together,
                // then let crossterm read what came. It may hold events
                // already read, so it is asked first; a millisecond, as with
                // no time at all it does not look at what it holds.
                #[cfg(unix)]
                if let Some(wake) = wake {
                    if !crossterm::event::poll(Duration::from_millis(1))? {
                        let tty = self.crossterm_tty()?;
                        // Nothing, or woken: back to the loop.
                        if !input_before_wake(tty, wake, wait)? {
                            return Ok(None);
                        }
                        // Input: a sequence's rest may come after its
                        // start, as crossterm would wait for it.
                        if !crossterm::event::poll(wait.min(Duration::from_millis(10)))? {
                            return Ok(None);
                        }
                    }
                } else if !crossterm::event::poll(wait)? {
                    return Ok(None);
                }
                #[cfg(not(unix))]
                {
                    let _ = wake;
                    if !crossterm::event::poll(wait)? {
                        return Ok(None);
                    }
                }
                let event = crossterm::event::read()?;
                Ok(if kitty {
                    from_crossterm_kitty(event)
                } else {
                    from_crossterm(event)
                })
            }
        }
    }

    /// The terminal crossterm reads, as it finds it: standard input when
    /// that is a terminal, else `/dev/tty`.
    #[cfg(unix)]
    fn crossterm_tty(&mut self) -> io::Result<std::os::unix::io::RawFd> {
        use std::io::IsTerminal;
        use std::os::unix::io::AsRawFd;
        if io::stdin().is_terminal() {
            return Ok(io::stdin().as_raw_fd());
        }
        if self.tty.is_none() {
            self.tty = Some(std::fs::File::open("/dev/tty")?);
        }
        Ok(self.tty.as_ref().map_or(0, |tty| tty.as_raw_fd()))
    }

    /// Restore the terminal. Also done on drop and on panic.
    pub fn leave(&mut self) -> io::Result<()> {
        if !std::mem::take(&mut self.active) {
            return Ok(());
        }
        // After any suspend under way has turned the modes back on, so
        // this restores them rather than being undone by it.
        let _suspending = SUSPENDING.lock().unwrap_or_else(|e| e.into_inner());
        restore(true)
    }

    pub fn options(&self) -> SessionOptions {
        self.options
    }

    /// Whether keys are read with the kitty keyboard protocol: the terminal
    /// has it, the backend reads it, and [`SessionOptions::legacy_keys`] is
    /// off. Every key is then [`exact`](crate::Key::exact), and with
    /// crossterm releases arrive.
    pub fn kitty_keys(&self) -> bool {
        self.kitty
    }

    /// Which key releases arrive as [`Event::KeyUp`]: with crossterm and
    /// the kitty keyboard protocol, every key's but the text keys', or
    /// every key's with [`SessionOptions::all_keys`]; every key's on the
    /// Windows console; none otherwise.
    pub fn releases_reported(&self) -> crate::Releases {
        use crate::Releases;
        match self.options.backend {
            BackendKind::Crossterm if cfg!(windows) => Releases::All,
            BackendKind::Crossterm if self.kitty && self.options.all_keys => Releases::All,
            BackendKind::Crossterm if self.kitty => Releases::ExceptText,
            #[allow(unreachable_patterns)]
            _ => Releases::None,
        }
    }

    /// Whether frames are written as synchronized updates: forced by
    /// [`SessionOptions::synchronized_output`] or `RICH_SYNC_OUTPUT`, or
    /// the terminal answered that it knows mode 2026.
    pub fn synchronized_output(&self) -> bool {
        self.sync
    }

    /// The colours the backend's own probe of the terminal found, when it
    /// has one (termwiz's: terminfo and `COLORTERM`); `None` to leave it to
    /// rich's detection. `Some(None)` is no colour.
    pub fn color_system(&self) -> Option<Option<rich::ColorSystem>> {
        match &self.input {
            #[cfg(feature = "termwiz")]
            Some(Input::Termwiz { probed, .. }) => Some(probed.color),
            _ => None,
        }
    }

    /// A resize to the current size, which repaints the whole view: after a
    /// suspend, what is on the screen is the shell's.
    fn repaint(&mut self) -> Event {
        if self.options.mouse
            && !self.options.alternate_screen
            && self.options.output == Output::Stdout
        {
            self.origin = self.cursor_row().unwrap_or(0);
        }
        let (columns, rows) = self.measure().unwrap_or((80, 24));
        Event::Resize { columns, rows }
    }
}

impl Drop for Session {
    fn drop(&mut self) {
        let _ = self.leave();
        if self.input.take().is_some() {
            self.options.backend.release();
        }
        OWNED.store(false, Ordering::SeqCst);
    }
}

impl Backend for Session {
    fn size(&self) -> (u16, u16) {
        self.measure().unwrap_or((80, 24))
    }

    fn read(&mut self, timeout: Option<Duration>) -> io::Result<Option<Event>> {
        if let Some(event) = self.typed.pop_front() {
            return Ok(Some(event));
        }
        let end = timeout.map(|timeout| Instant::now() + timeout);
        loop {
            // Back from a SIGTSTP sent from outside: the screen is the
            // shell's, so repaint all of it.
            if RESUMED.load(Ordering::SeqCst) {
                return Ok(Some(self.repaint()));
            }
            // Woken: back to the loop, which has something to pick up. An
            // app woken over and over (frames arriving faster than it draws
            // them) would never read the keyboard, so every `KEYS_SLICE` a
            // key already waiting comes first, with no wait; the loop picks
            // up what woke it all the same.
            if self.waker.as_ref().is_some_and(Waker::take) {
                if self.looked.elapsed() < KEYS_SLICE {
                    return Ok(None);
                }
                self.looked = Instant::now();
                return Ok(self.next_event(Duration::ZERO)?.map(|e| self.in_cells(e)));
            }
            // Short waits, so a resume is noticed without a key; shorter
            // where the waker cannot be waited on with the terminal.
            let mut wait = match end {
                Some(end) => end.saturating_duration_since(Instant::now()),
                None => Duration::from_secs(3600),
            }
            .min(Duration::from_millis(250));
            if self.waker.is_some() && !cfg!(unix) {
                wait = wait.min(WAKE_SLICE);
            }
            // Events the library reports that components do not see (focus)
            // are skipped, not returned as a timeout.
            self.looked = Instant::now();
            if let Some(event) = self.next_event(wait)? {
                return Ok(Some(self.in_cells(event)));
            }
            if end.is_some_and(|end| Instant::now() >= end) {
                return Ok(None);
            }
        }
    }

    fn write(&mut self, text: &str) -> io::Result<()> {
        self.options.output.write(text)
    }

    /// The session's [`Waker`]: on Unix the terminal and it are waited on
    /// in one `poll`, on every backend; elsewhere a read looks at it every
    /// few milliseconds.
    fn waker(&mut self) -> Option<Waker> {
        Some(self.waker.get_or_insert_with(Waker::new).clone())
    }

    fn releases_reported(&self) -> crate::Releases {
        Session::releases_reported(self)
    }

    fn synchronized_output(&self) -> bool {
        self.sync
    }

    fn clipboard(&self) -> Result<(), String> {
        let field = self.clipboard.field();
        if field.value {
            Ok(())
        } else {
            Err(field.reason.clone())
        }
    }

    fn copy(&mut self, text: &str) -> io::Result<()> {
        let sequence = rich_ext::clipboard::osc52(text)
            .map_err(|error| io::Error::new(io::ErrorKind::InvalidInput, error.to_string()))?;
        self.options.output.write(&sequence)
    }

    fn elapsed(&self) -> Duration {
        self.start.elapsed()
    }

    fn handoff(&mut self, command: &mut Command) -> io::Result<Option<i32>> {
        self.leave()?;
        let status = command.status();
        self.enter()?;
        Ok(status?.code())
    }

    fn alternate_screen(&self) -> bool {
        self.options.alternate_screen
    }

    fn origin(&self) -> u16 {
        self.origin
    }

    fn can_suspend(&self) -> bool {
        cfg!(unix)
    }

    fn suspend(&mut self) -> io::Result<()> {
        #[cfg(unix)]
        {
            suspend();
            self.repaint();
        }
        Ok(())
    }

    fn take_resumed(&mut self) -> bool {
        RESUMED.swap(false, Ordering::SeqCst)
    }
}

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

    #[test]
    fn backends_are_named() {
        assert_eq!(BackendKind::default(), BackendKind::Crossterm);
        assert_eq!(BackendKind::ALL[0], BackendKind::Crossterm);
        for kind in BackendKind::ALL {
            assert_eq!(BackendKind::from_name(kind.name()), Some(*kind));
            assert_eq!(
                BackendKind::from_name(&kind.name().to_uppercase()),
                Some(*kind)
            );
            assert_eq!(kind.to_string(), kind.name());
        }
        assert_eq!(BackendKind::from_name("curses"), None);
        assert_eq!(
            BackendKind::ALL.len(),
            1 + usize::from(cfg!(all(unix, feature = "termion")))
                + usize::from(cfg!(feature = "termwiz"))
        );
    }

    #[test]
    fn every_backend_leaves_the_same_modes() {
        let all = RAW | ALTERNATE | MOUSE | PASTE | KITTY;
        let expected =
            "\x1b[<1u\x1b[?1006l\x1b[?1015l\x1b[?1003l\x1b[?1002l\x1b[?1000l\x1b[?2004l\x1b[?25h";
        for kind in BackendKind::ALL {
            let out = undo(all, *kind);
            assert!(out.starts_with(expected), "{kind}: {out:?}");
            // The alternate screen last: in the sequences, or by the
            // library's own call.
            let rest = &out[expected.len()..];
            assert!(rest == "\x1b[?1049l" || rest.is_empty(), "{kind}: {rest:?}");
            assert_eq!(rest.is_empty(), kind.owns_alternate_screen());
        }
    }

    #[test]
    fn answers_are_stripped_from_what_was_typed() {
        assert_eq!(strip_answers(b"\x1b[?2026;2$yq\x1b[?62c"), b"q");
        assert_eq!(strip_answers(b"ab\x1b[?62"), b"ab");
        assert_eq!(strip_answers(b"\x1b[A\x1b"), b"\x1b[A\x1b");
        assert!(strip_answers(b"\x1b[?0u\x1b[?62c").is_empty());
    }

    #[test]
    fn private_answers_are_found() {
        let lasts = |bytes: &[u8]| -> Vec<u8> { private_answers(bytes).map(|a| a.last).collect() };
        assert_eq!(lasts(b"x\x1b[?0u\x1b[?62;22c"), b"uc");
        assert_eq!(lasts(b"\x1b[?62"), b"");
        let decrqm: Vec<_> = private_answers(b"\x1b[?2026;2$y").collect();
        assert_eq!(
            decrqm,
            [PrivateAnswer {
                parameters: b"2026;2",
                intermediates: b"$",
                last: b'y',
            }]
        );
        // An answer broken off by another sequence is passed over, and the
        // next one still read.
        assert_eq!(lasts(b"\x1b[?2026\x1b[?62c"), b"c");
    }

    #[test]
    fn the_start_up_answers_are_read() {
        let read = |bytes: &[u8]| Answers::read(bytes);
        let both = Answers {
            kitty: true,
            sync: true,
            pixels: false,
        };
        let sync = Answers {
            sync: true,
            ..Answers::default()
        };
        // Supported: set or reset (recognised), or permanently set.
        assert_eq!(read(b"\x1b[?2026;2$y\x1b[?0u\x1b[?62;22c"), Some(both));
        assert_eq!(read(b"\x1b[?2026;1$y\x1b[?62c"), Some(sync));
        assert_eq!(read(b"\x1b[?2026;3$y\x1b[?62c"), Some(sync));
        // Not recognised, or permanently reset: not supported.
        assert_eq!(read(b"\x1b[?2026;0$y\x1b[?62c"), Some(Answers::default()));
        assert_eq!(read(b"\x1b[?2026;4$y\x1b[?62c"), Some(Answers::default()));
        // No report at all (a terminal that does not know DECRQM).
        assert_eq!(
            read(b"\x1b[?1u\x1b[?62c"),
            Some(Answers {
                kitty: true,
                ..Answers::default()
            })
        );
        // Another mode's report says nothing about 2026.
        assert_eq!(read(b"\x1b[?2004;1$y\x1b[?62c"), Some(Answers::default()));
        // Until the device attributes come, the answer is not complete:
        // the session waits, then goes on with neither.
        assert_eq!(read(b""), None);
        assert_eq!(read(b"\x1b[?2026;2$y\x1b[?0u"), None);
        assert_eq!(read(b"\x1b[?2026;2$y\x1b[?6"), None);
        // Keys typed while it waits, between and inside the answers' runs,
        // are passed over.
        assert_eq!(
            read(b"j\x1b[A\x1b[?2026;2$yk\x1b[?0u\r\x1b[?62;22c"),
            Some(both)
        );
        // SGR-Pixels (1016), asked after 2026, read on its own (#819).
        let pixels = Answers {
            pixels: true,
            ..Answers::default()
        };
        let all = Answers {
            pixels: true,
            ..both
        };
        assert_eq!(read(b"\x1b[?1016;2$y\x1b[?62c"), Some(pixels));
        assert_eq!(read(b"\x1b[?1016;1$y\x1b[?62c"), Some(pixels));
        assert_eq!(read(b"\x1b[?1016;0$y\x1b[?62c"), Some(Answers::default()));
        assert_eq!(read(b"\x1b[?1016;4$y\x1b[?62c"), Some(Answers::default()));
        assert_eq!(
            read(b"\x1b[?2026;2$y\x1b[?1016;2$y\x1b[?0u\x1b[?62;22c"),
            Some(all)
        );
        // 2026's report says nothing about 1016, and the other way round.
        assert_eq!(read(b"\x1b[?2026;2$y\x1b[?62c"), Some(sync));
        for answers in [Answers::default(), sync, both, pixels, all] {
            assert_ne!(answers.encode(), 0);
            assert_eq!(Answers::decode(answers.encode()), answers);
        }
    }

    #[test]
    fn the_cell_size_comes_from_the_window_size_in_pixels() {
        assert_eq!(cell_of(80, 24, 800, 480), Some((10, 20)));
        // Rounded down: a window with a margin of a few pixels.
        assert_eq!(cell_of(80, 24, 805, 490), Some((10, 20)));
        // A terminal that leaves the pixel fields 0, or no window.
        assert_eq!(cell_of(80, 24, 0, 0), None);
        assert_eq!(cell_of(0, 0, 800, 480), None);
        assert_eq!(cell_of(80, 24, 40, 480), None);
    }

    #[test]
    fn pixel_reports_are_allowed_unless_turned_off() {
        assert!(pixels_allowed(None));
        assert!(pixels_allowed(Some("1")));
        assert!(!pixels_allowed(Some("0")));
        assert!(!pixels_allowed(Some(" 0 ")));
    }

    #[test]
    fn the_restore_turns_pixel_reports_off_before_the_mouse() {
        for kind in BackendKind::ALL {
            let out = undo(RAW | MOUSE | PIXELS, *kind);
            assert!(out.starts_with("\x1b[?1016l\x1b[?1006l"), "{kind}: {out:?}");
            assert!(!undo(RAW | MOUSE, *kind).contains("1016"));
        }
    }

    #[test]
    fn a_cursor_report_is_found_among_other_input() {
        assert_eq!(cursor_report(b"\x1b[12;1R"), Some((11, 0..7)));
        // After an arrow key, a mouse report or a sequence cut short, and
        // with a key after it.
        assert_eq!(cursor_report(b"\x1b[A\x1b[12;1R"), Some((11, 3..10)));
        assert_eq!(
            cursor_report(b"\x1b[<0;2;13M\x1b[3;40Rx"),
            Some((2, 10..17))
        );
        assert_eq!(cursor_report(b"\x1b[1;\x1b[5;1R"), Some((4, 4..10)));
        // Not complete, or not a report.
        for bytes in [
            &b"\x1b[12;"[..],
            b"\x1b[12R",
            b"\x1b[;1R",
            b"\x1b[1;5C",
            b"12;1R",
        ] {
            assert_eq!(cursor_report(bytes), None, "{bytes:?}");
        }
    }

    #[test]
    fn the_environment_forces_synchronized_output() {
        assert_eq!(sync_override(Some("0")), Some(false));
        assert_eq!(sync_override(Some("1")), Some(true));
        assert_eq!(sync_override(Some(" 1\n")), Some(true));
        assert_eq!(sync_override(None), None);
        assert_eq!(sync_override(Some("")), None);
        assert_eq!(sync_override(Some("auto")), None);
    }

    #[test]
    fn a_frame_is_one_synchronized_update_and_an_empty_one_nothing() {
        assert_eq!(
            synchronized_update("\x1b[2;1Hhi\x1b[?25l"),
            "\x1b[?2026h\x1b[2;1Hhi\x1b[?25l\x1b[?2026l"
        );
        assert_eq!(synchronized_update(""), "");
    }

    #[test]
    fn the_restore_ends_a_synchronized_update_first() {
        for kind in BackendKind::ALL {
            let out = undo(RAW | SYNC | MOUSE, *kind);
            assert!(out.starts_with("\x1b[?2026l\x1b[?1006l"), "{kind}: {out:?}");
            assert_eq!(out.matches("2026").count(), 1);
            // Off, nothing about it.
            assert!(!undo(RAW | MOUSE, *kind).contains("2026"));
        }
    }
}