1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
//! UI implementation.

use std::any::Any;
use std::borrow::Cow;
use std::cell::RefCell;
use std::cmp::min;
use std::collections::{BTreeMap, HashSet};
use std::fmt::Write;
use std::fmt::{Debug, Display};
use std::hash::Hash;
use std::path::Path;
use std::rc::Rc;
use std::{io, iter, mem, panic};

use crossterm::event::{
    DisableMouseCapture, EnableMouseCapture, KeyCode, KeyEvent, KeyEventKind, KeyModifiers,
    MouseButton, MouseEvent, MouseEventKind,
};
use crossterm::terminal::{
    disable_raw_mode, enable_raw_mode, is_raw_mode_enabled, EnterAlternateScreen,
    LeaveAlternateScreen,
};
use ratatui::backend::{Backend, TestBackend};
use ratatui::buffer::Buffer;
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::Span;
use ratatui::widgets::{Block, Borders, Clear, Paragraph};
use ratatui::{backend::CrosstermBackend, Terminal};
use tracing::warn;
use unicode_width::UnicodeWidthStr;

use crate::consts::ENV_VAR_DEBUG_UI;
use crate::render::{
    centered_rect, Component, DrawnRect, DrawnRects, Mask, Rect, RectSize, Viewport,
};
use crate::types::{ChangeType, Commit, RecordError, RecordState, Tristate};
use crate::util::{IsizeExt, UsizeExt};
use crate::{File, Section, SectionChangedLine};

const NUM_CONTEXT_LINES: usize = 3;

#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
struct FileKey {
    commit_idx: usize,
    file_idx: usize,
}

#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
struct SectionKey {
    commit_idx: usize,
    file_idx: usize,
    section_idx: usize,
}

#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
struct LineKey {
    commit_idx: usize,
    file_idx: usize,
    section_idx: usize,
    line_idx: usize,
}

#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
enum QuitDialogButtonId {
    Quit,
    GoBack,
}

#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
enum SelectionKey {
    None,
    File(FileKey),
    Section(SectionKey),
    Line(LineKey),
}

impl Default for SelectionKey {
    fn default() -> Self {
        Self::None
    }
}

/// A copy of the contents of the screen at a certain point in time.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct TestingScreenshot {
    contents: Rc<RefCell<Option<String>>>,
}

impl TestingScreenshot {
    fn set(&self, new_contents: String) {
        let Self { contents } = self;
        *contents.borrow_mut() = Some(new_contents);
    }

    /// Produce an `Event` which will record the screenshot when it's handled.
    pub fn event(&self) -> Event {
        Event::TakeScreenshot(self.clone())
    }
}

impl Display for TestingScreenshot {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let Self { contents } = self;
        match contents.borrow().as_ref() {
            Some(contents) => write!(f, "{contents}"),
            None => write!(f, "<this screenshot was never assigned>"),
        }
    }
}

#[allow(missing_docs)]
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum Event {
    None,
    QuitAccept,
    QuitCancel,
    QuitInterrupt,
    TakeScreenshot(TestingScreenshot),
    Redraw,
    EnsureSelectionInViewport,
    ScrollUp,
    ScrollDown,
    PageUp,
    PageDown,
    FocusPrev,
    FocusPrevPage,
    FocusNext,
    FocusNextPage,
    FocusInner,
    FocusOuter,
    ToggleItem,
    ToggleItemAndAdvance,
    ToggleAll,
    ToggleAllUniform,
    ExpandItem,
    ExpandAll,
    Click { row: usize, column: usize },
    ToggleCommitViewMode, // no key binding currently
    EditCommitMessage,
}

impl From<crossterm::event::Event> for Event {
    fn from(event: crossterm::event::Event) -> Self {
        use crossterm::event::Event;
        match event {
            Event::Key(KeyEvent {
                code: KeyCode::Char('q'),
                modifiers: KeyModifiers::NONE,
                kind: KeyEventKind::Press,
                state: _,
            }) => Self::QuitCancel,

            Event::Key(KeyEvent {
                code: KeyCode::Char('c'),
                modifiers: KeyModifiers::CONTROL,
                kind: KeyEventKind::Press,
                state: _,
            }) => Self::QuitInterrupt,

            Event::Key(KeyEvent {
                code: KeyCode::Char('c'),
                modifiers: KeyModifiers::NONE,
                kind: KeyEventKind::Press,
                state: _,
            }) => Self::QuitAccept,

            Event::Key(KeyEvent {
                code: KeyCode::Char('y'),
                modifiers: KeyModifiers::CONTROL,
                kind: KeyEventKind::Press,
                state: _,
            })
            | Event::Mouse(MouseEvent {
                kind: MouseEventKind::ScrollUp,
                column: _,
                row: _,
                modifiers: _,
            }) => Self::ScrollUp,
            Event::Key(KeyEvent {
                code: KeyCode::Char('e'),
                modifiers: KeyModifiers::CONTROL,
                kind: KeyEventKind::Press,
                state: _,
            })
            | Event::Mouse(MouseEvent {
                kind: MouseEventKind::ScrollDown,
                column: _,
                row: _,
                modifiers: _,
            }) => Self::ScrollDown,

            Event::Key(
                KeyEvent {
                    code: KeyCode::PageUp,
                    modifiers: KeyModifiers::NONE,
                    kind: KeyEventKind::Press,
                    state: _,
                }
                | KeyEvent {
                    code: KeyCode::Char('b'),
                    modifiers: KeyModifiers::CONTROL,
                    kind: KeyEventKind::Press,
                    state: _,
                },
            ) => Self::PageUp,
            Event::Key(
                KeyEvent {
                    code: KeyCode::PageDown,
                    modifiers: KeyModifiers::NONE,
                    kind: KeyEventKind::Press,
                    state: _,
                }
                | KeyEvent {
                    code: KeyCode::Char('f'),
                    modifiers: KeyModifiers::CONTROL,
                    kind: KeyEventKind::Press,
                    state: _,
                },
            ) => Self::PageDown,

            Event::Key(KeyEvent {
                code: KeyCode::Up | KeyCode::Char('k'),
                modifiers: KeyModifiers::NONE,
                kind: KeyEventKind::Press,
                state: _,
            }) => Self::FocusPrev,
            Event::Key(KeyEvent {
                code: KeyCode::Down | KeyCode::Char('j'),
                modifiers: KeyModifiers::NONE,
                kind: KeyEventKind::Press,
                state: _,
            }) => Self::FocusNext,

            Event::Key(KeyEvent {
                code: KeyCode::Left | KeyCode::Char('h'),
                modifiers: KeyModifiers::NONE,
                kind: KeyEventKind::Press,
                state: _,
            }) => Self::FocusOuter,
            Event::Key(KeyEvent {
                code: KeyCode::Right | KeyCode::Char('l'),
                modifiers: KeyModifiers::NONE,
                kind: KeyEventKind::Press,
                state: _,
            }) => Self::FocusInner,

            Event::Key(KeyEvent {
                code: KeyCode::Char('u'),
                modifiers: KeyModifiers::CONTROL,
                kind: KeyEventKind::Press,
                state: _,
            }) => Self::FocusPrevPage,
            Event::Key(KeyEvent {
                code: KeyCode::Char('d'),
                modifiers: KeyModifiers::CONTROL,
                kind: KeyEventKind::Press,
                state: _,
            }) => Self::FocusNextPage,

            Event::Key(KeyEvent {
                code: KeyCode::Char(' '),
                modifiers: KeyModifiers::NONE,
                kind: KeyEventKind::Press,
                state: _,
            }) => Self::ToggleItem,

            Event::Key(KeyEvent {
                code: KeyCode::Enter,
                modifiers: KeyModifiers::NONE,
                kind: KeyEventKind::Press,
                state: _,
            }) => Self::ToggleItemAndAdvance,

            Event::Key(KeyEvent {
                code: KeyCode::Char('a'),
                modifiers: KeyModifiers::NONE,
                kind: KeyEventKind::Press,
                state: _,
            }) => Self::ToggleAll,
            Event::Key(KeyEvent {
                code: KeyCode::Char('A'),
                modifiers: KeyModifiers::SHIFT,
                kind: KeyEventKind::Press,
                state: _,
            }) => Self::ToggleAllUniform,

            Event::Key(KeyEvent {
                code: KeyCode::Char('f'),
                modifiers: KeyModifiers::NONE,
                kind: KeyEventKind::Press,
                state: _,
            }) => Self::ExpandItem,
            Event::Key(KeyEvent {
                code: KeyCode::Char('F'),
                modifiers: KeyModifiers::SHIFT,
                kind: KeyEventKind::Press,
                state: _,
            }) => Self::ExpandAll,

            Event::Key(KeyEvent {
                code: KeyCode::Char('e'),
                modifiers: KeyModifiers::NONE,
                kind: KeyEventKind::Press,
                state: _event,
            }) => Self::EditCommitMessage,

            Event::Mouse(MouseEvent {
                kind: MouseEventKind::Down(MouseButton::Left),
                column,
                row,
                modifiers: _,
            }) => Self::Click {
                row: row.into(),
                column: column.into(),
            },

            _event => Self::None,
        }
    }
}

/// The terminal backend to use.
pub enum TerminalKind {
    /// Use the `CrosstermBackend` backend.
    Crossterm,

    /// Use the `TestingBackend` backend.
    Testing {
        /// The width of the virtual terminal.
        width: usize,

        /// The height of the virtual terminal.
        height: usize,
    },
}

/// Get user input.
pub trait RecordInput {
    /// Return the kind of terminal to use.
    fn terminal_kind(&self) -> TerminalKind;

    /// Get all available user events. This should block until there is at least
    /// one available event.
    fn next_events(&mut self) -> Result<Vec<Event>, RecordError>;

    /// Open a commit editor and interactively edit the given message.
    ///
    /// This function will only be invoked if one of the provided `Commit`s had
    /// a non-`None` commit message.
    fn edit_commit_message(&mut self, message: &str) -> Result<String, RecordError>;
}

/// Copied from internal implementation of `tui`.
fn buffer_view(buffer: &Buffer) -> String {
    let mut view =
        String::with_capacity(buffer.content.len() + usize::from(buffer.area.height) * 3);
    for cells in buffer.content.chunks(buffer.area.width.into()) {
        let mut overwritten = vec![];
        let mut skip: usize = 0;
        view.push('"');
        for (x, c) in cells.iter().enumerate() {
            if skip == 0 {
                view.push_str(c.symbol());
            } else {
                overwritten.push((x, c.symbol()))
            }
            skip = std::cmp::max(skip, c.symbol().width()).saturating_sub(1);
        }
        view.push('"');
        if !overwritten.is_empty() {
            write!(
                &mut view,
                " Hidden by multi-width symbols: {:?}",
                overwritten
            )
            .unwrap();
        }
        view.push('\n');
    }
    view
}

#[derive(Clone, Debug, PartialEq, Eq)]
enum StateUpdate {
    None,
    SetQuitDialog(Option<QuitDialog>),
    QuitAccept,
    QuitCancel,
    TakeScreenshot(TestingScreenshot),
    Redraw,
    EnsureSelectionInViewport,
    ScrollTo(isize),
    SelectItem {
        selection_key: SelectionKey,
        ensure_in_viewport: bool,
    },
    ToggleItem(SelectionKey),
    ToggleItemAndAdvance(SelectionKey, SelectionKey),
    ToggleAll,
    ToggleAllUniform,
    SetExpandItem(SelectionKey, bool),
    ToggleExpandItem(SelectionKey),
    ToggleExpandAll,
    UnfocusMenuBar,
    ClickMenu {
        menu_idx: usize,
    },
    ClickMenuItem(Event),
    ToggleCommitViewMode,
    EditCommitMessage {
        commit_idx: usize,
    },
}

#[derive(Clone, Copy, Debug)]
enum CommitViewMode {
    Inline,
    Adjacent,
}

/// UI component to record the user's changes.
pub struct Recorder<'state, 'input> {
    state: RecordState<'state>,
    input: &'input mut dyn RecordInput,
    pending_events: Vec<Event>,
    use_unicode: bool,
    commit_view_mode: CommitViewMode,
    expanded_items: HashSet<SelectionKey>,
    expanded_menu_idx: Option<usize>,
    selection_key: SelectionKey,
    focused_commit_idx: usize,
    quit_dialog: Option<QuitDialog>,
    scroll_offset_y: isize,
}

impl<'state, 'input> Recorder<'state, 'input> {
    /// Constructor.
    pub fn new(mut state: RecordState<'state>, input: &'input mut dyn RecordInput) -> Self {
        // Ensure that there are at least two commits.
        state.commits.extend(
            iter::repeat_with(Commit::default).take(2_usize.saturating_sub(state.commits.len())),
        );
        if state.commits.len() > 2 {
            unimplemented!("more than two commits");
        }

        let mut recorder = Self {
            state,
            input,
            pending_events: Default::default(),
            use_unicode: true,
            commit_view_mode: CommitViewMode::Inline,
            expanded_items: Default::default(),
            expanded_menu_idx: Default::default(),
            selection_key: SelectionKey::None,
            focused_commit_idx: 0,
            quit_dialog: None,
            scroll_offset_y: 0,
        };
        recorder.expand_initial_items();
        recorder
    }

    /// Run the terminal user interface and have the user interactively select
    /// changes.
    pub fn run(self) -> Result<RecordState<'state>, RecordError> {
        #[cfg(feature = "debug")]
        if std::env::var_os(crate::consts::ENV_VAR_DUMP_UI_STATE).is_some() {
            let ui_state =
                serde_json::to_string_pretty(&self.state).map_err(RecordError::SerializeJson)?;
            std::fs::write(crate::consts::DUMP_UI_STATE_FILENAME, ui_state)
                .map_err(RecordError::WriteFile)?;
        }

        match self.input.terminal_kind() {
            TerminalKind::Crossterm => self.run_crossterm(),
            TerminalKind::Testing { width, height } => self.run_testing(width, height),
        }
    }

    /// Run the recorder UI using `crossterm` as the backend connected to stdout.
    fn run_crossterm(self) -> Result<RecordState<'state>, RecordError> {
        Self::set_up_crossterm()?;
        Self::install_panic_hook();
        let backend = CrosstermBackend::new(io::stdout());
        let mut term = Terminal::new(backend).map_err(RecordError::SetUpTerminal)?;
        term.clear().map_err(RecordError::RenderFrame)?;
        let result = self.run_inner(&mut term);
        Self::clean_up_crossterm()?;
        result
    }

    fn install_panic_hook() {
        // HACK: installing a global hook here. This could be installed multiple
        // times, and there's no way to uninstall it once we return.
        //
        // The idea is
        // taken from
        // https://github.com/fdehau/tui-rs/blob/fafad6c96109610825aad89c4bba5253e01101ed/examples/panic.rs.
        //
        // For some reason, simply catching the panic, cleaning up, and
        // reraising the panic loses information about where the panic was
        // originally raised, which is frustrating.
        let original_hook = panic::take_hook();
        panic::set_hook(Box::new(move |panic| {
            Self::clean_up_crossterm().unwrap();
            original_hook(panic);
        }));
    }

    fn set_up_crossterm() -> Result<(), RecordError> {
        if !is_raw_mode_enabled().map_err(RecordError::SetUpTerminal)? {
            crossterm::execute!(io::stdout(), EnterAlternateScreen, EnableMouseCapture)
                .map_err(RecordError::SetUpTerminal)?;
            enable_raw_mode().map_err(RecordError::SetUpTerminal)?;
        }
        Ok(())
    }

    fn clean_up_crossterm() -> Result<(), RecordError> {
        if is_raw_mode_enabled().map_err(RecordError::CleanUpTerminal)? {
            disable_raw_mode().map_err(RecordError::CleanUpTerminal)?;
            crossterm::execute!(io::stdout(), LeaveAlternateScreen, DisableMouseCapture)
                .map_err(RecordError::CleanUpTerminal)?;
        }
        Ok(())
    }

    fn run_testing(self, width: usize, height: usize) -> Result<RecordState<'state>, RecordError> {
        let backend = TestBackend::new(width.clamp_into_u16(), height.clamp_into_u16());
        let mut term = Terminal::new(backend).map_err(RecordError::SetUpTerminal)?;
        self.run_inner(&mut term)
    }

    fn run_inner(
        mut self,
        term: &mut Terminal<impl Backend + Any>,
    ) -> Result<RecordState<'state>, RecordError> {
        self.selection_key = self.first_selection_key();
        let debug = if cfg!(feature = "debug") {
            std::env::var_os(ENV_VAR_DEBUG_UI).is_some()
        } else {
            false
        };

        'outer: loop {
            let menu_bar = self.make_menu_bar();
            let app = self.make_app(menu_bar.clone(), None);
            let term_height = usize::from(term.get_frame().size().height);

            let mut drawn_rects: Option<DrawnRects<ComponentId>> = None;
            term.draw(|frame| {
                drawn_rects = Some(Viewport::<ComponentId>::render_top_level(
                    frame,
                    0,
                    self.scroll_offset_y,
                    &app,
                ));
            })
            .map_err(RecordError::RenderFrame)?;
            let drawn_rects = drawn_rects.unwrap();

            // Dump debug info. We may need to use information about the
            // rendered app, so we perform a re-render here.
            if debug {
                let debug_info = AppDebugInfo {
                    term_height,
                    scroll_offset_y: self.scroll_offset_y,
                    selection_key: self.selection_key,
                    selection_key_y: self.selection_key_y(&drawn_rects, self.selection_key),
                    drawn_rects: drawn_rects.clone().into_iter().collect(),
                };
                let debug_app = AppView {
                    debug_info: Some(debug_info),
                    ..app.clone()
                };
                term.draw(|frame| {
                    Viewport::<ComponentId>::render_top_level(
                        frame,
                        0,
                        self.scroll_offset_y,
                        &debug_app,
                    );
                })
                .map_err(RecordError::RenderFrame)?;
            }

            let events = if self.pending_events.is_empty() {
                self.input.next_events()?
            } else {
                // FIXME: the pending events should be applied without redrawing
                // the screen, as otherwise there may be a flash of content
                // containing the screen contents before the event is applied.
                mem::take(&mut self.pending_events)
            };
            for event in events {
                match self.handle_event(event, term_height, &drawn_rects, &menu_bar)? {
                    StateUpdate::None => {}
                    StateUpdate::SetQuitDialog(quit_dialog) => {
                        self.quit_dialog = quit_dialog;
                    }
                    StateUpdate::QuitAccept => break 'outer,
                    StateUpdate::QuitCancel => return Err(RecordError::Cancelled),
                    StateUpdate::TakeScreenshot(screenshot) => {
                        let backend: &dyn Any = term.backend();
                        let test_backend = backend
                            .downcast_ref::<TestBackend>()
                            .expect("TakeScreenshot event generated for non-testing backend");
                        screenshot.set(buffer_view(test_backend.buffer()));
                    }
                    StateUpdate::Redraw => {
                        term.clear().map_err(RecordError::RenderFrame)?;
                    }
                    StateUpdate::EnsureSelectionInViewport => {
                        if let Some(scroll_offset_y) =
                            self.ensure_in_viewport(term_height, &drawn_rects, self.selection_key)
                        {
                            self.scroll_offset_y = scroll_offset_y;
                        }
                    }
                    StateUpdate::ScrollTo(scroll_offset_y) => {
                        self.scroll_offset_y = scroll_offset_y.clamp(0, {
                            let DrawnRect { rect, timestamp: _ } = drawn_rects[&ComponentId::App];
                            rect.height.unwrap_isize() - 1
                        });
                    }
                    StateUpdate::SelectItem {
                        selection_key,
                        ensure_in_viewport,
                    } => {
                        self.selection_key = selection_key;
                        self.expand_item_ancestors(selection_key);
                        if ensure_in_viewport {
                            self.pending_events.push(Event::EnsureSelectionInViewport);
                        }
                    }
                    StateUpdate::ToggleItem(selection_key) => {
                        self.toggle_item(selection_key)?;
                    }
                    StateUpdate::ToggleItemAndAdvance(selection_key, new_key) => {
                        self.toggle_item(selection_key)?;
                        self.selection_key = new_key;
                        self.pending_events.push(Event::EnsureSelectionInViewport);
                    }
                    StateUpdate::ToggleAll => {
                        self.toggle_all();
                    }
                    StateUpdate::ToggleAllUniform => {
                        self.toggle_all_uniform();
                    }
                    StateUpdate::SetExpandItem(selection_key, is_expanded) => {
                        self.set_expand_item(selection_key, is_expanded);
                        self.pending_events.push(Event::EnsureSelectionInViewport);
                    }
                    StateUpdate::ToggleExpandItem(selection_key) => {
                        self.toggle_expand_item(selection_key)?;
                        self.pending_events.push(Event::EnsureSelectionInViewport);
                    }
                    StateUpdate::ToggleExpandAll => {
                        self.toggle_expand_all()?;
                        self.pending_events.push(Event::EnsureSelectionInViewport);
                    }
                    StateUpdate::UnfocusMenuBar => {
                        self.unfocus_menu_bar();
                    }
                    StateUpdate::ClickMenu { menu_idx } => {
                        self.click_menu_header(menu_idx);
                    }
                    StateUpdate::ClickMenuItem(event) => {
                        self.click_menu_item(event);
                    }
                    StateUpdate::ToggleCommitViewMode => {
                        self.commit_view_mode = match self.commit_view_mode {
                            CommitViewMode::Inline => CommitViewMode::Adjacent,
                            CommitViewMode::Adjacent => CommitViewMode::Inline,
                        };
                    }
                    StateUpdate::EditCommitMessage { commit_idx } => {
                        self.pending_events.push(Event::Redraw);
                        self.edit_commit_message(commit_idx)?;
                    }
                }
            }
        }

        Ok(self.state)
    }

    fn make_menu_bar(&self) -> MenuBar<'static> {
        MenuBar {
            menus: vec![
                Menu {
                    label: Cow::Borrowed("File"),
                    items: vec![
                        MenuItem {
                            label: Cow::Borrowed("Confirm (c)"),
                            event: Event::QuitAccept,
                        },
                        MenuItem {
                            label: Cow::Borrowed("Quit (q)"),
                            event: Event::QuitCancel,
                        },
                    ],
                },
                Menu {
                    label: Cow::Borrowed("Edit"),
                    items: vec![
                        MenuItem {
                            label: Cow::Borrowed("Edit message (e)"),
                            event: Event::EditCommitMessage,
                        },
                        MenuItem {
                            label: Cow::Borrowed("Toggle current (space)"),
                            event: Event::ToggleItem,
                        },
                        MenuItem {
                            label: Cow::Borrowed("Toggle current and advance (enter)"),
                            event: Event::ToggleItemAndAdvance,
                        },
                        MenuItem {
                            label: Cow::Borrowed("Invert all items (a)"),
                            event: Event::ToggleAll,
                        },
                        MenuItem {
                            label: Cow::Borrowed("Invert all items uniformly (A)"),
                            event: Event::ToggleAllUniform,
                        },
                    ],
                },
                Menu {
                    label: Cow::Borrowed("Select"),
                    items: vec![
                        MenuItem {
                            label: Cow::Borrowed("Previous item (up, k)"),
                            event: Event::FocusPrev,
                        },
                        MenuItem {
                            label: Cow::Borrowed("Next item (down, j)"),
                            event: Event::FocusNext,
                        },
                        MenuItem {
                            label: Cow::Borrowed("Outer item (left, h)"),
                            event: Event::FocusOuter,
                        },
                        MenuItem {
                            label: Cow::Borrowed("Inner item (right, l)"),
                            event: Event::FocusInner,
                        },
                        MenuItem {
                            label: Cow::Borrowed("Previous page (ctrl-u)"),
                            event: Event::FocusPrevPage,
                        },
                        MenuItem {
                            label: Cow::Borrowed("Next page (ctrl-d)"),
                            event: Event::FocusNextPage,
                        },
                    ],
                },
                Menu {
                    label: Cow::Borrowed("View"),
                    items: vec![
                        MenuItem {
                            label: Cow::Borrowed("Fold/unfold current (f)"),
                            event: Event::ExpandItem,
                        },
                        MenuItem {
                            label: Cow::Borrowed("Fold/unfold all (F)"),
                            event: Event::ExpandAll,
                        },
                        MenuItem {
                            label: Cow::Borrowed("Scroll up (ctrl-y)"),
                            event: Event::ScrollUp,
                        },
                        MenuItem {
                            label: Cow::Borrowed("Scroll down (ctrl-e)"),
                            event: Event::ScrollDown,
                        },
                        MenuItem {
                            label: Cow::Borrowed("Page up (page-up, ctrl-b)"),
                            event: Event::PageUp,
                        },
                        MenuItem {
                            label: Cow::Borrowed("Page down (page-down, ctrl-f)"),
                            event: Event::PageDown,
                        },
                    ],
                },
            ],
            expanded_menu_idx: self.expanded_menu_idx,
        }
    }

    fn make_app(
        &'state self,
        menu_bar: MenuBar<'static>,
        debug_info: Option<AppDebugInfo>,
    ) -> AppView<'state> {
        let RecordState {
            is_read_only,
            commits,
            files,
        } = &self.state;
        let commit_views = match self.commit_view_mode {
            CommitViewMode::Inline => {
                vec![CommitView {
                    debug_info: None,
                    commit_message_view: CommitMessageView {
                        commit_idx: self.focused_commit_idx,
                        commit: &commits[self.focused_commit_idx],
                    },
                    file_views: self.make_file_views(
                        self.focused_commit_idx,
                        files,
                        &debug_info,
                        *is_read_only,
                    ),
                }]
            }

            CommitViewMode::Adjacent => commits
                .iter()
                .enumerate()
                .map(|(commit_idx, commit)| CommitView {
                    debug_info: None,
                    commit_message_view: CommitMessageView { commit_idx, commit },
                    file_views: self.make_file_views(commit_idx, files, &debug_info, *is_read_only),
                })
                .collect(),
        };
        AppView {
            debug_info: None,
            menu_bar,
            commit_view_mode: self.commit_view_mode,
            commit_views,
            quit_dialog: self.quit_dialog.clone(),
        }
    }

    fn make_file_views(
        &'state self,
        commit_idx: usize,
        files: &'state [File<'state>],
        debug_info: &Option<AppDebugInfo>,
        is_read_only: bool,
    ) -> Vec<FileView<'state>> {
        files
            .iter()
            .enumerate()
            .map(|(file_idx, file)| {
                let file_key = FileKey {
                    commit_idx,
                    file_idx,
                };
                let file_toggled = self.file_tristate(file_key).unwrap();
                let file_expanded = self.file_expanded(file_key);
                let is_focused = match self.selection_key {
                    SelectionKey::None | SelectionKey::Section(_) | SelectionKey::Line(_) => false,
                    SelectionKey::File(selected_file_key) => file_key == selected_file_key,
                };
                FileView {
                    debug: debug_info.is_some(),
                    file_key,
                    toggle_box: TristateBox {
                        use_unicode: self.use_unicode,
                        id: ComponentId::ToggleBox(SelectionKey::File(file_key)),
                        icon_style: TristateIconStyle::Check,
                        tristate: file_toggled,
                        is_focused,
                        is_read_only,
                    },
                    expand_box: TristateBox {
                        use_unicode: self.use_unicode,
                        id: ComponentId::ExpandBox(SelectionKey::File(file_key)),
                        icon_style: TristateIconStyle::Expand,
                        tristate: file_expanded,
                        is_focused,
                        is_read_only: false,
                    },
                    is_header_selected: is_focused,
                    old_path: file.old_path.as_deref(),
                    path: &file.path,
                    section_views: {
                        let mut section_views = Vec::new();
                        let total_num_sections = file.sections.len();
                        let total_num_editable_sections = file
                            .sections
                            .iter()
                            .filter(|section| section.is_editable())
                            .count();

                        let mut line_num = 1;
                        let mut editable_section_num = 0;
                        for (section_idx, section) in file.sections.iter().enumerate() {
                            let section_key = SectionKey {
                                commit_idx,
                                file_idx,
                                section_idx,
                            };
                            let section_toggled = self.section_tristate(section_key).unwrap();
                            let section_expanded = Tristate::from(
                                self.expanded_items
                                    .contains(&SelectionKey::Section(section_key)),
                            );
                            let is_focused = match self.selection_key {
                                SelectionKey::None
                                | SelectionKey::File(_)
                                | SelectionKey::Line(_) => false,
                                SelectionKey::Section(selection_section_key) => {
                                    selection_section_key == section_key
                                }
                            };
                            if section.is_editable() {
                                editable_section_num += 1;
                            }
                            section_views.push(SectionView {
                                use_unicode: self.use_unicode,
                                is_read_only,
                                section_key,
                                toggle_box: TristateBox {
                                    use_unicode: self.use_unicode,
                                    is_read_only,
                                    id: ComponentId::ToggleBox(SelectionKey::Section(section_key)),
                                    tristate: section_toggled,
                                    icon_style: TristateIconStyle::Check,
                                    is_focused,
                                },
                                expand_box: TristateBox {
                                    use_unicode: self.use_unicode,
                                    is_read_only: false,
                                    id: ComponentId::ExpandBox(SelectionKey::Section(section_key)),
                                    tristate: section_expanded,
                                    icon_style: TristateIconStyle::Expand,
                                    is_focused,
                                },
                                selection: match self.selection_key {
                                    SelectionKey::None | SelectionKey::File(_) => None,
                                    SelectionKey::Section(selected_section_key) => {
                                        if selected_section_key == section_key {
                                            Some(SectionSelection::SectionHeader)
                                        } else {
                                            None
                                        }
                                    }
                                    SelectionKey::Line(LineKey {
                                        commit_idx,
                                        file_idx,
                                        section_idx,
                                        line_idx,
                                    }) => {
                                        let selected_section_key = SectionKey {
                                            commit_idx,
                                            file_idx,
                                            section_idx,
                                        };
                                        if selected_section_key == section_key {
                                            Some(SectionSelection::ChangedLine(line_idx))
                                        } else {
                                            None
                                        }
                                    }
                                },
                                total_num_sections,
                                editable_section_num,
                                total_num_editable_sections,
                                section,
                                line_start_num: line_num,
                            });

                            line_num += match section {
                                Section::Unchanged { lines } => lines.len(),
                                Section::Changed { lines } => lines
                                    .iter()
                                    .filter(|changed_line| match changed_line.change_type {
                                        ChangeType::Added => false,
                                        ChangeType::Removed => true,
                                    })
                                    .count(),
                                Section::FileMode { .. } | Section::Binary { .. } => 0,
                            };
                        }
                        section_views
                    },
                }
            })
            .collect()
    }

    fn handle_event(
        &self,
        event: Event,
        term_height: usize,
        drawn_rects: &DrawnRects<ComponentId>,
        menu_bar: &MenuBar,
    ) -> Result<StateUpdate, RecordError> {
        let state_update = match (&self.quit_dialog, event) {
            (_, Event::None) => StateUpdate::None,
            (_, Event::Redraw) => StateUpdate::Redraw,
            (_, Event::EnsureSelectionInViewport) => StateUpdate::EnsureSelectionInViewport,

            // Confirm the changes.
            (None, Event::QuitAccept) => StateUpdate::QuitAccept,
            // Ignore the confirm action if the quit dialog is open.
            (Some(_), Event::QuitAccept) => StateUpdate::None,

            // Render quit dialog if the user made changes.
            (None, Event::QuitCancel | Event::QuitInterrupt) => {
                let num_commit_messages = self.num_user_commit_messages()?;
                let num_changed_files = self.num_user_file_changes()?;
                if num_commit_messages > 0 || num_changed_files > 0 {
                    StateUpdate::SetQuitDialog(Some(QuitDialog {
                        num_commit_messages,
                        num_changed_files,
                        focused_button: QuitDialogButtonId::Quit,
                    }))
                } else {
                    StateUpdate::QuitCancel
                }
            }
            // If pressing quit again while the dialog is open, close it.
            (Some(_), Event::QuitCancel) => StateUpdate::SetQuitDialog(None),
            // If pressing ctrl-c again wile the dialog is open, force quit.
            (Some(_), Event::QuitInterrupt) => StateUpdate::QuitCancel,
            // Select left quit dialog button.
            (Some(quit_dialog), Event::FocusOuter) => {
                StateUpdate::SetQuitDialog(Some(QuitDialog {
                    focused_button: QuitDialogButtonId::GoBack,
                    ..quit_dialog.clone()
                }))
            }
            // Select right quit dialog button.
            (Some(quit_dialog), Event::FocusInner) => {
                StateUpdate::SetQuitDialog(Some(QuitDialog {
                    focused_button: QuitDialogButtonId::Quit,
                    ..quit_dialog.clone()
                }))
            }
            // Press the appropriate dialog button.
            (Some(quit_dialog), Event::ToggleItem | Event::ToggleItemAndAdvance) => {
                let QuitDialog {
                    num_commit_messages: _,
                    num_changed_files: _,
                    focused_button,
                } = quit_dialog;
                match focused_button {
                    QuitDialogButtonId::Quit => StateUpdate::QuitCancel,
                    QuitDialogButtonId::GoBack => StateUpdate::SetQuitDialog(None),
                }
            }

            // Disable most keyboard shortcuts while the quit dialog is open.
            (
                Some(_),
                Event::ScrollUp
                | Event::ScrollDown
                | Event::PageUp
                | Event::PageDown
                | Event::FocusPrev
                | Event::FocusNext
                | Event::FocusPrevPage
                | Event::FocusNextPage
                | Event::ToggleAll
                | Event::ToggleAllUniform
                | Event::ExpandItem
                | Event::ExpandAll
                | Event::EditCommitMessage,
            ) => StateUpdate::None,

            (Some(_) | None, Event::TakeScreenshot(screenshot)) => {
                StateUpdate::TakeScreenshot(screenshot)
            }
            (None, Event::ScrollUp) => {
                StateUpdate::ScrollTo(self.scroll_offset_y.saturating_sub(1))
            }
            (None, Event::ScrollDown) => {
                StateUpdate::ScrollTo(self.scroll_offset_y.saturating_add(1))
            }
            (None, Event::PageUp) => StateUpdate::ScrollTo(
                self.scroll_offset_y
                    .saturating_sub(term_height.unwrap_isize()),
            ),
            (None, Event::PageDown) => StateUpdate::ScrollTo(
                self.scroll_offset_y
                    .saturating_add(term_height.unwrap_isize()),
            ),
            (None, Event::FocusPrev) => {
                let (keys, index) = self.find_selection();
                let selection_key = self.select_prev(&keys, index);
                StateUpdate::SelectItem {
                    selection_key,
                    ensure_in_viewport: true,
                }
            }
            (None, Event::FocusNext) => {
                let (keys, index) = self.find_selection();
                let selection_key = self.select_next(&keys, index);
                StateUpdate::SelectItem {
                    selection_key,
                    ensure_in_viewport: true,
                }
            }
            (None, Event::FocusPrevPage) => {
                let selection_key = self.select_prev_page(term_height, drawn_rects);
                StateUpdate::SelectItem {
                    selection_key,
                    ensure_in_viewport: true,
                }
            }
            (None, Event::FocusNextPage) => {
                let selection_key = self.select_next_page(term_height, drawn_rects);
                StateUpdate::SelectItem {
                    selection_key,
                    ensure_in_viewport: true,
                }
            }
            (None, Event::FocusOuter) => self.select_outer(),
            (None, Event::FocusInner) => {
                let selection_key = self.select_inner();
                StateUpdate::SelectItem {
                    selection_key,
                    ensure_in_viewport: true,
                }
            }
            (None, Event::ToggleItem) => StateUpdate::ToggleItem(self.selection_key),
            (None, Event::ToggleItemAndAdvance) => {
                let advanced_key = self.advance_to_next_of_kind();
                StateUpdate::ToggleItemAndAdvance(self.selection_key, advanced_key)
            }
            (None, Event::ToggleAll) => StateUpdate::ToggleAll,
            (None, Event::ToggleAllUniform) => StateUpdate::ToggleAllUniform,
            (None, Event::ExpandItem) => StateUpdate::ToggleExpandItem(self.selection_key),
            (None, Event::ExpandAll) => StateUpdate::ToggleExpandAll,
            (None, Event::EditCommitMessage) => StateUpdate::EditCommitMessage {
                commit_idx: self.focused_commit_idx,
            },

            (_, Event::Click { row, column }) => {
                let component_id = self.find_component_at(drawn_rects, row, column);
                self.click_component(menu_bar, component_id)
            }
            (_, Event::ToggleCommitViewMode) => StateUpdate::ToggleCommitViewMode,
        };
        Ok(state_update)
    }

    fn first_selection_key(&self) -> SelectionKey {
        match self.state.files.iter().enumerate().next() {
            Some((file_idx, _)) => SelectionKey::File(FileKey {
                commit_idx: self.focused_commit_idx,
                file_idx,
            }),
            None => SelectionKey::None,
        }
    }

    fn num_user_commit_messages(&self) -> Result<usize, RecordError> {
        let RecordState {
            files: _,
            commits,
            is_read_only: _,
        } = &self.state;
        Ok(commits
            .iter()
            .map(|commit| {
                let Commit { message } = commit;
                match message {
                    Some(message) if !message.is_empty() => 1,
                    _ => 0,
                }
            })
            .sum())
    }

    fn num_user_file_changes(&self) -> Result<usize, RecordError> {
        let RecordState {
            files,
            commits: _,
            is_read_only: _,
        } = &self.state;
        let mut result = 0;
        for (file_idx, _file) in files.iter().enumerate() {
            match self.file_tristate(FileKey {
                commit_idx: self.focused_commit_idx,
                file_idx,
            })? {
                Tristate::False => {}
                Tristate::Partial | Tristate::True => {
                    result += 1;
                }
            }
        }
        Ok(result)
    }

    fn all_selection_keys(&self) -> Vec<SelectionKey> {
        let mut result = Vec::new();
        for (commit_idx, _) in self.state.commits.iter().enumerate() {
            if commit_idx > 0 {
                // TODO: implement adjacent `CommitView s.
                continue;
            }
            for (file_idx, file) in self.state.files.iter().enumerate() {
                result.push(SelectionKey::File(FileKey {
                    commit_idx,
                    file_idx,
                }));
                for (section_idx, section) in file.sections.iter().enumerate() {
                    match section {
                        Section::Unchanged { .. } => {}
                        Section::Changed { lines } => {
                            result.push(SelectionKey::Section(SectionKey {
                                commit_idx,
                                file_idx,
                                section_idx,
                            }));
                            for (line_idx, _line) in lines.iter().enumerate() {
                                result.push(SelectionKey::Line(LineKey {
                                    commit_idx,
                                    file_idx,
                                    section_idx,
                                    line_idx,
                                }));
                            }
                        }
                        Section::FileMode {
                            is_checked: _,
                            before: _,
                            after: _,
                        }
                        | Section::Binary { .. } => {
                            result.push(SelectionKey::Section(SectionKey {
                                commit_idx,
                                file_idx,
                                section_idx,
                            }));
                        }
                    }
                }
            }
        }
        result
    }

    fn find_selection(&self) -> (Vec<SelectionKey>, Option<usize>) {
        // FIXME: finding the selected key is an O(n) algorithm (instead of O(log(n)) or O(1)).
        let visible_keys: Vec<_> = self
            .all_selection_keys()
            .iter()
            .cloned()
            .filter(|key| match key {
                SelectionKey::None => false,
                SelectionKey::File(_) => true,
                SelectionKey::Section(section_key) => {
                    let file_key = FileKey {
                        commit_idx: section_key.commit_idx,
                        file_idx: section_key.file_idx,
                    };
                    match self.file_expanded(file_key) {
                        Tristate::False => false,
                        Tristate::Partial | Tristate::True => true,
                    }
                }
                SelectionKey::Line(line_key) => {
                    let file_key = FileKey {
                        commit_idx: line_key.commit_idx,
                        file_idx: line_key.file_idx,
                    };
                    let section_key = SectionKey {
                        commit_idx: line_key.commit_idx,
                        file_idx: line_key.file_idx,
                        section_idx: line_key.section_idx,
                    };
                    self.expanded_items.contains(&SelectionKey::File(file_key))
                        && self
                            .expanded_items
                            .contains(&SelectionKey::Section(section_key))
                }
            })
            .collect();
        let index = visible_keys.iter().enumerate().find_map(|(k, v)| {
            if v == &self.selection_key {
                Some(k)
            } else {
                None
            }
        });
        (visible_keys, index)
    }

    fn select_prev(&self, keys: &[SelectionKey], index: Option<usize>) -> SelectionKey {
        match index {
            None => self.first_selection_key(),
            Some(index) => match index.checked_sub(1) {
                Some(index) => keys[index],
                None => {
                    // TODO: this behavior will be wrong if we have keys for each `Commit` (which currently isn't the case).
                    *keys.last().unwrap()
                }
            },
        }
    }

    fn select_next(&self, keys: &[SelectionKey], index: Option<usize>) -> SelectionKey {
        match index {
            None => self.first_selection_key(),
            Some(index) => match keys.get(index + 1) {
                Some(key) => *key,
                None => keys[0],
            },
        }
    }

    fn select_prev_page(
        &self,
        term_height: usize,
        drawn_rects: &DrawnRects<ComponentId>,
    ) -> SelectionKey {
        let (keys, index) = self.find_selection();
        let mut index = match index {
            Some(index) => index,
            None => return SelectionKey::None,
        };

        let original_y = match self.selection_key_y(drawn_rects, self.selection_key) {
            Some(original_y) => original_y,
            None => {
                return SelectionKey::None;
            }
        };
        let target_y = original_y.saturating_sub(term_height.unwrap_isize() / 2);
        while index > 0 {
            index -= 1;
            let selection_key_y = self.selection_key_y(drawn_rects, keys[index]);
            if let Some(selection_key_y) = selection_key_y {
                if selection_key_y <= target_y {
                    break;
                }
            }
        }
        keys[index]
    }

    fn select_next_page(
        &self,
        term_height: usize,
        drawn_rects: &DrawnRects<ComponentId>,
    ) -> SelectionKey {
        let (keys, index) = self.find_selection();
        let mut index = match index {
            Some(index) => index,
            None => return SelectionKey::None,
        };

        let original_y = match self.selection_key_y(drawn_rects, self.selection_key) {
            Some(original_y) => original_y,
            None => return SelectionKey::None,
        };
        let target_y = original_y.saturating_add(term_height.unwrap_isize() / 2);
        while index + 1 < keys.len() {
            index += 1;
            let selection_key_y = self.selection_key_y(drawn_rects, keys[index]);
            if let Some(selection_key_y) = selection_key_y {
                if selection_key_y >= target_y {
                    break;
                }
            }
        }
        keys[index]
    }

    fn select_inner(&self) -> SelectionKey {
        self.all_selection_keys()
            .into_iter()
            .skip_while(|selection_key| selection_key != &self.selection_key)
            .skip(1)
            .find(|selection_key| {
                match (self.selection_key, selection_key) {
                    (SelectionKey::None, _) => true,
                    (_, SelectionKey::None) => false, // shouldn't happen

                    (SelectionKey::File(_), SelectionKey::File(_)) => false,
                    (SelectionKey::File(_), SelectionKey::Section(_)) => true,
                    (SelectionKey::File(_), SelectionKey::Line(_)) => false, // shouldn't happen

                    (SelectionKey::Section(_), SelectionKey::File(_))
                    | (SelectionKey::Section(_), SelectionKey::Section(_)) => false,
                    (SelectionKey::Section(_), SelectionKey::Line(_)) => true,

                    (SelectionKey::Line(_), _) => false,
                }
            })
            .unwrap_or(self.selection_key)
    }

    fn select_outer(&self) -> StateUpdate {
        match self.selection_key {
            SelectionKey::None => StateUpdate::None,
            selection_key @ SelectionKey::File(_) => {
                StateUpdate::SetExpandItem(selection_key, false)
            }
            SelectionKey::Section(SectionKey {
                commit_idx,
                file_idx,
                section_idx: _,
            }) => StateUpdate::SelectItem {
                selection_key: SelectionKey::File(FileKey {
                    commit_idx,
                    file_idx,
                }),
                ensure_in_viewport: true,
            },
            SelectionKey::Line(LineKey {
                commit_idx,
                file_idx,
                section_idx,
                line_idx: _,
            }) => StateUpdate::SelectItem {
                selection_key: SelectionKey::Section(SectionKey {
                    commit_idx,
                    file_idx,
                    section_idx,
                }),
                ensure_in_viewport: true,
            },
        }
    }

    fn advance_to_next_of_kind(&self) -> SelectionKey {
        let (keys, index) = self.find_selection();
        let index = match index {
            Some(index) => index,
            None => return SelectionKey::None,
        };
        keys.iter()
            .skip(index + 1)
            .copied()
            .find(|key| match (self.selection_key, key) {
                (SelectionKey::None, _)
                | (SelectionKey::File(_), SelectionKey::File(_))
                | (SelectionKey::Section(_), SelectionKey::Section(_))
                | (SelectionKey::Line(_), SelectionKey::Line(_)) => true,
                (
                    SelectionKey::File(_),
                    SelectionKey::None | SelectionKey::Section(_) | SelectionKey::Line(_),
                )
                | (
                    SelectionKey::Section(_),
                    SelectionKey::None | SelectionKey::File(_) | SelectionKey::Line(_),
                )
                | (
                    SelectionKey::Line(_),
                    SelectionKey::None | SelectionKey::File(_) | SelectionKey::Section(_),
                ) => false,
            })
            .unwrap_or(self.selection_key)
    }

    fn selection_key_y(
        &self,
        drawn_rects: &DrawnRects<ComponentId>,
        selection_key: SelectionKey,
    ) -> Option<isize> {
        let rect = self.selection_rect(drawn_rects, selection_key)?;
        Some(rect.y)
    }

    fn selection_rect(
        &self,
        drawn_rects: &DrawnRects<ComponentId>,
        selection_key: SelectionKey,
    ) -> Option<Rect> {
        let id = match selection_key {
            SelectionKey::None => return None,
            SelectionKey::File(_) | SelectionKey::Section(_) | SelectionKey::Line(_) => {
                ComponentId::SelectableItem(selection_key)
            }
        };
        match drawn_rects.get(&id) {
            Some(DrawnRect { rect, timestamp: _ }) => Some(*rect),
            None => {
                if cfg!(debug_assertions) {
                    panic!(
                        "could not look up drawn rect for component with ID {id:?}; was it drawn?"
                    )
                } else {
                    warn!(component_id = ?id, "could not look up drawn rect for component; was it drawn?");
                    None
                }
            }
        }
    }

    fn ensure_in_viewport(
        &self,
        term_height: usize,
        drawn_rects: &DrawnRects<ComponentId>,
        selection_key: SelectionKey,
    ) -> Option<isize> {
        let menu_bar_height = 1;
        let sticky_file_header_height = match selection_key {
            SelectionKey::None | SelectionKey::File(_) => 0,
            SelectionKey::Section(_) | SelectionKey::Line(_) => 1,
        };
        let top_margin = sticky_file_header_height + menu_bar_height;

        let viewport_top_y = self.scroll_offset_y + top_margin;
        let viewport_height = term_height.unwrap_isize() - top_margin;
        let viewport_bottom_y = viewport_top_y + viewport_height;

        let selection_rect = self.selection_rect(drawn_rects, selection_key)?;
        let selection_top_y = selection_rect.y;
        let selection_height = selection_rect.height.unwrap_isize();
        let selection_bottom_y = selection_top_y + selection_height;

        // Idea: scroll the entire component into the viewport, not just the
        // first line, if possible. If the entire component is smaller than
        // the viewport, then we scroll only enough so that the entire
        // component becomes visible, i.e. align the component's bottom edge
        // with the viewport's bottom edge. Otherwise, we scroll such that
        // the component's top edge is aligned with the viewport's top edge.
        //
        // FIXME: if we scroll up from below, we would want to align the top
        // edge of the component, not the bottom edge. Thus, we should also
        // accept the previous `SelectionKey` and use that when making the
        // decision of where to scroll.
        let result = if viewport_top_y <= selection_top_y && selection_bottom_y < viewport_bottom_y
        {
            // Component is completely within the viewport, no need to scroll.
            self.scroll_offset_y
        } else if (
            // Component doesn't fit in the viewport; just render the top.
            selection_height >= viewport_height
        ) || (
            // Component is at least partially above the viewport.
            selection_top_y < viewport_top_y
        ) {
            selection_top_y - top_margin
        } else {
            // Component is at least partially below the viewport. Want to satisfy:
            // scroll_offset_y + term_height == rect_bottom_y
            selection_bottom_y - top_margin - viewport_height
        };
        Some(result)
    }

    fn find_component_at(
        &self,
        drawn_rects: &DrawnRects<ComponentId>,
        row: usize,
        column: usize,
    ) -> ComponentId {
        let x = column.unwrap_isize();
        let y = row.unwrap_isize() + self.scroll_offset_y;
        drawn_rects
            .iter()
            .filter(|(id, drawn_rect)| {
                let DrawnRect { rect, timestamp: _ } = drawn_rect;
                rect.contains_point(x, y)
                    && match id {
                        ComponentId::App
                        | ComponentId::AppFiles
                        | ComponentId::MenuHeader
                        | ComponentId::CommitMessageView => false,
                        ComponentId::MenuBar
                        | ComponentId::MenuItem(_)
                        | ComponentId::Menu(_)
                        | ComponentId::CommitEditMessageButton(_)
                        | ComponentId::FileViewHeader(_)
                        | ComponentId::SelectableItem(_)
                        | ComponentId::ToggleBox(_)
                        | ComponentId::ExpandBox(_)
                        | ComponentId::QuitDialog
                        | ComponentId::QuitDialogButton(_) => true,
                    }
            })
            .max_by_key(|(id, rect)| {
                let DrawnRect { rect: _, timestamp } = rect;
                (timestamp, *id)
            })
            .map(|(id, _rect)| *id)
            .unwrap_or(ComponentId::App)
    }

    fn click_component(&self, menu_bar: &MenuBar, component_id: ComponentId) -> StateUpdate {
        match component_id {
            ComponentId::App
            | ComponentId::AppFiles
            | ComponentId::MenuHeader
            | ComponentId::CommitMessageView
            | ComponentId::QuitDialog => StateUpdate::None,
            ComponentId::MenuBar => StateUpdate::UnfocusMenuBar,
            ComponentId::Menu(section_idx) => StateUpdate::ClickMenu {
                menu_idx: section_idx,
            },
            ComponentId::MenuItem(item_idx) => {
                StateUpdate::ClickMenuItem(self.get_menu_item_event(menu_bar, item_idx))
            }
            ComponentId::CommitEditMessageButton(commit_idx) => {
                StateUpdate::EditCommitMessage { commit_idx }
            }
            ComponentId::FileViewHeader(file_key) => StateUpdate::SelectItem {
                selection_key: SelectionKey::File(file_key),
                ensure_in_viewport: false,
            },
            ComponentId::SelectableItem(selection_key) => StateUpdate::SelectItem {
                selection_key,
                ensure_in_viewport: false,
            },
            ComponentId::ToggleBox(selection_key) => {
                if self.selection_key == selection_key {
                    StateUpdate::ToggleItem(selection_key)
                } else {
                    StateUpdate::SelectItem {
                        selection_key,
                        ensure_in_viewport: false,
                    }
                }
            }
            ComponentId::ExpandBox(selection_key) => {
                if self.selection_key == selection_key {
                    StateUpdate::ToggleExpandItem(selection_key)
                } else {
                    StateUpdate::SelectItem {
                        selection_key,
                        ensure_in_viewport: false,
                    }
                }
            }
            ComponentId::QuitDialogButton(QuitDialogButtonId::GoBack) => {
                StateUpdate::SetQuitDialog(None)
            }
            ComponentId::QuitDialogButton(QuitDialogButtonId::Quit) => StateUpdate::QuitCancel,
        }
    }

    fn get_menu_item_event(&self, menu_bar: &MenuBar, item_idx: usize) -> Event {
        let MenuBar {
            menus,
            expanded_menu_idx,
        } = menu_bar;
        let menu_idx = match expanded_menu_idx {
            Some(section_idx) => section_idx,
            None => {
                warn!(?item_idx, "Clicking menu item when no menu is expanded");
                return Event::None;
            }
        };
        let menu = match menus.get(*menu_idx) {
            Some(menu) => menu,
            None => {
                warn!(?menu_idx, "Clicking out-of-bounds menu");
                return Event::None;
            }
        };
        let item = match menu.items.get(item_idx) {
            Some(item) => item,
            None => {
                warn!(
                    ?menu_idx,
                    ?item_idx,
                    "Clicking menu bar section item that is out of bounds"
                );
                return Event::None;
            }
        };
        item.event.clone()
    }

    fn toggle_item(&mut self, selection: SelectionKey) -> Result<(), RecordError> {
        if self.state.is_read_only {
            return Ok(());
        }

        match selection {
            SelectionKey::None => {}
            SelectionKey::File(file_key) => {
                let tristate = self.file_tristate(file_key)?;
                let is_checked_new = match tristate {
                    Tristate::False => true,
                    Tristate::Partial | Tristate::True => false,
                };
                self.visit_file(file_key, |file| {
                    file.set_checked(is_checked_new);
                })?;
            }
            SelectionKey::Section(section_key) => {
                let tristate = self.section_tristate(section_key)?;
                let is_checked_new = match tristate {
                    Tristate::False => true,
                    Tristate::Partial | Tristate::True => false,
                };
                self.visit_section(section_key, |section| {
                    section.set_checked(is_checked_new);
                })?;
            }
            SelectionKey::Line(line_key) => {
                self.visit_line(line_key, |line| {
                    line.is_checked = !line.is_checked;
                })?;
            }
        }
        Ok(())
    }

    fn toggle_all(&mut self) {
        if self.state.is_read_only {
            return;
        }

        for file in &mut self.state.files {
            file.toggle_all();
        }
    }

    fn toggle_all_uniform(&mut self) {
        if self.state.is_read_only {
            return;
        }

        let checked = {
            let tristate = self
                .state
                .files
                .iter()
                .map(|file| file.tristate())
                .fold(None, |acc, elem| match (acc, elem) {
                    (None, tristate) => Some(tristate),
                    (Some(acc_tristate), tristate) if acc_tristate == tristate => Some(tristate),
                    _ => Some(Tristate::Partial),
                })
                .unwrap_or(Tristate::False);
            match tristate {
                Tristate::False | Tristate::Partial => true,
                Tristate::True => false,
            }
        };
        for file in &mut self.state.files {
            file.set_checked(checked);
        }
    }

    fn expand_item_ancestors(&mut self, selection: SelectionKey) {
        match selection {
            SelectionKey::None | SelectionKey::File(_) => {}
            SelectionKey::Section(SectionKey {
                commit_idx,
                file_idx,
                section_idx: _,
            }) => {
                self.expanded_items.insert(SelectionKey::File(FileKey {
                    commit_idx,
                    file_idx,
                }));
            }
            SelectionKey::Line(LineKey {
                commit_idx,
                file_idx,
                section_idx,
                line_idx: _,
            }) => {
                self.expanded_items.insert(SelectionKey::File(FileKey {
                    commit_idx,
                    file_idx,
                }));
                self.expanded_items
                    .insert(SelectionKey::Section(SectionKey {
                        commit_idx,
                        file_idx,
                        section_idx,
                    }));
            }
        }
    }

    fn set_expand_item(&mut self, selection: SelectionKey, is_expanded: bool) {
        if is_expanded {
            self.expanded_items.insert(selection);
        } else {
            self.expanded_items.remove(&selection);
        }
    }

    fn toggle_expand_item(&mut self, selection: SelectionKey) -> Result<(), RecordError> {
        match selection {
            SelectionKey::None => {}
            SelectionKey::File(file_key) => {
                if !self.expanded_items.insert(SelectionKey::File(file_key)) {
                    self.expanded_items.remove(&SelectionKey::File(file_key));
                }
            }
            SelectionKey::Section(section_key) => {
                if !self
                    .expanded_items
                    .insert(SelectionKey::Section(section_key))
                {
                    self.expanded_items
                        .remove(&SelectionKey::Section(section_key));
                }
            }
            SelectionKey::Line(_) => {
                // Do nothing.
            }
        }
        Ok(())
    }

    fn expand_initial_items(&mut self) {
        self.expanded_items = self
            .all_selection_keys()
            .into_iter()
            .filter(|selection_key| match selection_key {
                SelectionKey::None | SelectionKey::File(_) | SelectionKey::Line(_) => false,
                SelectionKey::Section(_) => true,
            })
            .collect();
    }

    fn toggle_expand_all(&mut self) -> Result<(), RecordError> {
        let all_selection_keys: HashSet<_> = self.all_selection_keys().into_iter().collect();
        self.expanded_items = if self.expanded_items == all_selection_keys {
            // Select an ancestor file key that will still be visible.
            self.selection_key = match self.selection_key {
                selection_key @ (SelectionKey::None | SelectionKey::File(_)) => selection_key,
                SelectionKey::Section(SectionKey {
                    commit_idx,
                    file_idx,
                    section_idx: _,
                })
                | SelectionKey::Line(LineKey {
                    commit_idx,
                    file_idx,
                    section_idx: _,
                    line_idx: _,
                }) => SelectionKey::File(FileKey {
                    commit_idx,
                    file_idx,
                }),
            };
            Default::default()
        } else {
            all_selection_keys
        };
        Ok(())
    }

    fn unfocus_menu_bar(&mut self) {
        self.expanded_menu_idx = None;
    }

    fn click_menu_header(&mut self, menu_idx: usize) {
        let menu_idx = Some(menu_idx);
        self.expanded_menu_idx = if self.expanded_menu_idx == menu_idx {
            None
        } else {
            menu_idx
        };
    }

    fn click_menu_item(&mut self, event: Event) {
        self.expanded_menu_idx = None;
        self.pending_events.push(event);
    }

    fn edit_commit_message(&mut self, commit_idx: usize) -> Result<(), RecordError> {
        let message = &mut self.state.commits[commit_idx].message;
        let message_str = match message.as_ref() {
            Some(message) => message,
            None => return Ok(()),
        };
        let new_message = {
            match self.input.terminal_kind() {
                TerminalKind::Testing { .. } => {}
                TerminalKind::Crossterm => {
                    Self::clean_up_crossterm()?;
                }
            }
            let result = self.input.edit_commit_message(message_str);
            match self.input.terminal_kind() {
                TerminalKind::Testing { .. } => {}
                TerminalKind::Crossterm => {
                    Self::set_up_crossterm()?;
                }
            }
            result?
        };
        *message = Some(new_message);
        Ok(())
    }

    fn file(&self, file_key: FileKey) -> Result<&File, RecordError> {
        let FileKey {
            commit_idx: _,
            file_idx,
        } = file_key;
        match self.state.files.get(file_idx) {
            Some(file) => Ok(file),
            None => Err(RecordError::Bug(format!(
                "Out-of-bounds file key: {file_key:?}"
            ))),
        }
    }

    fn section(&self, section_key: SectionKey) -> Result<&Section, RecordError> {
        let SectionKey {
            commit_idx,
            file_idx,
            section_idx,
        } = section_key;
        let file = self.file(FileKey {
            commit_idx,
            file_idx,
        })?;
        match file.sections.get(section_idx) {
            Some(section) => Ok(section),
            None => Err(RecordError::Bug(format!(
                "Out-of-bounds section key: {section_key:?}"
            ))),
        }
    }

    fn visit_file<T>(
        &mut self,
        file_key: FileKey,
        f: impl Fn(&mut File) -> T,
    ) -> Result<T, RecordError> {
        let FileKey {
            commit_idx: _,
            file_idx,
        } = file_key;
        match self.state.files.get_mut(file_idx) {
            Some(file) => Ok(f(file)),
            None => Err(RecordError::Bug(format!(
                "Out-of-bounds file key: {file_key:?}"
            ))),
        }
    }

    fn file_tristate(&self, file_key: FileKey) -> Result<Tristate, RecordError> {
        let file = self.file(file_key)?;
        Ok(file.tristate())
    }

    fn file_expanded(&self, file_key: FileKey) -> Tristate {
        let is_expanded = self.expanded_items.contains(&SelectionKey::File(file_key));
        if !is_expanded {
            Tristate::False
        } else {
            let any_section_unexpanded = self
                .file(file_key)
                .unwrap()
                .sections
                .iter()
                .enumerate()
                .any(|(section_idx, section)| {
                    match section {
                        Section::Unchanged { .. }
                        | Section::FileMode { .. }
                        | Section::Binary { .. } => {
                            // Not collapsible/expandable.
                            false
                        }
                        Section::Changed { .. } => {
                            let section_key = SectionKey {
                                commit_idx: file_key.commit_idx,
                                file_idx: file_key.file_idx,
                                section_idx,
                            };
                            !self
                                .expanded_items
                                .contains(&SelectionKey::Section(section_key))
                        }
                    }
                });
            if any_section_unexpanded {
                Tristate::Partial
            } else {
                Tristate::True
            }
        }
    }

    fn visit_section<T>(
        &mut self,
        section_key: SectionKey,
        f: impl Fn(&mut Section) -> T,
    ) -> Result<T, RecordError> {
        let SectionKey {
            commit_idx: _,
            file_idx,
            section_idx,
        } = section_key;
        let file = match self.state.files.get_mut(file_idx) {
            Some(file) => file,
            None => {
                return Err(RecordError::Bug(format!(
                    "Out-of-bounds file for section key: {section_key:?}"
                )));
            }
        };
        match file.sections.get_mut(section_idx) {
            Some(section) => Ok(f(section)),
            None => Err(RecordError::Bug(format!(
                "Out-of-bounds section key: {section_key:?}"
            ))),
        }
    }

    fn section_tristate(&self, section_key: SectionKey) -> Result<Tristate, RecordError> {
        let section = self.section(section_key)?;
        Ok(section.tristate())
    }

    fn visit_line(
        &mut self,
        line_key: LineKey,
        f: impl FnOnce(&mut SectionChangedLine),
    ) -> Result<(), RecordError> {
        let LineKey {
            commit_idx: _,
            file_idx,
            section_idx,
            line_idx,
        } = line_key;
        let section = &mut self.state.files[file_idx].sections[section_idx];
        match section {
            Section::Changed { lines } => {
                let line = &mut lines[line_idx];
                f(line);
                Ok(())
            }
            Section::Unchanged { .. } | Section::FileMode { .. } | Section::Binary { .. } => {
                // Do nothing.
                Ok(())
            }
        }
    }
}

#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
enum ComponentId {
    App,
    AppFiles,
    MenuBar,
    MenuHeader,
    Menu(usize),
    MenuItem(usize),
    CommitMessageView,
    CommitEditMessageButton(usize),
    FileViewHeader(FileKey),
    SelectableItem(SelectionKey),
    ToggleBox(SelectionKey),
    ExpandBox(SelectionKey),
    QuitDialog,
    QuitDialogButton(QuitDialogButtonId),
}

#[derive(Clone, Debug)]
enum TristateIconStyle {
    Check,
    Expand,
}

#[derive(Clone, Debug)]
struct TristateBox<Id> {
    use_unicode: bool,
    id: Id,
    tristate: Tristate,
    icon_style: TristateIconStyle,
    is_focused: bool,
    is_read_only: bool,
}

impl<Id> TristateBox<Id> {
    fn text(&self) -> String {
        let Self {
            use_unicode,
            id: _,
            tristate,
            icon_style,
            is_focused,
            is_read_only,
        } = self;

        let (l, r) = match (is_read_only, is_focused) {
            (true, _) => ("<", ">"),
            (false, false) => ("[", "]"),
            (false, true) => ("(", ")"),
        };

        let inner = match (icon_style, tristate, use_unicode) {
            (TristateIconStyle::Expand, Tristate::False, _) => "+",
            (TristateIconStyle::Expand, Tristate::True, _) => "-",

            (TristateIconStyle::Check | TristateIconStyle::Expand, Tristate::Partial, _) => "~",

            (TristateIconStyle::Check, Tristate::False, _) => " ",
            (TristateIconStyle::Check, Tristate::True, false) => "x",
            (TristateIconStyle::Check, Tristate::True, true) => "\u{00D7}", // Multiplication Sign
        };
        format!("{l}{inner}{r}")
    }
}

impl<Id: Clone + Debug + Eq + Hash> Component for TristateBox<Id> {
    type Id = Id;

    fn id(&self) -> Self::Id {
        self.id.clone()
    }

    fn draw(&self, viewport: &mut Viewport<Self::Id>, x: isize, y: isize) {
        let style = if self.is_read_only {
            Style::default().fg(Color::Gray).add_modifier(Modifier::DIM)
        } else {
            Style::default().add_modifier(Modifier::BOLD)
        };
        let span = Span::styled(self.text(), style);
        viewport.draw_span(x, y, &span);
    }
}

#[allow(dead_code)]
#[derive(Clone, Debug)]
struct AppDebugInfo {
    term_height: usize,
    scroll_offset_y: isize,
    selection_key: SelectionKey,
    selection_key_y: Option<isize>,
    drawn_rects: BTreeMap<ComponentId, DrawnRect>, // sorted for determinism
}

#[derive(Clone, Debug)]
struct AppView<'a> {
    debug_info: Option<AppDebugInfo>,
    menu_bar: MenuBar<'a>,
    commit_view_mode: CommitViewMode,
    commit_views: Vec<CommitView<'a>>,
    quit_dialog: Option<QuitDialog>,
}

impl Component for AppView<'_> {
    type Id = ComponentId;

    fn id(&self) -> Self::Id {
        ComponentId::App
    }

    fn draw(&self, viewport: &mut Viewport<Self::Id>, x: isize, _y: isize) {
        let Self {
            debug_info,
            menu_bar,
            commit_view_mode,
            commit_views,
            quit_dialog,
        } = self;

        if let Some(debug_info) = debug_info {
            viewport.debug(format!("app debug info: {debug_info:#?}"));
        }

        let viewport_rect = viewport.mask_rect();

        let menu_bar_height = 1usize;
        let commit_view_width = match commit_view_mode {
            CommitViewMode::Inline => viewport.rect().width,
            CommitViewMode::Adjacent => {
                const MAX_COMMIT_VIEW_WIDTH: usize = 120;
                MAX_COMMIT_VIEW_WIDTH
                    .min(viewport.rect().width.saturating_sub(CommitView::MARGIN) / 2)
            }
        };
        let commit_views_mask = Mask {
            x: viewport_rect.x,
            y: viewport_rect.y + menu_bar_height.unwrap_isize(),
            width: Some(viewport_rect.width),
            height: None,
        };
        viewport.with_mask(commit_views_mask, |viewport| {
            let mut commit_view_x = 0;
            for commit_view in commit_views {
                let commit_view_mask = Mask {
                    x: commit_views_mask.x + commit_view_x,
                    y: commit_views_mask.y,
                    width: Some(commit_view_width),
                    height: None,
                };
                let commit_view_rect = viewport.with_mask(commit_view_mask, |viewport| {
                    viewport.draw_component(
                        commit_view_x,
                        menu_bar_height.unwrap_isize(),
                        commit_view,
                    )
                });
                commit_view_x += (CommitView::MARGIN
                    + commit_view_mask.apply(commit_view_rect).width)
                    .unwrap_isize();
            }
        });

        viewport.draw_component(x, viewport_rect.y, menu_bar);

        if let Some(quit_dialog) = quit_dialog {
            viewport.draw_component(0, 0, quit_dialog);
        }
    }
}

#[derive(Clone, Debug)]
struct CommitMessageView<'a> {
    commit_idx: usize,
    commit: &'a Commit,
}

impl<'a> Component for CommitMessageView<'a> {
    type Id = ComponentId;

    fn id(&self) -> Self::Id {
        ComponentId::CommitMessageView
    }

    fn draw(&self, viewport: &mut Viewport<Self::Id>, x: isize, y: isize) {
        let Self { commit_idx, commit } = self;
        match commit {
            Commit { message: None } => {}
            Commit {
                message: Some(message),
            } => {
                viewport.draw_blank(Rect {
                    x,
                    y,
                    width: viewport.mask_rect().width,
                    height: 1,
                });
                let y = y + 1;

                let style = Style::default();
                let button_rect = viewport.draw_component(
                    x,
                    y,
                    &Button {
                        id: ComponentId::CommitEditMessageButton(*commit_idx),
                        label: Cow::Borrowed("Edit message"),
                        style,
                        is_focused: false,
                    },
                );
                let divider_rect =
                    viewport.draw_span(button_rect.end_x() + 1, y, &Span::raw(" • "));
                viewport.draw_text(
                    divider_rect.end_x() + 1,
                    y,
                    &Span::styled(
                        Cow::Borrowed({
                            let first_line = match message.split_once('\n') {
                                Some((before, _after)) => before,
                                None => message,
                            };
                            let first_line = first_line.trim();
                            if first_line.is_empty() {
                                "(no message)"
                            } else {
                                first_line
                            }
                        }),
                        style.add_modifier(Modifier::UNDERLINED),
                    ),
                );
                let y = y + 1;

                viewport.draw_blank(Rect {
                    x,
                    y,
                    width: viewport.mask_rect().width,
                    height: 1,
                });
            }
        }
    }
}

#[derive(Clone, Debug)]
struct CommitView<'a> {
    debug_info: Option<&'a AppDebugInfo>,
    commit_message_view: CommitMessageView<'a>,
    file_views: Vec<FileView<'a>>,
}

impl<'a> CommitView<'a> {
    const MARGIN: usize = 1;
}

impl Component for CommitView<'_> {
    type Id = ComponentId;

    fn id(&self) -> Self::Id {
        ComponentId::AppFiles
    }

    fn draw(&self, viewport: &mut Viewport<Self::Id>, x: isize, y: isize) {
        let Self {
            debug_info,
            commit_message_view,
            file_views,
        } = self;

        let commit_message_view_rect = viewport.draw_component(x, y, commit_message_view);
        if file_views.is_empty() {
            let message = "There are no changes to view.";
            let message_rect = centered_rect(
                Rect {
                    x,
                    y,
                    width: viewport.mask_rect().width,
                    height: viewport.mask_rect().height,
                },
                RectSize {
                    width: message.len(),
                    height: 1,
                },
                50,
                50,
            );
            viewport.draw_text(message_rect.x, message_rect.y, &Span::raw(message));
            return;
        }

        let mut y = y;
        y += commit_message_view_rect.height.unwrap_isize();
        for file_view in file_views {
            let file_view_rect = {
                let file_view_mask = Mask {
                    x,
                    y,
                    width: viewport.mask().width,
                    height: None,
                };
                viewport.with_mask(file_view_mask, |viewport| {
                    viewport.draw_component(x, y, file_view)
                })
            };

            // Render a sticky header if necessary.
            let mask = viewport.mask();
            if file_view_rect.y < mask.y
                && mask.y < file_view_rect.y + file_view_rect.height.unwrap_isize()
            {
                viewport.with_mask(
                    Mask {
                        x,
                        y: mask.y,
                        width: Some(viewport.mask_rect().width),
                        height: Some(1),
                    },
                    |viewport| {
                        viewport.draw_component(
                            x,
                            mask.y,
                            &FileViewHeader {
                                file_key: file_view.file_key,
                                path: file_view.path,
                                old_path: file_view.old_path,
                                is_selected: file_view.is_header_selected,
                                toggle_box: file_view.toggle_box.clone(),
                                expand_box: file_view.expand_box.clone(),
                            },
                        );
                    },
                );
            }

            y += file_view_rect.height.unwrap_isize();

            if debug_info.is_some() {
                viewport.debug(format!(
                    "file {} dims: {file_view_rect:?}",
                    file_view.path.to_string_lossy()
                ));
            }
        }
    }
}

#[derive(Clone, Debug)]
struct MenuItem<'a> {
    label: Cow<'a, str>,
    event: Event,
}

#[derive(Clone, Debug)]
struct Menu<'a> {
    label: Cow<'a, str>,
    items: Vec<MenuItem<'a>>,
}

impl Component for Menu<'_> {
    type Id = ComponentId;

    fn id(&self) -> Self::Id {
        ComponentId::MenuHeader
    }

    fn draw(&self, viewport: &mut Viewport<Self::Id>, x: isize, y: isize) {
        let Self { label: _, items } = self;

        let buttons = items
            .iter()
            .enumerate()
            .map(|(i, item)| Button {
                id: ComponentId::MenuItem(i),
                label: Cow::Borrowed(&item.label),
                style: Style::default(),
                is_focused: false,
            })
            .collect::<Vec<_>>();
        let max_width = buttons
            .iter()
            .map(|button| button.width())
            .max()
            .unwrap_or_default();
        let mut y = y;
        for button in buttons {
            viewport.draw_span(
                x,
                y,
                &Span::styled(
                    " ".repeat(max_width),
                    Style::reset().add_modifier(Modifier::REVERSED),
                ),
            );
            viewport.draw_component(x, y, &button);
            y += 1;
        }
    }
}

#[derive(Clone, Debug)]
struct MenuBar<'a> {
    menus: Vec<Menu<'a>>,
    expanded_menu_idx: Option<usize>,
}

impl Component for MenuBar<'_> {
    type Id = ComponentId;

    fn id(&self) -> Self::Id {
        ComponentId::MenuBar
    }

    fn draw(&self, viewport: &mut Viewport<Self::Id>, x: isize, y: isize) {
        let Self {
            menus,
            expanded_menu_idx,
        } = self;

        viewport.draw_blank(viewport.rect().top_row());
        highlight_rect(viewport, viewport.rect().top_row());
        let mut x = x;
        for (i, menu) in menus.iter().enumerate() {
            let menu_header = Button {
                id: ComponentId::Menu(i),
                label: Cow::Borrowed(&menu.label),
                style: Style::default(),
                is_focused: false,
            };
            let rect = viewport.draw_component(x, y, &menu_header);
            if expanded_menu_idx == &Some(i) {
                viewport.draw_component(x, y + 1, menu);
            }
            x += rect.width.unwrap_isize() + 1;
        }
    }
}

#[derive(Clone, Debug)]
struct FileView<'a> {
    debug: bool,
    file_key: FileKey,
    toggle_box: TristateBox<ComponentId>,
    expand_box: TristateBox<ComponentId>,
    is_header_selected: bool,
    old_path: Option<&'a Path>,
    path: &'a Path,
    section_views: Vec<SectionView<'a>>,
}

impl FileView<'_> {
    fn is_expanded(&self) -> bool {
        match self.expand_box.tristate {
            Tristate::False => false,
            Tristate::Partial | Tristate::True => true,
        }
    }
}

impl Component for FileView<'_> {
    type Id = ComponentId;

    fn id(&self) -> Self::Id {
        ComponentId::SelectableItem(SelectionKey::File(self.file_key))
    }

    fn draw(&self, viewport: &mut Viewport<Self::Id>, x: isize, y: isize) {
        let Self {
            debug,
            file_key,
            toggle_box,
            expand_box,
            old_path,
            path,
            section_views,
            is_header_selected,
        } = self;

        let file_view_header_rect = viewport.draw_component(
            x,
            y,
            &FileViewHeader {
                file_key: *file_key,
                path,
                old_path: *old_path,
                is_selected: *is_header_selected,
                toggle_box: toggle_box.clone(),
                expand_box: expand_box.clone(),
            },
        );
        if self.is_expanded() {
            let x = x + 2;
            let mut section_y = y + file_view_header_rect.height.unwrap_isize();
            let expanded_sections: HashSet<usize> = section_views
                .iter()
                .enumerate()
                .filter_map(|(i, view)| {
                    if view.is_expanded() && view.section.is_editable() {
                        return Some(i);
                    }
                    None
                })
                .collect();
            for (i, section_view) in section_views.iter().enumerate() {
                // Skip this section if it is an un-editable context section and
                // none of the editable sections surrounding it are expanded.
                let context_section = !section_view.section.is_editable();
                let prev_is_collapsed = i == 0 || !expanded_sections.contains(&(i - 1));
                let next_is_collapsed = !expanded_sections.contains(&(i + 1));
                if context_section && prev_is_collapsed && next_is_collapsed {
                    continue;
                }

                let section_rect = viewport.draw_component(x, section_y, section_view);
                section_y += section_rect.height.unwrap_isize();

                if *debug {
                    viewport.debug(format!("section dims: {section_rect:?}",));
                }
            }
        }
    }
}

struct FileViewHeader<'a> {
    file_key: FileKey,
    path: &'a Path,
    old_path: Option<&'a Path>,
    is_selected: bool,
    toggle_box: TristateBox<ComponentId>,
    expand_box: TristateBox<ComponentId>,
}

impl Component for FileViewHeader<'_> {
    type Id = ComponentId;

    fn id(&self) -> Self::Id {
        let Self {
            file_key,
            path: _,
            old_path: _,
            is_selected: _,
            toggle_box: _,
            expand_box: _,
        } = self;
        ComponentId::FileViewHeader(*file_key)
    }

    fn draw(&self, viewport: &mut Viewport<Self::Id>, x: isize, y: isize) {
        let Self {
            file_key: _,
            path,
            old_path,
            is_selected,
            toggle_box,
            expand_box,
        } = self;

        // Draw expand box at end of line.
        let expand_box_width = expand_box.text().width().unwrap_isize();
        let expand_box_rect = viewport.draw_component(
            viewport.mask_rect().end_x() - expand_box_width,
            y,
            expand_box,
        );

        viewport.with_mask(
            Mask {
                x,
                y,
                width: Some((expand_box_rect.x - x).clamp_into_usize()),
                height: Some(1),
            },
            |viewport| {
                viewport.draw_blank(Rect {
                    x,
                    y,
                    width: viewport.mask_rect().width,
                    height: 1,
                });
                let toggle_box_rect = viewport.draw_component(x, y, toggle_box);
                viewport.draw_text(
                    x + toggle_box_rect.width.unwrap_isize() + 1,
                    y,
                    &Span::styled(
                        format!(
                            "{}{}",
                            match old_path {
                                Some(old_path) => format!("{} => ", old_path.to_string_lossy()),
                                None => String::new(),
                            },
                            path.to_string_lossy(),
                        ),
                        if *is_selected {
                            Style::default().fg(Color::Blue)
                        } else {
                            Style::default()
                        },
                    ),
                );
            },
        );

        if *is_selected {
            highlight_rect(
                viewport,
                Rect {
                    x: viewport.mask_rect().x,
                    y,
                    width: viewport.mask_rect().width,
                    height: 1,
                },
            );
        }
    }
}

#[derive(Clone, Debug)]
enum SectionSelection {
    SectionHeader,
    ChangedLine(usize),
}

#[derive(Clone, Debug)]
struct SectionView<'a> {
    use_unicode: bool,
    is_read_only: bool,
    section_key: SectionKey,
    toggle_box: TristateBox<ComponentId>,
    expand_box: TristateBox<ComponentId>,
    selection: Option<SectionSelection>,
    total_num_sections: usize,
    editable_section_num: usize,
    total_num_editable_sections: usize,
    section: &'a Section<'a>,
    line_start_num: usize,
}

impl SectionView<'_> {
    fn is_expanded(&self) -> bool {
        match self.expand_box.tristate {
            Tristate::False => false,
            Tristate::Partial => {
                // Shouldn't happen.
                true
            }
            Tristate::True => true,
        }
    }
}

impl Component for SectionView<'_> {
    type Id = ComponentId;

    fn id(&self) -> Self::Id {
        ComponentId::SelectableItem(SelectionKey::Section(self.section_key))
    }

    fn draw(&self, viewport: &mut Viewport<Self::Id>, x: isize, y: isize) {
        let Self {
            use_unicode,
            is_read_only,
            section_key,
            toggle_box,
            expand_box,
            selection,
            total_num_sections,
            editable_section_num,
            total_num_editable_sections,
            section,
            line_start_num,
        } = self;
        viewport.draw_blank(Rect {
            x,
            y,
            width: viewport.mask_rect().width,
            height: 1,
        });

        let SectionKey {
            commit_idx,
            file_idx,
            section_idx,
        } = *section_key;
        match section {
            Section::Unchanged { lines } => {
                if lines.is_empty() {
                    return;
                }

                let lines: Vec<_> = lines.iter().enumerate().collect();
                let is_first_section = section_idx == 0;
                let is_last_section = section_idx + 1 == *total_num_sections;
                let before_ellipsis_lines = &lines[..min(NUM_CONTEXT_LINES, lines.len())];
                let after_ellipsis_lines = &lines[lines.len().saturating_sub(NUM_CONTEXT_LINES)..];

                match (before_ellipsis_lines, after_ellipsis_lines) {
                    ([.., (last_before_idx, _)], [(first_after_idx, _), ..])
                        if *last_before_idx + 1 >= *first_after_idx
                            && !is_first_section
                            && !is_last_section =>
                    {
                        let first_before_idx = before_ellipsis_lines.first().unwrap().0;
                        let last_after_idx = after_ellipsis_lines.last().unwrap().0;
                        let overlapped_lines = &lines[first_before_idx..=last_after_idx];
                        let overlapped_lines = if is_first_section {
                            &overlapped_lines
                                [overlapped_lines.len().saturating_sub(NUM_CONTEXT_LINES)..]
                        } else if is_last_section {
                            &overlapped_lines[..lines.len().min(NUM_CONTEXT_LINES)]
                        } else {
                            overlapped_lines
                        };
                        for (dy, (line_idx, line)) in overlapped_lines.iter().enumerate() {
                            let line_view = SectionLineView {
                                line_key: LineKey {
                                    commit_idx,
                                    file_idx,
                                    section_idx,
                                    line_idx: *line_idx,
                                },
                                inner: SectionLineViewInner::Unchanged {
                                    line: line.as_ref(),
                                    line_num: line_start_num + line_idx,
                                },
                            };
                            viewport.draw_component(x + 2, y + dy.unwrap_isize(), &line_view);
                        }
                        return;
                    }
                    _ => {}
                };

                let mut dy = 0;
                if !is_first_section {
                    for (line_idx, line) in before_ellipsis_lines {
                        let line_view = SectionLineView {
                            line_key: LineKey {
                                commit_idx,
                                file_idx,
                                section_idx,
                                line_idx: *line_idx,
                            },
                            inner: SectionLineViewInner::Unchanged {
                                line: line.as_ref(),
                                line_num: line_start_num + line_idx,
                            },
                        };
                        viewport.draw_component(x + 2, y + dy, &line_view);
                        dy += 1;
                    }
                }

                let should_render_ellipsis = lines.len() > NUM_CONTEXT_LINES;
                if should_render_ellipsis {
                    let ellipsis = if *use_unicode {
                        "\u{22EE}" // Vertical Ellipsis
                    } else {
                        ":"
                    };
                    viewport.draw_span(
                        x + 6, // align with line numbering
                        y + dy,
                        &Span::styled(ellipsis, Style::default().add_modifier(Modifier::DIM)),
                    );
                    dy += 1;
                }

                if !is_last_section {
                    for (line_idx, line) in after_ellipsis_lines {
                        let line_view = SectionLineView {
                            line_key: LineKey {
                                commit_idx,
                                file_idx,
                                section_idx,
                                line_idx: *line_idx,
                            },
                            inner: SectionLineViewInner::Unchanged {
                                line: line.as_ref(),
                                line_num: line_start_num + line_idx,
                            },
                        };
                        viewport.draw_component(x + 2, y + dy, &line_view);
                        dy += 1;
                    }
                }
            }

            Section::Changed { lines } => {
                // Draw expand box at end of line.
                let expand_box_width = expand_box.text().width().unwrap_isize();
                let expand_box_rect = viewport.draw_component(
                    viewport.mask_rect().width.unwrap_isize() - expand_box_width,
                    y,
                    expand_box,
                );

                // Draw section header.
                viewport.with_mask(
                    Mask {
                        x,
                        y,
                        width: Some((expand_box_rect.x - x).clamp_into_usize()),
                        height: Some(1),
                    },
                    |viewport| {
                        let toggle_box_rect = viewport.draw_component(x, y, toggle_box);
                        viewport.draw_text(
                            x + toggle_box_rect.width.unwrap_isize() + 1,
                            y,
                            &Span::styled(
                                format!(
                                    "Section {editable_section_num}/{total_num_editable_sections}"
                                ),
                                Style::default(),
                            ),
                        )
                    },
                );

                match selection {
                    Some(SectionSelection::SectionHeader) => {
                        highlight_rect(
                            viewport,
                            Rect {
                                x: viewport.mask_rect().x,
                                y,
                                width: viewport.mask_rect().width,
                                height: 1,
                            },
                        );
                    }
                    Some(SectionSelection::ChangedLine(_)) | None => {}
                }

                if self.is_expanded() {
                    // Draw changed lines.
                    let y = y + 1;
                    for (line_idx, line) in lines.iter().enumerate() {
                        let SectionChangedLine {
                            is_checked,
                            change_type,
                            line,
                        } = line;
                        let is_focused = match selection {
                            Some(SectionSelection::ChangedLine(selected_line_idx)) => {
                                line_idx == *selected_line_idx
                            }
                            Some(SectionSelection::SectionHeader) | None => false,
                        };
                        let line_key = LineKey {
                            commit_idx,
                            file_idx,
                            section_idx,
                            line_idx,
                        };
                        let toggle_box = TristateBox {
                            use_unicode: *use_unicode,
                            id: ComponentId::ToggleBox(SelectionKey::Line(line_key)),
                            icon_style: TristateIconStyle::Check,
                            tristate: Tristate::from(*is_checked),
                            is_focused,
                            is_read_only: *is_read_only,
                        };
                        let line_view = SectionLineView {
                            line_key,
                            inner: SectionLineViewInner::Changed {
                                toggle_box,
                                change_type: *change_type,
                                line: line.as_ref(),
                            },
                        };
                        let y = y + line_idx.unwrap_isize();
                        viewport.draw_component(x + 2, y, &line_view);
                        if is_focused {
                            highlight_rect(
                                viewport,
                                Rect {
                                    x: viewport.mask_rect().x,
                                    y,
                                    width: viewport.mask_rect().width,
                                    height: 1,
                                },
                            );
                        }
                    }
                }
            }

            Section::FileMode {
                is_checked,
                before,
                after,
            } => {
                let is_focused = match selection {
                    Some(SectionSelection::SectionHeader) => true,
                    Some(SectionSelection::ChangedLine(_)) | None => false,
                };
                let section_key = SectionKey {
                    commit_idx,
                    file_idx,
                    section_idx,
                };
                let selection_key = SelectionKey::Section(section_key);
                let toggle_box = TristateBox {
                    use_unicode: *use_unicode,
                    id: ComponentId::ToggleBox(selection_key),
                    icon_style: TristateIconStyle::Check,
                    tristate: Tristate::from(*is_checked),
                    is_focused,
                    is_read_only: *is_read_only,
                };
                let toggle_box_rect = viewport.draw_component(x, y, &toggle_box);
                let x = x + toggle_box_rect.width.unwrap_isize() + 1;
                let text = format!("File mode changed from {before} to {after}");
                viewport.draw_text(x, y, &Span::styled(text, Style::default().fg(Color::Blue)));
                if is_focused {
                    highlight_rect(
                        viewport,
                        Rect {
                            x: viewport.mask_rect().x,
                            y,
                            width: viewport.mask_rect().width,
                            height: 1,
                        },
                    );
                }
            }

            Section::Binary {
                is_checked,
                old_description,
                new_description,
            } => {
                let is_focused = match selection {
                    Some(SectionSelection::SectionHeader) => true,
                    Some(SectionSelection::ChangedLine(_)) | None => false,
                };
                let section_key = SectionKey {
                    commit_idx,
                    file_idx,
                    section_idx,
                };
                let toggle_box = TristateBox {
                    use_unicode: *use_unicode,
                    id: ComponentId::ToggleBox(SelectionKey::Section(section_key)),
                    icon_style: TristateIconStyle::Check,
                    tristate: Tristate::from(*is_checked),
                    is_focused,
                    is_read_only: *is_read_only,
                };
                let toggle_box_rect = viewport.draw_component(x, y, &toggle_box);
                let x = x + toggle_box_rect.width.unwrap_isize() + 1;

                let text = {
                    let mut result =
                        vec![if old_description.is_some() || new_description.is_some() {
                            "binary contents:"
                        } else {
                            "binary contents"
                        }
                        .to_string()];
                    let description: Vec<_> = [old_description, new_description]
                        .iter()
                        .copied()
                        .flatten()
                        .map(|s| s.as_ref())
                        .collect();
                    result.push(description.join(" -> "));
                    format!("({})", result.join(" "))
                };
                viewport.draw_text(x, y, &Span::styled(text, Style::default().fg(Color::Blue)));

                if is_focused {
                    highlight_rect(
                        viewport,
                        Rect {
                            x: viewport.mask_rect().x,
                            y,
                            width: viewport.mask_rect().width,
                            height: 1,
                        },
                    );
                }
            }
        }
    }
}

#[derive(Clone, Debug)]
enum SectionLineViewInner<'a> {
    Unchanged {
        line: &'a str,
        line_num: usize,
    },
    Changed {
        toggle_box: TristateBox<ComponentId>,
        change_type: ChangeType,
        line: &'a str,
    },
}

#[derive(Clone, Debug)]
struct SectionLineView<'a> {
    line_key: LineKey,
    inner: SectionLineViewInner<'a>,
}

impl Component for SectionLineView<'_> {
    type Id = ComponentId;

    fn id(&self) -> Self::Id {
        ComponentId::SelectableItem(SelectionKey::Line(self.line_key))
    }

    fn draw(&self, viewport: &mut Viewport<Self::Id>, x: isize, y: isize) {
        const NEWLINE_ICON: &str = "⏎";
        let Self { line_key: _, inner } = self;
        viewport.draw_blank(Rect {
            x: viewport.mask_rect().x,
            y,
            width: viewport.mask_rect().width,
            height: 1,
        });
        match inner {
            SectionLineViewInner::Unchanged { line, line_num } => {
                let style = Style::default().add_modifier(Modifier::DIM);
                // Pad the number in 5 columns because that will align the
                // beginning of the actual text with the `+`/`-` of the changed
                // lines.
                let line_num_rect =
                    viewport.draw_span(x, y, &Span::styled(format!("{line_num:5} "), style));
                let (line, line_end) = match line.strip_suffix('\n') {
                    Some(line) => (
                        Span::styled(line, style),
                        Some(Span::styled(
                            NEWLINE_ICON,
                            Style::default().fg(Color::DarkGray),
                        )),
                    ),
                    None => (Span::styled(*line, style), None),
                };
                let line_rect = viewport.draw_text(
                    line_num_rect.x + line_num_rect.width.unwrap_isize(),
                    line_num_rect.y,
                    &line,
                );
                if let Some(line_end) = line_end {
                    viewport.draw_span(line_rect.x + line_rect.width.unwrap_isize(), y, &line_end);
                }
            }

            SectionLineViewInner::Changed {
                toggle_box,
                change_type,
                line,
            } => {
                let toggle_box_rect = viewport.draw_component(x, y, toggle_box);
                let x = x + toggle_box_rect.width.unwrap_isize() + 1;

                let (change_type_text, style) = match change_type {
                    ChangeType::Added => ("+ ", Style::default().fg(Color::Green)),
                    ChangeType::Removed => ("- ", Style::default().fg(Color::Red)),
                };
                viewport.draw_span(x, y, &Span::styled(change_type_text, style));
                let x = x + change_type_text.width().unwrap_isize();
                let (line, line_end) = match line.strip_suffix('\n') {
                    Some(line) => (
                        Span::styled(line, style),
                        Some(Span::styled(
                            NEWLINE_ICON,
                            Style::default().fg(Color::DarkGray),
                        )),
                    ),
                    None => (Span::styled(*line, style), None),
                };
                let line_rect = viewport.draw_text(x, y, &line);
                if let Some(line_end) = line_end {
                    viewport.draw_span(line_rect.x + line_rect.width.unwrap_isize(), y, &line_end);
                }
            }
        }
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
struct QuitDialog {
    num_commit_messages: usize,
    num_changed_files: usize,
    focused_button: QuitDialogButtonId,
}

impl Component for QuitDialog {
    type Id = ComponentId;

    fn id(&self) -> Self::Id {
        ComponentId::QuitDialog
    }

    fn draw(&self, viewport: &mut Viewport<Self::Id>, _x: isize, _y: isize) {
        let Self {
            num_commit_messages,
            num_changed_files,
            focused_button,
        } = self;
        let title = "Quit";
        let alert_items = {
            let mut result = Vec::new();
            if *num_commit_messages > 0 {
                result.push(format!(
                    "{num_commit_messages} {}",
                    if *num_commit_messages == 1 {
                        "message"
                    } else {
                        "messages"
                    }
                ));
            }
            if *num_changed_files > 0 {
                result.push(format!(
                    "{num_changed_files} {}",
                    if *num_changed_files == 1 {
                        "file"
                    } else {
                        "files"
                    }
                ));
            }
            result
        };
        let alert = if alert_items.is_empty() {
            // Shouldn't happen.
            "".to_string()
        } else {
            format!("You have changes to {}. ", alert_items.join(" and "))
        };
        let body = format!("{alert}Are you sure you want to quit?",);

        let quit_button = Button {
            id: ComponentId::QuitDialogButton(QuitDialogButtonId::Quit),
            label: Cow::Borrowed("Quit"),
            style: Style::default(),
            is_focused: match focused_button {
                QuitDialogButtonId::Quit => true,
                QuitDialogButtonId::GoBack => false,
            },
        };
        let go_back_button = Button {
            id: ComponentId::QuitDialogButton(QuitDialogButtonId::GoBack),
            label: Cow::Borrowed("Go Back"),
            style: Style::default(),
            is_focused: match focused_button {
                QuitDialogButtonId::GoBack => true,
                QuitDialogButtonId::Quit => false,
            },
        };
        let buttons = [quit_button, go_back_button];

        let dialog = Dialog {
            id: ComponentId::QuitDialog,
            title: Cow::Borrowed(title),
            body: Cow::Owned(body),
            buttons: &buttons,
        };
        viewport.draw_component(0, 0, &dialog);
    }
}

struct Button<'a, Id> {
    id: Id,
    label: Cow<'a, str>,
    style: Style,
    is_focused: bool,
}

impl<'a, Id> Button<'a, Id> {
    fn span(&self) -> Span {
        let Self {
            id: _,
            label,
            style,
            is_focused,
        } = self;
        if *is_focused {
            Span::styled(format!("({label})"), style.add_modifier(Modifier::REVERSED))
        } else {
            Span::styled(format!("[{label}]"), *style)
        }
    }

    fn width(&self) -> usize {
        self.span().width()
    }
}

impl<Id: Clone + Debug + Eq + Hash> Component for Button<'_, Id> {
    type Id = Id;

    fn id(&self) -> Self::Id {
        self.id.clone()
    }

    fn draw(&self, viewport: &mut Viewport<Self::Id>, x: isize, y: isize) {
        let span = self.span();
        viewport.draw_span(x, y, &span);
    }
}

struct Dialog<'a, Id> {
    id: Id,
    title: Cow<'a, str>,
    body: Cow<'a, str>,
    buttons: &'a [Button<'a, Id>],
}

impl<Id: Clone + Debug + Eq + Hash> Component for Dialog<'_, Id> {
    type Id = Id;

    fn id(&self) -> Self::Id {
        self.id.clone()
    }

    fn draw(&self, viewport: &mut Viewport<Self::Id>, _x: isize, _y: isize) {
        let Self {
            id: _,
            title,
            body,
            buttons,
        } = self;
        let rect = {
            let border_size = 2;
            let rect = centered_rect(
                viewport.rect(),
                RectSize {
                    // FIXME: we might want to limit the width of the text and
                    // let `Paragraph` wrap it.
                    width: body.width() + border_size,
                    height: 1 + border_size,
                },
                60,
                20,
            );

            let paragraph = Paragraph::new(body.as_ref()).block(
                Block::default()
                    .title(title.as_ref())
                    .borders(Borders::all()),
            );
            let tui_rect = viewport.translate_rect(rect);
            viewport.draw_widget(tui_rect, Clear);
            viewport.draw_widget(tui_rect, paragraph);

            rect
        };

        let mut bottom_x = rect.x + rect.width.unwrap_isize() - 1;
        let bottom_y = rect.y + rect.height.unwrap_isize() - 1;
        for button in buttons.iter() {
            bottom_x -= button.width().unwrap_isize();
            let button_rect = viewport.draw_component(bottom_x, bottom_y, button);
            bottom_x = button_rect.x - 1;
        }
    }
}

fn highlight_rect<Id: Clone + Debug + Eq + Hash>(viewport: &mut Viewport<Id>, rect: Rect) {
    viewport.set_style(rect, Style::default().add_modifier(Modifier::REVERSED));
}

#[cfg(test)]
mod tests {
    use std::borrow::Cow;

    use crate::helpers::TestingInput;

    use super::*;

    use assert_matches::assert_matches;

    #[test]
    fn test_event_source_testing() {
        let mut event_source = TestingInput::new(80, 24, [Event::QuitCancel]);
        assert_matches!(
            event_source.next_events().unwrap().as_slice(),
            &[Event::QuitCancel]
        );
        assert_matches!(
            event_source.next_events().unwrap().as_slice(),
            &[Event::None]
        );
    }

    #[test]
    fn test_quit_returns_error() {
        let state = RecordState::default();
        let mut input = TestingInput::new(80, 24, [Event::QuitCancel]);
        let recorder = Recorder::new(state, &mut input);
        assert_matches!(recorder.run(), Err(RecordError::Cancelled));

        let state = RecordState {
            is_read_only: false,
            commits: vec![Commit::default(), Commit::default()],
            files: vec![File {
                old_path: None,
                path: Cow::Borrowed(Path::new("foo/bar")),
                file_mode: None,
                sections: Default::default(),
            }],
        };
        let mut input = TestingInput::new(80, 24, [Event::QuitAccept]);
        let recorder = Recorder::new(state.clone(), &mut input);
        assert_eq!(recorder.run().unwrap(), state);
    }
}