lazier 0.9.2

A fast terminal user interface for git, written in Rust with ratatui and gitoxide
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
use anyhow::Result;
use ratatui::DefaultTerminal;
use ratatui::crossterm::event::{DisableMouseCapture, EnableMouseCapture};
use ratatui::crossterm::event::{KeyCode, KeyEventKind, KeyModifiers};
use ratatui::crossterm::execute;
use ratatui::crossterm::terminal::{
    EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode,
};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc;
use std::time::Duration;

use std::collections::HashSet;

use crate::event::{self, Msg};
use crate::git::rebase::{self, RebaseInfo, TodoAction, TodoItem};
use crate::git::{
    self, BlameLine, BranchEntry, CommitEntry, DiffTarget, FileEntry, Git, ReflogEntry, Req, Resp,
    SubmoduleEntry, WorktreeEntry, patch,
};
use crate::keys::{Action, action_for};
use crate::tree::{self, TreeRow};
use crate::ui;

pub const PANELS: [&str; 5] = ["Status", "Files", "Branches", "Commits", "Stash"];
// Load commits in small chunks. A large chunk touches many pack pages at
// start time. The scroll logic requests the next chunk early enough.
const LOG_CHUNK: usize = 100;

#[derive(Default)]
pub struct RepoState {
    pub head: Option<String>,
    pub files: Vec<FileEntry>,
    pub branches: Vec<BranchEntry>,
    pub commits: Vec<CommitEntry>,
    pub stashes: Vec<String>,
    pub log_done: bool,
    pub diff: String,
    /// The diff of the changes that are in the index.
    pub diff_staged: String,
    pub ahead: u32,
    pub behind: u32,
    pub bisecting: bool,
    /// Short ids of commits that the upstream branch does not have.
    pub unpushed: HashSet<String>,
    /// The tags of each commit, by the short id of the commit.
    pub tags: std::collections::HashMap<String, Vec<String>>,
    /// The text that the commit list was searched for, if any.
    pub filter: Option<String>,
    /// The commit that the selected one is compared against.
    pub compare: Option<String>,
    /// The branch that the current one follows, such as "origin/main".
    pub upstream: Option<String>,
}

pub enum InputPurpose {
    NewBranch,
    RenameBranch(String),
    /// Run the text through the shell.
    Shell,
    /// Make a tag on a commit.
    Tag(String),
    /// Search the messages of the commits.
    Search,
}

/// What the commit window does when the user sends it.
pub enum CommitPurpose {
    /// Make a new commit from the staged changes.
    New,
    /// Change the message of the commit at this position in the list.
    /// Position zero is HEAD, which needs only an amend.
    Reword(usize),
}

pub struct LogEntry {
    pub ok: bool,
    pub cmd: String,
    pub ms: u64,
    /// What the command printed. The log is the only place that shows it.
    pub output: Vec<String>,
}

pub enum ConfirmAction {
    DeleteBranch {
        name: String,
        force: bool,
    },
    DropStash(usize),
    Merge(String),
    Revert(String),
    RemoveWorktree(String),
    /// Go to the worktree that holds a branch.
    GoToWorktree(String),
    /// Make a fixup commit for a commit, then fold it in.
    Fixup(String),
    /// Stage every change, then open the commit window.
    StageAllThenCommit,
    /// Send the staged changes back to the commits that wrote those lines.
    Absorb,
    /// Stop a rebase at one commit so it can become several commits.
    Split(usize),
    /// Run each command in order. Discard and delete need two commands,
    /// because tracked files and new files need different treatment.
    RunAll(Vec<Vec<String>>),
}

pub enum Mode {
    Normal,
    Input {
        prompt: &'static str,
        buffer: String,
        purpose: InputPurpose,
    },
    Confirm {
        prompt: String,
        action: ConfirmAction,
    },
    /// The hunk view of one file. `cursor` is the hunk in view. `line` is
    /// the body line in that hunk. `picked` holds the marked body lines.
    Hunks {
        path: String,
        header: String,
        hunks: Vec<String>,
        cursor: usize,
        line: usize,
        picked: Vec<usize>,
    },
    /// The key list. It is taller than most terminals, thus it scrolls.
    Help {
        scroll: u16,
    },
    /// The worktree list. It opens over the panels.
    Worktrees {
        list: Vec<WorktreeEntry>,
        cursor: usize,
    },
    /// The window that makes a worktree. It asks for a branch and a path.
    /// The path follows the branch name until the user edits the path.
    NewWorktree {
        branch: String,
        path: String,
        on_path: bool,
        path_edited: bool,
    },
    /// The window that adds a path to the ignore rules.
    Ignore {
        pattern: String,
        tracked: bool,
    },
    /// The window that moves HEAD to another commit.
    Reset {
        target: String,
        subject: String,
    },
    /// The list of recent positions of HEAD.
    Reflog {
        list: Vec<ReflogEntry>,
        cursor: usize,
    },
    /// A command failed. The window makes sure the user sees it, because
    /// the command log can be closed.
    Error {
        cmd: String,
        output: Vec<String>,
    },
    /// Who last changed each line of a file.
    Blame {
        path: String,
        lines: Vec<BlameLine>,
        cursor: usize,
    },
    /// The window that chooses what goes into a stash.
    Stash {
        path: Option<String>,
    },
    /// The submodules and their state.
    Submodules {
        list: Vec<SubmoduleEntry>,
        cursor: usize,
    },
    /// The commit message window. It has a summary line and a body.
    CommitMsg {
        summary: String,
        body: String,
        on_body: bool,
        purpose: CommitPurpose,
    },
    /// The todo list editor of an interactive rebase. `base` is the commit
    /// that the rebase starts from. None means the rebase starts at the root.
    Rebase {
        items: Vec<TodoItem>,
        cursor: usize,
        base: Option<String>,
    },
}

/// A git command to run with the terminal, and the environment it needs.
/// The arguments come first, then a name and a value for each variable.
type Suspend = (Vec<String>, Vec<(String, String)>);

pub struct App {
    /// Focus 0 to 4 is a left panel. Focus 5 is the diff pane.
    pub focus: usize,
    pub selected: [usize; 6],
    pub quit: bool,
    pub repo: RepoState,
    pub mode: Mode,
    pub message: String,
    pub message_ok: bool,
    pub zoom: bool,
    pub diff_scroll: u16,
    /// The number of lines in the diff pane. The scroll stops there.
    diff_lines: u16,
    pub tree: Vec<TreeRow>,
    pub collapsed: HashSet<String>,
    /// The files that the next action works on. Empty means the action
    /// works on the row under the cursor.
    pub marked: HashSet<String>,
    pub cmd_log: Vec<LogEntry>,
    pub show_log: bool,
    /// True when the commit list follows only the first parent. A merge
    /// then hides the branch that came into it.
    pub first_parent: bool,
    /// The commands that run now. The bar shows them.
    pub running: Vec<String>,
    /// Counts up while a command runs. It moves the spinner.
    tick: usize,
    /// The size of the terminal at the last draw. The mouse needs it to
    /// know which panel is under the pointer.
    area: ratatui::layout::Rect,
    pub rebase: Option<RebaseInfo>,
    git: Option<Git>,
    log_inflight: bool,
    diff_seq: u64,
    diff_target: Option<DiffTarget>,
    pending_suspend: Option<Suspend>,
    /// A program and a file to open in it, outside the interface.
    pending_open: Option<(String, String)>,
    /// The commit that a fixup goes into. The rebase waits for the fixup
    /// commit to exist.
    pending_fixup: Option<String>,
    /// True while the staging of every change runs before the commit
    /// window opens.
    pending_commit_window: bool,
    /// True between the start of a split and the stop of its rebase.
    pending_split: bool,
    /// True while one commit is open and waiting to become several.
    pub splitting: bool,
    /// True once a full scan of the work tree has finished. Until then a
    /// scan of a few paths would have nothing to build on.
    have_baseline: bool,
    pause: Arc<AtomicBool>,
    /// A copy of the message sender. A move to another worktree needs it to
    /// start new workers.
    tx: Option<mpsc::Sender<Msg>>,
}

impl App {
    pub fn new() -> Self {
        Self {
            focus: 1,
            selected: [0; 6],
            quit: false,
            repo: RepoState::default(),
            mode: Mode::Normal,
            message: String::new(),
            message_ok: true,
            zoom: false,
            diff_scroll: 0,
            diff_lines: 0,
            tree: Vec::new(),
            collapsed: HashSet::new(),
            marked: HashSet::new(),
            cmd_log: Vec::new(),
            show_log: true,
            first_parent: false,
            running: Vec::new(),
            tick: 0,
            area: ratatui::layout::Rect::ZERO,
            rebase: None,
            git: None,
            log_inflight: false,
            diff_seq: 0,
            diff_target: None,
            pending_suspend: None,
            pending_open: None,
            pending_fixup: None,
            pending_commit_window: false,
            pending_split: false,
            splitting: false,
            have_baseline: false,
            pause: Arc::new(AtomicBool::new(false)),
            tx: None,
        }
    }

    pub fn run(&mut self, terminal: &mut DefaultTerminal) -> Result<()> {
        let (tx, rx) = mpsc::channel();
        event::spawn_input(tx.clone(), self.pause.clone());
        let git = git::spawn(tx.clone())?;
        git::watch::spawn(git.git_dir.clone(), tx.clone());
        git::watch::spawn_worktree(git.root.clone(), tx.clone());
        self.git = Some(git);
        self.tx = Some(tx);
        self.refresh_all();

        // The mouse moves the focus and the selection.
        execute!(std::io::stdout(), EnableMouseCapture)?;
        while !self.quit {
            // Ask the backend for the size. get_frame would take a Frame
            // out of the draw cycle and stop the next draw from showing.
            let size = terminal.size()?;
            self.area = ratatui::layout::Rect::new(0, 0, size.width, size.height);
            terminal.draw(|f| ui::render(f, self))?;
            // The loop waits for a message and uses no processor time. While
            // a command runs, it wakes often enough to move the spinner.
            let msg = if self.running.is_empty() {
                rx.recv()?
            } else {
                match rx.recv_timeout(Duration::from_millis(90)) {
                    Ok(msg) => msg,
                    Err(mpsc::RecvTimeoutError::Timeout) => {
                        self.tick += 1;
                        continue;
                    }
                    Err(mpsc::RecvTimeoutError::Disconnected) => break,
                }
            };
            // Drain the queue before each draw. This makes one draw for a
            // burst of messages, not one draw for each message.
            self.update(msg);
            while let Ok(msg) = rx.try_recv() {
                self.update(msg);
            }
            self.flush_requests();
            if let Some((args, envs)) = self.pending_suspend.take() {
                self.suspend_and_run(terminal, args, envs)?;
            }
            if let Some((program, file)) = self.pending_open.take() {
                self.suspend_and_open(terminal, program, file)?;
            }
        }
        let _ = execute!(std::io::stdout(), DisableMouseCapture);
        Ok(())
    }

    /// Give the terminal to a git child process, for example push or an
    /// editor for a commit message. Restore the terminal after it.
    fn suspend_and_run(
        &mut self,
        terminal: &mut DefaultTerminal,
        args: Vec<String>,
        envs: Vec<(String, String)>,
    ) -> Result<()> {
        let Some(git) = &self.git else { return Ok(()) };
        self.pause.store(true, Ordering::Relaxed);
        let start = std::time::Instant::now();
        // A terminal that answers slowly must not end the session, thus
        // none of these steps may return an error upward.
        let _ = disable_raw_mode();
        // The child program owns the terminal, thus it must own the mouse.
        let _ = execute!(std::io::stdout(), DisableMouseCapture, LeaveAlternateScreen);
        let status = std::process::Command::new("git")
            .arg("-C")
            .arg(&git.root)
            .args(&args)
            .envs(envs)
            .status();
        let _ = enable_raw_mode();
        let _ = execute!(std::io::stdout(), EnterAlternateScreen, EnableMouseCapture);
        let _ = terminal.clear();
        self.pause.store(false, Ordering::Relaxed);
        let ok = matches!(&status, Ok(s) if s.success());
        let err = match status {
            Ok(s) if s.success() => None,
            Ok(s) => Some(s.to_string()),
            Err(e) => Some(e.to_string()),
        };
        let ms = start.elapsed().as_millis() as u64;
        self.log_cmd(ok, format!("git {}", args.join(" ")), ms, err.into_iter().collect());
        self.refresh_all();
        // A split stops the rebase at the commit. Undo that commit but
        // keep its work, thus the parts are ready to stage one at a time.
        if self.pending_split {
            self.pending_split = false;
            if self.rebase.is_some() {
                self.splitting = true;
                self.focus = 1;
                self.write(svec(&["reset", "HEAD^"]));
            }
        }
        Ok(())
    }

    /// Give the terminal to another program, for example an editor.
    fn suspend_and_open(
        &mut self,
        terminal: &mut DefaultTerminal,
        program: String,
        file: String,
    ) -> Result<()> {
        let Some(git) = &self.git else { return Ok(()) };
        let root = git.root.clone();
        self.pause.store(true, Ordering::Relaxed);
        let _ = disable_raw_mode();
        let _ = execute!(std::io::stdout(), DisableMouseCapture, LeaveAlternateScreen);
        // The program name can hold flags, thus give it to the shell.
        let (shell, flag) = if cfg!(windows) { ("cmd", "/C") } else { ("sh", "-c") };
        let status = std::process::Command::new(shell)
            .arg(flag)
            .arg(format!("{program} \"{file}\""))
            .current_dir(&root)
            .status();
        let _ = enable_raw_mode();
        let _ = execute!(std::io::stdout(), EnterAlternateScreen, EnableMouseCapture);
        let _ = terminal.clear();
        self.pause.store(false, Ordering::Relaxed);
        let ok = matches!(&status, Ok(s) if s.success());
        let err = match status {
            Ok(s) if s.success() => Vec::new(),
            Ok(s) => vec![s.to_string()],
            Err(e) => vec![e.to_string()],
        };
        self.log_cmd(ok, format!("{program} {file}"), 0, err);
        self.refresh_all();
        Ok(())
    }

    pub fn update(&mut self, msg: Msg) {
        match msg {
            Msg::Key(key) if key.kind == KeyEventKind::Press => self.handle_key(key),
            Msg::Mouse(m) => self.handle_mouse(m),
            Msg::Git(resp) => self.apply_resp(resp),
            Msg::Refresh => self.refresh_all(),
            // The work tree changed. Look at the named paths only, if the
            // rest of what we know is still good.
            Msg::Dirty(paths) => match paths {
                Some(paths) if self.have_baseline => {
                    if let Some(git) = &self.git {
                        git.send(Req::StatusPaths(paths));
                    }
                }
                // The change is not known, thus look at every file.
                _ => self.refresh(true),
            },
            // A resize needs no work. The next draw uses the new size.
            _ => {}
        }
    }

    fn handle_key(&mut self, key: ratatui::crossterm::event::KeyEvent) {
        match &mut self.mode {
            Mode::Normal => {
                // A key press removes the old message. The bar then shows
                // the key hints again.
                self.message.clear();
                // While a rebase is stopped, these keys drive it. On the
                // files panel the normal keys win, because that is where
                // you stage and commit the parts of the work.
                if self.rebase.is_some() && self.focus != 1 {
                    match key.code {
                        KeyCode::Char('c') => return self.apply(Action::RebaseContinue),
                        KeyCode::Char('s') => return self.apply(Action::RebaseSkip),
                        KeyCode::Char('A') => return self.apply(Action::RebaseAbort),
                        _ => {}
                    }
                }
                if let Some(action) = action_for(key, self.focus) {
                    self.apply(action);
                }
            }
            Mode::Help { scroll } => {
                // The list is taller than the window, thus it must move.
                // The last row stops at the foot of the window, thus a key
                // that does nothing never looks like a key that is stuck.
                let last = crate::ui::help_max_scroll(self.area);
                match key.code {
                    KeyCode::Char('j') | KeyCode::Down => *scroll = (*scroll + 1).min(last),
                    KeyCode::Char('k') | KeyCode::Up => *scroll = scroll.saturating_sub(1),
                    KeyCode::PageDown => *scroll = (*scroll + 10).min(last),
                    KeyCode::PageUp => *scroll = scroll.saturating_sub(10),
                    KeyCode::Home => *scroll = 0,
                    KeyCode::End => *scroll = last,
                    KeyCode::Char('d') if key.modifiers.contains(KeyModifiers::CONTROL) => {
                        *scroll = (*scroll + 10).min(last)
                    }
                    KeyCode::Char('u') if key.modifiers.contains(KeyModifiers::CONTROL) => {
                        *scroll = scroll.saturating_sub(10)
                    }
                    _ => self.mode = Mode::Normal,
                }
            }
            Mode::Error { .. } => self.mode = Mode::Normal,
            Mode::Worktrees { list, cursor } => match key.code {
                KeyCode::Esc | KeyCode::Char('q') | KeyCode::Char('W') => self.mode = Mode::Normal,
                KeyCode::Char('j') | KeyCode::Down => {
                    *cursor = (*cursor + 1).min(list.len().saturating_sub(1))
                }
                KeyCode::Char('k') | KeyCode::Up => *cursor = cursor.saturating_sub(1),
                KeyCode::Char('n') => {
                    self.mode = Mode::NewWorktree {
                        branch: String::new(),
                        path: String::new(),
                        on_path: false,
                        path_edited: false,
                    };
                }
                KeyCode::Char('p') => {
                    self.mode = Mode::Normal;
                    self.write(svec(&["worktree", "prune"]));
                }
                KeyCode::Char('d') => {
                    let Some(w) = list.get(*cursor) else { return };
                    let stop = if w.current {
                        Some("cannot remove the worktree you are in")
                    } else if w.main {
                        Some("cannot remove the main worktree")
                    } else if w.locked {
                        Some("that worktree is locked")
                    } else {
                        None
                    };
                    if let Some(reason) = stop {
                        self.mode = Mode::Normal;
                        self.message = reason.into();
                        self.message_ok = false;
                        return;
                    }
                    let path = w.path.clone();
                    self.mode = Mode::Confirm {
                        prompt: format!("remove the worktree {path}?"),
                        action: ConfirmAction::RemoveWorktree(path),
                    };
                }
                KeyCode::Enter => {
                    let Some(w) = list.get(*cursor) else { return };
                    let path = w.path.clone();
                    self.mode = Mode::Normal;
                    self.open_worktree(path);
                }
                _ => {}
            },
            Mode::Reset { target, .. } => {
                let target = target.clone();
                let go = |app: &mut Self, how: &str| {
                    app.mode = Mode::Normal;
                    app.write(svec(&["reset", how, &target]));
                };
                match key.code {
                    // Keep the changes in the index.
                    KeyCode::Char('s') => go(self, "--soft"),
                    // Keep the changes in the work tree only.
                    KeyCode::Char('m') => go(self, "--mixed"),
                    KeyCode::Char('h') => {
                        self.mode = Mode::Confirm {
                            prompt: format!(
                                "hard reset to {target}? it throws away every change that has no commit."
                            ),
                            action: ConfirmAction::RunAll(vec![svec(&[
                                "reset", "--hard", &target,
                            ])]),
                        };
                    }
                    _ => self.mode = Mode::Normal,
                }
            }
            Mode::Stash { path } => {
                let path = path.clone();
                // Each choice puts a different set of changes away.
                let args: Option<Vec<String>> = match key.code {
                    KeyCode::Char('a') => Some(svec(&["stash", "push"])),
                    KeyCode::Char('u') => Some(svec(&["stash", "push", "--include-untracked"])),
                    KeyCode::Char('s') => Some(svec(&["stash", "push", "--staged"])),
                    KeyCode::Char('f') => path.map(|p| svec(&["stash", "push", "--", &p])),
                    _ => None,
                };
                self.mode = Mode::Normal;
                if let Some(args) = args {
                    self.write(args);
                }
            }
            Mode::Blame { lines, cursor, .. } => match key.code {
                KeyCode::Esc | KeyCode::Char('q') | KeyCode::Char('b') => self.mode = Mode::Normal,
                KeyCode::Char('j') | KeyCode::Down => {
                    *cursor = (*cursor + 1).min(lines.len().saturating_sub(1))
                }
                KeyCode::Char('k') | KeyCode::Up => *cursor = cursor.saturating_sub(1),
                KeyCode::Char('d') => *cursor = (*cursor + 20).min(lines.len().saturating_sub(1)),
                KeyCode::Char('u') => *cursor = cursor.saturating_sub(20),
                KeyCode::Char('g') => *cursor = 0,
                KeyCode::Char('G') => *cursor = lines.len().saturating_sub(1),
                _ => {}
            },
            Mode::Submodules { list, cursor } => match key.code {
                KeyCode::Esc | KeyCode::Char('q') | KeyCode::Char('M') => self.mode = Mode::Normal,
                KeyCode::Char('j') | KeyCode::Down => {
                    *cursor = (*cursor + 1).min(list.len().saturating_sub(1))
                }
                KeyCode::Char('k') | KeyCode::Up => *cursor = cursor.saturating_sub(1),
                KeyCode::Enter => {
                    let Some(s) = list.get(*cursor) else { return };
                    let path = s.path.clone();
                    self.mode = Mode::Normal;
                    self.write(svec(&["submodule", "update", "--init", "--", &path]));
                }
                KeyCode::Char('u') => {
                    self.mode = Mode::Normal;
                    self.write(svec(&["submodule", "update", "--init", "--recursive"]));
                }
                _ => {}
            },
            Mode::Reflog { list, cursor } => match key.code {
                KeyCode::Esc | KeyCode::Char('q') | KeyCode::Char('U') => self.mode = Mode::Normal,
                KeyCode::Char('j') | KeyCode::Down => {
                    *cursor = (*cursor + 1).min(list.len().saturating_sub(1))
                }
                KeyCode::Char('k') | KeyCode::Up => *cursor = cursor.saturating_sub(1),
                KeyCode::Enter => {
                    let Some(e) = list.get(*cursor) else { return };
                    let (target, subject) = (e.at.clone(), e.what.clone());
                    self.mode = Mode::Reset { target, subject };
                }
                _ => {}
            },
            Mode::Ignore { pattern, .. } => {
                let pattern = pattern.clone();
                match key.code {
                    KeyCode::Char('i') => {
                        self.mode = Mode::Normal;
                        self.ignore(pattern, false);
                    }
                    KeyCode::Char('e') => {
                        self.mode = Mode::Normal;
                        self.ignore(pattern, true);
                    }
                    _ => self.mode = Mode::Normal,
                }
            }
            Mode::NewWorktree { branch, path, on_path, path_edited } => match key.code {
                KeyCode::Esc => self.mode = Mode::Normal,
                KeyCode::Tab | KeyCode::BackTab | KeyCode::Down | KeyCode::Up => {
                    *on_path = !*on_path
                }
                KeyCode::Backspace => {
                    if *on_path {
                        path.pop();
                        *path_edited = true;
                    } else {
                        branch.pop();
                    }
                }
                KeyCode::Char(c) => {
                    if *on_path {
                        path.push(c);
                        *path_edited = true;
                    } else {
                        branch.push(c);
                    }
                }
                KeyCode::Enter => {
                    let Mode::NewWorktree { branch, path, .. } =
                        std::mem::replace(&mut self.mode, Mode::Normal)
                    else {
                        return;
                    };
                    self.add_worktree(branch, path);
                }
                _ => {}
            },
            Mode::CommitMsg { summary, body, on_body, .. } => match key.code {
                KeyCode::Esc => self.mode = Mode::Normal,
                // Tab moves between the summary line and the body.
                KeyCode::Tab | KeyCode::BackTab => *on_body = !*on_body,
                KeyCode::Down if !*on_body => *on_body = true,
                KeyCode::Up if *on_body => *on_body = false,
                KeyCode::Backspace => {
                    if *on_body {
                        body.pop()
                    } else {
                        summary.pop()
                    };
                }
                // The enter key makes a new line in the body. In the summary
                // line it sends the commit.
                KeyCode::Enter if *on_body => body.push('\n'),
                KeyCode::Enter => {
                    let Mode::CommitMsg { summary, body, purpose, .. } =
                        std::mem::replace(&mut self.mode, Mode::Normal)
                    else {
                        return;
                    };
                    self.submit_commit(summary, body, purpose);
                }
                KeyCode::Char(c) => {
                    if *on_body {
                        body.push(c)
                    } else {
                        summary.push(c)
                    }
                }
                _ => {}
            },
            Mode::Rebase { items, cursor, .. } => match key.code {
                KeyCode::Esc | KeyCode::Char('q') => self.mode = Mode::Normal,
                KeyCode::Char('j') | KeyCode::Down => *cursor = (*cursor + 1).min(items.len() - 1),
                KeyCode::Char('k') | KeyCode::Up => *cursor = cursor.saturating_sub(1),
                // Control with j or k moves the commit itself.
                KeyCode::Char('J') if *cursor + 1 < items.len() => {
                    items.swap(*cursor, *cursor + 1);
                    *cursor += 1;
                }
                KeyCode::Char('K') if *cursor > 0 => {
                    items.swap(*cursor, *cursor - 1);
                    *cursor -= 1;
                }
                KeyCode::Char(c @ ('p' | 'r' | 'e' | 's' | 'f' | 'd')) => {
                    items[*cursor].action = match c {
                        'p' => TodoAction::Pick,
                        'r' => TodoAction::Reword,
                        'e' => TodoAction::Edit,
                        's' => TodoAction::Squash,
                        'f' => TodoAction::Fixup,
                        _ => TodoAction::Drop,
                    };
                }
                KeyCode::Enter => {
                    let Mode::Rebase { items, base, .. } =
                        std::mem::replace(&mut self.mode, Mode::Normal)
                    else {
                        return;
                    };
                    self.run_rebase(items, base);
                }
                _ => {}
            },
            Mode::Input { buffer, .. } => match key.code {
                KeyCode::Esc => self.mode = Mode::Normal,
                KeyCode::Backspace => {
                    buffer.pop();
                }
                KeyCode::Char(c) => buffer.push(c),
                KeyCode::Enter => {
                    let Mode::Input { buffer, purpose, .. } =
                        std::mem::replace(&mut self.mode, Mode::Normal)
                    else {
                        return;
                    };
                    self.submit_input(purpose, buffer);
                }
                _ => {}
            },
            Mode::Confirm { .. } => match key.code {
                KeyCode::Char('y') => {
                    let Mode::Confirm { action, .. } =
                        std::mem::replace(&mut self.mode, Mode::Normal)
                    else {
                        return;
                    };
                    match action {
                        ConfirmAction::RunAll(cmds) => {
                            for cmd in cmds {
                                self.write(cmd);
                            }
                            return;
                        }
                        ConfirmAction::GoToWorktree(path) => return self.open_worktree(path),
                        // The fixup commit must exist before the rebase can
                        // fold it in. The write runs on another thread, thus
                        // the rebase waits for the result of the commit.
                        ConfirmAction::Fixup(id) => {
                            self.pending_fixup = Some(id.clone());
                            self.write(svec(&["commit", &format!("--fixup={id}")]));
                            return;
                        }
                        // The window waits for the staging to finish, thus
                        // it opens over a state that is already correct.
                        ConfirmAction::StageAllThenCommit => {
                            self.pending_commit_window = true;
                            self.write(svec(&["add", "-A"]));
                            return;
                        }
                        ConfirmAction::Split(index) => {
                            let Some((mut items, base)) = self.rebase_slice(index) else {
                                return;
                            };
                            // The target is the oldest commit in the list.
                            items[index].action = TodoAction::Edit;
                            self.pending_split = true;
                            self.run_rebase(items, base);
                            return;
                        }
                        ConfirmAction::Absorb => {
                            let own = self.repo.unpushed.clone();
                            self.running.push("absorb".into());
                            if let Some(git) = &self.git {
                                git.send(Req::Absorb { own });
                            }
                            return;
                        }
                        _ => {}
                    }
                    let args: Vec<String> = match action {
                        // A plain delete refuses a branch that is not
                        // merged. The force delete does not refuse.
                        ConfirmAction::DeleteBranch { name, force } => {
                            svec(&["branch", if force { "-D" } else { "-d" }, &name])
                        }
                        ConfirmAction::DropStash(i) => {
                            svec(&["stash", "drop", &format!("stash@{{{i}}}")])
                        }
                        ConfirmAction::Merge(name) => svec(&["merge", "--no-edit", &name]),
                        ConfirmAction::Revert(id) => svec(&["revert", "--no-edit", &id]),
                        ConfirmAction::RemoveWorktree(path) => svec(&["worktree", "remove", &path]),
                        ConfirmAction::RunAll(_)
                        | ConfirmAction::GoToWorktree(_)
                        | ConfirmAction::Fixup(_)
                        | ConfirmAction::StageAllThenCommit
                        | ConfirmAction::Absorb
                        | ConfirmAction::Split(_) => return,
                    };
                    self.write(args);
                }
                _ => self.mode = Mode::Normal,
            },
            Mode::Hunks { header, hunks, cursor, line, picked, .. } => {
                let body_len = hunks[*cursor].lines().count().saturating_sub(1);
                match key.code {
                    KeyCode::Esc | KeyCode::Char('q') => self.mode = Mode::Normal,
                    KeyCode::Char('j') | KeyCode::Down => {
                        *line = (*line + 1).min(body_len.saturating_sub(1))
                    }
                    KeyCode::Char('k') | KeyCode::Up => *line = line.saturating_sub(1),
                    // A move to another hunk drops the marked lines. They
                    // point at the old hunk.
                    KeyCode::Char('J') | KeyCode::Tab => {
                        *cursor = (*cursor + 1).min(hunks.len() - 1);
                        *line = 0;
                        picked.clear();
                    }
                    KeyCode::Char('K') | KeyCode::BackTab => {
                        *cursor = cursor.saturating_sub(1);
                        *line = 0;
                        picked.clear();
                    }
                    KeyCode::Char(' ') => {
                        match picked.iter().position(|p| p == line) {
                            Some(i) => {
                                picked.remove(i);
                            }
                            None => picked.push(*line),
                        }
                        *line = (*line + 1).min(body_len.saturating_sub(1));
                    }
                    // Stage the whole hunk.
                    KeyCode::Char('a') => {
                        let patch = patch::hunk_patch(header, &hunks[*cursor]);
                        self.apply_and_leave(patch);
                    }
                    // Stage the marked lines only.
                    KeyCode::Enter => {
                        let marks = if picked.is_empty() { vec![*line] } else { picked.clone() };
                        match patch::subset_hunk(&hunks[*cursor], &marks) {
                            Some(sub) => {
                                let patch = patch::hunk_patch(header, &sub);
                                self.apply_and_leave(patch);
                            }
                            None => {
                                self.message = "mark a line that adds or removes text".into();
                                self.message_ok = false;
                            }
                        }
                    }
                    _ => {}
                }
            }
        }
    }

    fn submit_input(&mut self, purpose: InputPurpose, buffer: String) {
        if buffer.is_empty() {
            return;
        }
        if let InputPurpose::Shell = purpose {
            self.running.push(format!(": {buffer}"));
            if let Some(git) = &self.git {
                git.send(Req::Shell(buffer));
            }
            return;
        }
        let args: Vec<String> = match purpose {
            InputPurpose::NewBranch => svec(&["checkout", "-b", &buffer]),
            InputPurpose::RenameBranch(old) => svec(&["branch", "-m", &old, &buffer]),
            // Always make a tag with a message. Some settings turn every
            // tag into one that needs a message, and then a plain tag fails.
            InputPurpose::Tag(id) => svec(&["tag", "-a", &buffer, "-m", &buffer, &id]),
            InputPurpose::Search => {
                self.repo.filter = Some(buffer.clone());
                self.selected[3] = 0;
                self.focus = 3;
                if let Some(git) = &self.git {
                    git.send(Req::LogFilter(Some(buffer)));
                }
                return;
            }
            InputPurpose::Shell => return,
        };
        self.write(args);
    }

    fn open_commit_window(&mut self) {
        self.mode = Mode::CommitMsg {
            summary: String::new(),
            body: String::new(),
            on_body: false,
            purpose: CommitPurpose::New,
        };
    }

    /// Commit with the summary and the body. Git puts an empty line between
    /// two message parts, thus the body becomes a real commit body.
    fn submit_commit(&mut self, summary: String, body: String, purpose: CommitPurpose) {
        if summary.trim().is_empty() {
            self.message = "the summary must have text".into();
            self.message_ok = false;
            return;
        }
        let msg_args = |verb: &str| {
            let mut args = svec(&[verb, "-m", &summary]);
            if !body.trim().is_empty() {
                args.push("-m".into());
                args.push(body.clone());
            }
            args
        };
        match purpose {
            CommitPurpose::New => self.write(msg_args("commit")),
            // HEAD needs only an amend. No rebase runs.
            CommitPurpose::Reword(0) => {
                let mut args = msg_args("commit");
                args.insert(1, "--amend".into());
                self.write(args);
            }
            // An older commit needs a rebase with one reword step. Git asks
            // this program for both the todo list and the new message.
            CommitPurpose::Reword(index) => {
                let Some(git) = &self.git else { return };
                let mut text = summary.clone();
                if !body.trim().is_empty() {
                    text.push_str("\n\n");
                    text.push_str(body.trim_end());
                }
                text.push('\n');
                let msg_path = git.git_dir.join("lazier-msg");
                if let Err(e) = std::fs::write(&msg_path, text) {
                    self.message = e.to_string();
                    self.message_ok = false;
                    return;
                }
                let Some((mut items, base)) = self.rebase_slice(index) else {
                    return;
                };
                // The target is the oldest commit in the list.
                items[index].action = TodoAction::Reword;
                let editor = self.seq_editor_cmd(&msg_path);
                self.run_rebase_with(items, base, vec![("GIT_EDITOR".into(), editor)]);
            }
        }
    }

    /// The path that the branch name suggests. It sits beside the root of
    /// the repository, thus the directories stay together.
    pub fn suggested_worktree_path(&self, branch: &str) -> String {
        let Some(git) = &self.git else {
            return String::new();
        };
        if branch.is_empty() {
            return String::new();
        }
        let root = &git.root;
        let name = root.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
        // A branch name can hold a slash. A directory name must not.
        let safe = branch.replace(['/', ' '], "-");
        let parent = root.parent().map(|p| p.to_string_lossy().into_owned()).unwrap_or_default();
        format!("{parent}/{name}-{safe}")
    }

    /// Add a rule. `local` writes the private file, which no other person
    /// sees. The other file is `.gitignore`, which goes into a commit.
    fn ignore(&mut self, pattern: String, local: bool) {
        let Some(git) = &self.git else { return };
        // Several marked files give several rules, one for each line.
        for line in pattern.lines() {
            git.send(Req::Ignore { pattern: line.to_string(), local });
        }
    }

    fn add_worktree(&mut self, branch: String, path: String) {
        if branch.is_empty() {
            self.message = "the branch name must have text".into();
            self.message_ok = false;
            return;
        }
        let path = if path.is_empty() { self.suggested_worktree_path(&branch) } else { path };
        // An existing branch needs no -b flag. A new one does.
        let exists = self.repo.branches.iter().any(|b| b.name == branch);
        let args = if exists {
            svec(&["worktree", "add", &path, &branch])
        } else {
            svec(&["worktree", "add", "-b", &branch, &path])
        };
        self.write(args);
    }

    /// Move the program to another worktree. The old workers stop when
    /// their sender goes away. New workers start at the new directory.
    fn open_worktree(&mut self, path: String) {
        if let Err(e) = std::env::set_current_dir(&path) {
            self.message = e.to_string();
            self.message_ok = false;
            return;
        }
        let Some(tx) = self.tx.clone() else { return };
        match git::spawn(tx.clone()) {
            Ok(git) => {
                git::watch::spawn(git.git_dir.clone(), tx);
                self.git = Some(git);
                self.repo = RepoState::default();
                self.selected = [0; 6];
                self.tree.clear();
                self.refresh_all();
                self.log_cmd(true, format!("open worktree {path}"), 0, Vec::new());
            }
            Err(e) => {
                self.message = e.to_string();
                self.message_ok = false;
            }
        }
    }

    // Send the patch, then leave the hunk view. The line numbers of the
    // other hunks change after the apply, thus they must not stay in use.
    fn apply_and_leave(&mut self, patch: String) {
        self.mode = Mode::Normal;
        if let Some(git) = &self.git {
            git.send(Req::ApplyPatch { patch, reverse: false });
        }
    }

    /// Build the todo items for the commits from HEAD down to `index`, and
    /// the commit that the rebase starts from.
    fn rebase_slice(&mut self, index: usize) -> Option<(Vec<TodoItem>, Option<String>)> {
        let last = self.repo.commits.get(index)?;
        let base = if index + 1 < self.repo.commits.len() {
            Some(format!("{}^", last.id_str()))
        } else if self.repo.log_done {
            None // The oldest commit is a root commit.
        } else {
            self.message = "load more commits first".into();
            self.message_ok = false;
            return None;
        };
        let items = self.repo.commits[..=index]
            .iter()
            .map(|c| TodoItem {
                action: TodoAction::Pick,
                id: c.id_str().to_string(),
                subject: c.subject.to_string(),
            })
            .collect();
        Some((items, base))
    }

    /// The command line that makes git call this program as an editor. The
    /// program copies `file` over the file that git wants edited.
    fn seq_editor_cmd(&self, file: &std::path::Path) -> String {
        let exe = std::env::current_exe().unwrap_or_default();
        format!(
            "{} --seq-editor {}",
            rebase::sh_quote(&exe.to_string_lossy()),
            rebase::sh_quote(&file.to_string_lossy())
        )
    }

    fn write(&mut self, args: Vec<String>) {
        // A slow command shows in the bar until it ends.
        if git::is_network(&args) {
            self.running.push(format!("git {}", args.join(" ")));
        }
        if let Some(git) = &self.git {
            git.send(Req::Write(args));
        }
    }

    /// Run a git command with the real terminal. Use it for a command that
    /// asks the user something, for example a password or a commit message.
    fn suspend(&mut self, args: Vec<String>) {
        self.pending_suspend = Some((args, Vec::new()));
    }

    /// Open the todo editor for the commits above the selected one. The
    /// selected commit is the oldest commit in the list.
    fn start_rebase(&mut self) {
        if let Some((items, base)) = self.rebase_slice(self.selected[3]) {
            self.mode = Mode::Rebase { items, cursor: 0, base };
        }
    }

    /// Write the todo list, then run the rebase with the real terminal.
    /// Git calls this program as the sequence editor, thus git shows no
    /// editor for the todo list. A reword step still opens the user editor.
    fn run_rebase(&mut self, items: Vec<TodoItem>, base: Option<String>) {
        self.run_rebase_with(items, base, Vec::new());
    }

    fn run_rebase_with(
        &mut self,
        items: Vec<TodoItem>,
        base: Option<String>,
        mut envs: Vec<(String, String)>,
    ) {
        let Some(git) = &self.git else { return };
        let todo_path = git.git_dir.join("lazier-todo");
        if let Err(e) = std::fs::write(&todo_path, rebase::serialize(&items)) {
            self.message = e.to_string();
            self.message_ok = false;
            return;
        }
        envs.push(("GIT_SEQUENCE_EDITOR".into(), self.seq_editor_cmd(&todo_path)));
        let args = match &base {
            Some(b) => svec(&["rebase", "-i", b]),
            None => svec(&["rebase", "-i", "--root"]),
        };
        self.pending_suspend = Some((args, envs));
    }

    fn log_cmd(&mut self, ok: bool, cmd: String, ms: u64, output: Vec<String>) {
        self.cmd_log.push(LogEntry { ok, cmd, ms, output });
        // Keep the log short. Old entries have no value.
        if self.cmd_log.len() > 100 {
            self.cmd_log.remove(0);
        }
    }

    /// The mouse moves the focus and the selection. A window is open in
    /// every mode but Normal, thus the mouse does nothing then.
    fn handle_mouse(&mut self, m: ratatui::crossterm::event::MouseEvent) {
        use ratatui::crossterm::event::{MouseButton, MouseEventKind};
        // The key list is taller than the window, thus the wheel moves it.
        if let Mode::Help { scroll } = &mut self.mode {
            let last = ui::help_max_scroll(self.area);
            match m.kind {
                MouseEventKind::ScrollDown => *scroll = (*scroll + 3).min(last),
                MouseEventKind::ScrollUp => *scroll = scroll.saturating_sub(3),
                _ => {}
            }
            return;
        }
        if !matches!(self.mode, Mode::Normal) || self.zoom {
            return;
        }
        let p = ui::panes(self.area, self.show_log);
        // Find the panel under the pointer. Panel five is the diff.
        let hit = p
            .left
            .iter()
            .position(|r| contains(*r, m.column, m.row))
            .or_else(|| contains(p.diff, m.column, m.row).then_some(5));
        let Some(panel) = hit else { return };

        match m.kind {
            MouseEventKind::Down(MouseButton::Left) => {
                self.message.clear();
                self.focus = panel;
                if panel == 5 {
                    return;
                }
                // The row under the pointer becomes the selection.
                let area = p.left[panel];
                let visible = area.height.saturating_sub(2) as usize;
                let len = self.panel_len(panel);
                let inside = m.row.saturating_sub(area.y + 1) as usize;
                let idx = ui::list_offset(self.selected[panel], len, visible) + inside;
                if inside < visible && idx < len {
                    self.selected[panel] = idx;
                }
            }
            MouseEventKind::ScrollDown => {
                self.focus = panel;
                self.apply(Action::Down);
            }
            MouseEventKind::ScrollUp => {
                self.focus = panel;
                self.apply(Action::Up);
            }
            _ => {}
        }
    }

    /// The spinner character for this moment. None when nothing runs.
    pub fn spinner(&self) -> Option<char> {
        const FRAMES: [char; 10] = ['', '', '', '', '', '', '', '', '', ''];
        (!self.running.is_empty()).then(|| FRAMES[self.tick % FRAMES.len()])
    }

    pub fn panel_len(&self, panel: usize) -> usize {
        match panel {
            0 => 1,
            1 => self.tree.len(),
            2 => self.repo.branches.len(),
            3 => self.repo.commits.len(),
            4 => self.repo.stashes.len(),
            _ => 0,
        }
    }

    fn selected_row(&self) -> Option<&TreeRow> {
        self.tree.get(self.selected[1])
    }

    fn selected_file(&self) -> Option<&FileEntry> {
        self.selected_row().and_then(|r| r.file).and_then(|i| self.repo.files.get(i))
    }

    /// The paths that a file action works on: the marked files, or the row
    /// under the cursor when nothing is marked.
    fn action_paths(&self) -> Vec<String> {
        if !self.marked.is_empty() {
            let mut out: Vec<String> = self.marked.iter().cloned().collect();
            out.sort();
            return out;
        }
        self.selected_file().map(|f| vec![f.path.clone()]).unwrap_or_default()
    }

    /// A name for what the next action works on, for a question to the user.
    fn action_label(&self) -> String {
        match self.marked.len() {
            0 => self.selected_file().map(|f| f.path.clone()).unwrap_or_default(),
            1 => self.marked.iter().next().cloned().unwrap_or_default(),
            n => format!("{n} files"),
        }
    }

    /// The path that a file action works on. It gives the pathspec, whether
    /// git knows the path, and a name to show the user. The root row gives
    /// the whole work tree.
    fn file_target(&self) -> Option<(String, bool, String)> {
        let row = self.selected_row()?;
        if let Some(dir) = &row.dir {
            let path = if dir.is_empty() { ".".to_string() } else { dir.clone() };
            let label =
                if dir.is_empty() { "the whole work tree".into() } else { format!("{dir}/") };
            // A directory can hold both kinds of file.
            return Some((path, false, label));
        }
        let f = self.repo.files.get(row.file?)?;
        Some((f.path.clone(), f.work == '?', f.path.clone()))
    }

    fn rebuild_tree(&mut self) {
        self.tree = tree::build(&self.repo.files, &self.collapsed);
        self.clamp(1);
    }

    fn apply(&mut self, action: Action) {
        match action {
            Action::Quit => self.quit = true,
            Action::NextPanel => self.focus = (self.focus + 1) % 6,
            Action::PrevPanel => self.focus = (self.focus + 5) % 6,
            Action::FocusPanel(i) => self.focus = i,
            // In the diff pane, the motion keys scroll the text.
            Action::Down if self.focus == 5 => self.scroll_diff(1),
            Action::Up if self.focus == 5 => self.scroll_diff(-1),
            Action::PageDown if self.focus == 5 => self.scroll_diff(15),
            Action::PageUp if self.focus == 5 => self.scroll_diff(-15),
            Action::Top if self.focus == 5 => self.diff_scroll = 0,
            Action::Bottom if self.focus == 5 => self.scroll_diff(i16::MAX),
            Action::Down => {
                let len = self.panel_len(self.focus);
                let sel = &mut self.selected[self.focus];
                if *sel + 1 < len {
                    *sel += 1;
                }
            }
            Action::Up => {
                let sel = &mut self.selected[self.focus];
                *sel = sel.saturating_sub(1);
            }
            Action::PageDown => {
                let len = self.panel_len(self.focus);
                let sel = &mut self.selected[self.focus];
                *sel = (*sel + 15).min(len.saturating_sub(1));
            }
            Action::PageUp => {
                let sel = &mut self.selected[self.focus];
                *sel = sel.saturating_sub(15);
            }
            Action::Top => self.selected[self.focus] = 0,
            Action::Bottom => {
                self.selected[self.focus] = self.panel_len(self.focus).saturating_sub(1);
            }
            Action::DiffScroll(delta) => self.scroll_diff(delta as i16),
            Action::ZoomGraph => self.zoom = !self.zoom,
            Action::Help => self.mode = Mode::Help { scroll: 0 },
            Action::ToggleLog => self.show_log = !self.show_log,
            Action::FirstParent => {
                self.first_parent = !self.first_parent;
                // The list starts again from the top, thus the cursor must
                // not point past the end of the new list.
                self.selected[3] = 0;
                if let Some(git) = &self.git {
                    git.send(Req::LogFirstParent(self.first_parent));
                }
            }
            Action::Refresh => self.refresh_all(),

            Action::ToggleStage => {
                // On a directory row, stage the whole directory. The root
                // row has an empty path, which is not a valid pathspec.
                if let Some(dir) = self.selected_row().and_then(|r| r.dir.clone()) {
                    let args = if dir.is_empty() {
                        svec(&["add", "-A"])
                    } else {
                        svec(&["add", "--", &dir])
                    };
                    self.write(args);
                } else if !self.marked.is_empty() {
                    // With files marked, stage every one of them.
                    let paths = self.action_paths();
                    let mut args = svec(&["add", "--"]);
                    args.extend(paths);
                    self.marked.clear();
                    self.write(args);
                } else if let Some(f) = self.selected_file() {
                    let args = if f.staged() && f.work == ' ' {
                        svec(&["restore", "--staged", "--", &f.path])
                    } else {
                        svec(&["add", "--", &f.path])
                    };
                    self.write(args);
                }
            }
            Action::StageAll => self.write(svec(&["add", "-A"])),
            Action::CommitPrompt => {
                let staged = self.repo.files.iter().any(|f| f.staged());
                match (staged, self.repo.files.is_empty()) {
                    // Nothing is staged and nothing has changed.
                    (false, true) => {
                        self.mode = Mode::Error {
                            cmd: "commit".into(),
                            output: vec!["there is nothing to commit".into()],
                        };
                    }
                    // Changes are there, but none of them are staged yet.
                    (false, false) => {
                        self.mode = Mode::Confirm {
                            prompt:
                                "nothing is staged. stage every change, new files too, and commit?"
                                    .into(),
                            action: ConfirmAction::StageAllThenCommit,
                        };
                    }
                    _ => self.open_commit_window(),
                }
            }
            Action::CommitEditor => self.suspend(svec(&["commit"])),
            Action::StashPrompt => {
                let path = self.selected_file().map(|f| f.path.clone());
                self.mode = Mode::Stash { path };
            }
            Action::EnterHunks => {
                // On a directory row, the enter key folds or unfolds it.
                if let Some(dir) = self.selected_row().and_then(|r| r.dir.clone()) {
                    if !self.collapsed.remove(&dir) {
                        self.collapsed.insert(dir);
                    }
                    self.rebuild_tree();
                    return;
                }
                let Some(f) = self.selected_file() else {
                    return;
                };
                // A file that git does not track has no hunks to stage.
                if f.work == '?' {
                    self.message = "stage the whole file first".into();
                    self.message_ok = false;
                    return;
                }
                // The diff pane must already show this file. The diff text
                // is index-to-worktree, thus the hunks fit `apply --cached`.
                let want = DiffTarget::WorktreeFile { path: f.path.clone(), untracked: false };
                if self.diff_target.as_ref() != Some(&want) {
                    return;
                }
                match patch::split_diff(&self.repo.diff) {
                    Some((header, hunks)) if !hunks.is_empty() => {
                        self.mode = Mode::Hunks {
                            path: f.path.clone(),
                            header,
                            hunks,
                            cursor: 0,
                            line: 0,
                            picked: Vec::new(),
                        };
                    }
                    _ => self.message = "no hunks in this file".into(),
                }
            }
            // Discard removes work that has no commit. It always asks first.
            Action::DiscardChanges => {
                let (targets, label) = if self.marked.is_empty() {
                    let Some((t, _, l)) = self.file_target() else {
                        return;
                    };
                    (vec![t], l)
                } else {
                    (self.action_paths(), self.action_label())
                };
                let mut restore = svec(&["restore", "--staged", "--worktree", "--"]);
                restore.extend(targets.iter().cloned());
                let mut clean = svec(&["clean", "-fd", "--"]);
                clean.extend(targets);
                self.marked.clear();
                self.mode = Mode::Confirm {
                    prompt: format!("discard all changes in {label}? this cannot be undone."),
                    // A new file has no old state, thus only a clean removes
                    // it. A tracked file needs the restore.
                    action: ConfirmAction::RunAll(vec![restore, clean]),
                };
            }
            Action::DeleteFile => {
                let (targets, label) = if self.marked.is_empty() {
                    let Some((t, _, l)) = self.file_target() else {
                        return;
                    };
                    (vec![t], l)
                } else {
                    (self.action_paths(), self.action_label())
                };
                // A delete of the root would remove the whole work tree.
                if targets.iter().any(|t| t == ".") {
                    self.message = "select a file or a directory, not the root".into();
                    self.message_ok = false;
                    return;
                }
                // A file git knows needs rm. A new one needs clean. Both
                // run, and the one that does not apply changes nothing.
                let mut rm = svec(&["rm", "-r", "-f", "--ignore-unmatch", "--"]);
                rm.extend(targets.iter().cloned());
                let mut clean = svec(&["clean", "-fd", "--"]);
                clean.extend(targets);
                self.marked.clear();
                self.mode = Mode::Confirm {
                    prompt: format!("delete {label} from the disk?"),
                    action: ConfirmAction::RunAll(vec![rm, clean]),
                };
            }

            // Mark or unmark the file under the cursor, so the next action
            // works on several files at once.
            Action::ToggleMark => {
                let Some(row) = self.selected_row() else {
                    return;
                };
                match &row.dir {
                    // A directory row marks every file under it, or drops
                    // the marks when they are all there already.
                    Some(dir) => {
                        let under: Vec<String> = self
                            .repo
                            .files
                            .iter()
                            .filter(|f| dir.is_empty() || f.path.starts_with(&format!("{dir}/")))
                            .map(|f| f.path.clone())
                            .collect();
                        if under.iter().all(|p| self.marked.contains(p)) {
                            for p in under {
                                self.marked.remove(&p);
                            }
                        } else {
                            self.marked.extend(under);
                        }
                    }
                    None => {
                        let Some(f) = self.selected_file() else {
                            return;
                        };
                        let path = f.path.clone();
                        if !self.marked.remove(&path) {
                            self.marked.insert(path);
                        }
                    }
                }
                // The cursor moves on, thus marking a run needs one key
                // for each row.
                let len = self.panel_len(1);
                let sel = &mut self.selected[1];
                if *sel + 1 < len {
                    *sel += 1;
                }
            }
            Action::IgnorePrompt => {
                // With files marked, make a rule for each of them.
                if !self.marked.is_empty() {
                    let paths = self.action_paths();
                    self.mode = Mode::Ignore {
                        pattern: paths
                            .iter()
                            .map(|p| format!("/{p}"))
                            .collect::<Vec<_>>()
                            .join("\n"),
                        tracked: false,
                    };
                    self.marked.clear();
                    return;
                }
                let Some(row) = self.selected_row() else {
                    return;
                };
                // A directory rule ends with a slash, thus git takes the
                // whole directory. The root has no useful rule.
                let (pattern, tracked) = match &row.dir {
                    Some(d) if d.is_empty() => return,
                    Some(d) => (format!("/{d}/"), false),
                    None => {
                        let Some(f) = self.selected_file() else {
                            return;
                        };
                        (format!("/{}", f.path), f.work != '?')
                    }
                };
                self.mode = Mode::Ignore { pattern, tracked };
            }

            Action::TakeOurs | Action::TakeTheirs => {
                let side = if matches!(action, Action::TakeOurs) { "--ours" } else { "--theirs" };
                if let Some(f) = self.selected_file()
                    && f.conflicted()
                {
                    let path = f.path.clone();
                    self.write(svec(&["checkout", side, "--", &path]));
                    self.write(svec(&["add", "--", &path]));
                }
            }

            // Fold the staged changes into the last commit. The message
            // stays as it is.
            Action::AmendLast => {
                self.mode = Mode::Confirm {
                    prompt: "add the staged changes to the last commit?".into(),
                    action: ConfirmAction::RunAll(vec![svec(&["commit", "--amend", "--no-edit"])]),
                };
            }
            Action::ForcePush => {
                let head = self.repo.head.clone().unwrap_or_else(|| "HEAD".into());
                self.mode = Mode::Confirm {
                    // The lease makes git refuse when the remote moved,
                    // thus it cannot throw away work of another person.
                    prompt: format!("force push {head}? it replaces the branch on the remote."),
                    action: ConfirmAction::RunAll(vec![svec(&["push", "--force-with-lease"])]),
                };
            }
            Action::ResetPrompt => {
                if let Some(c) = self.repo.commits.get(self.selected[3]) {
                    self.mode = Mode::Reset {
                        target: c.id_str().to_string(),
                        subject: c.subject.to_string(),
                    };
                }
            }
            // Send the staged changes back to the commits they belong to.
            Action::Absorb => {
                if !self.repo.files.iter().any(|f| f.staged()) {
                    self.mode = Mode::Error {
                        cmd: "absorb".into(),
                        output: vec!["stage the changes you want to send back first".into()],
                    };
                    return;
                }
                if self.repo.unpushed.is_empty() {
                    self.mode = Mode::Error {
                        cmd: "absorb".into(),
                        output: vec![
                            "every commit is on the remote already".into(),
                            "a change can only go back into a commit that is still yours.".into(),
                        ],
                    };
                    return;
                }
                let n = self.repo.unpushed.len();
                self.mode = Mode::Confirm {
                    prompt: format!(
                        "send each staged change back to the commit that wrote those lines? it rewrites your {n} commits that no remote has."
                    ),
                    action: ConfirmAction::Absorb,
                };
            }
            Action::BlameFile => {
                let Some(f) = self.selected_file() else {
                    return;
                };
                if f.work == '?' {
                    self.message = "git does not track this file yet".into();
                    self.message_ok = false;
                    return;
                }
                let path = f.path.clone();
                if let Some(git) = &self.git {
                    git.send(Req::Blame(path));
                }
            }
            Action::SubmoduleList => {
                if let Some(git) = &self.git {
                    git.send(Req::Submodules);
                }
            }
            // Mark a commit, then move to another one to see what lies
            // between them. The same key on the marked commit clears it.
            Action::MarkForCompare => {
                let Some(c) = self.repo.commits.get(self.selected[3]) else {
                    return;
                };
                let id = c.id_str().to_string();
                self.repo.compare = match &self.repo.compare {
                    Some(old) if *old == id => None,
                    _ => Some(id),
                };
                self.diff_target = None;
            }
            Action::CopyId => {
                if let Some(c) = self.repo.commits.get(self.selected[3])
                    && let Some(git) = &self.git
                {
                    git.send(Req::Copy(c.id_str().to_string()));
                }
            }
            Action::TagPrompt => {
                if let Some(c) = self.repo.commits.get(self.selected[3]) {
                    self.mode = Mode::Input {
                        prompt: "name for the tag",
                        buffer: String::new(),
                        purpose: InputPurpose::Tag(c.id_str().to_string()),
                    };
                }
            }
            Action::PushTags => self.write(svec(&["push", "--tags"])),
            // Make a commit that git can fold into an older one, then fold
            // it. Git makes the todo list itself, thus no editor is needed.
            Action::FixupInto => {
                let Some(c) = self.repo.commits.get(self.selected[3]) else {
                    return;
                };
                let id = c.id_str().to_string();
                let subject = c.subject.to_string();
                self.mode = Mode::Confirm {
                    prompt: format!("fold the staged changes into {id} \"{subject}\"?"),
                    action: ConfirmAction::Fixup(id),
                };
            }
            Action::OpenInEditor => {
                let Some(f) = self.selected_file() else {
                    return;
                };
                let path = f.path.clone();
                let Some(git) = &self.git else { return };
                self.pending_open = Some((crate::git::editor(&git.root), path));
            }
            Action::SearchPrompt => {
                self.mode = Mode::Input {
                    prompt: "search the commit messages",
                    buffer: String::new(),
                    purpose: InputPurpose::Search,
                };
            }
            // The escape key drops whatever is set aside: first the marked
            // files, then the search.
            Action::ClearFilter => {
                if !self.marked.is_empty() {
                    self.marked.clear();
                    return;
                }
                if self.repo.filter.take().is_some() {
                    self.selected[3] = 0;
                    if let Some(git) = &self.git {
                        git.send(Req::LogFilter(None));
                    }
                }
            }
            Action::ReflogList => {
                if let Some(git) = &self.git {
                    git.send(Req::Reflog);
                }
            }

            Action::Checkout => {
                let Some(b) = self.repo.branches.get(self.selected[2]) else {
                    return;
                };
                // A remote branch needs a local one that follows it.
                if b.remote {
                    let name = b.name.clone();
                    self.write(svec(&["checkout", "--track", &name]));
                    return;
                }
                // A checkout of the branch you are on does nothing, but it
                // still reads every file. Do not run it.
                if b.current {
                    self.message = format!("you are already on {}", b.name);
                    self.message_ok = true;
                    return;
                }
                let name = b.name.clone();
                self.write(svec(&["checkout", &name]));
            }
            Action::NewBranchPrompt => {
                self.mode = Mode::Input {
                    prompt: "new branch name",
                    buffer: String::new(),
                    purpose: InputPurpose::NewBranch,
                };
            }
            Action::DeleteBranch { force } => {
                let Some(b) = self.repo.branches.get(self.selected[2]) else {
                    return;
                };
                if b.current {
                    self.message = "cannot delete the branch you are on".into();
                    self.message_ok = false;
                    return;
                }
                let word = if force { "force delete" } else { "delete" };
                self.mode = Mode::Confirm {
                    prompt: format!("{word} branch {}?", b.name),
                    action: ConfirmAction::DeleteBranch { name: b.name.clone(), force },
                };
            }
            Action::RenameBranchPrompt => {
                if let Some(b) = self.repo.branches.get(self.selected[2]) {
                    self.mode = Mode::Input {
                        prompt: "new name for the branch",
                        buffer: b.name.clone(),
                        purpose: InputPurpose::RenameBranch(b.name.clone()),
                    };
                }
            }
            // Put the commits of the current branch on top of another one.
            Action::RebaseOnto => {
                let Some(b) = self.repo.branches.get(self.selected[2]) else {
                    return;
                };
                if b.current {
                    self.message = "that is the branch you are on".into();
                    self.message_ok = false;
                    return;
                }
                let name = b.name.clone();
                let head = self.repo.head.clone().unwrap_or_else(|| "HEAD".into());
                self.mode = Mode::Confirm {
                    prompt: format!("put the commits of {head} on top of {name}?"),
                    action: ConfirmAction::RunAll(vec![svec(&["rebase", "--autostash", &name])]),
                };
            }
            Action::MergeBranch => {
                let Some(b) = self.repo.branches.get(self.selected[2]) else {
                    return;
                };
                if b.current {
                    self.message = "cannot merge a branch into itself".into();
                    self.message_ok = false;
                    return;
                }
                let name = b.name.clone();
                let head = self.repo.head.clone().unwrap_or_else(|| "HEAD".into());
                self.mode = Mode::Confirm {
                    prompt: format!("merge {name} into {head}?"),
                    action: ConfirmAction::Merge(name),
                };
            }

            Action::CherryPick => {
                if let Some(c) = self.repo.commits.get(self.selected[3]) {
                    let id = c.id_str().to_string();
                    self.write(svec(&["cherry-pick", "--no-commit", &id]));
                }
            }
            Action::BisectBad | Action::BisectGood | Action::BisectSkip | Action::BisectReset => {
                let id = self.repo.commits.get(self.selected[3]).map(|c| c.id_str().to_string());
                if let Some(args) = bisect_command(self.repo.bisecting, &action, id.as_deref()) {
                    self.write(args);
                }
            }

            Action::Worktrees => {
                if let Some(git) = &self.git {
                    git.send(Req::Worktrees);
                }
            }

            Action::RewordCommit => {
                // Read the old message first. The window opens when it
                // arrives.
                let index = self.selected[3];
                if let Some(c) = self.repo.commits.get(index)
                    && let Some(git) = &self.git
                {
                    git.send(Req::ReadMessage { id: c.id_str().to_string(), index });
                }
            }
            Action::RevertCommit => {
                if let Some(c) = self.repo.commits.get(self.selected[3]) {
                    let id = c.id_str().to_string();
                    let subject = c.subject.to_string();
                    self.mode = Mode::Confirm {
                        prompt: format!("revert {id} \"{subject}\"?"),
                        action: ConfirmAction::Revert(id),
                    };
                }
            }
            // These run in the background. The bar says one is running.
            Action::Push => self.write(svec(&["push"])),
            Action::Pull => self.write(svec(&["pull"])),
            Action::Fetch => self.write(svec(&["fetch"])),
            Action::ShellPrompt => {
                self.mode = Mode::Input {
                    prompt: "shell command",
                    buffer: String::new(),
                    purpose: InputPurpose::Shell,
                };
            }

            Action::InteractiveRebase => self.start_rebase(),
            // Open one commit so its changes can go into several commits.
            Action::SplitCommit => {
                let Some(c) = self.repo.commits.get(self.selected[3]) else {
                    return;
                };
                let (id, subject) = (c.id_str().to_string(), c.subject.to_string());
                self.mode = Mode::Confirm {
                    prompt: format!(
                        "open {id} \"{subject}\" so you can make several commits from it?"
                    ),
                    action: ConfirmAction::Split(self.selected[3]),
                };
            }
            // These three keys work only while a rebase is stopped.
            Action::RebaseContinue => self.suspend(svec(&["rebase", "--continue"])),
            Action::RebaseSkip => self.suspend(svec(&["rebase", "--skip"])),
            Action::RebaseAbort => self.write(svec(&["rebase", "--abort"])),

            Action::ApplyStash => {
                let i = self.selected[4];
                if i < self.repo.stashes.len() {
                    self.write(svec(&["stash", "apply", &format!("stash@{{{i}}}")]));
                }
            }
            Action::PopStash => {
                let i = self.selected[4];
                if i < self.repo.stashes.len() {
                    self.write(svec(&["stash", "pop", &format!("stash@{{{i}}}")]));
                }
            }
            Action::DropStash => {
                let i = self.selected[4];
                if i < self.repo.stashes.len() {
                    self.mode = Mode::Confirm {
                        prompt: format!("drop stash@{{{i}}}?"),
                        action: ConfirmAction::DropStash(i),
                    };
                }
            }
        }
    }

    fn apply_resp(&mut self, resp: Resp) {
        match resp {
            Resp::Status(files) => {
                self.repo.files = files;
                self.have_baseline = true;
                self.rebuild_tree();
            }
            // Only the paths that were looked at may change. A path that
            // was looked at and came back with nothing is clean now.
            Resp::StatusPaths { scanned, files } => {
                self.repo.files.retain(|f| !scanned.iter().any(|s| under(&f.path, s)));
                self.repo.files.extend(files);
                self.repo.files.sort_by(|a, b| a.path.cmp(&b.path));
                self.rebuild_tree();
            }
            Resp::Branches { current, entries } => {
                self.repo.head = current;
                self.repo.branches = entries;
                self.clamp(2);
            }
            Resp::Stashes(stashes) => {
                self.repo.stashes = stashes;
                self.clamp(4);
            }
            Resp::LogChunk { entries, done } => {
                self.repo.commits.extend(entries);
                self.repo.log_done = done;
                self.log_inflight = false;
                self.clamp(3);
            }
            // HEAD moved, thus the old list is wrong.
            Resp::LogReplace { entries, done } => {
                self.repo.commits = entries;
                self.repo.log_done = done;
                self.log_inflight = false;
                self.clamp(3);
            }
            // Ignore a diff for an old selection. Only the last request counts.
            Resp::Diff { seq, text, staged } => {
                if seq == self.diff_seq {
                    // Both diffs share one pane, thus the scroll counts the
                    // lines of both and the two header rows.
                    let total = text.lines().count() + staged.lines().count() + 2;
                    self.diff_lines = total.min(u16::MAX as usize) as u16;
                    self.repo.diff = text;
                    self.repo.diff_staged = staged;
                    self.diff_scroll = 0;
                }
            }
            Resp::WriteDone { ok, cmd, output, ms } => {
                // The command log holds the result and the output. The bar
                // keeps its key hints, thus a command never hides them.
                if let Some(i) = self.running.iter().position(|c| *c == cmd) {
                    self.running.remove(i);
                }
                // A checkout fails when another worktree holds the branch.
                // Offer to go to that worktree instead.
                if !ok && let Some(path) = worktree_in_use(&output) {
                    self.mode = Mode::Confirm {
                        prompt: format!("that branch is checked out at {path}. go there?"),
                        action: ConfirmAction::GoToWorktree(path),
                    };
                }
                // A push fails when the branch has no upstream. Offer to
                // make one, which is what the user wants nearly every time.
                if !ok
                    && output.iter().any(|l| l.contains("has no upstream branch"))
                    && let Some(head) = self.repo.head.clone()
                {
                    self.mode = Mode::Confirm {
                        prompt: format!("{head} has no upstream. push it to origin and follow it?"),
                        action: ConfirmAction::RunAll(vec![svec(&["push", "-u", "origin", &head])]),
                    };
                }
                // The fixup commit is there now, thus the rebase can fold
                // it in. Git makes the todo list itself, so the sequence
                // editor only has to accept it.
                if let Some(id) = self.pending_fixup.take()
                    && cmd.contains("--fixup=")
                    && ok
                {
                    self.pending_suspend = Some((
                        svec(&["rebase", "--autosquash", "--autostash", &format!("{id}^")]),
                        vec![("GIT_SEQUENCE_EDITOR".into(), "true".into())],
                    ));
                }
                // The staging is done, thus the commit window can open.
                if self.pending_commit_window && cmd.contains("add -A") {
                    self.pending_commit_window = false;
                    if ok {
                        self.open_commit_window();
                    }
                }
                // A worktree command changes the list, thus open it again
                // with the new content.
                let was_worktree = cmd.contains("worktree");
                // Show a failure that has no other answer. A window that
                // offers a fix is better, thus it comes first. A window the
                // user opened must not go away under their hands, thus the
                // log alone carries the failure then.
                if !ok && matches!(self.mode, Mode::Normal) {
                    self.mode = Mode::Error { cmd: cmd.clone(), output: output.clone() };
                }
                // A command that cannot change a file needs no scan of the
                // work tree. That scan is the costly part on a repository
                // with many files.
                let files = touches_files(&cmd);
                self.log_cmd(ok, cmd, ms, output);
                if ok {
                    self.refresh(files);
                    if was_worktree && let Some(git) = &self.git {
                        git.send(Req::Worktrees);
                    }
                }
            }
            // The reword window opens when the old message arrives.
            Resp::Message { text, index } => {
                let (summary, body) = match text.split_once('\n') {
                    Some((s, b)) => (s.to_string(), b.trim_start_matches('\n').to_string()),
                    None => (text, String::new()),
                };
                self.mode = Mode::CommitMsg {
                    summary,
                    body,
                    on_body: false,
                    purpose: CommitPurpose::Reword(index),
                };
            }
            Resp::Sync { ahead, behind, unpushed, upstream } => {
                self.repo.ahead = ahead;
                self.repo.behind = behind;
                self.repo.unpushed = unpushed;
                self.repo.upstream = upstream;
            }
            Resp::Worktrees(list) => self.mode = Mode::Worktrees { list, cursor: 0 },
            Resp::Reflog(list) => self.mode = Mode::Reflog { list, cursor: 0 },
            // A command the program started on its own. It writes to the
            // log, and it never takes the screen away from you.
            Resp::Background { ok, cmd, output, ms } => self.log_cmd(ok, cmd, ms, output),
            Resp::Tags(map) => self.repo.tags = map,
            Resp::Blame { path, lines } => {
                if lines.is_empty() {
                    self.message = "no blame for that file".into();
                    self.message_ok = false;
                } else {
                    self.mode = Mode::Blame { path, lines, cursor: 0 };
                }
            }
            Resp::Submodules(list) => {
                if list.is_empty() {
                    self.message = "this repository has no submodules".into();
                    self.message_ok = true;
                } else {
                    self.mode = Mode::Submodules { list, cursor: 0 };
                }
            }
        }
    }

    // Keep at least one line of the diff in view.
    fn scroll_diff(&mut self, delta: i16) {
        let last = self.diff_lines.saturating_sub(1);
        self.diff_scroll = self.diff_scroll.saturating_add_signed(delta).min(last);
    }

    fn clamp(&mut self, panel: usize) {
        let len = self.panel_len(panel);
        self.selected[panel] = self.selected[panel].min(len.saturating_sub(1));
    }

    fn refresh_all(&mut self) {
        self.refresh(true);
    }

    /// Read the repository again. `files` says whether to scan the work
    /// tree, which is the costly part on a repository with many files.
    fn refresh(&mut self, files: bool) {
        let Some(git) = &self.git else { return };
        if files {
            git.send(Req::Status);
        }
        for req in [Req::Branches, Req::Stashes, Req::Sync, Req::Tags] {
            git.send(req);
        }
        // The log thread walks again only when HEAD moved. A stage or a
        // fetch keeps the list that is already in memory.
        git.send(Req::LogRefresh { count: LOG_CHUNK });
        // Force a new diff request for the current selection.
        self.diff_target = None;
        let dir = self.git.as_ref().map(|g| g.git_dir.clone());
        self.rebase = dir.as_deref().and_then(rebase::detect);
        self.repo.bisecting = dir.as_deref().is_some_and(rebase::bisecting);
        // The split ends with the rebase.
        if self.rebase.is_none() {
            self.splitting = false;
        }
    }

    /// Send the requests that the new state makes necessary. The main loop
    /// calls this one time after each message burst. Thus a fast scroll makes
    /// one diff request, not one for each step.
    fn flush_requests(&mut self) {
        let Some(git) = &self.git else { return };

        // Load more commits before the selection comes near the loaded end.
        let near_end = self.selected[3] + LOG_CHUNK / 2 >= self.repo.commits.len();
        if self.focus == 3 && near_end && !self.repo.log_done && !self.log_inflight {
            git.send(Req::LogChunk { count: LOG_CHUNK });
            self.log_inflight = true;
        }

        let target = match self.focus {
            1 => self.selected_file().map(|f| DiffTarget::WorktreeFile {
                path: f.path.clone(),
                untracked: f.work == '?',
            }),
            // With a commit marked, the pane shows what lies between them.
            3 => self.repo.commits.get(self.selected[3]).map(|c| match &self.repo.compare {
                Some(from) if *from != c.id_str() => {
                    DiffTarget::Range { from: from.clone(), to: c.id_str().to_string() }
                }
                _ => DiffTarget::Commit(c.id_str().to_string()),
            }),
            // A stash shows its own changes, thus you can look before you
            // put them back.
            4 => (self.selected[4] < self.repo.stashes.len())
                .then(|| DiffTarget::Stash(self.selected[4])),
            _ => None,
        };
        if let Some(want) = target
            && Some(&want) != self.diff_target.as_ref()
        {
            self.diff_seq += 1;
            self.diff_target = Some(want.clone());
            git.send(Req::Diff { seq: self.diff_seq, target: want });
        }
    }
}

// True when the point sits inside the rectangle.
fn contains(r: ratatui::layout::Rect, x: u16, y: u16) -> bool {
    x >= r.x && x < r.x + r.width && y >= r.y && y < r.y + r.height
}

fn svec(args: &[&str]) -> Vec<String> {
    args.iter().map(|s| s.to_string()).collect()
}

/// True when `path` is the named path or sits under it as a directory.
fn under(path: &str, name: &str) -> bool {
    path == name || path.strip_prefix(name).is_some_and(|r| r.starts_with('/'))
}

/// True when a command can change a file in the work tree or the index.
/// Only a command that certainly cannot is left out, thus a wrong guess
/// never hides a change from you.
fn touches_files(cmd: &str) -> bool {
    // The text looks like "git tag -a v1 -m v1 abc1234".
    let Some(verb) = cmd.strip_prefix("git ").and_then(|r| r.split_whitespace().next()) else {
        // A shell command or a copy can do anything.
        return true;
    };
    !matches!(verb, "tag" | "push" | "fetch" | "branch" | "remote" | "config" | "reflog")
}

/// Find the worktree path in a git error. Git says:
///   fatal: 'x' is already used by worktree at '/path/to/tree'
fn worktree_in_use(output: &[String]) -> Option<String> {
    for line in output {
        if let Some((_, rest)) = line.split_once("is already used by worktree at ") {
            let path = rest.trim().trim_matches('\'').trim_matches('"');
            if !path.is_empty() {
                return Some(path.to_string());
            }
        }
    }
    None
}

/// The git arguments for a bisect key. None means the key does nothing.
/// Before a bisect runs, only the good and the bad key can start one.
fn bisect_command(bisecting: bool, action: &Action, id: Option<&str>) -> Option<Vec<String>> {
    Some(match (action, bisecting) {
        (Action::BisectBad, true) => svec(&["bisect", "bad"]),
        (Action::BisectGood, true) => svec(&["bisect", "good"]),
        (Action::BisectSkip, true) => svec(&["bisect", "skip"]),
        (Action::BisectReset, true) => svec(&["bisect", "reset"]),
        // The bad commit starts the bisect. Git then needs a good one.
        (Action::BisectBad, false) => svec(&["bisect", "start", id?]),
        (Action::BisectGood, false) => svec(&["bisect", "good", id?]),
        _ => return None,
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use ratatui::Terminal;
    use ratatui::backend::TestBackend;

    // Make an application with test data. The tests must not touch a real
    // repository.
    fn demo() -> App {
        let mut app = App::new();
        app.repo.head = Some("main".into());
        app.repo.ahead = 2;
        app.repo.files =
            [('M', 'M', "src/main.rs"), (' ', 'A', "src/app.rs"), (' ', '?', "notes.txt")]
                .into_iter()
                .map(|(index, work, path)| FileEntry { index, work, path: path.into() })
                .collect();
        app.repo.unpushed = ["0a0c000".to_string(), "0a0c001".to_string()].into();
        app.repo.branches = [
            ("main", true, 2, 0, "2h"),
            ("feature/ui", false, 1, 3, "1d"),
            ("old/thing", false, 0, 0, "3w"),
        ]
        .into_iter()
        .map(|(name, current, ahead, behind, age)| BranchEntry {
            name: name.into(),
            current,
            ahead,
            behind,
            gone: false,
            remote: false,
            age: age.into(),
        })
        .collect();
        app.repo.stashes = vec!["stash@{0}: WIP on main".into()];
        app.repo.commits = (0..100_000)
            .map(|i| {
                let mut id = [b'0'; 7];
                id.copy_from_slice(format!("{:07x}", 0xa0c000 + i).as_bytes());
                let graph = ["", "◉─╮", "● │", "│ ●", "●─╯"][i % 5];
                CommitEntry {
                    id,
                    graph: graph.into(),
                    subject: format!("fake: commit subject #{i}").into(),
                    author: "Test Author".into(),
                    time: 1_753_000_000 + i as u32,
                }
            })
            .collect();
        app.repo.diff = "diff --git a/src/main.rs b/src/main.rs\n+added line\n-removed line".into();
        app.repo.diff_staged = "diff --git a/src/main.rs b/src/main.rs\n+staged line".into();
        app.rebuild_tree();
        app
    }

    fn draw(app: &App, width: u16, height: u16) -> Terminal<TestBackend> {
        let mut terminal = Terminal::new(TestBackend::new(width, height)).unwrap();
        terminal.draw(|f| ui::render(f, app)).unwrap();
        terminal
    }

    #[test]
    fn layout_80x24() {
        insta::assert_snapshot!(draw(&demo(), 80, 24).backend());
    }

    #[test]
    fn layout_200x50() {
        insta::assert_snapshot!(draw(&demo(), 200, 50).backend());
    }

    #[test]
    fn commits_panel_scrolled_deep() {
        // Put the selection far below one screen. This shows that the list
        // renders only the rows in view.
        let mut app = demo();
        app.focus = 3;
        app.selected[3] = 99_999;
        insta::assert_snapshot!(draw(&app, 80, 24).backend());
    }

    #[test]
    fn rebase_editor() {
        let mut app = demo();
        app.focus = 3;
        app.selected[3] = 3;
        app.start_rebase();
        // Give the four commits different actions.
        if let Mode::Rebase { items, cursor, .. } = &mut app.mode {
            items[1].action = TodoAction::Squash;
            items[2].action = TodoAction::Drop;
            items[3].action = TodoAction::Reword;
            *cursor = 2;
        } else {
            panic!("the rebase editor did not open");
        }
        insta::assert_snapshot!(draw(&app, 100, 24).backend());
    }

    #[test]
    fn rebase_todo_matches_editor_order() {
        let mut app = demo();
        app.selected[3] = 2;
        app.start_rebase();
        let Mode::Rebase { items, base, .. } = &app.mode else { panic!("no editor") };
        // The base is the parent of the oldest commit in the list.
        assert_eq!(base.as_deref(), Some("0a0c002^"));
        // The file starts with the oldest commit.
        assert!(rebase::serialize(items).starts_with("pick 0a0c002"));
    }

    #[test]
    fn commit_window() {
        let mut app = demo();
        app.mode = Mode::CommitMsg {
            summary: "feat: add the commit window".into(),
            body: "The window has a summary line and a body.".into(),
            on_body: true,
            purpose: CommitPurpose::New,
        };
        insta::assert_snapshot!(draw(&app, 100, 30).backend());
    }

    #[test]
    fn reword_window() {
        let mut app = demo();
        app.mode = Mode::CommitMsg {
            summary: "fix: the old summary".into(),
            body: String::new(),
            on_body: false,
            purpose: CommitPurpose::Reword(0),
        };
        insta::assert_snapshot!(draw(&app, 100, 30).backend());
    }

    // A commit with nothing to commit must say so, not open a window that
    // cannot work.
    #[test]
    fn commit_with_no_changes_reports_it() {
        let mut app = demo();
        app.repo.files.clear();
        app.rebuild_tree();
        app.apply(Action::CommitPrompt);
        match &app.mode {
            Mode::Error { output, .. } => assert!(output[0].contains("nothing to commit")),
            _ => panic!("expected the failure window"),
        }
    }

    // With changes but nothing staged, offer to stage them all.
    #[test]
    fn commit_with_nothing_staged_offers_to_stage() {
        let mut app = demo();
        for f in &mut app.repo.files {
            f.index = ' ';
        }
        app.apply(Action::CommitPrompt);
        assert!(
            matches!(&app.mode, Mode::Confirm { action: ConfirmAction::StageAllThenCommit, .. }),
            "expected the offer to stage everything"
        );
        // Saying yes stages first. The window waits for that to finish.
        app.handle_key(ratatui::crossterm::event::KeyEvent::new(
            KeyCode::Char('y'),
            ratatui::crossterm::event::KeyModifiers::NONE,
        ));
        assert!(app.pending_commit_window);
        assert!(matches!(app.mode, Mode::Normal), "the window is not open yet");
        app.apply_resp(Resp::WriteDone {
            ok: true,
            cmd: "git add -A".into(),
            output: Vec::new(),
            ms: 4,
        });
        assert!(matches!(app.mode, Mode::CommitMsg { .. }), "now it opens");
    }

    // With something staged, go straight to the window.
    #[test]
    fn commit_with_staged_files_opens_the_window() {
        let mut app = demo();
        assert!(app.repo.files.iter().any(|f| f.staged()));
        app.apply(Action::CommitPrompt);
        assert!(matches!(app.mode, Mode::CommitMsg { .. }));
    }

    #[test]
    fn empty_summary_is_refused() {
        let mut app = demo();
        app.submit_commit(String::new(), "body only".into(), CommitPurpose::New);
        assert!(!app.message_ok);
        // Nothing went to git.
        assert!(app.cmd_log.is_empty());
    }

    #[test]
    fn the_current_branch_cannot_be_deleted() {
        let mut app = demo();
        app.focus = 2;
        app.selected[2] = 0; // The demo puts the current branch first.
        assert!(app.repo.branches[0].current);
        app.apply(Action::DeleteBranch { force: false });
        assert!(!app.message_ok);
        assert!(matches!(app.mode, Mode::Normal), "no confirm window opens");
    }

    #[test]
    fn command_log_keeps_the_result_and_the_time() {
        let mut app = demo();
        app.apply_resp(Resp::WriteDone {
            ok: false,
            cmd: "git branch -d old".into(),
            output: vec!["error: the branch is not merged".into()],
            ms: 12,
        });
        assert_eq!(app.cmd_log.len(), 1);
        assert!(!app.cmd_log[0].ok);
        assert_eq!(app.cmd_log[0].ms, 12);
        // The reason lives in the log, not on the bar.
        assert_eq!(app.cmd_log[0].output, ["error: the branch is not merged"]);
        assert!(app.message.is_empty(), "no command may hide the key hints");
        app.apply_resp(Resp::WriteDone {
            ok: true,
            cmd: "git add -A".into(),
            output: Vec::new(),
            ms: 3,
        });
        assert!(app.message.is_empty());
        assert!(app.cmd_log[1].output.is_empty());
    }

    #[test]
    fn hunk_view_marks_lines() {
        let mut app = demo();
        app.mode = Mode::Hunks {
            path: "src/app.rs".into(),
            header: "diff --git a/src/app.rs b/src/app.rs\n".into(),
            hunks: vec!["@@ -1,2 +1,3 @@\n keep\n-old line\n+new line\n".into()],
            cursor: 0,
            line: 1,
            picked: vec![1],
        };
        insta::assert_snapshot!(draw(&app, 100, 24).backend());
    }

    #[test]
    fn worktree_list() {
        let mut app = demo();
        app.mode = Mode::Worktrees {
            list: vec![
                WorktreeEntry {
                    path: "/home/max/lazier".into(),
                    branch: "main".into(),
                    current: true,
                    main: true,
                    locked: false,
                    prunable: false,
                },
                WorktreeEntry {
                    path: "/home/max/lazier-fix".into(),
                    branch: "fix/x".into(),
                    current: false,
                    main: false,
                    locked: false,
                    prunable: false,
                },
                WorktreeEntry {
                    path: "/home/max/lazier-old".into(),
                    branch: "old/thing".into(),
                    current: false,
                    main: false,
                    locked: true,
                    prunable: true,
                },
            ],
            cursor: 1,
        };
        insta::assert_snapshot!(draw(&app, 100, 24).backend());
    }

    // Before a bisect runs, skip and reset must do nothing. The bad key
    // starts the bisect. During a bisect the keys need no commit id.
    #[test]
    fn bisect_keys_need_a_running_bisect() {
        let id = Some("abc1234");
        assert_eq!(bisect_command(false, &Action::BisectSkip, id), None);
        assert_eq!(bisect_command(false, &Action::BisectReset, id), None);
        assert_eq!(
            bisect_command(false, &Action::BisectBad, id),
            Some(svec(&["bisect", "start", "abc1234"]))
        );
        assert_eq!(bisect_command(true, &Action::BisectBad, None), Some(svec(&["bisect", "bad"])));
        assert_eq!(
            bisect_command(true, &Action::BisectReset, None),
            Some(svec(&["bisect", "reset"]))
        );
        // With no commit in the list, a bisect cannot start.
        assert_eq!(bisect_command(false, &Action::BisectBad, None), None);
    }

    // A click moves the focus to the panel under the pointer, and puts the
    // selection on the row that was clicked.
    #[test]
    fn a_click_moves_the_focus_and_the_selection() {
        use ratatui::crossterm::event::{KeyModifiers, MouseButton, MouseEvent, MouseEventKind};
        let mut app = demo();
        app.area = ratatui::layout::Rect::new(0, 0, 80, 30);
        let p = ui::panes(app.area, app.show_log);
        let click = |x, y| MouseEvent {
            kind: MouseEventKind::Down(MouseButton::Left),
            column: x,
            row: y,
            modifiers: KeyModifiers::NONE,
        };
        // The branches panel is the third box on the left.
        let b = p.left[2];
        app.handle_mouse(click(b.x + 4, b.y + 1));
        assert_eq!(app.focus, 2, "the click must move the focus");
        assert_eq!(app.selected[2], 0, "the first row is under that point");
        app.handle_mouse(click(b.x + 4, b.y + 3));
        assert_eq!(app.selected[2], 2, "the third row is under that point");

        // A click in the diff pane moves the focus there.
        app.handle_mouse(click(p.diff.x + 2, p.diff.y + 2));
        assert_eq!(app.focus, 5);
    }

    #[test]
    fn the_wheel_moves_the_selection() {
        use ratatui::crossterm::event::{KeyModifiers, MouseEvent, MouseEventKind};
        let mut app = demo();
        app.area = ratatui::layout::Rect::new(0, 0, 80, 30);
        let p = ui::panes(app.area, app.show_log);
        let wheel = |kind, y| MouseEvent {
            kind,
            column: p.left[2].x + 2,
            row: y,
            modifiers: KeyModifiers::NONE,
        };
        app.handle_mouse(wheel(MouseEventKind::ScrollDown, p.left[2].y + 1));
        assert_eq!((app.focus, app.selected[2]), (2, 1));
        app.handle_mouse(wheel(MouseEventKind::ScrollUp, p.left[2].y + 1));
        assert_eq!(app.selected[2], 0);
    }

    /// The key list is taller than any usual window. The wheel and the keys
    /// must both move it, and neither may go past the last row.
    #[test]
    fn the_key_list_scrolls_and_stops_at_the_end() {
        use ratatui::crossterm::event::{KeyEvent, KeyModifiers, MouseEvent, MouseEventKind};
        let mut app = demo();
        app.area = ratatui::layout::Rect::new(0, 0, 100, 34);
        let last = ui::help_max_scroll(app.area);
        assert!(last > 0, "the list must be taller than the window");

        app.apply(Action::Help);
        // Far more presses than rows. The scroll stops at the last row.
        for _ in 0..500 {
            app.handle_key(KeyEvent::new(KeyCode::Char('j'), KeyModifiers::NONE));
        }
        let Mode::Help { scroll } = app.mode else { panic!("the help must stay open") };
        assert_eq!(scroll, last, "j must stop at the last row, and not go past it");

        // One press back must move at once, thus the end never feels stuck.
        app.handle_key(KeyEvent::new(KeyCode::Char('k'), KeyModifiers::NONE));
        let Mode::Help { scroll } = app.mode else { panic!("the help must stay open") };
        assert_eq!(scroll, last - 1);

        // The wheel moves it too.
        let wheel = |kind| MouseEvent { kind, column: 10, row: 10, modifiers: KeyModifiers::NONE };
        app.handle_mouse(wheel(MouseEventKind::ScrollUp));
        let Mode::Help { scroll } = app.mode else { panic!("the help must stay open") };
        assert_eq!(scroll, last - 4);
        app.handle_mouse(wheel(MouseEventKind::ScrollDown));
        let Mode::Help { scroll } = app.mode else { panic!("the help must stay open") };
        assert_eq!(scroll, last - 1);

        // Any other key closes it.
        app.handle_key(KeyEvent::new(KeyCode::Char('x'), KeyModifiers::NONE));
        assert!(matches!(app.mode, Mode::Normal));
    }

    // The spinner turns only while a command runs, and it repeats.
    #[test]
    fn the_spinner_turns_only_when_busy() {
        let mut app = demo();
        assert_eq!(app.spinner(), None, "nothing runs, thus no spinner");
        app.apply(Action::Push);
        let first = app.spinner().expect("a push must show a spinner");
        app.tick += 1;
        assert_ne!(app.spinner(), Some(first), "the next tick shows another frame");
        app.tick += 9;
        assert_eq!(app.spinner(), Some(first), "ten frames make a full turn");
        app.apply_resp(Resp::WriteDone {
            ok: true,
            cmd: "git push".into(),
            output: Vec::new(),
            ms: 12,
        });
        assert_eq!(app.spinner(), None, "the spinner stops with the command");
    }

    #[test]
    fn the_branch_row_shows_the_spinner() {
        let mut app = demo();
        app.focus = 2;
        app.apply(Action::Push);
        insta::assert_snapshot!(draw(&app, 80, 24).backend());
    }

    // A network command shows in the bar while it runs, then goes away
    // when the result arrives.
    #[test]
    fn a_running_command_shows_and_then_clears() {
        let mut app = demo();
        app.apply(Action::Push);
        assert_eq!(app.running, ["git push"]);
        app.apply_resp(Resp::WriteDone {
            ok: true,
            cmd: "git push".into(),
            output: vec!["To github.com:max/lazier.git".into()],
            ms: 900,
        });
        assert!(app.running.is_empty());
        assert_eq!(app.cmd_log[0].output.len(), 1);
    }

    #[test]
    fn a_busy_branch_offers_its_worktree() {
        let mut app = demo();
        app.apply_resp(Resp::WriteDone {
            ok: false,
            cmd: "git checkout max/pratt".into(),
            output: vec![
                "fatal: 'max/pratt' is already used by worktree at '/home/max/pratt'".into(),
            ],
            ms: 31,
        });
        match &app.mode {
            Mode::Confirm { action: ConfirmAction::GoToWorktree(p), .. } => {
                assert_eq!(p, "/home/max/pratt")
            }
            _ => panic!("expected the offer to go to the worktree"),
        }
    }

    // A long branch name must not push the counts off the panel.
    #[test]
    fn long_branch_names_keep_their_counts() {
        let mut app = demo();
        app.focus = 2;
        app.repo.branches = [
            ("max/macro-warehouse-selection-and-more", true, 5u32, 0u32),
            ("max/pratt-parser-cleanup-with-a-very-long-tail", false, 12, 3),
            ("main", false, 0, 0),
        ]
        .into_iter()
        .map(|(name, current, ahead, behind)| BranchEntry {
            name: name.into(),
            current,
            ahead,
            behind,
            gone: false,
            remote: false,
            age: "2d".into(),
        })
        .collect();
        insta::assert_snapshot!(draw(&app, 80, 24).backend());
    }

    #[test]
    fn reset_window() {
        let mut app = demo();
        app.mode =
            Mode::Reset { target: "0a0c003".into(), subject: "fake: commit subject #3".into() };
        insta::assert_snapshot!(draw(&app, 100, 30).backend());
    }

    #[test]
    fn reflog_window() {
        let mut app = demo();
        app.mode = Mode::Reflog {
            list: [
                ("a1b2c3d", "HEAD@{0}", "commit: feat: add the thing"),
                ("d4e5f6a", "HEAD@{1}", "rebase (finish): returning to refs/heads/main"),
                ("9876543", "HEAD@{2}", "checkout: moving from main to feature/x"),
            ]
            .into_iter()
            .map(|(id, at, what)| ReflogEntry { id: id.into(), at: at.into(), what: what.into() })
            .collect(),
            cursor: 1,
        };
        insta::assert_snapshot!(draw(&app, 100, 30).backend());
    }

    // A branch on a remote needs a local branch that follows it.
    #[test]
    fn a_remote_branch_is_followed_not_switched_to() {
        let mut app = demo();
        app.focus = 2;
        app.repo.branches.push(BranchEntry {
            name: "origin/theirs".into(),
            current: false,
            ahead: 0,
            behind: 0,
            gone: false,
            age: "1d".into(),
            remote: true,
        });
        app.selected[2] = app.repo.branches.len() - 1;
        app.apply(Action::Checkout);
        // No git worker runs in a test, thus check that no message of
        // refusal appeared and the mode stayed normal.
        assert!(app.message.is_empty());
        assert!(matches!(app.mode, Mode::Normal));
    }

    // Marking files makes the next action work on all of them.
    #[test]
    fn marks_drive_the_next_action() {
        let mut app = demo();
        app.focus = 1;
        // Put the cursor on the first file row of the tree.
        app.selected[1] = app.tree.iter().position(|r| r.file.is_some()).unwrap();
        app.apply(Action::ToggleMark);
        assert_eq!(app.marked.len(), 1, "one file is marked");
        // Walk to the next file row and mark that one too.
        while app.selected_row().is_some_and(|r| r.file.is_none()) {
            app.apply(Action::Down);
        }
        app.apply(Action::ToggleMark);
        assert_eq!(app.marked.len(), 2);
        assert_eq!(app.action_paths().len(), 2);
        assert_eq!(app.action_label(), "2 files");
        // Escape drops the marks before it touches the search.
        app.repo.filter = Some("x".into());
        app.apply(Action::ClearFilter);
        assert!(app.marked.is_empty());
        assert_eq!(app.repo.filter.as_deref(), Some("x"), "the search is still set");
        app.apply(Action::ClearFilter);
        assert!(app.repo.filter.is_none());
    }

    // A directory row marks every file under it in one key.
    #[test]
    fn a_directory_marks_all_of_its_files() {
        let mut app = demo();
        app.focus = 1;
        let src = app.tree.iter().position(|r| r.dir.as_deref() == Some("src")).unwrap();
        app.selected[1] = src;
        app.apply(Action::ToggleMark);
        assert_eq!(app.marked.len(), 2, "both files under src are marked");
        app.selected[1] = src;
        app.apply(Action::ToggleMark);
        assert!(app.marked.is_empty(), "the same key drops them again");
    }

    #[test]
    fn with_no_marks_the_action_uses_the_row() {
        let mut app = demo();
        app.focus = 1;
        app.selected[1] = app.tree.iter().position(|r| r.file.is_some()).unwrap();
        assert_eq!(app.action_paths().len(), 1);
    }

    #[test]
    fn ignore_window() {
        let mut app = demo();
        app.mode = Mode::Ignore { pattern: "/notes.txt".into(), tracked: false };
        insta::assert_snapshot!(draw(&app, 100, 30).backend());
    }

    #[test]
    fn ignore_window_warns_for_a_tracked_file() {
        let mut app = demo();
        app.mode = Mode::Ignore { pattern: "/src/main.rs".into(), tracked: true };
        insta::assert_snapshot!(draw(&app, 100, 30).backend());
    }

    // A file that git does not track needs a rule that starts at the root,
    // and a directory rule needs a slash at the end.
    #[test]
    fn ignore_makes_the_right_pattern() {
        let mut app = demo();
        app.focus = 1;
        // Row zero is the root. It has no useful rule.
        app.selected[1] = 0;
        app.apply(Action::IgnorePrompt);
        assert!(matches!(app.mode, Mode::Normal), "the root opens no window");
        // Find the untracked file in the tree.
        let i = app
            .tree
            .iter()
            .position(|r| r.file.is_some_and(|f| app.repo.files[f].path == "notes.txt"))
            .unwrap();
        app.selected[1] = i;
        app.apply(Action::IgnorePrompt);
        match &app.mode {
            Mode::Ignore { pattern, tracked } => {
                assert_eq!(pattern, "/notes.txt");
                assert!(!tracked);
            }
            _ => panic!("expected the ignore window"),
        }
    }

    #[test]
    fn new_worktree_window() {
        let mut app = demo();
        app.mode = Mode::NewWorktree {
            branch: "feature/parser".into(),
            path: String::new(),
            on_path: false,
            path_edited: false,
        };
        insta::assert_snapshot!(draw(&app, 100, 30).backend());
    }

    // An existing branch must not get the -b flag, or git refuses.
    #[test]
    fn a_worktree_uses_an_existing_branch_as_it_is() {
        let mut app = demo();
        assert!(app.repo.branches.iter().any(|b| b.name == "feature/ui"));
        app.add_worktree("feature/ui".into(), "/tmp/wt".into());
        app.add_worktree("brand/new".into(), "/tmp/wt2".into());
        // No git worker runs in a test, thus check through the commands
        // that the messages would carry.
        assert!(app.message.is_empty(), "both names are good");
    }

    #[test]
    fn a_worktree_needs_a_branch_name() {
        let mut app = demo();
        app.add_worktree(String::new(), String::new());
        assert!(!app.message_ok);
    }

    #[test]
    fn confirm_window() {
        let mut app = demo();
        app.mode = Mode::Confirm {
            prompt: "that branch is checked out at /Users/max/dbt/fs-warehouses. go there?".into(),
            action: ConfirmAction::GoToWorktree("/Users/max/dbt/fs-warehouses".into()),
        };
        insta::assert_snapshot!(draw(&app, 100, 30).backend());
    }

    // A failure the user cannot answer opens a window, because the command
    // log can be closed and a silent failure is the worst kind.
    #[test]
    fn a_failure_opens_a_window() {
        let mut app = demo();
        app.apply_resp(Resp::WriteDone {
            ok: false,
            cmd: "git checkout nope".into(),
            output: vec!["error: pathspec 'nope' did not match".into()],
            ms: 5,
        });
        match &app.mode {
            Mode::Error { cmd, output } => {
                assert_eq!(cmd, "git checkout nope");
                assert_eq!(output.len(), 1);
            }
            _ => panic!("expected the failure window"),
        }
        // The log keeps the record as well.
        assert_eq!(app.cmd_log.len(), 1);
        assert!(!app.cmd_log[0].ok);
    }

    // A window that offers a way out is better than one that only reports.
    #[test]
    fn an_offer_wins_over_the_failure_window() {
        let mut app = demo();
        app.apply_resp(Resp::WriteDone {
            ok: false,
            cmd: "git push".into(),
            output: vec!["fatal: The current branch main has no upstream branch".into()],
            ms: 5,
        });
        assert!(matches!(&app.mode, Mode::Confirm { .. }), "the upstream offer must come first");
    }

    // A failure of a command that runs in the background must not take a
    // window away from the user while they type.
    #[test]
    fn a_failure_never_closes_an_open_window() {
        let mut app = demo();
        app.mode = Mode::CommitMsg {
            summary: "feat: half typed".into(),
            body: String::new(),
            on_body: false,
            purpose: CommitPurpose::New,
        };
        app.apply_resp(Resp::WriteDone {
            ok: false,
            cmd: "git fetch".into(),
            output: vec!["fatal: could not read from remote".into()],
            ms: 5,
        });
        match &app.mode {
            Mode::CommitMsg { summary, .. } => assert_eq!(summary, "feat: half typed"),
            _ => panic!("the commit window must stay"),
        }
        assert!(!app.cmd_log[0].ok, "the log still holds the failure");
    }

    // A checkout of the branch you are on reads every file for nothing.
    #[test]
    fn no_checkout_of_the_branch_you_are_on() {
        let mut app = demo();
        app.focus = 2;
        app.selected[2] = 0;
        assert!(app.repo.branches[0].current);
        app.apply(Action::Checkout);
        assert!(app.running.is_empty());
        assert!(app.message.contains("you are already on"), "{}", app.message);
        assert!(app.message_ok, "this is not an error");
    }

    // A command that cannot change a file must not start a scan of the
    // work tree, and every other command must.
    #[test]
    fn only_the_right_commands_scan_the_work_tree() {
        for cmd in ["git tag -a v1 -m v1", "git push", "git fetch", "git branch -d old"] {
            assert!(!touches_files(cmd), "{cmd} should not scan");
        }
        for cmd in [
            "git add -A",
            "git checkout main",
            "git reset --hard HEAD",
            "git stash push",
            "git commit -m x",
            "git rebase --continue",
            "git clean -fd",
            ": rm -rf build",
            "absorb",
        ] {
            assert!(touches_files(cmd), "{cmd} should scan");
        }
    }

    // A scan of a few paths must change what is known about those paths
    // only, and must leave every other path as it was.
    #[test]
    fn a_partial_scan_touches_only_what_it_looked_at() {
        let mut app = demo();
        app.have_baseline = true;
        let mut before: Vec<String> = app.repo.files.iter().map(|f| f.path.clone()).collect();
        before.sort();
        assert!(before.contains(&"notes.txt".to_string()));
        // Look at one file and find it changed in another way.
        app.apply_resp(Resp::StatusPaths {
            scanned: vec!["src/main.rs".into()],
            files: vec![FileEntry { index: ' ', work: 'M', path: "src/main.rs".into() }],
        });
        let mut after: Vec<String> = app.repo.files.iter().map(|f| f.path.clone()).collect();
        after.sort();
        assert_eq!(before, after, "the set of files is the same");
        let m = app.repo.files.iter().find(|f| f.path == "src/main.rs").unwrap();
        assert_eq!((m.index, m.work), (' ', 'M'), "that one file changed");
    }

    // A path that was looked at and came back with nothing is clean now.
    #[test]
    fn a_partial_scan_removes_a_file_that_is_clean_again() {
        let mut app = demo();
        app.have_baseline = true;
        app.apply_resp(Resp::StatusPaths { scanned: vec!["notes.txt".into()], files: Vec::new() });
        assert!(!app.repo.files.iter().any(|f| f.path == "notes.txt"));
        assert!(app.repo.files.iter().any(|f| f.path == "src/main.rs"), "the rest stays");
    }

    // A directory name covers the files under it.
    #[test]
    fn a_partial_scan_of_a_directory_covers_its_files() {
        let mut app = demo();
        app.have_baseline = true;
        app.apply_resp(Resp::StatusPaths { scanned: vec!["src".into()], files: Vec::new() });
        assert!(!app.repo.files.iter().any(|f| f.path.starts_with("src/")));
        assert!(app.repo.files.iter().any(|f| f.path == "notes.txt"), "outside src it stays");
    }

    // Without a full scan first there is nothing to build on, thus a
    // change of the work tree must ask for the whole thing.
    #[test]
    fn no_partial_scan_before_the_first_full_one() {
        let mut app = demo();
        app.have_baseline = false;
        app.update(Msg::Dirty(Some(vec!["a.txt".into()])));
        // No git worker runs in a test. The point is that it did not panic
        // and did not mark a baseline it never had.
        assert!(!app.have_baseline);
    }

    #[test]
    fn under_matches_a_path_and_its_directory() {
        assert!(under("src/main.rs", "src"));
        assert!(under("src/main.rs", "src/main.rs"));
        // A name that only shares letters is not under it.
        assert!(!under("srcfile.rs", "src"));
        assert!(!under("other/main.rs", "src"));
    }

    #[test]
    fn the_current_branch_is_first() {
        let app = demo();
        assert!(app.repo.branches[0].current);
    }

    #[test]
    fn help_overlay() {
        let mut app = demo();
        app.mode = Mode::Help { scroll: 0 };
        insta::assert_snapshot!(draw(&app, 100, 30).backend());
    }

    #[test]
    fn zoomed_graph() {
        let mut app = demo();
        app.focus = 3;
        app.zoom = true;
        insta::assert_snapshot!(draw(&app, 80, 24).backend());
    }

    #[test]
    fn branch_prompt() {
        let mut app = demo();
        app.focus = 2;
        app.mode = Mode::Input {
            prompt: "new branch name",
            buffer: "feature/x".into(),
            purpose: InputPurpose::NewBranch,
        };
        insta::assert_snapshot!(draw(&app, 80, 24).backend());
    }

    #[test]
    fn navigation() {
        let mut app = demo();
        app.apply(Action::Down);
        assert_eq!(app.selected[1], 1);
        app.apply(Action::Up);
        app.apply(Action::Up); // The selection stays at zero.
        assert_eq!(app.selected[1], 0);
        app.apply(Action::FocusPanel(3));
        assert_eq!(app.focus, 3);
        app.apply(Action::NextPanel);
        app.apply(Action::NextPanel); // The focus reaches the diff pane.
        assert_eq!(app.focus, 5);
        app.apply(Action::NextPanel); // The focus wraps to panel 0.
        assert_eq!(app.focus, 0);
        app.apply(Action::PrevPanel);
        assert_eq!(app.focus, 5);
    }
}