corundum-framework-gui 0.2.0

The look shared by sapphire and asteria apps: egui shell, system fonts, Lucide icons, translations
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
//! [`Shell`]: an app's window frame — its screens and actions on a rail, and at the rail's
//! foot the screens that belong there (Settings) and a slot of the app's own (a status dot).
//!
//! The screens and the actions are in the app's order, or the person's ([`RailOrder`], set
//! on the settings page [`RailPage`](crate::settings::RailPage)). When some are left off
//! the rail — the window has no room for them, or the person hid them — the footer's place
//! is taken by a "More" button: its menu holds the footer first, then those left off.
//!
//! Wide, the rail runs down the left (as Obsidian's does); narrower than
//! [`COMPACT_WIDTH`], it becomes a bar along the bottom, as on a phone. The width decides,
//! not the platform, so a desktop window made narrow shows the phone layout.

mod order;

pub use order::RailOrder;

use crate::detail::Part;
pub(crate) use order::{RailEntry, move_to, published, request};

/// Below this width the layout is a phone's: the rail becomes a bottom bar, and screens
/// with a list and a page show one at a time.
pub const COMPACT_WIDTH: f32 = 600.0;

/// The rail's width, wide.
const RAIL_WIDTH: f32 = 48.0;

/// The space above and below the status bar's row.
const STATUS_MARGIN: f32 = 3.0;

/// The space at the rail's ends.
const RAIL_END: f32 = 4.0;

/// One of the app's screens on the rail.
pub struct Destination<D> {
    /// What the app matches on to draw it.
    pub id: D,
    /// A Lucide icon (see [`icons`](crate::icons)), stroked in white so it takes the text
    /// colour: the rail shows only this.
    pub icon: egui::ImageSource<'static>,
    /// The id of the screen's name in the app's translations, looked up each frame and shown
    /// when the icon is hovered.
    pub label: &'static str,
}

impl<D> Destination<D> {
    /// A screen named by the message `label`, drawn as `icon`.
    pub fn new(id: D, icon: egui::ImageSource<'static>, label: &'static str) -> Destination<D> {
        Destination { id, icon, label }
    }
}

/// A button of the app's on the rail that does something — "new-entry" — rather than
/// open a screen. [`Shell::take_action`] says which one was clicked.
pub struct Action {
    /// What [`Shell::take_action`] returns when it is clicked.
    pub id: &'static str,
    /// A Lucide icon, as for a [`Destination`].
    pub icon: egui::ImageSource<'static>,
    /// The id of what it does in the app's translations, looked up each frame and shown
    /// when the icon is hovered.
    pub label: &'static str,
}

impl Action {
    /// A button named by the message `label`, drawn as `icon`, reported as `id`.
    pub fn new(id: &'static str, icon: egui::ImageSource<'static>, label: &'static str) -> Action {
        Action { id, icon, label }
    }
}

/// A screen or an action on the rail, for [`Shell::from_items`]: the two mix in any order,
/// so the action used most — a new entry — can come first.
pub enum RailItem<D> {
    Screen(Destination<D>),
    Action(Action),
}

impl<D> From<Destination<D>> for RailItem<D> {
    fn from(d: Destination<D>) -> RailItem<D> {
        RailItem::Screen(d)
    }
}

impl<D> From<Action> for RailItem<D> {
    fn from(a: Action) -> RailItem<D> {
        RailItem::Action(a)
    }
}

/// The window frame. Hold one as the app's root; call [`ui`](Self::ui) every frame.
///
/// Labels are message ids: each frame the hover text is looked up in the language
/// installed (see [`i18n`](crate::i18n)), so a language switch shows on the next frame.
///
/// The shell keeps clear of the system's bars and notches (egui's
/// [safe area](egui::InputState::safe_area_insets), which iOS fills): the rail, the bar's
/// buttons and the screens stay inside it, and the bottom bar's fill runs on under the home
/// indicator, as a phone's tab bar does. Give it the window's whole root `ui`; the app adds
/// no margin of its own. If the app does keep `ui` clear of them itself, the shell sees
/// that and adds nothing, so the margin is never doubled. On Android,
/// `window::run_android` keeps the app's `ui` clear of the bars and the
/// keyboard already.
///
/// ```no_run
/// # use corundum_framework_gui::{Action, Destination, Shell, icons};
/// # fn example(ui: &mut egui::Ui) {
/// #[derive(Clone, Copy, PartialEq)]
/// enum Screen { Gallery, Albums, Settings }
///
/// let mut shell = Shell::from_items(vec![
///     Action::new("import", icons::plus(), "import").into(),
///     // The app's own Lucide SVGs: `egui::include_image!("../assets/icons/images.svg")`.
///     Destination::new(Screen::Gallery, icons::folder(), "gallery").into(),
///     Destination::new(Screen::Albums, icons::folder(), "albums").into(),
/// ])
/// .with_footer(vec![Destination::new(Screen::Settings, icons::settings(), "settings")]);
/// shell.ui(ui, |ui, screen| match screen {
///     Screen::Gallery => { egui::CentralPanel::default().show(ui, |ui| ui.label("…")); }
///     Screen::Albums => { egui::CentralPanel::default().show(ui, |ui| ui.label("…")); }
///     Screen::Settings => { egui::CentralPanel::default().show(ui, |ui| ui.label("…")); }
/// });
/// if shell.take_action() == Some("import") {
///     // …
/// }
/// # }
/// ```
pub struct Shell<D> {
    destinations: Vec<Destination<D>>,
    actions: Vec<Action>,
    footer: Vec<Destination<D>>,
    /// The screens and the actions in the app's order.
    defaults: Vec<Item>,
    /// The screens and the actions in the order the rail shows them, and whether each is
    /// shown there or left to the menu.
    slots: Vec<Slot>,
    /// The slots on the rail or the bar this frame; the rest are in the menu.
    on_rail: Vec<usize>,
    /// Whether the footer is in the menu this frame, the More button in its place.
    footer_in_menu: bool,
    /// The action clicked and not yet taken.
    clicked: Option<&'static str>,
    /// Where each action and footer destination was last drawn, for the tests to click.
    #[cfg(test)]
    action_rects: Vec<egui::Rect>,
    #[cfg(test)]
    footer_rects: Vec<egui::Rect>,
    /// The rects of the slots on the rail or the bar, in order, for the tests.
    #[cfg(test)]
    cell_rects: Vec<egui::Rect>,
    /// The More button, and its menu's rows, for the tests.
    #[cfg(test)]
    more_rect: egui::Rect,
    #[cfg(test)]
    menu_rects: Vec<egui::Rect>,
    open: Option<D>,
    /// How big the foot was last frame: the rail or the bar keeps room for it.
    foot_size: egui::Vec2,
    /// The side pane, [`with_side_pane`](Self::with_side_pane).
    pane: Option<crate::detail::DetailPane>,
    /// Whether the side column was on at the last frame's end, to save it when it turns.
    side_column: Option<bool>,
    /// Whether [`show`](Self::show) draws a status bar.
    status_bar: bool,
    /// Whether the SVG loader, the theme and the language have been put in place.
    loaders: bool,
}

/// An app as the shell draws it, each frame, with [`Shell::show`]: its screens, its side
/// pane, its foot and status, and what its actions do. The shell calls these in turn, each
/// with the app's `&mut self`, so a screen and the side pane share the app's state freely.
///
/// ```no_run
/// # use corundum_framework_gui::{Action, Destination, Shell, ShellApp, Side, icons};
/// #[derive(Clone, Copy, PartialEq)]
/// enum Screen { Entries, Settings }
///
/// struct Journal { draft: Option<String> }
///
/// impl ShellApp<Screen> for Journal {
///     fn screen_ui(&mut self, ui: &mut egui::Ui, screen: Screen, side: &mut Side) {
///         egui::CentralPanel::default().show(ui, |ui| ui.label("…"));
///     }
///
///     fn side_ui(&mut self, ui: &mut egui::Ui, screen: Screen, side: &mut Side) {
///         match &mut self.draft {
///             Some(text) => {
///                 ui.text_edit_multiline(text);
///                 if ui.button("Save").clicked() {
///                     self.draft = None;
///                     side.close();
///                 }
///             }
///             None => { ui.weak("Nothing selected"); }
///         }
///     }
///
///     fn action(&mut self, id: &'static str, side: &mut Side) {
///         if id == "new-entry" {
///             self.draft = Some(String::new());
///             side.open();
///         }
///     }
/// }
///
/// # fn example(ui: &mut egui::Ui) {
/// let mut shell = Shell::from_items(vec![
///     Action::new("new-entry", icons::plus(), "new-entry").into(),
///     Destination::new(Screen::Entries, icons::file_text(), "entries").into(),
/// ])
/// .with_footer(vec![Destination::new(Screen::Settings, icons::settings(), "settings")])
/// .with_side_pane()
/// .with_status_bar();
/// let mut journal = Journal { draft: None };
/// // Every frame:
/// shell.show(ui, &mut journal);
/// # }
/// ```
pub trait ShellApp<D> {
    /// Draw `screen` into what the frame leaves of `ui`, as it would at the root: its own
    /// panels, then a `CentralPanel`. Through `side` it opens the side pane — on a card, or
    /// on a phone in the screen's place — when the person picks an item.
    fn screen_ui(&mut self, ui: &mut egui::Ui, screen: D, side: &mut Side);

    /// Fill the side pane, [`with_side_pane`](Shell::with_side_pane) (no panels of its own):
    /// the new entry being written, else `screen`'s item, else a word that there is none.
    /// Through `side` it closes the pane once the entry is saved or dropped.
    fn side_ui(&mut self, ui: &mut egui::Ui, screen: D, side: &mut Side) {
        let _ = (ui, screen, side);
    }

    /// Draw the foot — a status dot, say — at the rail's foot, at the bottom bar's end, or
    /// on the status bar; a destination it returns is opened.
    fn foot_ui(&mut self, ui: &mut egui::Ui) -> Option<D> {
        let _ = ui;
        None
    }

    /// Fill the status bar from the left, [`with_status_bar`](Shell::with_status_bar).
    fn status_ui(&mut self, ui: &mut egui::Ui) {
        let _ = ui;
    }

    /// Do what the [`Action`] `id` names: it was clicked on the rail or in the More menu. A
    /// "new entry" begins the entry and opens it in the side pane through `side`.
    fn action(&mut self, id: &'static str, side: &mut Side) {
        let _ = (id, side);
    }
}

/// The side pane, as a [`ShellApp`] asks things of it. What is asked is done after the
/// call. Without a side pane, it asks nothing.
#[derive(Debug)]
pub struct Side {
    pane: bool,
    open: bool,
    asked: Option<bool>,
}

impl Side {
    /// Show the side pane's content: on the card, or on a phone in the screen's place. While
    /// the column shows it, there is nothing more to show.
    pub fn open(&mut self) {
        self.asked = Some(true);
        self.open = self.pane;
    }

    /// Back to the screen alone, on the card or on a phone. The column stays.
    pub fn close(&mut self) {
        self.asked = Some(false);
        self.open = false;
    }

    /// Whether the side pane is open on the card or in the screen's place.
    pub fn is_open(&self) -> bool {
        self.open
    }
}

/// The closures of [`Shell::ui`] and its kin, as a [`ShellApp`].
struct Closures<F, S, C> {
    foot: Option<F>,
    status: Option<S>,
    content: Option<C>,
}

impl<D, F, S, C> ShellApp<D> for Closures<F, S, C>
where
    F: FnOnce(&mut egui::Ui) -> Option<D>,
    S: FnOnce(&mut egui::Ui),
    C: FnOnce(&mut egui::Ui, D),
{
    fn screen_ui(&mut self, ui: &mut egui::Ui, screen: D, _: &mut Side) {
        if let Some(content) = self.content.take() {
            content(ui, screen);
        }
    }

    fn foot_ui(&mut self, ui: &mut egui::Ui) -> Option<D> {
        self.foot.take().and_then(|foot| foot(ui))
    }

    fn status_ui(&mut self, ui: &mut egui::Ui) {
        if let Some(status) = self.status.take() {
            status(ui);
        }
    }
}

/// A screen or an action, by its index in the shell's.
#[derive(Clone, Copy, PartialEq, Debug)]
enum Item {
    Screen(usize),
    Action(usize),
}

/// An item in its place on the rail, and whether the rail shows it.
#[derive(Clone, Copy, PartialEq, Debug)]
struct Slot {
    item: Item,
    shown: bool,
}

/// A row of the More menu.
#[derive(Clone, Copy, PartialEq, Debug)]
enum Row {
    Footer(usize),
    Slot(usize),
}

impl<D: Copy + PartialEq> Shell<D> {
    /// A frame with `destinations` on the rail, the first one open.
    pub fn new(destinations: Vec<Destination<D>>) -> Shell<D> {
        Shell::from_items(destinations.into_iter().map(RailItem::from).collect())
    }

    /// A frame with `items` — screens and actions — on the rail in this order, the first
    /// screen open.
    pub fn from_items(items: Vec<RailItem<D>>) -> Shell<D> {
        let mut shell = Shell {
            destinations: Vec::new(),
            actions: Vec::new(),
            footer: Vec::new(),
            defaults: Vec::new(),
            slots: Vec::new(),
            on_rail: Vec::new(),
            footer_in_menu: false,
            clicked: None,
            #[cfg(test)]
            action_rects: Vec::new(),
            #[cfg(test)]
            footer_rects: Vec::new(),
            #[cfg(test)]
            cell_rects: Vec::new(),
            #[cfg(test)]
            more_rect: egui::Rect::NOTHING,
            #[cfg(test)]
            menu_rects: Vec::new(),
            open: None,
            foot_size: egui::Vec2::ZERO,
            pane: None,
            side_column: None,
            status_bar: false,
            loaders: false,
        };
        for item in items {
            shell.push(item);
        }
        shell.open = shell.destinations.first().map(|d| d.id);
        shell.slots = shell.default_slots();
        shell
    }

    fn push(&mut self, item: RailItem<D>) {
        match item {
            RailItem::Screen(d) => {
                self.defaults.push(Item::Screen(self.destinations.len()));
                self.destinations.push(d);
            }
            RailItem::Action(a) => {
                self.defaults.push(Item::Action(self.actions.len()));
                self.actions.push(a);
            }
        }
    }

    /// Put `actions` on the rail after the items already there. To put one first, give the
    /// items to [`from_items`](Self::from_items) instead.
    pub fn with_actions(mut self, actions: Vec<Action>) -> Shell<D> {
        let order = self.rail_order();
        for action in actions {
            self.push(action.into());
        }
        self.set_rail_order(&order);
        self
    }

    /// Put `footer` at the rail's foot (at the bottom bar's end): where an app puts
    /// Settings. With no other destinations, the first of these is open. When some items
    /// are left off the rail, the footer moves into the More menu, which takes its place.
    pub fn with_footer(mut self, footer: Vec<Destination<D>>) -> Shell<D> {
        self.footer = footer;
        if self.open.is_none() {
            self.open = self.footer.first().map(|d| d.id);
        }
        self
    }

    /// Lay the rail out in `order`, as [`set_rail_order`](Self::set_rail_order).
    pub fn with_rail_order(mut self, order: &RailOrder) -> Shell<D> {
        self.set_rail_order(order);
        self
    }

    /// The order the rail's items are in, and which of them it leaves to the menu.
    pub fn rail_order(&self) -> RailOrder {
        RailOrder {
            order: self.slots.iter().map(|s| self.key(s.item).into()).collect(),
            hidden: self
                .slots
                .iter()
                .filter(|s| !s.shown)
                .map(|s| self.key(s.item).into())
                .collect(),
        }
    }

    /// Lay the rail out in `order`. With the `serde` feature and a
    /// [store](crate::store) attached, the order saved there replaces this on the first
    /// frame.
    pub fn set_rail_order(&mut self, order: &RailOrder) {
        let place = |key: &str| {
            order
                .order
                .iter()
                .position(|k| k == key)
                .unwrap_or(usize::MAX)
        };
        let mut slots = self.default_slots();
        // Stable: items of one name, and those the order does not name, keep the app's order.
        slots.sort_by_key(|s| place(self.key(s.item)));
        for slot in &mut slots {
            slot.shown = !order.hidden.iter().any(|k| k == self.key(slot.item));
        }
        self.slots = slots;
    }

    fn default_slots(&self) -> Vec<Slot> {
        self.defaults
            .iter()
            .map(|&item| Slot { item, shown: true })
            .collect()
    }

    /// The name `item` goes by in a [`RailOrder`].
    fn key(&self, item: Item) -> &'static str {
        match item {
            Item::Screen(i) => self.destinations[i].label,
            Item::Action(i) => self.actions[i].id,
        }
    }

    fn icon_and_label(&self, item: Item) -> (egui::ImageSource<'static>, &'static str) {
        match item {
            Item::Screen(i) => (
                self.destinations[i].icon.clone(),
                self.destinations[i].label,
            ),
            Item::Action(i) => (self.actions[i].icon.clone(), self.actions[i].label),
        }
    }

    /// Take the order the [rail's page](crate::settings::RailPage) set, and keep it in the
    /// store; then list the items for the page.
    fn sync_order(&mut self, ctx: &egui::Context) {
        if let Some(order) = order::take_request(ctx) {
            self.set_rail_order(&order);
            #[cfg(feature = "serde")]
            crate::store::update(ctx, |state| state.rail = Some(self.rail_order()));
        }
        let entries = self
            .slots
            .iter()
            .map(|s| {
                let (icon, label) = self.icon_and_label(s.item);
                RailEntry {
                    key: self.key(s.item),
                    icon,
                    label,
                    shown: s.shown,
                }
            })
            .collect();
        order::publish(ctx, entries);
    }

    /// The [`Action`] clicked in the last [`ui`](Self::ui), once: call it after `ui`
    /// every frame and do what it names.
    pub fn take_action(&mut self) -> Option<&'static str> {
        self.clicked.take()
    }

    /// The destination that is open; `None` only when there are none.
    pub fn current(&self) -> Option<D> {
        self.open
    }

    /// Open the destination `id`.
    pub fn open(&mut self, id: D) {
        self.open = Some(id);
    }

    /// Give the app a side pane: a right column beside every screen when wide, which the
    /// status bar's button hides; a card over the screen when it is hidden or there is no
    /// room; on a phone, the screen's place. [`ShellApp::side_ui`] fills it, and a screen
    /// or an action opens it through [`Side`]. Whether the column is on is kept with the
    /// rail's order, in the [store](crate::store) if one is attached.
    pub fn with_side_pane(mut self) -> Shell<D> {
        self.pane = Some(crate::detail::DetailPane::new("corundum_shell_side"));
        self
    }

    /// Draw a status bar along the window's bottom when wide: [`ShellApp::status_ui`] fills
    /// it from the left — a log's last line, the services' state, the track playing; its
    /// right end holds [`ShellApp::foot_ui`] (there rather than at the rail's foot), then
    /// the side pane's toggle. Narrow, as on a phone, there is no status bar: the foot stays
    /// on the bottom bar.
    pub fn with_status_bar(mut self) -> Shell<D> {
        self.status_bar = true;
        self
    }

    /// Render `app` into the window's root `ui`: the rail, the open screen
    /// ([`ShellApp::screen_ui`]) and, [`with_side_pane`](Self::with_side_pane), the side
    /// pane beside it; then hand an action clicked to [`ShellApp::action`]. The first frame
    /// installs the default [`theme`](crate::theme) and [`language`](crate::i18n) if the app
    /// has not installed them, and takes the rail's order and the side column from the
    /// [store](crate::store) if one is attached.
    pub fn show(&mut self, ui: &mut egui::Ui, app: &mut impl ShellApp<D>) {
        self.frame_ui(ui, app, self.status_bar);
        if let Some(id) = self.clicked.take() {
            let mut side = self.side();
            app.action(id, &mut side);
            self.apply_side(side);
            ui.ctx().request_repaint();
        }
    }

    /// Render into the window's root `ui`. `content` draws the open destination into what
    /// the frame leaves of `ui`, as it would at the root: its own panels, then a
    /// `CentralPanel`. An action clicked waits for [`take_action`](Self::take_action). The
    /// first frame installs the default [`theme`](crate::theme) and
    /// [`language`](crate::i18n) if the app has not installed them, and takes the rail's
    /// order from the [store](crate::store) if one is attached. An app with a side pane or
    /// state shared by its screens implements [`ShellApp`] and calls [`show`](Self::show).
    pub fn ui(&mut self, ui: &mut egui::Ui, content: impl FnOnce(&mut egui::Ui, D)) {
        self.ui_with_foot(ui, |_| None, content);
    }

    /// As [`ui`](Self::ui), with `foot` drawn beside the footer — a status dot, say. A
    /// destination `foot` returns is opened, and drawn this frame.
    pub fn ui_with_foot(
        &mut self,
        ui: &mut egui::Ui,
        foot: impl FnOnce(&mut egui::Ui) -> Option<D>,
        content: impl FnOnce(&mut egui::Ui, D),
    ) {
        let mut app = Closures {
            foot: Some(foot),
            status: None::<fn(&mut egui::Ui)>,
            content: Some(content),
        };
        self.frame_ui(ui, &mut app, false);
    }

    /// As [`ui_with_foot`](Self::ui_with_foot), with a status bar along the window's
    /// bottom when wide, as [`with_status_bar`](Self::with_status_bar): `status` fills it
    /// from the left, and its right end holds `foot`. Narrow, as on a phone, there is no
    /// status bar: `foot` stays on the bottom bar, and `status` is not called.
    pub fn ui_with_status(
        &mut self,
        ui: &mut egui::Ui,
        foot: impl FnOnce(&mut egui::Ui) -> Option<D>,
        status: impl FnOnce(&mut egui::Ui),
        content: impl FnOnce(&mut egui::Ui, D),
    ) {
        let mut app = Closures {
            foot: Some(foot),
            status: Some(status),
            content: Some(content),
        };
        self.frame_ui(ui, &mut app, true);
    }

    /// The side pane's state, for the app to ask things of.
    fn side(&self) -> Side {
        Side {
            pane: self.pane.is_some(),
            open: self.pane.as_ref().is_some_and(|p| p.is_open()),
            asked: None,
        }
    }

    fn apply_side(&mut self, side: Side) {
        if let (Some(pane), Some(open)) = (&mut self.pane, side.asked) {
            if open {
                pane.open();
            } else {
                pane.close();
            }
        }
    }

    /// The open screen, in the side pane when there is one.
    fn content_ui(&mut self, ui: &mut egui::Ui, app: &mut impl ShellApp<D>, id: D) {
        let mut side = self.side();
        match &mut self.pane {
            Some(pane) => pane.show(ui, |ui, part| match part {
                Part::Main => app.screen_ui(ui, id, &mut side),
                Part::Detail => app.side_ui(ui, id, &mut side),
            }),
            None => app.screen_ui(ui, id, &mut side),
        }
        self.apply_side(side);
    }

    /// Take the side column's state from the store on the first frame, and keep it there
    /// when the person turns it on or off.
    fn sync_side(&mut self, ctx: &egui::Context, first: bool) {
        let Some(pane) = &mut self.pane else {
            return;
        };
        #[cfg(feature = "serde")]
        {
            if first && let Some(saved) = crate::store::state(ctx).side {
                pane.set_column(saved.column);
            }
            let column = pane.column();
            if !first && self.side_column != Some(column) {
                crate::store::update(ctx, |state| {
                    state.side = Some(crate::store::SidePane { column });
                });
            }
        }
        #[cfg(not(feature = "serde"))]
        let _ = (ctx, first);
        self.side_column = Some(pane.column());
    }

    fn frame_ui(&mut self, ui: &mut egui::Ui, app: &mut impl ShellApp<D>, status: bool) {
        let first = !std::mem::replace(&mut self.loaders, true);
        if first {
            crate::icons::install_loaders(ui.ctx());
            // The app may have installed its saved theme already; only fill the gap.
            if !crate::theme::is_installed(ui.ctx()) {
                crate::theme::install(ui.ctx(), &crate::theme::ThemeSettings::default());
            }
            // Likewise the language.
            if !crate::i18n::is_installed(ui.ctx()) {
                crate::i18n::install(ui.ctx(), &crate::i18n::LanguageSettings::default());
            }
            #[cfg(feature = "serde")]
            if let Some(order) = crate::store::state(ui.ctx()).rail {
                self.set_rail_order(&order);
            }
            self.sync_side(ui.ctx(), true);
        }
        self.sync_order(ui.ctx());
        let safe = unsafe_margin(ui);
        let full = ui.max_rect();
        let compact = full.width() - safe.sum().x < COMPACT_WIDTH;
        // Narrow, the bar's fill runs on under the home indicator, its buttons above it;
        // wide, the rail stops above it too.
        let inner = if compact {
            full - egui::epaint::MarginF32 {
                bottom: 0.0,
                ..safe
            }
        } else {
            full - safe
        };
        // The strips under the status bar and the notch take the panels' colour.
        if safe != egui::epaint::MarginF32::ZERO {
            ui.painter().rect_filled(full, 0.0, ui.visuals().panel_fill);
        }
        if !compact && status {
            // The bar under the rail and the screen, which keep what is above it.
            let height = ui.spacing().interact_size.y + 2.0 * STATUS_MARGIN;
            let above = inner.with_max_y(inner.bottom() - height);
            let strip = inner.with_min_y(above.bottom());
            ui.scope_builder(egui::UiBuilder::new().max_rect(above), |ui| {
                let opened = egui::Panel::left("shell_rail")
                    .resizable(false)
                    .exact_size(RAIL_WIDTH)
                    .show(ui, |ui| self.rail_ui(ui, |_| None))
                    .inner;
                if let Some(id) = opened {
                    self.open = Some(id);
                }
                if let Some(id) = self.open {
                    self.content_ui(ui, app, id);
                }
            });
            // Drawn after the screen, so the toggle knows of the detail pane drawn there.
            if let Some(id) = status_bar_ui(ui, strip, app) {
                self.open = Some(id);
                ui.ctx().request_repaint();
            }
        } else {
            ui.scope_builder(egui::UiBuilder::new().max_rect(inner), |ui| {
                let foot = |ui: &mut egui::Ui| app.foot_ui(ui);
                let opened = if compact {
                    let mut frame = egui::Frame::side_top_panel(ui.style());
                    frame.inner_margin.bottom = frame
                        .inner_margin
                        .bottom
                        .saturating_add(safe.bottom.round().min(127.0) as i8);
                    egui::Panel::bottom("shell_bar")
                        .frame(frame)
                        .show(ui, |ui| self.bar_ui(ui, foot))
                        .inner
                } else {
                    egui::Panel::left("shell_rail")
                        .resizable(false)
                        .exact_size(RAIL_WIDTH)
                        .show(ui, |ui| self.rail_ui(ui, foot))
                        .inner
                };
                if let Some(id) = opened {
                    self.open = Some(id);
                }
                if let Some(id) = self.open {
                    self.content_ui(ui, app, id);
                }
            });
        }
        self.sync_side(ui.ctx(), false);
    }

    /// How many of the `shown` items the rail or bar holds in `room` (its length less the
    /// foot's), at `step` per button, and whether the More button takes the footer's place.
    /// When every shown item fits beside the footer and none is hidden, there is no menu;
    /// else the More button stands where the footer was and the items share the rest.
    fn fit(&self, shown: usize, room: f32, step: f32) -> (usize, bool) {
        let hidden = shown < self.slots.len();
        let footer = self.footer.len() as f32 * step;
        if !hidden && shown as f32 * step + footer <= room {
            return (shown, false);
        }
        let held = ((room - step) / step).floor().max(0.0) as usize;
        (held.min(shown), true)
    }

    /// Keep `size` as the foot's, laying the frame out again when it changed.
    fn foot_measured(&mut self, ctx: &egui::Context, size: egui::Vec2) {
        if (size - self.foot_size).length() > 0.5 {
            self.foot_size = size;
            ctx.request_discard("the shell's foot changed size");
        }
    }

    /// The wide layout: the footer (or the More button) and the foot from the bottom, then
    /// the screens and the actions from the top, as many as fit above them.
    fn rail_ui(
        &mut self,
        ui: &mut egui::Ui,
        foot: impl FnOnce(&mut egui::Ui) -> Option<D>,
    ) -> Option<D> {
        let full = ui.available_rect_before_wrap();
        let step = BUTTON + ui.spacing().item_spacing.y;
        let shown = self.shown();
        let room = full.height() - 2.0 * RAIL_END - self.foot_size.y;
        let (held, more) = self.fit(shown.len(), room, step);
        self.lay_out(&shown[..held], more);
        let bottom = ui.scope_builder(
            egui::UiBuilder::new()
                .max_rect(full)
                .layout(egui::Layout::bottom_up(egui::Align::Center)),
            |ui| {
                ui.add_space(RAIL_END);
                self.end_ui(ui, more, false);
                let foot = ui.scope(foot);
                (foot.inner, foot.response.rect.size())
            },
        );
        let (opened, foot_size) = bottom.inner;
        self.foot_measured(ui.ctx(), foot_size);
        let top = full.with_max_y(bottom.response.rect.top());
        ui.scope_builder(
            egui::UiBuilder::new()
                .max_rect(top)
                .layout(egui::Layout::top_down(egui::Align::Center)),
            |ui| {
                ui.add_space(RAIL_END);
                for &s in &shown[..held] {
                    self.slot_ui(ui, s, BUTTON);
                }
            },
        );
        opened
    }

    /// The phone layout: a cell per screen or action, as many as fit, then the footer (or
    /// the More button) and the foot at the bar's end.
    ///
    /// The end keeps the width it needs; the items share what is left, a full-size button
    /// each, and those that do not fit are in the More menu. So the foot never leaves the
    /// screen, however many items there are.
    fn bar_ui(
        &mut self,
        ui: &mut egui::Ui,
        foot: impl FnOnce(&mut egui::Ui) -> Option<D>,
    ) -> Option<D> {
        let rect = ui.available_rect_before_wrap();
        let gap = ui.spacing().item_spacing.x;
        let step = BUTTON + gap;
        let shown = self.shown();
        let room = rect.width() - self.foot_size.x - gap;
        let (held, more) = self.fit(shown.len(), room, step);
        self.lay_out(&shown[..held], more);
        // The end first, from the right: the cells get what it leaves.
        let end = ui.scope_builder(
            egui::UiBuilder::new()
                .max_rect(rect)
                .layout(egui::Layout::right_to_left(egui::Align::Center)),
            |ui| {
                let foot = ui.scope(foot);
                self.end_ui(ui, more, true);
                (foot.inner, foot.response.rect.size())
            },
        );
        let (opened, foot_size) = end.inner;
        self.foot_measured(ui.ctx(), foot_size);
        let cells = held;
        if cells > 0 {
            let row = rect.with_max_x(end.response.rect.left() - gap);
            ui.scope_builder(egui::UiBuilder::new().max_rect(row), |ui| {
                ui.columns(cells, |columns| {
                    for (i, column) in columns.iter_mut().enumerate() {
                        column.vertical_centered(|ui| {
                            let side = ui.available_width().min(BUTTON);
                            self.slot_ui(ui, shown[i], side);
                        });
                    }
                });
            });
        }
        opened
    }

    /// Set out this frame's rail: the slots on it, and whether the footer is in the menu.
    fn lay_out(&mut self, on_rail: &[usize], more: bool) {
        self.on_rail = on_rail.to_vec();
        self.footer_in_menu = more;
        #[cfg(test)]
        {
            self.cell_rects.clear();
            self.footer_rects.clear();
            self.more_rect = egui::Rect::NOTHING;
        }
    }

    /// The footer, or the More button in its place; `backwards` for a layout running right
    /// to left, so the footer still reads in its order.
    fn end_ui(&mut self, ui: &mut egui::Ui, more: bool, backwards: bool) {
        if more {
            self.more_ui(ui);
            return;
        }
        let mut order: Vec<usize> = (0..self.footer.len()).collect();
        if backwards {
            order.reverse();
        }
        for i in order {
            self.footer_ui(ui, i);
        }
    }

    /// The slots the person shows on the rail, in order: the first of them that fit are on it.
    fn shown(&self) -> Vec<usize> {
        (0..self.slots.len())
            .filter(|&s| self.slots[s].shown)
            .collect()
    }

    /// Slot `s`'s button on the rail or the bar.
    fn slot_ui(&mut self, ui: &mut egui::Ui, s: usize, side: f32) {
        let response = match self.slots[s].item {
            Item::Screen(i) => self.destination_ui(ui, i, side),
            Item::Action(i) => self.action_ui(ui, i, side),
        };
        #[cfg(test)]
        self.cell_rects.push(response.rect);
        #[cfg(not(test))]
        let _ = response;
    }

    /// The More menu's rows: the footer first, then the items left off the rail, in order.
    fn menu_rows(&self) -> Vec<Row> {
        let footer = (0..self.footer.len()).map(Row::Footer);
        let off = (0..self.slots.len())
            .filter(|s| !self.on_rail.contains(s))
            .map(Row::Slot);
        footer.chain(off).collect()
    }

    /// The More button, in the footer's place, and its menu.
    fn more_ui(&mut self, ui: &mut egui::Ui) {
        let rows = self.menu_rows();
        // Marked, as a screen's button is, when the screen open is in the menu.
        let open_inside = rows
            .iter()
            .any(|&row| self.row_opens(row) == self.open && self.open.is_some());
        let response = icon_button(ui, open_inside, crate::icons::ellipsis(), BUTTON)
            .on_hover_text(crate::i18n::tr(ui.ctx(), "corundum-shell-more"));
        #[cfg(test)]
        {
            self.more_rect = response.rect;
        }
        egui::Popup::menu(&response).show(|ui| self.menu_ui(ui, &rows));
    }

    /// The screen `row` opens, if it is one.
    fn row_opens(&self, row: Row) -> Option<D> {
        match row {
            Row::Footer(i) => Some(self.footer[i].id),
            Row::Slot(s) => match self.slots[s].item {
                Item::Screen(i) => Some(self.destinations[i].id),
                Item::Action(_) => None,
            },
        }
    }

    fn menu_ui(&mut self, ui: &mut egui::Ui, rows: &[Row]) {
        #[cfg(test)]
        self.menu_rects.clear();
        for (n, &row) in rows.iter().enumerate() {
            if n > 0 && matches!(rows[n - 1], Row::Footer(_)) && matches!(row, Row::Slot(_)) {
                ui.separator();
            }
            let (icon, label) = match row {
                Row::Footer(i) => (self.footer[i].icon.clone(), self.footer[i].label),
                Row::Slot(s) => self.icon_and_label(self.slots[s].item),
            };
            let open = self.open.is_some() && self.row_opens(row) == self.open;
            let image = crate::icons::image(ui, icon, 16.0);
            let response = ui.add(
                egui::Button::image_and_text(image, crate::i18n::tr(ui.ctx(), label))
                    .selected(open),
            );
            #[cfg(test)]
            self.menu_rects.push(response.rect);
            if response.clicked() {
                match row {
                    Row::Slot(s) => match self.slots[s].item {
                        Item::Screen(i) => self.open = Some(self.destinations[i].id),
                        Item::Action(i) => self.clicked = Some(self.actions[i].id),
                    },
                    Row::Footer(i) => self.open = Some(self.footer[i].id),
                }
            }
        }
    }

    fn destination_ui(&mut self, ui: &mut egui::Ui, i: usize, side: f32) -> egui::Response {
        let d = &self.destinations[i];
        let open = self.open == Some(d.id);
        let response = icon_button(ui, open, d.icon.clone(), side)
            .on_hover_text(crate::i18n::tr(ui.ctx(), d.label));
        if response.clicked() {
            self.open = Some(d.id);
        }
        response
    }

    /// What the hover text of destination `i` says now.
    #[cfg(test)]
    fn label_text(&self, ctx: &egui::Context, i: usize) -> String {
        crate::i18n::tr(ctx, self.destinations[i].label)
    }

    fn footer_ui(&mut self, ui: &mut egui::Ui, i: usize) {
        let d = &self.footer[i];
        let open = self.open == Some(d.id);
        let response = icon_button(ui, open, d.icon.clone(), BUTTON)
            .on_hover_text(crate::i18n::tr(ui.ctx(), d.label));
        #[cfg(test)]
        {
            self.footer_rects
                .resize(self.footer.len(), egui::Rect::NOTHING);
            self.footer_rects[i] = response.rect;
        }
        if response.clicked() {
            self.open = Some(self.footer[i].id);
        }
    }

    fn action_ui(&mut self, ui: &mut egui::Ui, i: usize, side: f32) -> egui::Response {
        let a = &self.actions[i];
        let response = icon_button(ui, false, a.icon.clone(), side)
            .on_hover_text(crate::i18n::tr(ui.ctx(), a.label));
        #[cfg(test)]
        {
            self.action_rects
                .resize(self.actions.len(), egui::Rect::NOTHING);
            self.action_rects[i] = response.rect;
        }
        if response.clicked() {
            self.clicked = Some(a.id);
        }
        response
    }
}

/// The status bar along the bottom of `strip`: the app's status from the left, its foot and
/// the side pane's toggle at the right end. The destination the foot returns, if any.
fn status_bar_ui<D>(ui: &mut egui::Ui, strip: egui::Rect, app: &mut impl ShellApp<D>) -> Option<D> {
    let visuals = ui.visuals();
    ui.painter().rect_filled(strip, 0.0, visuals.panel_fill);
    ui.painter().hline(
        strip.x_range(),
        strip.top(),
        visuals.widgets.noninteractive.bg_stroke,
    );
    let row = strip.shrink2(egui::vec2(8.0, STATUS_MARGIN));
    ui.scope_builder(
        egui::UiBuilder::new()
            .max_rect(row)
            .layout(egui::Layout::right_to_left(egui::Align::Center)),
        |ui| {
            ui.set_clip_rect(row);
            crate::detail::toggle_ui(ui);
            let opened = app.foot_ui(ui);
            // What is left, from the left: the app's.
            ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| {
                app.status_ui(ui)
            });
            opened
        },
    )
    .inner
}

/// How far the system's bars and notches (egui's safe area insets) reach into `ui`, side by
/// side: none where `ui` already keeps clear of them.
fn unsafe_margin(ui: &egui::Ui) -> egui::epaint::MarginF32 {
    let safe = ui.ctx().content_rect();
    let rect = ui.max_rect();
    egui::epaint::MarginF32 {
        left: (safe.left() - rect.left()).max(0.0),
        right: (rect.right() - safe.right()).max(0.0),
        top: (safe.top() - rect.top()).max(0.0),
        bottom: (rect.bottom() - safe.bottom()).max(0.0),
    }
}

/// A rail or bar button's side, where there is room for it.
const BUTTON: f32 = 36.0;

/// A button with `icon` in it, `side` points wide ([`BUTTON`], or less on a crowded bar) and
/// [`BUTTON`] tall, so a narrowed one still lines up with the rest and is as easy to tap.
fn icon_button(
    ui: &mut egui::Ui,
    open: bool,
    icon: egui::ImageSource<'static>,
    side: f32,
) -> egui::Response {
    // A narrow button takes a smaller icon first, then less padding beside it, so it stays
    // `side` wide.
    let pad = ui.spacing().button_padding.x;
    let icon_size = (side - 2.0 * pad).clamp(12.0, 20.0);
    ui.scope(|ui| {
        let padding = &mut ui.spacing_mut().button_padding.x;
        *padding = padding.min(((side - icon_size) / 2.0).max(0.0));
        // The open destination's icon takes the accent, as egui's selected text does.
        ui.add(
            crate::icons::button(icon, icon_size)
                .selected(open)
                .frame_when_inactive(open)
                .min_size(egui::vec2(side, BUTTON)),
        )
    })
    .inner
}

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

    #[derive(Clone, Copy, PartialEq, Debug)]
    enum Screen {
        Entries,
        Summary,
        Prefs,
    }

    const SIZES: [[f32; 2]; 2] = [[900.0, 600.0], [400.0, 700.0]];

    fn shell() -> Shell<Screen> {
        Shell::new(vec![
            Destination::new(Screen::Entries, crate::icons::settings(), "entries"),
            Destination::new(Screen::Summary, crate::icons::arrow_left(), "summary"),
        ])
    }

    fn prefs() -> Vec<Destination<Screen>> {
        vec![Destination::new(
            Screen::Prefs,
            crate::icons::settings(),
            "preferences",
        )]
    }

    fn screen(ui: &mut egui::Ui) {
        egui::CentralPanel::default().show(ui, |ui| ui.label("screen"));
    }

    /// Lay `shell` out over two frames of a `size` screen, then click where `at` says.
    fn click(shell: &mut Shell<Screen>, size: [f32; 2], at: impl Fn(&Shell<Screen>) -> egui::Pos2) {
        let ctx = egui::Context::default();
        let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(size[0], size[1]));
        let frame = |events: Vec<egui::Event>, shell: &mut Shell<Screen>| {
            let input = egui::RawInput {
                screen_rect: Some(rect),
                events,
                ..Default::default()
            };
            let mut output = ctx.run_ui(input, |ui| shell.ui(ui, |ui, _| screen(ui)));
            output.textures_delta.clear();
        };
        frame(vec![], shell);
        frame(vec![], shell);
        let pos = at(shell);
        let button = |pressed| egui::Event::PointerButton {
            pos,
            button: egui::PointerButton::Primary,
            pressed,
            modifiers: egui::Modifiers::NONE,
        };
        frame(vec![egui::Event::PointerMoved(pos)], shell);
        frame(vec![button(true)], shell);
        frame(vec![button(false)], shell);
    }

    #[test]
    fn it_opens_on_the_first_screen_and_draws_it() {
        let mut shell = shell();
        assert_eq!(shell.current(), Some(Screen::Entries));
        for size in SIZES {
            let mut drawn = Vec::new();
            render(size, |ui| {
                shell.ui(ui, |ui, s| {
                    drawn.push(s);
                    screen(ui);
                })
            });
            assert_eq!(drawn, [Screen::Entries, Screen::Entries]);
        }
    }

    #[test]
    fn actions_are_drawn_in_both_layouts_and_report_nothing_unclicked() {
        let mut shell =
            shell().with_actions(vec![Action::new("new", crate::icons::plus(), "new-entry")]);
        for size in SIZES {
            shell.action_rects.clear();
            render(size, |ui| shell.ui(ui, |ui, _| screen(ui)));
            assert!(shell.action_rects[0].is_positive(), "{size:?}");
            assert_eq!(shell.take_action(), None);
        }
        assert_eq!(shell.current(), Some(Screen::Entries));
    }

    #[test]
    fn a_clicked_action_is_taken_once_and_opens_nothing() {
        let mut shell =
            shell().with_actions(vec![Action::new("new", crate::icons::plus(), "new-entry")]);
        click(&mut shell, SIZES[0], |s| s.action_rects[0].center());
        assert_eq!(shell.take_action(), Some("new"));
        assert_eq!(shell.take_action(), None);
        assert_eq!(shell.current(), Some(Screen::Entries));
    }

    #[test]
    fn footer_and_foot_are_in_both_layouts() {
        let mut shell = shell().with_footer(prefs());
        for size in SIZES {
            shell.footer_rects.clear();
            let mut foot = egui::Rect::NOTHING;
            render(size, |ui| {
                shell.ui_with_foot(
                    ui,
                    |ui| {
                        foot = ui
                            .allocate_exact_size(egui::vec2(12.0, 12.0), egui::Sense::click())
                            .0;
                        None
                    },
                    |ui, _| screen(ui),
                )
            });
            assert!(shell.footer_rects[0].is_positive(), "{size:?}");
            assert!(foot.is_positive(), "{size:?}");
        }
    }

    #[test]
    fn clicking_a_footer_destination_opens_it() {
        for size in SIZES {
            let mut shell = shell().with_footer(prefs());
            click(&mut shell, size, |s| s.footer_rects[0].center());
            assert_eq!(shell.current(), Some(Screen::Prefs), "{size:?}");
        }
        let mut shell = shell().with_footer(prefs());
        shell.open(Screen::Prefs);
        let mut drawn = Vec::new();
        render([900.0, 600.0], |ui| {
            shell.ui(ui, |ui, s| {
                drawn.push(s);
                screen(ui);
            })
        });
        assert_eq!(drawn, [Screen::Prefs, Screen::Prefs]);
    }

    #[test]
    fn a_destination_the_foot_returns_is_opened() {
        let mut shell = shell();
        let mut drawn = Vec::new();
        render([900.0, 600.0], |ui| {
            shell.ui_with_foot(
                ui,
                |_| Some(Screen::Summary),
                |ui, s| {
                    drawn.push(s);
                    screen(ui);
                },
            )
        });
        assert_eq!(shell.current(), Some(Screen::Summary));
        assert_eq!(drawn, [Screen::Summary, Screen::Summary]);
    }

    #[test]
    fn the_shell_installs_the_default_theme() {
        let ctx = egui::Context::default();
        let mut shell = shell();
        crate::test_support::render_in(&ctx, [900.0, 600.0], |ui| shell.ui(ui, |ui, _| screen(ui)));
        assert!(crate::theme::is_installed(&ctx));
    }

    #[test]
    fn the_shell_keeps_an_installed_theme() {
        use crate::theme::{Contrast, ThemeSettings};
        let ctx = egui::Context::default();
        let settings = ThemeSettings {
            preference: egui::ThemePreference::Dark,
            contrast: Contrast::High,
            ..Default::default()
        };
        crate::theme::install(&ctx, &settings);
        let mut shell = shell();
        crate::test_support::render_in(&ctx, [900.0, 600.0], |ui| shell.ui(ui, |ui, _| screen(ui)));
        let high = crate::theme::Theme::new(
            true,
            Contrast::High,
            crate::theme::Tint::Swatch(crate::theme::Swatch::Blue),
        );
        assert_eq!(*crate::theme::current(&ctx), high);
    }

    const T: crate::i18n::Resources = crate::i18n::Resources {
        name: "shell-test",
        files: &[
            ("en", "t-entries = Entries\n"),
            ("ja", "t-entries = é …ç›®\n"),
        ],
    };

    #[test]
    fn the_shell_installs_the_default_language() {
        let ctx = egui::Context::default();
        let mut shell = shell();
        crate::test_support::render_in(&ctx, [900.0, 600.0], |ui| shell.ui(ui, |ui, _| screen(ui)));
        assert!(crate::i18n::is_installed(&ctx));
    }

    #[test]
    fn the_shell_keeps_an_installed_language() {
        use crate::i18n::{Language, LanguageSettings};
        let ctx = egui::Context::default();
        let ja = LanguageSettings {
            language: Language::Explicit("ja".into()),
        };
        crate::i18n::install(&ctx, &ja);
        let mut shell = shell();
        crate::test_support::render_in(&ctx, [900.0, 600.0], |ui| shell.ui(ui, |ui, _| screen(ui)));
        assert_eq!(crate::i18n::current(&ctx).to_string(), "ja");
    }

    #[test]
    fn hover_text_follows_the_language() {
        use crate::i18n::{Language, LanguageSettings};
        let ctx = egui::Context::default();
        crate::i18n::register(&ctx, T);
        let shell = Shell::new(vec![Destination::new(
            Screen::Entries,
            crate::icons::settings(),
            "t-entries",
        )]);
        let set = |tag: &str| {
            crate::i18n::install(
                &ctx,
                &LanguageSettings {
                    language: Language::Explicit(tag.into()),
                },
            )
        };
        set("en");
        assert_eq!(shell.label_text(&ctx, 0), "Entries");
        set("ja");
        assert_eq!(shell.label_text(&ctx, 0), "é …ç›®");
    }

    /// Lay `shell` out over two frames of a `size` screen whose system bars take `safe`,
    /// with `ui` clear of them by `own` already; returns the rect the open screen got.
    fn render_safe(
        shell: &mut Shell<Screen>,
        size: [f32; 2],
        safe: egui::epaint::MarginF32,
        own: egui::epaint::MarginF32,
    ) -> egui::Rect {
        let ctx = egui::Context::default();
        let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(size[0], size[1]));
        let mut drawn = egui::Rect::NOTHING;
        for _ in 0..2 {
            let input = egui::RawInput {
                screen_rect: Some(rect),
                safe_area_insets: Some(egui::SafeAreaInsets(safe)),
                ..Default::default()
            };
            let mut output = ctx.run_ui(input, |ui| {
                let inner = ui.max_rect() - own;
                ui.scope_builder(egui::UiBuilder::new().max_rect(inner), |ui| {
                    shell.ui(ui, |ui, _| {
                        drawn = ui.available_rect_before_wrap();
                        screen(ui);
                    })
                });
            });
            output.textures_delta.clear();
        }
        drawn
    }

    fn margin(left: f32, top: f32, right: f32, bottom: f32) -> egui::epaint::MarginF32 {
        egui::epaint::MarginF32 {
            left,
            right,
            top,
            bottom,
        }
    }

    #[test]
    fn narrow_it_keeps_clear_of_the_status_bar_and_the_home_indicator() {
        // An iPhone upright: the status bar and the dynamic island, the home indicator.
        let mut shell = shell().with_footer(prefs());
        let drawn = render_safe(
            &mut shell,
            [400.0, 800.0],
            margin(0.0, 62.0, 0.0, 34.0),
            egui::epaint::MarginF32::ZERO,
        );
        assert_eq!(drawn.top(), 62.0);
        let button = shell.footer_rects[0];
        assert!(button.bottom() <= 800.0 - 34.0, "{button:?}");
        // The bar sits right above the indicator: its fill runs on under it.
        assert!(button.bottom() > 800.0 - 34.0 - 12.0, "{button:?}");
        assert!(drawn.bottom() <= button.top(), "{drawn:?} {button:?}");
    }

    #[test]
    fn wide_it_keeps_clear_of_the_notch_and_the_home_indicator() {
        // An iPhone on its side: the notch on the left, the home indicator below.
        let mut shell = shell().with_footer(prefs());
        let drawn = render_safe(
            &mut shell,
            [900.0, 400.0],
            margin(59.0, 0.0, 59.0, 21.0),
            egui::epaint::MarginF32::ZERO,
        );
        let button = shell.footer_rects[0];
        assert!(button.left() >= 59.0, "{button:?}");
        assert!(button.bottom() <= 400.0 - 21.0, "{button:?}");
        assert!(drawn.right() <= 900.0 - 59.0, "{drawn:?}");
        assert!(drawn.bottom() <= 400.0 - 21.0, "{drawn:?}");
    }

    #[test]
    fn a_margin_the_app_already_keeps_is_not_doubled() {
        let safe = margin(0.0, 62.0, 0.0, 34.0);
        let mut shell = shell().with_footer(prefs());
        let drawn = render_safe(&mut shell, [400.0, 800.0], safe, safe);
        assert_eq!(drawn.top(), 62.0);
        let button = shell.footer_rects[0];
        assert!(button.bottom() > 800.0 - 34.0 - 12.0, "{button:?}");
    }

    #[test]
    fn with_only_a_footer_it_opens_on_the_footer() {
        let shell = Shell::new(vec![]).with_footer(prefs());
        assert_eq!(shell.current(), Some(Screen::Prefs));
    }

    /// The action first, then eight screens of their own names, with the footer.
    fn crowded_shell() -> Shell<Screen> {
        const NAMES: [&str; 8] = ["s0", "s1", "s2", "s3", "s4", "s5", "s6", "s7"];
        let mut items: Vec<RailItem<Screen>> =
            vec![Action::new("new", crate::icons::plus(), "new-entry").into()];
        items.extend(
            NAMES.iter().map(|&name| {
                Destination::new(Screen::Entries, crate::icons::settings(), name).into()
            }),
        );
        Shell::from_items(items).with_footer(prefs())
    }

    /// `shell` on a `size` screen, with a 12-point foot, and a status bar when `status`.
    /// Returns the foot's rect.
    fn crowded(shell: &mut Shell<Screen>, size: [f32; 2], status: bool) -> egui::Rect {
        let mut foot = egui::Rect::NOTHING;
        render(size, |ui| {
            let dot = |ui: &mut egui::Ui| {
                foot = ui
                    .allocate_exact_size(egui::vec2(12.0, 12.0), egui::Sense::click())
                    .0;
                None
            };
            if status {
                shell.ui_with_status(ui, dot, |ui| drop(ui.label("saved")), |ui, _| screen(ui));
            } else {
                shell.ui_with_foot(ui, dot, |ui, _| screen(ui));
            }
        });
        foot
    }

    #[test]
    fn items_and_actions_mix_in_the_apps_order() {
        let mut shell = crowded_shell();
        assert_eq!(
            shell.current(),
            Some(Screen::Entries),
            "the first screen, not the action"
        );
        crowded(&mut shell, [914.0, 900.0], true);
        assert_eq!(shell.cell_rects.len(), 9);
        assert_eq!(
            shell.cell_rects[0], shell.action_rects[0],
            "the action on top"
        );
        assert!(!shell.footer_in_menu);
        assert!(shell.footer_rects[0].is_positive());
        assert_eq!(shell.more_rect, egui::Rect::NOTHING, "no menu when all fit");
    }

    #[test]
    fn a_crowded_bar_puts_the_more_button_where_the_footer_was() {
        for width in [320.0, 360.0, 411.0] {
            let mut shell = crowded_shell();
            let foot = crowded(&mut shell, [width, 700.0], false);
            let (cells, more) = (&shell.cell_rects, shell.more_rect);
            assert!(
                !cells.is_empty() && cells.len() < 9,
                "{width}: {}",
                cells.len()
            );
            assert!(shell.footer_in_menu, "{width}");
            assert!(
                shell.footer_rects.is_empty(),
                "{width}: the footer is in the menu"
            );
            for rect in cells.iter().chain([&more, &foot]) {
                assert!(rect.is_positive(), "{width}: {rect:?}");
                assert!(
                    rect.left() >= 0.0 && rect.right() <= width,
                    "{width}: {rect:?}"
                );
            }
            // In order, and none on top of the next.
            let row: Vec<egui::Rect> = cells.iter().copied().chain([more, foot]).collect();
            for pair in row.windows(2) {
                assert!(pair[0].right() <= pair[1].left(), "{width}: {pair:?}");
            }
            // Every button keeps its full size, and they line up.
            for rect in cells.iter().chain([&more]) {
                assert_eq!(rect.size(), egui::vec2(BUTTON, BUTTON), "{width}: {rect:?}");
                assert_eq!(rect.center().y, more.center().y, "{width}: {rect:?}");
            }
        }
    }

    #[test]
    fn a_low_rail_keeps_its_items_clear_of_the_more_button() {
        // A phone on its side (#29), a short desktop window, one shorter still.
        for (height, status) in [(411.0, true), (411.0, false), (300.0, true), (160.0, false)] {
            let mut shell = crowded_shell();
            let foot = crowded(&mut shell, [914.0, height], status);
            let (cells, more) = (&shell.cell_rects, shell.more_rect);
            let case = format!("{height} {status}");
            assert!(cells.len() < 9, "{case}: {}", cells.len());
            assert!(
                shell.footer_rects.is_empty(),
                "{case}: the footer is in the menu"
            );
            assert!(more.is_positive(), "{case}");
            let column: Vec<egui::Rect> = cells.iter().copied().chain([more]).collect();
            for pair in column.windows(2) {
                assert!(pair[0].bottom() <= pair[1].top(), "{case}: {pair:?}");
            }
            if !status {
                // The foot sits above the More button, at the rail's foot.
                let last = cells.last().copied().unwrap_or(egui::Rect::NOTHING);
                assert!(last.bottom() <= foot.top(), "{case}: {last:?} {foot:?}");
                assert!(foot.bottom() <= more.top(), "{case}: {foot:?} {more:?}");
            }
        }
    }

    #[test]
    fn at_every_height_the_footer_or_the_more_button_holds_the_end() {
        let mut both = (false, false);
        for height in (200..=900).step_by(10) {
            let height = height as f32;
            let mut shell = crowded_shell();
            crowded(&mut shell, [914.0, height], true);
            let cells = &shell.cell_rects;
            let end = if shell.footer_in_menu {
                both.1 = true;
                assert!(cells.len() < 9, "{height}");
                assert!(shell.footer_rects.is_empty(), "{height}");
                shell.more_rect
            } else {
                both.0 = true;
                assert_eq!(cells.len(), 9, "{height}: all fit, or the footer goes");
                assert_eq!(shell.more_rect, egui::Rect::NOTHING, "{height}");
                shell.footer_rects[0]
            };
            assert!(end.is_positive(), "{height}");
            for pair in cells
                .iter()
                .copied()
                .chain([end])
                .collect::<Vec<_>>()
                .windows(2)
            {
                assert!(pair[0].bottom() <= pair[1].top(), "{height}: {pair:?}");
            }
        }
        assert_eq!(
            both,
            (true, true),
            "the sweep crosses from one to the other"
        );
    }

    fn keys(shell: &Shell<Screen>) -> Vec<String> {
        shell.rail_order().order
    }

    #[test]
    fn the_rail_order_round_trips_and_skips_names_it_does_not_know() {
        let mut shell = crowded_shell();
        assert_eq!(keys(&shell)[..3], ["new", "s0", "s1"]);
        let order = RailOrder {
            order: vec!["s3".into(), "gone".into(), "new".into(), "s1".into()],
            hidden: vec!["s1".into(), "gone".into()],
        };
        shell.set_rail_order(&order);
        // The named first, the action among them, then the rest in the app's order.
        assert_eq!(
            keys(&shell),
            ["s3", "new", "s1", "s0", "s2", "s4", "s5", "s6", "s7"]
        );
        assert_eq!(shell.rail_order().hidden, ["s1"]);
        let again = shell.rail_order();
        shell.set_rail_order(&again);
        assert_eq!(shell.rail_order(), again);
        shell.set_rail_order(&RailOrder::default());
        assert_eq!(
            keys(&shell)[..3],
            ["new", "s0", "s1"],
            "the default is the app's"
        );
    }

    #[test]
    fn with_actions_still_puts_them_last() {
        let shell =
            shell().with_actions(vec![Action::new("new", crate::icons::plus(), "new-entry")]);
        assert_eq!(keys(&shell), ["entries", "summary", "new"]);
    }

    #[test]
    fn a_hidden_item_sends_the_footer_into_the_menu() {
        let mut shell = shell().with_footer(prefs()).with_rail_order(&RailOrder {
            order: vec![],
            hidden: vec!["entries".into()],
        });
        for size in SIZES {
            render(size, |ui| shell.ui(ui, |ui, _| screen(ui)));
            assert_eq!(shell.on_rail, [1], "{size:?}");
            assert!(shell.footer_in_menu, "{size:?}");
            assert_eq!(
                shell.menu_rows(),
                [Row::Footer(0), Row::Slot(0)],
                "{size:?}: the footer first"
            );
        }
    }

    /// Run `shell` on a 900 × 600 screen in `ctx`; clicking at `at` when given.
    fn frames(ctx: &egui::Context, shell: &mut Shell<Screen>, at: Option<egui::Pos2>) {
        let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(900.0, 600.0));
        let frame = |events: Vec<egui::Event>, shell: &mut Shell<Screen>| {
            let input = egui::RawInput {
                screen_rect: Some(rect),
                events,
                ..Default::default()
            };
            let mut output = ctx.run_ui(input, |ui| shell.ui(ui, |ui, _| screen(ui)));
            output.textures_delta.clear();
        };
        let Some(pos) = at else {
            frame(vec![], shell);
            frame(vec![], shell);
            return;
        };
        let button = |pressed| egui::Event::PointerButton {
            pos,
            button: egui::PointerButton::Primary,
            pressed,
            modifiers: egui::Modifiers::NONE,
        };
        frame(vec![egui::Event::PointerMoved(pos)], shell);
        frame(vec![button(true)], shell);
        frame(vec![button(false)], shell);
        frame(vec![], shell);
    }

    #[test]
    fn the_menu_opens_what_is_off_the_rail() {
        let mut shell = shell().with_footer(prefs()).with_rail_order(&RailOrder {
            order: vec![],
            hidden: vec!["summary".into()],
        });
        let ctx = egui::Context::default();
        frames(&ctx, &mut shell, None);
        let at = shell.more_rect.center();
        frames(&ctx, &mut shell, Some(at));
        assert_eq!(
            shell.menu_rects.len(),
            2,
            "the footer and the hidden screen"
        );
        let at = shell.menu_rects[1].center();
        frames(&ctx, &mut shell, Some(at));
        assert_eq!(shell.current(), Some(Screen::Summary));
        let at = shell.more_rect.center();
        frames(&ctx, &mut shell, Some(at));
        let at = shell.menu_rects[0].center();
        frames(&ctx, &mut shell, Some(at));
        assert_eq!(shell.current(), Some(Screen::Prefs));
    }

    #[test]
    fn the_shell_lists_its_items_and_takes_the_order_asked_for() {
        let ctx = egui::Context::default();
        let mut shell = crowded_shell();
        frames(&ctx, &mut shell, None);
        let listed = published(&ctx).unwrap();
        assert_eq!(listed.len(), 9);
        assert_eq!(listed[0].key, "new");
        request(
            &ctx,
            RailOrder {
                order: vec!["s7".into()],
                hidden: vec!["new".into()],
            },
        );
        frames(&ctx, &mut shell, None);
        assert_eq!(keys(&shell)[0], "s7");
        assert_eq!(shell.rail_order().hidden, ["new"]);
        assert_eq!(published(&ctx).unwrap()[0].key, "s7");
    }

    #[cfg(feature = "serde")]
    #[test]
    fn the_rail_order_is_taken_from_the_store_and_saved_there() {
        use crate::store::{self, Store, Stored};
        let dir = tempfile::tempdir().unwrap();
        let file = Store::at(dir.path().join(store::FILE_NAME));
        let saved = RailOrder {
            order: vec!["summary".into(), "entries".into()],
            hidden: vec![],
        };
        file.save(&Stored {
            look: None,
            rail: Some(saved.clone()),
            side: None,
        })
        .unwrap();
        let ctx = egui::Context::default();
        store::attach(&ctx, file.clone());
        let mut shell = shell();
        frames(&ctx, &mut shell, None);
        assert_eq!(shell.rail_order(), saved);

        request(
            &ctx,
            RailOrder {
                order: vec!["entries".into(), "summary".into()],
                hidden: vec![],
            },
        );
        frames(&ctx, &mut shell, None);
        assert_eq!(
            file.load().and_then(|s| s.rail).map(|r| r.order),
            Some(vec!["entries".to_owned(), "summary".to_owned()])
        );
    }

    /// An app whose screens and side pane share its state: the draft an action begins, and
    /// what was drawn.
    #[derive(Default)]
    struct Notes {
        draft: Option<String>,
        screens: Vec<Screen>,
        sides: Vec<Screen>,
        status: bool,
    }

    impl ShellApp<Screen> for Notes {
        fn screen_ui(&mut self, ui: &mut egui::Ui, screen: Screen, _: &mut Side) {
            self.screens.push(screen);
            egui::CentralPanel::default().show(ui, |ui| ui.label("screen"));
        }

        fn side_ui(&mut self, ui: &mut egui::Ui, screen: Screen, side: &mut Side) {
            self.sides.push(screen);
            if let Some(draft) = &mut self.draft {
                ui.text_edit_singleline(draft);
                if ui.button("save").clicked() {
                    self.draft = None;
                    side.close();
                }
            }
        }

        fn status_ui(&mut self, ui: &mut egui::Ui) {
            self.status = true;
            ui.label("ready");
        }

        fn action(&mut self, id: &'static str, side: &mut Side) {
            assert_eq!(id, "new");
            self.draft = Some(String::new());
            side.open();
        }
    }

    fn notes_shell() -> Shell<Screen> {
        Shell::from_items(vec![
            Action::new("new", crate::icons::plus(), "new-entry").into(),
            Destination::new(Screen::Entries, crate::icons::settings(), "entries").into(),
            Destination::new(Screen::Summary, crate::icons::arrow_left(), "summary").into(),
        ])
        .with_footer(prefs())
        .with_side_pane()
        .with_status_bar()
    }

    /// Two frames of `app` in `shell` on a `size` screen in `ctx`, then a click at `at`.
    fn show(
        ctx: &egui::Context,
        shell: &mut Shell<Screen>,
        app: &mut Notes,
        size: [f32; 2],
        at: Option<egui::Pos2>,
    ) {
        let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(size[0], size[1]));
        let mut frame = |events: Vec<egui::Event>| {
            let input = egui::RawInput {
                screen_rect: Some(rect),
                events,
                ..Default::default()
            };
            let mut output = ctx.run_ui(input, |ui| shell.show(ui, app));
            output.textures_delta.clear();
        };
        frame(vec![]);
        frame(vec![]);
        if let Some(pos) = at {
            let button = |pressed| egui::Event::PointerButton {
                pos,
                button: egui::PointerButton::Primary,
                pressed,
                modifiers: egui::Modifiers::NONE,
            };
            frame(vec![egui::Event::PointerMoved(pos)]);
            frame(vec![button(true)]);
            frame(vec![button(false)]);
            frame(vec![]);
        }
    }

    #[test]
    fn wide_the_side_pane_is_beside_every_screen() {
        let ctx = egui::Context::default();
        let (mut shell, mut app) = (notes_shell(), Notes::default());
        for screen in [Screen::Entries, Screen::Summary, Screen::Prefs] {
            app.sides.clear();
            shell.open(screen);
            show(&ctx, &mut shell, &mut app, SIZES[0], None);
            assert_eq!(app.sides.last(), Some(&screen), "{screen:?}");
            assert_eq!(app.screens.last(), Some(&screen), "{screen:?}");
        }
        assert!(app.status, "the status bar is drawn");
    }

    #[test]
    fn an_action_begins_an_entry_in_the_side_pane() {
        // Wide, beside the screen; on a phone, in its place.
        for (size, in_place) in [(SIZES[0], false), (SIZES[1], true)] {
            let ctx = egui::Context::default();
            let (mut shell, mut app) = (notes_shell(), Notes::default());
            show(&ctx, &mut shell, &mut app, size, None);
            let at = shell.action_rects[0].center();
            show(&ctx, &mut shell, &mut app, size, Some(at));
            assert_eq!(app.draft.as_deref(), Some(""), "{size:?}");
            assert_eq!(
                shell.current(),
                Some(Screen::Entries),
                "{size:?}: the screen stays"
            );
            app.screens.clear();
            app.sides.clear();
            show(&ctx, &mut shell, &mut app, size, None);
            assert!(!app.sides.is_empty(), "{size:?}");
            assert_eq!(app.screens.is_empty(), in_place, "{size:?}");
        }
    }

    #[test]
    fn without_a_side_pane_side_ui_is_never_called() {
        let ctx = egui::Context::default();
        let mut shell =
            shell().with_actions(vec![Action::new("new", crate::icons::plus(), "new-entry")]);
        let mut app = Notes::default();
        show(&ctx, &mut shell, &mut app, SIZES[0], None);
        let at = shell.action_rects[0].center();
        show(&ctx, &mut shell, &mut app, SIZES[0], Some(at));
        assert!(app.draft.is_some(), "the action still reaches the app");
        assert!(app.sides.is_empty());
        assert!(!app.status, "no status bar unless asked for");
    }

    #[cfg(feature = "serde")]
    #[test]
    fn the_side_column_is_kept_in_the_store() {
        use crate::store::{self, Store};
        let dir = tempfile::tempdir().unwrap();
        let file = Store::at(dir.path().join(store::FILE_NAME));
        let ctx = egui::Context::default();
        store::attach(&ctx, file.clone());
        let (mut shell, mut app) = (notes_shell(), Notes::default());
        show(&ctx, &mut shell, &mut app, SIZES[0], None);
        assert_eq!(
            file.load().and_then(|s| s.side),
            None,
            "nothing changed yet"
        );
        shell.pane.as_mut().unwrap().set_column(false);
        show(&ctx, &mut shell, &mut app, SIZES[0], None);
        assert_eq!(
            file.load().and_then(|s| s.side).map(|s| s.column),
            Some(false)
        );

        // The next start.
        let ctx = egui::Context::default();
        store::attach(&ctx, file);
        let (mut shell, mut app) = (notes_shell(), Notes::default());
        show(&ctx, &mut shell, &mut app, SIZES[0], None);
        assert!(!shell.pane.as_ref().unwrap().column());
    }

    #[test]
    fn a_roomy_bar_keeps_full_size_buttons() {
        let mut shell = shell().with_footer(prefs());
        render(SIZES[1], |ui| shell.ui(ui, |ui, _| screen(ui)));
        assert_eq!(shell.cell_rects.len(), 2);
        for rect in &shell.cell_rects {
            assert_eq!(rect.size(), egui::vec2(BUTTON, BUTTON), "{rect:?}");
        }
    }

    /// Render `shell` with a status bar at `size`: where the foot was drawn, and whether
    /// the status was.
    fn with_status(shell: &mut Shell<Screen>, size: [f32; 2]) -> (egui::Rect, bool) {
        let (mut foot, mut status) = (egui::Rect::NOTHING, false);
        render(size, |ui| {
            shell.ui_with_status(
                ui,
                |ui| {
                    foot = ui.label("dot").rect;
                    None
                },
                |ui| {
                    status = true;
                    ui.label("saved");
                },
                |ui, _| screen(ui),
            )
        });
        (foot, status)
    }

    #[test]
    fn wide_the_status_bar_holds_the_status_and_the_foot() {
        let mut shell = shell().with_footer(prefs());
        let (foot, status) = with_status(&mut shell, SIZES[0]);
        assert!(status);
        // On the bar along the bottom, at its right end: not at the rail's foot.
        assert!(foot.bottom() > SIZES[0][1] - 30.0, "{foot:?}");
        assert!(foot.left() > SIZES[0][0] / 2.0, "{foot:?}");
        // The rail stops above the bar.
        assert!(
            shell.footer_rects[0].bottom() < foot.top(),
            "{:?}",
            shell.footer_rects
        );
    }

    #[test]
    fn narrow_there_is_no_status_bar_and_the_foot_stays_on_the_bar() {
        let mut shell = shell().with_footer(prefs());
        let (foot, status) = with_status(&mut shell, SIZES[1]);
        assert!(!status);
        assert!(foot.is_positive());
        let bar_top = shell.footer_rects[0].top();
        assert!(foot.top() >= bar_top - 10.0, "{foot:?} beside {bar_top}");
    }

    #[test]
    fn with_nothing_there_is_nothing_to_draw() {
        let mut shell: Shell<Screen> = Shell::new(vec![]);
        assert_eq!(shell.current(), None);
        for size in SIZES {
            render(size, |ui| shell.ui(ui, |_, s| panic!("{s:?} drawn")));
        }
    }
}