mirador 1.22.0

An opinionated personal dashboard for your terminal: world clocks, a calendar, weather, tasks, notes, a market watchlist, and live CPU and network graphs.
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
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
//! 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};

use crate::config::Config;
use crate::frame::{Binding, FrameSpec};
use crate::keymap::Action;
use crate::panel::{KeyOutcome, Panel, RenderContext};
use crate::state::UiState;
use crate::theme::Gradients;

/// The gap between two hints on the status bar and the arrange legend.
///
/// Three spaces once, which is what a hint list wants when it is not competing
/// for the row — but this row is the one place on the dashboard where width is
/// always short, and six of them were being spent to separate seven hints. Two
/// is still twice the single space inside a hint, so `q quit` still reads as
/// one thing rather than two.
///
/// Named rather than repeated, because the test that proves the bar never
/// draws half a hint rebuilds the bar from this same table and would otherwise
/// hold its own private copy of the gap.
const HINT_GAP: &str = "  ";

/// 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.
///
/// `maxima` pairs with `weights` index for index, so the two must be the same
/// length; both callers build them from the same rows, or from the same row's
/// entries, so they always match.
///
/// 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> {
    debug_assert_eq!(weights.len(), maxima.len(), "one maximum per weight");
    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)
    }
}

/// What leads an alert on the status bar.
const ALERT_MARKER: &str = " ⚠ ";

/// The status bar's alert, fitted to a bar `width` cells wide.
///
/// One part for [`crate::grid::assemble`], marker and text together, so the
/// whole thing is measured in cells and abridged as one value. The text used
/// to be cut to the room left beside the marker, counted in characters: right
/// for `⚠`, a cell over for a wide sign such as `🚨`, which the terminal would
/// have taken off the alert's end with no `…`. And a bar narrower than the
/// marker drew the marker over nothing, where now it ends in `…` like any
/// other cut.
fn alert_line(text: &str, width: u16, theme: &crate::theme::Theme) -> Line<'static> {
    crate::grid::assemble(
        vec![vec![
            Span::styled(
                ALERT_MARKER,
                Style::default()
                    .fg(theme.error)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::styled(text.to_string(), Style::default().fg(theme.error)),
        ]],
        width,
    )
}

/// The keys of the shell's four modes, read from the config together, each
/// named for the `[<mode>.keys]` table it comes from.
///
/// Both ways in — the start and a reload or reset from the key map — take
/// their keys from [`ModeKeys::read`] and unpack every field by name, so a
/// fifth mode added here does not compile until both have been told about
/// it. They used to be written out twice, once through the named
/// constructors and once by spelling each scope's name, action table and
/// config field again by hand.
struct ModeKeys {
    arrange: crate::keymap::PanelKeymap<crate::keymap::ArrangeAction>,
    panel_picker: crate::keymap::PanelKeymap<crate::picker::PickerAction>,
    theme_picker: crate::keymap::PanelKeymap<crate::theme_picker::ThemePickerAction>,
    help_overlay: crate::keymap::PanelKeymap<crate::keymap::HelpAction>,
}

impl ModeKeys {
    /// Each mode's `[<mode>.keys]` laid over its defaults, or why one of
    /// them cannot be.
    fn read(config: &Config) -> std::result::Result<Self, String> {
        Ok(Self {
            arrange: crate::keymap::arrange_keymap(&config.arrange.keys)?,
            panel_picker: crate::picker::keymap(&config.panel_picker.keys)?,
            theme_picker: crate::theme_picker::keymap(&config.theme_picker.keys)?,
            help_overlay: crate::keymap::help_keymap(&config.help_overlay.keys)?,
        })
    }
}

/// 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>,
    /// `(row, column)` in `config.layout` of the entry this panel was built
    /// for, so a resize knows which weights the focused panel is made of and
    /// `geometry` which box it draws in. Kept on the slot rather than in a
    /// list beside `slots`, which every builder had to push in step: a widget
    /// that builds nothing leaves a hole in the layout, and an index into one
    /// list read against the other then names some other panel.
    position: (usize, usize),
    /// 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,
    /// The shell's keys: the defaults with the config's `[keys]` over them.
    keymap: crate::keymap::Keymap,
    /// Arrange mode's keys, from `[arrange.keys]`.
    arrange_keys: crate::keymap::PanelKeymap<crate::keymap::ArrangeAction>,
    /// The `w` picker's keys, from `[panel_picker.keys]`, handed to it as it
    /// opens.
    panel_picker_keys: crate::keymap::PanelKeymap<crate::picker::PickerAction>,
    /// The `t` picker's keys, from `[theme_picker.keys]`.
    theme_picker_keys: crate::keymap::PanelKeymap<crate::theme_picker::ThemePickerAction>,
    /// The help overlay's scroll keys, from `[help_overlay.keys]`.
    help_keys: crate::keymap::PanelKeymap<crate::keymap::HelpAction>,
    gradients: Gradients,
    slots: Vec<Slot>,
    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,
    /// 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 key,
    /// paste or click: 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,
    /// What has happened since mirador started.
    ///
    /// Lives here rather than in the watch log panel because the panel may not
    /// be placed, may be toggled off and on, and is rebuilt whenever the layout
    /// changes. Events would be lost every time, and a log that forgets when
    /// you rearrange the dashboard is not a log.
    watch: crate::watch::WatchLog,
    /// The day the watch log last saw.
    ///
    /// Held here rather than in a panel because the day turning is not any
    /// panel's business — the todo panel happens to notice it too, but a
    /// dashboard whose day-divider disappears when you switch off the task
    /// list would be a strange thing.
    today: jiff::civil::Date,
    /// The panel picker, while it is open.
    picker: Option<crate::picker::Picker>,
    /// The theme picker, while it is open, and the theme to put back if it is
    /// cancelled. Previewing means the live theme is not the committed one, so
    /// the dialog cannot be closed without knowing what it replaced.
    theme_picker: Option<(crate::theme_picker::ThemePicker, crate::theme::Theme)>,
    /// The key map, opened by pressing the help key while help is open.
    keymap_dialog: Option<crate::keymap_dialog::KeymapDialog>,
    /// The layout as it stood when arrange mode opened, kept so that `Esc` can
    /// put it back. Moving panels is a bigger, more spatial change than
    /// toggling one on, and being able to try an arrangement and back out of it
    /// is most of what makes it safe to try at all.
    arranging: Option<Arrangement>,
    /// 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 and
    /// on the bar: a change you made that silently did not persist is the
    /// worst outcome here. Set by [`App::write_layout`] and by nothing else,
    /// so the alert that reads it is true whenever it is lit.
    layout_error: Option<String>,
    /// Why the last layout change was refused, if it was — the last panel,
    /// or a layout the panels would not build from, already put back.
    /// Nothing changed and nothing is unsaved, so it is said in the picker
    /// and not on the bar, and it goes when the picker closes. It used to
    /// share `layout_error`, which put "The layout could not be saved" on
    /// the bar for a save nobody attempted, until some later layout change
    /// happened to succeed.
    layout_notice: 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,
}

/// What arrange mode has to put back if the user changes their mind.
struct Arrangement {
    layout: crate::config::Layout,
    /// Whether the layout was already unwritten when the mode opened — a resize
    /// a moment earlier, say. Cancelling restores the layout, and must not also
    /// throw away a change that was never part of this arrangement.
    was_dirty: bool,
}

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 = Self::build_slots(&config)?;
        Self::around(config, slots)
    }

    /// The shell around panels already built: key tables, gradients and a
    /// dashboard in its opening state.
    fn around(config: Config, slots: Vec<Slot>) -> Result<Self> {
        let (keymap, _) = crate::keymap::KeyTables::from_config(&config)
            .check()
            .map_err(anyhow::Error::msg)?;
        // Checked with the rest just above, so this cannot fail.
        let ModeKeys {
            arrange: arrange_keys,
            panel_picker: panel_picker_keys,
            theme_picker: theme_picker_keys,
            help_overlay: help_keys,
        } = ModeKeys::read(&config).map_err(anyhow::Error::msg)?;

        let gradients = config.theme.gradients();
        Ok(Self {
            config,
            keymap,
            arrange_keys,
            panel_picker_keys,
            theme_picker_keys,
            help_keys,
            gradients,
            slots,
            focus: 0,
            show_help: false,
            help_scroll: 0,
            help_overflow: 0,
            help_viewport: 0,
            should_quit: false,
            update: crate::update::Found::default(),
            show_update_hint: true,
            watch: crate::watch::WatchLog::default(),
            today: jiff::Zoned::now().date(),
            picker: None,
            theme_picker: None,
            keymap_dialog: None,
            arranging: None,
            config_path: None,
            last_resize: None,
            layout_dirty: false,
            layout_error: None,
            layout_notice: 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<Vec<Slot>> {
        let mut slots = 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,
                        position: (row_index, column_index),
                        last_tick: None,
                        area: None,
                    });
                }
            }
        }

        anyhow::ensure!(
            !slots.is_empty(),
            "no panels were built; check the `[layout]` table in your config"
        );
        Ok(slots)
    }

    /// 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);
        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,
                        position: (row, column),
                        last_tick: None,
                        area: None,
                    })
            });
            if let Some(mut slot) = slot {
                // A carried panel is almost certainly somewhere else in the
                // layout now, and on screen. Its place is the entry it was
                // just matched to; its `area`, which mouse events are matched
                // against, is cleared rather than trusted until the next draw
                // sets it.
                slot.position = (row, column);
                slot.area = None;
                slots.push(slot);
            }
        }

        // 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;
        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(self.poll_wait(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::Paste(text) => dirty |= self.handle_paste(&text),
                    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,
                    // The closest thing to "the reader is looking" that a
                    // terminal will tell us. Not every terminal sends it and
                    // tmux forwards it only with `focus-events on`, so it is
                    // an improvement where available rather than the mechanism
                    // — the keypress below carries it everywhere else.
                    //
                    // **Losing focus only.** This used to mark on both, on the
                    // reasoning that gaining focus means they are here now and
                    // losing it means they were here until this moment — each
                    // true in isolation, and together they made the rule line
                    // impossible to see. Returning to the dashboard set "last
                    // looked" to *now*, so everything that arrived while the
                    // reader was away landed on the old side of the line and the
                    // line vanished in the instant they came back to read it.
                    // A terminal that reported focus *correctly* therefore made
                    // the feature less visible than one that did not (#132).
                    //
                    // Leaving is the half that can be recorded without
                    // destroying what it describes: they were present with those
                    // entries on screen, so marking them seen is honest. Coming
                    // back is precisely when the line has to still be there.
                    Event::FocusLost => self.watch.mark_seen(),
                    _ => {}
                }
            }

            dirty |= self.tick_panels();
            dirty |= self.collect_events();
            self.write_settled_resize();
        }

        self.finish();
        Ok(())
    }

    /// Write a resize once the key has stopped repeating.
    ///
    /// 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 [`App::finish`]: 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.
    ///
    /// Not while arrange mode is open. A resize made inside the mode is part
    /// of the arrangement, which Keep (or Ctrl+C, see `finish`) writes and Esc
    /// puts back. Settling it
    /// anyway wrote the file behind the mode's back, so Esc restored the
    /// screen and left the config resized for the next launch. A resize made
    /// before the mode opened is still dirty after Esc and settles here once
    /// the mode has closed.
    fn write_settled_resize(&mut self) {
        if self.arranging.is_none()
            && self.layout_dirty
            && self
                .last_resize
                .is_some_and(|at| at.elapsed() >= RESIZE_SETTLE)
        {
            self.write_layout();
            self.last_resize = None;
        }
    }

    /// Shut the panels down and write whatever is still unwritten.
    ///
    /// That includes an arrangement still open in arrange mode: Ctrl+C keeps
    /// it, as Keep would, and only Esc discards one. Decided by the owner on
    /// 2026-10-07 — Ctrl+C is the way out that always works, and leaving
    /// should not throw away work that is on screen.
    fn finish(&mut self) {
        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();
    }

    /// 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);
        }
        // The theme is the shell's, not any panel's, so it is reported here —
        // but reported the same way, unconditionally, so invariant 17 holds for
        // it too and picking your config's own theme back retracts the entry.
        //
        // While the theme picker is open the live theme is only a preview, so
        // the one reported is the theme it opened on. Otherwise every arrow
        // key wrote the file, and a dashboard closed mid-browse came back in
        // a theme nobody chose.
        let committed = self
            .theme_picker
            .as_ref()
            .map_or(&self.config.theme, |(_, original)| original);
        current.theme.clone_from(&committed.name);
        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;
        }
    }

    /// Drain what the panels have noticed into the log.
    ///
    /// Returns whether anything was recorded, so the dashboard redraws: a new
    /// entry is a visible change if the watch log is on screen, and cheaper to
    /// report unconditionally than to ask whether it is placed.
    fn collect_events(&mut self) -> bool {
        let mut recorded = false;

        // The day turning is the one thing in here that always happens, which
        // matters more than it sounds: with a calendar unconfigured and no task
        // falling due, every other source can go quiet for days and leave the
        // panel looking broken. It is also the most useful divider a log of
        // "what changed while I was away" can have.
        let today = jiff::Zoned::now().date();
        if today != self.today {
            self.today = today;
            self.watch.push(crate::watch::Event::new(
                "clock",
                format!("{} began", today.strftime("%A %-d %B")),
            ));
            recorded = true;
        }

        for slot in &mut self.slots {
            for event in slot.panel.events() {
                self.watch.push(event);
                recorded = true;
            }
        }
        recorded
    }

    /// 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 = changed || slot.panel.tick()`: `||`
                // short-circuits once the accumulator is true, and a panel that
                // stops being ticked stops updating. The call goes on the left
                // so the order is visibly load-bearing; `|=` on a `bool` is
                // eager and would be as safe, which is what `run` relies on.
                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())
    }

    /// Let a focused interactive panel request responsive asynchronous echo
    /// without changing the dashboard-wide polling budget. The floor prevents
    /// an external process from turning the shell into a busy loop.
    fn poll_wait(&self, configured: Duration) -> Duration {
        self.slots
            .get(self.focus)
            .filter(|slot| slot.panel.captures_input())
            .map_or(configured, |slot| {
                configured.min(slot.panel.refresh_interval().max(Duration::from_millis(16)))
            })
    }

    fn handle_key(&mut self, key: KeyEvent) {
        // Any key at all retires the update notice. It has been read or it has
        // been ignored; either way it has had its turn.
        self.show_update_hint = false;
        // A keypress is weaker evidence than a focus event — the moments this
        // most wants to be right are the glances that touch nothing — but it is
        // the only evidence available on a terminal that does not report focus.
        self.watch.mark_seen();

        let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);

        // Editors get first refusal only for a real selection. No modal panel,
        // child process or external protocol can veto the escape hatch: after
        // the selection collapses, Ctrl+C exits from every state.
        if ctrl && matches!(key.code, KeyCode::Char('c')) {
            let consumed = self.slots.get_mut(self.focus).is_some_and(|slot| {
                slot.panel.copy_selection() == crate::panel::KeyOutcome::Consumed
            });
            if consumed {
                return;
            }
            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 {
            // The help key a second time goes one level deeper, to the full
            // key map. Reached through help rather than on a key of its own:
            // every free letter is some panel's already, and the overlay is
            // where someone wondering about keys has just arrived.
            if self.keymap.action(key) == Some(Action::Help) {
                self.show_help = false;
                self.keymap_dialog = Some(crate::keymap_dialog::KeymapDialog::new());
                return;
            }
            // The scroll keys are `[help_overlay.keys]`, and bind only when
            // there is something below the fold; every other key closes.
            if self.help_overflow > 0 {
                use crate::keymap::HelpAction;
                let page = self.help_viewport.max(1);
                let moved = self.help_keys.action(key).map(|action| match action {
                    HelpAction::Down => self.help_scroll.saturating_add(1),
                    HelpAction::Up => self.help_scroll.saturating_sub(1),
                    HelpAction::PageDown => self.help_scroll.saturating_add(page),
                    HelpAction::PageUp => self.help_scroll.saturating_sub(page),
                    HelpAction::First => 0,
                    HelpAction::Last => self.help_overflow,
                });
                if let Some(to) = moved {
                    self.help_scroll = to.min(self.help_overflow);
                    return;
                }
            }
            self.show_help = false;
            return;
        }

        if let Some(dialog) = self.keymap_dialog.as_mut() {
            match dialog.handle_key(key) {
                crate::keymap_dialog::Request::None => {}
                crate::keymap_dialog::Request::Close => self.keymap_dialog = None,
                crate::keymap_dialog::Request::Reload => self.reload_keys(),
                crate::keymap_dialog::Request::Reset => self.reset_keys(),
            }
            return;
        }

        // The picker is a real dialog rather than a notice, so it reads keys
        // instead of dismissing on any of them.
        if self.theme_picker.is_some() {
            self.handle_theme_picker_key(key);
            return;
        }
        if self.picker.is_some() {
            self.handle_picker_key(key);
            return;
        }

        let resize = self.keymap.action(key).filter(|action| action.is_resize());

        // Arrange mode claims the bare arrows, which is the whole point of it
        // being a mode: no modifier to discover, and no terminal that declines
        // to deliver the chord. The resize keys fall through wherever they
        // have been moved to, so resizing keeps working while you are
        // rearranging — which is when you are most likely to want it — and a
        // key in `[arrange.keys]` that is also a resize key is refused at load
        // for that reason. Any other Ctrl key falls through too, unless
        // `[arrange.keys]` binds it.
        if self.arranging.is_some()
            && resize.is_none()
            && (!ctrl || self.arrange_keys.action(key).is_some())
        {
            self.handle_arrange_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 let Some(action) = resize
            && !self.focus_captures_input()
        {
            let resized = match action {
                Action::ResizeWider => self.resize_width(true),
                Action::ResizeNarrower => self.resize_width(false),
                Action::ResizeTaller => self.resize_height(true),
                _ => self.resize_height(false),
            };
            // 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);
    }

    /// Route a terminal bracketed paste to the focused editor.
    ///
    /// A panel can consume the whole block so a multiline editor preserves
    /// hard lines and literal tabs. Older form fields still receive the same
    /// printable key stream they did before bracketed paste was enabled; it is
    /// dispatched straight to the capturing panel so pasted `q` cannot become
    /// a global quit command.
    ///
    /// The veto is asked again before every key, and the paste ends when it
    /// lapses. A newline is Enter, and Enter commits a one-line form: what
    /// follows it would otherwise reach the panel as commands, which in the
    /// task list means a second line beginning `a` opens another task and
    /// one beginning `dy` deletes the first. The rest is dropped instead.
    ///
    /// A delete confirmation captures input too, and nothing here can tell
    /// it from a form, so the panels that ask one claim a paste themselves
    /// and drop it: typed in, a paste beginning with `y` was the answer.
    fn handle_paste(&mut self, text: &str) -> bool {
        // A paste is the reader acting, as a key is: it retires the update
        // notice and marks the watch log seen. Both change what is on screen,
        // and `run` redraws after a paste only when asked — so every way out
        // of here asks when either did, as `handle_mouse` does with the
        // notice. Without it a paste no panel took left both standing.
        let had_hint = std::mem::take(&mut self.show_update_hint);
        let line_before = self.watch.unseen();
        self.watch.mark_seen();
        let retired = had_hint || self.watch.unseen() != line_before;

        if self.show_help {
            self.show_help = false;
            return true;
        }
        if self.theme_picker.is_some()
            || self.picker.is_some()
            || self.arranging.is_some()
            || self.keymap_dialog.is_some()
        {
            return retired;
        }

        let Some(slot) = self.slots.get_mut(self.focus) else {
            return retired;
        };
        if slot.panel.handle_paste(text) == crate::panel::KeyOutcome::Consumed {
            return true;
        }
        let text = text.replace("\r\n", "\n").replace('\r', "\n");
        let mut used = false;
        for character in text.chars() {
            if !slot.panel.captures_input() {
                break;
            }
            let code = match character {
                '\n' => KeyCode::Enter,
                '\t' => KeyCode::Tab,
                c if !c.is_control() => KeyCode::Char(c),
                _ => continue,
            };
            used = slot
                .panel
                .handle_key(KeyEvent::new(code, KeyModifiers::NONE))
                == crate::panel::KeyOutcome::Consumed
                || used;
        }
        used || retired
    }

    /// Read every key table from the config again, for the key map's `r`.
    ///
    /// A keymap that does not check out is reported and not applied: the keys
    /// in force stay in force, so a half-finished edit cannot take away the
    /// key the reader would use to fix it.
    fn reload_keys(&mut self) {
        let result = match self.config_path.as_deref() {
            Some(path) => crate::keymap::read_keys(path),
            None => Err("there is no config file to read keys from".into()),
        };
        let outcome = match result {
            Ok((tables, keymap)) => {
                tables.apply(&mut self.config);
                self.keymap = keymap;
                self.rebind_panels();
                Ok(match self.keys_changed() {
                    0 => "Loaded. Every key is its default.".to_string(),
                    1 => "Loaded. One key differs from its default.".to_string(),
                    n => format!("Loaded. {n} keys differ from their defaults."),
                })
            }
            Err(error) => Err(format!("Kept the keys you had. {error}")),
        };
        self.report_to_key_map(outcome);
    }

    /// Say in the key map how a reload or a reset went: what it did, or why
    /// it did nothing, shown as a failure.
    fn report_to_key_map(&mut self, outcome: std::result::Result<String, String>) {
        let (text, failed) = match outcome {
            Ok(text) => (text, false),
            Err(text) => (text, true),
        };
        if let Some(dialog) = self.keymap_dialog.as_mut() {
            dialog.report(text, failed);
        }
    }

    /// How many actions, the shell's and every panel's, are not on their
    /// default keys.
    fn keys_changed(&self) -> usize {
        let shell = Action::LISTED
            .iter()
            .filter(|action| !self.keymap.is_default(**action))
            .count();
        let panels = self
            .panel_keys()
            .iter()
            .flat_map(|(_, listing)| listing)
            .filter(|listed| !listed.is_default())
            .count();
        shell + panels
    }

    /// Every panel scope's keys as the key map lists them.
    fn panel_keys(&self) -> crate::keymap::PanelListing {
        crate::keymap::KeyTables::from_config(&self.config)
            .check()
            .map(|(_, panels)| panels)
            .unwrap_or_default()
    }

    /// Hand the shell's modes and every live panel their keys from the
    /// config again.
    ///
    /// Both callers apply tables that have just been checked — a reload's,
    /// or the defaults — so the modes' keys always build. Were one somehow
    /// not to, the keys in force stay in force, which is what a reload that
    /// does not check out does too.
    fn rebind_panels(&mut self) {
        if let Ok(ModeKeys {
            arrange,
            panel_picker,
            theme_picker,
            help_overlay,
        }) = ModeKeys::read(&self.config)
        {
            self.arrange_keys = arrange;
            self.panel_picker_keys = panel_picker;
            self.theme_picker_keys = theme_picker;
            self.help_keys = help_overlay;
        }
        for slot in &mut self.slots {
            slot.panel.set_keys(&self.config);
        }
    }

    /// Comment out every key table in the config and go back to the
    /// defaults, for the key map's `d` once the reader has said yes.
    fn reset_keys(&mut self) {
        let result = match self.config_path.as_deref() {
            Some(path) => crate::keymap::reset_file(path),
            None => Err("there is no config file to reset".into()),
        };
        let outcome = match result {
            Ok(edited) => {
                self.keymap = crate::keymap::Keymap::default();
                crate::keymap::KeyTables::default().apply(&mut self.config);
                self.rebind_panels();
                let text = if edited {
                    "Every key is back to its default. Your old key lines are \
                     still in the config, commented out."
                } else {
                    "The config sets no keys, so every key is its default."
                };
                Ok(text.to_string())
            }
            Err(error) => Err(format!("Nothing was changed. {error}")),
        };
        self.report_to_key_map(outcome);
    }

    /// Open arrange mode, remembering what to go back to.
    fn enter_arrange(&mut self) {
        self.arranging = Some(Arrangement {
            layout: self.config.layout.clone(),
            was_dirty: self.layout_dirty,
        });
    }

    /// Move the focused panel, or leave the mode.
    fn handle_arrange_key(&mut self, key: KeyEvent) {
        use crate::arrange::Direction;
        use crate::keymap::ArrangeAction;

        // Esc backs out of it, which is what Esc means everywhere else in
        // mirador, and so it is in no table. The picker commits on Esc instead,
        // and that is defensible there because each of its changes is one
        // keystroke to undo; an arrangement is not.
        if key.code == KeyCode::Esc {
            if let Some(before) = self.arranging.take() {
                self.config.layout = before.layout;
                // Rebuilding from a layout that was live a moment ago
                // cannot fail, and if it somehow did there is nothing
                // better to fall back to.
                let _ = self.rebuild_panels();
                self.layout_dirty = before.was_dirty;
            }
            return;
        }
        // The digits pick a panel here as they do outside the mode, and are
        // in no table for the same reason.
        if self.jump_to_slot(key) {
            return;
        }

        let Some(action) = self.arrange_keys.action(key) else {
            return;
        };
        match action {
            // The shifted keys move the whole row rather than the panel,
            // which is the same escalation the clock panel uses: the bare key
            // moves the small thing, the shifted key the thing it sits in.
            //
            // Not `Ctrl+←→↑↓`, which #100 proposed: those resize inside this
            // mode, advertised in the legend and pinned by
            // `ctrl_arrows_still_resize_inside_arrange_mode`.
            ArrangeAction::RowUp => self.move_focused_row(false),
            ArrangeAction::RowDown => self.move_focused_row(true),
            ArrangeAction::MoveLeft => self.move_focused(Direction::Left),
            ArrangeAction::MoveRight => self.move_focused(Direction::Right),
            ArrangeAction::MoveUp => self.move_focused(Direction::Up),
            ArrangeAction::MoveDown => self.move_focused(Direction::Down),
            // Pick a different panel to move without leaving the mode.
            // Rearranging a dashboard means moving several things, and having
            // to commit and re-enter between each one would make a two-panel
            // swap a six-keystroke job.
            ArrangeAction::FocusNext => self.cycle_focus(true),
            ArrangeAction::FocusPrevious => self.cycle_focus(false),
            // Keeping it is the ordinary way out, so it gets the ordinary keys.
            // Written here rather than on every arrow: trying four arrangements
            // should cost one write, and the mode is a natural commit point —
            // the same reasoning as the picker.
            ArrangeAction::Keep => {
                self.arranging = None;
                self.write_layout();
            }
        }
    }

    /// Move the focused panel one step, putting the layout back if the result
    /// will not build.
    fn move_focused(&mut self, direction: crate::arrange::Direction) {
        let Some((row, column)) = self.focused_position() else {
            return;
        };
        let before = self.config.layout.clone();
        if crate::arrange::move_panel(&mut self.config.layout, row, column, direction).is_none() {
            return;
        }

        // Focus follows the panel by name, so the moved panel keeps the
        // highlight wherever it lands and nothing here has to chase it.
        // A move builds no new panel, and only building one can fail, so a
        // refusal is a guard rather than a path, and arrange mode, which
        // draws no picker, has nowhere to say more.
        let _ = self.commit_layout(before);
    }

    /// Move the row the focused panel sits in, up or down, putting the layout
    /// back if the result will not build — silently, for the reason a panel
    /// move gives.
    fn move_focused_row(&mut self, down: bool) {
        let Some((row, _)) = self.focused_position() else {
            return;
        };
        let before = self.config.layout.clone();
        if crate::arrange::move_row(&mut self.config.layout, row, down).is_none() {
            return;
        }

        // Focus follows the panel by name, as it does for a panel move, so the
        // highlight stays on whatever the reader was moving even though every
        // panel in the row changed its flat index.
        let _ = self.commit_layout(before);
    }

    /// Rebuild the panels around the layout now in the config, or put
    /// `before` back and say why not.
    ///
    /// Every change to which panels there are, or where they sit, comes
    /// through here — a panel moved, a row moved, a panel switched on or off.
    /// Two layout changes go around it. A resize only moves weights, which the
    /// next draw reads from the config with no panel rebuilt. Esc in arrange
    /// mode rebuilds the panels itself, from a layout that was live a moment
    /// ago, so there is nothing to undo, and it puts back whether that layout
    /// was already waiting to be written rather than marking it.
    ///
    /// A layout the panels cannot be built from is undone rather than left
    /// half-applied, so the dashboard is always one the config can describe,
    /// and only a change that took is marked as needing to be written. What to
    /// say about a refusal is the caller's: the picker shows it, arrange mode
    /// has nowhere to.
    fn commit_layout(&mut self, before: crate::config::Layout) -> Result<()> {
        if let Err(error) = self.rebuild_panels() {
            // Rebuilding from a layout that was live a moment ago cannot
            // fail, and if it somehow did there is nothing better to fall
            // back to.
            self.config.layout = before;
            let _ = self.rebuild_panels();
            return Err(error);
        }
        self.layout_dirty = true;
        Ok(())
    }

    /// 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;
                self.layout_notice = 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();
            }
        }
    }

    /// Open the theme picker, remembering the theme to put back on `Esc`.
    ///
    /// The themes directory sits beside the config, so a `--config` somewhere
    /// unusual looks for themes beside *it*. With no config path — which is
    /// only ever the tests — the bundled set is the whole list.
    fn open_theme_picker(&mut self) {
        let dir = self
            .config_path
            .as_deref()
            .and_then(crate::themes::user_dir);
        let picker = crate::theme_picker::ThemePicker::new(
            self.config.theme.name.as_deref(),
            dir.as_deref(),
        )
        .with_keys(self.theme_picker_keys.clone());
        self.theme_picker = Some((picker, self.config.theme.clone()));
    }

    /// Act on whatever the theme picker made of a keypress.
    fn handle_theme_picker_key(&mut self, key: KeyEvent) {
        let Some((picker, original)) = self.theme_picker.as_mut() else {
            return;
        };
        match picker.handle_key(key) {
            crate::theme_picker::Action::None => {}
            crate::theme_picker::Action::Preview(name) => {
                let dir = self
                    .config_path
                    .as_deref()
                    .and_then(crate::themes::user_dir);
                // A theme that will not load is left as a dead row rather than
                // reported: the file is the user's own, they have just watched
                // every other name repaint the screen, and the one that does
                // nothing is legible enough. Anything louder would put an error
                // dialog on top of a colour picker.
                if let Ok(theme) = crate::themes::resolve(&name, dir.as_deref()) {
                    self.apply_theme(theme);
                }
            }
            crate::theme_picker::Action::Accept => {
                self.theme_picker = None;
                // The live theme is already the chosen one, so there is nothing
                // to apply — only to record. Written here rather than on every
                // cursor move, so browsing the list costs no writes: while the
                // dialog is open, `collect_preferences` reports the theme it
                // opened on, and closing it is what lets this one through.
                self.persist_preferences();
            }
            crate::theme_picker::Action::Cancel => {
                let restore = original.clone();
                self.theme_picker = None;
                self.apply_theme(restore);
            }
        }
    }

    /// Swap the live theme, including the colours derived from it.
    ///
    /// `gradients` is the one thing that does not read `config.theme` at draw
    /// time — it is a baked 101-entry ramp, computed once. Forgetting it here
    /// would leave the cpu and network graphs painted in the previous theme
    /// while everything around them changed, which looks like a rendering bug
    /// rather than a missing line.
    fn apply_theme(&mut self, theme: crate::theme::Theme) {
        self.config.theme = theme;
        self.gradients = self.config.theme.gradients();
    }

    /// 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_notice = Some("at least one panel has to stay".into());
                return;
            }
        } else {
            self.config.layout.add_widget(widget);
        }

        // A layout that will not build is a reason to refuse the toggle, not
        // to leave the dashboard in pieces, and the picker says why.
        self.layout_notice = self.commit_layout(before).err().map(|e| format!("{e:#}"));
    }

    /// 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:#}")),
        }
    }

    /// Why the layout could not be written, if the last attempt failed.
    ///
    /// For `main`, after [`App::run`] has returned and the terminal is back.
    /// The write on the way out is the last chance to keep a resize made a
    /// moment before quitting, and when it fails there is no status bar left
    /// to say so. Dropping it there was the one place [`App::write_layout`]'s
    /// promise not to swallow a failure did not hold.
    pub fn unsaved_layout(&self) -> Option<&str> {
        self.layout_error.as_deref()
    }

    /// The line `main` prints after restoring the terminal, if a layout change
    /// was lost on the way out. Built here so its wording is tested; `main`
    /// only prints it.
    pub fn exit_report(&self) -> Option<String> {
        self.unsaved_layout()
            .map(|why| format!("mirador: the layout could not be saved — {why}"))
    }

    /// 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 self.keymap.action(key) {
            // The configured quit key 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, which is why the keymap will not take it.
            Some(Action::Quit) => self.should_quit = true,
            Some(Action::FocusNext) => self.cycle_focus(true),
            Some(Action::FocusPrevious) => self.cycle_focus(false),
            Some(Action::Help) => {
                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;
            }
            Some(Action::Panels) => {
                self.picker = Some(
                    crate::picker::Picker::new(self.config.widget_names())
                        .with_keys(self.panel_picker_keys.clone()),
                );
            }
            Some(Action::Theme) => self.open_theme_picker(),
            Some(Action::Arrange) => self.enter_arrange(),
            // Reached only while a panel captures input, which vetoes resizing
            // along with every other global key; see `handle_key`.
            Some(
                Action::ResizeWider
                | Action::ResizeNarrower
                | Action::ResizeTaller
                | Action::ResizeShorter,
            )
            | None => {
                self.jump_to_slot(key);
            }
        }
    }

    /// Focus the panel a digit names, `1` for the first, and say whether the
    /// key was a digit at all.
    ///
    /// A digit with no panel behind it is still a digit: it moves nothing,
    /// and it is not offered anywhere else. One place for both the dashboard
    /// and arrange mode, because `1`–`9` are the keys no table may take and
    /// the two must not come to disagree about what they do.
    fn jump_to_slot(&mut self, key: KeyEvent) -> bool {
        let KeyCode::Char(c @ '1'..='9') = key.code else {
            return false;
        };
        let index = c as usize - '1' as usize;
        if index < self.slots.len() {
            self.focus = index;
        }
        true
    }

    /// 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.focused_position() 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.focused_position() 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 update notice, 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_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 shell dialog owns the keyboard while it is open, and the mouse
        // with it. None of them reads the pointer, so the event goes nowhere:
        // offered to the panels it fell through the dialog, and a click moved
        // focus to a panel beneath and selected a row nobody could see.
        if self.picker.is_some() || self.theme_picker.is_some() || self.keymap_dialog.is_some() {
            return had_hint;
        }

        // 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
        };
    }

    /// Where the focused panel sits in `config.layout`, as `(row, column)`.
    fn focused_position(&self) -> Option<(usize, usize)> {
        self.slots.get(self.focus).map(|slot| slot.position)
    }

    /// 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;

        // The slot each layout entry built, from one walk of the slots. An
        // entry that built no panel stays `None`: a hole, which the rows and
        // columns below leave empty rather than closing up.
        let mut built: Vec<Vec<Option<usize>>> = rows
            .iter()
            .map(|row| vec![None; row.panels.len()])
            .collect();
        for (index, slot) in self.slots.iter().enumerate() {
            let (row, column) = slot.position;
            if let Some(entry) = built.get_mut(row).and_then(|row| row.get_mut(column)) {
                *entry = Some(index);
            }
        }

        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>> = built
            .iter()
            .map(|row| {
                let mut tallest = 0u16;
                for slot in row {
                    let max = slot.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. 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, slots)) in rows.iter().zip(&built).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>> = slots
                .iter()
                .map(|slot| slot.and_then(|slot| self.slots[slot].panel.max_width()))
                .collect();
            let columns = distribute(area.width, &widths, &maxima);

            let mut x = area.x;
            for (slot, width) in slots.iter().zip(columns) {
                if let Some(slot) = *slot {
                    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)
    }

    /// The dashboard `config` lays out, from panels already built rather than
    /// through `widgets::build` — which, under test, refuses the weather,
    /// markets and news panels, because each starts a fetch thread that goes
    /// straight to the network. A test wanting the whole default dashboard
    /// hands over the offline panels instead.
    ///
    /// Each layout entry takes the first unused panel of its widget, in the
    /// row-major order `new` builds in. An entry with none to take is an
    /// error, as a panel that will not build is to `new`, and panels nothing
    /// in the layout takes are dropped.
    #[cfg(test)]
    pub fn with_panels(config: Config, mut panels: Vec<(&str, Box<dyn Panel>)>) -> Result<Self> {
        let mut slots = Vec::new();
        for (row_index, row) in config.layout.rows.iter().enumerate() {
            for (column_index, entry) in row.panels.iter().enumerate() {
                let index = panels
                    .iter()
                    .position(|(widget, _)| *widget == entry.widget)
                    .with_context(|| format!("no `{}` panel was supplied", entry.widget))?;
                let (_, panel) = panels.remove(index);
                slots.push(Slot {
                    widget: entry.widget.clone(),
                    panel,
                    position: (row_index, column_index),
                    last_tick: None,
                    area: None,
                });
            }
        }
        Self::around(config, slots)
    }

    /// 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;
        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,
                    gradients: &self.gradients,
                    focused,
                    watch: &self.watch,
                },
            );
        }

        // Panel dialogs, before the shell's own overlays and after every
        // panel: drawn any earlier and the panels following the one that owns
        // the dialog paint straight over it.
        for slot in &self.slots {
            if let Some(prompt) = slot.panel.overlay() {
                prompt.render(frame, area, &self.config.theme);
            }
        }

        if self.show_help {
            self.render_help(frame, area);
        }
        // Listed only while the key map is open; the draw pays for nothing
        // otherwise.
        let panel_keys = if self.keymap_dialog.is_some() {
            self.panel_keys()
        } else {
            Vec::new()
        };
        if let Some(dialog) = self.keymap_dialog.as_mut() {
            dialog.render(
                frame,
                area,
                &self.keymap,
                &panel_keys,
                self.config_path.as_deref(),
                &self.config.theme,
            );
        }
        if let Some((picker, _)) = &self.theme_picker {
            picker.render(frame, area, &self.config.theme);
        }
        if let Some(picker) = &self.picker {
            picker.render(
                frame,
                area,
                &self.config.theme,
                |name| self.config.layout.places(name),
                // What was just refused, or else why the last write failed.
                self.layout_notice
                    .as_deref()
                    .or(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);

        // In arrange mode the bar belongs to the mode. The global keys are not
        // reachable anyway — the arrows have been claimed — so listing them
        // would be listing keys that do nothing.
        //
        // This also hides an alert for as long as the mode is open, which is a
        // decision rather than an oversight. Arrange mode is a gesture measured
        // in seconds and the legend is what makes it usable; an alert that
        // waits until `Enter` or `Esc` has lost nothing, because the thing it
        // names has already happened either way.
        if self.arranging.is_some() {
            let spans = vec![Span::styled(
                " ARRANGE",
                Style::default()
                    .fg(theme.accent)
                    .add_modifier(Modifier::BOLD),
            )];
            // Which arrow moves along the row and which moves between rows is
            // self-evident the moment you press one, because the panels move.
            // What is *not* evident is that there is a row past the last one,
            // so the width saved by collapsing the first two entries into
            // "move" is spent saying so. Someone had to ask.
            //
            // Ordered so that the two that matter most survive a narrow
            // terminal: knowing how to get out of a mode beats knowing every
            // trick inside it.
            let mut parts = vec![spans];
            // Both vertical hints were shortened when `Shift+↑↓` was added in
            // #100: a sixth entry does not fit beside the old wording at an
            // ordinary 110 columns, and dropping one was not an option —
            // the help overlay carries only the *global* keys, so this legend
            // is the only place any of these are documented. A key that ships
            // undiscoverable is the mistake the resize keys already made once.
            //
            // Derived from `[arrange.keys]` and the shell's resize keys, so a
            // key moved in either is shown where it went.
            let legend =
                crate::keymap::arrange_legend(&self.arrange_keys, self.keymap.resize_bindings());
            for binding in legend {
                // Dropped whole rather than clipped: half a hint reads as a
                // rendering fault, where a missing one just reads as a narrow
                // terminal. The gap leads the hint it introduces, so a dropped
                // hint takes its gap with it.
                parts.push(vec![
                    Span::styled(HINT_GAP, muted),
                    Span::styled(binding.key, key_style),
                    Span::styled(format!(" {}", binding.action), muted),
                ]);
            }
            frame.render_widget(
                Paragraph::new(crate::grid::assemble(parts, area.width)),
                area,
            );
            return;
        }

        let spans = vec![Span::styled(
            " mirador",
            Style::default()
                .fg(theme.accent)
                .add_modifier(Modifier::BOLD),
        )];

        // Dropped whole rather than clipped, exactly as the arrange legend
        // above does it: half a hint reads as a rendering fault, a missing one
        // reads as a narrow terminal. This bar had no such guard and did not
        // need one while every primary was a single character — `t theme` was
        // the widest thing in it. Promoting the resize keys made it need one:
        // at 80 columns the bar ended `Ctrl+←`.
        let mut parts = vec![spans];
        for binding in self.keymap.bindings().iter().filter(|b| b.primary) {
            parts.push(vec![
                Span::styled(HINT_GAP, muted),
                Span::styled(binding.key.clone(), key_style),
                Span::styled(format!(" {}", binding.action), muted),
            ]);
        }

        // An alert takes the whole bar rather than sharing it. It outranks the
        // update notice, which does not get worse while you read the alert,
        // and it outranks the key list too, because the *reason* is the
        // actionable part and squeezing it in beside `Tab focus` truncated it
        // to "read-only file syste…". The keys are behind `?`, and an alert is
        // gone as soon as the thing it names is.
        if let Some(alert) = self.alert() {
            frame.render_widget(
                Paragraph::new(alert_line(&alert.text, area.width, theme)),
                area,
            );
            return;
        }

        // 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.
        let mut line = crate::grid::assemble(parts, area.width);
        if let Some(hint) = self.update_hint() {
            let used: usize = line
                .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 {
                line.spans.push(Span::styled(
                    " ".repeat(total - used - hint_width - 1),
                    muted,
                ));
                line.spans
                    .push(Span::styled(hint, Style::default().fg(theme.label)));
            }
        }

        frame.render_widget(Paragraph::new(line), area);
    }

    /// The single most pressing thing, if anything is pressing.
    ///
    /// Absent almost always, which is the point — see [`crate::panel::Alert`].
    /// There is no all-clear: an indicator that says everything is fine is a
    /// light you have to read in order to learn nothing, and reading it is work
    /// a dashboard should not ask for.
    fn alert(&self) -> Option<crate::panel::Alert> {
        // The layout write is the one genuine silent failure in the program.
        // It is reported inside the `w` picker and nowhere else, so a
        // rearrangement that fails to persist says nothing at all once the
        // picker closes — and the change is gone at the next launch.
        let own = self.layout_error.as_ref().map(|why| {
            crate::panel::Alert::failing(format!("The layout could not be saved — {why}"))
        });

        self.slots
            .iter()
            .filter_map(|slot| slot.panel.alert())
            .chain(own)
            // Most severe wins, and the newest of equals — with two levels and
            // both near-never, which one shows barely matters; that it is only
            // ever *one* does.
            .max_by_key(|alert| alert.severity)
    }

    /// 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.
    ///
    /// Rare, actionable now, and it stops being true the moment you act on it —
    /// which is what earned it a place on the bar when the unused-widget hint,
    /// the same every launch until you changed your layout, lost its own.
    fn update_hint(&self) -> Option<String> {
        if !self.show_update_hint {
            return None;
        }
        let latest = self
            .update
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .clone()?;
        Some(format!("mirador {latest} is out   mirador --update "))
    }

    /// The overlay's text: the global keys, then the focused panel's own.
    ///
    /// Split out from `render_help` because that function reached clippy's
    /// hundred-line limit — the same wall `run()` hit when #177 and #182 landed
    /// together. The seam is a real one either way: this half decides what the
    /// overlay *says*, the other half where it sits.
    fn help_lines(
        global: &[Binding],
        panel: Option<(&str, &[Binding])>,
        theme: &crate::theme::Theme,
    ) -> Vec<Line<'static>> {
        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 panel_keys: &[Binding] = panel.map_or(&[], |(_, keys)| keys);
        // Sized to the widest key on show rather than to a constant. The
        // constant was 12, the width of the longest key the program has, so
        // `q` was followed by eleven spaces in every overlay ever drawn and the
        // actions began a third of the way across a 46-cell popup. Still capped
        // at 12: a plugin names its own keys, and one long enough to push the
        // actions off the edge would be a plugin deciding how this dialog is
        // laid out.
        let key_column = global
            .iter()
            .chain(panel_keys)
            .map(|binding| crate::grid::display_width(&binding.key).min(12))
            .max()
            .unwrap_or(1);
        let entry = |binding: &Binding| {
            let key = crate::grid::truncate(&binding.key, key_column);
            let padding = " ".repeat(key_column.saturating_sub(crate::grid::display_width(&key)));
            Line::from(vec![
                Span::styled(format!("  {key}{padding}  "), 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((title, keys)) = panel.filter(|(_, keys)| !keys.is_empty()) {
            lines.push(Line::from(""));
            lines.push(section(title));
            lines.extend(keys.iter().map(entry));
        }
        lines
    }

    fn render_help(&mut self, frame: &mut ratatui::Frame, area: Rect) {
        let theme = &self.config.theme;

        let panel_title = self.slots.get(self.focus).map(|slot| slot.panel.title());
        let lines = Self::help_lines(
            self.keymap.bindings(),
            self.slots
                .get(self.focus)
                .zip(panel_title.as_deref())
                .map(|(slot, title)| (title, slot.panel.bindings())),
            theme,
        );

        // 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.
        //
        // The overlay is 46 cells wide, frame included. The key column's
        // comment in `help_lines` and the doc of the test that sizes it both
        // quote that figure, so they move with it.
        let width = 46.min(area.width);
        let text_width = width.saturating_sub(crate::frame::FRAME_WIDTH).max(1);
        // Pre-wrap with Mirador's cell-aware rules. The focused panel may be an
        // external process, so handing its binding text to ratatui's wrapper
        // would give plugin-controlled emoji and combining marks a known panic
        // path in the host renderer.
        let lines: Vec<Line<'static>> = lines
            .iter()
            .flat_map(|line| crate::grid::wrap_line(line, text_width))
            .collect();
        let text_height = u16::try_from(lines.len()).unwrap_or(u16::MAX);
        let body = Paragraph::new(lines);

        // 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)),
            ]))
            // Right-aligned in the border, the way every panel shows its
            // counter — `?` is where someone goes to find out what the thing
            // does, so it is also where they will look for what version it is,
            // and the border costs no rows to say so.
            .title_top(
                Line::from(vec![
                    Span::styled("┤", Style::default().fg(theme.border_focused)),
                    Span::styled(
                        concat!("v", env!("CARGO_PKG_VERSION")),
                        Style::default().fg(theme.muted),
                    ),
                    Span::styled("├", Style::default().fg(theme.border_focused)),
                ])
                .right_aligned(),
            );
        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.width)),
                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 — so
    /// when there is a position it comes first, ahead of the way to the key
    /// map, and the close hint is short enough that all three fit the
    /// overlay's fixed width, three-digit counts included.
    ///
    /// Each separator leads the part it introduces, so a part dropped for
    /// want of width takes its `·` with it. The first version put the
    /// separator after `? key map`, and was two cells too wide besides: an
    /// overlay that scrolled showed `? key map ·` and nothing else, the
    /// position and the way out both gone.
    /// `the_help_footer_keeps_its_position_and_ends_on_no_separator` pins it.
    fn help_footer(&self, theme: &crate::theme::Theme, width: u16) -> Line<'static> {
        let italic = Style::default()
            .fg(theme.muted)
            .add_modifier(Modifier::ITALIC);
        let key_style = Style::default().fg(theme.key).add_modifier(Modifier::BOLD);

        let mut parts: Vec<Vec<Span<'static>>> = Vec::new();
        let mut push = |mut part: Vec<Span<'static>>| {
            if !parts.is_empty() {
                part.insert(0, Span::styled(" · ", italic));
            }
            parts.push(part);
        };

        if self.help_overflow > 0 {
            let more_above = self.help_scroll > 0;
            let more_below = self.help_scroll < self.help_overflow;
            // The keys that scroll, from `[help_overlay.keys]`: `↑↓` at the
            // defaults, and whatever the reader moved them to otherwise.
            let arrows = crate::keymap::help_scroll_hint(&self.help_keys, more_above, more_below);
            // The count is spaced from the keys, and needs no space when
            // there are none to be spaced from.
            let gap = if arrows.is_some() { " " } else { "" };
            push(vec![
                Span::styled(arrows.unwrap_or_default(), key_style),
                Span::styled(
                    format!(
                        "{gap}{}/{}",
                        self.help_scroll + self.help_viewport,
                        self.help_overflow + self.help_viewport,
                    ),
                    italic,
                ),
            ]);
        }
        // The way to the key map, and the only place it is advertised.
        if let Some(help) = self.keymap.keys(Action::Help).first() {
            push(vec![
                Span::styled(help.to_string(), key_style),
                Span::styled(" key map", italic),
            ]);
        }
        push(vec![Span::styled(
            if self.help_overflow > 0 {
                "other keys close"
            } else {
                "any key to close"
            },
            italic,
        )]);
        crate::grid::assemble(parts, width)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::{Layout as LayoutConfig, LayoutPanel, LayoutRow};
    use crate::store::testing::TempDir;

    /// 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()
        }
    }

    /// The status bar as drawn at `width`, with styling dropped.
    fn status_bar_at(app: &mut App, width: u16) -> String {
        use ratatui::Terminal;
        use ratatui::backend::TestBackend;

        let mut terminal = Terminal::new(TestBackend::new(width, 1)).expect("backend");
        terminal
            .draw(|frame| app.render_status_bar(frame, Rect::new(0, 0, width, 1)))
            .expect("draws");
        crate::widgets::testing::rows(terminal.backend().buffer()).concat()
    }

    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()
    }

    /// The whole grid as widget names, which is what a move is supposed to
    /// change and what a cancelled one is supposed to restore.
    fn widgets_by_row(app: &App) -> Vec<Vec<String>> {
        app.config
            .layout
            .rows
            .iter()
            .map(|row| row.panels.iter().map(|p| p.widget.clone()).collect())
            .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");
    }

    /// The mode has to say that there is a row past the last one. Someone read
    /// `↑↓ move rows`, took it to mean "move between the rows that exist", and
    /// asked how to make a new one — which the mode had done all along.
    #[test]
    fn the_arrange_legend_says_a_row_can_be_opened() {
        let mut app = App::new(resizable()).expect("builds");
        app.handle_key(KeyEvent::from(KeyCode::Char('m')));

        let bar = status_bar_at(&mut app, 110);
        assert!(bar.contains("ARRANGE"), "the mode names itself: {bar}");
        assert!(
            bar.contains("new row"),
            "and says rows can be opened: {bar}"
        );
        // #100 added `Shift+↑↓`, and this legend is the only place the mode's
        // keys are written down — the help overlay carries global keys only. So
        // an ordinary terminal has to show every one of them, which is what
        // forced both vertical hints to be shortened rather than one dropped.
        assert!(
            bar.contains("move row"),
            "and says a row can be moved: {bar}"
        );
    }

    /// The resize keys shipped as `extra` and so appeared only behind `?`.
    /// The owner went looking for them in the status bar, did not find them,
    /// and concluded the feature did not exist — which is the whole argument
    /// for `primary`, and the same failure #109 and #117 already made.
    #[test]
    fn the_resize_keys_are_advertised_on_the_status_bar() {
        let mut app = App::new(resizable()).expect("builds");
        let bar = status_bar_at(&mut app, 120);
        assert!(
            bar.contains("Ctrl+←→↑↓ resize"),
            "resize must be advertised where someone looking for it will look: {bar}"
        );
    }

    /// The bar is built from one table, so a hint cannot be worded differently
    /// in two places — but it *can* be worded differently from the legend and
    /// `--help`, which are separate strings. All three say `Ctrl+←→↑↓`.
    #[test]
    fn the_resize_hint_is_worded_the_way_arrange_mode_words_it() {
        let mut app = App::new(resizable()).expect("builds");
        let plain = status_bar_at(&mut app, 120);
        app.handle_key(KeyEvent::from(KeyCode::Char('m')));
        let legend = status_bar_at(&mut app, 120);
        assert!(
            plain.contains("Ctrl+←→↑↓ resize") && legend.contains("Ctrl+←→↑↓ resize"),
            "the same key must read the same in both bars:\n  {plain}\n  {legend}"
        );
    }

    /// Every width must show whole hints or none — never a fragment. This is
    /// the property the arrange legend has always had and this bar did not:
    /// while every primary was one character the shortfall never showed, and
    /// promoting the resize hint made it show at 80 columns as `Ctrl+←`.
    /// Now that the hint is itself four arrows, a fragment of it would read as
    /// a plausible narrower binding, which is the same fault wearing a
    /// better disguise.
    ///
    /// Asserted by construction rather than by looking for a fragment: the
    /// drawn bar has to be one of the prefixes that end on a hint boundary,
    /// which no partial hint can be.
    #[test]
    fn the_status_bar_never_draws_half_a_hint() {
        let mut app = App::new(resizable()).expect("builds");

        let mut whole = Vec::new();
        let mut acc = String::from(" mirador");
        whole.push(acc.clone());
        for binding in app.keymap.bindings().iter().filter(|b| b.primary) {
            acc.push_str(HINT_GAP);
            acc.push_str(&binding.key);
            acc.push(' ');
            acc.push_str(&binding.action);
            whole.push(acc.clone());
        }

        for width in 8..200u16 {
            let bar = status_bar_at(&mut app, width);
            let drawn = bar.trim_end().to_string();
            assert!(
                whole.contains(&drawn),
                "the bar was cut mid-hint at {width}: {drawn:?}"
            );
            assert!(
                crate::grid::display_width(&drawn) <= usize::from(width),
                "the bar overflowed at {width}: {drawn:?}"
            );
        }
    }

    /// A terminal too narrow for every hint keeps the ones that get you out.
    /// Half a hint reads as a rendering fault; a missing one reads as a narrow
    /// terminal, which is what it is.
    #[test]
    fn a_narrow_arrange_legend_drops_whole_hints_and_keeps_the_way_out() {
        let mut app = App::new(resizable()).expect("builds");
        app.handle_key(KeyEvent::from(KeyCode::Char('m')));

        for width in 40..110u16 {
            let bar = status_bar_at(&mut app, width);
            assert!(
                crate::grid::display_width(bar.trim_end()) <= usize::from(width),
                "the bar overflowed at {width}: {bar}"
            );
            if width >= 46 {
                assert!(bar.contains("Esc cancel"), "no way out at {width}: {bar}");
            }
        }
    }

    /// The day turning is the one source that always fires, which is what
    /// stops the watch log looking broken on a dashboard with no calendar and
    /// nothing falling due. It lives in the shell rather than a panel so that
    /// switching off the task list cannot take it away.
    #[test]
    fn the_day_turning_is_recorded_whatever_panels_are_placed() {
        // Only a clock: neither of the panels that report events is here.
        let mut app = App::new(config_with(&["clocks"])).expect("builds");
        assert!(app.watch.entries().next().is_none(), "nothing yet");

        // Wind the remembered day back, which is what a night does.
        app.today = app.today.yesterday().expect("a day before today exists");
        assert!(app.collect_events(), "the rollover is worth a redraw");

        let entry = app.watch.entries().next().expect("an entry was recorded");
        assert!(
            entry.text.ends_with("began"),
            "reads as a day divider: {}",
            entry.text
        );

        // And only once — a second pass on the same day adds nothing.
        assert!(!app.collect_events(), "the same day is not news twice");
        assert_eq!(app.watch.entries().count(), 1);
    }

    /// The layout write is the one thing in the program that could fail
    /// silently: it was reported inside the `w` picker and nowhere else, so a
    /// rearrangement that did not persist said nothing once the picker closed,
    /// and the change was gone at the next launch.
    #[test]
    fn a_layout_that_would_not_save_reaches_the_status_bar() {
        let mut app = App::new(resizable()).expect("builds");
        assert!(app.alert().is_none(), "nothing is wrong yet");

        app.layout_error = Some("read-only file system (os error 30)".into());
        let alert = app.alert().expect("an alert");
        assert_eq!(alert.severity, crate::panel::Severity::Failing);
        assert!(alert.text.contains("layout"), "names it: {}", alert.text);

        let bar = status_bar_at(&mut app, 120);
        assert!(bar.contains('⚠'), "and it is on the bar: {bar}");
        assert!(bar.contains("os error 30"), "with the reason: {bar}");
    }

    /// There is no all-clear. An indicator saying everything is fine is a light
    /// you have to read to learn nothing, and reading it is work.
    #[test]
    fn a_quiet_dashboard_says_nothing_at_all() {
        let mut app = App::new(resizable()).expect("builds");
        let bar = status_bar_at(&mut app, 120);
        assert!(!bar.contains('⚠'), "no marker: {bar}");
        assert!(
            !bar.to_lowercase().contains("ok") && !bar.to_lowercase().contains("clear"),
            "and no reassurance: {bar}"
        );
    }

    /// The alert is measured where it is built, because a rendered bar only
    /// holds what the terminal kept. At every width it fits the bar, and it is
    /// either the marker and the whole alert or ends in `…` — and a bar too
    /// narrow for the marker still says it was cut, rather than drawing
    /// ` ⚠ ` over an alert that is not there.
    #[test]
    fn the_alert_line_never_outgrows_the_bar() {
        let theme = crate::theme::Theme::default();
        for text in [
            "The layout could not be saved — read-only file system",
            "設定を保存できませんでした 🌞 ディスクがいっぱいです",
        ] {
            let whole = format!("{ALERT_MARKER}{text}");
            let mut cut = false;
            for width in 1..=80u16 {
                let line: String = alert_line(text, width, &theme)
                    .spans
                    .iter()
                    .map(|span| span.content.as_ref())
                    .collect();
                assert!(
                    crate::grid::display_width(&line) <= usize::from(width),
                    "{line:?} is wider than {width}"
                );
                if let Some(head) = line.strip_suffix('…') {
                    assert!(whole.starts_with(head), "{width}: {line:?}");
                    cut = true;
                } else {
                    assert_eq!(line, whole, "cut with nothing to say so at {width}");
                }
            }
            assert!(cut, "a sweep that never cut {text:?} tests nothing");
        }
    }

    /// An alert outranks the update notice. That notice is not going to get
    /// worse while you read the alert; the alert might.
    #[test]
    fn an_alert_displaces_the_hints_rather_than_queueing_behind_them() {
        let mut app = App::new(config_with(&["clocks"])).expect("builds");
        app.watch_for_updates(std::sync::Arc::new(std::sync::Mutex::new(Some(
            "9.9.9".to_string(),
        ))));
        let before = status_bar_at(&mut app, 200);
        assert!(before.contains("9.9.9"), "the notice is there to displace");

        app.layout_error = Some("disk full".into());
        let after = status_bar_at(&mut app, 200);
        assert!(after.contains("disk full"), "the alert shows: {after}");
        assert!(
            !after.contains("9.9.9"),
            "and the notice gives way: {after}"
        );
    }

    /// The mode has to claim the bare arrows before panels do, for the same
    /// reason the resize keys are claimed: the calendar binds plain arrows and
    /// does not inspect modifiers, so a left arrow meant to move a panel would
    /// scroll a month instead.
    #[test]
    fn arrange_claims_the_arrows_the_focused_panel_would_otherwise_take() {
        let mut app = App::new(resizable()).expect("builds");
        app.handle_key(KeyEvent::from(KeyCode::Char('m')));
        assert!(app.arranging.is_some(), "m opened the mode");

        let before = widgets_by_row(&app);
        app.handle_key(KeyEvent::from(KeyCode::Right));
        assert_ne!(
            widgets_by_row(&app),
            before,
            "the arrow moved a panel rather than reaching the calendar"
        );
    }

    /// Esc means "back out of this" everywhere else in mirador, and an
    /// arrangement is exactly the kind of change worth being able to abandon.
    #[test]
    fn esc_puts_the_layout_back_exactly_as_it_was() {
        let mut app = App::new(resizable()).expect("builds");
        let before = widgets_by_row(&app);

        app.handle_key(KeyEvent::from(KeyCode::Char('m')));
        for code in [KeyCode::Right, KeyCode::Down, KeyCode::Up] {
            app.handle_key(KeyEvent::from(code));
        }
        assert_ne!(widgets_by_row(&app), before, "something actually moved");

        app.handle_key(KeyEvent::from(KeyCode::Esc));
        assert!(app.arranging.is_none(), "the mode closed");
        assert_eq!(widgets_by_row(&app), before, "and the layout came back");
        assert!(
            !app.layout_dirty,
            "a cancelled arrangement leaves nothing to write"
        );
    }

    /// A resize made before the mode opened is not part of the arrangement, so
    /// cancelling must not swallow it. Restoring the layout and clearing the
    /// flag unconditionally would lose a change the user had already made.
    #[test]
    fn cancelling_does_not_discard_a_change_made_before_the_mode_opened() {
        let mut app = App::new(resizable()).expect("builds");
        app.handle_key(KeyEvent::new(KeyCode::Right, KeyModifiers::CONTROL));
        assert!(app.layout_dirty, "the resize is waiting to be written");

        app.handle_key(KeyEvent::from(KeyCode::Char('m')));
        app.handle_key(KeyEvent::from(KeyCode::Down));
        app.handle_key(KeyEvent::from(KeyCode::Esc));

        assert!(
            app.layout_dirty,
            "the earlier resize still needs writing after the cancel"
        );
    }

    /// Focus follows the widget rather than the slot index, so the panel you
    /// are moving stays the one under the highlight. Without this you would
    /// move a panel once and then start moving whatever slid into its place.
    #[test]
    fn the_moved_panel_keeps_the_focus() {
        let mut app = App::new(resizable()).expect("builds");
        app.focus = 0;
        let moving = app.slots[0].widget.clone();

        app.handle_key(KeyEvent::from(KeyCode::Char('m')));
        app.handle_key(KeyEvent::from(KeyCode::Right));

        assert_eq!(
            app.slots[app.focus].widget, moving,
            "the highlight went with the panel"
        );
    }

    /// #100, tested through the shell rather than through `arrange::move_row`.
    ///
    /// The arithmetic having its own tests is not enough — #106 shipped a
    /// correct helper that was simply never called, and two unit tests passed
    /// throughout. This presses the key.
    #[test]
    fn shift_arrows_move_the_whole_row_in_arrange_mode() {
        let mut app = App::new(resizable()).expect("builds");
        // `resizable` is [clocks, calendar] over [cpu]. Focus the lone panel in
        // the second row — before #100 it could only ever merge upward.
        app.focus = 2;
        let moving = app.slots[2].widget.clone();
        assert_eq!(moving, "cpu", "fixture changed under this test");

        app.handle_key(KeyEvent::from(KeyCode::Char('m')));
        app.handle_key(KeyEvent::new(KeyCode::Up, KeyModifiers::SHIFT));

        assert_eq!(
            app.config.layout.rows.len(),
            2,
            "moving a row must not merge it away"
        );
        assert_eq!(
            app.config.layout.rows[0].panels[0].widget, "cpu",
            "the cpu row should now be first"
        );
        assert_eq!(
            app.slots[app.focus].widget, moving,
            "the highlight went with the panel"
        );
        assert!(app.arranging.is_some(), "and the mode stayed open");
    }

    /// `J`/`K` are the same gesture without a modifier, matching the clock
    /// panel. Bare `j`/`k` must still move the *panel*, or the shifted pair
    /// would have quietly replaced the plain one.
    #[test]
    fn capital_and_plain_movement_keys_do_different_things() {
        let mut app = App::new(resizable()).expect("builds");
        app.focus = 2;
        app.handle_key(KeyEvent::from(KeyCode::Char('m')));
        app.handle_key(KeyEvent::from(KeyCode::Char('K')));
        assert_eq!(
            app.config.layout.rows[0].panels[0].widget, "cpu",
            "K should have moved the row"
        );

        // And the plain key still merges, which is the behaviour #100 was
        // careful not to take away.
        let mut app = App::new(resizable()).expect("builds");
        app.focus = 2;
        app.handle_key(KeyEvent::from(KeyCode::Char('m')));
        app.handle_key(KeyEvent::from(KeyCode::Char('k')));
        assert_eq!(
            app.config.layout.rows.len(),
            1,
            "plain k should still merge the panel into the row above"
        );
    }

    /// The arrows are the mode's, but Ctrl+arrow still has to reach the resize
    /// path — rearranging is exactly when you want to adjust proportions.
    #[test]
    fn ctrl_arrows_still_resize_inside_arrange_mode() {
        let mut app = App::new(resizable()).expect("builds");
        app.handle_key(KeyEvent::from(KeyCode::Char('m')));

        let before = widths(&app);
        app.handle_key(KeyEvent::new(KeyCode::Right, KeyModifiers::CONTROL));
        assert_ne!(widths(&app), before, "Ctrl+Right resized rather than moved");
        assert!(app.arranging.is_some(), "and did not close the mode");
    }

    #[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"
        );
    }

    /// A panel that will not build refuses the toggle: the layout and the
    /// panels on screen are the ones from before, nothing is left to write,
    /// and the picker is told why. Under test `weather` is such a panel — it
    /// would start a fetch thread — and a toggle that does build afterwards
    /// clears the reason again.
    #[test]
    fn a_panel_that_will_not_build_is_refused_and_the_layout_put_back() {
        let mut app = App::new(config_with(&["clocks", "todo"])).unwrap();
        let layout = widgets_by_row(&app);
        let panels: Vec<*const u8> = app
            .slots
            .iter()
            .map(|slot| std::ptr::from_ref(&*slot.panel).cast::<u8>())
            .collect();

        app.toggle_widget("weather");
        assert_eq!(widgets_by_row(&app), layout, "the layout came back");
        let after: Vec<*const u8> = app
            .slots
            .iter()
            .map(|slot| std::ptr::from_ref(&*slot.panel).cast::<u8>())
            .collect();
        assert_eq!(after, panels, "and so did the very same panels");
        assert!(!app.layout_dirty, "a refusal leaves nothing to write");
        let notice = app.layout_notice.clone().unwrap_or_default();
        assert!(
            notice.contains("`weather`"),
            "the picker says why: {notice:?}"
        );

        app.toggle_widget("notes");
        assert!(app.config.layout.places("notes"));
        assert!(
            app.layout_dirty,
            "a toggle that took is waiting to be written"
        );
        assert_eq!(app.layout_notice, None, "and the old reason is gone");
    }

    #[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() {
        // 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 the_update_notice_has_the_end_of_the_status_bar_to_itself() {
        // It used to share the row with a hint listing the widgets your layout
        // left out. That hint is gone — see
        // `a_layout_missing_widgets_is_not_advertised_anywhere` — so the update
        // notice is the only thing that can appear here.
        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(),
        ))));
        let shown = app.update_hint().expect("an update is waiting");
        assert!(shown.contains("9.9.9"), "got `{shown}`");
    }

    /// A layout that leaves widgets out is a decision, not an oversight.
    ///
    /// mirador used to say so — once in the status bar at startup, and for ever
    /// in the help overlay. The status bar line retired on the first keypress;
    /// the overlay section did not, so someone who had deliberately switched
    /// four panels off was told about them every time they pressed `?`. That is
    /// the nagging this dashboard exists not to do, arrived at from the
    /// direction of helpfulness rather than of notifications.
    ///
    /// `w` is still a primary binding, so the way to switch a panel on is on
    /// the status bar and in the help. What is gone is being told you *should*.
    #[test]
    fn a_layout_missing_widgets_is_not_advertised_anywhere() {
        // One panel out of fourteen, so thirteen are unused — the loudest possible
        // case for the hint that used to be here.
        let mut app = App::new(config_with(&["clocks"])).unwrap();
        let screen = |app: &mut App, help: bool| -> String {
            if help {
                app.handle_key(KeyEvent::from(KeyCode::Char('?')));
            }
            drawn(app, 200, 40).join("\n")
        };

        let dashboard = screen(&mut app, false);
        assert!(
            !dashboard.contains("unused"),
            "the dashboard advertises what you chose not to run"
        );

        let help = screen(&mut app, true);
        assert!(app.show_help, "the overlay is open");
        for banned in ["unused", "not in your layout", "switch them on"] {
            assert!(
                !help.contains(banned),
                "the help overlay still nags about unused widgets: found `{banned}`"
            );
        }
    }

    /// The key column was a hardcoded 12 — the width of the longest key the
    /// program has — so every overlay ever drawn put eleven spaces after `q`
    /// and began its actions a third of the way across a 46-cell popup.
    ///
    /// Asserted against the widest key actually on show, not against a number:
    /// a test that pinned 9 would have to be edited by whoever next renames a
    /// binding, and would pass just as happily if the column went back to being
    /// a constant that happened to equal 9.
    #[test]
    fn the_help_overlay_sizes_its_key_column_to_the_keys_it_shows() {
        let mut app = App::new(config_with(&["clocks"])).unwrap();
        app.handle_key(KeyEvent::from(KeyCode::Char('?')));
        let rows = drawn(&mut app, 120, 40);

        let widest = app
            .keymap
            .bindings()
            .iter()
            .chain(app.slots[app.focus].panel.bindings())
            .map(|binding| crate::grid::display_width(&binding.key))
            .max()
            .expect("there are bindings");
        assert!(
            widest < 12,
            "no key is 12 cells wide any more, so a column of 12 is padding: {widest}"
        );

        // `q quit` is the shortest key in the overlay and so the one the old
        // constant punished hardest. Its action must start where every other
        // action starts.
        let row = rows
            .iter()
            .find(|row| row.contains(" q ") && row.contains("quit"))
            .expect("the overlay lists `q quit`");
        let key_at = row.find('q').expect("the key is on the row");
        let action_at = row.find("quit").expect("the action is on the row");
        assert_eq!(
            action_at - key_at,
            widest + 2,
            "the action starts one column past the widest key plus its gap: {row:?}"
        );
    }

    /// Two list panels with their files in a scratch directory, so nothing a
    /// test does can reach the user's own tasks or notes.
    fn two_lists(name: &str) -> (Config, TempDir) {
        let dir = TempDir::new(&format!("app-{name}"));
        let mut config = config_with(&["notes", "todo"]);
        config.notes.file = Some(dir.join("notes.toml"));
        config.todo.file = Some(dir.join("todos.toml"));
        (config, dir)
    }

    /// The rows of the dashboard as drawn, so a test can read where things are.
    fn drawn(app: &mut App, width: u16, height: u16) -> Vec<String> {
        use ratatui::Terminal;
        use ratatui::backend::TestBackend;
        let mut terminal = Terminal::new(TestBackend::new(width, height)).unwrap();
        terminal.draw(|frame| app.render_for_test(frame)).unwrap();
        crate::widgets::testing::rows(terminal.backend().buffer())
    }

    /// The screen row carrying the selection marker inside `area`, if any.
    fn marker_row(rows: &[String], area: Rect) -> Option<u16> {
        (area.y..area.y + area.height).find(|&y| {
            let row = &rows[usize::from(y)];
            row.chars()
                .skip(usize::from(area.x))
                .take(usize::from(area.width))
                .any(|c| c == '▸')
        })
    }

    fn at(kind: MouseEventKind, column: u16, row: u16) -> MouseEvent {
        MouseEvent {
            kind,
            column,
            row,
            modifiers: KeyModifiers::NONE,
        }
    }

    /// `handle_mouse` goes to the panel under the *pointer*, and a scroll must
    /// move the list it is aimed at without yanking the keyboard away from
    /// what the user was typing in. Nothing exercised that seam: every mouse
    /// path in the panels was unexecuted by the suite.
    ///
    /// Observed from the outside, since the panel's selection is its own: the
    /// tasks panel draws its marker only while focused, so focus is moved
    /// there *afterwards* with Tab and the marker is read from the second row,
    /// where the scroll left it — against a control that never scrolled and
    /// finds it on the first.
    #[test]
    fn a_scroll_acts_on_the_panel_under_the_pointer_and_leaves_focus_where_it_was() {
        let (config, _dir) = two_lists("scroll");
        let mut app = App::new(config.clone()).unwrap();
        let rows = drawn(&mut app, 120, 30);
        let todo = app.slots[1].area.expect("the tasks panel was drawn");
        assert_eq!(app.focus, 0, "notes start focused");
        assert!(
            marker_row(&rows, todo).is_none(),
            "unfocused, the tasks panel draws no marker"
        );

        let redraw = app.handle_mouse(at(MouseEventKind::ScrollDown, todo.x + 3, todo.y + 3));
        assert!(redraw, "the wheel over a list is consumed by it");
        assert_eq!(app.focus, 0, "and focus did not move");

        app.handle_key(KeyEvent::from(KeyCode::Tab));
        let after = drawn(&mut app, 120, 30);
        let scrolled = marker_row(&after, todo).expect("focused, the marker shows");

        let mut control = App::new(config).unwrap();
        drawn(&mut control, 120, 30);
        control.handle_key(KeyEvent::from(KeyCode::Tab));
        let untouched = marker_row(&drawn(&mut control, 120, 30), todo).unwrap();
        assert_eq!(
            scrolled,
            untouched + 1,
            "the scroll moved the selection one row while the panel was not focused"
        );
    }

    /// A click focuses the panel it lands in and selects the row it hit.
    #[test]
    fn a_click_focuses_the_panel_under_the_pointer_and_selects_the_row_it_hit() {
        let (config, _dir) = two_lists("click");
        let mut app = App::new(config).unwrap();
        let rows = drawn(&mut app, 120, 30);
        let todo = app.slots[1].area.unwrap();
        // The third task row: header line, column headings, then tasks.
        // Columns, not bytes: the frame's `│` is three bytes wide and one
        // cell, which is invariant 9 reaching into a test.
        let target = (todo.y..todo.y + todo.height)
            .filter(|&y| {
                rows[usize::from(y)]
                    .chars()
                    .skip(usize::from(todo.x))
                    .collect::<String>()
                    .contains("[ ]")
            })
            .nth(2)
            .expect("three task rows on screen");

        app.handle_mouse(at(
            MouseEventKind::Down(ratatui::crossterm::event::MouseButton::Left),
            todo.x + 6,
            target,
        ));
        assert_eq!(app.focus, 1, "the click moved focus to the tasks panel");
        let after = drawn(&mut app, 120, 30);
        assert_eq!(
            marker_row(&after, todo),
            Some(target),
            "and selected the row it hit"
        );
    }

    /// A panel in a text-entry state has 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.
    #[test]
    fn an_open_form_vetoes_a_click_landing_in_another_panel() {
        let (config, _dir) = two_lists("veto");
        let mut app = App::new(config).unwrap();
        drawn(&mut app, 120, 30);
        let notes = app.slots[0].area.unwrap();

        app.handle_key(KeyEvent::from(KeyCode::Tab));
        assert_eq!(app.focus, 1);
        app.handle_key(KeyEvent::from(KeyCode::Char('a')));
        assert!(app.focus_captures_input(), "the task form is open");

        app.handle_mouse(at(
            MouseEventKind::Down(ratatui::crossterm::event::MouseButton::Left),
            notes.x + 2,
            notes.y + 2,
        ));
        assert_eq!(app.focus, 1, "focus stayed with the form");
        assert!(app.focus_captures_input(), "and the form is still open");
    }

    /// Invariant 17, at the seam that shipped wrong twice: the *App* gathers
    /// what every panel reports, compares it against the config once, and
    /// writes only the difference — so a preference toggled back to what the
    /// config says leaves the file rather than asserting itself for ever.
    /// `UiState` has unit tests for the comparison; nothing had ever driven
    /// the plumbing that calls it.
    #[test]
    fn a_preference_moved_off_the_config_is_written_and_moved_back_is_retracted() {
        let dir = TempDir::new("prefs");
        let path = dir.join("state.toml");
        let config = config_with(&["clocks"]);
        let baseline = crate::state::UiState::from_config(&config);
        let mut app = App::new(config).unwrap();
        app.remember_preferences_at(path.clone(), crate::state::UiState::default(), baseline);

        app.handle_key(KeyEvent::from(KeyCode::Char('s')));
        app.persist_preferences();
        let written = std::fs::read_to_string(&path).expect("a change was written");
        assert!(
            written.contains("clocks_show_seconds = false"),
            "the toggle is recorded as a difference from the config: {written}"
        );

        app.handle_key(KeyEvent::from(KeyCode::Char('s')));
        app.persist_preferences();
        let written = std::fs::read_to_string(&path).unwrap();
        assert!(
            !written.contains("clocks_show_seconds"),
            "toggled back to the config's value, the entry is gone: {written:?}"
        );
    }

    /// The picker's edit reaches the config file as a textual edit that keeps
    /// the comments, and a file the editor cannot work on is refused and
    /// reported rather than rewritten. Both halves through the keys, not by
    /// calling `layout_edit` directly.
    #[test]
    fn a_picker_change_is_written_to_the_config_and_an_uneditable_file_is_reported() {
        let dir = TempDir::new("layout");

        // One panel per line, the way the shipped config is written: the
        // editor rebuilds a row from captured panel *lines*, and a comment
        // above a panel travels with it.
        let editable = "[layout]\nrows = [\n  { height = 1, panels = [\n    # keep me\n    { widget = \"clocks\",   width = 1 },\n    { widget = \"calendar\", width = 1 },\n  ] },\n]\n";
        let path = dir.join("config.toml");
        std::fs::write(&path, editable).unwrap();
        let config: Config = toml::from_str(editable).expect("a minimal config parses");

        let mut app = App::new(config.clone()).unwrap();
        app.write_layout_to(path.clone());
        app.handle_key(KeyEvent::from(KeyCode::Char('w')));
        assert!(app.picker.is_some(), "`w` opens the picker");
        // Down to `calendar` — sixth in `widget_names` — and switch it off.
        for _ in 0..5 {
            app.handle_key(KeyEvent::from(KeyCode::Down));
        }
        assert_eq!(
            app.picker.as_ref().map(crate::picker::Picker::selected),
            Some(5)
        );
        app.handle_key(KeyEvent::from(KeyCode::Char(' ')));
        app.handle_key(KeyEvent::from(KeyCode::Esc));

        assert_eq!(app.layout_error, None, "the edit was accepted");
        let after = std::fs::read_to_string(&path).unwrap();
        assert!(
            !after.contains("calendar"),
            "calendar left the layout: {after}"
        );
        assert!(after.contains("# keep me"), "the comment survived: {after}");
        assert!(after.contains("\"clocks\""), "clocks stayed: {after}");

        // The other spelling loads but cannot be edited; the file is left
        // exactly as it was and the failure is on the bar, not swallowed.
        let sections = "# keep me\n[[layout.rows]]\nheight = 1\n[[layout.rows.panels]]\nwidget = \"clocks\"\nwidth = 1\n[[layout.rows.panels]]\nwidget = \"calendar\"\nwidth = 1\n";
        let other = dir.join("sections.toml");
        std::fs::write(&other, sections).unwrap();
        let mut app = App::new(config).unwrap();
        app.write_layout_to(other.clone());
        app.handle_key(KeyEvent::from(KeyCode::Char('w')));
        for _ in 0..5 {
            app.handle_key(KeyEvent::from(KeyCode::Down));
        }
        app.handle_key(KeyEvent::from(KeyCode::Char(' ')));
        app.handle_key(KeyEvent::from(KeyCode::Esc));
        assert!(
            app.layout_error.is_some(),
            "a file it cannot edit is reported"
        );
        assert_eq!(
            std::fs::read_to_string(&other).unwrap(),
            sections,
            "and left untouched"
        );
    }

    #[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.watch_for_updates(std::sync::Arc::new(std::sync::Mutex::new(Some(
            "9.9.9".to_string(),
        ))));
        app.handle_mouse(mouse(MouseEventKind::Moved));
        assert!(
            app.update_hint().is_some(),
            "the mouse crossing the window is not the user reading anything"
        );

        app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left)));
        assert!(app.update_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");
    }

    /// The paste half of the test above. A paste retires the notice and marks
    /// the watch log seen, as a key does — but where `run` redraws after every
    /// key, it redraws after a paste only when `handle_paste` asks, and a
    /// paste the focused panel does not take asked for nothing. The notice
    /// then stayed on screen until something else happened to redraw, and so
    /// did a rule line the paste had just made untrue.
    #[test]
    fn retiring_the_hint_by_paste_forces_a_redraw_too() {
        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());
        let dirty = app.handle_paste("hello");
        assert!(app.update_hint().is_none(), "a paste retires the notice");
        assert!(
            dirty,
            "the notice was retired, so the screen is out of date"
        );

        // The rule line alone, with the notice already gone: one entry from
        // before the reader was last here and one from after, which is the one
        // state that draws a line. Spinning until the clock moves keeps the
        // second strictly after that moment and before the paste's own.
        let mut app = App::new(config_with(&["clocks"])).unwrap();
        app.show_update_hint = false;
        let an_hour_ago = jiff::Zoned::now()
            .checked_sub(jiff::Span::new().hours(1))
            .unwrap();
        app.watch.push(crate::watch::Event {
            at: an_hour_ago,
            source: "test".into(),
            text: "before".into(),
        });
        app.watch.mark_seen();
        let seen = jiff::Zoned::now();
        while jiff::Zoned::now() <= seen {
            std::hint::spin_loop();
        }
        app.watch.push(crate::watch::Event::new("test", "after"));
        assert_eq!(app.watch.unseen(), Some(1), "the line is on screen");
        let dirty = app.handle_paste("hello");
        assert_eq!(app.watch.unseen(), None, "the paste marked it seen");
        assert!(dirty, "the line moved, so the screen is out of date");
    }

    #[test]
    fn the_help_overlay_renders_at_any_size() {
        use ratatui::Terminal;
        use ratatui::backend::TestBackend;

        // The overlay clips silently rather than erroring, so a size that
        // cannot fit its text must still draw something rather than panic on
        // the arithmetic. It once carried an unused-widget section that made
        // it taller still; the section is gone and the sizes stay.
        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_hint_gives_way_to_the_global_keys_on_a_narrow_terminal() {
        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(),
        ))));
        let row_text = |app: &mut App, width: u16| -> String { drawn(app, width, 6)[5].clone() };

        // Wide enough for the global keys *and* the notice.
        let wide = row_text(&mut app, 200);
        assert!(wide.contains("9.9.9"), "wide enough for both: `{wide}`");

        let narrow = row_text(&mut app, 44);
        assert!(
            !narrow.contains("9.9.9"),
            "knowing how to quit outranks the notice: `{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]);
    }

    /// A maximum with no weight beside it was ignored in silence, and a weight
    /// with no maximum panicked on an index; both are a caller pairing the
    /// wrong slices, and the assertion says so by name. A debug assertion, so
    /// the test is a debug build's only.
    #[test]
    #[cfg(debug_assertions)]
    #[should_panic(expected = "one maximum per weight")]
    fn distribute_refuses_maxima_that_do_not_pair_with_the_weights() {
        distribute(100, &[50, 50], &[None, None, Some(10)]);
    }

    #[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]);
        let shares = distribute(10, &[], &[]);
        assert!(shares.is_empty(), "{shares:?}");
        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!(slot_positions(&app), 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);
    }

    /// Where each slot says it sits in `config.layout`, in slot order.
    fn slot_positions(app: &App) -> Vec<(usize, usize)> {
        app.slots.iter().map(|slot| slot.position).collect()
    }

    /// Every slot's `(row, column)` names the layout entry it was built for,
    /// through every kind of rebuild: a panel moved along its row and into
    /// the next, a whole row moved, and a panel toggled off and back on in
    /// the picker. A resize, a move and `geometry` all find a panel's place
    /// from it, so a slot left holding the place it had before a rebuild
    /// resizes the wrong weights and draws in another panel's box.
    #[test]
    fn every_slot_knows_where_it_sits_after_a_rebuild() {
        let check = |app: &App, after: &str| {
            for (slot, (row, column)) in app.slots.iter().zip(slot_positions(app)) {
                let entry = app
                    .config
                    .layout
                    .rows
                    .get(row)
                    .and_then(|r| r.panels.get(column))
                    .map(|entry| entry.widget.as_str());
                assert_eq!(
                    entry,
                    Some(slot.widget.as_str()),
                    "after {after}, the `{}` slot says it sits at ({row}, {column})",
                    slot.widget
                );
            }
        };
        let mut app = App::new(resizable()).expect("builds");
        check(&app, "building");
        let before = widgets_by_row(&app);

        app.focus = 0;
        app.handle_key(key(KeyCode::Char('m')));
        app.handle_key(key(KeyCode::Right));
        check(&app, "a move along the row");
        app.handle_key(key(KeyCode::Down));
        check(&app, "a move into the next row");
        app.handle_key(KeyEvent::new(KeyCode::Up, KeyModifiers::SHIFT));
        check(&app, "a row move");
        app.handle_key(key(KeyCode::Enter));
        assert_ne!(widgets_by_row(&app), before, "the moves moved nothing");

        app.handle_key(key(KeyCode::Char('w')));
        app.handle_key(key(KeyCode::Char(' ')));
        check(&app, "a toggle off");
        app.handle_key(key(KeyCode::Char(' ')));
        check(&app, "a toggle back on");
    }

    #[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 = 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.
        //
        // The calls are counted by the panels themselves. This test used to
        // check `last_tick`, which `tick_panels` sets on the next line whether
        // or not `tick()` ran, so it passed with the short-circuit put back.
        struct TickingPanel {
            ticks: std::rc::Rc<std::cell::Cell<usize>>,
        }

        impl crate::panel::Panel for TickingPanel {
            fn title(&self) -> String {
                "ticking test".into()
            }

            fn tick(&mut self) -> bool {
                self.ticks.set(self.ticks.get() + 1);
                true
            }

            fn render(
                &mut self,
                _frame: &mut ratatui::Frame,
                _area: Rect,
                _ctx: crate::panel::RenderContext<'_>,
            ) {
            }
        }

        let first = std::rc::Rc::new(std::cell::Cell::new(0));
        let second = std::rc::Rc::new(std::cell::Cell::new(0));
        let panels: Vec<(&str, Box<dyn Panel>)> = vec![
            (
                "clocks",
                Box::new(TickingPanel {
                    ticks: first.clone(),
                }),
            ),
            (
                "todo",
                Box::new(TickingPanel {
                    ticks: second.clone(),
                }),
            ),
        ];
        let mut app = App::with_panels(config_with(&["clocks", "todo"]), panels).unwrap();
        for slot in &mut app.slots {
            slot.last_tick = None;
        }
        assert!(app.tick_panels(), "both panels reported a change");
        assert_eq!(
            (first.get(), second.get()),
            (1, 1),
            "each due panel is ticked once, the second even after the first changed"
        );
    }

    #[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"
        );
    }

    /// `config` with `[keys]` set from `toml_text`.
    fn with_keys(config: Config, toml_text: &str) -> Config {
        Config {
            keys: crate::keymap::keys_config(toml_text),
            ..config
        }
    }

    /// A rebound quit key replaces `q` rather than joining it, and Ctrl+C is
    /// untouched by any of it — invariant 2's way out does not depend on the
    /// reader's config being sensible.
    #[test]
    fn a_rebound_quit_key_replaces_q_and_ctrl_c_still_quits() {
        let config = || with_keys(config_with(&["clocks"]), "[keys]\nquit = \"x\"");

        let mut app = App::new(config()).unwrap();
        app.handle_key(KeyEvent::from(KeyCode::Char('q')));
        assert!(!app.should_quit, "q is no longer the quit key");
        app.handle_key(KeyEvent::from(KeyCode::Char('x')));
        assert!(app.should_quit, "x is");

        let mut app = App::new(config()).unwrap();
        app.handle_key(KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL));
        assert!(app.should_quit, "and Ctrl+C always is");
    }

    /// #284, end to end: Ctrl+arrows switch desktops on a Mac, so resize moves
    /// to Alt. Alt resizes, Ctrl no longer does, arrange mode lets Alt through
    /// the way it let Ctrl through, and both bars say where the keys went.
    #[test]
    fn resize_rebound_to_alt_works_everywhere_ctrl_did() {
        let config = with_keys(
            resizable(),
            r#"
            [keys]
            resize_wider = "alt+right"
            resize_narrower = "alt+left"
            resize_taller = "alt+down"
            resize_shorter = "alt+up"
            "#,
        );
        let widths = |app: &App| -> Vec<u16> {
            app.config.layout.rows[0]
                .panels
                .iter()
                .map(|p| p.width)
                .collect()
        };
        let mut app = App::new(config).expect("builds");
        app.focus = 0;
        let before = widths(&app);

        app.handle_key(KeyEvent::new(KeyCode::Right, KeyModifiers::CONTROL));
        assert_eq!(widths(&app), before, "Ctrl+→ is not a resize key any more");

        app.handle_key(KeyEvent::new(KeyCode::Right, KeyModifiers::ALT));
        let widened = widths(&app);
        assert!(widened[0] > before[0], "Alt+→ widened the panel");

        app.handle_key(KeyEvent::from(KeyCode::Char('m')));
        let arrangement = widgets_by_row(&app);
        app.handle_key(KeyEvent::new(KeyCode::Right, KeyModifiers::ALT));
        assert_eq!(
            widgets_by_row(&app),
            arrangement,
            "inside arrange mode Alt+→ resized rather than moving the panel"
        );
        assert!(widths(&app)[0] > widened[0], "and it did resize");

        let legend = status_bar_at(&mut app, 120);
        app.handle_key(KeyEvent::from(KeyCode::Enter));
        let plain = status_bar_at(&mut app, 120);
        for bar in [&plain, &legend] {
            assert!(bar.contains("Alt+←→↑↓ resize"), "{bar}");
            assert!(!bar.contains("Ctrl+←"), "{bar}");
        }
    }

    /// A config file of its own, removed when the test ends.
    struct KeysFile {
        path: std::path::PathBuf,
        _dir: TempDir,
    }

    impl KeysFile {
        fn new(name: &str, text: &str) -> Self {
            let dir = TempDir::new(&format!("keymap-{name}"));
            let path = dir.join("config.toml");
            std::fs::write(&path, text).expect("write");
            Self { path, _dir: dir }
        }

        fn text(&self) -> String {
            std::fs::read_to_string(&self.path).expect("read")
        }
    }

    fn open_key_map(app: &mut App) {
        app.handle_key(KeyEvent::from(KeyCode::Char('?')));
        assert!(app.show_help, "the first press opens help");
        app.handle_key(KeyEvent::from(KeyCode::Char('?')));
        assert!(
            !app.show_help && app.keymap_dialog.is_some(),
            "the second, the key map"
        );
    }

    /// The only place the key map is advertised is the help overlay's footer,
    /// so the footer has to say it — in the help key's own name.
    #[test]
    fn help_says_how_to_reach_the_key_map_and_the_key_map_opens() {
        let mut app = App::new(config_with(&["clocks"])).unwrap();
        app.handle_key(KeyEvent::from(KeyCode::Char('?')));
        let backend = ratatui::backend::TestBackend::new(100, 40);
        let mut terminal = ratatui::Terminal::new(backend).expect("terminal");
        terminal.draw(|frame| app.render(frame)).expect("draw");
        let screen: String = terminal
            .backend()
            .buffer()
            .content()
            .iter()
            .map(ratatui::buffer::Cell::symbol)
            .collect();
        assert!(screen.contains("? key map"), "the footer names the way in");

        app.handle_key(KeyEvent::from(KeyCode::Char('?')));
        assert!(app.keymap_dialog.is_some());
        app.handle_key(KeyEvent::from(KeyCode::Esc));
        assert!(app.keymap_dialog.is_none(), "Esc closes it");
        assert!(!app.should_quit);
    }

    /// Invariant 2 holds inside the dialog too: it reads keys, and Ctrl+C is
    /// taken before it can.
    #[test]
    fn ctrl_c_quits_from_inside_the_key_map_even_mid_question() {
        let mut app = App::new(config_with(&["clocks"])).unwrap();
        open_key_map(&mut app);
        app.handle_key(KeyEvent::from(KeyCode::Char('d')));
        app.handle_key(KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL));
        assert!(app.should_quit);
    }

    /// Edit the config, press `r`, and the new keys are live — no restart.
    /// A bad edit is reported and the keys in force stay in force.
    #[test]
    fn reload_applies_a_good_edit_and_refuses_a_bad_one() {
        let file = KeysFile::new("reload", "[keys]\nquit = \"x\"\n");
        let mut app = App::new(config_with(&["clocks"])).unwrap();
        app.write_layout_to(file.path.clone());
        open_key_map(&mut app);

        app.handle_key(KeyEvent::from(KeyCode::Char('r')));
        assert_eq!(
            app.keymap.action(KeyEvent::from(KeyCode::Char('x'))),
            Some(Action::Quit),
            "the edit is live"
        );

        std::fs::write(&file.path, "[keys]\ntheme = \"q\"\n").expect("write");
        app.handle_key(KeyEvent::from(KeyCode::Char('r')));
        assert_eq!(
            app.keymap.action(KeyEvent::from(KeyCode::Char('x'))),
            Some(Action::Quit),
            "a clash is refused and x still quits"
        );
    }

    /// A panel's keys reload and reset with the shell's, and the panel that
    /// is already on screen takes them at once — it is carried across, not
    /// rebuilt, so nothing but [`Panel::set_keys`] would ever tell it.
    #[test]
    fn a_live_panel_takes_its_keys_from_a_reload_and_gives_them_back_on_reset() {
        use crate::panel::KeyOutcome;
        let file = KeysFile::new(
            "panel",
            "[cpu]\nhistory = 5\n\n[cpu.keys]\nper_core = \"p\"\n",
        );
        let mut app = App::new(config_with(&["cpu"])).unwrap();
        app.write_layout_to(file.path.clone());
        let press = |app: &mut App, c| {
            app.slots[0]
                .panel
                .handle_key(KeyEvent::from(KeyCode::Char(c)))
        };
        let hinted =
            |app: &App, key: &str| app.slots[0].panel.bindings().iter().any(|b| b.key == key);
        assert!(hinted(&app, "c"));

        open_key_map(&mut app);
        app.handle_key(KeyEvent::from(KeyCode::Char('r')));
        assert_eq!(
            press(&mut app, 'p'),
            KeyOutcome::Consumed,
            "the new key is live"
        );
        assert_eq!(
            press(&mut app, 'c'),
            KeyOutcome::Ignored,
            "the old one is gone"
        );
        assert!(
            hinted(&app, "p") && !hinted(&app, "c"),
            "and the hint follows"
        );

        app.handle_key(KeyEvent::from(KeyCode::Char('d')));
        app.handle_key(KeyEvent::from(KeyCode::Char('y')));
        let text = file.text();
        assert!(text.contains("\n# per_core = \"p\""), "{text}");
        assert!(text.starts_with("[cpu]\nhistory = 5\n"), "{text}");
        assert_eq!(
            press(&mut app, 'c'),
            KeyOutcome::Consumed,
            "the default is back"
        );
        assert!(hinted(&app, "c"));
    }

    #[test]
    fn a_panel_keymap_that_does_not_check_out_does_not_start() {
        let mut config = config_with(&["cpu"]);
        config.cpu.keys = toml::from_str("per_core = \"1\"").expect("a table");
        let Err(error) = App::new(config) else {
            panic!("a panel key on a jump key was accepted");
        };
        assert!(error.to_string().contains("[cpu.keys]"), "{error}");
    }

    /// `d`, then `y`: the file's `[keys]` lines are commented out and the
    /// defaults are live at once. Anything else leaves both alone.
    #[test]
    fn defaults_resets_the_file_and_the_live_keys_only_on_yes() {
        let file = KeysFile::new("reset", "[general]\nmouse = true\n\n[keys]\nquit = \"x\"\n");
        let config = with_keys(config_with(&["clocks"]), "[keys]\nquit = \"x\"");
        let mut app = App::new(config).unwrap();
        app.write_layout_to(file.path.clone());
        open_key_map(&mut app);

        app.handle_key(KeyEvent::from(KeyCode::Char('d')));
        app.handle_key(KeyEvent::from(KeyCode::Char('n')));
        assert!(
            file.text().contains("\nquit = \"x\""),
            "a no changed nothing"
        );
        assert!(!app.keymap.is_default(Action::Quit));

        app.handle_key(KeyEvent::from(KeyCode::Char('d')));
        app.handle_key(KeyEvent::from(KeyCode::Char('y')));
        assert!(file.text().contains("\n# quit = \"x\""), "{}", file.text());
        assert!(file.text().starts_with("[general]\nmouse = true\n"));
        assert!(app.keymap.is_default(Action::Quit), "the defaults are live");
        assert!(
            app.keymap_dialog.is_some(),
            "and the dialog stays to say so"
        );
    }

    /// What the key map last reported, and whether it said so as a failure.
    fn key_map_notice(app: &App) -> (String, bool) {
        let (text, failed) = app
            .keymap_dialog
            .as_ref()
            .and_then(crate::keymap_dialog::KeymapDialog::notice)
            .expect("the key map reported something");
        (text.to_string(), failed)
    }

    /// A reload that does not check out is reported in the failure colour,
    /// and says the keys in force were kept. Nothing read either half of the
    /// report back, so a flag flipped on this branch would have shown a
    /// refused keymap as though it had loaded.
    #[test]
    fn a_key_reload_that_does_not_check_out_is_reported_as_a_failure() {
        let file = KeysFile::new("reload-refused", "[keys]\nquit = \"no such key\"\n");
        let mut app = App::new(config_with(&["clocks"])).expect("builds");
        app.write_layout_to(file.path.clone());
        open_key_map(&mut app);
        app.handle_key(key(KeyCode::Char('r')));

        let (text, failed) = key_map_notice(&app);
        assert!(failed, "reported as a success: {text}");
        assert!(text.starts_with("Kept the keys you had. "), "{text}");
        assert!(app.keymap.is_default(Action::Quit), "and nothing changed");
    }

    /// The other half: a reload that checks out says what it loaded, and not
    /// in the failure colour.
    #[test]
    fn a_key_reload_that_checks_out_is_reported_as_a_success() {
        let file = KeysFile::new("reload-taken", "[keys]\nquit = \"x\"\n");
        let mut app = App::new(config_with(&["clocks"])).expect("builds");
        app.write_layout_to(file.path.clone());
        open_key_map(&mut app);
        app.handle_key(key(KeyCode::Char('r')));

        let (text, failed) = key_map_notice(&app);
        assert!(!failed, "reported as a failure: {text}");
        assert_eq!(text, "Loaded. One key differs from its default.");
    }

    /// A reset with no config file to rewrite says nothing was changed, as a
    /// failure; one that lands says the keys are back, as a success. The
    /// same report as a reload's, and as unread until these.
    #[test]
    fn a_key_reset_says_whether_it_took() {
        let mut app = App::new(config_with(&["clocks"])).expect("builds");
        open_key_map(&mut app);
        app.handle_key(key(KeyCode::Char('d')));
        app.handle_key(key(KeyCode::Char('y')));
        let (text, failed) = key_map_notice(&app);
        assert!(failed, "reported as a success: {text}");
        assert!(text.starts_with("Nothing was changed. "), "{text}");

        let file = KeysFile::new("reset-taken", "[keys]\nquit = \"x\"\n");
        app.write_layout_to(file.path.clone());
        app.handle_key(key(KeyCode::Char('d')));
        app.handle_key(key(KeyCode::Char('y')));
        let (text, failed) = key_map_notice(&app);
        assert!(!failed, "reported as a failure: {text}");
        assert!(
            text.starts_with("Every key is back to its default."),
            "{text}"
        );
    }

    /// `config` with `[arrange.keys]` set from `toml_text`.
    fn with_arrange_keys(config: Config, toml_text: &str) -> Config {
        let mut config = config;
        config.arrange.keys = toml::from_str(toml_text).expect("a table");
        config
    }

    /// A moved arrange key moves the panel and the old one does nothing —
    /// and a Ctrl key, which the mode used to hand straight on, is the mode's
    /// once `[arrange.keys]` binds it.
    #[test]
    fn a_moved_arrange_key_works_even_with_ctrl_and_the_old_key_is_free() {
        let config = with_arrange_keys(resizable(), "move_right = \"ctrl+l\"");
        let mut app = App::new(config).expect("builds");
        app.focus = 0;
        app.handle_key(KeyEvent::from(KeyCode::Char('m')));
        let before = widgets_by_row(&app);

        app.handle_key(KeyEvent::from(KeyCode::Right));
        app.handle_key(KeyEvent::from(KeyCode::Char('l')));
        assert_eq!(
            widgets_by_row(&app),
            before,
            "neither old key moves anything"
        );

        app.handle_key(KeyEvent::new(KeyCode::Char('l'), KeyModifiers::CONTROL));
        assert_ne!(widgets_by_row(&app), before, "Ctrl+L moved the panel");
        assert!(app.arranging.is_some(), "and the mode is still open");

        let legend = status_bar_at(&mut app, 200);
        assert!(legend.contains("Ctrl+l move right"), "{legend}");
    }

    /// Reload reaches a mode that is already open: the keys change under the
    /// reader's hands, as the panels' do.
    #[test]
    fn reload_gives_arrange_mode_its_new_keys() {
        let file = KeysFile::new("arrange", "[arrange.keys]\nkeep = \"space\"\n");
        let mut app = App::new(resizable()).expect("builds");
        app.write_layout_to(file.path.clone());
        open_key_map(&mut app);
        app.handle_key(KeyEvent::from(KeyCode::Char('r')));
        app.handle_key(KeyEvent::from(KeyCode::Esc));

        app.handle_key(KeyEvent::from(KeyCode::Char('m')));
        app.handle_key(KeyEvent::from(KeyCode::Enter));
        assert!(app.arranging.is_some(), "Enter no longer keeps");
        app.handle_key(KeyEvent::from(KeyCode::Char(' ')));
        assert!(app.arranging.is_none(), "space does");
    }

    /// Reload reaches both pickers: a picker opened after it reads the new
    /// keys, the same way arrange mode and the panels do.
    #[test]
    fn reload_gives_the_pickers_their_new_keys() {
        let file = KeysFile::new(
            "pickers",
            "[panel_picker.keys]\nclose = \"x\"\n\n[theme_picker.keys]\nput_back = \"x\"\n\n\
             [help_overlay.keys]\ndown = \"s\"\n",
        );
        let mut app = App::new(config_with(&["clocks"])).expect("builds");
        app.write_layout_to(file.path.clone());
        open_key_map(&mut app);
        app.handle_key(KeyEvent::from(KeyCode::Char('r')));
        app.handle_key(KeyEvent::from(KeyCode::Esc));

        app.handle_key(KeyEvent::from(KeyCode::Char('w')));
        app.handle_key(KeyEvent::from(KeyCode::Char('q')));
        assert!(app.picker.is_some(), "q no longer closes the panel picker");
        app.handle_key(KeyEvent::from(KeyCode::Char('x')));
        assert!(app.picker.is_none(), "x does");

        app.handle_key(KeyEvent::from(KeyCode::Char('t')));
        app.handle_key(KeyEvent::from(KeyCode::Char('t')));
        assert!(
            app.theme_picker.is_some(),
            "t no longer puts the theme back"
        );
        app.handle_key(KeyEvent::from(KeyCode::Char('x')));
        assert!(app.theme_picker.is_none(), "x does");
        assert_eq!(
            app.help_keys.action(KeyEvent::from(KeyCode::Char('s'))),
            Some(crate::keymap::HelpAction::Down),
            "and the help overlay's"
        );
    }

    /// The keys the shell holds live for the mode `[<mode>.keys]` configures,
    /// as the key map would list them. A mode with no arm here is one whose
    /// table nothing reads, and says so.
    fn live_mode_keys(app: &App, mode: &str) -> Vec<(&'static str, Vec<crate::keymap::Key>)> {
        let listing = match mode {
            "arrange" => app.arrange_keys.listing(),
            "panel_picker" => app.panel_picker_keys.listing(),
            "theme_picker" => app.theme_picker_keys.listing(),
            "help_overlay" => app.help_keys.listing(),
            other => panic!("[{other}.keys] is a mode the shell holds no live keys for"),
        };
        listing
            .into_iter()
            .map(|listed| (listed.name, listed.keys))
            .collect()
    }

    /// Every table in `MODE_SCOPES` reaches a field the shell reads keys
    /// from. The tests above each name the modes they knew of; this one asks
    /// the list, so a mode added to it whose reload lands nowhere — checked,
    /// listed in the key map, reset, and never in force — fails here.
    #[test]
    fn every_mode_table_reloads_into_the_keys_the_shell_reads() {
        for scope in crate::keymap::MODE_SCOPES {
            let defaults = (scope.listing)(&crate::keymap::KeysConfig::default()).expect("valid");
            let moved = defaults.first().expect("a mode has keys").name;
            let table = format!("{moved} = \"f9\"\n");
            let file = KeysFile::new(
                &format!("mode-{}", scope.widget),
                &format!("[{}.keys]\n{table}", scope.widget),
            );
            let mut app = App::new(config_with(&["clocks"])).expect("builds");
            app.write_layout_to(file.path.clone());
            assert_ne!(
                live_mode_keys(&app, scope.widget)[0].1,
                vec!["f9".parse::<crate::keymap::Key>().expect("a key")],
                "{}: f9 is not already the default",
                scope.widget
            );

            app.reload_keys();

            let written: crate::keymap::KeysConfig = toml::from_str(&table).expect("a table");
            let expected: Vec<_> = (scope.listing)(&written)
                .expect("valid")
                .into_iter()
                .map(|listed| (listed.name, listed.keys))
                .collect();
            assert_eq!(
                live_mode_keys(&app, scope.widget),
                expected,
                "[{}.keys] reloaded into nothing the shell reads",
                scope.widget
            );
        }
    }

    /// An open picker is offered every key before resizing is, so a picker
    /// key may be a resize key — it is the picker's while the picker is open,
    /// and a resize again once it closes. Arrange mode reads after resize,
    /// and there the same key is refused.
    #[test]
    fn a_picker_key_may_be_a_resize_key_but_an_arrange_key_may_not() {
        let mut config = resizable();
        config.panel_picker.keys = toml::from_str("down = \"ctrl+down\"").expect("a table");
        let mut app = App::new(config).expect("a picker may use a resize key");
        app.handle_key(KeyEvent::from(KeyCode::Char('w')));
        let before = app.picker.as_ref().expect("open").selected();
        app.handle_key(KeyEvent::new(KeyCode::Down, KeyModifiers::CONTROL));
        assert_eq!(
            app.picker.as_ref().expect("still open").selected(),
            before + 1,
            "Ctrl+↓ moved the cursor in the picker"
        );
        assert!(!app.layout_dirty, "and resized nothing");

        let mut config = resizable();
        config.arrange.keys = toml::from_str("move_down = \"ctrl+down\"").expect("a table");
        let Err(error) = App::new(config) else {
            panic!("an arrange key on a resize key was accepted");
        };
        assert!(error.to_string().contains("[arrange.keys]"), "{error}");
    }

    /// The help footer an 80x24 terminal actually shows, scrolled to the top,
    /// the middle and the bottom: the position, the way to the key map and
    /// the way out, all three, and never a line ending on a separator. It
    /// shipped in 1.17.0 reading `? key map ·` and nothing else.
    #[test]
    fn the_help_footer_keeps_its_position_and_ends_on_no_separator() {
        use ratatui::Terminal;
        use ratatui::backend::TestBackend;
        let mut app = App::new(config_with(&["todo"])).expect("builds");
        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 test needs an overlay that scrolls"
        );

        for key in [KeyCode::Home, KeyCode::Down, KeyCode::End] {
            app.handle_key(KeyEvent::from(key));
            terminal.draw(|frame| app.render_for_test(frame)).unwrap();
            let footer = crate::widgets::testing::rows(terminal.backend().buffer())
                .into_iter()
                .find(|row| row.contains("key map"))
                .expect("the footer row");
            let text = footer.split('│').nth(1).expect("inside the overlay").trim();
            assert!(
                text.contains('/') && text.contains("? key map") && text.contains("close"),
                "{key:?}: {text}"
            );
            assert!(!text.ends_with('·'), "{key:?}: {text}");
        }

        // Every width the footer could be squeezed to ends on a whole part.
        for width in 1..60 {
            let line = app.help_footer(&crate::theme::Theme::default(), width);
            let text: String = line.spans.iter().map(|s| s.content.as_ref()).collect();
            assert!(!text.trim_end().ends_with('·'), "{width}: {text}");
        }
    }

    /// A moved scroll key scrolls the overlay, the old one closes it like any
    /// other key, and the footer names the new one.
    #[test]
    fn a_moved_help_scroll_key_scrolls_and_the_old_one_closes() {
        use ratatui::Terminal;
        use ratatui::backend::TestBackend;
        let mut config = config_with(&["todo"]);
        config.help_overlay.keys = toml::from_str("down = \"s\"").expect("a table");
        let mut app = App::new(config).expect("builds");
        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 test needs an overlay that scrolls"
        );

        let footer = crate::widgets::testing::rows(terminal.backend().buffer())
            .into_iter()
            .find(|row| row.contains("key map"))
            .expect("the footer row");
        let text = footer.split('│').nth(1).expect("inside the overlay").trim();
        assert!(
            text.starts_with("s "),
            "the footer names the new key: {text}"
        );

        app.handle_key(KeyEvent::from(KeyCode::Char('s')));
        assert_eq!(app.help_scroll, 1, "s scrolled");
        assert!(app.show_help);
        app.handle_key(KeyEvent::from(KeyCode::Down));
        assert!(!app.show_help, "the old key closes it like any other");
    }

    #[test]
    fn a_keymap_that_does_two_things_with_one_key_does_not_start() {
        let config = with_keys(config_with(&["clocks"]), "[keys]\ntheme = \"q\"");
        let Err(error) = App::new(config) else {
            panic!("a clashing keymap was accepted");
        };
        let error = error.to_string();
        assert!(error.contains("bound to both"), "{error}");
    }

    #[test]
    fn only_a_focused_capturing_panel_can_shorten_the_event_wait() {
        struct ResponsivePanel {
            capturing: bool,
        }

        impl crate::panel::Panel for ResponsivePanel {
            fn title(&self) -> String {
                "responsive test".into()
            }

            fn refresh_interval(&self) -> Duration {
                Duration::from_millis(8)
            }

            fn captures_input(&self) -> bool {
                self.capturing
            }

            fn render(
                &mut self,
                _frame: &mut ratatui::Frame,
                _area: Rect,
                _ctx: crate::panel::RenderContext<'_>,
            ) {
            }
        }

        let configured = Duration::from_millis(250);
        let mut app = App::new(config_with(&["clocks"])).unwrap();
        app.slots[0].panel = Box::new(ResponsivePanel { capturing: false });
        assert_eq!(app.poll_wait(configured), configured);

        app.slots[0].panel = Box::new(ResponsivePanel { capturing: true });
        assert_eq!(app.poll_wait(configured), Duration::from_millis(16));
        assert_eq!(
            app.poll_wait(Duration::from_millis(10)),
            Duration::from_millis(10),
            "a panel may ask for responsiveness but never slow the configured loop"
        );

        app.handle_key(KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL));
        assert!(
            app.should_quit,
            "even a capturing panel cannot intercept Ctrl+C"
        );
    }

    #[test]
    fn clipboard_inputs_reach_the_editor_before_global_keys() {
        struct CopyPanel {
            selected: bool,
            pasted: std::rc::Rc<std::cell::RefCell<String>>,
        }

        impl crate::panel::Panel for CopyPanel {
            fn title(&self) -> String {
                "copy test".to_string()
            }

            fn render(
                &mut self,
                _frame: &mut ratatui::Frame,
                _area: Rect,
                _ctx: crate::panel::RenderContext<'_>,
            ) {
            }

            fn copy_selection(&mut self) -> crate::panel::KeyOutcome {
                if std::mem::take(&mut self.selected) {
                    crate::panel::KeyOutcome::Consumed
                } else {
                    crate::panel::KeyOutcome::Ignored
                }
            }

            fn handle_paste(&mut self, text: &str) -> crate::panel::KeyOutcome {
                self.pasted.borrow_mut().push_str(text);
                crate::panel::KeyOutcome::Consumed
            }
        }

        let mut app = App::new(config_with(&["clocks"])).unwrap();
        let pasted = std::rc::Rc::new(std::cell::RefCell::new(String::new()));
        app.slots[0].panel = Box::new(CopyPanel {
            selected: true,
            pasted: pasted.clone(),
        });
        let ctrl_c = KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL);

        app.handle_key(ctrl_c);
        assert!(!app.should_quit, "the selection gets Ctrl+C first");
        assert!(app.handle_paste("one\n\ttwo"));
        assert_eq!(&*pasted.borrow(), "one\n\ttwo", "paste stays one block");
        app.handle_key(ctrl_c);
        assert!(app.should_quit, "without a selection Ctrl+C still quits");
    }

    #[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");
    }

    /// The digits pick the panel to move inside arrange mode as they pick
    /// one outside it. The mode is the second of the two places that read
    /// them, and until this test nothing had pressed a digit there.
    #[test]
    fn number_keys_pick_the_panel_to_move_inside_arrange_mode_too() {
        let mut app = App::new(resizable()).expect("builds");
        app.focus = 0;
        let before = widgets_by_row(&app);
        app.handle_key(KeyEvent::from(KeyCode::Char('m')));

        app.handle_key(KeyEvent::from(KeyCode::Char('3')));
        assert_eq!(app.slots[app.focus].widget, "cpu", "3 picked the third");
        app.handle_key(KeyEvent::from(KeyCode::Char('9')));
        assert_eq!(app.focus, 2, "an out-of-range index moves nothing");
        assert!(app.arranging.is_some(), "and the mode is still open");
        assert_eq!(widgets_by_row(&app), before, "with nothing moved");
    }

    #[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)
    }

    /// Walk the theme picker down to a named theme and report what it landed on.
    fn preview_a_theme(app: &mut App) -> String {
        app.handle_key(key(KeyCode::Char('t')));
        // Down until the accent actually moves. The list is alphabetical and
        // starts on `ansi`, whose accent is an ANSI index rather than an RGB
        // triple, so the first row that differs is a real repaint.
        let start = app.config.theme.accent;
        for _ in 0..20 {
            app.handle_key(key(KeyCode::Down));
            if app.config.theme.accent != start {
                break;
            }
        }
        app.config
            .theme
            .name
            .clone()
            .expect("a previewed theme is a named one")
    }

    #[test]
    fn moving_in_the_theme_picker_repaints_before_anything_is_committed() {
        let mut app = App::new(config_with(&["clocks", "cpu"])).unwrap();
        let before = app.config.theme.accent;
        let name = preview_a_theme(&mut app);
        assert_ne!(
            app.config.theme.accent, before,
            "`{name}` was selected but the live theme did not change"
        );
        assert!(
            app.theme_picker.is_some(),
            "moving must not close the dialog"
        );
    }

    /// The graphs read a baked ramp rather than the theme, so a swap that
    /// forgets it leaves cpu and network painted in the previous palette.
    #[test]
    fn a_theme_swap_rebakes_the_gradients_the_graphs_draw_from() {
        let mut app = App::new(config_with(&["cpu"])).unwrap();
        let before = app.gradients.clone();
        preview_a_theme(&mut app);
        assert_ne!(
            app.gradients, before,
            "the graph ramp still holds the previous theme's colours"
        );
    }

    #[test]
    fn esc_puts_back_the_theme_the_picker_opened_on() {
        let mut app = App::new(config_with(&["clocks", "cpu"])).unwrap();
        let theme = app.config.theme.clone();
        let gradients = app.gradients.clone();

        preview_a_theme(&mut app);
        app.handle_key(key(KeyCode::Esc));

        assert!(app.theme_picker.is_none(), "Esc must close the dialog");
        assert_eq!(app.config.theme.accent, theme.accent, "theme not restored");
        assert_eq!(app.gradients, gradients, "gradients not restored");
    }

    #[test]
    fn enter_keeps_the_previewed_theme() {
        let mut app = App::new(config_with(&["clocks"])).unwrap();
        let name = preview_a_theme(&mut app);
        app.handle_key(key(KeyCode::Enter));

        assert!(app.theme_picker.is_none());
        assert_eq!(
            app.config.theme.name.as_deref(),
            Some(name.as_str()),
            "Enter must keep what was on screen"
        );
    }

    /// The dialog owns the keyboard while it is open. Otherwise `q` under the
    /// cursor quits the dashboard mid-browse, which is invariant 2's rule
    /// applied to a shell dialog rather than a panel.
    #[test]
    fn the_theme_picker_takes_the_keyboard_while_it_is_open() {
        let mut app = App::new(config_with(&["clocks", "todo"])).unwrap();
        app.handle_key(key(KeyCode::Char('t')));
        let focus = app.focus;

        app.handle_key(key(KeyCode::Tab));
        assert_eq!(app.focus, focus, "Tab reached the focus ring");
        app.handle_key(key(KeyCode::Char('w')));
        assert!(
            app.picker.is_none(),
            "`w` opened the panel picker underneath"
        );

        app.handle_key(key(KeyCode::Char('q')));
        assert!(
            !app.should_quit,
            "`q` quit the dashboard from inside a dialog"
        );
        assert!(app.theme_picker.is_none(), "`q` should close the dialog");
    }

    #[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());
    }

    #[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);
        let rows = drawn(&mut app, 120, 30).join("\n");
        assert!(
            rows.contains("at least one panel has to stay"),
            "and the picker says why:\n{rows}"
        );

        // A refusal changes nothing and leaves nothing unsaved, so it belongs
        // to the dialog and goes with it. On the bar it read "The layout could
        // not be saved", which was false, and stayed lit until some later
        // layout change happened to succeed.
        app.handle_key(key(KeyCode::Esc));
        assert!(app.picker.is_none());
        assert!(
            app.alert().is_none(),
            "a refusal is not a failed save: {:?}",
            app.alert().map(|alert| alert.text)
        );
        let bar = status_bar_at(&mut app, 120);
        assert!(!bar.contains('⚠'), "and the bar is calm: {bar}");
    }

    /// A paste into a one-line form arrives as keys, and the first newline
    /// commits the form. Whatever follows it is no longer typing: it used to
    /// reach the task list as commands, so a second line beginning with `a`
    /// opened a new task, a space marked one done and `dy` deleted it.
    #[test]
    fn a_paste_stops_at_the_newline_that_closes_a_one_line_form() {
        let dir = TempDir::new("paste");
        let file = dir.join("todos.toml");
        // Empty rather than absent, so the store does not seed examples.
        std::fs::write(&file, "").unwrap();
        let mut config = config_with(&["todo"]);
        config.todo.file = Some(file.clone());
        let mut app = App::new(config).unwrap();

        app.handle_key(key(KeyCode::Char('a')));
        assert!(app.focus_captures_input(), "the task form is open");
        assert!(app.handle_paste("Buy milk\nand eggs\n"));

        let titles: Vec<String> = crate::task::TaskStore::load(&file)
            .unwrap()
            .tasks()
            .iter()
            .map(|task| task.title.clone())
            .collect();
        assert_eq!(
            titles,
            ["Buy milk"],
            "the first line is the task; the rest is not a command"
        );
        assert!(
            !app.focus_captures_input(),
            "and the list is back, not a second form"
        );
    }

    /// A paste is text, and a delete confirmation takes no text. The shell
    /// types a paste no panel claims into a capturing one key by key, so a
    /// paste beginning with `y` answered the question it landed on: `d` on a
    /// task, then a paste of "yesterday's notes", and the task was gone —
    /// the one action in these panels with no undo. Each of the three that
    /// ask now claims the paste and does nothing with it.
    #[test]
    fn a_paste_never_answers_a_delete_confirmation() {
        /// Ask to delete the one item, paste `y`, and check it is still there
        /// and the question is still waiting for a key.
        fn ask_then_paste(app: &mut App, which: &str, items: &dyn Fn() -> usize) {
            assert_eq!(items(), 1, "{which}: one item to begin with");
            app.handle_key(key(KeyCode::Char('d')));
            assert!(app.focus_captures_input(), "{which}: the question is open");
            app.handle_paste("y");
            assert_eq!(items(), 1, "{which}: a pasted `y` deleted the item");
            assert!(
                app.focus_captures_input(),
                "{which}: and the question is still waiting for a key"
            );
            app.handle_key(key(KeyCode::Char('n')));
            assert!(!app.focus_captures_input(), "{which}: `n` still answers it");
            assert_eq!(items(), 1, "{which}: and keeps the item");
        }
        fn type_in(app: &mut App, text: &str) {
            app.handle_key(key(KeyCode::Char('a')));
            for c in text.chars() {
                app.handle_key(key(KeyCode::Char(c)));
            }
            app.handle_key(key(KeyCode::Enter));
        }

        let dir = TempDir::new("confirm");

        // Empty rather than absent, so neither store seeds its examples.
        let tasks = dir.join("todos.toml");
        let notes = dir.join("notes.toml");
        std::fs::write(&tasks, "").unwrap();
        std::fs::write(&notes, "").unwrap();
        let mut config = config_with(&["todo"]);
        config.todo.file = Some(tasks.clone());
        let mut app = App::new(config).unwrap();
        type_in(&mut app, "Doomed");
        ask_then_paste(&mut app, "tasks", &|| {
            crate::task::TaskStore::load(&tasks).unwrap().tasks().len()
        });

        let mut config = config_with(&["notes"]);
        config.notes.file = Some(notes.clone());
        let mut app = App::new(config).unwrap();
        type_in(&mut app, "Doomed");
        ask_then_paste(&mut app, "notes", &|| {
            crate::note::NoteStore::load(&notes).unwrap().notes().len()
        });

        // `build` would reach Yahoo, so the stocks panel goes in by hand, on
        // a canned source, over a calculator that reads nothing.
        let watchlist = dir.join("watchlist.toml");
        std::fs::write(&watchlist, "symbols = [\"AAPL\"]\n").unwrap();
        let mut app = App::new(config_with(&["calculator"])).unwrap();
        app.slots[0].panel = Box::new(
            crate::widgets::stocks::StocksPanel::offline(
                crate::config::StocksConfig {
                    refresh_secs: 86_400,
                    ..crate::config::StocksConfig::default()
                },
                watchlist.clone(),
            )
            .unwrap(),
        );
        ask_then_paste(&mut app, "stocks", &|| {
            crate::quote::Watchlist::load(&watchlist, &[])
                .unwrap()
                .symbols()
                .len()
        });
    }

    /// Previewing is not choosing. Every arrow key in the theme picker used to
    /// write `state.toml`, so the comment on Accept was untrue and a dashboard
    /// killed mid-browse came back in a theme nobody picked.
    #[test]
    fn browsing_themes_writes_nothing_until_one_is_chosen() {
        let dir = TempDir::new("browse");
        let path = dir.join("state.toml");
        let config = config_with(&["clocks"]);
        let baseline = crate::state::UiState::from_config(&config);
        let mut app = App::new(config).unwrap();
        app.remember_preferences_at(path.clone(), crate::state::UiState::default(), baseline);

        app.handle_key(key(KeyCode::Char('t')));
        let mut previewed = Vec::new();
        for _ in 0..2 {
            app.handle_key(key(KeyCode::Down));
            // What the run loop does after every key.
            app.persist_preferences();
            previewed.push(app.config.theme.name.clone());
        }
        assert!(
            previewed.iter().all(Option::is_some) && previewed[0] != previewed[1],
            "two different themes were on screen: {previewed:?}"
        );
        assert!(
            !path.exists(),
            "browsing wrote {:?}",
            std::fs::read_to_string(&path).unwrap_or_default()
        );

        app.handle_key(key(KeyCode::Enter));
        app.persist_preferences();
        let chosen = previewed[1].clone().unwrap();
        let written = std::fs::read_to_string(&path).expect("Enter records the choice");
        assert!(
            written.contains(&chosen),
            "the theme chosen is the one written: {written}"
        );
    }

    /// Arrange mode is a commit point: Keep writes and Esc puts everything
    /// back. A resize inside it used to start the settle timer anyway, so a
    /// pause before Esc left the file holding widths the screen had undone.
    #[test]
    fn a_resize_inside_arrange_mode_waits_for_the_mode_to_close() {
        let dir = TempDir::new("settle");
        let text = "[layout]\nrows = [\n  { height = 1, panels = [\n    { widget = \"clocks\",   width = 50 },\n    { widget = \"calendar\", width = 50 },\n  ] },\n]\n";
        let path = dir.join("config.toml");
        std::fs::write(&path, text).unwrap();
        let mut app = App::new(toml::from_str(text).unwrap()).unwrap();
        app.write_layout_to(path.clone());
        let settled = || Instant::now().checked_sub(RESIZE_SETTLE * 2);

        app.handle_key(key(KeyCode::Char('m')));
        app.handle_key(KeyEvent::new(KeyCode::Right, KeyModifiers::CONTROL));
        assert_ne!(widths(&app), [50, 50], "the resize happened");
        app.last_resize = settled();
        app.write_settled_resize();
        assert_eq!(
            std::fs::read_to_string(&path).unwrap(),
            text,
            "a resize inside the mode is part of the arrangement"
        );

        app.handle_key(key(KeyCode::Esc));
        app.write_settled_resize();
        assert_eq!(widths(&app), [50, 50], "Esc put the widths back");
        assert_eq!(
            std::fs::read_to_string(&path).unwrap(),
            text,
            "and the file never left them"
        );

        // The control: outside the mode the same resize settles to the file,
        // so the silence above is the guard and not a timer that never fires.
        app.handle_key(KeyEvent::new(KeyCode::Right, KeyModifiers::CONTROL));
        app.last_resize = settled();
        app.write_settled_resize();
        assert_ne!(
            std::fs::read_to_string(&path).unwrap(),
            text,
            "outside the mode a settled resize is written"
        );
    }

    /// Ctrl+C in arrange mode keeps the arrangement, as Keep would; only Esc
    /// discards one. The owner's decision of 2026-10-07, pinned so a change to
    /// the exit path cannot quietly reverse it.
    #[test]
    fn ctrl_c_in_arrange_mode_keeps_the_arrangement() {
        let dir = TempDir::new("ctrlc");
        let text = "[layout]\nrows = [\n  { height = 1, panels = [\n    { widget = \"clocks\",   width = 50 },\n    { widget = \"calendar\", width = 50 },\n  ] },\n]\n";
        let path = dir.join("config.toml");
        std::fs::write(&path, text).unwrap();
        let mut app = App::new(toml::from_str(text).unwrap()).unwrap();
        app.write_layout_to(path.clone());

        app.handle_key(key(KeyCode::Char('m')));
        app.handle_key(KeyEvent::new(KeyCode::Right, KeyModifiers::CONTROL));
        let arranged = widths(&app);
        assert_ne!(arranged, [50, 50], "the resize happened");
        app.handle_key(KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL));
        app.finish();

        let written: crate::config::Config =
            toml::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
        let saved: Vec<u16> = written.layout.rows[0]
            .panels
            .iter()
            .map(|p| p.width)
            .collect();
        assert_eq!(
            saved, arranged,
            "the arrangement on screen is the one written"
        );
    }

    /// The write on the way out is the last chance to keep a resize made just
    /// before `q`. When it fails there is no bar left to show it on, so it is
    /// handed back for `main` to print once the terminal is restored.
    #[test]
    fn a_layout_that_cannot_be_written_on_the_way_out_is_handed_back() {
        let dir = TempDir::new("exit");
        // Loads, but `layout_edit` only rewrites the `rows = [ … ]` form.
        let sections = "[[layout.rows]]\nheight = 1\n[[layout.rows.panels]]\nwidget = \"clocks\"\nwidth = 50\n[[layout.rows.panels]]\nwidget = \"calendar\"\nwidth = 50\n";
        let path = dir.join("config.toml");
        std::fs::write(&path, sections).unwrap();
        let mut app = App::new(toml::from_str(sections).unwrap()).unwrap();
        app.write_layout_to(path.clone());

        assert_eq!(app.unsaved_layout(), None, "nothing to report yet");
        app.handle_key(KeyEvent::new(KeyCode::Right, KeyModifiers::CONTROL));
        app.finish();

        let report = app
            .exit_report()
            .expect("the failed write on the way out is not dropped");
        assert!(
            report.starts_with("mirador: the layout could not be saved — ")
                && report.contains("rows = ["),
            "it says what was lost and why: {report}"
        );
        assert_eq!(std::fs::read_to_string(&path).unwrap(), sections);
    }

    /// Keys go to an open shell dialog and nowhere else, and so does the
    /// mouse now. A click under the panel picker used to move focus to the
    /// panel beneath and select a row nobody could see, and the wheel
    /// scrolled lists behind the key map.
    #[test]
    fn an_open_dialog_keeps_the_mouse_from_the_panels_beneath_it() {
        use ratatui::crossterm::event::MouseButton;
        // Its name, how to open it, and how to tell it is still open.
        type Dialog = (&'static str, fn(&mut App), fn(&App) -> bool);

        let (config, _dir) = two_lists("dialog");
        let mut app = App::new(config).unwrap();
        drawn(&mut app, 120, 30);
        let todo = app.slots[1].area.expect("the tasks panel was drawn");
        let click = at(
            MouseEventKind::Down(MouseButton::Left),
            todo.x + 6,
            todo.y + 4,
        );
        let wheel = at(MouseEventKind::ScrollDown, todo.x + 6, todo.y + 4);

        let dialogs: [Dialog; 3] = [
            (
                "panel picker",
                |app| app.handle_key(key(KeyCode::Char('w'))),
                |app| app.picker.is_some(),
            ),
            (
                "theme picker",
                |app| app.handle_key(key(KeyCode::Char('t'))),
                |app| app.theme_picker.is_some(),
            ),
            ("key map", open_key_map, |app| app.keymap_dialog.is_some()),
        ];
        for (name, open, is_open) in dialogs {
            open(&mut app);
            assert!(is_open(&app), "the {name} opened");
            assert!(
                !app.handle_mouse(wheel),
                "the wheel reached the list under the {name}"
            );
            app.handle_mouse(click);
            assert_eq!(app.focus, 0, "a click under the {name} moved focus");
            assert!(is_open(&app), "and the {name} is still open");
            app.handle_key(key(KeyCode::Esc));
            assert!(!is_open(&app), "Esc closed the {name}");
        }

        // The control: with nothing open, the same click lands.
        app.handle_mouse(click);
        assert_eq!(app.focus, 1, "without a dialog the click focuses the list");
    }

    #[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() {
        let keymap = crate::keymap::Keymap::default();
        for binding in keymap.bindings() {
            assert!(!binding.key.is_empty());
            assert!(!binding.action.is_empty());
        }
        assert!(
            keymap.bindings().iter().any(|b| b.key == "?" && b.primary),
            "help must always be advertised"
        );
    }

    /// And the event loop itself must offer only `FocusLost` to `mark_seen`.
    /// The two tests above exercise `WatchLog`; this one is about the wiring,
    /// which is where #132 actually lived — the log was always correct.
    #[test]
    fn only_losing_focus_marks_the_log_seen() {
        let source = std::fs::read_to_string(file!()).expect("this file is readable");
        let wiring = source
            .lines()
            .find(|line| line.contains("=> self.watch.mark_seen()"))
            .expect("the focus arm still exists");
        assert!(
            wiring.contains("FocusLost") && !wiring.contains("FocusGained"),
            "gaining focus must not mark the log seen: {wiring:?}"
        );
    }
}