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
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
//! The application shell: layout, focus, the event loop and global bindings.
//!
//! The shell knows nothing about what any panel displays. It owns the grid, the
//! focus ring, the frames and the tick schedule, and forwards everything else
//! through the [`Panel`] trait.
use std::path::PathBuf;
use std::time::{Duration, Instant};
use anyhow::{Context, Result};
use ratatui::DefaultTerminal;
use ratatui::crossterm::event::{
self, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers, MouseEvent, MouseEventKind,
};
use ratatui::layout::{Constraint, Layout, Position, Rect};
use ratatui::style::{Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, BorderType, Borders, Clear, Padding, Paragraph, Wrap};
use crate::config::Config;
use crate::frame::{Binding, FrameSpec};
use crate::panel::{KeyOutcome, Panel, RenderContext};
use crate::state::UiState;
use crate::theme::Gradients;
/// Global bindings, used for both the status bar and the help overlay.
const GLOBAL: &[Binding] = &[
Binding::primary("Tab", "focus"),
Binding::primary("?", "keys"),
Binding::primary("q", "quit"),
// After `quit` deliberately. The status bar shows as many primary bindings
// as fit, in order, and on a narrow terminal knowing how to get out beats
// knowing how to add a panel. The unused-widget notice names this key
// anyway, which is where someone actually needs to be told about it.
Binding::primary("w", "panels"),
Binding::extra("Shift+Tab", "focus back"),
Binding::extra("1-9", "jump to panel"),
Binding::extra("Ctrl+←/→", "resize width"),
Binding::extra("Ctrl+↑/↓", "resize height"),
Binding::extra("Ctrl+C", "quit"),
];
/// The text of `lines` with the styling dropped, for measuring.
///
/// Only the characters decide how text wraps, so a measurement does not need
/// the spans — but it does need them concatenated in order, which is why this
/// is not simply the first span of each line.
fn plain_text(lines: &[Line<'_>]) -> String {
lines
.iter()
.map(|line| {
line.spans
.iter()
.map(|span| span.content.as_ref())
.collect::<String>()
})
.collect::<Vec<_>>()
.join("\n")
}
/// How long a run of resize keystrokes must be quiet before the layout is
/// written back.
///
/// Long enough to sit out key auto-repeat, short enough that closing the window
/// a moment later still keeps the change.
const RESIZE_SETTLE: Duration = Duration::from_millis(750);
/// Smallest weight a panel or row may be squeezed to.
const MIN_WEIGHT: u16 = 1;
/// Split `total` cells across `weights`, giving no slot more than its maximum
/// and handing what it declines to the slots that can still use it.
///
/// A clock cannot use a hundred columns; a calendar cannot use more than its
/// months need. Pure proportional layout gives them the space anyway and they
/// sit in it, while the task list next door runs out of room. So a panel may
/// declare the point past which more space does nothing for it, and the surplus
/// moves sideways to a neighbour that will actually fill it.
///
/// When *every* slot is bounded there is nobody left who can use the surplus,
/// and it is spread back across the whole row rather than left unallocated:
/// panels draw their own frames, so a gap would show as a hole in the middle of
/// the dashboard. Better every panel slightly over its maximum than a seam.
///
/// The emphasis on *spread* is the fix for a real bug. The surplus used to be
/// handed to the slots that could still grow without re-capping them, so on the
/// next pass they were over their own maxima, nobody could absorb it, and the
/// loop broke leaving the whole overshoot on one panel. On the shipped default
/// layout at 400 columns that gave the clock 302 of them — and the clock's
/// numerals stop growing at 158, so about 145 columns were literally blank
/// while the weather panel beside it sat at 51 and the task list below ran out
/// of room. It only appeared once the terminal was wider than the row's maxima
/// summed, which is why nothing caught it until someone opened a 4K terminal.
fn distribute(total: u16, weights: &[u16], maxima: &[Option<u16>]) -> Vec<u16> {
let count = weights.len();
if count == 0 || total == 0 {
return vec![0; count];
}
let mut sizes = proportional(total, weights);
// Each pass caps whoever is over and re-splits what they gave up. Bounded
// by the slot count: every pass either caps at least one more slot or ends,
// because a slot only receives surplus while it is still under its maximum.
for _ in 0..count {
let mut surplus: u32 = 0;
for i in 0..count {
if let Some(max) = maxima[i]
&& sizes[i] > max
{
surplus += u32::from(sizes[i] - max);
sizes[i] = max;
}
}
if surplus == 0 {
break;
}
// `surplus` was summed out of `sizes`, which sums to `total`.
let surplus = u16::try_from(surplus).unwrap_or(u16::MAX);
let takers: Vec<usize> = (0..count)
.filter(|&i| maxima[i].is_none_or(|max| sizes[i] < max))
.collect();
if takers.is_empty() {
// Every slot is at its declared maximum and there are still cells
// to place. Spread them across the row in proportion, so the
// overshoot is shared rather than landing entirely on whichever
// slot happened to be uncapped last.
for (i, extra) in proportional(surplus, weights).into_iter().enumerate() {
sizes[i] = sizes[i].saturating_add(extra);
}
break;
}
let taker_weights: Vec<u16> = takers.iter().map(|&i| weights[i].max(1)).collect();
for (slot, extra) in takers.iter().zip(proportional(surplus, &taker_weights)) {
sizes[*slot] = sizes[*slot].saturating_add(extra);
}
// A taker may now be over its own maximum; the next pass caps it.
}
sizes
}
/// Split `total` in proportion to `weights`, losing no cells to rounding.
///
/// Largest-remainder rather than plain division: dividing and truncating leaves
/// up to one cell per slot unallocated, which shows up as a ragged right edge.
fn proportional(total: u16, weights: &[u16]) -> Vec<u16> {
let count = weights.len();
if count == 0 {
return Vec::new();
}
let sum: u32 = weights.iter().map(|w| u32::from((*w).max(1))).sum();
if sum == 0 {
return vec![0; count];
}
let mut sizes = Vec::with_capacity(count);
let mut remainders: Vec<(u32, usize)> = Vec::with_capacity(count);
let mut used: u32 = 0;
for (index, weight) in weights.iter().enumerate() {
let exact = u32::from(total) * u32::from((*weight).max(1));
let whole = exact / sum;
remainders.push((exact % sum, index));
used += whole;
sizes.push(u16::try_from(whole).unwrap_or(u16::MAX));
}
// Hand the leftover cells to the largest remainders, ties by position so
// the result is stable frame to frame.
remainders.sort_by(|a, b| b.0.cmp(&a.0).then(a.1.cmp(&b.1)));
let mut leftover = u32::from(total).saturating_sub(used);
for (_, index) in remainders {
if leftover == 0 {
break;
}
sizes[index] = sizes[index].saturating_add(1);
leftover -= 1;
}
sizes
}
/// The index to trade space with: the next one along, or the previous one when
/// `index` is last. `None` when there is nobody to trade with.
fn neighbour_of(index: usize, len: usize) -> Option<usize> {
if len < 2 {
return None;
}
if index + 1 < len {
Some(index + 1)
} else {
index.checked_sub(1)
}
}
/// The panels of a layout, with the `(row, column)` each came from.
type Built = (Vec<Slot>, Vec<(usize, usize)>);
/// A panel plus its tick bookkeeping.
struct Slot {
/// Which widget this is, so a layout change can carry the panel across
/// rather than rebuilding it. Kept on the slot because the config's
/// `[layout]` has already been mutated by the time a rebuild runs, so it
/// no longer says what the *current* panels are.
widget: String,
panel: Box<dyn Panel>,
/// When this panel last ticked. `None` until it has, which is what makes
/// the first tick fire immediately.
///
/// Deliberately not "now minus a day": `Instant` on Windows is a duration
/// since boot, so `checked_sub` there returns `None` on a machine up for
/// less than that and the `unwrap` was a hard panic before the terminal
/// was even initialised. `network.rs` already solved the same "the first
/// sample is not meaningful" problem this way.
last_tick: Option<Instant>,
/// Interior rectangle the panel was last drawn into, used to route mouse
/// events. `None` until the first draw, and while the panel is too small
/// to render at all — in both cases there is nothing to click.
area: Option<Rect>,
}
/// The running dashboard.
///
/// The flags are genuinely independent — an overlay being open says nothing
/// about whether the layout needs writing — so grouping them into a struct to
/// satisfy the lint would add a name without adding a meaning.
#[allow(clippy::struct_excessive_bools)]
pub struct App {
config: Config,
gradients: Gradients,
slots: Vec<Slot>,
/// `(row, column)` in `config.layout` for each slot, so a resize knows
/// which weights the focused panel is made of. Built alongside `slots`
/// rather than recomputed, because a widget that fails to build leaves a
/// hole and the two would drift apart.
positions: Vec<(usize, usize)>,
focus: usize,
show_help: bool,
/// First visible line of the help overlay.
help_scroll: u16,
/// How far the help overlay can scroll, and how tall its viewport is — both
/// measured during the render that laid it out, because both depend on the
/// terminal width the text wrapped at. Zero overflow is also what tells the
/// key handler to leave the arrow keys alone and close on anything.
help_overflow: u16,
help_viewport: u16,
should_quit: bool,
/// Widgets available but not placed by this layout.
///
/// A config written by an earlier version silently lacks every widget added
/// since — an absent widget is a valid choice, so nothing errors and
/// `--migrate-config` has nothing to fix. This is the only way to find out.
unused_widgets: Vec<&'static str>,
/// Whether the startup hint is still on screen. Cleared by the first input
/// of any kind: a dashboard you leave open all day must not nag, and a
/// notice that will not go away is a nag.
show_widget_hint: bool,
/// A newer version, if the opt-in check found one. Empty otherwise, and
/// empty always when the check is off — `App` never starts it, so no test
/// and no `--print-config` run can reach the network.
update: crate::update::Found,
/// Whether the update notice is still on screen. Retired by the first
/// keypress, exactly like the widget hint: a dashboard you leave open all
/// day must not nag, and a notice that will not go away is a nag.
show_update_hint: bool,
/// The panel picker, while it is open.
picker: Option<crate::picker::Picker>,
/// The config file, so layout changes can be written back to it. `None` in
/// tests, which is what keeps them off a real user's config.
config_path: Option<PathBuf>,
/// When the last `Ctrl+arrow` landed, if one is still unwritten.
last_resize: Option<Instant>,
/// Whether the layout has been changed since it was last written.
layout_dirty: bool,
/// Why the last layout write failed, if it did. Shown in the picker: a
/// change you made that silently did not persist is the worst outcome here.
layout_error: Option<String>,
/// Where to write remembered preferences, once someone asks for that.
/// `None` in tests, which is what keeps them off a real user's file.
state_path: Option<PathBuf>,
/// The last state written, so a keypress that changed nothing writes
/// nothing.
saved_state: UiState,
/// What the config file itself says. Preferences are recorded as the
/// difference from this, which is what lets one be un-set.
baseline: UiState,
}
impl std::fmt::Debug for App {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("App")
.field("panels", &self.slots.len())
.field("focus", &self.focus)
.finish_non_exhaustive()
}
}
impl App {
/// Build every panel named in the layout, in row-major order.
pub fn new(config: Config) -> Result<Self> {
let (slots, positions) = Self::build_slots(&config)?;
let gradients = config.theme.gradients();
let unused_widgets = crate::widgets::unused_widgets(&config);
Ok(Self {
config,
gradients,
slots,
positions,
focus: 0,
show_help: false,
help_scroll: 0,
help_overflow: 0,
help_viewport: 0,
should_quit: false,
show_widget_hint: !unused_widgets.is_empty(),
update: crate::update::Found::default(),
show_update_hint: true,
unused_widgets,
picker: None,
config_path: None,
last_resize: None,
layout_dirty: false,
layout_error: None,
state_path: None,
saved_state: UiState::default(),
baseline: UiState::default(),
})
}
/// Build one panel per entry in the layout, in row-major order.
fn build_slots(config: &Config) -> Result<Built> {
let mut slots = Vec::new();
let mut positions = Vec::new();
for (row_index, row) in config.layout.rows.iter().enumerate() {
for (column_index, entry) in row.panels.iter().enumerate() {
let panel = crate::widgets::build(&entry.widget, config)
.with_context(|| format!("building the `{}` panel", entry.widget))?;
if let Some(panel) = panel {
slots.push(Slot {
widget: entry.widget.clone(),
panel,
last_tick: None,
area: None,
});
positions.push((row_index, column_index));
}
}
}
anyhow::ensure!(
!slots.is_empty(),
"no panels were built; check the `[layout]` table in your config"
);
Ok((slots, positions))
}
/// Reconcile the panels with a changed layout, carrying across every panel
/// that is still placed.
///
/// This used to throw every panel away and remake them all, on the grounds
/// that a beat of re-fetching reads as the dashboard responding. That was
/// wrong, and the demo recording is what showed it: **start the pomodoro,
/// toggle an unrelated panel, and the timer resets to 25:00.** A running
/// timer is not a cache that can be refilled — it is the user's state, and
/// nothing about switching the network panel off says to discard it. The
/// weather and stocks panels lost their readings the same way and spent a
/// fetch cycle showing "loading" after any toggle.
///
/// A panel is matched to a layout entry by widget name. Nothing stops a
/// hand-written config placing the same widget twice — `validate` checks
/// that names are *known*, not that they are unique — so the surviving
/// panels are consumed from a pool rather than looked up, and a second
/// `clocks` entry gets a second panel rather than the same one twice.
///
/// Two orderings matter here:
///
/// 1. Every genuinely new panel is built **before** any existing one is
/// disturbed, so a layout that will not build leaves the running
/// dashboard exactly as it was. That was already true and is preserved.
/// 2. Panels are shut down only once the new arrangement is settled, and
/// only the ones actually leaving. Dropping them without `shutdown`
/// discards the task store's save-on-shutdown and leaks the fetch
/// threads.
///
/// This is only ever called after a `[layout]` edit, so no panel's *own*
/// config can have changed underneath it. A caller that changes, say,
/// `[weather].units` cannot use this — the carried-over panel would keep
/// the old setting.
fn rebuild_panels(&mut self) -> Result<()> {
use std::collections::{HashMap, VecDeque};
let desired: Vec<(usize, usize, String)> = self
.config
.layout
.rows
.iter()
.enumerate()
.flat_map(|(row, entry)| {
entry
.panels
.iter()
.enumerate()
.map(move |(column, panel)| (row, column, panel.widget.clone()))
})
.collect();
// What the live panels can supply, by name.
let mut spare: HashMap<&str, usize> = HashMap::new();
for slot in &self.slots {
*spare.entry(slot.widget.as_str()).or_default() += 1;
}
// Build only what cannot be carried across. Any failure returns here,
// with `self` untouched.
let mut fresh: HashMap<String, VecDeque<Box<dyn Panel>>> = HashMap::new();
let mut placed = 0usize;
for (_, _, widget) in &desired {
if let Some(count) = spare.get_mut(widget.as_str())
&& *count > 0
{
*count -= 1;
placed += 1;
continue;
}
let panel = crate::widgets::build(widget, &self.config)
.with_context(|| format!("building the `{widget}` panel"))?;
if let Some(panel) = panel {
fresh.entry(widget.clone()).or_default().push_back(panel);
placed += 1;
}
}
// Checked before anything is taken apart, so a layout that would leave
// nothing on screen is refused rather than applied.
anyhow::ensure!(
placed > 0,
"no panels were built; check the `[layout]` table in your config"
);
let focused = self.slots.get(self.focus).map(|slot| slot.widget.clone());
let mut pool: HashMap<String, VecDeque<Slot>> = HashMap::new();
for slot in std::mem::take(&mut self.slots) {
pool.entry(slot.widget.clone()).or_default().push_back(slot);
}
let mut slots = Vec::with_capacity(placed);
let mut positions = Vec::with_capacity(placed);
for (row, column, widget) in desired {
let carried = pool.get_mut(&widget).and_then(VecDeque::pop_front);
let slot = carried.or_else(|| {
fresh
.get_mut(&widget)
.and_then(VecDeque::pop_front)
.map(|panel| Slot {
widget: widget.clone(),
panel,
last_tick: None,
area: None,
})
});
if let Some(mut slot) = slot {
// The panel is almost certainly somewhere else on screen now,
// and `area` is what mouse events are matched against. Cleared
// rather than trusted until the next draw sets it.
slot.area = None;
slots.push(slot);
positions.push((row, column));
}
}
// Whatever is left was removed from the layout.
for (_, leaving) in pool {
for mut slot in leaving {
slot.panel.shutdown();
}
}
// Follow the focused panel to wherever it ended up, rather than leaving
// the highlight on whatever now occupies its old index.
self.focus = focused
.and_then(|widget| slots.iter().position(|slot| slot.widget == widget))
.unwrap_or_else(|| self.focus.min(slots.len().saturating_sub(1)));
self.slots = slots;
self.positions = positions;
self.unused_widgets = crate::widgets::unused_widgets(&self.config);
Ok(())
}
/// Run until the user quits.
pub fn run(&mut self, terminal: &mut DefaultTerminal) -> Result<()> {
let tick_rate = Duration::from_millis(self.config.general.tick_rate_ms.clamp(16, 5_000));
// Redraw only when something actually changed. Mouse reporting makes
// this matter: the terminal sends an event for every cell the pointer
// crosses, and drawing on each one would have a dashboard left open all
// day burning CPU whenever the mouse passes over it.
let mut dirty = true;
while !self.should_quit {
if dirty {
terminal.draw(|frame| self.render(frame))?;
dirty = false;
}
if event::poll(tick_rate)? {
match event::read()? {
// Only react to presses; on Windows every key also emits a
// release event, which would otherwise double every action.
Event::Key(key) if key.kind == KeyEventKind::Press => {
self.handle_key(key);
// Only keys can move a preference, and only after one
// has been handled can it have moved. Cheap because it
// compares before writing: an arrow key costs a struct
// comparison, not a file.
self.persist_preferences();
dirty = true;
}
Event::Mouse(mouse) => dirty |= self.handle_mouse(mouse),
// Resize re-runs layout against the new frame size, which
// is the next draw's job — but that draw has to happen.
Event::Resize(_, _) => dirty = true,
_ => {}
}
}
dirty |= self.tick_panels();
// Resizes are batched rather than written per keystroke —
// `Ctrl+arrow` auto-repeats, and rewriting the config on every
// repeat would be absurd — but they are not batched all the way to
// exit any more. Closing the terminal window is a normal way to
// stop a dashboard you leave open all day, and it never reaches the
// code below: the process is signalled and the pending resize is
// gone. This settles once the repeats stop, which is the earliest
// moment the write is not wasted.
//
// Deliberately not a signal handler. The only thing at risk is this
// one write, `SIGKILL` cannot be caught anyway, and the terminal
// does not need restoring when the terminal is what went away.
if self.layout_dirty
&& self
.last_resize
.is_some_and(|at| at.elapsed() >= RESIZE_SETTLE)
{
self.write_layout();
self.last_resize = None;
}
}
for slot in &mut self.slots {
slot.panel.shutdown();
}
// Once more on the way out, in case the last thing changed was not a
// key — and because Ctrl+C reaches here too.
self.persist_preferences();
self.write_layout();
Ok(())
}
/// Remember preferences to `path` from now on.
///
/// Separate from [`App::new`] so that tests, which build apps constantly,
/// cannot write to a real user's state file by forgetting to opt out. An
/// app with no path set simply never persists.
///
/// `loaded` is what was read from that file, so startup does not rewrite a
/// file it has just read. `baseline` is what the *config* says, taken before
/// the loaded values were folded in — every write is the difference between
/// the panels and that.
pub fn remember_preferences_at(&mut self, path: PathBuf, loaded: UiState, baseline: UiState) {
self.saved_state = loaded;
self.baseline = baseline;
self.state_path = Some(path);
}
/// The preferences that differ from the config, which is all that is worth
/// recording.
///
/// Panels report their current values unconditionally; the comparison is
/// here, once, so a value set back to what the config says drops out of the
/// file instead of leaving the earlier change asserted for ever.
fn collect_preferences(&self) -> UiState {
let mut current = UiState::default();
for slot in &self.slots {
slot.panel.remember(&mut current);
}
current.only_changes_from(&self.baseline)
}
/// Write preferences if any of them moved.
///
/// A failed write is deliberately not surfaced. There is no panel that owns
/// this to show an error in, and the failure costs a sort order that one
/// keystroke restores — putting a warning on a dashboard designed to be
/// left open, over that, would be the wrong trade. Task and note saves,
/// which can lose something you cannot retype, do surface theirs.
fn persist_preferences(&mut self) {
let Some(path) = self.state_path.clone() else {
return;
};
let current = self.collect_preferences();
if current == self.saved_state {
return;
}
if current.save(&path).is_ok() {
self.saved_state = current;
}
}
/// Tick any panel whose refresh interval has elapsed.
///
/// Returns whether any panel ticked, and so whether the screen may now be
/// out of date.
/// Tick every panel whose interval has elapsed, and report whether any of
/// them said something a viewer could see had changed.
///
/// The distinction is the whole point, and getting it wrong is invisible in
/// a screenshot and enormous in a profile. This used to return "some
/// panel's timer fired", which the run loop OR'd straight into `dirty`.
/// Measured on the shipped nine-panel default at 400x100: **243 redraws a
/// minute**, and the same 243 whether `show_seconds` was on or off — so
/// with seconds off the dashboard repainted 243 times to show content that
/// changed once.
fn tick_panels(&mut self) -> bool {
let now = Instant::now();
let mut changed = false;
for slot in &mut self.slots {
let due = slot
.last_tick
.is_none_or(|last| now.duration_since(last) >= slot.panel.refresh_interval());
if due {
// Not `changed |= slot.panel.tick()`: `|=` short-circuits once
// the accumulator is true, and a panel that stops being ticked
// stops updating. The operand order is load-bearing.
changed = slot.panel.tick() || changed;
slot.last_tick = Some(now);
}
}
changed
}
/// True when the focused panel is in a text-entry or modal state and global
/// bindings must not fire.
fn focus_captures_input(&self) -> bool {
self.slots
.get(self.focus)
.is_some_and(|slot| slot.panel.captures_input())
}
fn handle_key(&mut self, key: KeyEvent) {
// Any key at all retires the startup hint. It has been read or it has
// been ignored; either way it has had its turn.
self.show_widget_hint = false;
self.show_update_hint = false;
let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
// Ctrl+C always quits, even mid-form, because a terminal user expects
// it to and there is no state we would lose: panels save as they go.
if ctrl && matches!(key.code, KeyCode::Char('c')) {
self.should_quit = true;
return;
}
// The help overlay swallows the next key, whatever it is — except the
// ones that scroll it, because on an 80x24 terminal the focused panel's
// own bindings do not fit and a key that cannot be reached is a key
// that does not exist. Scrolling only binds when there is something
// below the fold, so on a tall terminal any key still closes it.
if self.show_help {
if self.help_overflow > 0 {
let page = self.help_viewport.max(1);
let moved = match key.code {
KeyCode::Down | KeyCode::Char('j') => Some(self.help_scroll.saturating_add(1)),
KeyCode::Up | KeyCode::Char('k') => Some(self.help_scroll.saturating_sub(1)),
KeyCode::PageDown => Some(self.help_scroll.saturating_add(page)),
KeyCode::PageUp => Some(self.help_scroll.saturating_sub(page)),
KeyCode::Home => Some(0),
KeyCode::End => Some(self.help_overflow),
_ => None,
};
if let Some(to) = moved {
self.help_scroll = to.min(self.help_overflow);
return;
}
}
self.show_help = false;
return;
}
// The picker is a real dialog rather than a notice, so it reads keys
// instead of dismissing on any of them.
if self.picker.is_some() {
self.handle_picker_key(key);
return;
}
// Resizing is a shell-level concern, the way it is in tmux, so it is
// claimed before panels get a look. It has to be: the calendar binds
// the bare arrow keys and does not inspect modifiers, so offering the
// key onward first would have Ctrl+Left scroll the month instead.
//
// A panel in a text-entry state still vetoes it, under the same rule
// that stops `q` quitting mid-form.
if ctrl && !self.focus_captures_input() {
let resized = match key.code {
KeyCode::Right => self.resize_width(true),
KeyCode::Left => self.resize_width(false),
KeyCode::Down => self.resize_height(true),
KeyCode::Up => self.resize_height(false),
_ => return self.dispatch_key(key),
};
// Only a resize that actually moved something needs writing. Held
// against a minimum, the key repeats without changing anything, and
// marking those dirty would write the config on shutdown after a
// session that changed nothing.
self.layout_dirty |= resized;
if resized {
self.last_resize = Some(Instant::now());
}
// Swallowed either way: a resize that hit the minimum is still a
// resize key, and must not fall through to a panel binding.
return;
}
self.dispatch_key(key);
}
/// Act on whatever the picker made of a keypress.
fn handle_picker_key(&mut self, key: KeyEvent) {
let Some(picker) = self.picker.as_mut() else {
return;
};
match picker.handle_key(key) {
crate::picker::Action::None => {}
crate::picker::Action::Toggle(name) => self.toggle_widget(name),
crate::picker::Action::Close => {
self.picker = None;
// Written on close rather than on every toggle: someone trying
// three arrangements should cost one write, not three, and the
// dialog is a natural commit point.
self.write_layout();
}
}
}
/// Turn a widget on or off, rebuilding the dashboard around it.
fn toggle_widget(&mut self, widget: &str) {
let before = self.config.layout.clone();
if self.config.layout.places(widget) {
if !self.config.layout.remove_widget(widget) {
// The last panel. An empty layout is rejected at startup, so
// allowing this would write a config that cannot be opened.
self.layout_error = Some("at least one panel has to stay".into());
return;
}
} else {
self.config.layout.add_widget(widget);
}
if let Err(e) = self.rebuild_panels() {
// Put it back. A layout that will not build is a reason to refuse
// the toggle, not to leave the dashboard in pieces.
self.config.layout = before;
let _ = self.rebuild_panels();
self.layout_error = Some(format!("{e:#}"));
return;
}
self.layout_error = None;
self.layout_dirty = true;
}
/// Write the layout back into the config file, if it changed.
///
/// Textual, so comments and formatting survive; see [`crate::layout_edit`].
/// A failure is kept and shown rather than swallowed — a panel you switched
/// on that quietly fails to persist is worse than one that never appeared,
/// because you will not find out until the next start.
fn write_layout(&mut self) {
if !self.layout_dirty {
return;
}
let Some(path) = self.config_path.clone() else {
return;
};
// Atomic, like every other file mirador writes. This used to be a bare
// `fs::write`, which is the one place it mattered most: the target is
// the user's own config, complete with the comments they may have edited
// and the ones mirador wrote to explain itself, and a crash or a full
// disk part-way through a plain overwrite leaves them a truncated file
// and nothing to recover from.
let result = std::fs::read_to_string(&path)
.map_err(anyhow::Error::from)
.and_then(|source| crate::layout_edit::apply(&source, &self.config.layout))
.and_then(|updated| crate::store::write_atomic(&path, &updated));
match result {
Ok(()) => {
self.layout_dirty = false;
self.layout_error = None;
}
Err(e) => self.layout_error = Some(format!("{e:#}")),
}
}
/// Write layout changes to `path` from now on.
///
/// Separate from [`App::new`] for the same reason the state path is: tests
/// build apps constantly and must not be able to touch a real config.
pub fn write_layout_to(&mut self, path: PathBuf) {
self.config_path = Some(path);
}
/// Offer a key to the focused panel, then to the global bindings.
fn dispatch_key(&mut self, key: KeyEvent) {
// Offer the key to the focused panel first.
if let Some(slot) = self.slots.get_mut(self.focus)
&& slot.panel.handle_key(key) == KeyOutcome::Consumed
{
return;
}
// A panel in a modal state gets an absolute veto on global bindings, so
// typing "q" into a task title cannot quit the dashboard.
if self.focus_captures_input() {
return;
}
match key.code {
// `q` and Ctrl+C only. Esc used to quit here, undocumented — while
// the task panel prints "Nothing matches this filter. Esc to
// clear." A panel consumes Esc only while its filter is non-empty,
// so the same key in the same panel one keystroke apart either
// cleared the filter or killed the dashboard, and nothing on screen
// said which. Esc means "back out of something" everywhere else.
KeyCode::Char('q') => self.should_quit = true,
KeyCode::Tab => self.cycle_focus(true),
KeyCode::BackTab => self.cycle_focus(false),
KeyCode::Char('?') => {
self.show_help = true;
// Opening it always starts at the top; the bindings for the
// panel you just focused are the reason you pressed `?`.
self.help_scroll = 0;
}
KeyCode::Char('w') => self.picker = Some(crate::picker::Picker::new()),
KeyCode::Char(c @ '1'..='9') => {
let index = c as usize - '1' as usize;
if index < self.slots.len() {
self.focus = index;
}
}
_ => {}
}
}
/// Move `step` weight from `donor` to `taker` within a set of weights,
/// leaving the total untouched.
///
/// Keeping the total fixed is what makes this feel like tmux: widening one
/// panel narrows its neighbour and nothing else on screen moves. Scaling a
/// single weight instead would silently reflow every other panel in the row.
fn transfer(weights: &mut [u16], taker: usize, donor: usize) -> bool {
let total: u32 = weights.iter().map(|w| u32::from(*w)).sum();
// Step with the scale of the config rather than a fixed number of
// units: weights are relative, so `width = 60` and `width = 3` are both
// legitimate ways to write the same layout.
let step = u16::try_from(total / 50).unwrap_or(1).max(1);
let (Some(&grows), Some(&shrinks)) = (weights.get(taker), weights.get(donor)) else {
return false;
};
// Never squeeze a panel out of existence — a panel that vanished could
// not be focused, and so could not be given its space back.
let step = step.min(shrinks.saturating_sub(MIN_WEIGHT));
if step == 0 {
return false;
}
weights[taker] = grows.saturating_add(step);
weights[donor] = shrinks - step;
true
}
/// Widen or narrow the focused panel against its neighbour in the row.
fn resize_width(&mut self, grow: bool) -> bool {
let Some(&(row, column)) = self.positions.get(self.focus) else {
return false;
};
let Some(entry) = self.config.layout.rows.get_mut(row) else {
return false;
};
// Borrow from the panel to the right, or from the left when the focused
// panel is last in its row.
let Some(neighbour) = neighbour_of(column, entry.panels.len()) else {
return false;
};
let mut weights: Vec<u16> = entry.panels.iter().map(|p| p.width).collect();
let (taker, donor) = if grow {
(column, neighbour)
} else {
(neighbour, column)
};
if !Self::transfer(&mut weights, taker, donor) {
return false;
}
for (panel, weight) in entry.panels.iter_mut().zip(weights) {
panel.width = weight;
}
true
}
/// Grow or shrink the focused panel's row against the neighbouring row.
fn resize_height(&mut self, grow: bool) -> bool {
let Some(&(row, _)) = self.positions.get(self.focus) else {
return false;
};
let rows = &mut self.config.layout.rows;
let Some(neighbour) = neighbour_of(row, rows.len()) else {
return false;
};
let mut weights: Vec<u16> = rows.iter().map(|r| r.height).collect();
let (taker, donor) = if grow {
(row, neighbour)
} else {
(neighbour, row)
};
if !Self::transfer(&mut weights, taker, donor) {
return false;
}
for (entry, weight) in rows.iter_mut().zip(weights) {
entry.height = weight;
}
true
}
/// The panel whose interior contains this point, if any.
fn panel_at(&self, column: u16, row: u16) -> Option<usize> {
self.slots.iter().position(|slot| {
slot.area
.is_some_and(|area| area.contains(Position::new(column, row)))
})
}
/// Route a mouse event, returning whether the screen needs redrawing.
///
/// Click focuses the panel under the pointer and is then offered to it;
/// scroll is offered to the panel under the pointer *without* moving focus,
/// so running the wheel over a list does not yank the keyboard away from
/// whatever the user was working in.
fn handle_mouse(&mut self, event: MouseEvent) -> bool {
let interesting = matches!(
event.kind,
MouseEventKind::Down(_) | MouseEventKind::ScrollUp | MouseEventKind::ScrollDown
);
if !interesting {
// Motion and button-release arrive constantly and mean nothing
// here. Returning false is what keeps the redraw loop quiet.
return false;
}
// A deliberate click or scroll retires the startup hint, as a key does.
// Pointer motion deliberately does not: the mouse crossing the window
// on its way somewhere else is not the user reading anything.
let had_hint =
std::mem::take(&mut self.show_widget_hint) | std::mem::take(&mut self.show_update_hint);
// The help overlay swallows the next input, whatever it is — the same
// rule keys follow.
if self.show_help {
self.show_help = false;
return true;
}
// A panel in a text-entry or modal state gets the same absolute veto
// over the mouse that it has over global keys: a stray click must not
// pull focus out of a half-typed task and strand the form.
if self.focus_captures_input() {
let focus = self.focus;
let Some(area) = self.slots.get(focus).and_then(|slot| slot.area) else {
return had_hint;
};
if !area.contains(Position::new(event.column, event.row)) {
return had_hint;
}
let consumed = self
.slots
.get_mut(focus)
.is_some_and(|slot| slot.panel.handle_mouse(event, area) == KeyOutcome::Consumed);
return consumed || had_hint;
}
let Some(index) = self.panel_at(event.column, event.row) else {
return had_hint;
};
let focus_moved = if matches!(event.kind, MouseEventKind::Down(_)) {
let moved = self.focus != index;
self.focus = index;
moved
} else {
false
};
let Some(slot) = self.slots.get_mut(index) else {
return focus_moved || had_hint;
};
let Some(area) = slot.area else {
return focus_moved || had_hint;
};
let consumed = slot.panel.handle_mouse(event, area) == KeyOutcome::Consumed;
consumed || focus_moved || had_hint
}
/// Move focus one panel forward or backward, wrapping at both ends.
fn cycle_focus(&mut self, forward: bool) {
let len = self.slots.len();
if len == 0 {
return;
}
self.focus = if forward {
(self.focus + 1) % len
} else {
(self.focus + len - 1) % len
};
}
/// The slot index of the panel at `(row, column)` of the layout.
fn slot_at(&self, row: usize, column: usize) -> Option<usize> {
self.positions.iter().position(|p| *p == (row, column))
}
/// Compute one rectangle per panel, in the same row-major order as
/// `self.slots`.
///
/// Two passes of [`distribute`]: heights down the rows, then widths across
/// each row. Both honour the panels' declared maxima, so a panel that
/// cannot use more space passes it to one that can.
fn geometry(&self, area: Rect) -> Vec<Rect> {
let rows = &self.config.layout.rows;
let row_weights: Vec<u16> = rows.iter().map(|row| row.height.max(1)).collect();
// A row is only bounded when every panel in it is: they share the
// height, so one unbounded panel keeps the whole row unbounded.
let row_maxima: Vec<Option<u16>> = rows
.iter()
.enumerate()
.map(|(row_index, row)| {
let mut tallest = 0u16;
for column in 0..row.panels.len() {
let max = self
.slot_at(row_index, column)
.and_then(|slot| self.slots[slot].panel.max_height())?;
tallest = tallest.max(max);
}
(tallest > 0).then_some(tallest)
})
.collect();
let heights = distribute(area.height, &row_weights, &row_maxima);
// Indexed by slot, not by layout column, and written through `slot_at`.
// Pushing one rect per column assumes every layout entry produced a
// panel; a single entry that did not shifts every later slot onto the
// previous entry's rectangle, which is what `slot.area` hit-tests, so
// clicks land on the wrong panel. A slot that gets no rectangle keeps
// the zero one and is skipped by the caller's size check.
let mut rects = vec![Rect::default(); self.slots.len()];
let mut y = area.y;
for (row_index, row) in rows.iter().enumerate() {
let height = heights.get(row_index).copied().unwrap_or(0);
let widths: Vec<u16> = row.panels.iter().map(|p| p.width.max(1)).collect();
let maxima: Vec<Option<u16>> = (0..row.panels.len())
.map(|column| {
self.slot_at(row_index, column)
.and_then(|slot| self.slots[slot].panel.max_width())
})
.collect();
let columns = distribute(area.width, &widths, &maxima);
let mut x = area.x;
for (column, width) in columns.into_iter().enumerate() {
if let Some(slot) = self.slot_at(row_index, column) {
rects[slot] = Rect::new(x, y, width, height);
}
x = x.saturating_add(width);
}
y = y.saturating_add(height);
}
rects
}
/// Which row the open picker is on, for tests that drive it by keystroke.
#[cfg(test)]
fn picker_row(&self) -> Option<usize> {
self.picker.as_ref().map(crate::picker::Picker::selected)
}
/// Test-only access to the private render pass.
#[cfg(test)]
pub fn render_for_test(&mut self, frame: &mut ratatui::Frame) {
self.render(frame);
}
fn render(&mut self, frame: &mut ratatui::Frame) {
let area = frame.area();
let body = if self.config.general.show_status_bar && area.height > 1 {
let parts = Layout::vertical([Constraint::Min(1), Constraint::Length(1)]).split(area);
self.render_status_bar(frame, parts[1]);
parts[0]
} else {
area
};
let rects = self.geometry(body);
let theme = self.config.theme.clone();
let focus = self.focus;
for (index, slot) in self.slots.iter_mut().enumerate() {
// Cleared first so a panel that fails to draw this pass cannot keep
// catching clicks at the place it used to be.
slot.area = None;
let Some(rect) = rects.get(index).copied() else {
continue;
};
if rect.width == 0 || rect.height == 0 {
continue;
}
let focused = index == focus;
let title = slot.panel.title();
let spec = FrameSpec {
title: &title,
counter: slot.panel.counter(),
focused,
bindings: slot.panel.bindings(),
index: index + 1,
};
let inner = crate::frame::draw(frame, rect, &theme, &spec);
if inner.width == 0 || inner.height == 0 {
continue;
}
slot.area = Some(inner);
slot.panel.render(
frame,
inner,
RenderContext {
theme: &theme,
gradients: &self.gradients,
focused,
},
);
}
if self.show_help {
self.render_help(frame, area);
}
if let Some(picker) = &self.picker {
picker.render(
frame,
area,
&self.config.theme,
|name| self.config.layout.places(name),
self.layout_error.as_deref(),
);
}
}
/// The status bar carries *global* bindings only.
///
/// Panel bindings live in the focused panel's own border, which keeps the
/// two scopes visually separate. A flat list of both teaches users to press
/// panel keys while the wrong panel is focused.
fn render_status_bar(&self, frame: &mut ratatui::Frame, area: Rect) {
let theme = &self.config.theme;
let key_style = Style::default().fg(theme.key).add_modifier(Modifier::BOLD);
let muted = Style::default().fg(theme.muted);
let mut spans = vec![Span::styled(
" mirador",
Style::default()
.fg(theme.accent)
.add_modifier(Modifier::BOLD),
)];
for binding in GLOBAL.iter().filter(|b| b.primary) {
spans.push(Span::styled(" ", muted));
spans.push(Span::styled(binding.key, key_style));
spans.push(Span::styled(format!(" {}", binding.action), muted));
}
// The hint rides on the right of the bar it shares with the global
// keys, and gives way to them when the terminal is too narrow: knowing
// how to quit matters more than knowing what you are not using.
if let Some(hint) = self.update_hint().or_else(|| self.widget_hint()) {
let used: usize = spans
.iter()
.map(|s| crate::grid::display_width(&s.content))
.sum();
let hint_width = crate::grid::display_width(&hint);
let total = usize::from(area.width);
// One space of breathing room on each side of the gap.
if used + hint_width + 3 <= total {
spans.push(Span::styled(
" ".repeat(total - used - hint_width - 1),
muted,
));
spans.push(Span::styled(hint, Style::default().fg(theme.label)));
}
}
frame.render_widget(Paragraph::new(Line::from(spans)), area);
}
/// The one-line startup notice about widgets this layout does not place.
/// Watch `found` for a newer version from now on.
///
/// Separate from [`App::new`] for the same reason the state path is: tests
/// build apps constantly, and none of them should be able to start a
/// network request by accident.
pub fn watch_for_updates(&mut self, found: crate::update::Found) {
self.update = found;
}
/// The update notice, if there is one and it has not been dismissed.
///
/// Takes precedence over the unused-widget hint when both apply: this one
/// is rarer, is actionable now, and stops being true the moment you act on
/// it, where the widget hint is the same every launch until you change your
/// layout.
fn update_hint(&self) -> Option<String> {
if !self.show_update_hint {
return None;
}
let latest = match self.update.lock() {
Ok(guard) => guard.clone(),
Err(poisoned) => poisoned.into_inner().clone(),
}?;
Some(format!("mirador {latest} is out mirador-update "))
}
fn widget_hint(&self) -> Option<String> {
if !self.show_widget_hint || self.unused_widgets.is_empty() {
return None;
}
// Names the key rather than only the widgets. Saying what is missing
// without saying what to do about it is how someone ends up reading the
// help, not finding the answer there either, and going to look for a
// config file.
Some(format!(
"{} unused: {} press w ",
self.unused_widgets.len(),
self.unused_widgets.join(", ")
))
}
fn render_help(&mut self, frame: &mut ratatui::Frame, area: Rect) {
let theme = self.config.theme.clone();
let theme = &theme;
let key_style = Style::default().fg(theme.key).add_modifier(Modifier::BOLD);
let muted = Style::default().fg(theme.muted);
let section = |title: &str| {
Line::from(Span::styled(
crate::glyphs::utility(title),
Style::default()
.fg(theme.label)
.add_modifier(Modifier::BOLD),
))
};
let entry = |binding: &Binding| {
Line::from(vec![
Span::styled(format!(" {:<12}", binding.key), key_style),
Span::styled(binding.action.to_string(), muted),
])
};
let mut lines = vec![section("global")];
lines.extend(GLOBAL.iter().map(entry));
// Bindings are grouped by the panel they belong to, so it is always
// clear which panel a key acts on.
if let Some(slot) = self.slots.get(self.focus) {
let panel_keys = slot.panel.bindings();
if !panel_keys.is_empty() {
lines.push(Line::from(""));
lines.push(section(&slot.panel.title()));
lines.extend(panel_keys.iter().map(entry));
}
}
// The durable half of the unused-widget hint. The status bar notice is
// gone after one keypress; this stays, because `?` is where someone
// goes when they wonder what else the thing does.
if !self.unused_widgets.is_empty() {
lines.push(Line::from(""));
lines.push(section("widgets not in your layout"));
// The actionable line comes before the list because it is the more
// useful of the two if only one is on screen. The names go on one
// wrapped line because one line per widget cost eight rows on a
// stale config.
lines.push(Line::from(vec![
Span::styled(" press ", muted),
Span::styled("w", key_style),
Span::styled(" to switch them on", muted),
]));
lines.push(Line::from(Span::styled(
format!(" {}", self.unused_widgets.join(", ")),
Style::default().fg(theme.text),
)));
}
// The footer is rendered separately and pinned to the last row, rather
// than being the last line of the scrolling text. A hint saying how to
// close the overlay is no use once it has scrolled out of the overlay.
let width = 46.min(area.width);
let text_width = width.saturating_sub(crate::frame::FRAME_WIDTH).max(1);
// Measured after wrapping, not from `lines.len()`. The two differ
// whenever a line is longer than the popup, which the list of unused
// widgets routinely is — sizing from the unwrapped count is how the
// overlay came to be shorter than its own contents.
let text_height = crate::grid::wrapped_height(&plain_text(&lines), text_width);
let body = Paragraph::new(lines).wrap(Wrap { trim: false });
// Borders, the blank line, and the footer.
let chrome = 4;
let height = text_height.saturating_add(chrome).min(area.height);
let popup = crate::frame::centred(area, width, height);
frame.render_widget(Clear, popup);
let block = Block::default()
.borders(Borders::ALL)
.border_type(BorderType::Rounded)
.border_style(Style::default().fg(theme.border_focused))
.padding(Padding::horizontal(1))
.title_top(Line::from(vec![
Span::styled("┤", Style::default().fg(theme.border_focused)),
Span::styled(
"Keys",
Style::default()
.fg(theme.title)
.add_modifier(Modifier::BOLD),
),
Span::styled("├", Style::default().fg(theme.border_focused)),
]));
let inner = block.inner(popup);
frame.render_widget(block, popup);
if inner.height == 0 {
self.help_overflow = 0;
self.help_viewport = 0;
return;
}
// Give the footer the last row and the blank line the one above it,
// but never at the cost of showing no text at all.
let footer_rows = 2.min(inner.height.saturating_sub(1));
let viewport = Rect {
height: inner.height - footer_rows,
..inner
};
self.help_viewport = viewport.height;
self.help_overflow = text_height.saturating_sub(viewport.height);
// The terminal may have shrunk since the last frame, or the focused
// panel changed to one with fewer bindings.
self.help_scroll = self.help_scroll.min(self.help_overflow);
frame.render_widget(body.scroll((self.help_scroll, 0)), viewport);
if footer_rows > 0 {
let footer = Rect {
y: inner.y + inner.height - 1,
height: 1,
..inner
};
frame.render_widget(Paragraph::new(self.help_footer(theme)), footer);
}
}
/// The pinned last row of the help overlay.
///
/// It says how to close the overlay, and when there is more text than fits,
/// that scrolling is possible and where in the list you are. Without the
/// position there is no way to tell a full list from a truncated one.
fn help_footer(&self, theme: &crate::theme::Theme) -> Line<'static> {
let italic = Style::default()
.fg(theme.muted)
.add_modifier(Modifier::ITALIC);
if self.help_overflow == 0 {
return Line::from(Span::styled("any key to close", italic));
}
let key_style = Style::default().fg(theme.key).add_modifier(Modifier::BOLD);
let more_above = self.help_scroll > 0;
let more_below = self.help_scroll < self.help_overflow;
let arrows = match (more_above, more_below) {
(true, true) => "↑↓",
(true, false) => "↑",
_ => "↓",
};
Line::from(vec![
Span::styled(arrows, key_style),
Span::styled(
format!(
" {}/{} · any other key to close",
self.help_scroll + self.help_viewport,
self.help_overflow + self.help_viewport,
),
italic,
),
])
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::config::{Layout as LayoutConfig, LayoutPanel, LayoutRow};
/// A config whose layout is only panels that need no I/O.
fn config_with(widgets: &[&str]) -> Config {
Config {
layout: LayoutConfig {
rows: vec![LayoutRow {
height: 1,
panels: widgets
.iter()
.map(|w| LayoutPanel {
widget: (*w).to_string(),
width: 1,
})
.collect(),
}],
},
..Config::default()
}
}
/// A two-row layout with two panels in the first row, all on a 100 scale.
fn resizable() -> Config {
Config {
layout: LayoutConfig {
rows: vec![
LayoutRow {
height: 50,
panels: vec![
LayoutPanel {
widget: "clocks".into(),
width: 50,
},
LayoutPanel {
widget: "calendar".into(),
width: 50,
},
],
},
LayoutRow {
height: 50,
panels: vec![LayoutPanel {
widget: "cpu".into(),
width: 100,
}],
},
],
},
..Config::default()
}
}
fn widths(app: &App) -> Vec<u16> {
app.config.layout.rows[0]
.panels
.iter()
.map(|p| p.width)
.collect()
}
fn heights(app: &App) -> Vec<u16> {
app.config.layout.rows.iter().map(|r| r.height).collect()
}
#[test]
fn widening_a_panel_narrows_its_neighbour_and_holds_the_total() {
let mut app = App::new(resizable()).unwrap();
let before: u16 = widths(&app).iter().sum();
assert!(app.resize_width(true));
let after = widths(&app);
assert!(after[0] > 50, "focused panel must grow: {after:?}");
assert!(after[1] < 50, "its neighbour must give the space up");
assert_eq!(
after.iter().sum::<u16>(),
before,
"the row total must not drift, or every panel reflows"
);
}
#[test]
fn narrowing_is_the_exact_inverse_of_widening() {
let mut app = App::new(resizable()).unwrap();
let before = widths(&app);
assert!(app.resize_width(true));
assert!(app.resize_width(false));
assert_eq!(widths(&app), before);
}
#[test]
fn the_last_panel_in_a_row_borrows_from_the_one_before_it() {
let mut app = App::new(resizable()).unwrap();
app.focus = 1;
assert!(app.resize_width(true));
let after = widths(&app);
assert!(after[1] > 50, "the last panel must still be able to grow");
assert!(after[0] < 50);
}
#[test]
fn a_panel_alone_in_its_row_cannot_be_resized_horizontally() {
let mut app = App::new(resizable()).unwrap();
// The cpu panel is the only one in row 1; there is nobody to take
// space from, and stretching it alone would mean nothing.
app.focus = 2;
assert!(!app.resize_width(true));
assert!(!app.resize_width(false));
}
#[test]
fn resizing_height_trades_between_rows() {
let mut app = App::new(resizable()).unwrap();
let before: u16 = heights(&app).iter().sum();
assert!(app.resize_height(true));
let after = heights(&app);
assert!(after[0] > 50 && after[1] < 50, "{after:?}");
assert_eq!(after.iter().sum::<u16>(), before);
}
#[test]
fn a_panel_can_never_be_squeezed_out_of_existence() {
let mut app = App::new(resizable()).unwrap();
// Far more presses than it takes to consume the neighbour entirely.
for _ in 0..500 {
app.resize_width(true);
}
let after = widths(&app);
assert!(
after[1] >= MIN_WEIGHT,
"a panel squeezed to nothing can never be focused to get its space back: {after:?}"
);
assert_eq!(after.iter().sum::<u16>(), 100, "total still holds");
}
#[test]
fn resize_keys_are_claimed_before_the_focused_panel_sees_them() {
// The calendar binds bare Left/Right and ignores modifiers, so if the
// shell offered the key onward first, Ctrl+Left would scroll the month
// instead of resizing. Focus it and check the width actually moved.
let mut app = App::new(resizable()).unwrap();
app.focus = 1;
let before = widths(&app);
app.handle_key(KeyEvent::new(KeyCode::Left, KeyModifiers::CONTROL));
assert_ne!(widths(&app), before, "Ctrl+Left was swallowed by the panel");
}
#[test]
fn toggling_one_panel_leaves_the_others_untouched() {
// The bug the demo recording caught: `rebuild_panels` remade every
// panel, so switching the network panel off reset a running pomodoro to
// 25:00 and sent the weather and stocks panels back to "loading".
//
// Panels are compared by pointer identity — the same allocation before
// and after is the only thing that actually proves state survived,
// where comparing a rendered figure would pass for a panel that had
// been rebuilt and happened to look the same.
let mut app = App::new(config_with(&["clocks", "todo", "pomodoro"])).unwrap();
let before: Vec<*const u8> = app
.slots
.iter()
.map(|slot| std::ptr::from_ref(&*slot.panel).cast::<u8>())
.collect();
app.toggle_widget("pomodoro");
assert!(!app.config.layout.places("pomodoro"), "it went");
let after: Vec<*const u8> = app
.slots
.iter()
.map(|slot| std::ptr::from_ref(&*slot.panel).cast::<u8>())
.collect();
assert_eq!(after, before[..2], "the surviving panels were rebuilt");
// And back again: the two that never left are still the same panels.
app.toggle_widget("pomodoro");
assert!(app.config.layout.places("pomodoro"));
let again: Vec<*const u8> = app
.slots
.iter()
.take(2)
.map(|slot| std::ptr::from_ref(&*slot.panel).cast::<u8>())
.collect();
assert_eq!(again, before[..2], "re-adding a panel rebuilt the others");
}
#[test]
fn focus_follows_the_panel_rather_than_the_index() {
// Removing a panel to the left of the focused one shifts every later
// index down. Leaving `focus` where it was moves the highlight to a
// different panel, which gets noticed only when the next keypress goes
// somewhere unexpected.
//
// The indices are chosen so that clamping cannot pass by accident: with
// four panels and focus on the second, removing the first leaves the
// old `min(focus, len - 1)` pointing at the *third* widget.
let mut app = App::new(config_with(&["clocks", "todo", "pomodoro", "notes"])).unwrap();
app.focus = 1;
assert_eq!(app.slots[app.focus].widget, "todo");
app.toggle_widget("clocks");
assert_eq!(
app.slots[app.focus].widget, "todo",
"focus jumped to another panel"
);
}
#[test]
fn a_widget_placed_twice_gets_two_panels() {
// `Config::validate` checks that widget names are *known*, not that
// they are unique, so a hand-written config can place one twice.
// Matching panels to entries by name has to consume from a pool — a
// lookup would hand the same panel to both entries.
let mut config = config_with(&["clocks", "clocks", "todo"]);
config.layout.rows[0].panels[0].width = 30;
config.layout.rows[0].panels[1].width = 30;
config.layout.rows[0].panels[2].width = 40;
let mut app = App::new(config).unwrap();
assert_eq!(app.slots.len(), 3);
let distinct: std::collections::HashSet<*const u8> = app
.slots
.iter()
.map(|slot| std::ptr::from_ref(&*slot.panel).cast::<u8>())
.collect();
assert_eq!(distinct.len(), 3, "two entries share one panel");
// A rebuild must keep them distinct too.
app.toggle_widget("notes");
let distinct: std::collections::HashSet<*const u8> = app
.slots
.iter()
.map(|slot| std::ptr::from_ref(&*slot.panel).cast::<u8>())
.collect();
assert_eq!(distinct.len(), app.slots.len(), "a panel was reused twice");
}
#[test]
fn no_update_notice_until_something_finds_a_version() {
// `App` never starts a check itself. A dashboard built in a test — or
// by `--print-config` — must not be able to reach the network.
let mut app = App::new(config_with(&["clocks"])).unwrap();
assert_eq!(app.update_hint(), None);
app.watch_for_updates(std::sync::Arc::new(std::sync::Mutex::new(Some(
"9.9.9".to_string(),
))));
let hint = app.update_hint().expect("a found version should show");
assert!(hint.contains("9.9.9"), "got `{hint}`");
assert!(
hint.contains("mirador-update"),
"the notice must say what to do about it: `{hint}`"
);
}
#[test]
fn the_update_notice_retires_on_the_first_keypress() {
// Same rule as the widget hint. A dashboard left open all day must not
// keep telling you something you have already read.
let mut app = App::new(config_with(&["clocks"])).unwrap();
app.watch_for_updates(std::sync::Arc::new(std::sync::Mutex::new(Some(
"9.9.9".to_string(),
))));
assert!(app.update_hint().is_some());
app.handle_key(key(KeyCode::Tab));
assert_eq!(app.update_hint(), None, "the notice outlived a keypress");
}
#[test]
fn an_update_notice_displaces_the_widget_hint_rather_than_sharing_the_row() {
// Both want the right-hand end of the status bar. The update notice is
// rarer and stops being true once acted on, so it wins; the widget hint
// is unchanged every launch until the layout changes.
let mut app = App::new(config_with(&["clocks"])).unwrap();
assert!(app.widget_hint().is_some(), "this layout omits widgets");
app.watch_for_updates(std::sync::Arc::new(std::sync::Mutex::new(Some(
"9.9.9".to_string(),
))));
let shown = app.update_hint().or_else(|| app.widget_hint()).unwrap();
assert!(shown.contains("9.9.9"), "the widget hint won: `{shown}`");
}
#[test]
fn a_layout_missing_widgets_says_so_once_and_then_stops() {
let mut app = App::new(config_with(&["clocks"])).unwrap();
assert!(
app.unused_widgets.contains(&"stocks"),
"a widget the layout never places must be reported: {:?}",
app.unused_widgets
);
let hint = app.widget_hint().expect("the hint shows at startup");
assert!(hint.contains("stocks"), "got `{hint}`");
app.handle_key(KeyEvent::from(KeyCode::Char('?')));
assert!(
app.widget_hint().is_none(),
"a dashboard left open all day must not keep nagging"
);
}
#[test]
fn a_layout_using_everything_gets_no_hint_at_all() {
let config = Config {
layout: LayoutConfig {
rows: crate::widgets::WIDGET_NAMES
.iter()
.map(|name| LayoutRow {
height: 1,
panels: vec![LayoutPanel {
widget: (*name).to_string(),
width: 1,
}],
})
.collect(),
},
..Config::default()
};
let unused = crate::widgets::unused_widgets(&config);
assert!(unused.is_empty(), "nothing to suggest: {unused:?}");
}
#[test]
fn a_click_retires_the_hint_but_the_pointer_merely_passing_over_does_not() {
use ratatui::crossterm::event::MouseButton;
let mouse = |kind| MouseEvent {
kind,
column: 0,
row: 0,
modifiers: KeyModifiers::NONE,
};
let mut app = App::new(config_with(&["clocks"])).unwrap();
app.handle_mouse(mouse(MouseEventKind::Moved));
assert!(
app.widget_hint().is_some(),
"the mouse crossing the window is not the user reading anything"
);
app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left)));
assert!(app.widget_hint().is_none(), "a deliberate click retires it");
}
#[test]
fn retiring_the_hint_forces_a_redraw_so_it_actually_disappears() {
use ratatui::crossterm::event::MouseButton;
// A click landing on no panel at all still has to repaint, or the
// retired hint stays on screen until something else happens to redraw.
let mut app = App::new(config_with(&["clocks"])).unwrap();
let dirty = app.handle_mouse(MouseEvent {
kind: MouseEventKind::Down(MouseButton::Left),
column: 9_000,
row: 9_000,
modifiers: KeyModifiers::NONE,
});
assert!(dirty, "the hint was cleared, so the screen is out of date");
}
#[test]
fn the_help_overlay_renders_at_any_size_with_widgets_to_report() {
use ratatui::Terminal;
use ratatui::backend::TestBackend;
// The unused-widget section grows the overlay, and the overlay clips
// silently rather than erroring — so a size that cannot fit it must
// still draw something rather than panic on the arithmetic.
let mut app = App::new(config_with(&["clocks"])).unwrap();
app.handle_key(KeyEvent::from(KeyCode::Char('?')));
assert!(app.show_help);
for (width, height) in [(1, 1), (4, 3), (30, 8), (80, 24), (200, 60)] {
let mut terminal = Terminal::new(TestBackend::new(width, height)).unwrap();
terminal
.draw(|frame| app.render_for_test(frame))
.unwrap_or_else(|e| panic!("help failed to draw at {width}x{height}: {e}"));
}
}
#[test]
fn every_binding_of_the_focused_panel_is_reachable_on_an_80x24_terminal() {
use ratatui::Terminal;
use ratatui::backend::TestBackend;
// The tasks panel declares 17 bindings; with the global block, the
// section headings and the footer that is well past the 22 rows an
// 80x24 terminal leaves inside the overlay. It used to clip there
// silently, so about a third of the keys did not exist as far as
// anyone reading `?` could tell.
let mut app = App::new(config_with(&["todo"])).unwrap();
let bindings = app.slots[0].panel.bindings().len();
assert!(bindings > 4, "this test needs a panel with many bindings");
let mut terminal = Terminal::new(TestBackend::new(80, 24)).unwrap();
app.handle_key(KeyEvent::from(KeyCode::Char('?')));
terminal.draw(|frame| app.render_for_test(frame)).unwrap();
assert!(
app.help_overflow > 0,
"the overlay fits at 80x24, so this test no longer proves anything"
);
// Scroll to the bottom one key at a time, redrawing as a user would.
let mut guard = 0;
while app.help_scroll < app.help_overflow {
app.handle_key(KeyEvent::from(KeyCode::Down));
terminal.draw(|frame| app.render_for_test(frame)).unwrap();
assert!(app.show_help, "scrolling must not dismiss the overlay");
guard += 1;
assert!(guard < 200, "scrolling made no progress");
}
// The last row of text is on screen, and `End` and `Home` agree.
app.handle_key(KeyEvent::from(KeyCode::Home));
assert_eq!(app.help_scroll, 0);
app.handle_key(KeyEvent::from(KeyCode::End));
assert_eq!(app.help_scroll, app.help_overflow);
// Anything that is not a scroll key still closes it.
app.handle_key(KeyEvent::from(KeyCode::Char('x')));
assert!(
!app.show_help,
"a non-scroll key must still close the overlay"
);
}
#[test]
fn the_overlay_closes_on_any_key_when_it_all_fits() {
use ratatui::Terminal;
use ratatui::backend::TestBackend;
// Scrolling only binds the arrow keys when there is something below the
// fold. On a terminal with room to spare, `?` then Down must close,
// because that is what "any key to close" promises.
let mut app = App::new(config_with(&["clocks"])).unwrap();
let mut terminal = Terminal::new(TestBackend::new(120, 60)).unwrap();
app.handle_key(KeyEvent::from(KeyCode::Char('?')));
terminal.draw(|frame| app.render_for_test(frame)).unwrap();
assert_eq!(
app.help_overflow, 0,
"120x60 has room for the whole overlay"
);
app.handle_key(KeyEvent::from(KeyCode::Down));
assert!(!app.show_help);
}
#[test]
fn the_unused_widget_section_stays_a_fixed_size_however_many_are_unused() {
// One line per widget put eight rows into an overlay that clips
// silently; the names share a single wrapped line instead.
let one = App::new(config_with(&["clocks"])).unwrap();
let hint = one.widget_hint().expect("something is unused");
assert!(
hint.lines().count() == 1,
"the status hint must stay one line: `{hint}`"
);
}
#[test]
fn the_hint_gives_way_to_the_global_keys_on_a_narrow_terminal() {
use ratatui::Terminal;
use ratatui::backend::TestBackend;
let mut app = App::new(config_with(&["clocks"])).unwrap();
let row_text = |app: &mut App, width: u16| -> String {
let mut terminal = Terminal::new(TestBackend::new(width, 6)).unwrap();
terminal.draw(|frame| app.render_for_test(frame)).unwrap();
let buf = terminal.backend().buffer().clone();
(0..width).map(|x| buf[(x, 5)].symbol()).collect()
};
let wide = row_text(&mut app, 160);
assert!(wide.contains("unused"), "wide enough for both: `{wide}`");
let narrow = row_text(&mut app, 44);
assert!(
!narrow.contains("unused"),
"knowing how to quit outranks the hint: `{narrow}`"
);
assert!(
narrow.contains("quit"),
"the global keys survive: `{narrow}`"
);
}
#[test]
fn space_is_split_by_weight_when_nobody_declares_a_limit() {
assert_eq!(distribute(100, &[50, 50], &[None, None]), vec![50, 50]);
assert_eq!(distribute(100, &[25, 75], &[None, None]), vec![25, 75]);
}
#[test]
fn every_cell_is_allocated_however_the_weights_divide() {
// Truncating division would leave a ragged edge where the frames stop
// short of the terminal.
for total in [1u16, 7, 23, 80, 81, 199, 200] {
for weights in [vec![1, 1, 1], vec![34, 33, 33], vec![1, 2, 7]] {
let maxima = vec![None; weights.len()];
let sizes = distribute(total, &weights, &maxima);
assert_eq!(
sizes.iter().sum::<u16>(),
total,
"{total} across {weights:?} gave {sizes:?}"
);
}
}
}
#[test]
fn a_panel_that_cannot_use_more_space_hands_it_to_one_that_can() {
// The calendar case: bounded neighbour, unbounded list.
let sizes = distribute(100, &[50, 50], &[Some(30), None]);
assert_eq!(sizes, vec![30, 70], "the surplus must move sideways");
assert_eq!(sizes.iter().sum::<u16>(), 100);
}
#[test]
fn surplus_from_several_bounded_panels_lands_on_the_one_that_can_grow() {
let sizes = distribute(120, &[40, 40, 40], &[Some(20), Some(20), None]);
assert_eq!(sizes, vec![20, 20, 80]);
}
#[test]
fn surplus_is_shared_between_takers_in_proportion_to_their_weights() {
// Two unbounded panels, one twice the weight of the other.
let sizes = distribute(120, &[60, 20, 40], &[Some(30), None, None]);
assert_eq!(sizes.iter().sum::<u16>(), 120);
assert_eq!(sizes[0], 30, "the bounded one is capped");
assert!(
sizes[2] > sizes[1],
"the heavier taker gets more of it: {sizes:?}"
);
}
#[test]
fn a_row_of_entirely_bounded_panels_still_covers_its_full_width() {
// Nobody to hand the surplus to. Panels draw their own frames, so
// leaving cells unallocated would show as a hole in the dashboard —
// an over-wide panel is the lesser evil.
//
// Note this case is capped *before* redistribution, so it never reaches
// the path that was broken. `no_slot_exceeds_its_maximum_while_another`
// is the one that does; this one alone could not fail.
let sizes = distribute(200, &[50, 50], &[Some(30), Some(30)]);
assert_eq!(
sizes.iter().sum::<u16>(),
200,
"no gap may be left: {sizes:?}"
);
assert_eq!(sizes, vec![100, 100], "and the overshoot is shared");
}
#[test]
fn a_row_too_wide_for_its_maxima_shares_the_overshoot() {
// The invariant that actually distinguishes the fix from the bug.
//
// "Nobody exceeds their maximum while somebody is under theirs" is not
// enough: the buggy output [302, 47, 51] satisfies it, because 47 and
// 51 are exactly at their maxima rather than under. What it violates is
// that the *excess* be shared — [140, 0, 0] against weights
// [26, 34, 40] is not a proportional split of anything.
//
// The real default top row: clocks / calendar / weather, at every width
// from too-narrow to a 4K terminal.
let weights = [26u16, 34, 40];
let maxima = [Some(162u16), Some(47), Some(51)];
let ceiling: u16 = maxima.iter().map(|m| m.unwrap()).sum();
for total in (20u16..=1000).step_by(7) {
let sizes = distribute(total, &weights, &maxima);
assert_eq!(
sizes.iter().map(|s| u32::from(*s)).sum::<u32>(),
u32::from(total),
"the row must cover its width exactly at {total}: {sizes:?}"
);
if total <= ceiling {
// There is room to honour every maximum, so nobody may exceed.
for i in 0..3 {
assert!(
sizes[i] <= maxima[i].unwrap(),
"at {total}: slot {i} exceeded its maximum with room to \
spare — {sizes:?} against {maxima:?}"
);
}
continue;
}
// Past the ceiling everybody has to go over. The excess must track
// the weights, not land on one panel.
let excess: Vec<u16> = (0..3).map(|i| sizes[i] - maxima[i].unwrap()).collect();
let want = proportional(total - ceiling, &weights);
assert_eq!(
excess, want,
"at {total}: the overshoot is not shared — {sizes:?}, excess \
{excess:?}, expected {want:?}"
);
}
}
#[test]
fn a_wide_terminal_does_not_park_the_surplus_on_one_panel() {
// The specific regression, with the numbers from the bug report.
let sizes = distribute(400, &[26, 34, 40], &[Some(162), Some(47), Some(51)]);
assert_eq!(sizes.iter().sum::<u16>(), 400);
assert!(
sizes[0] < 250,
"the clock took the whole surplus again: {sizes:?}"
);
assert!(
sizes[2] > 51,
"the panel that could have used the space got none of it: {sizes:?}"
);
}
#[test]
fn a_limit_larger_than_the_space_available_changes_nothing() {
let sizes = distribute(40, &[50, 50], &[Some(500), None]);
assert_eq!(sizes, vec![20, 20], "a limit nobody reaches is inert");
}
#[test]
fn degenerate_distributions_do_not_panic() {
assert_eq!(distribute(0, &[1, 1], &[None, None]), vec![0, 0]);
assert!(distribute(10, &[], &[]).is_empty());
assert_eq!(
distribute(10, &[0, 0], &[None, None]).iter().sum::<u16>(),
10
);
assert_eq!(distribute(1, &[1, 1, 1], &[None; 3]).iter().sum::<u16>(), 1);
}
#[test]
fn a_bounded_row_gives_its_leftover_height_to_the_row_below() {
// The clock is bounded on height — numerals, date, zone table, and
// nothing that grows past that. The CPU graph is not. The whole point
// of the mechanism: reclaim the void under the clock and give it to
// something that fills it.
//
// The calendar is deliberately *not* used here: it stacks another row
// of months when given height, so it is bounded on width only.
let config = Config {
layout: LayoutConfig {
rows: vec![
LayoutRow {
height: 50,
panels: vec![LayoutPanel {
widget: "clocks".into(),
width: 100,
}],
},
LayoutRow {
height: 50,
panels: vec![LayoutPanel {
widget: "cpu".into(),
width: 100,
}],
},
],
},
..Config::default()
};
let app = App::new(config).unwrap();
let bound = app.slots[0]
.panel
.max_height()
.expect("the clock is bounded");
let rects = app.geometry(Rect::new(0, 0, 120, bound * 3));
assert_eq!(rects.len(), 2);
assert_eq!(rects[0].height, bound, "the clock takes only what it uses");
assert_eq!(
rects[0].height + rects[1].height,
bound * 3,
"and the height it gave up must be used, not lost"
);
assert_eq!(rects[1].y, rects[0].height, "the rows stay flush");
}
#[test]
fn a_calendar_keeps_its_height_because_it_stacks_more_months_into_it() {
let config = Config {
layout: LayoutConfig {
rows: vec![
LayoutRow {
height: 50,
panels: vec![LayoutPanel {
widget: "calendar".into(),
width: 100,
}],
},
LayoutRow {
height: 50,
panels: vec![LayoutPanel {
widget: "cpu".into(),
width: 100,
}],
},
],
},
..Config::default()
};
let app = App::new(config).unwrap();
let rects = app.geometry(Rect::new(0, 0, 120, 60));
assert_eq!(
rects[0].height, 30,
"extra height becomes another row of months, so none is handed back"
);
}
#[test]
fn a_bounded_panel_gives_its_leftover_width_to_its_neighbour() {
let config = Config {
layout: LayoutConfig {
rows: vec![LayoutRow {
height: 100,
panels: vec![
LayoutPanel {
widget: "calendar".into(),
width: 50,
},
LayoutPanel {
widget: "cpu".into(),
width: 50,
},
],
}],
},
..Config::default()
};
let app = App::new(config).unwrap();
let rects = app.geometry(Rect::new(0, 0, 200, 40));
assert!(
rects[0].width < 100,
"the calendar is bounded: {:?}",
rects[0]
);
assert_eq!(
rects[0].width + rects[1].width,
200,
"and the columns still cover the terminal"
);
assert_eq!(rects[1].x, rects[0].width, "the panels stay flush");
}
#[test]
fn focus_wraps_in_both_directions() {
let mut app = App::new(config_with(&["clocks", "cpu", "network"])).unwrap();
assert_eq!(app.focus, 0);
app.cycle_focus(true);
assert_eq!(app.focus, 1);
app.cycle_focus(true);
app.cycle_focus(true);
assert_eq!(app.focus, 0, "forward focus must wrap");
app.cycle_focus(false);
assert_eq!(app.focus, 2, "backward focus must wrap");
}
#[test]
fn geometry_returns_one_rect_per_panel_and_fills_the_area() {
let config = Config {
layout: LayoutConfig {
rows: vec![
LayoutRow {
height: 50,
panels: vec![
LayoutPanel {
widget: "clocks".into(),
width: 50,
},
LayoutPanel {
widget: "cpu".into(),
width: 50,
},
],
},
LayoutRow {
height: 50,
panels: vec![LayoutPanel {
widget: "network".into(),
width: 100,
}],
},
],
},
..Config::default()
};
let app = App::new(config).unwrap();
let area = Rect::new(0, 0, 80, 24);
let rects = app.geometry(area);
assert_eq!(rects.len(), 3);
assert_eq!(rects[2].width, 80);
assert_eq!(rects[0].width + rects[1].width, 80);
assert_eq!(rects[0].x, 0);
assert_eq!(rects[1].x, rects[0].width);
for rect in &rects {
assert!(rect.x + rect.width <= area.x + area.width);
assert!(rect.y + rect.height <= area.y + area.height);
}
}
#[test]
fn a_layout_entry_that_builds_no_panel_does_not_shift_the_rest() {
// `geometry` used to push one rect per layout column and `render` read
// it back by slot index. Any entry that produced no panel made the two
// disagree, so every later slot drew — and hit-tested clicks — in the
// previous entry's box.
//
// `Config::validate` rejects an unknown widget name, but `App::new`
// does not re-validate and neither does `rebuild_panels`, so this is
// one `config.layout` mutation away from being reachable.
let mut config = config_with(&["nope", "clocks", "cpu"]);
config.layout.rows[0].panels[0].width = 25;
config.layout.rows[0].panels[1].width = 25;
config.layout.rows[0].panels[2].width = 50;
let app = App::new(config).unwrap();
assert_eq!(app.slots.len(), 2, "the unknown widget builds no panel");
assert_eq!(app.positions, vec![(0, 1), (0, 2)]);
let rects = app.geometry(Rect::new(0, 0, 80, 24));
assert_eq!(rects.len(), 2, "one rect per slot, not per layout column");
// Column 0 is 20 cells wide and belongs to nothing. The clock is the
// first *slot* but the second *column*, so it starts at x = 20.
assert_eq!(
rects[0].x, 20,
"the clock took the missing panel's rectangle"
);
assert_eq!(rects[1].x, rects[0].x + rects[0].width);
assert_eq!(rects[0].width + rects[1].width, 60);
}
#[test]
fn a_settled_dashboard_stops_asking_to_be_redrawn() {
// The property this whole change exists for: with nothing moving,
// ticking must eventually report no change. Before, every panel whose
// timer fired counted as one, so the dashboard never went quiet and
// repainted at the fastest panel's cadence for ever.
//
// Panels that legitimately change on a timer are left out: the clock
// (its second or minute turns), pomodoro while running, and cpu and
// network (a fresh sample is a new number). What is left must settle.
let mut app = App::new(config_with(&["todo", "notes", "calendar"])).unwrap();
// The first tick may report a change; nothing has been drawn yet.
app.tick_panels();
for round in 0..5 {
// Force every panel due, so this cannot pass by ticking nothing.
for slot in &mut app.slots {
slot.last_tick = None;
}
assert!(
!app.tick_panels(),
"round {round}: a dashboard with nothing moving asked for a repaint"
);
}
}
#[test]
fn a_due_panel_is_ticked_even_when_an_earlier_one_already_reported_a_change() {
// `changed |= panel.tick()` would short-circuit and skip the call, and
// a panel that stops being ticked stops updating — a bug that would
// show up only when some *other* panel happened to change first.
let mut app = App::new(config_with(&["clocks", "todo"])).unwrap();
for slot in &mut app.slots {
slot.last_tick = None;
}
app.tick_panels();
assert!(
app.slots.iter().all(|slot| slot.last_tick.is_some()),
"a due panel was skipped"
);
}
#[test]
fn geometry_survives_a_terminal_too_small_to_draw() {
let app = App::new(config_with(&["clocks", "cpu"])).unwrap();
for (w, h) in [(0, 0), (1, 1), (3, 2)] {
let rects = app.geometry(Rect::new(0, 0, w, h));
assert_eq!(rects.len(), 2, "must still return one rect per panel");
}
}
#[test]
fn zero_weights_are_treated_as_one_rather_than_dividing_by_zero() {
let config = Config {
layout: LayoutConfig {
rows: vec![LayoutRow {
height: 0,
panels: vec![LayoutPanel {
widget: "cpu".into(),
width: 0,
}],
}],
},
..Config::default()
};
let app = App::new(config).unwrap();
let rects = app.geometry(Rect::new(0, 0, 80, 24));
assert_eq!(rects.len(), 1);
assert!(rects[0].width > 0);
}
#[test]
fn quit_keys_set_the_quit_flag() {
let mut app = App::new(config_with(&["clocks"])).unwrap();
assert!(!app.should_quit);
app.handle_key(KeyEvent::new(KeyCode::Char('q'), KeyModifiers::NONE));
assert!(app.should_quit);
let mut app = App::new(config_with(&["clocks"])).unwrap();
app.handle_key(KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL));
assert!(app.should_quit);
// Esc must not. The task panel tells you to press it to clear a filter,
// and a panel only consumes it while the filter is non-empty — so when
// Esc also quit, the same key in the same panel one keystroke apart
// either cleared the filter or killed the dashboard.
let mut app = App::new(config_with(&["clocks"])).unwrap();
app.handle_key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE));
assert!(
!app.should_quit,
"Esc means back out of something, not quit"
);
}
#[test]
fn number_keys_jump_to_a_panel_and_ignore_out_of_range_indices() {
let mut app = App::new(config_with(&["clocks", "cpu"])).unwrap();
app.handle_key(KeyEvent::new(KeyCode::Char('2'), KeyModifiers::NONE));
assert_eq!(app.focus, 1);
app.handle_key(KeyEvent::new(KeyCode::Char('9'), KeyModifiers::NONE));
assert_eq!(app.focus, 1, "an out-of-range index must not move focus");
}
#[test]
fn help_opens_and_the_next_key_closes_it() {
let mut app = App::new(config_with(&["clocks"])).unwrap();
app.handle_key(KeyEvent::new(KeyCode::Char('?'), KeyModifiers::NONE));
assert!(app.show_help);
app.handle_key(KeyEvent::new(KeyCode::Char('x'), KeyModifiers::NONE));
assert!(!app.show_help);
assert!(!app.should_quit, "closing help must not also quit");
}
fn key(code: KeyCode) -> KeyEvent {
KeyEvent::new(code, KeyModifiers::NONE)
}
#[test]
fn the_picker_opens_and_toggles_a_panel_on_and_off() {
let mut app = App::new(config_with(&["clocks", "todo"])).unwrap();
let before = app.slots.len();
app.handle_key(key(KeyCode::Char('w')));
assert!(app.picker.is_some(), "w opens the dialog");
// WIDGET_NAMES starts with clocks, which this layout already places.
app.handle_key(key(KeyCode::Char(' ')));
assert!(!app.config.layout.places("clocks"), "space turned it off");
assert_eq!(app.slots.len(), before - 1, "and the panel actually went");
assert!(app.layout_dirty);
app.handle_key(key(KeyCode::Char(' ')));
assert!(
app.config.layout.places("clocks"),
"space turned it back on"
);
assert_eq!(app.slots.len(), before);
}
#[test]
fn the_picker_moves_and_closes_without_quitting() {
let mut app = App::new(config_with(&["clocks", "todo"])).unwrap();
app.handle_key(key(KeyCode::Char('w')));
// Cursor movement itself is `picker`'s; what matters here is that the
// keys reach it rather than the panels or the global bindings.
app.handle_key(key(KeyCode::Down));
assert_eq!(app.picker_row(), Some(1));
app.handle_key(key(KeyCode::Up));
assert_eq!(app.picker_row(), Some(0));
app.handle_key(key(KeyCode::Esc));
assert!(app.picker.is_none());
assert!(
!app.should_quit,
"Esc closes the dialog rather than falling through to quit"
);
}
#[test]
fn rebuilding_shuts_the_outgoing_panels_down() {
// The picker rebuilds every panel on each toggle. Dropping the old ones
// without shutdown() discarded the task store's save and left each
// panel's fetch thread running — so toggling stocks five times left
// five pollers hitting the same endpoint, defeating the per-thread
// rate limit the module documents as enforced in code.
let mut app = App::new(config_with(&["clocks", "todo"])).unwrap();
let before = std::thread::available_parallelism().is_ok();
assert!(before, "sanity: threads are available");
app.handle_key(key(KeyCode::Char('w')));
for _ in 0..5 {
app.handle_key(key(KeyCode::Char(' ')));
}
// Whatever the toggles did, the dashboard is still coherent and every
// slot still has a panel behind it.
assert!(!app.slots.is_empty());
assert_eq!(app.slots.len(), app.positions.len());
}
#[test]
fn a_panel_ticks_immediately_rather_than_one_interval_late() {
// Previously arranged by back-dating an Instant by 24 hours, which is
// None on Windows below that uptime and panicked on the unwrap.
let mut app = App::new(config_with(&["clocks"])).unwrap();
assert!(
app.slots.iter().all(|s| s.last_tick.is_none()),
"a fresh panel has never ticked"
);
assert!(app.tick_panels(), "and is due immediately");
assert!(app.slots.iter().all(|s| s.last_tick.is_some()));
}
#[test]
fn the_last_panel_cannot_be_switched_off() {
let mut app = App::new(config_with(&["clocks"])).unwrap();
app.handle_key(key(KeyCode::Char('w')));
app.handle_key(key(KeyCode::Char(' ')));
assert!(
app.config.layout.places("clocks"),
"an empty layout is rejected at startup, so this would write a \
config that cannot be opened again"
);
assert_eq!(app.slots.len(), 1);
assert!(app.layout_error.is_some(), "and it says why");
}
#[test]
fn a_toggle_updates_the_unused_list_the_hint_reads_from() {
let mut app = App::new(config_with(&["clocks", "todo"])).unwrap();
assert!(app.unused_widgets.contains(&"pomodoro"));
app.handle_key(key(KeyCode::Char('w')));
let index = crate::widgets::WIDGET_NAMES
.iter()
.position(|n| *n == "pomodoro")
.unwrap();
for _ in 0..index {
app.handle_key(key(KeyCode::Down));
}
assert_eq!(app.picker_row(), Some(index));
app.handle_key(key(KeyCode::Char(' ')));
assert!(
!app.unused_widgets.contains(&"pomodoro"),
"switching a widget on must stop it being advertised as missing"
);
}
#[test]
fn nothing_is_written_when_no_config_path_was_given() {
// The guard that keeps the whole test suite off a real user's config.
let mut app = App::new(config_with(&["clocks", "todo"])).unwrap();
app.handle_key(key(KeyCode::Char('w')));
app.handle_key(key(KeyCode::Char(' ')));
assert!(app.layout_dirty);
app.handle_key(key(KeyCode::Esc));
assert!(
app.layout_dirty,
"still pending, because there was nowhere to write it"
);
assert_eq!(app.layout_error, None, "and that is not an error");
}
#[test]
fn a_resize_that_changed_nothing_does_not_mark_the_layout_dirty() {
let mut app = App::new(config_with(&["clocks"])).unwrap();
// One panel in its row: there is no neighbour to trade with, so the
// key does nothing and must not queue a config write.
app.handle_key(KeyEvent::new(KeyCode::Right, KeyModifiers::CONTROL));
assert!(!app.layout_dirty);
}
#[test]
fn an_empty_layout_is_rejected_at_construction() {
let config = Config {
layout: LayoutConfig { rows: Vec::new() },
..Config::default()
};
assert!(App::new(config).is_err());
}
#[test]
fn every_global_binding_has_a_key_and_an_action() {
for binding in GLOBAL {
assert!(!binding.key.is_empty());
assert!(!binding.action.is_empty());
}
assert!(
GLOBAL.iter().any(|b| b.key == "?" && b.primary),
"help must always be advertised"
);
}
}