croft-software 0.2.232

VSCode-style TUI written in Rust
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
//! How the editor draws a buffer: minimap, folding, wrap, gutter, scrolling
//! and inline decorations.

use super::*;

#[test]
fn minimap_rgba_paints_chars_skips_whitespace() {
    let mut e = crate::widgets::editor::Editor::new();
    // Two leading spaces then a glyph: indentation must read as bg, the glyph
    // in fg. Second (blank) line keeps the file at 2 rows so each maps to one
    // pixel row in a height-2 canvas.
    e.lines = vec![String::from("  x"), String::new()];
    let bg = (0u8, 0, 0);
    let fg = (200u8, 200, 200);
    let buf = e.minimap_rgba(4, 2, 2, bg, fg);
    let px = |x: u32, y: u32| {
        let i = ((y * 4 + x) * 4) as usize;
        (buf[i], buf[i + 1], buf[i + 2])
    };
    assert_eq!(px(0, 0), bg, "indentation stays background");
    assert_eq!(px(1, 0), bg, "indentation stays background");
    assert_eq!(px(2, 0), fg, "the glyph is painted in the default fg");
}

#[test]
fn minimap_goto_moves_the_cursor() {
    // The editor force-follows the cursor on render, so minimap navigation must
    // move the caret to the target line or the scroll would snap straight back
    // (the bug behind "clicking the minimap does nothing").
    let mut e = crate::widgets::editor::Editor::new();
    e.lines = (0..200).map(|i| format!("line {i}")).collect();
    e.goto_line_centered(100);
    assert_eq!(e.cursor_row, 100, "caret jumps to the clicked line");
    assert!(e.scroll <= 100, "viewport scrolls toward the target");
}

#[test]
fn minimap_short_file_does_not_stretch() {
    // Two lines into a tall (h=10) canvas with content_h=4: the lines occupy
    // the top 4 rows; the rest of the strip stays background (no stretching a
    // short file down the whole column).
    let mut e = crate::widgets::editor::Editor::new();
    e.lines = vec![String::from("x"), String::from("y")];
    let bg = (0u8, 0, 0);
    let fg = (200u8, 200, 200);
    let buf = e.minimap_rgba(1, 10, 4, bg, fg);
    let px = |y: u32| {
        let i = (y * 4) as usize;
        (buf[i], buf[i + 1], buf[i + 2])
    };
    assert_eq!(px(0), fg, "first line sits at the top");
    assert_eq!(
        px(8),
        bg,
        "rows past the content stay background, not stretched"
    );
}

#[test]
fn minimap_viewport_box_lightens_visible_rows_only() {
    // 1px-wide, 4px-tall black raster; viewport = top 2 of 4 lines.
    let base = vec![0u8; 4 * 4];
    let out = composite_minimap_viewport(
        &base,
        1,
        4,
        MinimapOverlay {
            top: 0,
            rows: 2,
            total: 4,
            light: false,
            selection: None,
            sel_rgb: (0, 0, 0),
            content_h: 4,
        },
    );
    let row = |y: usize| out[y * 4]; // R channel
    assert!(row(0) > 0, "a visible row is lightened toward white");
    assert!(row(1) > 0, "a visible row is lightened toward white");
    assert_eq!(row(3), 0, "an off-screen row is untouched");
}

#[test]
fn minimap_selection_band_tints_selected_rows() {
    // 1px-wide, 4px-tall black raster; rows 2..=3 selected in red, viewport is
    // the top row only, so the selection band shows on its own.
    let base = vec![0u8; 4 * 4];
    let out = composite_minimap_viewport(
        &base,
        1,
        4,
        MinimapOverlay {
            top: 0,
            rows: 1,
            total: 4,
            light: false,
            selection: Some((2, 3)),
            sel_rgb: (255, 0, 0),
            content_h: 4,
        },
    );
    let r = |y: usize| out[y * 4];
    assert!(r(2) > 0, "selected row picks up the selection color");
    assert!(r(3) > 0, "selected row picks up the selection color");
}

#[test]
fn minimap_rgba_to_png_roundtrips() {
    let png = rgba_to_png(vec![1u8; 2 * 2 * 4], 2, 2).expect("encode");
    assert_eq!(
        &png[1..4],
        b"PNG",
        "emits a PNG the inline-image path can use"
    );
}

/// #1544 negative: the line number and the text body keep their clicks:
/// the number selects its line (#1570), the text moves the caret, and
/// neither sets a breakpoint.
#[test]
fn a_click_on_the_line_number_or_the_text_sets_no_breakpoint() {
    let (mut app, _tmp, f) = app_with_painted_file("l1\nl2\nl3\nl4\nl5\n");
    let number = app.editor.last_inner.x + 2;
    let text_x = app.editor.last_inner.x + app.editor.last_gutter_width + 1;
    let (row2, row3) = (app.editor.last_inner.y + 2, app.editor.last_inner.y + 3);
    click_and_release(&mut app, number, row2);
    assert_eq!(
        app.editor.selection.map(|s| s.normalised()),
        Some(((2, 0), (3, 0))),
        "the number click selects its line"
    );
    app.editor_click.clear();
    click_and_release(&mut app, text_x + 1, row3);
    assert_eq!(app.editor.cursor_row, 3, "the text click moves the caret");
    assert!(app.editor.breakpoint_lines(&f).is_empty());
}

/// #1570: a third click on the same cell inside the double-click window
/// selects the whole line, newline included, so typing replaces it. It used
/// to start over as a single click and drop the word the double selected.
/// Holding the third press and dragging extends the selection by lines.
#[test]
fn a_triple_click_selects_the_line_and_a_drag_extends_it_by_lines() {
    use crossterm::event::{MouseButton, MouseEventKind};
    let (mut app, _tmp, _f) = app_with_painted_file("def f():\n    return 1\n    pass\n");
    let col = app.editor.last_inner.x + app.editor.last_gutter_width + 1 + 6;
    let row = app.editor.last_inner.y + 1;
    click_and_release(&mut app, col, row);
    click_and_release(&mut app, col, row);
    assert_eq!(
        app.editor.selection.map(|s| s.normalised()),
        Some(((1, 4), (1, 10))),
        "the double selects `return`"
    );
    click_and_release(&mut app, col, row);
    assert_eq!(
        app.editor.selection.map(|s| s.normalised()),
        Some(((1, 0), (2, 0))),
        "the triple selects line 2 through the start of line 3"
    );
    app.handle_key(key(KeyCode::Char('Z'), KeyModifiers::NONE))
        .unwrap();
    assert_eq!(app.editor.lines, ["def f():", "Z    pass"]);

    let (mut app, _tmp, _f) = app_with_painted_file("def f():\n    return 1\n    pass\n");
    click_and_release(&mut app, col, row);
    click_and_release(&mut app, col, row);
    app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), col, row));
    app.handle_mouse(mouse(MouseEventKind::Drag(MouseButton::Left), col, row + 1));
    app.handle_mouse(mouse(MouseEventKind::Up(MouseButton::Left), col, row + 1));
    assert_eq!(
        app.editor.selection.map(|s| s.normalised()),
        Some(((1, 0), (2, 8))),
        "the drag takes whole lines 2 and 3, the last to its end"
    );
}

/// #1570: a press on line number 2 selects that line through the start of
/// line 3, and a drag down or up the numbers selects whole lines. It used to
/// put the caret at column 1.
#[test]
fn a_line_number_press_selects_the_line_and_a_drag_selects_lines() {
    use crossterm::event::{MouseButton, MouseEventKind};
    let (mut app, _tmp, _f) = app_with_painted_file("l1\nl2\nl3\nl4\nl5\n");
    let number = app.editor.last_inner.x + 2;
    let y = app.editor.last_inner.y;
    click_and_release(&mut app, number, y + 1);
    assert_eq!(
        app.editor.selection.map(|s| s.normalised()),
        Some(((1, 0), (2, 0)))
    );
    // Down from line 2 to line 4, then up from line 4 to line 1, the caret
    // at the end the pointer went to.
    for (from, to, want, caret) in [(1, 3, ((1, 0), (4, 0)), 4), (3, 0, ((0, 0), (4, 0)), 0)] {
        app.handle_mouse(mouse(
            MouseEventKind::Down(MouseButton::Left),
            number,
            y + from,
        ));
        app.handle_mouse(mouse(
            MouseEventKind::Drag(MouseButton::Left),
            number,
            y + to,
        ));
        app.handle_mouse(mouse(MouseEventKind::Up(MouseButton::Left), number, y + to));
        assert_eq!(app.editor.selection.map(|s| s.normalised()), Some(want));
        assert_eq!(app.editor.cursor_row, caret, "{from}->{to}");
    }
}

#[test]
fn dragging_line_numbers_into_the_explorer_does_not_change_the_tree_selection() {
    use crossterm::event::{MouseButton, MouseEventKind};
    let tmp = tempfile::tempdir().unwrap();
    let f = tmp.path().join("a.txt");
    std::fs::write(&f, "l1\nl2\nl3\nl4\n").unwrap();
    std::fs::write(tmp.path().join("b.txt"), "b").unwrap();
    std::fs::write(tmp.path().join("c.txt"), "c").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&f).unwrap();
    draw(&mut app, 120, 40);

    app.tree.select(0);
    let number = app.editor.last_inner.x + 2;
    let y = app.editor.last_inner.y;
    let tree_col = app.tree.last_inner.x + 2;
    let tree_row = app.tree.last_inner.y + 2;
    assert!(
        app.tree.node_at_y(tree_row).is_some_and(|i| i != 0),
        "precondition: target tree row must name a different node than index 0"
    );

    app.handle_mouse(mouse(
        MouseEventKind::Down(MouseButton::Left),
        number,
        y + 1,
    ));
    app.handle_mouse(mouse(
        MouseEventKind::Drag(MouseButton::Left),
        tree_col,
        tree_row,
    ));
    assert_eq!(
        app.tree.selected, 0,
        "an editor line-number drag crossing into Explorer must not move the tree selection"
    );
    app.handle_mouse(mouse(
        MouseEventKind::Up(MouseButton::Left),
        tree_col,
        tree_row,
    ));
    assert_eq!(
        app.editor.selection.map(|s| s.normalised()),
        Some(((1, 0), (2, 0)))
    );
    assert!(app.gesture.is_none());
}

/// #1570 negative: only the number's own columns select a line. A press on
/// the blank chevron cell of a line with no fold, on the spacer before the
/// change bar, or in a gutter with line numbers off still puts the caret at
/// column 1 and selects nothing.
#[test]
fn only_the_line_number_columns_select_the_line() {
    use crate::widgets::editor::LineNumbers;
    let (mut app, _tmp, _f) = app_with_painted_file("l1\nl2\nl3\n");
    let x = app.editor.last_inner.x;
    let row = app.editor.last_inner.y + 1;
    let spacer = x + app.editor.last_gutter_width - 1;
    let selected = |app: &App| app.editor.selection.map(|s| s.normalised());
    for col in [x + 1, spacer] {
        app.editor_click.clear();
        click_and_release(&mut app, col, row);
        assert_eq!(selected(&app), None, "column {col} selects nothing");
        assert_eq!((app.editor.cursor_row, app.editor.cursor_col), (1, 0));
    }
    app.editor_click.clear();
    click_and_release(&mut app, x + 2, row);
    assert_eq!(selected(&app), Some(((1, 0), (2, 0))), "the number does");

    app.editor.line_numbers = LineNumbers::Off;
    draw(&mut app, 100, 30);
    app.editor_click.clear();
    click_and_release(&mut app, x + 2, row + 1);
    assert_eq!(selected(&app), None, "no numbers, no line selection");
    assert_eq!((app.editor.cursor_row, app.editor.cursor_col), (2, 0));
}

/// #1544 negative: the fold chevron still folds, and a lane click past the
/// last line or with Shift held sets nothing.
#[test]
fn the_chevron_still_folds_and_off_line_or_shift_lane_clicks_set_nothing() {
    use crossterm::event::{MouseButton, MouseEventKind};
    let (mut app, _tmp, f) = app_with_painted_file("def f():\n    a = 1\n    b = 2\n");
    let x = app.editor.last_inner.x;
    let y = app.editor.last_inner.y;
    click_and_release(&mut app, x + 1, y);
    assert!(app.editor.is_line_hidden(1), "the chevron folds the body");
    assert!(app.editor.breakpoint_lines(&f).is_empty());
    app.editor_click.clear();
    click_and_release(&mut app, x, y + 20);
    assert!(app.editor.breakpoint_lines(&f).is_empty(), "no line there");
    app.editor_click.clear();
    let mut shift = mouse(MouseEventKind::Down(MouseButton::Left), x, y);
    shift.modifiers = KeyModifiers::SHIFT;
    app.handle_mouse(shift);
    assert!(
        app.editor.breakpoint_lines(&f).is_empty(),
        "Shift+click keeps extending the selection"
    );
}

/// #1563: with word wrap on, the edges are the first and last wrapped rows:
/// Down on the last row goes to the end of the line, Up on the first row to
/// its start.
#[test]
fn wrapped_arrows_reach_the_ends_of_the_first_and_last_rows() {
    use ratatui::widgets::Widget as _;
    let (_tmp, mut app) = app_with_run_script();
    let last = app.editor.lines.len() - 1;
    let long = "done # ".to_string() + &"word ".repeat(30);
    app.editor.lines[last] = long.clone();
    app.editor.toggle_wrap();
    assert!(app.editor.wrap_enabled());
    let area = Rect::new(0, 0, 40, 20);
    let mut buf = ratatui::buffer::Buffer::empty(area);
    (&mut *app.editor).render(area, &mut buf);

    app.editor.cursor_row = last;
    app.editor.cursor_col = 2;
    for _ in 0..10 {
        app.handle_key(key(KeyCode::Down, KeyModifiers::NONE))
            .unwrap();
    }
    assert_eq!(
        (app.editor.cursor_row, app.editor.cursor_col),
        (last, long.chars().count())
    );

    app.editor.cursor_row = 0;
    app.editor.cursor_col = 6;
    app.handle_key(key(KeyCode::Up, KeyModifiers::NONE))
        .unwrap();
    assert_eq!((app.editor.cursor_row, app.editor.cursor_col), (0, 0));
}

#[test]
fn dragging_editor_horizontal_scrollbar_pans_the_buffer() {
    // The editor paints a horizontal scrollbar on its bottom row when the
    // longest line overflows the text column. Clicking and dragging its thumb
    // must move scroll_col, and releasing must end the drag.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let f = tmp.path().join("long.txt");
    let long: String = std::iter::repeat_n('z', 500).collect();
    std::fs::write(&f, format!("{long}\n")).unwrap();
    app.editor.open(&f).unwrap();
    app.focus_pane(Pane::Editor);

    let backend = ratatui::backend::TestBackend::new(80, 24);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();

    let bar = app.editor.last_hscrollbar;
    assert!(
        bar.width > 0 && bar.height == 1,
        "an overflowing line must paint a horizontal scrollbar"
    );

    // Click-drag the thumb to the far-right end of the track.
    let right_x = bar.x + bar.width - 1;
    app.handle_mouse(crossterm::event::MouseEvent {
        kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
        column: right_x,
        row: bar.y,
        modifiers: KeyModifiers::NONE,
    });
    assert!(
        app.editor.scroll_col > 0,
        "clicking the right of the track must pan right"
    );
    let after_down = app.editor.scroll_col;

    // Dragging back to the left edge pans back to column 0.
    app.handle_mouse(crossterm::event::MouseEvent {
        kind: crossterm::event::MouseEventKind::Drag(crossterm::event::MouseButton::Left),
        column: bar.x,
        row: bar.y,
        modifiers: KeyModifiers::NONE,
    });
    assert_eq!(
        app.editor.scroll_col, 0,
        "dragging to the left edge pans home"
    );
    assert_ne!(after_down, app.editor.scroll_col);

    // Release ends the drag so later moves don't keep panning.
    app.handle_mouse(crossterm::event::MouseEvent {
        kind: crossterm::event::MouseEventKind::Up(crossterm::event::MouseButton::Left),
        column: bar.x,
        row: bar.y,
        modifiers: KeyModifiers::NONE,
    });
    assert!(
        app.gesture != Some(Gesture::EditorHScrollbar),
        "releasing must clear the drag flag"
    );
}

/// #1352: F7 in an editor tab walks its change bars (line 5, then the
/// deletion boundary at line 9) and wraps; Shift+F7 goes back.
#[test]
fn next_change_in_the_editor_walks_the_change_bars_and_wraps() {
    let (mut app, _t) = app_with_change_bars();
    app.editor.cursor_row = 0;
    let f7 = |app: &mut App, m: KeyModifiers| {
        app.handle_key(key(KeyCode::F(7), m)).unwrap();
        app.editor.cursor_row
    };
    assert_eq!(f7(&mut app, KeyModifiers::NONE), 4);
    assert_eq!(f7(&mut app, KeyModifiers::NONE), 8);
    assert_eq!(f7(&mut app, KeyModifiers::NONE), 4, "wraps to the first");
    assert_eq!(f7(&mut app, KeyModifiers::SHIFT), 8, "Shift+F7 wraps back");
    assert_eq!(f7(&mut app, KeyModifiers::SHIFT), 4);
}

#[test]
fn inline_blame_annotation_paints_on_the_cursor_line() {
    let tmp = tempfile::tempdir().unwrap();
    let f = tmp.path().join("m.rs");
    std::fs::write(&f, "fn main() {}\nlet x = 1;\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&f).unwrap();
    app.focus_pane(Pane::Editor);
    app.editor.cursor_row = 0;
    app.editor.set_blame(
        f.clone(),
        Some(crate::git::Blame::new(
            vec![
                std::sync::Arc::new(crate::git::BlameCommit {
                    hash: "abc12345".into(),
                    summary: "init".into(),
                    author: "Vitali".into(),
                    age_secs: 3600,
                    uncommitted: false,
                }),
                std::sync::Arc::new(crate::git::BlameCommit {
                    hash: "abc12345".into(),
                    summary: "add x".into(),
                    author: "Alice".into(),
                    age_secs: 60,
                    uncommitted: false,
                }),
            ],
            None,
        )),
    );
    let backend = ratatui::backend::TestBackend::new(120, 30);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|frame| app.render(frame)).unwrap();
    let buf = term.backend().buffer();
    let mut whole = String::new();
    for y in 0..30 {
        for x in 0..120 {
            whole.push_str(buf[(x, y)].symbol());
        }
        whole.push('\n');
    }
    assert!(
        whole.contains("Vitali, 1 hour ago"),
        "the cursor line's blame annotation must render; got:\n{whole}"
    );
    assert!(
        !whole.contains("Alice"),
        "only the cursor line is annotated, not every line"
    );
}

/// `Editor: Toggle Provenance` (#349) flips the lens on the active editor
/// and keeps it across the per-tick sync; off again on a second toggle.
#[test]
fn toggle_provenance_command_flips_the_editor_lens() {
    let mut app = editor_app_with_lines(&["one", "two"]);
    assert!(!app.editor.provenance_overlay, "the lens is off by default");
    app.run_command(crate::widgets::command_palette::Command::ToggleProvenance);
    assert!(app.editor.provenance_overlay, "the command turns it on");
    assert_eq!(app.status, "Provenance: on");
    app.sync_blame();
    assert!(
        app.editor.provenance_overlay,
        "and the tick sync keeps it on"
    );
    app.run_command(crate::widgets::command_palette::Command::ToggleProvenance);
    app.sync_blame();
    assert!(
        !app.editor.provenance_overlay,
        "toggling again turns it off"
    );
}

/// The group-by-seat lens on a Source Control diff (#349, slice four): the
/// command loads the file's persisted map and reports who wrote the lines
/// the change adds, so a review can be read as "the agent's part" and "my
/// part". Driven through the real command, not by setting the flag.
#[test]
fn the_group_by_seat_lens_reports_who_wrote_the_added_lines() {
    use crate::provenance::Seat;
    let tmp = tempfile::tempdir().unwrap();
    let hist = tempfile::tempdir().unwrap();
    let f = tmp.path().join("note.txt");
    // The working tree: one line HEAD already had, two the change adds.
    std::fs::write(&f, "kept\nmine\nnobody's\n").unwrap();
    let mut seats = crate::provenance::Provenance::new();
    seats.record(1..2, Seat::Me);
    crate::history::record_with_seats_in(
        hist.path(),
        &f,
        &std::fs::read(&f).unwrap(),
        1_000,
        &seats,
    )
    .unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.history_root = hist.path().to_path_buf();
    app.focus_pane(Pane::Editor);
    app.editor
        .open_head_diff_with_text(
            std::path::PathBuf::from("note.txt (HEAD)"),
            "kept\n",
            &f,
            true,
        )
        .unwrap();
    assert!(app.editor.diff.is_some(), "staging: a diff view is open");
    assert!(
        !app.editor.diff.as_ref().unwrap().group_by_seat,
        "staging: the lens is off by default"
    );

    app.run_command(crate::widgets::command_palette::Command::DiffToggleGroupBySeat);
    let diff = app.editor.diff.as_ref().unwrap();
    assert!(diff.group_by_seat, "the command turns the lens on");
    assert_eq!(
        diff.seat_summary(),
        "you 1 \u{2022} unrecorded 1",
        "the added lines are reported per seat, the unwatched one as unrecorded"
    );
    assert_eq!(
        app.status, "Diff: group by seat \u{2022} you 1 \u{2022} unrecorded 1",
        "and the status line says the same"
    );

    app.run_command(crate::widgets::command_palette::Command::DiffToggleGroupBySeat);
    assert!(
        !app.editor.diff.as_ref().unwrap().group_by_seat,
        "toggling again turns it off"
    );
}

/// The lens survives a rebuild of the view under it (#349 review): the
/// real refresh re-reads a Source Control diff whose file moved, and the
/// lens must stay on with a map reloaded against the NEW rows, rather than
/// going dark or keeping a map that named lines these rows renumbered.
#[test]
fn the_group_by_seat_lens_survives_a_rebuild_of_the_view() {
    use crate::provenance::Seat;
    let (tmp, f) = repo_with_seed("kept\n");
    let hist = tempfile::tempdir().unwrap();
    std::fs::write(&f, "kept\nmine\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.history_root = hist.path().to_path_buf();
    app.focus_pane(Pane::Editor);
    let record = |millis: u64, seats: &crate::provenance::Provenance| {
        crate::history::record_with_seats_in(
            hist.path(),
            &f,
            &std::fs::read(&f).unwrap(),
            millis,
            seats,
        )
        .unwrap();
    };
    let mut seats = crate::provenance::Provenance::new();
    seats.record(1..2, Seat::Me);
    record(1_000, &seats);
    app.editor
        .open_head_diff_with_text(
            std::path::PathBuf::from("seed.txt (HEAD)"),
            "kept\n",
            &f,
            true,
        )
        .unwrap();
    app.tag_open_diff(crate::widgets::diff::DiffSource::HeadVsWorking {
        root: tmp.path().to_path_buf(),
        rel: String::from("seed.txt"),
    });
    app.run_command(crate::widgets::command_palette::Command::DiffToggleGroupBySeat);
    assert_eq!(
        app.editor.diff.as_ref().unwrap().seat_summary(),
        "you 1",
        "staging: the lens is on and reports the one added line"
    );

    // An agent appends a line; the real refresh re-reads the moved file.
    rewrite_later(&f, "kept\nmine\ntheirs\n");
    let mut seats2 = crate::provenance::Provenance::new();
    seats2.record(1..2, Seat::Me);
    seats2.record(2..3, Seat::Agent(String::from("pane 2")));
    record(500_000, &seats2);
    let no_paths = std::collections::BTreeSet::new();
    assert!(
        app.refresh_open_diff_views(false, &[], &no_paths),
        "staging: the refresh rebuilt the view"
    );
    let diff = app.editor.diff.as_ref().unwrap();
    assert_eq!(
        diff.right_lines.len(),
        3,
        "staging: the rebuilt view shows the new line"
    );
    assert!(
        diff.group_by_seat,
        "the lens stays on across the rebuild rather than going dark"
    );
    assert_eq!(
        diff.seat_summary(),
        "you 1 \u{2022} agent (pane 2) 1",
        "and its map is reloaded against the rebuilt rows: {}",
        diff.seat_summary()
    );
}

/// A map is never joined onto rows it does not describe (#349 review): if
/// the file moved on disk since the view was built, the lens reports
/// nothing rather than crediting the view's stale lines from a newer map.
#[test]
fn the_group_by_seat_lens_refuses_a_map_for_lines_the_view_does_not_show() {
    use crate::provenance::Seat;
    let tmp = tempfile::tempdir().unwrap();
    let hist = tempfile::tempdir().unwrap();
    let f = tmp.path().join("note.txt");
    std::fs::write(&f, "kept\nmine\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.history_root = hist.path().to_path_buf();
    app.focus_pane(Pane::Editor);
    app.editor
        .open_head_diff_with_text(
            std::path::PathBuf::from("note.txt (HEAD)"),
            "kept\n",
            &f,
            true,
        )
        .unwrap();
    // Same LENGTH, different content ("else" for "mine"), so the (mtime,
    // len) stamp gate genuinely cannot see this rewrite: the view still
    // shows the old lines while disk and its snapshot have moved.
    std::fs::write(&f, "kept\nelse\n").unwrap();
    let mut seats = crate::provenance::Provenance::new();
    seats.record(1..2, Seat::Me);
    crate::history::record_with_seats_in(
        hist.path(),
        &f,
        &std::fs::read(&f).unwrap(),
        1_000,
        &seats,
    )
    .unwrap();
    app.run_command(crate::widgets::command_palette::Command::DiffToggleGroupBySeat);
    let diff = app.editor.diff.as_ref().unwrap();
    assert_eq!(
        diff.right_lines,
        vec![String::from("kept"), String::from("mine")],
        "staging: the view still shows the pre-rewrite lines"
    );
    assert_eq!(
        diff.seat_summary(),
        "unrecorded 1",
        "the newer map is refused rather than joined onto lines it never described"
    );
}

/// A lone carriage return is one line to the diff opener (#349 review):
/// the comparison that binds a map to the view's rows has to split the same
/// way, or the lens reports every line unrecorded on such a file.
#[test]
fn the_group_by_seat_lens_handles_a_lone_carriage_return() {
    use crate::provenance::Seat;
    let tmp = tempfile::tempdir().unwrap();
    let hist = tempfile::tempdir().unwrap();
    let f = tmp.path().join("note.txt");
    // "a\rb" is ONE line to `str::lines`, which is how the view is built.
    std::fs::write(&f, "kept\na\rb\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.history_root = hist.path().to_path_buf();
    app.focus_pane(Pane::Editor);
    let mut seats = crate::provenance::Provenance::new();
    seats.record(1..2, Seat::Me);
    crate::history::record_with_seats_in(
        hist.path(),
        &f,
        &std::fs::read(&f).unwrap(),
        1_000,
        &seats,
    )
    .unwrap();
    app.editor
        .open_head_diff_with_text(
            std::path::PathBuf::from("note.txt (HEAD)"),
            "kept\n",
            &f,
            true,
        )
        .unwrap();
    assert_eq!(
        app.editor.diff.as_ref().unwrap().right_lines.len(),
        2,
        "staging: the opener made two lines, the lone CR inside the second"
    );
    app.run_command(crate::widgets::command_palette::Command::DiffToggleGroupBySeat);
    assert_eq!(
        app.editor.diff.as_ref().unwrap().seat_summary(),
        "you 1",
        "the map is applied rather than refused over a splitting difference"
    );
}

/// The lens refuses a diff whose right side is not the working tree (#349):
/// a diff parsed from raw git output numbers its rows by position in that
/// text, so joining a line-keyed seat map onto it would credit lines at
/// random. Refusing is the only safe answer.
#[test]
fn the_group_by_seat_lens_refuses_a_diff_that_is_not_the_working_tree() {
    let tmp = tempfile::tempdir().unwrap();
    let f = tmp.path().join("note.txt");
    std::fs::write(&f, "one\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.focus_pane(Pane::Editor);
    // A Timeline snapshot diff: same opener, left_is_git_head false.
    app.editor
        .open_head_diff_with_text(
            std::path::PathBuf::from("note.txt (snapshot)"),
            "old\n",
            &f,
            false,
        )
        .unwrap();
    app.run_command(crate::widgets::command_palette::Command::DiffToggleGroupBySeat);
    assert!(
        !app.editor.diff.as_ref().unwrap().group_by_seat,
        "the lens stays off on a diff it cannot key"
    );
    assert!(
        app.status.contains("working tree"),
        "and says why: {}",
        app.status
    );
}

/// Provenance survives a restart (#349, criterion 2): a save records who
/// typed each line beside the history snapshot, and a fresh app that opens
/// the unchanged file gets the map back. Distinguishable seats per line, or
/// a seat on the wrong line would be invisible.
#[test]
fn provenance_survives_a_restart_when_the_file_is_unchanged() {
    use crate::provenance::Seat;
    let tmp = tempfile::tempdir().unwrap();
    let hist = tempfile::tempdir().unwrap();
    let f = tmp.path().join("note.txt");
    std::fs::write(&f, "one\ntwo\nthree\n").unwrap();
    {
        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        app.history_root = hist.path().to_path_buf();
        app.editor.open(&f).unwrap();
        app.focus_pane(Pane::Editor);
        // Recorded directly rather than typed: a typed newline splits the
        // line below and credits it to the typist (the shipped rule), and
        // this test needs one line nobody touched.
        app.editor.provenance.record(0..1, Seat::Navigator);
        app.editor
            .provenance
            .record(1..2, Seat::Agent(String::from("pane 2")));
        app.editor.dirty = true;
        app.save();
        let snaps = wait_for_snapshots(&app.history_root, &f);
        assert_eq!(snaps.len(), 1, "staging: the save recorded a snapshot");
        assert_eq!(
            std::fs::read(&snaps[0].file).unwrap(),
            std::fs::read(&f).unwrap(),
            "staging: the snapshot holds the saved bytes"
        );
        // The sidecar lands after the snapshot, on the same thread; wait for
        // it rather than for the snapshot it follows.
        wait_for_seats(&app.history_root, &f, snaps[0].millis);
    }
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.history_root = hist.path().to_path_buf();
    app.editor.open(&f).unwrap();
    assert_eq!(
        app.editor.provenance.attributed(),
        0,
        "staging: a fresh open knows nothing yet"
    );
    app.sync_provenance();
    assert_eq!(
        app.editor.provenance.seat(0),
        Some(&Seat::Navigator),
        "the navigator's line comes back: {:?}",
        app.editor.provenance
    );
    assert_eq!(
        app.editor.provenance.seat(1),
        Some(&Seat::Agent(String::from("pane 2"))),
        "and the agent's: {:?}",
        app.editor.provenance
    );
    assert_eq!(
        app.editor.provenance.seat(2),
        None,
        "the untouched line stays unknown"
    );
}

/// A whole-buffer swap under the same path clears the map and is reconsidered
/// on its own (#349 review): the reload behind an FS-sync sweep or a
/// disk-conflict popup, a revert, "Reopen as Text" and a re-decode all go
/// through an opener, and none of them has to reset anything by hand. Driven
/// through the openers themselves; the marker is never touched.
#[test]
fn provenance_comes_back_after_every_same_path_swap() {
    use crate::provenance::Seat;
    let tmp = tempfile::tempdir().unwrap();
    let hist = tempfile::tempdir().unwrap();
    let f = tmp.path().join("note.txt");
    std::fs::write(&f, "one\ntwo\n").unwrap();
    let mut seats = crate::provenance::Provenance::new();
    seats.record(0..1, Seat::Navigator);
    crate::history::record_with_seats_in(
        hist.path(),
        &f,
        &std::fs::read(&f).unwrap(),
        1_000,
        &seats,
    )
    .unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.history_root = hist.path().to_path_buf();
    app.editor.open(&f).unwrap();
    app.sync_provenance();
    assert_eq!(
        app.editor.provenance, seats,
        "staging: the first sync restores"
    );

    // The revert every reload path ends in.
    app.editor.revert_to_disk().unwrap();
    assert_eq!(
        app.editor.provenance.attributed(),
        0,
        "staging: the revert cleared the map"
    );
    app.sync_provenance();
    assert_eq!(
        app.editor.provenance, seats,
        "the map comes back after a revert of the same path"
    );

    // "Reopen as Text": `open` on the path already open.
    app.editor.open(&f).unwrap();
    assert_eq!(
        app.editor.provenance.attributed(),
        0,
        "staging: the reopen cleared the map"
    );
    app.sync_provenance();
    assert_eq!(
        app.editor.provenance, seats,
        "and after a reopen of the same path"
    );
}

/// A tab's history is looked at once per buffer generation (#2925): a file
/// with no history was looked up on disk on every pass of the loop, 125
/// times a second for every such tab. When croft finishes recording a
/// snapshot of the file, its tabs look again and pick up who typed it.
#[test]
fn a_tab_with_no_history_is_looked_up_once_until_croft_records_one() {
    use crate::provenance::Seat;
    let tmp = tempfile::tempdir().unwrap();
    let hist = tempfile::tempdir().unwrap();
    let f = tmp.path().join("note.txt");
    std::fs::write(&f, "one\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.history_root = hist.path().to_path_buf();
    app.editor.open(&f).unwrap();
    app.sync_provenance();
    assert_eq!(
        app.editor.provenance_synced_seq,
        Some(app.editor.edit_seq),
        "a file with no history is looked at once, not on every pass"
    );
    // A snapshot and its record land, as a save's worker writes them...
    let mut seats = crate::provenance::Provenance::new();
    seats.record(0..1, Seat::Navigator);
    crate::history::record_with_seats_in(
        hist.path(),
        &f,
        &std::fs::read(&f).unwrap(),
        1_000,
        &seats,
    )
    .unwrap();
    app.sync_provenance();
    assert_eq!(
        app.editor.provenance.attributed(),
        0,
        "the next pass does not look again"
    );
    // ...and the worker says it is done.
    app.history_done_tx.send(f.clone()).unwrap();
    app.sync_explorer_panels();
    app.sync_provenance();
    assert_eq!(
        app.editor.provenance, seats,
        "a snapshot croft records is looked at"
    );
}

/// Two tabs on one file are two buffers (#349 review): a split opens the
/// same path in a fresh group, whose tab sits at the same `edit_seq` as the
/// first one did when it was synced. The marker is per buffer, so the split
/// pane gets the map too rather than staying blank for the session.
#[test]
fn a_split_of_a_synced_file_gets_the_map_in_the_new_group() {
    use crate::provenance::Seat;
    let tmp = tempfile::tempdir().unwrap();
    let hist = tempfile::tempdir().unwrap();
    let f = tmp.path().join("note.txt");
    std::fs::write(&f, "one\n").unwrap();
    let mut seats = crate::provenance::Provenance::new();
    seats.record(0..1, Seat::Navigator);
    crate::history::record_with_seats_in(
        hist.path(),
        &f,
        &std::fs::read(&f).unwrap(),
        1_000,
        &seats,
    )
    .unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.history_root = hist.path().to_path_buf();
    app.editor.open(&f).unwrap();
    app.focus_pane(Pane::Editor);
    app.sync_provenance();
    assert_eq!(
        app.editor.provenance, seats,
        "staging: the first tab is synced"
    );
    app.split_editor();
    assert_eq!(
        app.editor.path.as_deref(),
        Some(f.as_path()),
        "staging: the split opened the same file in the focused group"
    );
    assert_eq!(
        app.editor.provenance.attributed(),
        0,
        "staging: the new group's tab knows nothing yet"
    );
    app.sync_provenance();
    assert_eq!(
        app.editor.provenance, seats,
        "the split pane's buffer is synced on its own"
    );
}

/// The lens paints in every pane, so the map is restored onto every open
/// buffer (#349 review), not only the focused one: a split whose other
/// group holds the file must not show the lens on with every line blank.
#[test]
fn provenance_is_synced_onto_the_inactive_group_too() {
    use crate::provenance::Seat;
    let tmp = tempfile::tempdir().unwrap();
    let hist = tempfile::tempdir().unwrap();
    let f = tmp.path().join("note.txt");
    std::fs::write(&f, "one\n").unwrap();
    let mut seats = crate::provenance::Provenance::new();
    seats.record(0..1, Seat::Navigator);
    crate::history::record_with_seats_in(
        hist.path(),
        &f,
        &std::fs::read(&f).unwrap(),
        1_000,
        &seats,
    )
    .unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.history_root = hist.path().to_path_buf();
    app.editor.open(&f).unwrap();
    app.focus_pane(Pane::Editor);
    // Split before any sync: both groups hold the file, neither knows its map.
    app.split_editor();
    let inactive = app.editor_layout.inactive_groups().collect::<Vec<_>>();
    assert_eq!(inactive.len(), 1, "staging: one inactive group");
    assert_eq!(
        inactive[0].path.as_deref(),
        Some(f.as_path()),
        "staging: the inactive group holds the file"
    );
    app.sync_provenance();
    assert_eq!(
        app.editor.provenance, seats,
        "staging: the focused tab is synced"
    );
    assert_eq!(
        app.editor_layout
            .inactive_groups()
            .next()
            .unwrap()
            .provenance,
        seats,
        "the inactive group's tab is synced too"
    );
}

/// A save records the saved tab's own map (#349 review): with the same file
/// open in two groups, an auto save of the inactive group's buffer must not
/// persist the focused group's map against bytes it never described.
#[test]
fn an_inactive_group_save_records_the_map_of_that_buffer() {
    use crate::provenance::Seat;
    let tmp = tempfile::tempdir().unwrap();
    let hist = tempfile::tempdir().unwrap();
    let f = tmp.path().join("note.txt");
    std::fs::write(&f, "one\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.history_root = hist.path().to_path_buf();
    app.editor.open(&f).unwrap();
    app.focus_pane(Pane::Editor);
    app.split_editor();
    // The focused group's buffer: clean, and wearing a map of its own.
    app.editor
        .provenance
        .record(0..1, Seat::Peer(String::from("ana")));
    // The inactive group's buffer: the navigator types, so it is dirty and
    // due, and its map says navigator.
    {
        let mut groups = app.editor_layout.inactive_groups_mut().collect::<Vec<_>>();
        let other: &mut crate::widgets::editor::Editor = &mut *groups[0];
        assert_eq!(
            other.path.as_deref(),
            Some(f.as_path()),
            "staging: same file"
        );
        other.cursor_row = 0;
        other.cursor_col = 0;
        other.insert_str_as("nav\n", Seat::Navigator);
        assert!(other.dirty, "staging: the inactive buffer is dirty");
        age_last_edit(other);
    }
    app.auto_save = true;
    assert!(
        app.tick_auto_save(),
        "staging: the sweep saved the dirty buffer"
    );
    assert!(
        std::fs::read_to_string(&f).unwrap().starts_with("nav\n"),
        "staging: the inactive buffer's text is what hit the disk"
    );
    let snaps = wait_for_snapshots(&app.history_root, &f);
    assert_eq!(snaps.len(), 1, "staging: the save recorded a snapshot");
    wait_for_seats(&app.history_root, &f, snaps[0].millis);
    let recorded = crate::history::seats_for(&app.history_root, &f, snaps[0].millis).unwrap();
    assert_eq!(
        recorded.seat(0),
        Some(&Seat::Navigator),
        "the sidecar holds the saved buffer's map, not the focused tab's: {recorded:?}"
    );
}

/// A clean buffer can still be stale (#349 review): when one tab of a split
/// saves, the other keeps the pre-save text and its own disk stamp. The
/// newest snapshot then matches disk while describing text that tab never
/// held, so the map must NOT be applied to it.
#[test]
fn a_stale_tab_is_not_credited_with_the_map_of_the_saving_tab() {
    use crate::provenance::Seat;
    let tmp = tempfile::tempdir().unwrap();
    let hist = tempfile::tempdir().unwrap();
    let f = tmp.path().join("note.txt");
    std::fs::write(&f, "one\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.history_root = hist.path().to_path_buf();
    app.editor.open(&f).unwrap();
    app.focus_pane(Pane::Editor);
    app.split_editor();
    // The inactive group types and saves; the focused tab is untouched, so
    // it stays clean, unattributed, and holding the pre-save text.
    {
        let mut groups = app.editor_layout.inactive_groups_mut().collect::<Vec<_>>();
        let other: &mut crate::widgets::editor::Editor = &mut *groups[0];
        other.cursor_row = 0;
        other.cursor_col = 0;
        other.insert_str_as("nav\n", Seat::Navigator);
        age_last_edit(other);
    }
    app.auto_save = true;
    assert!(
        app.tick_auto_save(),
        "staging: the sweep saved the other buffer"
    );
    let snaps = wait_for_snapshots(&app.history_root, &f);
    wait_for_seats(&app.history_root, &f, snaps[0].millis);
    // Positive control: there IS a map beside a snapshot matching disk, so a
    // sync that ignored staleness would have something to apply.
    assert_eq!(
        std::fs::read(&snaps[0].file).unwrap(),
        std::fs::read(&f).unwrap(),
        "staging: the newest snapshot matches the file on disk"
    );
    assert!(!app.editor.dirty, "staging: the focused tab is clean");
    assert_eq!(
        app.editor.lines,
        vec![String::from("one")],
        "staging: and still holds the pre-save text"
    );
    app.sync_provenance();
    assert_eq!(
        app.editor.provenance.attributed(),
        0,
        "a stale buffer is not credited from a snapshot of text it never held: {:?}",
        app.editor.provenance
    );
}

/// An empty file gets its map back too (#349 review): `open` gives an empty
/// buffer one sentinel line, so a comparison against the snapshot's bare
/// (zero-line) split would withhold the map from every emptied file.
#[test]
fn the_map_of_an_emptied_file_survives_a_restart() {
    use crate::provenance::Seat;
    let tmp = tempfile::tempdir().unwrap();
    let hist = tempfile::tempdir().unwrap();
    let f = tmp.path().join("note.txt");
    std::fs::write(&f, "").unwrap();
    let mut seats = crate::provenance::Provenance::new();
    seats.record(0..1, Seat::Navigator);
    crate::history::record_with_seats_in(hist.path(), &f, b"", 1_000, &seats).unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.history_root = hist.path().to_path_buf();
    app.editor.open(&f).unwrap();
    assert_eq!(
        app.editor.lines,
        vec![String::new()],
        "staging: an empty file opens as one empty line"
    );
    app.sync_provenance();
    assert_eq!(
        app.editor.provenance, seats,
        "the emptied file's map comes back: {:?}",
        app.editor.provenance
    );
}

/// A UTF-16 file's map comes back too (#349 review): the snapshot holds the
/// file's raw bytes, so the comparison must decode them the way `open` does,
/// through the BOM, rather than assuming UTF-8.
#[test]
fn the_map_of_a_utf16_file_survives_a_restart() {
    use crate::provenance::Seat;
    let tmp = tempfile::tempdir().unwrap();
    let hist = tempfile::tempdir().unwrap();
    let f = tmp.path().join("note.txt");
    let mut bytes = vec![0xFF, 0xFE];
    for unit in "one
two
"
    .encode_utf16()
    {
        bytes.extend_from_slice(&unit.to_le_bytes());
    }
    std::fs::write(&f, &bytes).unwrap();
    let mut seats = crate::provenance::Provenance::new();
    seats.record(0..1, Seat::Navigator);
    crate::history::record_with_seats_in(hist.path(), &f, &bytes, 1_000, &seats).unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.history_root = hist.path().to_path_buf();
    app.editor.open(&f).unwrap();
    assert_eq!(
        app.editor.lines,
        vec![String::from("one"), String::from("two")],
        "staging: the file opened as UTF-16 text"
    );
    app.sync_provenance();
    assert_eq!(
        app.editor.provenance, seats,
        "the UTF-16 file's map comes back: {:?}",
        app.editor.provenance
    );
}

/// The recorded map is bound to the bytes it describes (#349 review): the
/// worker re-reads the file, so a save of the same path landing in between
/// must not get the earlier buffer's map attached to its bytes. The snapshot
/// is still recorded; only the attribution is withheld.
#[test]
fn the_map_is_not_recorded_against_another_save_s_bytes() {
    use crate::provenance::Seat;
    let tmp = tempfile::tempdir().unwrap();
    let hist = tempfile::tempdir().unwrap();
    let f = tmp.path().join("note.txt");
    std::fs::write(&f, "one\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.history_root = hist.path().to_path_buf();
    app.editor.open(&f).unwrap();
    app.focus_pane(Pane::Editor);
    let mut seats = crate::provenance::Provenance::new();
    seats.record(0..1, Seat::Navigator);
    // The map describes "one", but something else reaches the disk first:
    // exactly the race the worker's re-read opens.
    std::fs::write(&f, "someone else\n").unwrap();
    app.record_history_snapshot_of(&f, seats, Some(b"one\n".to_vec()));
    let snaps = wait_for_snapshots(&app.history_root, &f);
    assert_eq!(snaps.len(), 1, "the snapshot is still recorded");
    assert_eq!(
        std::fs::read(&snaps[0].file).unwrap(),
        b"someone else\n",
        "and holds the bytes that were actually on disk"
    );
    assert_eq!(
        crate::history::seats_for(&app.history_root, &f, snaps[0].millis),
        None,
        "but wears no map, rather than one describing text it does not hold"
    );
    // Positive control: the same call with matching bytes DOES record a map,
    // so the assertion above is about the binding and not about the plumbing.
    let mut seats2 = crate::provenance::Provenance::new();
    seats2.record(0..1, Seat::Peer(String::from("ana")));
    let on_disk = std::fs::read(&f).unwrap();
    app.record_history_snapshot_of(&f, seats2, Some(on_disk));
    crate::test_budget::await_spawned(
        std::time::Duration::from_millis(500),
        "the control's sidecar",
        || {
            crate::history::entries_in(&app.history_root, &f)
                .first()
                .is_some_and(|s| {
                    crate::history::seats_for(&app.history_root, &f, s.millis).is_some()
                })
        },
    );
}

/// A tab that is not eligible yet is not the same as one considered (#349
/// review): a sync that lands on a dirty buffer leaves it for a later tick
/// rather than burning the map for the session.
#[test]
fn a_dirty_tab_is_reconsidered_for_provenance_once_it_is_clean() {
    use crate::provenance::Seat;
    let tmp = tempfile::tempdir().unwrap();
    let hist = tempfile::tempdir().unwrap();
    let f = tmp.path().join("note.txt");
    std::fs::write(&f, "one\n").unwrap();
    let mut seats = crate::provenance::Provenance::new();
    seats.record(0..1, Seat::Peer(String::from("ana")));
    crate::history::record_with_seats_in(
        hist.path(),
        &f,
        &std::fs::read(&f).unwrap(),
        1_000,
        &seats,
    )
    .unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.history_root = hist.path().to_path_buf();
    app.editor.open(&f).unwrap();
    app.editor.dirty = true;
    app.sync_provenance();
    assert_eq!(
        app.editor.provenance.attributed(),
        0,
        "staging: a dirty buffer takes no map"
    );
    app.editor.dirty = false;
    app.sync_provenance();
    assert_eq!(
        app.editor.provenance, seats,
        "the same buffer, clean, gets the map on the next tick"
    );
}

/// A persisted map is restored only onto the text it described: a file
/// changed since the snapshot (by anything, croft or not) opens with every
/// line unknown rather than credited from a stale map.
#[test]
fn provenance_is_not_restored_onto_text_the_snapshot_never_saw() {
    use crate::provenance::Seat;
    let tmp = tempfile::tempdir().unwrap();
    let hist = tempfile::tempdir().unwrap();
    let f = tmp.path().join("note.txt");
    std::fs::write(&f, "v1\n").unwrap();
    {
        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        app.history_root = hist.path().to_path_buf();
        app.editor.open(&f).unwrap();
        app.focus_pane(Pane::Editor);
        app.editor.cursor_row = 0;
        app.editor.cursor_col = 0;
        app.editor.insert_str_as("nav\n", Seat::Navigator);
        app.save();
        let snaps = wait_for_snapshots(&app.history_root, &f);
        assert_eq!(snaps.len(), 1, "staging: the save recorded a snapshot");
        // Positive control: there IS a map that a careless restore would apply.
        wait_for_seats(&app.history_root, &f, snaps[0].millis);
    }
    // Edited outside croft after the save: the snapshot's map describes text
    // that is no longer what is on disk.
    let mut on_disk = std::fs::read_to_string(&f).unwrap();
    on_disk.insert_str(0, "someone else\n");
    std::fs::write(&f, on_disk).unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.history_root = hist.path().to_path_buf();
    app.editor.open(&f).unwrap();
    app.sync_provenance();
    assert_eq!(
        app.editor.provenance.attributed(),
        0,
        "a changed file is not credited from a stale map: {:?}",
        app.editor.provenance
    );
}

/// The lens reaches every tab of every group, not only the focused editor
/// (#349 review): the gutter bar paints in every pane, so `sync_focus_flags`
/// carries it the way it carries indent guides.
#[test]
fn the_provenance_lens_reaches_every_editor_after_the_flag_sync() {
    let mut app = editor_app_with_lines(&["one", "two"]);
    app.editor
        .push_editor(crate::widgets::editor::Editor::new());
    assert!(app.editor.editors.len() >= 2, "fixture: two tabs");
    // A split puts the first group out of focus; the lens must reach it too.
    app.editor.path = Some(std::path::PathBuf::from("split-anchor.txt"));
    app.split_editor();
    app.run_command(crate::widgets::command_palette::Command::ToggleProvenance);
    app.sync_focus_flags();
    let every_editor_on = app.editor.editors.iter().all(|e| e.provenance_overlay)
        && app
            .editor_layout
            .inactive_groups()
            .flat_map(|g| g.editors.iter())
            .all(|e| e.provenance_overlay);
    assert!(
        every_editor_on,
        "every tab in every group carries the lens after the sync"
    );
    app.run_command(crate::widgets::command_palette::Command::ToggleProvenance);
    app.sync_focus_flags();
    assert!(
        app.editor.editors.iter().all(|e| !e.provenance_overlay),
        "and every tab drops it"
    );
}

#[test]
fn toggle_inline_blame_command_flips_the_editor_flag_and_pref() {
    let mut app = editor_app_with_lines(&["one", "two"]);
    assert!(
        app.inline_blame_enabled,
        "inline blame is on by default (GitLens parity)"
    );
    app.run_command(crate::widgets::command_palette::Command::ToggleInlineBlame);
    assert!(!app.inline_blame_enabled, "the command turns it off");
    // sync_blame propagates the pref onto the active editor each tick.
    app.sync_blame();
    assert!(!app.editor.blame_enabled);
    app.run_command(crate::widgets::command_palette::Command::ToggleInlineBlame);
    assert!(app.inline_blame_enabled, "toggling again turns it back on");
    app.sync_blame();
    assert!(app.editor.blame_enabled);
}

#[test]
fn toggle_indent_guides_command_flips_every_editor_via_the_frame_sync() {
    let mut app = editor_app_with_lines(&["fn a() {", "    x();", "}"]);
    assert!(
        app.indent_guides_enabled,
        "indent guides are on by default (VS Code editor.guides.indentation)"
    );
    app.run_command(crate::widgets::command_palette::Command::ToggleIndentGuides);
    assert!(!app.indent_guides_enabled, "the command turns them off");
    // The per-frame focus sync pushes the flag onto every editor in every
    // group, so tabs opened after the toggle can never resurrect guides.
    app.sync_focus_flags();
    assert!(app.editor.editors.iter().all(|e| !e.show_indent_guides));
    // A tab opened AFTER the toggle starts on the constructor default (true)
    // and must be brought in line by the next frame's sync.
    app.editor
        .open_text_buffer(std::path::Path::new("later.rs"), "fn x() {\n    y();\n}")
        .unwrap();
    assert!(
        app.editor.show_indent_guides,
        "a fresh tab starts on the default, proving the sync below does the work"
    );
    app.sync_focus_flags();
    assert!(
        app.editor.editors.iter().all(|e| !e.show_indent_guides),
        "the frame sync disables guides on the tab opened after the toggle"
    );
    app.run_command(crate::widgets::command_palette::Command::ToggleIndentGuides);
    assert!(app.indent_guides_enabled);
    app.editor
        .open_text_buffer(std::path::Path::new("even-later.rs"), "fn z() {}")
        .unwrap();
    app.sync_focus_flags();
    assert!(
        app.editor.editors.iter().all(|e| e.show_indent_guides),
        "re-enabling reaches tabs opened before and after the toggle"
    );
}

#[test]
fn toggle_bracket_colors_command_flips_every_editor_via_the_frame_sync() {
    let mut app = editor_app_with_lines(&["fn a(x: u8) {}"]);
    assert!(
        app.bracket_colors_enabled,
        "bracket colorization is on by default (VS Code default since 1.67)"
    );
    app.run_command(crate::widgets::command_palette::Command::ToggleBracketColors);
    assert!(!app.bracket_colors_enabled, "the command turns it off");
    app.editor
        .open_text_buffer(std::path::Path::new("later.rs"), "g(1)")
        .unwrap();
    app.sync_focus_flags();
    assert!(
        app.editor.editors.iter().all(|e| !e.show_bracket_colors),
        "the frame sync disables the tab opened after the toggle too"
    );
    app.run_command(crate::widgets::command_palette::Command::ToggleBracketColors);
    app.sync_focus_flags();
    assert!(app.editor.editors.iter().all(|e| e.show_bracket_colors));
}

#[test]
fn toggle_render_whitespace_cycles_modes_across_every_editor() {
    use crate::widgets::editor::WhitespaceMode;
    let mut app = editor_app_with_lines(&["a b"]);
    let all_editors_in = |app: &App, mode: WhitespaceMode| {
        app.editor.editors.iter().all(|e| e.whitespace_mode == mode)
    };
    assert_eq!(
        app.whitespace_mode,
        WhitespaceMode::Selection,
        "selection is the default (VS Code editor.renderWhitespace)"
    );
    app.sync_focus_flags();
    assert!(all_editors_in(&app, WhitespaceMode::Selection));
    app.run_command(crate::widgets::command_palette::Command::ToggleRenderWhitespace);
    assert_eq!(app.whitespace_mode, WhitespaceMode::All);
    app.editor
        .open_text_buffer(std::path::Path::new("later.txt"), "c d")
        .unwrap();
    app.sync_focus_flags();
    assert!(
        all_editors_in(&app, WhitespaceMode::All),
        "the frame sync carries the mode to tabs opened after the toggle"
    );
    app.run_command(crate::widgets::command_palette::Command::ToggleRenderWhitespace);
    assert_eq!(app.whitespace_mode, WhitespaceMode::None);
    app.sync_focus_flags();
    assert!(all_editors_in(&app, WhitespaceMode::None));
    app.run_command(crate::widgets::command_palette::Command::ToggleRenderWhitespace);
    assert_eq!(app.whitespace_mode, WhitespaceMode::Selection, "full cycle");
    app.sync_focus_flags();
    assert!(all_editors_in(&app, WhitespaceMode::Selection));
}

/// #1524: a settings reload carries the rulers straight onto every open
/// editor, without waiting for an unrelated focus sync.
#[test]
fn reloaded_rulers_reach_every_open_editor() {
    let mut app = editor_app_with_lines(&["a b"]);
    app.editor
        .open_text_buffer(std::path::Path::new("later.txt"), "c d")
        .unwrap();
    app.apply_merged_settings(&crate::prefs::Prefs {
        rulers: vec![80, 100],
        ..Default::default()
    });
    assert!(app.editor.editors.len() >= 2);
    assert!(app.editor.editors.iter().all(|e| e.rulers == vec![80, 100]));
    app.apply_merged_settings(&crate::prefs::Prefs {
        rulers: vec![100, 80, 100],
        ..Default::default()
    });
    assert!(
        app.editor.editors.iter().all(|e| e.rulers == vec![80, 100]),
        "normalized on the way in"
    );
    app.apply_merged_settings(&crate::prefs::Prefs::default());
    assert!(app.editor.editors.iter().all(|e| e.rulers.is_empty()));
}

/// #1569: a settings reload carries `home_walks_wrapped_rows` straight onto
/// every open editor, not only the active one, so a tab picked without a
/// focus sync walks (or does not) as the setting says.
#[test]
fn reloaded_home_walk_reaches_every_open_editor() {
    let mut app = editor_app_with_lines(&["a b"]);
    app.editor
        .open_text_buffer(std::path::Path::new("later.txt"), "c d")
        .unwrap();
    app.apply_merged_settings(&crate::prefs::Prefs {
        home_walks_wrapped_rows: true,
        ..Default::default()
    });
    assert!(app.editor.editors.len() >= 2);
    assert!(app.editor.editors.iter().all(|e| e.home_walks_rows));
    app.apply_merged_settings(&crate::prefs::Prefs::default());
    assert!(app.editor.editors.iter().all(|e| !e.home_walks_rows));
}

/// Every open editor: the active group's tabs and every tab of the split.
fn every_editor(app: &App) -> Vec<&crate::widgets::editor::Editor> {
    app.editor
        .editors
        .iter()
        .chain(
            app.editor_layout
                .inactive_groups()
                .flat_map(|g| g.editors.iter()),
        )
        .collect()
}

/// #2075: a settings reload and the palette toggles change indent guides,
/// bracket colours and rendered whitespace on every open tab of every group
/// at once. They reached only the active tab; the rest, and a split, kept
/// the old look until something moved focus.
#[test]
fn view_settings_reach_every_tab_of_every_group_without_a_focus_change() {
    use crate::widgets::command_palette::Command;
    use crate::widgets::editor::WhitespaceMode;
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "a.rs", "fn a() {\n    (1)\n}\n");
    let b = tmp.path().join("b.rs");
    std::fs::write(&b, "fn b() {\n    (2)\n}\n").unwrap();
    app.editor.open_pinned(&b).unwrap();
    app.split_editor();
    assert_eq!(every_editor(&app).len(), 3, "setup: two tabs and a split");

    app.apply_merged_settings(&crate::prefs::Prefs {
        disable_indent_guides: true,
        disable_bracket_colors: true,
        render_whitespace: String::from("all"),
        ..Default::default()
    });
    for ed in every_editor(&app) {
        assert!(!ed.show_indent_guides, "{:?}: indent guides", ed.path);
        assert!(!ed.show_bracket_colors, "{:?}: bracket colours", ed.path);
        assert_eq!(ed.whitespace_mode, WhitespaceMode::All, "{:?}", ed.path);
    }

    app.run_command(Command::ToggleIndentGuides);
    app.run_command(Command::ToggleBracketColors);
    app.run_command(Command::ToggleRenderWhitespace);
    for ed in every_editor(&app) {
        assert!(ed.show_indent_guides, "{:?}: indent guides", ed.path);
        assert!(ed.show_bracket_colors, "{:?}: bracket colours", ed.path);
        assert_eq!(ed.whitespace_mode, WhitespaceMode::None, "{:?}", ed.path);
    }
}

#[test]
fn build_sticky_lines_pins_enclosing_headers_scrolled_above_the_viewport() {
    use crate::lsp::manager::OutlineKind;
    let tmp = tempfile::tempdir().unwrap();
    let f = tmp.path().join("m.rs");
    std::fs::write(&f, "x\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&f).unwrap();
    app.outline.set_symbols(
        f.clone(),
        vec![
            sym("Widget", OutlineKind::Class, 0, 0, 40),
            sym("build", OutlineKind::Method, 1, 10, 30),
        ],
    );
    // Scrolled deep inside build: both the class and method headers are above.
    app.editor.scroll = 20;
    assert_eq!(app.build_sticky_lines(), vec![0, 10], "outermost first");
    // Scrolled inside the class but above the method: only the class pins.
    app.editor.scroll = 5;
    assert_eq!(app.build_sticky_lines(), vec![0]);
    // Parked on the class header itself: nothing is scrolled off, so no pins.
    app.editor.scroll = 0;
    assert!(app.build_sticky_lines().is_empty());
}

/// #940: a decorated definition's range starts at its decorator, but the
/// sticky header is its `def`/`class` line, which names it. With that line
/// itself at the top, nothing is pinned over it.
#[test]
fn sticky_scroll_pins_the_name_line_of_a_decorated_definition() {
    use crate::lsp::manager::OutlineKind;
    let tmp = tempfile::tempdir().unwrap();
    let f = tmp.path().join("api.py");
    std::fs::write(&f, "x\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&f).unwrap();
    // `@dataclass` on line 3 above `class Order:` on 4; inside it,
    // `@staticmethod` on 6 above `def validate` on 7.
    let mut order = sym("Order", OutlineKind::Class, 0, 3, 40);
    order.line = 4;
    let mut validate = sym("validate", OutlineKind::Method, 1, 6, 30);
    validate.line = 7;
    app.outline.set_symbols(f.clone(), vec![order, validate]);
    app.editor.scroll = 20;
    assert_eq!(app.build_sticky_lines(), vec![4, 7], "the name lines");
    // Negative: the class line at the top is shown, not covered by a pin.
    app.editor.scroll = 4;
    assert!(app.build_sticky_lines().is_empty());
}

#[test]
fn minimap_edit_rebakes_in_place_but_a_moved_strip_arms_the_clear() {
    // Issue: every keystroke bumped `edit_seq`, the minimap layout signature
    // mismatched, and `update_minimap_overlay` armed the full-screen clear
    // latch - so the whole app blinked on every edit (a 2J + full redraw is
    // one visible round trip over SSH). A content-only change re-emits the
    // raster over the SAME cells (fixed Kitty id / same-cell OSC-1337 emit
    // replaces in place), so only a moved or resized strip may arm the clear.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.cell_pixel = Some((8, 16));
    app.inline_protocol = crate::iterm2_inline::InlineImageProtocol::Kitty;
    app.editor.lines = (0..80).map(|i| format!("line {i}")).collect();
    let strip = ratatui::layout::Rect {
        x: 100,
        y: 1,
        width: 6,
        height: 40,
    };
    app.update_minimap_overlay(strip);
    assert!(app.minimap_image_payload().is_some(), "minimap must bake");
    let _ = app.consume_minimap_image_clear();
    app.mark_minimap_image_displayed();

    app.editor.lines.push(String::from("one more line"));
    app.editor.edit_seq += 1;
    app.update_minimap_overlay(strip);
    assert!(
        !app.consume_minimap_image_clear(),
        "a content-only minimap change must replace the image in place, not blank the screen"
    );
    assert!(
        app.minimap_image_payload().is_some(),
        "the rebaked raster must still be there to re-emit"
    );

    app.mark_minimap_image_displayed();
    let moved = ratatui::layout::Rect { x: 60, ..strip };
    app.update_minimap_overlay(moved);
    assert!(
        app.consume_minimap_image_clear(),
        "a moved minimap strip must arm the eviction clear so no ghost remains"
    );
}

#[test]
fn timestamps_gutter_toggles_on_and_shows_arrival_times() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.terminals[0] = crate::widgets::terminal::PtyTerminal::new_running(
        "/bin/sh",
        &[
            String::from("-c"),
            String::from("g=gutter; echo ${g}-row-9; sleep 30"),
        ],
        tmp.path(),
    )
    .unwrap();
    app.focus_pane(Pane::Terminal);
    crate::test_budget::await_spawned(
        crate::test_budget::tests::SHELL_PAINT_BASE,
        "the pane output \"gutter-row-9\"",
        || {
            app.terminals[0]
                .grid_lines()
                .0
                .iter()
                .any(|l| l.starts_with("gutter-row-9"))
        },
    );
    fn gutter_of(rows: &[String], needle: &str) -> Option<String> {
        let row = rows.iter().find(|r| r.contains(needle))?;
        let inner = row.trim_end().trim_end_matches(['│', '┃']);
        Some(
            inner
                .chars()
                .rev()
                .take(8)
                .collect::<String>()
                .chars()
                .rev()
                .collect(),
        )
    }
    let backend = ratatui::backend::TestBackend::new(120, 40);
    let mut term = ratatui::Terminal::new(backend).unwrap();

    // Off by default: the row ends with its own text, no clock.
    term.draw(|f| app.render(f)).unwrap();
    let g = gutter_of(&screen_char_rows(&term), "gutter-row-9").unwrap_or_default();
    assert!(
        !g.chars().filter(|c| *c == ':').count().eq(&2),
        "no gutter while the toggle is off: {g:?}"
    );

    app.toggle_terminal_timestamps();
    assert!(app.show_terminal_timestamps);
    term.draw(|f| app.render(f)).unwrap();
    let g = gutter_of(&screen_char_rows(&term), "gutter-row-9").expect("row still on screen");
    let looks_like_clock = g.len() == 8
        && g.as_bytes()[2] == b':'
        && g.as_bytes()[5] == b':'
        && g.chars().filter(|c| c.is_ascii_digit()).count() == 6;
    assert!(
        looks_like_clock,
        "the toggled gutter shows HH:MM:SS at the row's right edge: {g:?}"
    );

    app.toggle_terminal_timestamps();
    term.draw(|f| app.render(f)).unwrap();
    let g = gutter_of(&screen_char_rows(&term), "gutter-row-9").unwrap_or_default();
    assert!(
        !(g.len() == 8 && g.as_bytes()[2] == b':' && g.as_bytes()[5] == b':'),
        "toggling off removes the gutter: {g:?}"
    );
}

#[test]
fn sticky_command_header_pins_the_command_while_scrolled_into_its_output() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    // Full OSC 133 marks around a runtime-assembled command (the pane's
    // `▶ …` run header echoes the script text, so the typed command must
    // never appear verbatim in it), then enough output to scroll.
    let script = "b=build; printf \"\\033]133;A\\007$ \\033]133;B\\007${b}-it-77 now\\n\\033]133;C\\007\"; i=0; while [ $i -lt 80 ]; do echo out-$i; i=$((i+1)); done; printf '\\033]133;D;0\\007'; sleep 30";
    app.terminals[0] = crate::widgets::terminal::PtyTerminal::new_running(
        "/bin/sh",
        &[String::from("-c"), String::from(script)],
        tmp.path(),
    )
    .unwrap();
    app.focus_pane(Pane::Terminal);
    crate::test_budget::await_spawned(
        crate::test_budget::tests::SHELL_PAINT_BASE,
        "the command to finish",
        || !app.terminals[0].command_decorations().is_empty(),
    );
    let backend = ratatui::backend::TestBackend::new(120, 40);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let inner = app.terminals[0].last_inner;

    // At the live bottom nothing pins.
    let rows = screen_char_rows(&term);
    assert!(
        !rows[inner.y as usize].contains("build-it-77"),
        "no header at the live bottom: {:?}",
        rows[inner.y as usize]
    );

    // Scroll so the viewport's top row sits inside the command's output,
    // with its prompt above the view: the typed command pins to row 0.
    app.terminals[0].scroll_to_top();
    for _ in 0..4 {
        app.terminals[0].scroll_down(1);
    }
    term.draw(|f| app.render(f)).unwrap();
    let rows = screen_char_rows(&term);
    assert!(
        rows[inner.y as usize].contains("build-it-77 now"),
        "the command must pin to the pane's top row: {:?}",
        rows[inner.y as usize]
    );

    // Back at the live bottom the header unpins.
    app.terminals[0].reset_scrollback();
    term.draw(|f| app.render(f)).unwrap();
    let rows = screen_char_rows(&term);
    assert!(
        !rows[inner.y as usize].contains("build-it-77"),
        "the header unpins at the live bottom: {:?}",
        rows[inner.y as usize]
    );
}

#[test]
fn the_wheel_still_scrolls_a_long_text_file() {
    let tmp = tempfile::tempdir().unwrap();
    let path = tmp.path().join("long.txt");
    let body: String = (0..500).map(|i| format!("line {i}\n")).collect();
    std::fs::write(&path, body).unwrap();

    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&path).unwrap();
    let (col, row) = place_editor_pane(&mut app);

    wheel(&mut app, MouseEventKind::ScrollDown, col, row);
    assert_eq!(app.editor.scroll, 3, "wheel down still scrolls text");
    wheel(&mut app, MouseEventKind::ScrollUp, col, row);
    assert_eq!(app.editor.scroll, 0, "wheel up still scrolls text back");
}

#[test]
fn drag_target_over_the_sticky_band_is_the_pinned_directory() {
    use crossterm::event::{MouseButton, MouseEventKind};
    let tmp = tempfile::tempdir().unwrap();
    std::fs::create_dir_all(tmp.path().join("outer/inner")).unwrap();
    for i in 0..25 {
        std::fs::write(tmp.path().join(format!("outer/inner/f{i:02}.rs")), "x\n").unwrap();
    }
    std::fs::write(tmp.path().join("loose.txt"), "x\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    // Three pinned rows, not the compact row `outer/inner` (#1486).
    app.tree.set_compact_folders(false);
    let outer = app
        .tree
        .nodes
        .iter()
        .position(|n| n.path.ends_with("outer"))
        .unwrap();
    app.tree.selected = outer;
    app.tree.expand_selected();
    let inner = app
        .tree
        .nodes
        .iter()
        .position(|n| n.path.ends_with("inner"))
        .unwrap();
    app.tree.selected = inner;
    app.tree.expand_selected();
    // Scroll deep so the band pins ancestors, selection far below.
    let deep = app
        .tree
        .nodes
        .iter()
        .position(|n| n.path.ends_with("f20.rs"))
        .unwrap();
    app.tree.selected = deep;
    app.tree.scroll = deep.saturating_sub(3);
    let backend = ratatui::backend::TestBackend::new(120, 20);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let (band_y, pinned_idx) = {
        let rows = app.tree.sticky_rows_for_test();
        // The MIDDLE pinned row ("outer") is where the behaviors diverge:
        // the outermost is the workspace root (dropping a root-level file
        // into its own parent is correctly refused), and the deepest
        // ("inner") coincides with the covered rows' parent, where the old
        // sticky-blind resolution accidentally agreed.
        assert!(rows.len() >= 3, "band must pin root/outer/inner here");
        rows[1]
    };
    let loose = tmp.path().join("loose.txt");
    let target = drag_target_index(&app.tree, band_y, std::slice::from_ref(&loose))
        .expect("a pinned directory is a valid drop target");
    assert_eq!(
        target, pinned_idx,
        "the drop target under the band is the PINNED directory, not the covered row"
    );
    let covered = app.tree.node_at_y(band_y);
    assert_ne!(
        covered,
        Some(target),
        "precondition: the band actually covers a different row there"
    );
    let _ = MouseEventKind::Down(MouseButton::Left); // silence unused import paths on some cfgs
}

#[test]
fn fold_all_regions_command_works_with_no_language_server_attached() {
    // #254's fallback criterion: region folding must work when no LSP
    // ever answers — here the file's language has no server at all.
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(
        tmp.path().join("notes.txt"),
        "#region setup\nline a\nline b\n#endregion\nrest\n",
    )
    .unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor
        .open_pinned(&tmp.path().join("notes.txt"))
        .unwrap();
    app.focus_pane(Pane::Editor);
    app.run_command(crate::widgets::command_palette::Command::FoldAllRegions);
    assert!(app.editor.is_line_hidden(1) && app.editor.is_line_hidden(2));
    assert!(!app.editor.is_line_hidden(0) && !app.editor.is_line_hidden(4));
    app.run_command(crate::widgets::command_palette::Command::UnfoldAllRegions);
    assert!(!app.editor.is_line_hidden(1), "regions expanded again");
}

/// #1653: the issue's `nested.py` open with the caret on line 1. Lines:
/// 0 `class Outer`, 1 `def method_one`, 2 `if`, 3 `for`, 4 `print`,
/// 5 `def method_two`, 6 `return`.
fn nested_fold_app(dir: &std::path::Path) -> App {
    std::fs::write(
        dir.join("nested.py"),
        "class Outer:\n    def method_one(self):\n        if True:\n            for i in range(10):\n                print(i)\n    def method_two(self):\n        return 1\n",
    )
    .unwrap();
    let mut app = App::new(dir.to_path_buf()).unwrap();
    app.editor.open_pinned(&dir.join("nested.py")).unwrap();
    app.focus_pane(Pane::Editor);
    app
}

/// #1653: the lines of the open buffer still in view.
fn visible_lines(app: &App) -> Vec<usize> {
    (0..app.editor.lines.len())
        .filter(|&l| !app.editor.is_line_hidden(l))
        .collect()
}

fn run_fold_command(app: &mut App, id: &str) {
    let cmd = crate::widgets::command_palette::Command::from_id(id)
        .unwrap_or_else(|| panic!("croft has no {id} command"));
    app.run_command(cmd);
}

/// #1653: Fold Level 2 leaves the class and both methods in view with the
/// bodies collapsed, the overview Fold All cannot give.
#[test]
fn fold_level_2_keeps_the_class_and_its_methods_in_view() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = nested_fold_app(tmp.path());
    run_fold_command(&mut app, "fold_level_2");
    assert_eq!(visible_lines(&app), vec![0, 1, 5]);
}

/// #1653: Fold Level 1 collapses the class only, as VS Code does: opening
/// the class again shows what was inside it as it was before.
#[test]
fn fold_level_1_collapses_only_the_class() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = nested_fold_app(tmp.path());
    run_fold_command(&mut app, "fold_level_1");
    assert_eq!(visible_lines(&app), vec![0]);
    app.editor.toggle_fold(0);
    assert_eq!(visible_lines(&app), (0..7).collect::<Vec<_>>());
    // A deeper fold the user closed earlier keeps its state.
    app.editor.toggle_fold(2);
    run_fold_command(&mut app, "fold_level_1");
    app.editor.toggle_fold(0);
    assert_eq!(visible_lines(&app), vec![0, 1, 2, 5, 6]);
}

/// #1653: Cmd+K Cmd+3 is Fold Level 3: the `if` and the `for` inside it
/// collapse, both methods stay open.
#[test]
fn cmd_k_cmd_3_folds_level_3() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = nested_fold_app(tmp.path());
    app.handle_key(key(KeyCode::Char('k'), KeyModifiers::SUPER))
        .unwrap();
    app.handle_key(key(KeyCode::Char('3'), KeyModifiers::SUPER))
        .unwrap();
    assert_eq!(visible_lines(&app), vec![0, 1, 2, 5, 6]);
}

/// #1653: Fold Recursively on `method_one` collapses it and the `if`/`for`
/// inside, so opening the method shows the `if` still folded; Unfold
/// Recursively opens all of it.
#[test]
fn fold_recursively_collapses_the_block_and_everything_inside() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = nested_fold_app(tmp.path());
    app.editor.cursor_row = 1;
    run_fold_command(&mut app, "fold_recursively");
    assert_eq!(visible_lines(&app), vec![0, 1, 5, 6]);
    app.editor.toggle_fold(1);
    assert_eq!(
        visible_lines(&app),
        vec![0, 1, 2, 5, 6],
        "the if stays folded"
    );
    app.editor.toggle_fold(1);
    run_fold_command(&mut app, "unfold_recursively");
    assert_eq!(visible_lines(&app), (0..7).collect::<Vec<_>>());
}

/// #1653 negative: Unfold Recursively leaves a fold outside its block alone,
/// and a fold level on a file with nothing to fold changes nothing.
#[test]
fn recursive_and_level_folds_stay_inside_their_scope() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = nested_fold_app(tmp.path());
    app.editor.toggle_fold(5);
    app.editor.cursor_row = 1;
    run_fold_command(&mut app, "fold_recursively");
    run_fold_command(&mut app, "unfold_recursively");
    assert_eq!(
        visible_lines(&app),
        vec![0, 1, 2, 3, 4, 5],
        "method_two is still folded"
    );

    std::fs::write(tmp.path().join("flat.txt"), "one\ntwo\nthree\n").unwrap();
    app.editor
        .open_pinned(&tmp.path().join("flat.txt"))
        .unwrap();
    run_fold_command(&mut app, "fold_level_1");
    assert_eq!(visible_lines(&app), vec![0, 1, 2]);
}

/// #1653: VS Code's fold level and recursive fold keybindings import.
#[test]
fn vscode_fold_level_keybindings_import() {
    let mut report = crate::import_vscode::Report::default();
    crate::import_vscode::convert_keybindings(
        &serde_json::json!([
            { "key": "ctrl+alt+2", "command": "editor.foldLevel2" },
            { "key": "ctrl+alt+r", "command": "editor.foldRecursively" },
            { "key": "ctrl+alt+u", "command": "editor.unfoldRecursively" }
        ]),
        &mut report,
    );
    assert!(
        report.dropped_keybindings.is_empty(),
        "{:?}",
        report.dropped_keybindings
    );
    let commands: Vec<String> = serde_json::to_value(&report.keybindings)
        .unwrap()
        .as_array()
        .unwrap()
        .iter()
        .map(|row| row[1].as_str().unwrap().to_string())
        .collect();
    assert_eq!(
        commands,
        vec!["fold_level_2", "fold_recursively", "unfold_recursively"]
    );
}

#[test]
fn expand_selection_falls_back_to_tree_sitter_when_the_lsp_cannot_route() {
    // #254 item 2's serverless criterion, end to end: the worker answers
    // `unsupported` for an untracked doc, and the drained verdict grows
    // the selection from tree-sitter node ancestry — the gesture never
    // hangs and never needs a real server.
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(
        tmp.path().join("lib.rs"),
        "fn main() {\n    let value = 1;\n}\n",
    )
    .unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&tmp.path().join("lib.rs")).unwrap();
    app.focus_pane(Pane::Editor);
    app.editor.cursor_row = 1;
    app.editor.cursor_col = 9; // inside `value`
    app.run_command(crate::widgets::command_palette::Command::ExpandSelection);
    // The request is in flight; the worker's unsupported verdict lands
    // asynchronously. Drain until it resolves the queued press.
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
    while app.editor.selection.is_none() && std::time::Instant::now() < deadline {
        app.drain_lsp_selection_ranges();
        std::thread::sleep(std::time::Duration::from_millis(20));
    }
    let sel = app
        .editor
        .selection
        .expect("the fallback grew a selection")
        .normalised();
    assert!(
        sel.0 <= (1, 8) && sel.1 >= (1, 13),
        "the identifier (or an enclosing node) is selected: {sel:?}"
    );
    // Shrink retraces locally, no LSP involved.
    app.run_command(crate::widgets::command_palette::Command::ShrinkSelection);
    assert!(app.editor.selection.is_none(), "back to the bare caret");
}

#[test]
fn cmd_k_shift_e_runs_the_caret_lines_only_lens() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "a.rs", "fn main() {}\n");
    app.editor.code_lenses = vec![lens_at(
        0,
        "fn main() {}",
        "Frobnicate",
        "vendor.frobnicate",
    )];
    assert!(app.handle_cmd_k_chord(key(KeyCode::Char('E'), KeyModifiers::SHIFT)));
    assert!(app.status.starts_with("Code lens:"), "{}", app.status);
    app.editor
        .code_lenses
        .push(lens_at(0, "fn main() {}", "Other", "vendor.other"));
    assert!(app.handle_cmd_k_chord(key(KeyCode::Char('e'), KeyModifiers::SHIFT)));
    assert!(
        app.context_menu.is_some(),
        "two lenses open a menu to pick from"
    );
}

/// #682: typing re-bakes the minimap at most every `MINIMAP_EDIT_REBAKE`,
/// and the deferred bake still lands once the wait is over.
#[test]
fn minimap_rebakes_for_typing_at_most_every_few_hundred_ms() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.cell_pixel = Some((8, 16));
    app.inline_protocol = crate::iterm2_inline::InlineImageProtocol::Kitty;
    app.editor.lines = (0..80).map(|i| format!("line {i}")).collect();
    let strip = ratatui::layout::Rect {
        x: 100,
        y: 1,
        width: 6,
        height: 40,
    };
    app.update_minimap_overlay(strip);
    let first = app.minimap_image_payload().map(|(o, _)| o.to_string());
    assert!(first.is_some());
    app.editor.lines[0] = String::from("changed");
    app.editor.edit_seq += 1;
    app.update_minimap_overlay(strip);
    assert_eq!(
        app.minimap_image_payload().map(|(o, _)| o.to_string()),
        first,
        "a keystroke right after a bake waits"
    );
    assert!(!app.tick_minimap(), "not due yet");
    app.minimap.baked_at = Some(std::time::Instant::now() - super::MINIMAP_EDIT_REBAKE);
    assert!(app.tick_minimap(), "the wait is over: redraw");
    assert!(
        !app.tick_minimap(),
        "one redraw per deferred bake, even if the minimap is gone by then"
    );
    app.update_minimap_overlay(strip);
    assert_ne!(
        app.minimap_image_payload().map(|(o, _)| o.to_string()),
        first,
        "the deferred edit is baked"
    );
    assert!(!app.tick_minimap());
    // Scrolling is not held back.
    app.editor.scroll = 5;
    let before = app.minimap_image_payload().map(|(o, _)| o.to_string());
    app.update_minimap_overlay(strip);
    assert_ne!(
        app.minimap_image_payload().map(|(o, _)| o.to_string()),
        before
    );
}

/// #850: a syntax pass that outlives its keystroke lands through the tick,
/// in the focused group and in a split's other group alike, with the colors
/// a whole-buffer pass gives, and the minimap strip re-bakes in them.
#[test]
fn a_syntax_pass_that_outlives_the_keystroke_lands_on_a_later_tick() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "main.rs", "fn main() {\n    let x = 1;\n}\n");
    app.split_editor();
    let path = tmp.path().join("main.rs");
    let type_into = |ed: &mut crate::widgets::editor::Editor| {
        ed.defer_highlights_for_test();
        ed.cursor_row = 1;
        ed.cursor_col = 4;
        ed.insert_str("let y = \"s\"; // (note)\n    ");
        assert!(ed.highlight_pending(), "the keystroke did not wait");
    };
    type_into(&mut app.editor);
    type_into(app.editor_layout.inactive_groups_mut().next().unwrap());
    app.cell_pixel = Some((8, 16));
    app.inline_protocol = crate::iterm2_inline::InlineImageProtocol::Kitty;
    let strip = ratatui::layout::Rect {
        x: 100,
        y: 1,
        width: 6,
        height: 40,
    };
    app.update_minimap_overlay(strip);
    let carried = app.minimap_image_payload().map(|(o, _)| o.to_string());
    assert!(carried.is_some());

    let pending = |app: &mut App| {
        app.editor.highlight_pending()
            || app
                .editor_layout
                .inactive_groups()
                .next()
                .unwrap()
                .highlight_pending()
    };
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(60);
    let mut landed = false;
    while pending(&mut app) {
        landed |= app.poll_highlights();
        assert!(
            std::time::Instant::now() < deadline,
            "the passes never landed"
        );
        std::thread::sleep(std::time::Duration::from_millis(1));
    }
    assert!(
        landed,
        "the tick reported the landing, so the frame repaints"
    );
    let want = |lines: &[String]| {
        let fresh =
            crate::widgets::editor::Editor::historical(&path, &lines.join("\n"), Vec::new());
        format!("{:?}", fresh.highlights_for_test())
    };
    let inactive = &app.editor_layout.inactive_groups().next().unwrap();
    assert_eq!(
        format!("{:?}", inactive.highlights_for_test()),
        want(&inactive.lines),
        "the other group's tab"
    );
    assert_eq!(
        format!("{:?}", app.editor.highlights_for_test()),
        want(&app.editor.lines),
        "the focused tab"
    );

    app.minimap.baked_at = Some(std::time::Instant::now() - super::MINIMAP_EDIT_REBAKE);
    app.update_minimap_overlay(strip);
    assert_ne!(
        app.minimap_image_payload().map(|(o, _)| o.to_string()),
        carried,
        "the strip re-bakes in the landed colors"
    );
}

/// #682: the minimap PNG is compressed hard; a typical strip encodes to a
/// fraction of its default size.
#[test]
fn the_minimap_png_is_small() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.lines = (0..400)
        .map(|i| format!("    let value_{i} = compute(a, b, {i}); // note"))
        .collect();
    let (w, h) = (6 * 9, 45 * 18);
    let rgba = app
        .editor
        .minimap_rgba(w, h, h, (30, 30, 30), (200, 200, 200));
    let png = super::rgba_to_png(rgba, w, h).unwrap();
    assert!(png.len() < 1500, "{} bytes", png.len());
    assert!(image::load_from_memory(&png).is_ok());
}

#[test]
fn home_after_scrolling_right_brings_the_view_back() {
    let tmp = tempfile::tempdir().unwrap();
    let (mut app, _term) = wide_line_app(tmp.path());
    app.handle_key(key(KeyCode::End, KeyModifiers::NONE))
        .unwrap();
    app.editor.scroll_col = 500;
    app.editor.cursor_col = 600;
    app.handle_key(key(KeyCode::Home, KeyModifiers::NONE))
        .unwrap();
    assert_eq!(app.editor.cursor_col, 0);
    assert_eq!(app.editor.scroll_col, 0);
}

/// After Reopen with Encoding, the gutter baseline is HEAD decoded the same
/// way, so the added line gets its bar and the old lines none.
#[test]
fn a_windows_1252_file_gets_gutter_marks_after_reopen_with_encoding() {
    let (tmp, f) = encoded_repo("latin1.txt", LATIN1_HEAD, LATIN1_ADDED);
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&f).unwrap();
    app.sync_git_gutters();
    app.editor
        .reopen_with_encoding(encoding_rs::WINDOWS_1252)
        .unwrap();
    app.sync_git_gutters();
    assert_eq!(
        app.editor.git_head_lines,
        Some(crate::packed_lines::PackedLines::from(
            &["name;city", "Müller;Köln", "José;Málaga"][..]
        ))
    );
    draw(&mut app, 100, 30);
    assert_eq!(
        app.editor.git_mark_at(3),
        Some(crate::widgets::editor::GitMark::Added)
    );
    assert_eq!(app.editor.git_mark_at(1), None);
}

/// A UTF-16LE file with a BOM is decoded as UTF-16 on both sides.
#[test]
fn a_utf16_file_gets_gutter_marks() {
    let utf16 = |s: &str| -> Vec<u8> { s.encode_utf16().flat_map(u16::to_le_bytes).collect() };
    let head = [&[0xff, 0xfe][..], &utf16("one\ntwo\n")].concat();
    let (tmp, f) = encoded_repo("app.rc", &head, &utf16("three\n"));
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open_pinned(&f).unwrap();
    app.sync_git_gutters();
    assert_eq!(
        app.editor.git_head_lines,
        Some(crate::packed_lines::PackedLines::from(&["one", "two"][..]))
    );
    draw(&mut app, 100, 30);
    assert_eq!(
        app.editor.git_mark_at(2),
        Some(crate::widgets::editor::GitMark::Added)
    );
}

// --- Minimap without inline images (#1231) --------------------------------

/// An app with a 300-line Rust file open, in a terminal that cannot draw
/// inline images (tmux, Alacritty, GNOME Terminal, plain xterm).
fn text_minimap_app() -> (tempfile::TempDir, App) {
    let tmp = tempfile::tempdir().unwrap();
    let path = tmp.path().join("long.rs");
    let body: String = (0..300)
        .map(|i| format!("fn f{i}() {{ let value = {i}; }}\n"))
        .collect();
    std::fs::write(&path, body).unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.inline_protocol = crate::iterm2_inline::InlineImageProtocol::None;
    app.cell_pixel = None;
    app.editor.open(&path).unwrap();
    (tmp, app)
}

fn is_braille(s: &str) -> bool {
    s.chars()
        .next()
        .is_some_and(|c| ('\u{2801}'..='\u{28ff}').contains(&c))
}

/// The braille cells drawn inside `r`.
fn braille_in(term: &ratatui::Terminal<ratatui::backend::TestBackend>, r: Rect) -> usize {
    let buf = term.backend().buffer();
    let mut n = 0;
    for y in r.y..r.y + r.height {
        for x in r.x..r.x + r.width {
            if is_braille(buf[(x, y)].symbol()) {
                n += 1;
            }
        }
    }
    n
}

#[test]
fn the_minimap_draws_as_braille_without_inline_images() {
    let (_tmp, mut app) = text_minimap_app();
    let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(160, 40)).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let strip = app.minimap.img_rect;
    assert_eq!(strip.width, 6, "the strip is carved: {strip:?}");
    assert!(
        braille_in(&term, strip) > 0,
        "the strip shows the file's shape:\n{}",
        screen_text(&term)
    );
    let text = app.editor.last_full_area;
    assert_eq!(
        strip.x,
        text.x + text.width,
        "the strip sits right of the text"
    );
}

/// On Croft Loch the tab strip's chrome runs through the minimap's column
/// to the right edge instead of stopping a black column short, and the seam
/// under the breadcrumbs crosses the column too.
#[test]
fn a_loch_tab_strip_and_header_seam_run_through_the_minimap_column() {
    let (_tmp, mut app) = text_minimap_app();
    let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(160, 40)).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let t = crate::theme::tones(app.theme).expect("Loch is the default");
    let strip = app.minimap.img_rect;
    let top = app.editor.last_full_area.y;
    let seam_y = app.editor.last_body.y;
    let buf = term.backend().buffer();
    for x in strip.x..strip.x + strip.width {
        assert_eq!(buf[(x, top)].bg, app.theme.tab_strip_bg(), "column {x}");
        assert_eq!(buf[(x, seam_y)].symbol(), "\u{2594}", "column {x}");
        assert_eq!(buf[(x, seam_y)].fg, t.hairline());
    }
}

/// While a modal quick input has the keyboard, Croft Loch takes the accent
/// lip off the editor's top seam (a hairline remains); focus itself stays
/// on the editor, and the lip returns when the palette closes.
#[test]
fn a_modal_quick_input_takes_the_accent_off_the_editor_seam() {
    let (_tmp, mut app) = text_minimap_app();
    app.focus_pane(Pane::Editor);
    let t = crate::theme::tones(app.theme).expect("Loch is the default");
    let seam = |app: &mut App| {
        let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(160, 40)).unwrap();
        term.draw(|f| app.render(f)).unwrap();
        let body = app.editor.last_body;
        term.backend().buffer()[(body.x, body.y)].fg
    };
    // The palette's scrim sinks everything behind the card, the seam
    // included, so the palette-open seam is the hairline as the scrim
    // leaves it on the black canvas.
    let theme = app.theme;
    let behind_scrim = |c: ratatui::style::Color| {
        let mut b = ratatui::buffer::Buffer::empty(Rect::new(0, 0, 1, 1));
        b[(0, 0)].set_fg(c).set_bg(t.canvas());
        crate::widgets::surface::dim_backdrop(&mut b, Rect::default(), theme);
        b[(0, 0)].fg
    };
    assert_eq!(seam(&mut app), t.accent(), "the focused editor's lip");
    app.open_command_palette();
    let palette_open = seam(&mut app);
    assert_eq!(
        palette_open,
        behind_scrim(t.hairline()),
        "the palette has the keyboard"
    );
    assert_ne!(palette_open, behind_scrim(t.accent()));
    assert!(app.focus == Pane::Editor && app.editor.focused);
    app.command_palette = None;
    assert_eq!(seam(&mut app), t.accent());
}

/// Croft Loch's layout icons are header actions: muted at rest, and under
/// the pointer the strong ink on a faint chip across the two-cell slot,
/// never the accent.
#[test]
fn loch_layout_icons_rest_muted_and_lift_on_a_chip() {
    let (_tmp, mut app) = text_minimap_app();
    app.chrome_bake = None;
    app.overlays.activity.clear_images();
    draw(&mut app, 160, 40);
    let t = crate::theme::tones(app.theme).expect("Loch is the default");
    let side = app.layout_icon_areas.toggle_side_bar;
    let cust = app.layout_icon_areas.customize;
    assert!(side.width == 2 && cust.width == 2);
    app.pointer_cell = Some((cust.x, cust.y));
    let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(160, 40)).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let buf = term.backend().buffer();
    let idle = &buf[(side.x + 1, side.y)];
    assert_eq!(idle.fg, t.muted());
    assert_eq!(idle.bg, app.theme.tab_strip_bg(), "no chip at rest");
    let chip = t.hover_on(t.chrome);
    assert_eq!(buf[(cust.x + 1, cust.y)].fg, t.strong());
    assert_eq!(buf[(cust.x, cust.y)].bg, chip);
    assert_eq!(buf[(cust.x + 1, cust.y)].bg, chip);
}

#[test]
fn a_click_on_the_text_minimap_jumps_to_that_part_of_the_file() {
    let (_tmp, mut app) = text_minimap_app();
    draw(&mut app, 160, 40);
    let strip = app.minimap.img_rect;
    assert!(strip.height > 0);
    assert_eq!(app.editor.scroll, 0);
    // 300 lines at one dot row each fill 75 cell rows; the strip is shorter,
    // so the whole file is folded into it and the bottom row is the end.
    left_click(&mut app, strip.x + 2, strip.y + strip.height - 1);
    assert!(
        app.editor.cursor_row > 250,
        "the bottom of the strip is the end of the file: row {}",
        app.editor.cursor_row
    );
}

#[test]
fn the_minimap_stays_on_the_active_group_in_a_split() {
    let (_tmp, mut app) = text_minimap_app();
    app.split_editor();
    assert!(app.editor_layout.is_split());
    let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(200, 40)).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let strip = app.minimap.img_rect;
    let active = app.editor.last_full_area;
    assert_eq!(strip.width, 6, "a split keeps the minimap: {strip:?}");
    assert!(braille_in(&term, strip) > 0, "{}", screen_text(&term));
    assert!(
        strip.x == active.x + active.width || strip.x + strip.width == active.x,
        "the strip is beside the active group: strip {strip:?}, group {active:?}"
    );
}

#[test]
fn the_minimap_off_draws_no_strip() {
    let (_tmp, mut app) = text_minimap_app();
    app.toggle_minimap();
    assert_eq!(app.status, "Minimap off");
    let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(160, 40)).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    assert_eq!(app.minimap.img_rect, Rect::default());
    let screen = screen_text(&term);
    assert!(
        !screen.chars().any(|c| is_braille(&c.to_string())),
        "{screen}"
    );
}

#[test]
fn turning_the_minimap_on_in_a_narrow_editor_says_why_it_is_hidden() {
    let (_tmp, mut app) = text_minimap_app();
    app.toggle_minimap();
    draw(&mut app, 70, 30);
    app.toggle_minimap();
    assert!(
        app.status.starts_with("Minimap on") && app.status.contains("wide"),
        "{}",
        app.status
    );
    // With room, the toggle just says it is on.
    app.toggle_minimap();
    draw(&mut app, 160, 40);
    app.toggle_minimap();
    assert_eq!(app.status, "Minimap on");
}

#[test]
fn braille_minimap_folds_each_two_by_four_dot_block_into_a_cell() {
    let bg = (0, 0, 0);
    let ink = (200, 100, 50);
    // One cell: 2 dot columns of 4 source chars each, 4 dot rows.
    let (w, h) = (2 * MINIMAP_TEXT_CHARS_PER_DOT, 4);
    let mut rgba = vec![0u8; (w * h * 4) as usize];
    for px in rgba.chunks_exact_mut(4) {
        px[3] = 0xff;
    }
    let cells = braille_minimap(&rgba, w, h, bg, 1, 1);
    assert_eq!(cells, vec![None], "a blank block is a blank cell");
    // Ink in the second char of the first dot column, top row: dot 1.
    let idx = 4;
    rgba[idx..idx + 3].copy_from_slice(&[ink.0, ink.1, ink.2]);
    assert_eq!(
        braille_minimap(&rgba, w, h, bg, 1, 1),
        vec![Some(('\u{2801}', ink))]
    );
    // Every dot lit is the full cell.
    for px in rgba.chunks_exact_mut(4) {
        px[..3].copy_from_slice(&[ink.0, ink.1, ink.2]);
    }
    assert_eq!(
        braille_minimap(&rgba, w, h, bg, 1, 1),
        vec![Some(('\u{28ff}', ink))]
    );
}

/// #1569: Shift+End in a wrapped paragraph selects to the end of the row the
/// caret is on, not the rest of the paragraph; a second Shift+End extends it
/// to the line's end.
#[test]
fn shift_end_in_a_wrapped_paragraph_selects_to_the_end_of_the_row() {
    let tmp = tempfile::tempdir().unwrap();
    let f = tmp.path().join("long.txt");
    let words: Vec<String> = (0..60).map(|i| format!("word{i}")).collect();
    std::fs::write(&f, format!("Notes: {}\n", words.join(" "))).unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&f).unwrap();
    app.editor.toggle_wrap();
    assert!(app.editor.wrap_enabled());
    app.focus_pane(Pane::Editor);
    draw(&mut app, 100, 30);
    app.handle_editor_key(key(KeyCode::Down, KeyModifiers::NONE));
    let row_start = app.editor.cursor_col;
    assert!(row_start > 0, "Down moved onto row 2 of line 1");
    app.handle_editor_key(key(KeyCode::End, KeyModifiers::SHIFT));
    let selected = app.editor.selection_text();
    assert!(
        !selected.is_empty() && selected.len() < 60,
        "one row, not the paragraph: {selected:?}"
    );
    assert_eq!(
        app.editor.lines[0].chars().nth(app.editor.cursor_col),
        Some(' '),
        "up to the space the row breaks at: {selected:?}"
    );
    app.handle_editor_key(key(KeyCode::End, KeyModifiers::SHIFT));
    let selected = app.editor.selection_text();
    assert!(selected.ends_with("word59"), "{selected:?}");
}

/// #1569 negative: Ctrl+A / Ctrl+E stay readline's start / end of the
/// logical line in a wrapped paragraph, one press each.
#[test]
fn ctrl_a_and_ctrl_e_reach_the_line_ends_in_a_wrapped_paragraph() {
    let tmp = tempfile::tempdir().unwrap();
    let f = tmp.path().join("long.txt");
    let words: Vec<String> = (0..60).map(|i| format!("word{i}")).collect();
    std::fs::write(&f, format!("Notes: {}\n", words.join(" "))).unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&f).unwrap();
    app.editor.toggle_wrap();
    assert!(app.editor.wrap_enabled());
    app.focus_pane(Pane::Editor);
    draw(&mut app, 100, 30);
    app.handle_editor_key(key(KeyCode::Down, KeyModifiers::NONE));
    assert!(app.editor.cursor_col > 0, "Down moved onto row 2 of line 1");
    let mid_row = app.editor.cursor_col + 3;
    app.handle_editor_key(key(KeyCode::Char('e'), KeyModifiers::CONTROL));
    assert_eq!(app.editor.cursor_col, app.editor.lines[0].chars().count());
    app.editor.cursor_col = mid_row;
    app.handle_editor_key(key(KeyCode::Char('a'), KeyModifiers::CONTROL));
    assert_eq!(app.editor.cursor_col, 0);
}

/// #1576: "View: Change Line Numbers" steps on, relative, interval, off
/// and back, on every open editor, including tabs opened afterwards.
#[test]
fn change_line_numbers_cycles_modes_across_every_editor() {
    use crate::widgets::editor::LineNumbers;
    let mut app = editor_app_with_lines(&["a b"]);
    let all_in =
        |app: &App, mode: LineNumbers| app.editor.editors.iter().all(|e| e.line_numbers == mode);
    assert_eq!(app.line_numbers, LineNumbers::On, "on by default");
    let mut seen = Vec::new();
    for _ in 0..4 {
        app.run_command(crate::widgets::command_palette::Command::CycleLineNumbers);
        app.editor
            .open_text_buffer(std::path::Path::new("later.txt"), "c d")
            .unwrap();
        app.sync_focus_flags();
        assert!(all_in(&app, app.line_numbers), "{:?}", app.line_numbers);
        seen.push(app.status.clone());
    }
    assert_eq!(
        seen,
        [
            "Line Numbers: relative",
            "Line Numbers: interval",
            "Line Numbers: off",
            "Line Numbers: on"
        ]
    );
}

/// #1576: the palette command and a settings reload both reach the split
/// beside the active one at once, not at the next focus change.
#[test]
fn line_numbers_reach_every_split_group() {
    use crate::widgets::editor::LineNumbers;
    let tmp = tempfile::tempdir().unwrap();
    let mut app = app_with_open_file(tmp.path(), "a.txt", "a\nb\n");
    app.split_editor_dir(editor_layout::SplitDir::Horizontal, true);
    let modes = |app: &App| -> Vec<LineNumbers> {
        app.editor_layout
            .all_groups(&app.editor)
            .flat_map(|group| group.editors.iter().map(|e| e.line_numbers))
            .collect()
    };
    assert_eq!(modes(&app), [LineNumbers::On, LineNumbers::On]);

    app.run_command(crate::widgets::command_palette::Command::CycleLineNumbers);
    assert_eq!(modes(&app), [LineNumbers::Relative, LineNumbers::Relative]);

    let prefs = crate::prefs::Prefs {
        line_numbers: String::from("off"),
        ..Default::default()
    };
    app.apply_merged_settings(&prefs);
    assert_eq!(modes(&app), [LineNumbers::Off, LineNumbers::Off]);
}

fn overwrite_app(text: &str) -> (tempfile::TempDir, App) {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.focus = Pane::Editor;
    app.editor.lines = text.lines().map(String::from).collect();
    app.editor.cursor_row = 0;
    app.editor.cursor_col = 0;
    (tmp, app)
}

#[test]
fn insert_key_toggles_overwrite_mode_and_typing_replaces() {
    let (_t, mut app) = overwrite_app("abcdef");
    app.handle_key(key(KeyCode::Char('X'), KeyModifiers::NONE))
        .unwrap();
    assert_eq!(
        app.editor.lines[0], "Xabcdef",
        "insert mode pushes the text"
    );
    app.handle_key(key(KeyCode::Insert, KeyModifiers::NONE))
        .unwrap();
    assert!(app.overwrite_mode);
    assert_eq!(app.status, "Overwrite mode");
    app.handle_key(key(KeyCode::Char('Y'), KeyModifiers::NONE))
        .unwrap();
    app.handle_key(key(KeyCode::Char('Z'), KeyModifiers::NONE))
        .unwrap();
    assert_eq!(app.editor.lines[0], "XYZcdef", "overwrite replaces a, b");
    assert_eq!(app.editor.cursor_col, 3);
    app.handle_key(key(KeyCode::Insert, KeyModifiers::NONE))
        .unwrap();
    assert!(!app.overwrite_mode);
    assert_eq!(app.status, "Insert mode");
    app.handle_key(key(KeyCode::Char('!'), KeyModifiers::NONE))
        .unwrap();
    assert_eq!(app.editor.lines[0], "XYZ!cdef");
}

#[test]
fn overwrite_appends_at_the_end_of_a_line_and_replaces_a_whole_emoji() {
    let (_t, mut app) = overwrite_app("a\u{1F468}\u{200D}\u{1F469}b");
    app.overwrite_mode = true;
    app.editor.cursor_col = 1;
    app.handle_key(key(KeyCode::Char('x'), KeyModifiers::NONE))
        .unwrap();
    assert_eq!(app.editor.lines[0], "axb", "the ZWJ cluster goes as one");
    app.editor.cursor_col = 3;
    app.handle_key(key(KeyCode::Char('!'), KeyModifiers::NONE))
        .unwrap();
    assert_eq!(app.editor.lines[0], "axb!", "at the line end it appends");
}

#[test]
fn overwrite_typing_undoes_in_one_step_and_a_selection_is_replaced_as_usual() {
    let (_t, mut app) = overwrite_app("hello");
    app.overwrite_mode = true;
    app.handle_key(key(KeyCode::Char('J'), KeyModifiers::NONE))
        .unwrap();
    app.handle_key(key(KeyCode::Char('K'), KeyModifiers::NONE))
        .unwrap();
    assert_eq!(app.editor.lines[0], "JKllo");
    app.editor.undo();
    assert_eq!(app.editor.lines[0], "hello", "one undo step for the run");
    app.editor.cursor_col = 1;
    app.editor.selection = Some(crate::widgets::editor::EditorSelection {
        anchor: (0, 1),
        head: (0, 4),
    });
    app.editor.cursor_col = 4;
    app.handle_key(key(KeyCode::Char('_'), KeyModifiers::NONE))
        .unwrap();
    assert_eq!(app.editor.lines[0], "h_o", "a selection is replaced, once");
}

#[test]
fn switching_the_typing_mode_starts_a_new_undo_step() {
    let (_t, mut app) = overwrite_app("hello");
    app.handle_key(key(KeyCode::Char('A'), KeyModifiers::NONE))
        .unwrap();
    app.handle_key(key(KeyCode::Insert, KeyModifiers::NONE))
        .unwrap();
    app.handle_key(key(KeyCode::Char('B'), KeyModifiers::NONE))
        .unwrap();
    assert_eq!(app.editor.lines[0], "ABello");
    app.editor.undo();
    assert_eq!(
        app.editor.lines[0], "Ahello",
        "the overwrite run undoes on its own"
    );
    app.editor.undo();
    assert_eq!(app.editor.lines[0], "hello");
}

#[test]
fn overwrite_leaves_the_caret_after_a_cluster_the_typed_char_joins() {
    // U+1F1FA before the French flag's two indicators pairs with the first of
    // them, so the caret must step past that new pair, not stop inside it.
    let (_t, mut app) = overwrite_app("a\u{1F1EB}\u{1F1F7}");
    app.overwrite_mode = true;
    app.handle_key(key(KeyCode::Char('\u{1F1FA}'), KeyModifiers::NONE))
        .unwrap();
    assert_eq!(app.editor.lines[0], "\u{1F1FA}\u{1F1EB}\u{1F1F7}");
    assert_eq!(app.editor.cursor_col, 2, "after the joined pair");
    app.handle_key(key(KeyCode::Char('x'), KeyModifiers::NONE))
        .unwrap();
    assert_eq!(
        app.editor.lines[0], "\u{1F1FA}\u{1F1EB}x",
        "the next key replaces the cluster after the caret"
    );
}

#[test]
fn overwrite_adds_a_combining_mark_to_the_letter_before_the_caret() {
    // The accent belongs to the `e` just typed: it must not eat the `b`.
    let (_t, mut app) = overwrite_app("abcd");
    app.overwrite_mode = true;
    app.handle_key(key(KeyCode::Char('e'), KeyModifiers::NONE))
        .unwrap();
    app.handle_key(key(KeyCode::Char('\u{301}'), KeyModifiers::NONE))
        .unwrap();
    assert_eq!(app.editor.lines[0], "e\u{301}bcd");
    assert_eq!(app.editor.cursor_col, 2);
    app.handle_key(key(KeyCode::Char('x'), KeyModifiers::NONE))
        .unwrap();
    assert_eq!(
        app.editor.lines[0], "e\u{301}xcd",
        "the next key replaces again"
    );
    app.editor.undo();
    assert_eq!(
        app.editor.lines[0], "abcd",
        "still one undo step for the run"
    );
}

#[test]
fn overwrite_steps_past_an_emoji_a_typed_zwj_joins() {
    // A ZWJ typed between 👩 and 💻 makes one 👩‍💻: the caret goes after it,
    // so the next key replaces the `x`, not the 💻.
    let (_t, mut app) = overwrite_app("\u{1F469}\u{1F4BB}x");
    app.overwrite_mode = true;
    app.editor.cursor_col = 1;
    app.handle_key(key(KeyCode::Char('\u{200D}'), KeyModifiers::NONE))
        .unwrap();
    assert_eq!(app.editor.lines[0], "\u{1F469}\u{200D}\u{1F4BB}x");
    assert_eq!(app.editor.cursor_col, 3, "after the joined emoji");
    app.handle_key(key(KeyCode::Char('a'), KeyModifiers::NONE))
        .unwrap();
    assert_eq!(app.editor.lines[0], "\u{1F469}\u{200D}\u{1F4BB}a");
}

#[test]
fn overwrite_drops_the_empty_selection_a_click_leaves() {
    let (_t, mut app) = overwrite_app("abcd");
    app.overwrite_mode = true;
    app.editor.selection = Some(crate::widgets::editor::EditorSelection {
        anchor: (0, 0),
        head: (0, 0),
    });
    app.handle_key(key(KeyCode::Char('x'), KeyModifiers::NONE))
        .unwrap();
    assert_eq!(app.editor.lines[0], "xbcd");
    assert!(
        app.editor.selection.is_none(),
        "no stale anchor for a later Shift+arrow"
    );
}

#[test]
fn overwrite_mode_is_shown_by_a_glyph_after_the_workspace_cap_not_in_the_position() {
    let (_t, mut app) = overwrite_app("abc");
    let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(120, 30)).unwrap();
    let bar = |t: &ratatui::Terminal<ratatui::backend::TestBackend>| -> String {
        let b = t.backend().buffer();
        let y = b.area.height - 1;
        (0..b.area.width)
            .map(|x| b[(x, y)].symbol().to_string())
            .collect()
    };
    term.draw(|f| app.render(f)).unwrap();
    let insert = bar(&term);
    assert!(
        !insert.contains('\u{2380}') && !insert.contains('\u{2381}'),
        "Insert, the default, adds nothing to the bar: {insert}"
    );
    app.handle_key(key(KeyCode::Insert, KeyModifiers::NONE))
        .unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let over = bar(&term);
    // The workspace cap ends on its rounded right edge; the glyph follows
    // one cell of air later.
    assert!(
        over.contains("\u{e0b4} \u{2381}"),
        "overwrite glyph after the workspace cap: {over}"
    );
    assert!(!over.contains("OVR"), "the Ln/Col segment stays unchanged");
}

#[test]
fn centring_a_line_before_the_first_render_leaves_context_above() {
    // A file opened for the first time has no viewport yet (zero text rows),
    // so there is no middle to centre on: the target must still be brought
    // near the top instead of staying at scroll 0 (a Global Search hit).
    let mut e = crate::widgets::editor::Editor::new();
    e.lines = (0..200).map(|i| format!("line {i}")).collect();
    assert_eq!(e.text_rows(), 0, "precondition: not rendered yet");
    e.goto_line_centered(100);
    assert_eq!(e.cursor_row, 100);
    assert_eq!(e.scroll, 95, "five lines of context above the target");
    e.goto_line_centered(2);
    assert_eq!(e.scroll, 0, "near the top it saturates at 0");
}

#[test]
fn a_crowded_tab_strip_offers_a_list_of_all_open_tabs() {
    use crate::widgets::list_picker::ListPurpose;
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    for i in 0..14 {
        let f = tmp.path().join(format!("a_rather_long_name_{i:02}.txt"));
        std::fs::write(&f, "x\n").unwrap();
        app.editor.open_pinned(&f).unwrap();
    }
    let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(100, 30)).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let y = app.editor.tab_strip_y_for_test();
    let col = (0..100)
        .find(|&c| app.editor.tab_list_button_at(c, y))
        .expect("the tabs overflow, so the strip draws the list button");
    assert_eq!(app.ui_tooltip_at(col, y), Some("Show All Open Tabs"));
    app.handle_mouse(mouse(
        crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
        col,
        y,
    ));
    let picker = app.list_picker.as_ref().expect("the button opens the list");
    assert_eq!(picker.purpose, ListPurpose::OpenTab);
    assert_eq!(picker.rows.len(), 14);
    assert_eq!(picker.selected, 13, "the active tab is the selected row");
    // Picking the first row activates that tab and scrolls the strip to it.
    for _ in 0..13 {
        app.handle_key(key(KeyCode::Up, KeyModifiers::NONE))
            .unwrap();
    }
    app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
        .unwrap();
    assert_eq!(app.editor.active_index(), 0);
    term.draw(|f| app.render(f)).unwrap();
    assert!(
        app.editor.tab_screen_x(0).is_some_and(|(_, w)| w > 0),
        "the picked tab is on screen"
    );
}