noctiluca 0.0.2

A terminal web browser: page text as terminal text, media as media
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
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
//! The browser as an intuiTUIve app: the address line, the page (the
//! projection by default, reader mode one key away), the status line, and
//! the action registry's keys, hints, find, F1 overlay and site keys.
//!
//! The tab runs on a thread of its own ([`crate::tab`]); its updates come
//! to the app's thread through a proxy, into signals the nodes read.

use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;
use std::sync::mpsc;
use std::sync::Arc;
use std::time::{Duration, Instant};

use rich_embed::PageState;
use rich_intuituive::interact::keymap::{try_keys, Keymap};
use rich_intuituive::interact::{Key, KeyCode};
use rich_intuituive::prelude::*;
use rich_intuituive::{
    button_of, image_graphics, picture_bytes, picture_of, scroll_virtual_with, slider,
    spawn_stream, Action, ImageView, Picture, Pixels,
};

use crate::actions::{self, keys_label, ACTIONS};
use crate::adapt::{Adapt, RULES};
use crate::bookmarks::{Bookmark, Bookmarks};
use crate::cdp::CELL;
use crate::clean::{markup, truncate};
use crate::config::{remove_site_key, save_site_key, Config, Images, Site, Target, View};
use crate::engine::{Engine, HistoryStep, MediaOp, NodeId, Playback};
use crate::layout::{
    self, hint_labels, matches, scroll_log, to_text, Line, LogScroll, Marks, Piece, Projection,
};
use crate::model::{Binding, MediaKind, Page, Role};
use crate::pictures::{self, Live};
use crate::tab::{Command, Intent, Refusal, Tab, Update};
use crate::video::{Pacing, VideoFrame};
use crate::widgets::{web_widget, WebControl};

/// The video regions on screen and the pacing's intervals, as told to the
/// tab.
type RegionsSent = (Vec<NodeId>, Vec<(NodeId, Duration)>);

/// What happens when an action of the tab's is answered.
type Then = Box<dyn FnOnce(Result<(), Refusal>, &mut Ctx)>;

/// Link hints under way: each label and its control, and what was typed.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Hints {
    pub labels: Vec<(String, usize)>,
    pub typed: String,
}

/// How the app starts.
#[derive(Clone, Debug)]
pub struct Options {
    pub config: Config,
    pub bookmarks: Bookmarks,
    /// The first address; else the config's home page.
    pub url: Option<String>,
    /// The first view; else the config's.
    pub view: Option<View>,
    /// How images show; else the config's.
    pub images: Option<Images>,
}

/// The app's state, all of it in signals so it can be copied into every
/// handler and sent with the tab's updates.
#[derive(Clone, Copy)]
pub struct Browser {
    pub page: Signal<Option<Arc<Page>>>,
    pub state: Signal<PageState>,
    pub view: Signal<View>,
    pub hints: Signal<Option<Hints>>,
    pub find: Signal<Option<String>>,
    pub find_at: Signal<usize>,
    /// The first row in view.
    pub scroll: Signal<u64>,
    /// The current view's rows, laid out once per reading, width, view
    /// and hints: what is drawn, what find searches and what the scroll
    /// keys measure. Not laid out again per key or per draw.
    pub layout: Memo<Rc<Projection>>,
    /// Where find's matches are in [`layout`](Self::layout): (row, nth on
    /// the row).
    pub found: Memo<Rc<Vec<(usize, usize)>>>,
    /// Where Chrome's own scroll is, in CSS pixels, as last sent or read.
    pub chrome_y: Signal<f64>,
    /// The pending send of our scroll to Chrome.
    follow: Signal<Option<Timer>>,
    pub message: Signal<String>,
    pub config: Signal<Config>,
    pub keymap: Signal<Keymap>,
    pub bookmarks: Signal<Bookmarks>,
    pub images: Signal<Images>,
    /// How images show where no site says otherwise.
    pub images_default: Signal<Images>,
    /// The terminal's size in cells.
    pub viewport: Memo<(u16, u16)>,
    /// Each video region's newest frame, as its pacing let it through, and
    /// the protocol the pacing chose: merged into [`live`](Self::live).
    pub videos: Signal<Rc<HashMap<NodeId, Live>>>,
    /// The frames' pacing within the terminal's byte budget.
    pacing: Signal<Rc<RefCell<Pacing>>>,
    /// The regions on screen and the pacing's intervals, as last told to
    /// the tab.
    regions_sent: Signal<RegionsSent>,
    /// The terminal adaptations configured.
    pub adapt: Signal<Adapt>,
    /// Whether the faithful projection is shown: no adaptation at all.
    pub faithful: Signal<bool>,
    /// Where the user has scrolled each live log.
    pub logs: Signal<HashMap<NodeId, LogScroll>>,
    /// The protocol pictures are drawn with, from [`images`](Self::images).
    pub pixels: Memo<Pixels>,
    /// Whether moving pictures are held still (`media.freeze`).
    pub frozen: Signal<bool>,
    /// The frame each moving picture in view shows now, by node: an
    /// animated GIF's, stepped within the byte budget.
    pub live: Signal<Rc<HashMap<NodeId, Live>>>,
    tab: Signal<Tab>,
    waiting: Signal<HashMap<u64, Then>>,
    controls: Signal<HashMap<NodeId, Rc<WebControl>>>,
}

impl Browser {
    fn send(&self, command: Command) -> u64 {
        self.tab.with_untracked(|t| t.send(command))
    }

    /// Run `intent` on the control `binding` names, then `then` with the
    /// answer.
    pub fn act(
        &self,
        binding: Binding,
        intent: Intent,
        then: impl FnOnce(Result<(), Refusal>, &mut Ctx) + 'static,
    ) {
        let id = self.send(Command::Act { binding, intent });
        self.waiting.update(|w| {
            w.insert(id, Box::new(then));
        });
    }

    fn after(&self, id: u64, then: impl FnOnce(Result<(), Refusal>, &mut Ctx) + 'static) {
        self.waiting.update(|w| {
            w.insert(id, Box::new(then));
        });
    }

    /// The widget state of `control`, made once per control.
    pub fn web_control(&self, control: &crate::model::Control) -> Rc<WebControl> {
        let mut found = None;
        self.controls.update(|all| {
            found = Some(
                all.entry(control.node)
                    .or_insert_with(|| Rc::new(WebControl::new(control)))
                    .clone(),
            );
        });
        found.expect("made")
    }

    /// Make every widget follow the page now.
    pub fn refresh_controls(&self) {
        let page = self.page.with_untracked(Clone::clone);
        let Some(page) = page else { return };
        // Out of the signal first: a widget's write can reach it.
        let all: Vec<(NodeId, Rc<WebControl>)> = self
            .controls
            .with_untracked(|all| all.iter().map(|(n, w)| (*n, w.clone())).collect());
        for (node, web) in all {
            if let Some(control) = page.control(node) {
                web.sync(&page, control);
            }
        }
    }

    fn url(&self) -> String {
        self.page
            .with(|p| p.as_ref().map(|p| p.url.clone()))
            .unwrap_or_else(|| self.state.with(|s| crate::clean::clean(&s.url)))
    }

    /// The site table for the page open now.
    fn site(&self) -> Option<Site> {
        let url = self.url();
        self.config.with(|c| c.site(&url).cloned())
    }

    /// The adaptations in effect: none while the faithful projection is
    /// shown.
    pub fn effective_adapt(&self) -> Adapt {
        if self.faithful.get() {
            Adapt::none()
        } else {
            self.adapt.get()
        }
    }

    /// What the views lay out with: hint labels, the adaptations and the
    /// live logs' scroll (find marks are drawn over the layout, not part
    /// of it).
    pub fn hint_marks(&self) -> Marks {
        let hints = self
            .hints
            .with(|h| {
                h.as_ref()
                    .map(|h| h.labels.iter().map(|(l, c)| (*c, l.clone())).collect())
            })
            .unwrap_or_default();
        Marks {
            hints,
            adapt: self.effective_adapt(),
            logs: self.logs.get(),
            ..Marks::default()
        }
    }

    /// What the views mark: hint labels and find.
    pub fn marks(&self) -> Marks {
        let hints = self
            .hints
            .with(|h| {
                h.as_ref()
                    .map(|h| h.labels.iter().map(|(l, c)| (*c, l.clone())).collect())
            })
            .unwrap_or_default();
        Marks {
            hints,
            find: self.find.get(),
            current: None,
            adapt: self.effective_adapt(),
            logs: self.logs.get(),
        }
    }

    fn say(&self, markup: impl Into<String>) {
        self.message.set(markup.into());
    }
}

/// The page's lines in the current view at `width`, as find counts rows:
/// every piece of reader mode in turn (a media region or a control as its
/// rows of nothing), or the projection, with each row's key and place on
/// the page.
fn lay_out(page: &Page, view: View, width: u16, marks: &Marks) -> Projection {
    match view {
        View::Reader => {
            let mut lines = Vec::new();
            for piece in layout::reader(page, width.saturating_sub(2), marks) {
                match piece {
                    Piece::Text(text) => lines.extend(text),
                    other => lines.extend(std::iter::repeat_n(Line::default(), other.rows())),
                }
            }
            // Reader rows stand for the page's height in proportion.
            let rows = lines.len().max(1) as f64;
            let y = (0..lines.len())
                .map(|r| r as f64 / rows * page.height)
                .collect();
            let keys: Vec<u64> = (0..lines.len() as u64).collect();
            let rows = keys.iter().map(|&k| (k, k as usize)).collect();
            Projection {
                lines,
                keys,
                y,
                rows,
                ..Projection::default()
            }
        }
        _ => layout::project(page, width, (CELL.0 as f64, CELL.1 as f64), marks),
    }
}

/// Where find's matches are: (row, nth on the row).
fn find_rows(b: Browser) -> Rc<Vec<(usize, usize)>> {
    b.found.get_untracked()
}

/// Our first row in view as Chrome's scroll: a wheel turn for a move of a
/// few screens, a jump for more, sent once the view rests.
fn follow_scroll(b: Browser, row: u64, cx: &mut Ctx) {
    if let Some(timer) = b.follow.get_untracked() {
        timer.cancel();
    }
    let timer = cx.after(FOLLOW, move |_| {
        b.follow.set(None);
        // The first row is the page's top, whatever its margin.
        let to = match row {
            0 => 0.0,
            _ => b.layout.with_untracked(|l| l.y_of(row as usize)),
        };
        let from = b.chrome_y.get_untracked();
        let screen = b.viewport.get_untracked().1 as f64 * CELL.1 as f64;
        let delta = to - from;
        if delta.abs() < 1.0 {
            return;
        }
        b.chrome_y.set(to);
        if delta.abs() > 3.0 * screen.max(1.0) {
            b.send(Command::Scroll(to));
        } else {
            b.send(Command::Wheel(delta));
        }
    });
    b.follow.set(Some(timer));
}

/// How often moving pictures are looked at: a GIF's frame steps on the
/// first look after its time (and its byte budget) allows.
const MOTION: std::time::Duration = std::time::Duration::from_millis(25);

/// Step the moving pictures in view, and publish their frames when one
/// changed.
fn step_motion(b: Browser, motion: &mut pictures::Motion) {
    // GIFs and videos share one byte budget, from the config and the
    // bandwidth rule.
    let budget = byte_budget(b);
    let videos = b.pacing.with_untracked(|p| {
        let mut pacing = p.borrow_mut();
        pacing.budget = budget;
        pacing.moving()
    });
    motion.share_with(budget, videos);
    let page = b.page.get_untracked();
    let images = b.images.get_untracked();
    let next = match page {
        Some(page) if images != Images::None && b.view.get_untracked() != View::Reader => {
            let height = usize::from(b.viewport.get_untracked().1);
            b.layout.with_untracked(|l| {
                // The first row in view; "the end" is a scroll past it.
                let first = usize::try_from(b.scroll.get_untracked())
                    .unwrap_or(usize::MAX)
                    .min(l.lines.len().saturating_sub(height));
                let rows = first..first.saturating_add(height);
                motion.step(
                    &page,
                    &l.regions,
                    rows,
                    b.pixels.get_untracked(),
                    b.frozen.get_untracked(),
                    std::time::Instant::now(),
                )
            })
        }
        _ => HashMap::new(),
    };
    b.pacing
        .with_untracked(|p| p.borrow_mut().others = motion.moving_count());
    // The videos' frames, which come from the tab, with them.
    let mut next = next;
    b.videos.with_untracked(|v| {
        for (node, live) in v.iter() {
            next.insert(*node, live.clone());
        }
    });
    if b.live.with_untracked(|l| **l != next) {
        b.live.set(Rc::new(next));
    }
}

/// How long the view rests before Chrome's scroll follows it.
const FOLLOW: std::time::Duration = std::time::Duration::from_millis(120);

/// Whether action `id` can run now, or why not. Reads signals, so the
/// overlay that calls it follows them.
pub fn availability(b: Browser, id: &str) -> Result<(), String> {
    let state = b.state.get();
    let has_page = b.page.with(Option::is_some);
    match id {
        "back" if !state.can_go_back => Err("Nothing to go back to.".into()),
        "forward" if !state.can_go_forward => Err("Nothing to go forward to.".into()),
        "open_tab" | "tab.next" | "tab.previous" => {
            Err("One tab for now: tabs come with rs-rich-embed's several pages.".into())
        }
        "hints"
            if !b.page.with(|p| {
                p.as_ref()
                    .is_some_and(|p| p.controls.iter().any(|c| !c.disabled))
            }) =>
        {
            Err("Nothing on this page to follow or use.".into())
        }
        "find.next" | "find.previous"
            if b.find.with(|f| f.as_ref().is_none_or(String::is_empty)) =>
        {
            Err("Find something first.".into())
        }
        "media.play_pause" | "media.mute" | "media.volume_up" | "media.volume_down"
        | "media.seek_back" | "media.seek_forward" => {
            if current_media(b).is_some() {
                Ok(())
            } else if b.page.with(|p| {
                p.as_ref().is_some_and(|p| {
                    p.media
                        .iter()
                        .any(|m| matches!(m.kind, MediaKind::Video | MediaKind::Audio))
                })
            }) {
                Err("The media is not ready yet.".into())
            } else {
                Err("No video or audio on this page.".into())
            }
        }
        "log.older" | "log.newer"
            if b.page
                .with(|p| p.as_ref().is_none_or(|p| p.logs.is_empty())) =>
        {
            Err("No live log on this page.".into())
        }
        "bookmark" | "reload" | "address" | "site.bind" | "site.keys" if !has_page => {
            Err("No page yet.".into())
        }
        "site.bind" | "site.keys" if b.config.with(|c| c.path.is_none()) => {
            Err("No config file to keep site keys in.".into())
        }
        "site.bind" | "site.keys" if crate::url::host(&b.url()).is_none() => {
            Err("This page has no site (a local file): site keys need a host.".into())
        }
        _ => Ok(()),
    }
}

/// Whether a site key's target can run now, or why not.
fn target_availability(b: Browser, target: &Target) -> Result<(), String> {
    match target {
        Target::Action(id) => match actions::get(id) {
            None => Err(format!("{id:?} is not an action.")),
            Some(_) => availability(b, id),
        },
        Target::Element { role, name, nth } => b.page.with(|p| {
            let found = p.as_ref().map_or(0, |p| p.find(role, name).len());
            if found >= *nth {
                Ok(())
            } else if found == 0 {
                Err(format!(
                    "No {role} named {:?} on this page.",
                    truncate(name, 40)
                ))
            } else {
                Err(format!(
                    "Only {found} {role}s named {:?} on this page.",
                    truncate(name, 40)
                ))
            }
        }),
        Target::Sequence(all) => all.iter().try_for_each(|t| target_availability(b, t)),
    }
}

/// Run action `id`, if it is available; else say why.
pub fn run(b: Browser, id: &str, cx: &mut Ctx) {
    if let Err(why) = availability(b, id) {
        cx.toast(format!("[yellow]{}[/]", markup(&why)));
        return;
    }
    let rows = b.viewport.get_untracked().1.saturating_sub(4).max(1) as u64;
    match id {
        "open" => open_prompt(b, String::new(), cx),
        "address" => open_prompt(b, b.url(), cx),
        "hints" => start_hints(b),
        "back" => drop(b.send(Command::History(HistoryStep::Back))),
        "forward" => drop(b.send(Command::History(HistoryStep::Forward))),
        "reload" => drop(b.send(Command::History(HistoryStep::Reload))),
        "media.freeze" => {
            let frozen = !b.frozen.get_untracked();
            b.frozen.set(frozen);
            // Videos too: no frames while frozen.
            send_regions(b);
            b.say(if frozen {
                "[yellow]Moving pictures frozen[/] · F4 resumes"
            } else {
                "Moving pictures resumed"
            });
        }
        "find" => find_prompt(b, cx),
        "find.next" | "find.previous" => {
            let found = find_rows(b);
            if found.is_empty() {
                cx.toast("[yellow]No matches.[/]");
                return;
            }
            let at = b.find_at.get_untracked();
            let next = match (id, at) {
                ("find.next", usize::MAX) => 0,
                ("find.next", at) => (at + 1) % found.len(),
                (_, usize::MAX) => found.len() - 1,
                (_, at) => (at % found.len() + found.len() - 1) % found.len(),
            };
            b.find_at.set(next);
            b.scroll.set((found[next].0 as u64).saturating_sub(3));
            b.say(format!("match {} of {}", next + 1, found.len()));
        }
        // The view keeps the offset within the page.
        "scroll.down" => b.scroll.update(|s| *s = s.saturating_add(1)),
        "scroll.up" => b.scroll.update(|s| *s = s.saturating_sub(1)),
        "page.down" => b.scroll.update(|s| *s = s.saturating_add(rows)),
        "page.up" => b.scroll.update(|s| *s = s.saturating_sub(rows)),
        "top" => b.scroll.set(0),
        "bottom" => b.scroll.set(u64::MAX),
        "reader" => {
            b.view.update(|v| {
                *v = if *v == View::Reader {
                    View::Projection
                } else {
                    View::Reader
                }
            });
            b.scroll.set(0);
            b.say(format!("{} view", b.view.get_untracked().name()));
        }
        "bookmark" => {
            let (url, title) = b.page.with_untracked(|p| {
                p.as_ref()
                    .map(|p| (p.url.clone(), p.title.clone()))
                    .unwrap_or_default()
            });
            let mut result = Ok(());
            b.bookmarks.update(|marks| {
                result = marks.add(Bookmark {
                    url,
                    title: title.clone(),
                    keyword: None,
                });
            });
            match result {
                Ok(()) => cx.toast(format!("Bookmarked {}.", markup(&title))),
                Err(e) => cx.toast(format!("[red]{}[/]", markup(&e.to_string()))),
            }
        }
        "bookmarks" => bookmarks_list(b, cx),
        "adapt" => {
            b.faithful.update(|f| *f = !*f);
            if b.faithful.get_untracked() {
                b.say("[yellow]faithful[/] projection: no terminal adaptations");
            } else {
                let on = b.adapt.get_untracked().active().count();
                b.say(format!("adapted projection: {on} adaptations on"));
            }
        }
        "log.older" | "log.newer" => {
            let Some((node, rows)) = current_log(b) else {
                return;
            };
            let step = (rows / 2).max(1) as isize;
            let by = if id == "log.older" { -step } else { step };
            let next = b.page.with_untracked(|p| {
                let log = p.as_ref()?.logs.iter().find(|l| l.node == node)?;
                let now = b
                    .logs
                    .with_untracked(|l| l.get(&node).copied().unwrap_or_default());
                Some(scroll_log(log, now, by))
            });
            if let Some(next) = next {
                b.logs.update(|l| {
                    if next == LogScroll::Follow {
                        l.remove(&node);
                    } else {
                        l.insert(node, next);
                    }
                });
                b.say(if next == LogScroll::Follow {
                    "live log: following its newest entries".to_string()
                } else {
                    format!(
                        "live log: [yellow]paused[/] · {} to follow again",
                        markup(&keys_label_of(b, "log.newer"))
                    )
                });
            }
        }
        "about" => drop(b.send(Command::Open(crate::about::ADDRESS.into()))),
        "media.play_pause" | "media.mute" | "media.volume_up" | "media.volume_down"
        | "media.seek_back" | "media.seek_forward" => {
            let Some((node, playback)) = current_media(b) else {
                return;
            };
            let op = match id {
                "media.play_pause" if playback.paused => MediaOp::Play,
                "media.play_pause" => MediaOp::Pause,
                "media.mute" => MediaOp::Mute(!playback.muted),
                // Ten points at a time, kept in 0 to 100%; a muted element
                // stays muted.
                "media.volume_up" => MediaOp::Volume((playback.volume + 0.1).min(1.0)),
                "media.seek_back" => MediaOp::Seek(-SEEK),
                "media.seek_forward" => MediaOp::Seek(SEEK),
                _ => MediaOp::Volume((playback.volume - 0.1).max(0.0)),
            };
            media_op(b, node, op);
        }
        "site.bind" => bind_picker(b, cx),
        "site.keys" => site_keys_list(b, cx),
        "actions" => overlay(b, cx),
        "quit" => cx.quit(),
        _ => {}
    }
}

fn keys_label_of(b: Browser, id: &str) -> String {
    b.keymap.with_untracked(|k| keys_label(k, id))
}

/// The live log the log keys scroll, and its rows: the first in view in
/// the projection, else the page's first.
pub fn current_log(b: Browser) -> Option<(NodeId, usize)> {
    let first = b
        .page
        .with_untracked(|p| p.as_ref()?.logs.first().map(|l| (l.node, 10)));
    if b.view.get_untracked() == View::Reader {
        return first;
    }
    let top = b.scroll.get_untracked().min(usize::MAX as u64) as usize;
    let height = b.viewport.get_untracked().1 as usize;
    b.layout
        .with_untracked(|l| {
            let top = top.min(l.lines.len().saturating_sub(1));
            l.logs
                .iter()
                .find(|(_, row, rows)| *row < top + height && top < row + rows)
                .map(|(node, _, rows)| (*node, *rows))
        })
        .or(first)
}

/// The about page (`about:noctiluca`): the version, the browser, every
/// terminal adaptation, on or off, and what the browser can play, as its
/// `canPlayType` `answers` to [`crate::about::CODECS`] say.
fn about(b: Browser, answers: Vec<String>, product: String, cx: &mut Ctx) {
    cx.modal(Size::Percent(90), Size::Percent(90), move || {
        let answers = answers.clone();
        let product = product.clone();
        let body = text(move || {
            let configured = b.adapt.get();
            let faithful = b.faithful.get();
            let mut lines = vec![
                format!("[bold]Noctiluca[/] {}", env!("CARGO_PKG_VERSION")),
                format!("Browser: {}", markup(&product)),
                String::new(),
                if faithful {
                    "[bold]Terminal adaptations[/]: [yellow]off, the faithful projection[/]".into()
                } else {
                    "[bold]Terminal adaptations[/] (active rules):".into()
                },
            ];
            for rule in RULES {
                let on = configured.on(rule.rule) && !faithful;
                lines.push(format!(
                    " {} {:<20} [dim]{}[/]",
                    if on { "[green]on [/]" } else { "[dim]off[/]" },
                    rule.name,
                    markup(rule.what)
                ));
            }
            lines.push(String::new());
            lines.push(
                "[bold]Codecs[/]: what this browser says it can play (canPlayType). DRM playback is never tried."
                    .into(),
            );
            for ((name, kind), answer) in crate::about::CODECS.iter().zip(&answers) {
                lines.push(format!(
                    " {:<14} {:<15} [dim]{}[/]",
                    name,
                    crate::about::verdict(answer),
                    markup(kind)
                ));
            }
            lines.push(String::new());
            lines.push(format!(
                "[dim]{} toggles adapted and faithful · \\[adapt] in the config or --adapt=-RULE switch one off · Esc closes[/]",
                markup(&keys_label_of(b, "adapt"))
            ));
            lines.join("\n")
        });
        scroll_with(body, signal(0u16))
            .focusable()
            .autofocus()
            .on_key("esc q", |cx| cx.pop())
            .panel(crate::about::TITLE)
    });
}

/// The video or audio the media actions work on: the one playing, else
/// the first that is ready.
pub fn current_media(b: Browser) -> Option<(NodeId, Playback)> {
    b.page.with(|p| {
        let page = p.as_ref()?;
        let ready = || {
            page.media
                .iter()
                .filter_map(|m| Some((m.node, m.playback?)))
        };
        ready().find(|(_, p)| !p.paused).or_else(|| ready().next())
    })
}

/// Do `op` to the media `node` of the page now.
fn media_op(b: Browser, node: NodeId, op: MediaOp) {
    let Some(document) = b.page.with_untracked(|p| p.as_ref().map(|p| p.document)) else {
        return;
    };
    let id = b.send(Command::Media { document, node, op });
    b.after(id, |result, cx| {
        if let Err(refusal) = result {
            cx.toast(format!("[red]{}[/]", markup(&refusal.to_string())));
        }
    });
}

use crate::bars::clock;

/// How far the seek keys move the media, in seconds: the PoC's step.
const SEEK: f64 = 5.0;

/// A video's frame from the tab: offered to its pacing, and drawn when due.
fn video_frame(b: Browser, frame: &VideoFrame) {
    let Some(rect) = b.page.with_untracked(|p| {
        p.as_ref()?
            .media
            .iter()
            .find(|m| m.node == frame.node)
            .map(|m| m.rect)
    }) else {
        return;
    };
    let cols = ((rect.width / CELL.0 as f64).ceil() as usize).clamp(1, 400);
    let rows = ((rect.height / CELL.1 as f64).ceil() as usize).clamp(1, 200);
    let (picture, pixels) = b.pacing.with_untracked(|p| {
        let mut pacing = p.borrow_mut();
        let picture = pacing.offer(frame, cols, rows, Instant::now(), picture_bytes);
        (picture, pacing.pixels(frame.node))
    });
    if let Some(picture) = picture {
        let live = Live { picture, pixels };
        let mut videos = (*b.videos.get_untracked()).clone();
        videos.insert(frame.node, live.clone());
        b.videos.set(Rc::new(videos));
        // Shown at once, with the moving GIFs.
        let mut shown = (*b.live.get_untracked()).clone();
        shown.insert(frame.node, live);
        b.live.set(Rc::new(shown));
    }
    send_regions(b);
}

/// The video regions the view shows: those whose box meets the page's
/// rows in view.
fn regions_on_screen(b: Browser) -> Vec<NodeId> {
    let rows = b.viewport.get().1 as usize;
    let first = b.scroll.get() as usize;
    let (top, bottom) = b.layout.with(|l| {
        let top = if first == 0 { 0.0 } else { l.y_of(first) };
        let bottom = if first.saturating_add(rows) >= l.lines.len() {
            f64::MAX
        } else {
            l.y_of(first + rows)
        };
        (top, bottom)
    });
    b.page.with(|p| {
        p.as_ref()
            .map(|p| {
                p.media
                    .iter()
                    .filter(|m| m.kind == MediaKind::Video)
                    .filter(|m| m.rect.bottom() > top && m.rect.y < bottom)
                    .map(|m| m.node)
                    .collect()
            })
            .unwrap_or_default()
    })
}

/// Tell the tab which video regions are on screen and how often each may
/// have a frame, when that changed.
fn send_regions(b: Browser) {
    // Frozen, no region gets frames: the screencast stops.
    let on_screen = if b.frozen.get_untracked() {
        Vec::new()
    } else {
        regions_on_screen(b)
    };
    let intervals: Vec<(NodeId, Duration)> = b.pacing.with_untracked(|p| {
        p.borrow()
            .intervals()
            .into_iter()
            // In steps of 25 ms, so a small change in the estimate does
            // not send again.
            .map(|(node, d)| (node, Duration::from_millis(d.as_millis() as u64 / 25 * 25)))
            .collect()
    });
    let next = (on_screen, intervals);
    if b.regions_sent.with_untracked(|sent| *sent != next) {
        b.regions_sent.set(next.clone());
        b.send(Command::Regions {
            on_screen: next.0,
            intervals: next.1,
        });
    }
}

/// A video's region in reader mode: its newest frame while it has played,
/// else its poster, in the protocol its pacing chose; with the play mark
/// under it while it is not playing.
fn video_region(b: Browser, node: NodeId) -> Node {
    let picture = switch(
        move || shown_picture(b, node).map_or(b.pixels.get(), |(_, pixels)| pixels),
        move |pixels| {
            picture_of(
                move || shown_picture(b, node).map(|(p, _)| p),
                ImageView::new().pixels(pixels),
            )
        },
    )
    .flex(1);
    let mark = text(move || {
        let playing = b.page.with(|p| {
            p.as_ref()
                .and_then(|p| p.media.iter().find(|m| m.node == node)?.playback)
                .is_some_and(|p| p.playing())
        });
        if playing {
            String::new()
        } else {
            "[bold black on white] â–¶ [/]".into()
        }
    })
    .no_wrap()
    .fixed(1);
    column([picture, mark])
}

/// A video's or an audio's controls, from the element's real state:
/// Play/Pause and Mute/Unmute with live labels (C1), a volume slider, and
/// its time. Sound plays on the machine Chrome runs on.
fn player(b: Browser, node: NodeId) -> Node {
    let playback = move || {
        b.page
            .with(|p| p.as_ref()?.media.iter().find(|m| m.node == node)?.playback)
    };
    let volume = signal(
        b.page
            .with_untracked(|p| p.as_ref()?.media.iter().find(|m| m.node == node)?.playback)
            .map_or(100.0, |p| (p.volume * 100.0).round()),
    );
    // The slider follows the element, and moving it sets the element.
    watch(
        move || playback().map(|p| (p.volume * 100.0).round() as i64),
        move |v, _| {
            if let Some(v) = v {
                if volume.get_untracked() != v as f64 {
                    volume.set(v as f64);
                }
            }
        },
    );
    on_write(volume, move |v, _| {
        let now = b
            .page
            .with_untracked(|p| p.as_ref()?.media.iter().find(|m| m.node == node)?.playback);
        if now.is_some_and(|p| ((p.volume * 100.0).round() - v).abs() >= 1.0) {
            media_op(b, node, MediaOp::Volume(v / 100.0));
        }
    });
    let play = button_of(
        move || {
            if playback().is_some_and(|p| !p.paused) {
                "Pause".into()
            } else {
                "Play".into()
            }
        },
        move |_| {
            if let Some(p) = playback() {
                media_op(
                    b,
                    node,
                    if p.paused {
                        MediaOp::Play
                    } else {
                        MediaOp::Pause
                    },
                );
            }
        },
    )
    .disabled_when(move || playback().is_none())
    .auto();
    let mute = button_of(
        move || {
            if playback().is_some_and(|p| p.muted) {
                "Unmute".into()
            } else {
                "Mute".into()
            }
        },
        move |_| {
            if let Some(p) = playback() {
                media_op(b, node, MediaOp::Mute(!p.muted));
            }
        },
    )
    .disabled_when(move || playback().is_none())
    .auto();
    let status = text(move || {
        let sound = if b.config.with(|c| c.audio) {
            ""
        } else {
            "  [dim]sound is off: start with --audio[/]"
        };
        match playback() {
            None => format!("[dim]not ready[/]{sound}"),
            Some(p) => format!(
                " {} / {}{}{sound}",
                clock(p.time),
                p.duration.map_or("live".into(), clock),
                if p.muted { " [yellow]muted[/]" } else { "" }
            ),
        }
    })
    .auto();
    row([
        play,
        label(" ").fixed(1),
        mute,
        label(" Volume ").auto(),
        slider(volume, 0.0..=100.0, 10.0).fixed(16),
        status,
        label("").flex(1),
    ])
    .fixed(1)
    .name(&format!("player-{node}"))
}

/// Run a site key's target.
fn run_target(b: Browser, target: &Target, cx: &mut Ctx) {
    if let Err(why) = target_availability(b, target) {
        cx.toast(format!("[yellow]{}[/]", markup(&why)));
        return;
    }
    match target {
        Target::Action(id) => run(b, id, cx),
        Target::Element { role, name, nth } => {
            let id = b.send(Command::Activate {
                role: role.clone(),
                name: name.clone(),
                nth: nth.saturating_sub(1),
            });
            b.after(id, |result, cx| {
                if let Err(refusal) = result {
                    cx.toast(format!("[red]{}[/]", markup(&refusal.to_string())));
                }
            });
        }
        Target::Sequence(all) => {
            for t in all {
                run_target(b, t, cx);
            }
        }
    }
}

fn start_hints(b: Browser) {
    let hintable: Vec<usize> = b.page.with_untracked(|p| {
        p.as_ref()
            .map(|p| {
                p.controls
                    .iter()
                    .enumerate()
                    .filter(|(_, c)| !c.disabled)
                    .map(|(i, _)| i)
                    .collect()
            })
            .unwrap_or_default()
    });
    let labels = hint_labels(hintable.len())
        .into_iter()
        .zip(hintable)
        .collect();
    b.hints.set(Some(Hints {
        labels,
        typed: String::new(),
    }));
}

/// Use control `index` of the page: click what clicks, and give the
/// others their widget (focused in reader mode, in a box in the
/// projection).
fn activate(b: Browser, index: usize, cx: &mut Ctx) {
    let page = b.page.with_untracked(Clone::clone);
    let Some(page) = page else { return };
    let Some(control) = page.controls.get(index).cloned() else {
        return;
    };
    let clicks = matches!(
        control.role,
        Role::Link
            | Role::Button
            | Role::CheckBox
            | Role::Switch
            | Role::Radio
            | Role::Tab
            | Role::MenuItem
    );
    if clicks {
        b.act(control.binding(&page), Intent::Click, |result, cx| {
            if let Err(refusal) = result {
                cx.toast(format!("[red]{}[/]", markup(&refusal.to_string())));
            }
        });
        return;
    }
    if b.view.get_untracked() == View::Reader {
        if let Some(id) = b.web_control(&control).widget.get() {
            cx.focus(id);
            return;
        }
    }
    let node = control.node;
    let title = markup(&crate::tab::describe(&control));
    cx.modal(Size::Percent(70), Size::Fixed(3 + 2), move || {
        web_widget(b, vec![node])
            .on_key("esc", |cx| cx.pop())
            .panel(&title)
    });
}

/// A key while hints are under way: whether it was used.
fn hint_key(b: Browser, key: Key, cx: &mut Ctx) -> bool {
    let Some(mut hints) = b.hints.get_untracked() else {
        return false;
    };
    match key.code {
        KeyCode::Escape => {
            b.hints.set(None);
        }
        KeyCode::Backspace => {
            hints.typed.pop();
            b.hints.set(Some(hints));
        }
        KeyCode::Char(c) if !key.modifiers.ctrl && !key.modifiers.alt => {
            hints.typed.push(c);
            if let Some((_, index)) = hints.labels.iter().find(|(l, _)| *l == hints.typed) {
                let index = *index;
                b.hints.set(None);
                activate(b, index, cx);
            } else if hints
                .labels
                .iter()
                .any(|(l, _)| l.starts_with(&hints.typed))
            {
                b.hints.set(Some(hints));
            } else {
                b.hints.set(None);
                cx.toast(format!("[yellow]No hint {}.[/]", markup(&hints.typed)));
            }
        }
        _ => return false,
    }
    true
}

/// The site key `key` runs on the page open now.
fn site_key(b: Browser, key: Key) -> Option<Target> {
    let site = b.site()?;
    site.keys
        .iter()
        .find(|k| try_keys(&k.keys).is_ok_and(|keys| keys == [key]))
        .map(|k| k.target.clone())
}

/// A text box in a box: Enter gives its text to `submit`.
fn prompt(title: &str, initial: String, cx: &mut Ctx, submit: impl Fn(String, &mut Ctx) + 'static) {
    let title = title.to_string();
    let text = signal(initial);
    cx.modal(Size::Percent(80), Size::Fixed(3), move || {
        input(text)
            .on_submit(move |value, cx| {
                let value = value.to_string();
                cx.pop();
                submit(value, cx);
            })
            .on_key("esc", |cx| cx.pop())
            .autofocus()
            .panel(&title)
    });
}

fn open_prompt(b: Browser, initial: String, cx: &mut Ctx) {
    prompt(
        "Open: an address, a keyword, or words to search",
        initial,
        cx,
        move |typed, _| {
            let url = b.url();
            let destination = b.config.with_untracked(|c| {
                b.bookmarks
                    .with_untracked(|m| c.destination(&typed, &url, &m.items))
            });
            b.send(Command::Open(destination.url().to_string()));
            b.say(format!("opening {}", markup(destination.url())));
        },
    );
}

fn find_prompt(b: Browser, cx: &mut Ctx) {
    let initial = b.find.get_untracked().unwrap_or_default();
    prompt("Find in page", initial, cx, move |query, cx| {
        b.find.set((!query.is_empty()).then_some(query));
        b.find_at.set(usize::MAX);
        if b.find.get_untracked().is_some() {
            run(b, "find.next", cx);
        }
    });
}

/// One row of a `chooser`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Entry {
    /// Console markup.
    pub text: String,
    /// Why it cannot be chosen now, if it cannot.
    pub unavailable: Option<String>,
}

type Choose = Rc<dyn Fn(usize, &mut Ctx)>;

/// A live list in a box: `items` is read again whenever a signal it reads
/// changes, so it follows the page while open; the selection is kept by
/// position. ↑/↓ (or k/j) move, Esc closes, and each of `keys` runs on
/// the selected row.
fn chooser(
    title: &str,
    hint: &str,
    items: Rc<dyn Fn() -> Vec<Entry>>,
    keys: Vec<(&'static str, Choose)>,
    cx: &mut Ctx,
) {
    let title = title.to_string();
    let hint = hint.to_string();
    cx.modal(Size::Percent(90), Size::Percent(85), move || {
        let selected = signal(0usize);
        let shown = items.clone();
        // The rows the box has for the list: it shows a window of them
        // that keeps the selection in view.
        let room = (viewport().get_untracked().1 as usize * 85 / 100)
            .saturating_sub(4)
            .max(3);
        let list = text(move || {
            let all = shown();
            let at = selected.get().min(all.len().saturating_sub(1));
            let first = at.saturating_sub(room.saturating_sub(2));
            let mut out = Vec::new();
            for (i, entry) in all.iter().enumerate().skip(first).take(room) {
                let mark = if i == at { "[reverse]â–¸" } else { " " };
                let end = if i == at { "[/]" } else { "" };
                let body = match &entry.unavailable {
                    None => entry.text.clone(),
                    Some(why) => format!("[dim]{}  — {}[/]", entry.text, markup(why)),
                };
                out.push(format!("{mark} {body}{end}"));
            }
            if out.is_empty() {
                out.push("[dim]Nothing here yet.[/]".into());
            }
            out.join("\n")
        })
        .live();
        let count = items.clone();
        let mut node = column([list.flex(1), label(format!("[dim]{}[/]", hint)).fixed(1)])
            .focusable()
            .autofocus()
            .on_key("up k", move |_| {
                selected.update(|s| *s = s.saturating_sub(1))
            })
            .on_key("down j", move |_| {
                let n = count().len();
                selected.update(|s| *s = (*s + 1).min(n.saturating_sub(1)))
            })
            .on_key("esc", |cx| cx.pop());
        for (keys, choose) in keys.clone() {
            node = node.on_key(keys, move |cx| choose(selected.get_untracked(), cx));
        }
        node.panel(&title)
    });
}

/// The F1 overlay's rows: this site's keys first, marked as the site's,
/// then every action of the registry, each with its keys and, when it
/// cannot run now, why. It reads signals, so the overlay (intuiTUIve's
/// live `action_overlay`, C4) follows the page while open.
pub fn overlay_actions(b: Browser) -> Vec<Action> {
    let keymap = b.keymap.get();
    let mut out = Vec::new();
    if let Some(site) = b.site() {
        for (n, key) in site.keys.iter().enumerate() {
            out.push(Action {
                id: format!("site:{n}"),
                label: format!("{} [site {}]", key.target.describe(), site.pattern),
                keys: try_keys(&key.keys).unwrap_or_default(),
                unavailable: target_availability(b, &key.target).err(),
            });
        }
    }
    for action in ACTIONS {
        let keys = keymap
            .bindings()
            .into_iter()
            .find(|binding| binding.action == action.id)
            .map(|binding| binding.keys)
            .unwrap_or_default();
        // The media actions say what they would do now.
        let label = match (action.id, current_media(b)) {
            ("media.play_pause", Some((_, p))) if p.paused => "Play the media",
            ("media.play_pause", Some(_)) => "Pause the media",
            ("media.mute", Some((_, p))) if p.muted => "Unmute the media",
            ("media.mute", Some(_)) => "Mute the media",
            _ => action.label,
        };
        out.push(Action {
            id: action.id.to_string(),
            label: label.to_string(),
            keys,
            unavailable: availability(b, action.id).err(),
        });
    }
    out
}

fn overlay(b: Browser, cx: &mut Ctx) {
    cx.action_palette(
        move || overlay_actions(b),
        move |id, cx| match id
            .strip_prefix("site:")
            .and_then(|n| n.parse::<usize>().ok())
        {
            Some(n) => {
                if let Some(target) = b
                    .site()
                    .and_then(|s| s.keys.get(n).map(|k| k.target.clone()))
                {
                    run_target(b, &target, cx);
                }
            }
            None => run(b, id, cx),
        },
    );
}

/// Choose what to bind a key to on this site: an action, or an element
/// of the page by its role and name.
fn bind_picker(b: Browser, cx: &mut Ctx) {
    let targets = move || -> Vec<(Entry, Target, Option<String>)> {
        let mut out = Vec::new();
        b.page.with(|p| {
            if let Some(page) = p {
                for (i, c) in page.controls.iter().enumerate() {
                    if c.name.is_empty() {
                        continue;
                    }
                    let same = page.find(c.role.name(), &c.name);
                    let nth = same
                        .iter()
                        .position(|o| std::ptr::eq(*o, &page.controls[i]))
                        .unwrap_or(0)
                        + 1;
                    let note = (same.len() > 1).then(|| {
                        format!(
                            "{} elements are named {:?}; this binds match {nth}.",
                            same.len(),
                            truncate(&c.name, 40)
                        )
                    });
                    out.push((
                        Entry {
                            text: format!("{} {}", c.role.name(), markup(&format!("{:?}", c.name))),
                            unavailable: None,
                        },
                        Target::Element {
                            role: c.role.name().to_string(),
                            name: c.name.clone(),
                            nth,
                        },
                        note,
                    ));
                }
            }
        });
        for action in ACTIONS {
            out.push((
                Entry {
                    text: format!("action {}  [dim]{}[/]", action.id, markup(action.label)),
                    unavailable: None,
                },
                Target::Action(action.id.to_string()),
                None,
            ));
        }
        out
    };
    let items: Rc<dyn Fn() -> Vec<Entry>> =
        Rc::new(move || targets().into_iter().map(|(e, _, _)| e).collect());
    let choose: Choose = Rc::new(move |i, cx| {
        let Some((_, target, note)) = targets().into_iter().nth(i) else {
            return;
        };
        cx.pop();
        capture_key(b, target, note, cx);
    });
    chooser(
        "Bind a key on this site: to what?",
        "Enter chooses · Esc closes",
        items,
        vec![("enter", choose)],
        cx,
    );
}

/// Wait for the key to bind `target` to, then ask to confirm it, saying
/// what it does now, and where it applies.
fn capture_key(b: Browser, target: Target, note: Option<String>, cx: &mut Ctx) {
    let Some(host) = crate::url::host(&b.url()) else {
        return;
    };
    let key: Signal<Option<Key>> = signal(None);
    let describe = target.describe();
    cx.modal(Size::Percent(80), Size::Fixed(8), move || {
        let host2 = host.clone();
        let target2 = target.clone();
        let prompt = text(move || {
            let mut lines = vec![format!(
                "Bind a key to [bold]{}[/] on [bold]{}[/].",
                markup(&describe),
                markup(&host2)
            )];
            if let Some(note) = &note {
                lines.push(format!("[yellow]{}[/]", markup(note)));
            }
            match key.get() {
                None => lines.push("Press the key. (Esc cancels.)".into()),
                Some(k) => {
                    if let Some(now) = conflict(b, k) {
                        lines.push(format!(
                            "[yellow]{} already does {} here: Enter replaces it.[/]",
                            markup(&k.to_string()),
                            markup(&now)
                        ));
                    }
                    lines.push(format!(
                        "{}: Enter binds it on {} · w on *.{} · Esc cancels",
                        markup(&k.to_string()),
                        markup(&host2),
                        markup(&host2)
                    ));
                }
            }
            lines.join("\n")
        });
        let host3 = host.clone();
        prompt
            .focusable()
            .autofocus()
            .on_any_key(move |cx, pressed| {
                match (key.get_untracked(), pressed.code) {
                    (_, KeyCode::Escape) => cx.pop(),
                    (None, _) => key.set(Some(pressed)),
                    (Some(k), KeyCode::Enter) => save_binding(b, &host3, k, &target2, cx),
                    (Some(k), KeyCode::Char('w')) => {
                        save_binding(b, &format!("*.{host3}"), k, &target2, cx)
                    }
                    _ => {}
                }
                true
            })
            .panel("Bind a key on this site")
    });
}

/// What `key` does on this page now, if anything: a site key or an action.
fn conflict(b: Browser, key: Key) -> Option<String> {
    if let Some(target) = site_key(b, key) {
        return Some(target.describe());
    }
    b.keymap.with_untracked(|k| actions::action_for(k, key))
}

fn save_binding(b: Browser, pattern: &str, key: Key, target: &Target, cx: &mut Ctx) {
    cx.pop();
    let Some(path) = b.config.with_untracked(|c| c.path.clone()) else {
        return;
    };
    match save_site_key(&path, pattern, &key.to_string(), target) {
        Ok(_) => {
            reload_config(b);
            cx.toast(format!(
                "{} now does {} on {}.",
                markup(&key.to_string()),
                markup(&target.describe()),
                markup(pattern)
            ));
        }
        Err(e) => cx.toast(format!("[red]{}[/]", markup(&e.to_string()))),
    }
}

/// Read the config file again (after an edit of ours).
fn reload_config(b: Browser) {
    let path = b.config.with_untracked(|c| c.path.clone());
    if let Ok(config) = Config::load(path.as_deref()) {
        b.config.set(config);
    }
}

/// This site's keys: Enter tests one, d removes it, e binds it to another
/// key, s moves it between this host and `*.host`.
fn site_keys_list(b: Browser, cx: &mut Ctx) {
    let rows = move || -> Vec<(String, String, Target)> {
        b.site()
            .map(|s| {
                s.keys
                    .iter()
                    .map(|k| (s.pattern.clone(), k.keys.clone(), k.target.clone()))
                    .collect()
            })
            .unwrap_or_default()
    };
    let items: Rc<dyn Fn() -> Vec<Entry>> = Rc::new(move || {
        rows()
            .into_iter()
            .map(|(pattern, keys, target)| Entry {
                text: format!(
                    "{:>10}  {}  [cyan]\\[{}][/]",
                    markup(&keys),
                    markup(&target.describe()),
                    markup(&pattern)
                ),
                unavailable: target_availability(b, &target).err(),
            })
            .collect()
    });
    let test: Choose = Rc::new(move |i, cx| {
        if let Some((_, _, target)) = rows().into_iter().nth(i) {
            cx.pop();
            run_target(b, &target, cx);
        }
    });
    let path = move || b.config.with_untracked(|c| c.path.clone());
    let remove: Choose = Rc::new(move |i, cx| {
        let (Some((pattern, keys, _)), Some(path)) = (rows().into_iter().nth(i), path()) else {
            return;
        };
        match remove_site_key(&path, &pattern, &keys) {
            Ok(_) => {
                reload_config(b);
                cx.toast(format!(
                    "Removed {} from {}.",
                    markup(&keys),
                    markup(&pattern)
                ));
            }
            Err(e) => cx.toast(format!("[red]{}[/]", markup(&e.to_string()))),
        }
    });
    let edit: Choose = Rc::new(move |i, cx| {
        let (Some((pattern, keys, target)), Some(path)) = (rows().into_iter().nth(i), path())
        else {
            return;
        };
        let _ = remove_site_key(&path, &pattern, &keys);
        reload_config(b);
        cx.pop();
        capture_key(b, target, None, cx);
    });
    let scope: Choose = Rc::new(move |i, cx| {
        let (Some((pattern, keys, target)), Some(path)) = (rows().into_iter().nth(i), path())
        else {
            return;
        };
        let other = match pattern.strip_prefix("*.") {
            Some(host) => host.to_string(),
            None => format!("*.{pattern}"),
        };
        let moved = save_site_key(&path, &other, &keys, &target)
            .and_then(|_| remove_site_key(&path, &pattern, &keys));
        reload_config(b);
        match moved {
            Ok(_) => cx.toast(format!(
                "{} now applies on {}.",
                markup(&keys),
                markup(&other)
            )),
            Err(e) => cx.toast(format!("[red]{}[/]", markup(&e.to_string()))),
        }
    });
    chooser(
        "Site shortcuts",
        "Enter tests · d removes · e binds another key · s: this host or *.host · Esc closes",
        items,
        vec![("enter", test), ("d", remove), ("e", edit), ("s", scope)],
        cx,
    );
}

fn bookmarks_list(b: Browser, cx: &mut Ctx) {
    let items: Rc<dyn Fn() -> Vec<Entry>> = Rc::new(move || {
        b.bookmarks.with(|m| {
            m.items
                .iter()
                .map(|bm| Entry {
                    text: format!(
                        "{}  [dim]{}[/]{}",
                        markup(&bm.title),
                        markup(&bm.url),
                        bm.keyword
                            .as_ref()
                            .map(|k| format!("  [cyan]{}[/]", markup(k)))
                            .unwrap_or_default()
                    ),
                    unavailable: None,
                })
                .collect()
        })
    });
    let open: Choose = Rc::new(move |i, cx| {
        if let Some(url) = b
            .bookmarks
            .with_untracked(|m| m.items.get(i).map(|bm| bm.url.clone()))
        {
            cx.pop();
            b.send(Command::Open(url));
        }
    });
    let remove: Choose = Rc::new(move |i, _| {
        if let Some(url) = b
            .bookmarks
            .with_untracked(|m| m.items.get(i).map(|bm| bm.url.clone()))
        {
            b.bookmarks.update(|m| {
                let _ = m.remove(&url);
            });
        }
    });
    chooser(
        "Bookmarks",
        "Enter opens · d removes · Esc closes",
        items,
        vec![("enter", open), ("d", remove)],
        cx,
    );
}

/// A new document's site settings: its view, whether images show, and the
/// width Chrome lays it out at. (`audio` and `fps` are read, and wait for
/// the media phase: sound is a switch of the browser's launch.)
fn apply_site(b: Browser, url: &str) {
    let site = b.config.with_untracked(|c| c.site(url).cloned());
    let base = b.images_default.get_untracked();
    let images = match site.as_ref().and_then(|s| s.images) {
        Some(false) => Images::None,
        _ => base,
    };
    if b.images.get_untracked() != images {
        b.images.set(images);
    }
    if let Some(view) = site
        .as_ref()
        .and_then(|s| s.view)
        .filter(|v| *v != View::Raster)
    {
        b.view.set(view);
    }
    let (columns, rows) = b.viewport.get_untracked();
    let width = site.as_ref().and_then(|s| s.width).unwrap_or(columns);
    b.send(Command::Resize(width, rows.saturating_sub(CHROME_ROWS)));
}

/// Apply one of the tab's updates, on the app's thread.
fn apply(b: Browser, update: Update, cx: &mut Ctx) {
    match update {
        Update::Page(page) => {
            let new_document =
                b.page.with_untracked(|p| p.as_ref().map(|p| p.document)) != Some(page.document);
            if new_document {
                b.controls.update(HashMap::clear);
                b.videos.set(Rc::new(HashMap::new()));
                b.pacing.with_untracked(|p| p.borrow_mut().clear());
                b.logs.update(HashMap::clear);
                b.scroll.set(0);
                b.hints.set(None);
                b.find_at.set(usize::MAX);
            }
            let url = page.url.clone();
            // A site whose config says `audio = false` keeps its media
            // muted (sound is a switch of the browser's launch, so a site
            // cannot turn it on for one run that started without it).
            if b.config
                .with_untracked(|c| c.site(&url).is_some_and(|s| s.audio == Some(false)))
            {
                for media in &page.media {
                    if media.playback.is_some_and(|p| !p.muted) {
                        b.send(Command::Media {
                            document: page.document,
                            node: media.node,
                            op: MediaOp::Mute(true),
                        });
                    }
                }
            }
            b.page.set(Some(page));
            b.refresh_controls();
            if new_document {
                apply_site(b, &url);
            }
        }
        Update::State(state) => b.state.set(state),
        Update::Metrics(metrics) => b.chrome_y.set(metrics.scroll_y),
        Update::Done(id, result) => {
            let mut then = None;
            b.waiting.update(|w| then = w.remove(&id));
            match then {
                Some(then) => then(result, cx),
                None => {
                    if let Err(refusal) = result {
                        cx.toast(format!("[red]{}[/]", markup(&refusal.to_string())));
                    }
                }
            }
        }
        Update::Frame(frame) => video_frame(b, &frame),
        Update::Still(node) => {
            b.pacing.with_untracked(|p| p.borrow_mut().still(node));
            send_regions(b);
        }
        Update::Download { name, .. } => cx.toast(format!(
            "[yellow]A download, {}, waits in quarantine.[/]",
            markup(&name)
        )),
        Update::DownloadDone { .. } => {}
        Update::About { answers, product } => about(b, answers, product, cx),
    }
}

/// The key of a piece of reader mode, for `each`.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
enum PieceKey {
    Text(usize, u64),
    Media(NodeId, u16),
    Controls(Vec<NodeId>),
    Player(NodeId),
}

fn piece_keys(page: &Page, pieces: &[Piece], images: Images) -> Vec<PieceKey> {
    use std::hash::{Hash, Hasher};
    pieces
        .iter()
        .enumerate()
        .filter_map(|(i, piece)| match piece {
            Piece::Text(lines) => {
                let mut h = std::collections::hash_map::DefaultHasher::new();
                lines.hash(&mut h);
                Some(PieceKey::Text(i, h.finish()))
            }
            Piece::Media { index, rows } => {
                (images != Images::None).then(|| PieceKey::Media(page.media[*index].node, *rows))
            }
            Piece::Controls(c) => Some(PieceKey::Controls(
                c.iter().map(|i| page.controls[*i].node).collect(),
            )),
            Piece::Player(i) => Some(PieceKey::Player(page.media[*i].node)),
        })
        .collect()
}

/// The picture media region `node` shows now, and the protocol it is
/// drawn with: a moving picture's live frame, else its decoded picture.
fn shown_picture(b: Browser, node: NodeId) -> Option<(Picture, Pixels)> {
    if let Some(live) = b.live.with(|l| l.get(&node).cloned()) {
        return Some((live.picture, live.pixels));
    }
    let (picture, video) = b.page.with(|p| {
        let media = p.as_ref()?.media.iter().find(|m| m.node == node)?;
        Some((
            media.picture.clone()?,
            layout::play_mark(media, 3).is_some(),
        ))
    })?;
    let pixels = b.pixels.get();
    // A video not playing shows its poster with a play mark: in pixels,
    // drawn into them (cells over a Sixel or iTerm2 picture would be
    // covered); in cells, the mark is cells ([`play_marks`]).
    if video && pixels != Pixels::Cells {
        return Some((marked(&picture), pixels));
    }
    Some((picture, pixels))
}

thread_local! {
    /// Posters with their play mark drawn in, by picture frame.
    static MARKED: std::cell::RefCell<HashMap<(u32, u32), Picture>> =
        std::cell::RefCell::new(HashMap::new());
}

/// `picture` with a play mark drawn into its pixels, made once.
fn marked(picture: &Picture) -> Picture {
    let key = (picture.id(), picture.version());
    MARKED.with(|m| {
        let mut made = m.borrow_mut();
        if made.len() > 64 {
            made.clear();
        }
        made.entry(key)
            .or_insert_with(|| Picture::new(rich_art::graphics::play_mark(picture.image())))
            .clone()
    })
}

/// The play mark over the bottom left of each video region on `row` that
/// is not playing, as the PoC drew it over the poster.
fn play_marks(
    line: Vec<rich::Segment>,
    width: usize,
    row: usize,
    regions: &[layout::Region],
    page: &Page,
) -> Vec<rich::Segment> {
    let mut line = line;
    for region in regions {
        let Some(media) = page.media.get(region.media) else {
            continue;
        };
        let last = region.row + region.rows.saturating_sub(1);
        if row != last || region.cols < 3 || region.column + 3 > width {
            continue;
        }
        let Some(mark) = layout::play_mark(media, region.cols) else {
            continue;
        };
        let style = rich::Style::parse(&mark.spans[0].style).ok();
        let mut pieces = rich::Segment::divide(&line, &[region.column, region.column + 3, width]);
        pieces.resize(3, Vec::new());
        let mut joined = std::mem::take(&mut pieces[0]);
        joined.push(rich::Segment::new(mark.spans[0].text.clone(), style));
        joined.extend(std::mem::take(&mut pieces[2]));
        line = joined;
    }
    line
}

fn reader_view(b: Browser) -> Node {
    // The pieces and their keys, made together so they always agree.
    let reading = memo(move || {
        let width = b.viewport.get().0;
        let marks = b.hint_marks();
        let images = b.images.get();
        b.page.with(|p| {
            p.as_ref()
                .map(|p| {
                    let pieces = layout::reader(p, width.saturating_sub(2), &marks);
                    let keys = piece_keys(p, &pieces, images);
                    (pieces, keys)
                })
                .unwrap_or_default()
        })
    });
    let build = move |key: PieceKey| -> Node {
        match key {
            PieceKey::Text(i, _) => {
                let rows = reading.with_untracked(|(d, _)| d.get(i).map_or(1, Piece::rows)) as u16;
                renderable(move || {
                    let mut marks = Marks {
                        find: b.find.get(),
                        ..Marks::default()
                    };
                    reading.with(|(d, _)| {
                        let start: usize = d.iter().take(i).map(Piece::rows).sum();
                        marks.current = b.found.with(|f| f.get(b.find_at.get()).copied());
                        match d.get(i) {
                            Some(Piece::Text(lines)) => to_text(lines, &marks, start),
                            _ => rich::Text::new(""),
                        }
                    })
                })
                .fixed(rows)
            }
            PieceKey::Media(node, rows)
                if b.page.with_untracked(|p| {
                    p.as_ref().is_some_and(|p| {
                        p.media
                            .iter()
                            .any(|m| m.node == node && m.kind == MediaKind::Video)
                    })
                }) =>
            {
                let width = b.page.with_untracked(|p| {
                    p.as_ref()
                        .and_then(|p| p.media.iter().find(|m| m.node == node))
                        .map_or(10, |m| {
                            ((m.rect.width / CELL.0 as f64).ceil() as u16).clamp(4, 120)
                        })
                });
                row([video_region(b, node).fixed(width), label("").flex(1)]).fixed(rows)
            }
            PieceKey::Media(node, rows) => {
                let width = b.page.with_untracked(|p| {
                    p.as_ref()
                        .and_then(|p| p.media.iter().find(|m| m.node == node))
                        .map_or(10, |m| {
                            ((m.rect.width / CELL.0 as f64).ceil() as u16).clamp(4, 120)
                        })
                });
                let view = rich_intuituive::ImageView::new().pixels(b.pixels.get_untracked());
                let picture = picture_of(move || shown_picture(b, node).map(|(p, _)| p), view);
                row([picture.fixed(width), label("").flex(1)]).fixed(rows)
            }
            PieceKey::Controls(nodes) => web_widget(b, nodes),
            PieceKey::Player(node) => player(b, node),
        }
    };
    // Each piece an item, built only near the view, keyed by what it
    // shows: a piece that stays keeps its node across readings.
    let key_of = |key: &PieceKey| {
        use std::hash::{Hash, Hasher};
        let mut h = std::collections::hash_map::DefaultHasher::new();
        key.hash(&mut h);
        h.finish()
    };
    // A piece's rows: text and media are as tall as they say; controls
    // and players are measured once drawn.
    let rows_of = move |i: usize| -> u16 {
        reading.with_untracked(|(d, k)| match k.get(i) {
            Some(PieceKey::Text(at, _)) => d.get(*at).map_or(1, Piece::rows) as u16,
            Some(PieceKey::Media(_, rows)) => *rows,
            _ => 1,
        })
    };
    scroll_virtual_with(
        move || reading.with(|(_, k)| k.len()),
        rows_of,
        move |i| match reading.with_untracked(|(_, k)| k.get(i).cloned()) {
            Some(key) => build(key),
            None => label(""),
        },
        b.scroll,
    )
    .item_key(move |i| reading.with_untracked(|(_, k)| k.get(i).map_or(i as u64, key_of)))
    .on_near_end(near_end(b), move |_| load_more(b))
    .autofocus()
    .name("page")
}

/// How near the end, in rows, the view asks the page for more: a screen.
fn near_end(b: Browser) -> u64 {
    b.viewport.get_untracked().1.max(1) as u64
}

/// Near the end of what was read: scroll Chrome to its bottom, so an
/// infinite feed loads more. The page is read again on its change ping;
/// the view asks again only once it has more rows.
fn load_more(b: Browser) {
    if b.page.with_untracked(Option::is_some) {
        b.send(Command::LoadMore);
    }
}

fn projection_view(b: Browser) -> Node {
    // The pictures' cells, made once per frame and size, shared by rows.
    let cells = Rc::new(pictures::Cells::default());
    // One item per row of the shared layout, built only near the view and
    // keyed by the row's node, so the row in view stays when the page
    // grows above it.
    let line = move |i: usize| {
        // The row this item is: by its key, as rows move when the page
        // grows above them.
        let key = b
            .layout
            .with_untracked(|l| l.keys.get(i).copied().unwrap_or(i as u64));
        let cells = cells.clone();
        leaf(move |console, width, _| {
            let marks = Marks {
                find: b.find.get(),
                current: b.found.with(|f| f.get(b.find_at.get()).copied()),
                ..Marks::default()
            };
            let width = usize::from(width.max(1));
            // The page colours rule off: the page's own colours, on white
            // (a light terminal) or black.
            let backdrop = (!b.effective_adapt().on(crate::adapt::Rule::PageColors))
                .then(|| crate::adapt::backdrop(crate::adapt::background()));
            let drawn = b.layout.with(|l| {
                let row = l.rows.get(&key).copied().unwrap_or(i);
                let Some(line) = l.lines.get(row) else {
                    return vec![Vec::new()];
                };
                let text = to_text(std::slice::from_ref(line), &marks, row);
                let options = console.options().update_width(width);
                let segments = console
                    .render_lines(&text, &options, false)
                    .into_iter()
                    .next()
                    .unwrap_or_default();
                // Only a row a picture covers reads the pictures.
                let inline: Vec<&(layout::Region, String)> =
                    l.inline.iter().filter(|(r, _)| r.on(row)).collect();
                if b.images.get() == Images::None
                    || (inline.is_empty() && !l.regions.iter().any(|r| r.on(row)))
                {
                    return vec![segments];
                }
                let nodes: Vec<Option<NodeId>> = b.page.with(|p| {
                    l.regions
                        .iter()
                        .map(|r| p.as_ref()?.media.get(r.media).map(|m| m.node))
                        .collect()
                });
                // The media regions, then the small pictures in the row's
                // lines, each with its picture.
                let mut on_row: Vec<layout::Region> =
                    l.regions.iter().filter(|r| r.on(row)).copied().collect();
                on_row.extend(inline.iter().map(|(r, _)| *r));
                let pixels = b.pixels.get();
                let small = |region: &layout::Region| -> Option<(Picture, Pixels)> {
                    let (_, src) = inline.iter().find(|(r, _)| r == region)?;
                    let picture = b
                        .page
                        .with(|p| p.as_ref()?.inline_pictures.get(src).cloned())?;
                    Some((picture, pixels))
                };
                let spliced =
                    pictures::splice(console, &cells, segments, width, row, &on_row, |region| {
                        if region.media == usize::MAX {
                            return small(region);
                        }
                        let at = l.regions.iter().position(|r| r == region)?;
                        shown_picture(b, nodes.get(at).copied().flatten()?)
                    });
                // The play mark as cells only where pictures are cells:
                // in pixels it is drawn into the poster ([`marked`]).
                vec![b.page.with(|p| match p {
                    Some(page) if pixels == Pixels::Cells => {
                        play_marks(spliced, width, row, &l.regions, page)
                    }
                    _ => spliced,
                })]
            });
            match backdrop {
                Some(backdrop) => drawn
                    .into_iter()
                    .map(|line| pictures::on_backdrop(line, width, backdrop))
                    .collect(),
                None => drawn,
            }
        })
        .fixed(1)
    };
    scroll_virtual_with(
        move || b.layout.with(|l| l.lines.len()),
        |_| 1,
        line,
        b.scroll,
    )
    .item_key(move |i| {
        b.layout
            .with_untracked(|l| l.keys.get(i).copied().unwrap_or(i as u64))
    })
    .on_near_end(near_end(b), move |_| load_more(b))
    .autofocus()
    .name("page")
}

/// The rows the header and the status bar take.
pub const CHROME_ROWS: u16 = 4;

/// The byte budget moving pictures (GIFs and videos) share: the config's
/// `bandwidth`, else rs-rich-art's guess, lowered to the terminal's
/// measured output rate ([`OutputRate`]), at most the config's frame rate
/// and never more than eight a second. With the bandwidth rule off (the
/// faithful projection), no budget: every frame, never a step down.
pub fn byte_budget(b: Browser) -> rich_art::picture::ByteBudget {
    let adapt = b.effective_adapt();
    let measured = OUTPUT.with(|o| o.borrow_mut().rate());
    b.config.with_untracked(|c| {
        let mut budget = c.bandwidth.map_or_else(
            || {
                let mut guess = rich_art::picture::ByteBudget::guess();
                // The painter's measured rate, when it is lower: a terminal
                // that takes output slower than the guess.
                if let Some(rate) = measured {
                    guess.bytes_per_second = guess.bytes_per_second.min(rate);
                }
                guess
            },
            rich_art::picture::ByteBudget::new,
        );
        budget.max_fps = f64::from(c.fps).clamp(1.0, crate::video::MAX_FPS as f64);
        if !adapt.on(crate::adapt::Rule::Bandwidth) {
            budget.bytes_per_second = u64::MAX / 4;
            budget.min_fps = 0.0;
        }
        budget
    })
}

thread_local! {
    /// The painter's counters, for the terminal's measured output rate.
    static OUTPUT: std::cell::RefCell<OutputRate> = std::cell::RefCell::default();
}

/// How fast the terminal takes output, from the painter's [`FrameStats`]
/// (`rich_intuituive::FrameStats`): the bytes written over the time the
/// writes took, once enough was written to tell. A terminal that keeps up
/// reads fast, so the rate only ever lowers the guessed budget.
#[derive(Default)]
pub struct OutputRate {
    stats: Option<rich_intuituive::StatsHandle>,
    last: (u64, Duration),
    rate: Option<f64>,
}

/// Written since the last sample before a rate is taken from it.
const RATE_SAMPLE: u64 = 64 * 1024;

impl OutputRate {
    /// Fold in the counters: `total_bytes` written in `total_write`.
    pub fn observe(&mut self, total_bytes: u64, total_write: Duration) {
        let bytes = total_bytes.saturating_sub(self.last.0);
        let write = total_write.saturating_sub(self.last.1);
        if bytes < RATE_SAMPLE {
            return;
        }
        self.last = (total_bytes, total_write);
        if write.is_zero() {
            return;
        }
        let rate = bytes as f64 / write.as_secs_f64();
        self.rate = Some(self.rate.map_or(rate, |before| before * 0.7 + rate * 0.3));
    }

    /// Bytes a second the terminal took, measured; `None` until known.
    pub fn rate(&mut self) -> Option<u64> {
        if let Some(stats) = self.stats.as_ref().map(rich_intuituive::StatsHandle::get) {
            self.observe(stats.total_bytes, stats.total_write);
        }
        self.rate.map(|r| r as u64)
    }
}

/// The frames' pacing: within the guessed byte budget, at most the
/// config's frame rate and never more than eight a second, starting at
/// the protocol the user asked for, else character art over SSH, else
/// what the terminal speaks. [`step_motion`] replaces the budget with
/// [`byte_budget`]'s on its first look.
fn video_pacing(config: &Config, images: Images) -> Pacing {
    let mut budget = rich_art::picture::ByteBudget::guess();
    budget.max_fps = (config.fps as f64).clamp(1.0, crate::video::MAX_FPS as f64);
    let asked = (images != Images::Auto).then(|| pictures::pixels(images));
    Pacing::new(budget, Pacing::start_for(asked, Pixels::detect()))
}

/// The browser app over `engine`.
pub fn app(engine: Box<dyn Engine>, options: Options) -> App {
    let Options {
        config,
        bookmarks,
        url,
        view,
        images,
    } = options;
    let start = url
        .or_else(|| config.home.clone())
        .unwrap_or_else(|| "about:blank".into());
    let first_view = view.unwrap_or(config.view);
    let images = images.unwrap_or(config.images);
    let configured_adapt = config.adapt;
    let app = App::new(move || {
        let (keymap, warnings) = actions::keymap(config.preset, &config.keys);
        let mut warnings = [config.warnings.clone(), warnings].concat();
        warnings.truncate(3);
        let (send, receive) = mpsc::channel::<Update>();
        let tab = Tab::spawn(engine, move |update| {
            let _ = send.send(update);
        });
        let page: Signal<Option<Arc<Page>>> = signal(None);
        let view: Signal<View> = signal(if first_view == View::Raster {
            View::Projection
        } else {
            first_view
        });
        let hints: Signal<Option<Hints>> = signal(None);
        let find: Signal<Option<String>> = signal(None);
        let adapt = signal(configured_adapt);
        let faithful = signal(false);
        let logs: Signal<HashMap<NodeId, LogScroll>> = signal(HashMap::new());
        let port = viewport();
        let layout = memo(move || {
            let width = port.get().0;
            let marks = Marks {
                hints: hints
                    .with(|h| {
                        h.as_ref()
                            .map(|h| h.labels.iter().map(|(l, c)| (*c, l.clone())).collect())
                    })
                    .unwrap_or_default(),
                adapt: if faithful.get() {
                    Adapt::none()
                } else {
                    adapt.get()
                },
                logs: logs.get(),
                ..Marks::default()
            };
            let view = view.get();
            Rc::new(page.with(|p| {
                p.as_ref()
                    .map(|p| lay_out(p, view, width, &marks))
                    .unwrap_or_default()
            }))
        });
        let images_signal = signal(images);
        let found = memo(move || {
            let query = find.get().filter(|q| !q.is_empty());
            Rc::new(match query {
                Some(query) => layout.with(|l| {
                    l.lines
                        .iter()
                        .enumerate()
                        .flat_map(|(row, line)| {
                            (0..matches(&line.plain(), &query).len()).map(move |k| (row, k))
                        })
                        .collect()
                }),
                None => Vec::new(),
            })
        });
        let pacing = video_pacing(&config, images);
        let b = Browser {
            page,
            state: signal(PageState::default()),
            view,
            hints,
            find,
            find_at: signal(usize::MAX),
            scroll: signal(0),
            layout,
            found,
            chrome_y: signal(0.0),
            follow: signal(None),
            message: signal(
                warnings
                    .iter()
                    .map(|w| format!("[yellow]config: {}[/]", markup(w)))
                    .collect::<Vec<_>>()
                    .join(" · "),
            ),
            config: signal(config),
            keymap: signal(keymap.clone()),
            bookmarks: signal(bookmarks),
            images: images_signal,
            images_default: signal(images),
            viewport: port,
            adapt,
            faithful,
            logs,
            pixels: memo(move || pictures::pixels(images_signal.get())),
            frozen: signal(false),
            live: signal(Rc::new(HashMap::new())),
            tab: signal(tab),
            waiting: signal(HashMap::new()),
            controls: signal(HashMap::new()),
            videos: signal(Rc::new(HashMap::new())),
            pacing: signal(Rc::new(RefCell::new(pacing))),
            regions_sent: signal((Vec::new(), Vec::new())),
        };
        spawn_stream(move |stream| {
            let proxy = stream.proxy().clone();
            while let Ok(update) = receive.recv() {
                if !proxy.run_with(move |cx| apply(b, update, cx)) {
                    break;
                }
            }
        });
        // Moving pictures in view step within the byte budget.
        let motion = Rc::new(std::cell::RefCell::new(pictures::Motion::new(byte_budget(
            b,
        ))));
        every(MOTION, move |_| step_motion(b, &mut motion.borrow_mut()));
        // Chrome lays the page out at the terminal's size.
        watch(
            move || b.viewport.get(),
            move |(columns, rows), _| {
                b.send(Command::Resize(columns, rows.saturating_sub(CHROME_ROWS)));
            },
        );
        b.send(Command::Open(start.clone()));
        // The tab hears which video regions the view shows, so only those
        // get frames.
        watch(move || regions_on_screen(b), move |_, _| send_regions(b));
        // Chrome's scroll follows ours, so the page's lazy loading and
        // infinite feeds see the reader scroll.
        watch(
            move || b.scroll.get(),
            move |row, cx| follow_scroll(b, row, cx),
        );

        let address = crate::bars::header(b);
        let status = crate::bars::status(b);
        // Built again on each switch: a view kept while hidden could miss
        // the pages opened meanwhile.
        let body = keyed(
            move || b.view.get(),
            move |view| match view {
                View::Reader => reader_view(b),
                _ => projection_view(b),
            },
        )
        .flex(1);
        let mut root = column([address, body, status]);
        for action in ACTIONS {
            let Some((keys, sequence)) = actions::keys_of(&keymap, action.id) else {
                continue;
            };
            let id = action.id;
            let handler = move |cx: &mut Ctx| {
                b.message.set(String::new());
                // A site key overrides a global one, on its site only.
                if let Some(target) = cx.key().and_then(|key| site_key(b, key)) {
                    run_target(b, &target, cx);
                    return;
                }
                run(b, id, cx);
            };
            root = if sequence {
                root.bind_sequence(&keys, action.label, handler)
            } else {
                root.bind(&keys, action.label, handler)
            };
        }
        // Hints and site keys see keys before the page and its widgets
        // (a text box keeps what is typed into it).
        column([root.flex(1)])
            .previews_keys()
            .on_any_key(move |cx, key| {
                if b.hints.with_untracked(Option::is_some) {
                    return hint_key(b, key, cx);
                }
                if let Some(target) = site_key(b, key) {
                    b.message.set(String::new());
                    run_target(b, &target, cx);
                    return true;
                }
                false
            })
    })
    .graphics(image_graphics());
    let stats = app.stats_handle();
    OUTPUT.with(|o| o.borrow_mut().stats = Some(stats));
    app
}

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

    #[test]
    fn the_output_rate_is_measured_once_enough_was_written() {
        let mut rate = OutputRate::default();
        // Too little written to tell.
        rate.observe(10_000, Duration::from_millis(100));
        assert_eq!(rate.rate(), None);
        // 200 kB in a second: 200 kB a second.
        rate.observe(200_000, Duration::from_secs(1));
        assert_eq!(rate.rate(), Some(200_000));
        // Then 400 kB more in a second moves it toward 400 kB a second.
        rate.observe(600_000, Duration::from_secs(2));
        let now = rate.rate().unwrap();
        assert!((200_000..400_000).contains(&now), "{now}");
        // Writes that took no time say nothing.
        rate.observe(900_000, Duration::from_secs(2));
        assert_eq!(rate.rate(), Some(now));
    }
}