rs-rich-embed 0.0.7

A terminal pane and a web view for intuiTUIve apps, over swappable PTY and browser backends
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
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
//! [`ChromeEngine`]: headless Chrome or Chromium, which the user installs,
//! driven over the DevTools protocol.
//!
//! The protocol subset is spoken directly, on one thread of the engine's
//! own, so no async runtime comes with it:
//!
//! - on Linux and macOS, over a pipe: the browser is started with
//!   `--remote-debugging-pipe` and reads DevTools messages from descriptor 3
//!   and writes them to descriptor 4, each a JSON text ended by a NUL byte.
//!   No port is opened. The descriptors are passed with `command-fds`;
//! - on Windows, over a WebSocket (`tungstenite`) on a random port of
//!   `127.0.0.1` (`--remote-debugging-port=0`), whose address the browser
//!   prints on its standard error. See [`ChromeEngine`]'s security note;
//! - the browser is started headless with a temporary profile directory
//!   (only this user's, removed when the engine goes; or a kept one, when
//!   asked: [`ChromeEngine::profile`]), its sandbox on (no switch that turns
//!   any of it off, ever), muted (unless [`ChromeEngine::audio`]), and
//!   downloads denied (`Browser.setDownloadBehavior`; or kept in a
//!   quarantine directory, when asked: [`ChromeEngine::downloads`]);
//! - a page target is created and attached in flat mode;
//! - frames come from `Page.startScreencast` (JPEG, each acknowledged),
//!   at the page's size in cells times [`ChromeEngine::cell_pixels`], while
//!   the screencast is on ([`ChromeEngine::screencast`]): an app that reads
//!   the page rather than its pixels turns it off, so no frame is decoded;
//! - keys, the mouse and pastes go in as `Input.dispatchKeyEvent`,
//!   `Input.dispatchMouseEvent` and `Input.insertText`;
//! - the address, loading state and history come from `Page` events and
//!   `Page.getNavigationHistory`;
//! - any other command goes to the page through [`DevTools::call`], for an
//!   app that reads the page itself (`DOMSnapshot.captureSnapshot`,
//!   `Accessibility.getFullAXTree`, …), and its events come to
//!   [`DevTools::listen`].
//!
//! The browser is found at an explicit path, else by the usual names on
//! `PATH` ([`BINARY_NAMES`]). Nothing is downloaded.

use std::io::{BufRead, BufReader, ErrorKind};
use std::net::TcpStream;
use std::path::{Path, PathBuf};
use std::process::{Child, ChildStderr, Command, Stdio};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::mpsc::{self, Receiver, Sender};
use std::sync::{Arc, Mutex, MutexGuard, PoisonError, Weak};
use std::thread;
use std::time::{Duration, Instant};
use std::{fmt, io};

use rich_intuituive::interact::{Button, Key, KeyCode, ModifierKey, Modifiers, Mouse, MouseKind};
use serde_json::{Value, json};
use tungstenite::{Message, WebSocket};

use crate::host::Notify;
use crate::pixels::Pixels;
use crate::web::{PageState, WebEngine, WebFrame, WebInput};

/// Names the browser is looked for under on `PATH`, in order.
pub const BINARY_NAMES: &[&str] = &[
    "google-chrome",
    "google-chrome-stable",
    "chromium",
    "chromium-browser",
    "chrome",
    "headless_shell",
    "microsoft-edge",
];

/// Where browsers install themselves outside `PATH`.
const KNOWN_PATHS: &[&str] = &[
    "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
    "/Applications/Chromium.app/Contents/MacOS/Chromium",
    r"C:\Program Files\Google\Chrome\Application\chrome.exe",
    r"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",
];

/// How the engine reaches the browser's DevTools.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Wire {
    /// `--remote-debugging-pipe`: descriptors 3 and 4, no port.
    #[cfg(unix)]
    Pipe,
    /// `--remote-debugging-port=0`: a WebSocket on a port of `127.0.0.1`.
    /// Windows's; on Unix only the tests choose it, to keep it exercised.
    #[cfg_attr(all(unix, not(test)), allow(dead_code))]
    Port,
}

impl Wire {
    /// The pipe on Linux and macOS; the port on Windows, where the browser
    /// takes the pipe only as two inheritable handles, which nothing here
    /// can pass without `unsafe`.
    #[cfg(unix)]
    const DEFAULT: Wire = Wire::Pipe;
    #[cfg(not(unix))]
    const DEFAULT: Wire = Wire::Port;

    /// The browser's switch for it.
    fn switch(self) -> &'static str {
        match self {
            #[cfg(unix)]
            Wire::Pipe => "--remote-debugging-pipe",
            Wire::Port => "--remote-debugging-port=0",
        }
    }
}

/// How long the browser has to say where its DevTools endpoint is.
const START_TIMEOUT: Duration = Duration::from_secs(30);
/// How long a read of the socket waits before the thread looks at what the
/// app asked for.
const POLL: Duration = Duration::from_millis(15);

/// What the app asked the browser to do, for the engine's thread.
#[derive(Clone, Debug, PartialEq)]
enum Request {
    Open(String),
    Resize(u16, u16),
    Input(WebInput),
    Back,
    Forward,
    Reload,
    Screencast(bool),
    /// Frames this fraction of the viewport's size (`maxWidth`,
    /// `maxHeight`).
    ScreencastScale(f64),
    /// Acknowledge the screencast frame with this session id: Chrome sends
    /// the next one only after it.
    Ack(i64),
}

/// Where a screencast frame was taken: `Page.screencastFrame`'s metadata,
/// in CSS pixels.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct FrameMeta {
    /// The page's scroll position when the frame was painted.
    pub scroll_x: f64,
    pub scroll_y: f64,
    /// The top of the frame's content in the device's pixels (a browser
    /// bar, none when headless).
    pub offset_top: f64,
    /// The page's zoom: device pixels per CSS pixel of the frame.
    pub page_scale: f64,
    /// The device's size in CSS pixels.
    pub device_width: f64,
    pub device_height: f64,
    /// When it was painted, in seconds since the epoch, if Chrome says.
    pub timestamp: Option<f64>,
}

impl FrameMeta {
    fn of(metadata: &Value) -> FrameMeta {
        let f = |key: &str, default: f64| metadata[key].as_f64().unwrap_or(default);
        FrameMeta {
            scroll_x: f("scrollOffsetX", 0.0),
            scroll_y: f("scrollOffsetY", 0.0),
            offset_top: f("offsetTop", 0.0),
            page_scale: f("pageScaleFactor", 1.0),
            device_width: f("deviceWidth", 0.0),
            device_height: f("deviceHeight", 0.0),
            timestamp: metadata["timestamp"].as_f64(),
        }
    }
}

/// A screencast frame with where it was taken: what
/// [`ChromeEngine::take_screencast`] hands back.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct ScreencastFrame {
    /// The viewport's pixels.
    pub pixels: Pixels,
    pub meta: FrameMeta,
}

impl ScreencastFrame {
    /// The pixels of a rectangle of the document, in CSS pixels (as a
    /// layout box gives it): mapped through the frame's scroll position,
    /// zoom and size, and clipped to what the frame shows. `None` when
    /// none of it is in the frame.
    pub fn crop(&self, x: f64, y: f64, width: f64, height: f64) -> Option<Pixels> {
        let meta = &self.meta;
        // Frame pixels per CSS pixel: the frame may be scaled down from
        // the device (`maxWidth`), and zoomed.
        let device = if meta.device_width > 0.0 {
            meta.device_width
        } else {
            self.pixels.width as f64
        };
        let scale = self.pixels.width as f64 / device * meta.page_scale.max(f64::MIN_POSITIVE);
        let left = (x - meta.scroll_x) * scale;
        let top = (y - meta.scroll_y) * scale + meta.offset_top;
        let x0 = left.max(0.0).floor();
        let y0 = top.max(0.0).floor();
        let x1 = ((left + width * scale).ceil()).min(self.pixels.width as f64);
        let y1 = ((top + height * scale).ceil()).min(self.pixels.height as f64);
        if x1 <= x0 || y1 <= y0 {
            return None;
        }
        self.pixels
            .crop(x0 as u32, y0 as u32, (x1 - x0) as u32, (y1 - y0) as u32)
    }
}

/// A frame Chrome sent and the engine has not yet decoded (on-demand
/// screencast): base64 image data, metadata, and the session id to
/// acknowledge when it is taken (`None`: acknowledged as it came).
type RawFrame = (String, FrameMeta, Option<i64>);

/// Keep `frame` (whose session id is `ack`) as the newest waiting to be
/// taken, in place of any other; the id to acknowledge now, if any.
///
/// When none was waiting (the last was taken), it is acknowledged at once,
/// so Chrome paints the next while this one waits: the app takes a frame
/// at most one paint old, not one painted a round trip after its last
/// take. When one was waiting, this one waits unacknowledged in its place
/// and is acknowledged when taken: Chrome is at most one frame ahead of
/// the app, so it encodes no more than about two frames a take.
fn keep_frame(
    waiting: &mut Option<RawFrame>,
    data: String,
    meta: FrameMeta,
    ack: i64,
) -> Option<i64> {
    let ahead = waiting.is_none();
    *waiting = Some((data, meta, (!ahead).then_some(ack)));
    ahead.then_some(ack)
}

#[derive(Default)]
struct Shared {
    frame: Option<Pixels>,
    /// Where the last decoded frame was taken.
    meta: FrameMeta,
    /// On demand: the newest frame, waiting to be taken.
    raw: Option<RawFrame>,
    state: PageState,
    notify: Option<Notify>,
    /// The browser process, so the engine can end it from any thread.
    child: Option<Child>,
}

/// What the browser does with a download: [`ChromeEngine::downloads`].
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub enum Downloads {
    /// Refuse every download (the default).
    #[default]
    Deny,
    /// Let the browser download into this directory, each file under its
    /// download's id (`Browser.setDownloadBehavior`'s `allowAndName`), so a
    /// page cannot choose a name or a place. The directory is made, this
    /// user's only. The app hears of each download through
    /// [`DevTools::listen`] (`Browser.downloadWillBegin`,
    /// `Browser.downloadProgress`) and decides what to keep: nothing here
    /// opens, runs or moves a file.
    Quarantine(PathBuf),
}

/// An event from the browser, for [`DevTools::listen`]: its method and its
/// parameters, which are the page's and untrusted.
#[derive(Clone, Debug, PartialEq)]
pub struct DevToolsEvent {
    pub method: String,
    pub params: Value,
}

/// The apps' event listeners: the methods each wants, and where they go.
type Listeners = Arc<Mutex<Vec<(Vec<String>, Sender<DevToolsEvent>)>>>;

/// A command an app sends the page, and where its answer goes.
struct Call {
    method: String,
    params: Value,
    answer: Sender<io::Result<Value>>,
}

/// The page's DevTools, for the commands the engine does not send itself:
/// from [`ChromeEngine::devtools`]. `Clone` and `Send`: a thread of the
/// app's may hold one. Every call goes to the page's session, after the
/// page is attached; what the page says back is the page's, and is
/// untrusted.
#[derive(Clone, Debug)]
pub struct DevTools {
    calls: Sender<Call>,
    listeners: Listeners,
}

impl DevTools {
    /// Send `method` with `params` to the page, and wait up to `timeout`
    /// for its `result`. DevTools's own error, a browser that has gone and
    /// a timeout are errors.
    pub fn call(&self, method: &str, params: Value, timeout: Duration) -> io::Result<Value> {
        let (answer, wait) = mpsc::channel();
        let call = Call {
            method: method.to_string(),
            params,
            answer,
        };
        self.calls
            .send(call)
            .map_err(|_| io::Error::new(ErrorKind::BrokenPipe, "the browser has gone"))?;
        match wait.recv_timeout(timeout) {
            Ok(result) => result,
            Err(mpsc::RecvTimeoutError::Timeout) => Err(io::Error::new(
                ErrorKind::TimedOut,
                format!("{method}: no answer in time"),
            )),
            Err(mpsc::RecvTimeoutError::Disconnected) => Err(io::Error::new(
                ErrorKind::BrokenPipe,
                "the browser has gone",
            )),
        }
    }

    /// The browser's events named in `methods` (`"Runtime.bindingCalled"`,
    /// `"Browser.downloadWillBegin"`, …), from now on, as they come: the
    /// page's own session's and the browser's. A domain's events come only
    /// once it is enabled, which the app does with [`call`](Self::call)
    /// (`Page` is always on). The channel ends when the browser goes; drop
    /// the receiver to stop listening.
    pub fn listen(&self, methods: &[&str]) -> Receiver<DevToolsEvent> {
        let (send, receive) = mpsc::channel();
        let methods = methods.iter().map(|m| m.to_string()).collect();
        self.listeners
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .push((methods, send));
        receive
    }
}

/// Send `event` to every listener that asked for its method, and forget
/// the listeners that have gone.
fn deliver(listeners: &Listeners, method: &str, params: &Value) {
    let mut listeners = listeners.lock().unwrap_or_else(PoisonError::into_inner);
    listeners.retain(|(methods, send)| {
        if !methods.iter().any(|m| m == method) {
            return true;
        }
        send.send(DevToolsEvent {
            method: method.to_string(),
            params: params.clone(),
        })
        .is_ok()
    });
}

fn lock(shared: &Mutex<Shared>) -> MutexGuard<'_, Shared> {
    shared.lock().unwrap_or_else(PoisonError::into_inner)
}

fn notify(shared: &Mutex<Shared>) {
    let notify = lock(shared).notify.clone();
    if let Some(notify) = notify {
        notify();
    }
}

/// A headless Chrome or Chromium behind a web view. Frames are pixels,
/// drawn as half blocks.
///
/// # Security
///
/// On Linux and macOS the engine drives the browser over DevTools on a
/// pipe only the two processes hold: no port is opened, and nothing else on
/// the machine can reach it.
///
/// On Windows it uses a random TCP port of `127.0.0.1`. While the view is
/// open, that port can be reached by other programs and other users on this
/// machine, and DevTools has no authentication of its own: whoever finds it
/// can drive the browser as this user (open local files, run script in
/// pages). On Windows, use this engine on a machine you do not share.
///
/// Everywhere, the profile directory is readable by this user only.
pub struct ChromeEngine {
    binary: Option<PathBuf>,
    args: Vec<String>,
    cell: (u32, u32),
    shared: Arc<Mutex<Shared>>,
    commands: Option<Sender<Request>>,
    calls: Option<Sender<Call>>,
    /// The profile the browser runs in, once it started.
    profile: Option<PathBuf>,
    /// A kept profile the app chose: never removed.
    kept_profile: Option<PathBuf>,
    audio: bool,
    downloads: Downloads,
    listeners: Listeners,
    wire: Wire,
    screencast: bool,
    on_demand: bool,
    /// The screencast's frames as a fraction of the viewport's size.
    scale: f64,
}

impl fmt::Debug for ChromeEngine {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ChromeEngine")
            .field("binary", &self.binary)
            .field("cell", &self.cell)
            .finish()
    }
}

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

impl ChromeEngine {
    /// The browser found by [`find`](Self::find) when it starts.
    pub fn new() -> ChromeEngine {
        ChromeEngine {
            binary: None,
            args: Vec::new(),
            cell: (10, 20),
            shared: Arc::default(),
            commands: None,
            calls: None,
            profile: None,
            kept_profile: None,
            audio: false,
            downloads: Downloads::Deny,
            listeners: Arc::default(),
            wire: Wire::DEFAULT,
            screencast: true,
            on_demand: false,
            scale: 1.0,
        }
    }

    /// Let the page's sound play (on the machine the browser runs on). Off
    /// by default: the browser starts with `--mute-audio`.
    #[must_use]
    pub fn audio(mut self, on: bool) -> ChromeEngine {
        self.audio = on;
        self
    }

    /// What the browser does with downloads: [`Downloads::Deny`] (the
    /// default) or [`Downloads::Quarantine`].
    #[must_use]
    pub fn downloads(mut self, downloads: Downloads) -> ChromeEngine {
        self.downloads = downloads;
        self
    }

    /// Run the browser in `dir`, a profile kept between runs (its cookies,
    /// its storage and its cache), rather than a temporary one. Opt-in: by
    /// default every engine gets a new, private profile, removed when it
    /// goes. `dir` is made if it is missing (this user's only, on Unix) and
    /// is never removed. Two browsers cannot share one profile at a time.
    #[must_use]
    pub fn profile(mut self, dir: impl Into<PathBuf>) -> ChromeEngine {
        self.kept_profile = Some(dir.into());
        self
    }

    /// Run the browser at `path`.
    #[must_use]
    pub fn binary(mut self, path: impl Into<PathBuf>) -> ChromeEngine {
        self.binary = Some(path.into());
        self
    }

    /// More command-line switches for the browser. The sandbox stays on
    /// whatever they say: `--no-sandbox`, and every other switch that turns
    /// part of it off, is dropped, however it is spelled. So is every
    /// `--remote-debugging-…` switch: the engine says where DevTools goes.
    #[must_use]
    pub fn args<I: IntoIterator<Item = S>, S: Into<String>>(mut self, args: I) -> ChromeEngine {
        self.args.extend(
            args.into_iter()
                .map(Into::into)
                .filter(|arg| !turns_sandbox_off(arg) && !moves_devtools(arg)),
        );
        self
    }

    /// Whether the page's pixels stream in as frames (`Page.startScreencast`,
    /// each JPEG decoded). On by default; an app that reads the page itself
    /// (its snapshot, its accessibility tree) and never shows the frames
    /// turns it off, so the browser does not encode them nor the engine
    /// decode them. [`set_screencast`](Self::set_screencast) switches it
    /// while the page is open: screencast on demand.
    #[must_use]
    pub fn screencast(mut self, on: bool) -> ChromeEngine {
        self.screencast = on;
        self
    }

    /// Start or stop the screencast now (see [`screencast`](Self::screencast)).
    /// Frames come again from the next one Chrome paints.
    pub fn set_screencast(&mut self, on: bool) -> io::Result<()> {
        self.screencast = on;
        if self.commands.is_none() {
            return Ok(());
        }
        self.send(Request::Screencast(on))
    }

    /// Screencast frames on demand: each frame is kept as Chrome sent it,
    /// and decoded only when the app takes it
    /// ([`take_screencast`](Self::take_screencast)). Chrome sends the next
    /// frame only after an acknowledgement, and the engine keeps it at
    /// most one frame ahead of the app: a frame that comes when the last
    /// was taken is acknowledged at once (so the next is painted while it
    /// waits, and the app's next take finds a fresh one), one that comes
    /// while another waits is acknowledged when taken. So the browser
    /// encodes about as many frames as the app takes: an app that wants a
    /// few frames a second of a video costs a few. Off by default: each
    /// frame is decoded and acknowledged as it comes, for
    /// [`WebEngine::poll`].
    #[must_use]
    pub fn screencast_on_demand(mut self, on: bool) -> ChromeEngine {
        self.on_demand = on;
        self
    }

    /// The screencast's frames as `scale` (above 0, at most 1) of the
    /// viewport's size, through `maxWidth` and `maxHeight`: an app that
    /// draws a region in fewer pixels than the page has (character art,
    /// two pixels a cell) asks for no more, and Chrome encodes and the
    /// engine decodes a fraction of the bytes.
    /// [`ScreencastFrame::crop`] maps through the frame's own size, so a
    /// region is cut the same at any scale. Taking effect restarts the
    /// screencast; frames come again from the next Chrome paints.
    pub fn set_screencast_scale(&mut self, scale: f64) -> io::Result<()> {
        let scale = if scale.is_finite() {
            scale.clamp(0.01, 1.0)
        } else {
            1.0
        };
        if (scale - self.scale).abs() < f64::EPSILON {
            return Ok(());
        }
        self.scale = scale;
        if self.commands.is_none() {
            return Ok(());
        }
        self.send(Request::ScreencastScale(scale))
    }

    /// The newest screencast frame since the last call, with where it was
    /// taken (its scroll position, for [`ScreencastFrame::crop`]). On
    /// demand, it is decoded now, and acknowledged if it was not as it
    /// came, which lets Chrome send the next.
    pub fn take_screencast(&mut self) -> Option<ScreencastFrame> {
        let (raw, decoded) = {
            let mut shared = lock(&self.shared);
            let meta = shared.meta;
            (shared.raw.take(), shared.frame.take().map(|p| (p, meta)))
        };
        if let Some((data, meta, ack)) = raw {
            if let Some(ack) = ack {
                let _ = self.send(Request::Ack(ack));
            }
            return decode_frame(&data).map(|pixels| ScreencastFrame { pixels, meta });
        }
        decoded.map(|(pixels, meta)| ScreencastFrame { pixels, meta })
    }

    /// The CSS pixels one cell of the pane stands for (default 10 x 20):
    /// the page is laid out at the pane's size times this.
    #[must_use]
    pub fn cell_pixels(mut self, width: u32, height: u32) -> ChromeEngine {
        self.cell = (width.max(1), height.max(1));
        self
    }

    /// End every browser an engine started and has not ended, and remove
    /// each one's temporary profile, as dropping each engine would. A kept
    /// profile stays. For the way out of a process whose engines live on
    /// where no `Drop` reaches them (in state that lasts until the process
    /// exits, on a thread still running, or past a signal): call it last.
    /// An engine used after it has no browser, and starts no other.
    pub fn end_all() {
        let all = std::mem::take(&mut *RUNNING.lock().unwrap_or_else(PoisonError::into_inner));
        for running in all {
            if let Some(shared) = running.shared.upgrade() {
                let child = lock(&shared).child.take();
                if let Some(mut child) = child {
                    end_browser(&mut child);
                }
            }
            if let Some(profile) = running.profile {
                remove_profile(&profile);
            }
        }
    }

    /// The first browser on `PATH` by [`BINARY_NAMES`], or in a usual
    /// install location.
    pub fn find() -> Option<PathBuf> {
        let path = std::env::var_os("PATH").unwrap_or_default();
        for name in BINARY_NAMES {
            for dir in std::env::split_paths(&path) {
                let candidate = dir.join(name);
                if candidate.is_file() {
                    return Some(candidate);
                }
                let exe = candidate.with_extension("exe");
                if cfg!(windows) && exe.is_file() {
                    return Some(exe);
                }
            }
        }
        KNOWN_PATHS
            .iter()
            .map(PathBuf::from)
            .find(|path| path.is_file())
    }

    /// The page's DevTools, for commands of the app's own. Starts the
    /// browser if it has not started.
    pub fn devtools(&mut self) -> io::Result<DevTools> {
        if self.commands.is_none() {
            self.start()?;
        }
        let calls = self
            .calls
            .clone()
            .ok_or_else(|| io::Error::new(ErrorKind::BrokenPipe, "the browser has gone"))?;
        Ok(DevTools {
            calls,
            listeners: Arc::clone(&self.listeners),
        })
    }

    fn fail(&self, message: impl Into<String>) {
        lock(&self.shared).state.error = Some(message.into());
        notify(&self.shared);
    }

    /// Start the browser and the engine's thread.
    fn start(&mut self) -> io::Result<()> {
        let Some(binary) = self.binary.clone().or_else(ChromeEngine::find) else {
            let message = format!(
                "no Chrome or Chromium found: install one, or name it with \
                 ChromeEngine::binary (looked for {})",
                BINARY_NAMES.join(", ")
            );
            self.fail(message.clone());
            return Err(io::Error::new(ErrorKind::NotFound, message));
        };
        let profile = match &self.kept_profile {
            Some(dir) => {
                private_dir(dir)?;
                dir.clone()
            }
            None => temporary_profile()?,
        };
        if let Downloads::Quarantine(dir) = &self.downloads {
            private_dir(dir)?;
        }
        // The window's first size; the page is sized to the pane once
        // attached.
        let mut command = Command::new(&binary);
        command
            .args(launch_args(
                &profile, &self.args, 80, 24, self.cell, self.wire, self.audio,
            ))
            .stdin(Stdio::null())
            .stdout(Stdio::null())
            .stderr(Stdio::piped());
        // A group of its own, so ending it ends its helpers too (the
        // zygote, renderers, GPU and crash handler), which otherwise keep
        // writing to the profile while it is removed.
        #[cfg(unix)]
        std::os::unix::process::CommandExt::process_group(&mut command, 0);
        let spawned = connect(&mut command, self.wire).and_then(|connect| {
            let child = command.spawn()?;
            Ok((child, connect))
        });
        // Our copies of the browser's ends of the pipe close with the
        // command, so its exit reads as the end of the pipe.
        drop(command);
        // The profile is the engine's to remove only once Chrome runs in
        // it; a failed start removes it here, so retries leave none behind.
        let (mut child, connect) = match spawned {
            Ok(spawned) => spawned,
            Err(error) => {
                if self.kept_profile.is_none() {
                    let _ = std::fs::remove_dir_all(&profile);
                }
                return Err(error);
            }
        };
        self.profile = Some(profile.clone());
        RUNNING
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .push(Running {
                shared: Arc::downgrade(&self.shared),
                profile: self.kept_profile.is_none().then(|| profile.clone()),
            });
        let stderr = child.stderr.take().expect("piped stderr");
        lock(&self.shared).child = Some(child);
        let (sender, receiver) = mpsc::channel();
        self.commands = Some(sender);
        let (calls, called) = mpsc::channel();
        self.calls = Some(calls);
        let shared = Arc::clone(&self.shared);
        let cell = self.cell;
        let wiring = Wiring {
            downloads: self.downloads.clone(),
            listeners: Arc::clone(&self.listeners),
            screencast: self.screencast,
            on_demand: self.on_demand,
            scale: self.scale,
        };
        thread::spawn(move || {
            if let Err(error) = run(connect, stderr, receiver, called, &shared, cell, wiring) {
                let mut state = lock(&shared);
                state.state.error = Some(format!("Chrome: {error}"));
                state.state.loading = false;
                drop(state);
                notify(&shared);
            }
        });
        Ok(())
    }

    fn send(&mut self, command: Request) -> io::Result<()> {
        if self.commands.is_none() {
            self.start()?;
        }
        if let Some(commands) = &self.commands {
            commands
                .send(command)
                .map_err(|_| io::Error::new(ErrorKind::BrokenPipe, "the browser has gone"))?;
        }
        Ok(())
    }
}

/// A browser an engine started, for [`ChromeEngine::end_all`]: its
/// process (in the engine's shared state) and its temporary profile.
struct Running {
    shared: Weak<Mutex<Shared>>,
    profile: Option<PathBuf>,
}

/// Every browser started and not yet ended by its engine's `Drop`.
static RUNNING: Mutex<Vec<Running>> = Mutex::new(Vec::new());

impl Drop for ChromeEngine {
    fn drop(&mut self) {
        // This engine ends its own browser here.
        RUNNING
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .retain(|running| !std::ptr::eq(running.shared.as_ptr(), Arc::as_ptr(&self.shared)));
        // Closing the channel ends the thread's loop; the browser goes now.
        self.commands = None;
        self.calls = None;
        let child = lock(&self.shared).child.take();
        if let Some(mut child) = child {
            end_browser(&mut child);
        }
        if let Some(profile) = &self.profile
            && self.kept_profile.is_none()
        {
            remove_profile(profile);
        }
    }
}

/// End the browser and every helper in its process group, then reap it.
fn end_browser(child: &mut Child) {
    kill_group(child);
    let _ = child.kill();
    let _ = child.wait();
}

/// Kill the process group the browser leads, with SIGKILL.
#[cfg(unix)]
#[allow(unsafe_code)]
fn kill_group(child: &Child) {
    if let Ok(group) = libc::pid_t::try_from(child.id()) {
        // SAFETY: `killpg` takes plain integers. The browser has not been
        // reaped, so its id still names the group it leads.
        unsafe {
            libc::killpg(group, libc::SIGKILL);
        }
    }
}

/// Elsewhere only the browser itself is ended.
#[cfg(not(unix))]
fn kill_group(_child: &Child) {}

/// Remove a temporary profile. A helper the kill has not reached yet can
/// still write into it for a moment, so the removal is tried again for up
/// to a second while the directory is there.
fn remove_profile(profile: &std::path::Path) {
    for _ in 0..20 {
        let _ = std::fs::remove_dir_all(profile);
        if !profile.exists() {
            return;
        }
        std::thread::sleep(std::time::Duration::from_millis(50));
    }
}

impl WebEngine for ChromeEngine {
    fn open(&mut self, url: &str) -> io::Result<()> {
        {
            let mut shared = lock(&self.shared);
            shared.state.loading = true;
            shared.state.error = None;
        }
        self.send(Request::Open(url.to_string()))
    }

    fn resize(&mut self, columns: u16, rows: u16) -> io::Result<()> {
        self.send(Request::Resize(columns, rows))
    }

    fn input(&mut self, input: WebInput) -> io::Result<()> {
        self.send(Request::Input(input))
    }

    fn back(&mut self) -> io::Result<()> {
        self.send(Request::Back)
    }

    fn forward(&mut self) -> io::Result<()> {
        self.send(Request::Forward)
    }

    fn reload(&mut self) -> io::Result<()> {
        self.send(Request::Reload)
    }

    fn poll(&mut self) -> Option<WebFrame> {
        lock(&self.shared).frame.take().map(WebFrame::Pixels)
    }

    fn state(&self) -> PageState {
        lock(&self.shared).state.clone()
    }

    fn set_notify(&mut self, notify: Notify) {
        lock(&self.shared).notify = Some(notify);
    }
}

/// The engine's ends of the browser's DevTools connection, before it runs.
enum Connect {
    /// Read the address from the browser's standard error, then connect.
    Port,
    /// Write to the browser's descriptor 3, read from its descriptor 4.
    #[cfg(unix)]
    Pipe(io::PipeWriter, io::PipeReader),
}

/// Set `command` up for `wire`: for the pipe, two pipes whose far ends the
/// browser gets as descriptors 3 (it reads) and 4 (it writes).
#[cfg_attr(not(unix), allow(unused_variables))]
fn connect(command: &mut Command, wire: Wire) -> io::Result<Connect> {
    match wire {
        #[cfg(unix)]
        Wire::Pipe => {
            use command_fds::{CommandFdExt, FdMapping};

            let (browser_reads, we_write) = io::pipe()?;
            let (we_read, browser_writes) = io::pipe()?;
            command
                .fd_mappings(vec![
                    FdMapping {
                        parent_fd: browser_reads.into(),
                        child_fd: 3,
                    },
                    FdMapping {
                        parent_fd: browser_writes.into(),
                        child_fd: 4,
                    },
                ])
                .map_err(|_| io::Error::other("descriptors 3 and 4 collide"))?;
            Ok(Connect::Pipe(we_write, we_read))
        }
        Wire::Port => Ok(Connect::Port),
    }
}

/// A new, empty directory for the browser's profile.
fn temporary_profile() -> io::Result<PathBuf> {
    static NEXT: AtomicU64 = AtomicU64::new(0);
    let nanos = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.subsec_nanos())
        .unwrap_or(0);
    loop {
        let n = NEXT.fetch_add(1, Ordering::SeqCst);
        let dir = std::env::temp_dir().join(format!(
            "rich-embed-chrome-{}-{n}-{nanos}",
            std::process::id()
        ));
        #[cfg_attr(not(unix), allow(unused_mut))]
        let mut builder = std::fs::DirBuilder::new();
        // This user's only: it holds the browser's cookies and its cache.
        #[cfg(unix)]
        std::os::unix::fs::DirBuilderExt::mode(&mut builder, 0o700);
        match builder.create(&dir) {
            Ok(()) => {
                #[cfg(test)]
                tests::MADE.with(|made| made.borrow_mut().push(dir.clone()));
                return Ok(dir);
            }
            Err(error) if error.kind() == ErrorKind::AlreadyExists => continue,
            Err(error) => return Err(error),
        }
    }
}

/// Make `dir` if it is missing, this user's only on Unix. A directory
/// that is there already keeps its mode.
fn private_dir(dir: &Path) -> io::Result<()> {
    if dir.is_dir() {
        return Ok(());
    }
    #[cfg_attr(not(unix), allow(unused_mut))]
    let mut builder = std::fs::DirBuilder::new();
    builder.recursive(true);
    #[cfg(unix)]
    std::os::unix::fs::DirBuilderExt::mode(&mut builder, 0o700);
    builder.create(dir)
}

/// Whether `arg` is a switch that turns any part of the browser's sandbox
/// off (`--no-sandbox`, `--disable-setuid-sandbox`, `--single-process`, …),
/// in any spelling the browser reads as one: one dash or two (or a slash
/// on Windows), any case, with or without a value.
pub(crate) fn turns_sandbox_off(arg: &str) -> bool {
    let name = arg.trim_start_matches(|c| c == '-' || (cfg!(windows) && c == '/'));
    if name.len() == arg.len() {
        // Not a switch: an address.
        return false;
    }
    let name = name
        .split('=')
        .next()
        .unwrap_or_default()
        .to_ascii_lowercase();
    ((name.starts_with("no-") || name.starts_with("disable-")) && name.contains("sandbox"))
        || matches!(name.as_str(), "single-process" | "no-zygote")
}

/// Whether `arg` opens DevTools somewhere of its own
/// (`--remote-debugging-port`, `--remote-debugging-pipe`, …): the engine
/// chooses where DevTools goes, and a port would undo the pipe.
pub(crate) fn moves_devtools(arg: &str) -> bool {
    let name = arg.trim_start_matches(|c| c == '-' || (cfg!(windows) && c == '/'));
    name.len() != arg.len() && name.to_ascii_lowercase().starts_with("remote-debugging-")
}

/// The browser's command line: headless, with DevTools on `wire`, in its
/// own profile, without first-run screens, extensions or background
/// traffic, muted unless `audio`. Never a switch that turns the sandbox
/// off, nor one that moves DevTools elsewhere.
pub(crate) fn launch_args(
    profile: &Path,
    extra: &[String],
    columns: u16,
    rows: u16,
    cell: (u32, u32),
    wire: Wire,
    audio: bool,
) -> Vec<String> {
    let (width, height) = viewport(columns, rows, cell);
    let mut args = vec![
        "--headless=new".to_string(),
        wire.switch().to_string(),
        format!("--user-data-dir={}", profile.display()),
        format!("--window-size={width},{height}"),
        "--no-first-run".to_string(),
        "--no-default-browser-check".to_string(),
        "--disable-extensions".to_string(),
        "--disable-background-networking".to_string(),
        "--disable-sync".to_string(),
        "--hide-scrollbars".to_string(),
    ];
    if !audio {
        args.push("--mute-audio".to_string());
    }
    args.extend(
        extra
            .iter()
            .filter(|arg| !turns_sandbox_off(arg) && !moves_devtools(arg))
            .cloned(),
    );
    args.push("about:blank".to_string());
    args
}

/// The page's size in CSS pixels for a pane of `columns` x `rows` cells.
fn viewport(columns: u16, rows: u16, (cw, ch): (u32, u32)) -> (u32, u32) {
    (columns.max(1) as u32 * cw, rows.max(1) as u32 * ch)
}

/// `size` times `scale`, rounded up, at least a pixel.
fn scaled((width, height): (u32, u32), scale: f64) -> (u32, u32) {
    let by = |n: u32| ((f64::from(n) * scale).ceil() as u32).clamp(1, n.max(1));
    (by(width), by(height))
}

/// The DevTools address in a line of the browser's standard error.
pub(crate) fn devtools_url(line: &str) -> Option<String> {
    let at = line.find("ws://")?;
    let url = line[at..].trim();
    url.contains("/devtools/browser/").then(|| url.to_string())
}

/// A DevTools command: `{"id", "method", "params"}`, and the session it is
/// for (none: the browser itself).
pub(crate) fn command(id: u64, method: &str, params: Value, session: Option<&str>) -> String {
    let mut message = json!({"id": id, "method": method, "params": params});
    if let Some(session) = session {
        message["sessionId"] = Value::String(session.to_string());
    }
    message.to_string()
}

/// The DevTools modifier bits: Alt 1, Ctrl 2, Meta 4, Shift 8.
fn modifier_bits(modifiers: Modifiers) -> u8 {
    modifiers.alt as u8 + 2 * modifiers.ctrl as u8 + 8 * modifiers.shift as u8
}

/// A key's DOM name, its Windows virtual key code, and the text it types.
fn key_parts(key: Key) -> (String, u32, Option<String>) {
    let named = |name: &str, code: u32| (name.to_string(), code, None);
    match key.code {
        KeyCode::Char(c) => {
            let upper = c.to_ascii_uppercase();
            let code = if upper.is_ascii_alphanumeric() {
                upper as u32
            } else if c == ' ' {
                32
            } else {
                0
            };
            let text = (!key.modifiers.ctrl && !key.modifiers.alt).then(|| c.to_string());
            (c.to_string(), code, text)
        }
        KeyCode::Enter => ("Enter".into(), 13, Some("\r".into())),
        KeyCode::Tab => named("Tab", 9),
        KeyCode::BackTab => named("Tab", 9),
        KeyCode::Backspace => named("Backspace", 8),
        KeyCode::Delete => named("Delete", 46),
        KeyCode::Insert => named("Insert", 45),
        KeyCode::Escape => named("Escape", 27),
        KeyCode::Up => named("ArrowUp", 38),
        KeyCode::Down => named("ArrowDown", 40),
        KeyCode::Left => named("ArrowLeft", 37),
        KeyCode::Right => named("ArrowRight", 39),
        KeyCode::Home => named("Home", 36),
        KeyCode::End => named("End", 35),
        KeyCode::PageUp => named("PageUp", 33),
        KeyCode::PageDown => named("PageDown", 34),
        KeyCode::Menu => named("ContextMenu", 93),
        KeyCode::Modifier(which) => match which {
            ModifierKey::Shift => named("Shift", 16),
            ModifierKey::Ctrl => named("Control", 17),
            ModifierKey::Alt => named("Alt", 18),
            ModifierKey::Super => named("Meta", 91),
        },
        KeyCode::F(n) => (format!("F{n}"), 111 + n as u32, None),
    }
}

/// The `Input.dispatchKeyEvent` parameters for a key press: down (with its
/// text, if it types one) and up. Public for programs that drive a page
/// over DevTools themselves (Noctiluca's pixel view passes keys through).
pub fn key_events(key: Key) -> Vec<Value> {
    let (name, code, text) = key_parts(key);
    let mut modifiers = modifier_bits(key.modifiers);
    if key.code == KeyCode::BackTab {
        modifiers |= 8;
    }
    let mut down = json!({
        "type": if text.is_some() { "keyDown" } else { "rawKeyDown" },
        "key": name,
        "windowsVirtualKeyCode": code,
        "modifiers": modifiers,
    });
    if let Some(text) = text {
        down["text"] = Value::String(text.clone());
        down["unmodifiedText"] = Value::String(text);
    }
    let up = json!({
        "type": "keyUp",
        "key": name,
        "windowsVirtualKeyCode": code,
        "modifiers": modifiers,
    });
    vec![down, up]
}

/// The `Input.dispatchMouseEvent` parameters for `mouse` at a cell of the
/// pane, at the middle of that cell in CSS pixels.
pub(crate) fn mouse_event(mouse: Mouse, (cw, ch): (u32, u32)) -> Value {
    let x = mouse.column as f64 * cw as f64 + cw as f64 / 2.0;
    let y = mouse.row as f64 * ch as f64 + ch as f64 / 2.0;
    let button = |b: Button| match b {
        Button::Left => "left",
        Button::Middle => "middle",
        Button::Right => "right",
    };
    let (kind, button, clicks) = match mouse.kind {
        MouseKind::Down(b) => ("mousePressed", button(b), 1),
        MouseKind::Up(b) => ("mouseReleased", button(b), 1),
        MouseKind::Drag(b) => ("mouseMoved", button(b), 0),
        MouseKind::Moved => ("mouseMoved", "none", 0),
        MouseKind::ScrollUp | MouseKind::ScrollDown => ("mouseWheel", "none", 0),
    };
    let mut event = json!({
        "type": kind,
        "x": x,
        "y": y,
        "button": button,
        "clickCount": clicks,
        "modifiers": modifier_bits(mouse.modifiers),
    });
    if kind == "mouseWheel" {
        let rows = if mouse.kind == MouseKind::ScrollUp {
            -3.0
        } else {
            3.0
        };
        event["deltaX"] = json!(0);
        event["deltaY"] = json!(rows * ch as f64);
    }
    event
}

/// Standard base64, as DevTools sends screencast frames.
pub(crate) fn base64_decode(text: &str) -> Option<Vec<u8>> {
    let mut out = Vec::with_capacity(text.len() / 4 * 3);
    let mut buffer = 0u32;
    let mut bits = 0;
    for byte in text.bytes() {
        let value = match byte {
            b'A'..=b'Z' => byte - b'A',
            b'a'..=b'z' => byte - b'a' + 26,
            b'0'..=b'9' => byte - b'0' + 52,
            b'+' => 62,
            b'/' => 63,
            b'=' => break,
            b'\r' | b'\n' => continue,
            _ => return None,
        };
        buffer = buffer << 6 | value as u32;
        bits += 6;
        if bits >= 8 {
            bits -= 8;
            out.push((buffer >> bits) as u8);
            buffer &= (1 << bits) - 1;
        }
    }
    Some(out)
}

/// A screencast frame (base64 JPEG or PNG) as RGB pixels.
fn decode_frame(data: &str) -> Option<Pixels> {
    let bytes = base64_decode(data)?;
    let image = image::load_from_memory(&bytes).ok()?.to_rgb8();
    Pixels::new(image.width(), image.height(), image.into_raw())
}

/// Wait for the browser to print where DevTools listens, then keep reading
/// its standard error so it never blocks on a full pipe.
fn devtools_address(stderr: ChildStderr) -> io::Result<String> {
    let (found, wait) = mpsc::channel();
    thread::spawn(move || {
        let mut found = Some(found);
        let mut last = String::new();
        for line in BufReader::new(stderr).lines() {
            let Ok(line) = line else { break };
            if let Some(url) = devtools_url(&line) {
                if let Some(found) = found.take() {
                    let _ = found.send(Ok(url));
                }
            } else if found.is_some() && !line.trim().is_empty() {
                last = line;
            }
        }
        if let Some(found) = found {
            let _ = found.send(Err(last));
        }
    });
    match wait.recv_timeout(START_TIMEOUT) {
        Ok(Ok(url)) => Ok(url),
        Ok(Err(last)) => Err(io::Error::other(if last.is_empty() {
            "the browser exited before DevTools started".to_string()
        } else {
            format!("the browser exited before DevTools started: {last}")
        })),
        Err(_) => Err(io::Error::new(
            ErrorKind::TimedOut,
            "the browser did not start DevTools in time",
        )),
    }
}

/// Keep reading the browser's standard error so it never blocks on a full
/// pipe; its last line, once it ends, says why the browser went.
#[cfg(unix)]
fn drain(stderr: ChildStderr) -> Receiver<String> {
    let (last_line, wait) = mpsc::channel();
    thread::spawn(move || {
        let mut last = String::new();
        for line in BufReader::new(stderr).lines() {
            let Ok(line) = line else { break };
            if !line.trim().is_empty() {
                last = line;
            }
        }
        let _ = last_line.send(last);
    });
    wait
}

/// The DevTools connection's messages, whichever way they travel.
enum Transport {
    /// A WebSocket on a port of `127.0.0.1`, read with a timeout.
    WebSocket(Box<WebSocket<TcpStream>>),
    /// NUL-ended JSON on a pipe each way, read on a thread of its own so
    /// the engine's thread can wait with a timeout.
    #[cfg(unix)]
    Pipe {
        write: io::PipeWriter,
        read: Receiver<Vec<u8>>,
        /// The browser's last line on standard error, once it ends.
        stderr: Receiver<String>,
    },
}

impl Transport {
    /// Over the WebSocket the browser announced on its standard error.
    fn websocket(stderr: ChildStderr) -> io::Result<Transport> {
        let url = devtools_address(stderr)?;
        let address = url
            .trim_start_matches("ws://")
            .split('/')
            .next()
            .unwrap_or_default()
            .to_string();
        let stream = TcpStream::connect(&address)?;
        let (socket, _) = tungstenite::client::client(url.as_str(), stream)
            .map_err(|error| io::Error::other(error.to_string()))?;
        socket.get_ref().set_read_timeout(Some(POLL))?;
        Ok(Transport::WebSocket(Box::new(socket)))
    }

    /// Over the pipe to the browser's descriptors 3 and 4.
    #[cfg(unix)]
    fn pipe(write: io::PipeWriter, read: io::PipeReader, stderr: ChildStderr) -> Transport {
        let (messages, receive) = mpsc::channel();
        thread::spawn(move || {
            let mut read = BufReader::new(read);
            loop {
                let mut message = Vec::new();
                match read.read_until(0, &mut message) {
                    // The pipe's end: the browser went.
                    Ok(0) | Err(_) => break,
                    Ok(_) => {
                        if message.last() == Some(&0) {
                            message.pop();
                        }
                        if messages.send(message).is_err() {
                            break;
                        }
                    }
                }
            }
        });
        Transport::Pipe {
            write,
            read: receive,
            stderr: drain(stderr),
        }
    }

    fn send(&mut self, text: &str) -> io::Result<()> {
        match self {
            Transport::WebSocket(socket) => socket
                .send(Message::text(text))
                .map_err(|error| io::Error::other(error.to_string())),
            #[cfg(unix)]
            Transport::Pipe { write, .. } => {
                // JSON escapes NUL inside strings, so it only ever ends one.
                let mut bytes = Vec::with_capacity(text.len() + 1);
                bytes.extend_from_slice(text.as_bytes());
                bytes.push(0);
                io::Write::write_all(write, &bytes)?;
                io::Write::flush(write)
            }
        }
    }

    /// The next message, or none if none came within [`POLL`].
    fn read(&mut self) -> io::Result<Option<String>> {
        match self {
            Transport::WebSocket(socket) => match socket.read() {
                Ok(Message::Text(text)) => Ok(Some(text.as_str().to_string())),
                Ok(Message::Close(_)) => Err(io::Error::other("the browser closed")),
                Ok(_) => Ok(None),
                Err(tungstenite::Error::Io(error))
                    if matches!(error.kind(), ErrorKind::WouldBlock | ErrorKind::TimedOut) =>
                {
                    Ok(None)
                }
                Err(error) => Err(io::Error::other(error.to_string())),
            },
            #[cfg(unix)]
            Transport::Pipe { read, stderr, .. } => match read.recv_timeout(POLL) {
                Ok(message) => Ok(Some(String::from_utf8_lossy(&message).into_owned())),
                Err(mpsc::RecvTimeoutError::Timeout) => Ok(None),
                Err(mpsc::RecvTimeoutError::Disconnected) => {
                    let last = stderr
                        .recv_timeout(Duration::from_secs(1))
                        .unwrap_or_default();
                    Err(io::Error::other(if last.is_empty() {
                        "the browser closed".to_string()
                    } else {
                        format!("the browser closed: {last}")
                    }))
                }
            },
        }
    }
}

/// What a pending command's answer is for.
enum Pending {
    CreateTarget,
    Attach,
    History,
    /// An app's, through [`DevTools`]: the answer goes back to it.
    Call(Sender<io::Result<Value>>),
    Other,
}

/// The DevTools connection, on the engine's thread.
struct Session {
    transport: Transport,
    next: u64,
    pending: Vec<(u64, Pending)>,
    session: Option<String>,
    target: Option<String>,
    /// History entries' ids, and the current one's index.
    history: Vec<i64>,
    current: usize,
    /// The page's area in cells, for the viewport and the screencast.
    size: (u16, u16),
    cell: (u32, u32),
    /// What the app asked for before the page was attached.
    waiting: Vec<Request>,
    /// The app's DevTools calls made before the page was attached.
    calls: Vec<Call>,
    listeners: Listeners,
    /// Whether frames stream in.
    screencast: bool,
    /// Whether frames wait, undecoded, to be taken.
    on_demand: bool,
    /// The frames as a fraction of the viewport's size.
    scale: f64,
}

/// What the engine's thread is set up with besides its channels.
struct Wiring {
    downloads: Downloads,
    listeners: Listeners,
    screencast: bool,
    on_demand: bool,
    scale: f64,
}

/// The `Browser.setDownloadBehavior` parameters for `downloads`.
pub(crate) fn download_behavior(downloads: &Downloads) -> Value {
    match downloads {
        Downloads::Deny => json!({"behavior": "deny"}),
        Downloads::Quarantine(dir) => json!({
            "behavior": "allowAndName",
            "downloadPath": dir.display().to_string(),
            "eventsEnabled": true,
        }),
    }
}

impl Session {
    fn send(&mut self, method: &str, params: Value, kind: Pending, page: bool) -> io::Result<()> {
        self.next += 1;
        let session = if page { self.session.clone() } else { None };
        let text = command(self.next, method, params, session.as_deref());
        self.pending.push((self.next, kind));
        self.transport.send(&text)
    }

    fn page(&mut self, method: &str, params: Value) -> io::Result<()> {
        self.send(method, params, Pending::Other, true)
    }

    /// Send an app's call to the page, or keep it until there is one.
    fn call(&mut self, call: Call) -> io::Result<()> {
        if self.session.is_none() {
            self.calls.push(call);
            return Ok(());
        }
        self.send(&call.method, call.params, Pending::Call(call.answer), true)
    }

    fn screencast(&mut self) -> io::Result<()> {
        let (width, height) = viewport(self.size.0, self.size.1, self.cell);
        self.page(
            "Emulation.setDeviceMetricsOverride",
            json!({"width": width, "height": height, "deviceScaleFactor": 1, "mobile": false}),
        )?;
        self.page("Page.stopScreencast", json!({}))?;
        if !self.screencast {
            return Ok(());
        }
        let (max_width, max_height) = scaled((width, height), self.scale);
        self.page(
            "Page.startScreencast",
            json!({"format": "jpeg", "quality": 70, "maxWidth": max_width,
                   "maxHeight": max_height, "everyNthFrame": 1}),
        )
    }

    fn history(&mut self) -> io::Result<()> {
        self.send(
            "Page.getNavigationHistory",
            json!({}),
            Pending::History,
            true,
        )
    }

    fn apply(&mut self, command: Request) -> io::Result<()> {
        if self.session.is_none() {
            self.waiting.push(command);
            return Ok(());
        }
        match command {
            Request::Open(url) => self.page("Page.navigate", json!({"url": url})),
            Request::Resize(columns, rows) => {
                self.size = (columns, rows);
                self.screencast()
            }
            Request::Input(WebInput::Key(key)) => {
                for event in key_events(key) {
                    self.page("Input.dispatchKeyEvent", event)?;
                }
                Ok(())
            }
            Request::Input(WebInput::Mouse(mouse)) => {
                let event = mouse_event(mouse, self.cell);
                self.page("Input.dispatchMouseEvent", event)
            }
            Request::Input(WebInput::Paste(text)) => {
                self.page("Input.insertText", json!({"text": text}))
            }
            Request::Back if self.current > 0 => {
                let entry = self.history[self.current - 1];
                self.page("Page.navigateToHistoryEntry", json!({"entryId": entry}))
            }
            Request::Forward if self.current + 1 < self.history.len() => {
                let entry = self.history[self.current + 1];
                self.page("Page.navigateToHistoryEntry", json!({"entryId": entry}))
            }
            Request::Back | Request::Forward => Ok(()),
            Request::Reload => self.page("Page.reload", json!({})),
            Request::Screencast(on) => {
                self.screencast = on;
                self.screencast()
            }
            Request::ScreencastScale(scale) => {
                self.scale = scale;
                self.screencast()
            }
            Request::Ack(id) => self.page("Page.screencastFrameAck", json!({"sessionId": id})),
        }
    }

    /// Handle one message from the browser.
    fn message(&mut self, text: &str, shared: &Mutex<Shared>) -> io::Result<()> {
        let Ok(message) = serde_json::from_str::<Value>(text) else {
            return Ok(());
        };
        if let Some(id) = message.get("id").and_then(Value::as_u64) {
            let kind = self
                .pending
                .iter()
                .position(|(n, _)| *n == id)
                .map(|at| self.pending.remove(at).1)
                .unwrap_or(Pending::Other);
            if let Some(error) = message.get("error") {
                return match kind {
                    // The history is asked for again at the next
                    // navigation event. A request sent while a navigation
                    // swaps the page's renderer process (from `about:blank`
                    // to a `file://` page, or to another site) is refused
                    // with "Not attached to an active page"; that must not
                    // end the engine.
                    Pending::Other | Pending::History => Ok(()),
                    // An app's call failing fails only that call.
                    Pending::Call(answer) => {
                        let _ = answer.send(Err(io::Error::other(error.to_string())));
                        Ok(())
                    }
                    _ => Err(io::Error::other(error.to_string())),
                };
            }
            let result = &message["result"];
            match kind {
                Pending::CreateTarget => {
                    let target = result["targetId"].as_str().unwrap_or_default().to_string();
                    self.target = Some(target.clone());
                    self.send(
                        "Target.attachToTarget",
                        json!({"targetId": target, "flatten": true}),
                        Pending::Attach,
                        false,
                    )?;
                }
                Pending::Attach => {
                    self.session = result["sessionId"].as_str().map(str::to_string);
                    self.page("Page.enable", json!({}))?;
                    self.screencast()?;
                    for command in std::mem::take(&mut self.waiting) {
                        self.apply(command)?;
                    }
                    for call in std::mem::take(&mut self.calls) {
                        self.call(call)?;
                    }
                }
                Pending::Call(answer) => {
                    let _ = answer.send(Ok(result.clone()));
                }
                Pending::History => {
                    let entries = result["entries"].as_array().cloned().unwrap_or_default();
                    self.history = entries
                        .iter()
                        .filter_map(|entry| entry["id"].as_i64())
                        .collect();
                    self.current = result["currentIndex"].as_u64().unwrap_or(0) as usize;
                    let entry = entries.get(self.current);
                    {
                        let mut shared = lock(shared);
                        if let Some(entry) = entry {
                            if let Some(url) = entry["url"].as_str() {
                                shared.state.url = url.to_string();
                            }
                            shared.state.title =
                                entry["title"].as_str().unwrap_or_default().to_string();
                        }
                        shared.state.can_go_back = self.current > 0;
                        shared.state.can_go_forward = self.current + 1 < self.history.len();
                    }
                    notify(shared);
                }
                Pending::Other => {}
            }
            return Ok(());
        }
        let params = &message["params"];
        let method = message["method"].as_str().unwrap_or_default();
        // The page's session's events and the browser's own; never another
        // target's.
        let ours = match message.get("sessionId").and_then(Value::as_str) {
            Some(id) => self.session.as_deref() == Some(id),
            None => true,
        };
        if ours && !method.is_empty() {
            deliver(&self.listeners, method, params);
        }
        match method {
            "Page.screencastFrame" => {
                let meta = FrameMeta::of(&params["metadata"]);
                let ack = params["sessionId"].as_i64();
                if self.on_demand {
                    // Kept as sent, at most one frame ahead of the app
                    // ([`keep_frame`]). Without an id there is nothing to
                    // wait for.
                    if let (Some(data), Some(ack)) = (params["data"].as_str(), ack) {
                        let now = keep_frame(&mut lock(shared).raw, data.to_string(), meta, ack);
                        if let Some(ack) = now {
                            self.page("Page.screencastFrameAck", json!({"sessionId": ack}))?;
                        }
                        notify(shared);
                        return Ok(());
                    }
                }
                if let Some(ack) = ack {
                    self.page("Page.screencastFrameAck", json!({"sessionId": ack}))?;
                }
                if let Some(pixels) = params["data"].as_str().and_then(decode_frame) {
                    let mut state = lock(shared);
                    state.frame = Some(pixels);
                    state.meta = meta;
                    drop(state);
                    notify(shared);
                }
            }
            "Page.frameStartedLoading" | "Page.frameStoppedLoading" => {
                let main = params["frameId"].as_str() == self.target.as_deref();
                if main {
                    let started = message["method"] == "Page.frameStartedLoading";
                    lock(shared).state.loading = started;
                    notify(shared);
                    if !started {
                        self.history()?;
                    }
                }
            }
            "Page.frameNavigated" if params["frame"].get("parentId").is_none() => {
                if let Some(url) = params["frame"]["url"].as_str() {
                    lock(shared).state.url = url.to_string();
                    notify(shared);
                }
                self.history()?;
            }
            "Page.navigatedWithinDocument" => {
                if let Some(url) = params["url"].as_str() {
                    lock(shared).state.url = url.to_string();
                    notify(shared);
                }
                self.history()?;
            }
            "Inspector.detached" | "Target.detachedFromTarget" => {
                return Err(io::Error::other("the page was closed"));
            }
            _ => {}
        }
        Ok(())
    }
}

/// The engine's thread: connect, then pass messages both ways until the
/// engine goes.
fn run(
    connect: Connect,
    stderr: ChildStderr,
    commands: Receiver<Request>,
    calls: Receiver<Call>,
    shared: &Mutex<Shared>,
    cell: (u32, u32),
    wiring: Wiring,
) -> io::Result<()> {
    let transport = match connect {
        Connect::Port => Transport::websocket(stderr)?,
        #[cfg(unix)]
        Connect::Pipe(write, read) => Transport::pipe(write, read, stderr),
    };
    let mut session = Session {
        transport,
        next: 0,
        pending: Vec::new(),
        session: None,
        target: None,
        history: Vec::new(),
        current: 0,
        size: (80, 24),
        cell,
        waiting: Vec::new(),
        calls: Vec::new(),
        listeners: wiring.listeners,
        screencast: wiring.screencast,
        on_demand: wiring.on_demand,
        scale: wiring.scale,
    };
    session.send(
        "Browser.setDownloadBehavior",
        download_behavior(&wiring.downloads),
        Pending::Other,
        false,
    )?;
    session.send(
        "Target.createTarget",
        json!({"url": "about:blank"}),
        Pending::CreateTarget,
        false,
    )?;
    let started = Instant::now();
    loop {
        loop {
            match commands.try_recv() {
                Ok(command) => session.apply(command)?,
                Err(mpsc::TryRecvError::Empty) => break,
                // The engine went: close the browser.
                Err(mpsc::TryRecvError::Disconnected) => {
                    let _ = session.send("Browser.close", json!({}), Pending::Other, false);
                    return Ok(());
                }
            }
        }
        while let Ok(call) = calls.try_recv() {
            session.call(call)?;
        }
        if let Some(text) = session.transport.read()? {
            session.message(&text, shared)?;
        }
        if session.session.is_none() && started.elapsed() > START_TIMEOUT {
            return Err(io::Error::new(
                ErrorKind::TimedOut,
                "the browser did not open a page in time",
            ));
        }
    }
}

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

    /// Held by the tests that start a Chrome that is not there: each makes
    /// and removes a profile, which would move another's count of them.
    static STARTS: Mutex<()> = Mutex::new(());

    thread_local! {
        /// The profiles this test thread made: a count of the temporary
        /// directory would also see those of tests that start a real Chrome
        /// alongside.
        pub(super) static MADE: std::cell::RefCell<Vec<PathBuf>> =
            const { std::cell::RefCell::new(Vec::new()) };
    }

    #[test]
    fn a_chrome_that_cannot_start_leaves_no_profile_behind() {
        let _starts = STARTS.lock().unwrap_or_else(|e| e.into_inner());
        MADE.with(|made| made.borrow_mut().clear());
        let mut engine = ChromeEngine::new().binary("/nonexistent/rich-embed-chrome");
        for _ in 0..3 {
            assert!(engine.start().is_err());
        }
        assert!(engine.profile.is_none());
        let made = MADE.with(|made| made.borrow().clone());
        // Each start made a profile, and took it away again.
        assert_eq!(made.len(), 3, "{made:?}");
        let left: Vec<_> = made.iter().filter(|dir| dir.exists()).collect();
        assert!(left.is_empty(), "left behind: {left:?}");
    }

    #[test]
    fn commands_are_devtools_json() {
        let text = command(7, "Page.navigate", json!({"url": "https://a"}), Some("S1"));
        let value: Value = serde_json::from_str(&text).unwrap();
        assert_eq!(
            value,
            json!({"id": 7, "method": "Page.navigate", "params": {"url": "https://a"},
                   "sessionId": "S1"})
        );
        let browser: Value =
            serde_json::from_str(&command(1, "Browser.close", json!({}), None)).unwrap();
        assert!(browser.get("sessionId").is_none());
    }

    #[test]
    fn keys_become_key_events() {
        let events = key_events(Key::char('a'));
        assert_eq!(
            events[0],
            json!({"type": "keyDown", "key": "a", "windowsVirtualKeyCode": 65, "modifiers": 0,
                   "text": "a", "unmodifiedText": "a"})
        );
        assert_eq!(events[1]["type"], "keyUp");
        let enter = key_events(Key::parse("enter").unwrap());
        assert_eq!(enter[0]["text"], "\r");
        let up = key_events(Key::parse("ctrl+up").unwrap());
        assert_eq!(
            up[0],
            json!({"type": "rawKeyDown", "key": "ArrowUp", "windowsVirtualKeyCode": 38,
                   "modifiers": 2})
        );
        // Ctrl with a letter types nothing; Shift+Tab is Tab with Shift.
        assert!(key_events(Key::ctrl('l'))[0].get("text").is_none());
        assert_eq!(
            key_events(Key::parse("shift+tab").unwrap())[0]["modifiers"],
            8
        );
        assert_eq!(
            key_events(Key::parse("f5").unwrap())[0]["windowsVirtualKeyCode"],
            116
        );
    }

    #[test]
    fn the_mouse_lands_in_the_middle_of_its_cell() {
        let press = mouse_event(Mouse::new(MouseKind::Down(Button::Left), 2, 1), (10, 20));
        assert_eq!(
            press,
            json!({"type": "mousePressed", "x": 25.0, "y": 30.0, "button": "left",
                   "clickCount": 1, "modifiers": 0})
        );
        let wheel = mouse_event(Mouse::new(MouseKind::ScrollDown, 0, 0), (10, 20));
        assert_eq!(wheel["type"], "mouseWheel");
        assert_eq!(wheel["deltaY"], 60.0);
        let moved = mouse_event(Mouse::new(MouseKind::Moved, 0, 0), (10, 20));
        assert_eq!(moved["button"], "none");
    }

    #[test]
    fn the_browser_is_launched_sandboxed_in_its_own_profile() {
        let extra = vec!["--no-sandbox".to_string(), "--lang=en".to_string()];
        let args = launch_args(
            Path::new("/tmp/profile"),
            &extra,
            80,
            24,
            (10, 20),
            Wire::DEFAULT,
            false,
        );
        assert!(args.contains(&"--headless=new".to_string()));
        assert!(args.contains(&"--user-data-dir=/tmp/profile".to_string()));
        assert!(args.contains(&"--window-size=800,480".to_string()));
        assert!(args.contains(&"--lang=en".to_string()));
        assert!(!args.iter().any(|arg| arg.contains("no-sandbox")));
        assert_eq!(args.last().unwrap(), "about:blank");
        let engine = ChromeEngine::new().args(["--no-sandbox"]);
        assert!(engine.args.is_empty());
    }

    #[test]
    fn devtools_runs_over_a_pipe_on_unix_and_a_port_elsewhere() {
        let args = launch_args(Path::new("/p"), &[], 80, 24, (10, 20), Wire::DEFAULT, false);
        let pipe = args.iter().any(|arg| arg == "--remote-debugging-pipe");
        let port = args.iter().any(|arg| arg == "--remote-debugging-port=0");
        assert_eq!((pipe, port), (cfg!(unix), !cfg!(unix)), "{args:?}");
        assert_eq!(ChromeEngine::new().wire, Wire::DEFAULT);
    }

    #[test]
    fn a_devtools_switch_of_the_callers_is_dropped() {
        let extra: Vec<String> = [
            "--remote-debugging-port=9222",
            "-Remote-Debugging-Address=0.0.0.0",
            "--remote-debugging-pipe",
            "--lang=en",
            "https://remote-debugging-port.example",
        ]
        .map(String::from)
        .to_vec();
        let args = launch_args(
            Path::new("/p"),
            &extra,
            80,
            24,
            (10, 20),
            Wire::DEFAULT,
            false,
        );
        let devtools: Vec<_> = args
            .iter()
            .filter(|arg| arg.to_ascii_lowercase().starts_with("--remote-debugging"))
            .collect();
        assert_eq!(devtools, [Wire::DEFAULT.switch()]);
        let engine = ChromeEngine::new().args(extra);
        assert_eq!(
            engine.args,
            ["--lang=en", "https://remote-debugging-port.example"]
        );
    }

    /// A page's first frame over `wire`, from the browser `RICH_EMBED_CHROME`
    /// names (skipped without one). Both ways are tried on Linux and macOS,
    /// so the port Windows uses is still exercised where a browser is.
    fn a_frame_arrives_over(wire: Wire) {
        let Some(binary) = std::env::var_os("RICH_EMBED_CHROME") else {
            eprintln!("skipped: set RICH_EMBED_CHROME to a Chrome or Chromium binary to run");
            return;
        };
        let mut engine = ChromeEngine::new().binary(binary);
        engine.wire = wire;
        engine.resize(8, 4).unwrap();
        engine
            .open("data:text/html,<body style='background:%2300ff00'>")
            .unwrap();
        // A green frame at the pane's size: 8 x 4 cells of 10 x 20 pixels.
        let green = |frame: &Option<WebFrame>| match frame {
            Some(WebFrame::Pixels(p)) => {
                let at = (p.width as usize * p.height as usize / 2 + p.width as usize / 2) * 3;
                (p.width, p.height) == (80, 80)
                    && p.rgb
                        .get(at..at + 3)
                        .is_some_and(|c| c[0] < 60 && c[1] > 200 && c[2] < 60)
            }
            _ => false,
        };
        let start = Instant::now();
        let mut frame = None;
        while !green(&frame) && start.elapsed() < Duration::from_secs(60) {
            frame = engine.poll().or(frame);
            thread::sleep(Duration::from_millis(20));
        }
        assert!(
            green(&frame),
            "no green frame over {wire:?}: {:?}",
            engine.state().error
        );
    }

    #[cfg(unix)]
    #[test]
    fn a_frame_arrives_over_the_pipe() {
        a_frame_arrives_over(Wire::Pipe);
    }

    #[test]
    fn a_frame_arrives_over_the_port() {
        a_frame_arrives_over(Wire::Port);
    }

    /// On demand, frames of a page that keeps painting wait to be taken,
    /// and keep coming as they are (each take acknowledges one), with the
    /// scroll position they were painted at.
    #[test]
    fn on_demand_frames_come_as_they_are_taken() {
        let Some(binary) = std::env::var_os("RICH_EMBED_CHROME") else {
            eprintln!("skipped: set RICH_EMBED_CHROME to a Chrome or Chromium binary to run");
            return;
        };
        let mut engine = ChromeEngine::new()
            .binary(binary)
            .screencast_on_demand(true);
        engine.resize(8, 4).unwrap();
        // A page that changes colour every frame, scrolled 40 pixels down.
        engine
            .open(
                "data:text/html,<body style='height:2000px;margin:0'><script>                 scrollTo(0,40);let n=0;(function f(){document.body.style.background=                 'rgb('+(n++%25256)+',0,0)';requestAnimationFrame(f)})()</script>",
            )
            .unwrap();
        let start = Instant::now();
        let mut taken = Vec::new();
        while taken.len() < 4 && start.elapsed() < Duration::from_secs(60) {
            if let Some(frame) = engine.take_screencast() {
                taken.push(frame);
            }
            thread::sleep(Duration::from_millis(30));
        }
        assert_eq!(taken.len(), 4, "{:?}", engine.state().error);
        let last = taken.last().unwrap();
        assert_eq!((last.pixels.width, last.pixels.height), (80, 80));
        assert_eq!(last.meta.scroll_y, 40.0);
    }

    #[test]
    fn on_demand_frames_stay_at_most_one_ahead() {
        let meta = FrameMeta::default();
        let mut waiting = None;
        // The first comes with nothing waiting: acknowledged at once, so
        // Chrome paints the next while it waits.
        assert_eq!(keep_frame(&mut waiting, "a".into(), meta, 1), Some(1));
        // The next comes before the first was taken: it takes its place,
        // and waits unacknowledged (Chrome sends no more meanwhile).
        assert_eq!(keep_frame(&mut waiting, "b".into(), meta, 2), None);
        let (data, _, ack) = waiting.take().unwrap();
        assert_eq!((data.as_str(), ack), ("b", Some(2)));
        // Taken (and acknowledged then): the one after comes to an empty
        // slot, and is acknowledged as it comes.
        assert_eq!(keep_frame(&mut waiting, "c".into(), meta, 3), Some(3));
        assert_eq!(waiting.unwrap().2, None);
    }

    #[test]
    fn a_scaled_screencast_asks_for_fewer_pixels() {
        assert_eq!(scaled((800, 720), 1.0), (800, 720));
        assert_eq!(scaled((800, 720), 0.125), (100, 90));
        assert_eq!(scaled((800, 720), 0.001), (1, 1));
        // A frame at an eighth of the device is cut where a full one is.
        let frame = ScreencastFrame {
            pixels: Pixels::new(100, 90, vec![0; 100 * 90 * 3]).unwrap(),
            meta: FrameMeta {
                page_scale: 1.0,
                device_width: 800.0,
                device_height: 720.0,
                ..FrameMeta::default()
            },
        };
        let cut = frame.crop(80.0, 160.0, 480.0, 270.0).unwrap();
        assert_eq!((cut.width, cut.height), (60, 34));
    }

    #[test]
    fn every_spelling_of_a_sandbox_switch_is_dropped() {
        for arg in [
            "--no-sandbox",
            "-no-sandbox",
            "---no-sandbox",
            "--No-Sandbox",
            "--no-sandbox=1",
            "--disable-setuid-sandbox",
            "--disable-namespace-sandbox",
            "-disable-seccomp-filter-sandbox",
            "--disable-gpu-sandbox",
            "--no-zygote-sandbox",
            "--no-sandbox-and-elevated",
            "--single-process",
            "--no-zygote",
        ] {
            assert!(turns_sandbox_off(arg), "{arg}");
        }
        assert_eq!(turns_sandbox_off("/no-sandbox"), cfg!(windows));
        for arg in [
            "--lang=en",
            "--enable-sandbox",
            "https://no-sandbox.example",
            "--",
        ] {
            assert!(!turns_sandbox_off(arg), "{arg}");
        }
        let extra: Vec<String> = ["-no-sandbox", "--Disable-Setuid-Sandbox", "--lang=en"]
            .map(String::from)
            .to_vec();
        let args = launch_args(
            Path::new("/tmp/profile"),
            &extra,
            80,
            24,
            (10, 20),
            Wire::DEFAULT,
            false,
        );
        assert!(
            !args
                .iter()
                .any(|arg| arg.to_ascii_lowercase().contains("sandbox"))
        );
        let engine = ChromeEngine::new().args(extra);
        assert_eq!(engine.args, ["--lang=en"]);
    }

    #[cfg(unix)]
    #[test]
    fn the_profile_is_this_users_only() {
        use std::os::unix::fs::PermissionsExt;

        let _starts = STARTS.lock().unwrap_or_else(|e| e.into_inner());
        let profile = temporary_profile().unwrap();
        let mode = std::fs::metadata(&profile).unwrap().permissions().mode();
        std::fs::remove_dir(&profile).unwrap();
        assert_eq!(mode & 0o777, 0o700, "{mode:o}");
    }

    #[test]
    fn the_devtools_address_is_read_from_standard_error() {
        assert_eq!(
            devtools_url("DevTools listening on ws://127.0.0.1:41235/devtools/browser/ab-cd"),
            Some("ws://127.0.0.1:41235/devtools/browser/ab-cd".to_string())
        );
        assert_eq!(devtools_url("[1:2:ERROR] something else"), None);
    }

    #[test]
    fn screencast_frames_crop_by_their_scroll_and_scale() {
        // A 4 x 4 frame of a device 8 CSS pixels wide: half scale. Each
        // pixel's red is its index.
        let rgb = (0..16u8).flat_map(|i| [i, 0, 0]).collect();
        let frame = ScreencastFrame {
            pixels: Pixels::new(4, 4, rgb).unwrap(),
            meta: FrameMeta {
                scroll_y: 100.0,
                page_scale: 1.0,
                device_width: 8.0,
                device_height: 8.0,
                ..FrameMeta::default()
            },
        };
        // The document's (2, 102) to (6, 106) is the frame's (1, 1) to (3, 3).
        let part = frame.crop(2.0, 102.0, 4.0, 4.0).unwrap();
        assert_eq!((part.width, part.height), (2, 2));
        assert_eq!(part.rgb, vec![5, 0, 0, 6, 0, 0, 9, 0, 0, 10, 0, 0]);
        // Above the scroll position: out of the frame.
        assert!(frame.crop(0.0, 0.0, 8.0, 50.0).is_none());
        // Partly in: clipped.
        assert_eq!(frame.crop(0.0, 98.0, 8.0, 4.0).unwrap().height, 1);
        let meta = FrameMeta::of(&json!({"scrollOffsetY": 7.5, "pageScaleFactor": 2,
            "deviceWidth": 800, "timestamp": 1.5}));
        assert_eq!(
            (meta.scroll_y, meta.page_scale, meta.timestamp),
            (7.5, 2.0, Some(1.5))
        );
    }

    #[test]
    fn frames_decode_from_base64() {
        assert_eq!(base64_decode("aGk=").unwrap(), b"hi");
        assert_eq!(base64_decode("aGVsbG8gd29ybGQ=").unwrap(), b"hello world");
        assert_eq!(base64_decode("not base64!"), None);
        // A 1 x 1 PNG, red.
        let mut png = Vec::new();
        image::RgbImage::from_pixel(1, 1, image::Rgb([255, 0, 0]))
            .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
            .unwrap();
        let encoded = encode(&png);
        let pixels = decode_frame(&encoded).unwrap();
        assert_eq!(
            (pixels.width, pixels.height, pixels.rgb),
            (1, 1, vec![255, 0, 0])
        );
    }

    /// Base64 for the test above.
    fn encode(bytes: &[u8]) -> String {
        const ALPHABET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
        let mut out = String::new();
        for chunk in bytes.chunks(3) {
            let n = chunk.iter().fold(0u32, |n, &b| n << 8 | b as u32) << (8 * (3 - chunk.len()));
            for i in 0..=chunk.len() {
                out.push(ALPHABET[(n >> (18 - 6 * i) & 63) as usize] as char);
            }
            for _ in chunk.len()..3 {
                out.push('=');
            }
        }
        out
    }

    #[test]
    fn the_browser_is_muted_unless_audio_is_asked_for() {
        let muted = launch_args(Path::new("/p"), &[], 80, 24, (10, 20), Wire::DEFAULT, false);
        assert!(muted.contains(&"--mute-audio".to_string()));
        let loud = launch_args(Path::new("/p"), &[], 80, 24, (10, 20), Wire::DEFAULT, true);
        assert!(!loud.iter().any(|arg| arg.contains("mute")), "{loud:?}");
        assert!(!ChromeEngine::new().audio);
        assert!(ChromeEngine::new().audio(true).audio);
    }

    #[test]
    fn downloads_are_denied_unless_a_quarantine_is_given() {
        assert_eq!(ChromeEngine::new().downloads, Downloads::Deny);
        assert_eq!(
            download_behavior(&Downloads::Deny),
            json!({"behavior": "deny"})
        );
        let kept = download_behavior(&Downloads::Quarantine(PathBuf::from("/q")));
        // Named by the download's id: the page chooses neither name nor place.
        assert_eq!(kept["behavior"], "allowAndName");
        assert_eq!(kept["downloadPath"], "/q");
        assert_eq!(kept["eventsEnabled"], true);
    }

    #[test]
    fn listeners_get_only_the_methods_they_asked_for() {
        let listeners: Listeners = Arc::default();
        let devtools = DevTools {
            calls: mpsc::channel().0,
            listeners: Arc::clone(&listeners),
        };
        let pings = devtools.listen(&["Runtime.bindingCalled"]);
        let gone = devtools.listen(&["Runtime.bindingCalled"]);
        drop(gone);
        deliver(&listeners, "Page.loadEventFired", &json!({}));
        deliver(&listeners, "Runtime.bindingCalled", &json!({"name": "x"}));
        assert_eq!(
            pings.try_recv().unwrap(),
            DevToolsEvent {
                method: "Runtime.bindingCalled".into(),
                params: json!({"name": "x"})
            }
        );
        assert!(pings.try_recv().is_err());
        // The dropped receiver was forgotten.
        assert_eq!(listeners.lock().unwrap().len(), 1);
    }

    #[test]
    fn a_kept_profile_is_made_private_and_never_removed() {
        let _starts = STARTS.lock().unwrap_or_else(|e| e.into_inner());
        let dir = std::env::temp_dir().join(format!("rich-embed-kept-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        let mut engine = ChromeEngine::new()
            .binary("/nonexistent/rich-embed-chrome")
            .profile(&dir);
        assert!(engine.start().is_err());
        drop(engine);
        assert!(dir.is_dir(), "a kept profile stays");
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let mode = std::fs::metadata(&dir).unwrap().permissions().mode();
            assert_eq!(mode & 0o777, 0o700, "{mode:o}");
        }
        std::fs::remove_dir_all(&dir).unwrap();
    }

    /// A download a page starts, from the browser `RICH_EMBED_CHROME`
    /// names (skipped without one): with a quarantine it is announced and
    /// lands there under its id; denied, it never begins.
    fn download_with(downloads: Downloads) -> Option<(DevToolsEvent, DevToolsEvent)> {
        let binary = std::env::var_os("RICH_EMBED_CHROME")?;
        let _starts = STARTS.lock().unwrap_or_else(|e| e.into_inner());
        let mut engine = ChromeEngine::new().binary(binary).downloads(downloads);
        engine.resize(20, 10).unwrap();
        let devtools = engine.devtools().unwrap();
        let begun = devtools.listen(&["Browser.downloadWillBegin", "Browser.downloadProgress"]);
        engine
            .open("data:text/html,<a id=d download=evil.sh href='data:text/plain,hi'>x</a>")
            .unwrap();
        let start = Instant::now();
        while start.elapsed() < Duration::from_secs(30) {
            let clicked = devtools.call(
                "Runtime.evaluate",
                json!({"expression": "document.getElementById('d') && (d.click(), 1)"}),
                Duration::from_secs(10),
            );
            if clicked.is_ok_and(|r| r["result"]["value"] == 1) {
                break;
            }
            thread::sleep(Duration::from_millis(50));
        }
        let first = begun.recv_timeout(Duration::from_secs(5)).ok()?;
        // The engine (and the browser) must outlive the download.
        while let Ok(event) = begun.recv_timeout(Duration::from_secs(10)) {
            if event.params["state"] == "completed" {
                return Some((first, event));
            }
        }
        let unfinished = DevToolsEvent {
            method: String::new(),
            params: json!({}),
        };
        Some((first, unfinished))
    }

    #[test]
    fn a_quarantined_download_is_announced_and_kept_under_its_id() {
        if std::env::var_os("RICH_EMBED_CHROME").is_none() {
            eprintln!("skipped: set RICH_EMBED_CHROME to a Chrome or Chromium binary to run");
            return;
        }
        let dir = std::env::temp_dir().join(format!("rich-embed-q-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        let (event, done) = download_with(Downloads::Quarantine(dir.clone())).expect("no download");
        assert_eq!(event.method, "Browser.downloadWillBegin");
        assert_eq!(event.params["suggestedFilename"], "evil.sh");
        let guid = event.params["guid"].as_str().unwrap();
        assert_eq!(done.params["state"], "completed", "{done:?}");
        assert!(dir.join(guid).is_file(), "not kept under its id");
        assert!(!dir.join("evil.sh").exists());
        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn a_denied_download_never_begins() {
        if std::env::var_os("RICH_EMBED_CHROME").is_none() {
            eprintln!("skipped: set RICH_EMBED_CHROME to a Chrome or Chromium binary to run");
            return;
        }
        assert!(download_with(Downloads::Deny).is_none());
    }

    #[test]
    fn a_missing_browser_is_an_error_not_a_hang() {
        let _starts = STARTS.lock().unwrap_or_else(|e| e.into_inner());
        let mut engine = ChromeEngine::new().binary("/nonexistent/chrome-for-a-test");
        assert!(engine.resize(80, 24).is_err());
    }
}