1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
use std::sync::Arc;
use std::time::Duration;
use async_trait::async_trait;
use kimun_core::NoteVault;
use kimun_core::error::{FSError, VaultError};
use kimun_core::nfs::VaultPath;
use ratatui::layout::{Constraint, Direction, Layout};
use ratatui::style::Style;
use ratatui::widgets::Paragraph;
use crate::app_screen::ask::AskCoordinator;
use crate::app_screen::editor_input::{
Classification, CycleDir, EditorIntent, EditorOp, InputCtx, OverlayOpen, PanelFallback,
classify,
};
use crate::app_screen::overlay_host::OverlayHost;
use crate::app_screen::panel_set::PanelSet;
use crate::app_screen::{AppScreen, ScreenKind};
use crate::components::ask_thread::ThreadPanel;
use crate::components::attachment_view::AttachmentView;
use crate::components::autosave_timer::AutosaveTimer;
use crate::components::dialogs::ActiveDialog;
use crate::components::drawer::{DrawerHost, DrawerView};
use crate::components::drawer_views::{LinksPanel, OutlinePanel, TagsPanel};
use crate::components::event_state::EventState;
use crate::components::events::{
AppEvent, AppTx, FileOp, InputEvent, OverlayData, SaveSource, SavedSearchFlow, ScreenEvent,
SortTarget, UpdateFlow,
};
use crate::components::file_list::FileListEntry;
use crate::components::footer_bar::FooterBar;
use crate::components::note_browser::file_finder_provider::FileFinderProvider;
use crate::components::note_browser::search_provider::resolving_search_source;
use crate::components::note_browser::{BrowserScope, NoteBrowserModal};
use crate::components::overlay::{Overlay, OverlayKind};
use crate::components::panel::PanelKind;
use crate::components::query_panel::QueryPanel;
use crate::components::saved_searches_modal::SavedSearchesModal;
use crate::components::sidebar::SidebarComponent;
use crate::components::text_editor::TextEditorComponent;
use crate::keys::KeyBindings;
use crate::keys::action_shortcuts::ActionShortcuts;
use crate::keys::leader::{LeaderAction, LeaderEngine, LeaderOutcome};
use crate::settings::SharedSettings;
use crate::settings::icons::Icons;
use crate::settings::themes::Theme;
use crate::util::single_slot_task::SingleSlotTask;
/// Hard cap on every blocking save path so a stuck disk (NFS hang,
/// fsync stall) cannot freeze quit, navigation, or the next autosave
/// tick. The same value is used both to wait for an in-flight
/// background autosave and to bound our own synchronous save call —
/// the worst-case quit time is therefore one cap plus the
/// observability of `abort()` on a syscall in progress.
const SAVE_TIMEOUT: Duration = Duration::from_secs(5);
pub struct EditorScreen {
vault: Arc<NoteVault>,
settings: SharedSettings,
icons: Icons,
theme: Theme,
/// The persistent panels (sidebar, editor, Query panel) plus their order,
/// visibility, and focus. The host reaches a specific panel through the
/// typed accessors (`panels.editor_mut()`, …) for panel-specific calls.
panels: PanelSet,
path: VaultPath,
footer: FooterBar,
/// Async document/status state: backlink count, git summary, link
/// affordance cache, pending emphasis needles (see `doc_meta.rs`).
doc_meta: crate::app_screen::doc_meta::DocMeta,
/// App-global update notice, seeded by `AppEvent::Update(UpdateFlow::Available)`. Drives
/// the footer indicator; `None` when up to date or the check found nothing.
update: Option<crate::update::UpdateStatus>,
/// Latest RAG connection/sync status from the background sync task, shown in
/// the footer. `Disabled` (no server) renders nothing.
rag_status: crate::rag::RagStatus,
/// The Ask workspace's coordination layer: Thread↔Sources sync, capability
/// refresh, AskData routing, and show/stash transitions (see `ask.rs`).
ask: AskCoordinator,
/// The leader-key sequence state machine (Ctrl-G gateway, spec §8a).
leader: LeaderEngine,
/// The mouse presses currently forming one gesture, so a double-click in
/// the editor can follow a link (see `click_run`). Fed before each
/// classification; its answer reaches the classifier as `InputCtx`.
clicks: crate::app_screen::click_run::ClickRun,
/// App event sender, captured on enter — render-side async kicks (the
/// link-affordance backlink fetch) need it where no `tx` is threaded.
app_tx: Option<AppTx>,
autosave: AutosaveTimer,
/// The active overlay, if any. An open overlay intercepts input ahead of
/// the panels; closing it restores focus to the panel that opened it.
overlays: OverlayHost<PanelKind>,
/// Handle to the most recently spawned background autosave task.
/// `is_in_flight()` is the source of truth for "is a save still in
/// flight"; both successful completion AND panic flip it to false
/// so the next periodic tick can spawn fresh. The synchronous save
/// paths (`open_path` / `on_entry_op` / `on_exit`) await this slot
/// before issuing their own `vault.save_note`, so two concurrent
/// writes for the same path can never collide. Drop aborts the
/// in-flight task so the spawned future cannot outlive the screen.
autosave_task: SingleSlotTask<()>,
}
impl EditorScreen {
pub fn new(vault: Arc<NoteVault>, path: VaultPath, settings: SharedSettings) -> Self {
let s = settings.read().unwrap();
let kb = s.key_bindings.clone();
let theme = s.get_theme();
let footer = FooterBar::new();
let icons = s.icons();
let sidebar = SidebarComponent::from_settings(vault.clone(), &s);
let query_panel = QueryPanel::new(vault.clone(), kb.clone(), icons.clone());
let semantic = crate::components::semantic_search::SemanticPanel::new(
vault.clone(),
settings.clone(),
s.icons(),
s.yank_combos(),
);
let tags = TagsPanel::new(vault.clone(), s.icons(), s.yank_combos());
let links = LinksPanel::new(vault.clone(), s.icons(), s.yank_combos());
let outline = OutlinePanel::new(vault.clone(), s.icons(), s.yank_combos());
let drawer = DrawerHost::new(
vault.clone(),
&kb,
sidebar,
query_panel,
semantic,
tags,
links,
outline,
);
let rail_kb = kb.clone();
let mut editor = TextEditorComponent::new(kb, &s);
editor.set_vault(vault.clone());
let leader_engine = LeaderEngine::with_tree(s.leader_tree());
drop(s);
let rail_icons = icons.clone();
let ask = AskCoordinator::new(settings.clone(), vault.clone());
Self {
settings,
icons,
theme,
// SEM and ASK both start hidden: no RAG status has arrived yet, so
// the server's search/LLM capability is unknown. The rail rebuilds
// when the first health probe lands (both are status-driven).
panels: PanelSet::from_panels(
drawer,
editor,
rail_icons,
rail_kb,
crate::components::activity_rail::RailCaps {
semantic: false,
ask: false,
},
),
doc_meta: crate::app_screen::doc_meta::DocMeta::new(vault.clone()),
update: None,
rag_status: crate::rag::RagStatus::Disabled,
ask,
vault,
path,
footer,
leader: leader_engine,
clicks: Default::default(),
app_tx: None,
autosave: AutosaveTimer::new(),
overlays: OverlayHost::new(),
autosave_task: SingleSlotTask::empty(),
}
}
}
/// Encodes raw RGBA pixels as a PNG byte stream.
fn encode_rgba_to_png(width: u32, height: u32, rgba: &[u8]) -> std::io::Result<Vec<u8>> {
let mut buf = Vec::new();
{
let mut encoder = png::Encoder::new(&mut buf, width, height);
encoder.set_color(png::ColorType::Rgba);
encoder.set_depth(png::BitDepth::Eight);
let mut writer = encoder
.write_header()
.map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
writer
.write_image_data(rgba)
.map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
}
Ok(buf)
}
impl EditorScreen {
/// Pulls an image off the system clipboard, encodes it to PNG, saves it as
/// an attachment under the vault's `/assets` directory, and inserts a
/// markdown image link (relative to the current note) at the cursor.
///
/// Returns `true` if a clipboard image was found and the paste was
/// dispatched — even if the encode/save is still in flight. Returns
/// `false` if the clipboard contained no image, so the caller can fall
/// through to a regular text paste.
fn try_paste_image(&mut self, tx: &AppTx) -> bool {
let Some(editor) = self.panels.editor_mut() else {
return false;
};
let img = match editor.take_clipboard_image() {
Some(i) if !i.rgba.is_empty() && i.width > 0 && i.height > 0 => i,
_ => return false,
};
// arboard contract: rgba length == width * height * 4. A mismatch means
// a misbehaving clipboard provider — refuse rather than encode garbage.
let expected = img
.width
.checked_mul(img.height)
.and_then(|n| n.checked_mul(4));
if expected != Some(img.rgba.len()) {
self.footer
.flash("Clipboard image size mismatch".to_string(), tx);
return true;
}
// The selection is NOT dropped here. Both steps below can fail — the
// PNG encode and the attachment save — and a cut done now would destroy
// the user's text with nothing to replace it. `insert_at_cursor`, which
// runs only on success, does the replacement and reconciles the vim
// engine out of Visual in the same breath.
let asset_path = self.vault.generate_attachment_path("image", "png");
let link_path = asset_path.relative_link_from_note(&self.path);
let markdown = format!("");
let vault = self.vault.clone();
let tx2 = tx.clone();
let width = img.width as u32;
let height = img.height as u32;
let rgba = img.rgba;
tokio::spawn(async move {
// PNG encoding is CPU-bound — keep it off the runtime worker threads.
let png_bytes =
match tokio::task::spawn_blocking(move || encode_rgba_to_png(width, height, &rgba))
.await
{
Ok(Ok(b)) => b,
Ok(Err(e)) => {
tx2.send(AppEvent::OverlayData(OverlayData::Error(format!(
"Image encode failed: {e}"
))))
.ok();
return;
}
Err(e) => {
tx2.send(AppEvent::OverlayData(OverlayData::Error(format!(
"Image encode task failed: {e}"
))))
.ok();
return;
}
};
match vault.save_attachment(&asset_path, &png_bytes).await {
Ok(()) => {
tx2.send(AppEvent::InsertAtCursor(markdown)).ok();
// Only on success — the failure branches below already
// report, and this path is async, so the chord echo would
// otherwise be the last thing the user saw.
tx2.send(AppEvent::FlashMessage("image pasted".into())).ok();
}
Err(e) => {
tx2.send(AppEvent::OverlayData(OverlayData::Error(format!(
"Image save failed: {e}"
))))
.ok();
}
}
});
true
}
/// Persist a saved search via core. Used by the SaveSearchConfirmed handler
/// and unit tests.
#[cfg(test)]
async fn persist_saved_search(&self, name: &str, query: &str) -> Result<(), VaultError> {
self.vault.save_search(name, query).await
}
async fn follow_link(&mut self, target: String, tx: &AppTx) {
// External URL — hand off to the OS browser/handler.
if kimun_core::note::scan::is_remote_url(&target) {
match open::that_detached(&target) {
Ok(()) => self.footer.flash(format!("Opening {target}"), tx),
Err(e) => self.footer.flash(format!("Cannot open URL: {e}"), tx),
}
return;
}
// Image attachment — resolve the (potentially relative) path against
// the current note's directory, convert to an OS path, hand off to the
// OS default handler. Images are not notes, so skip the note lookup.
if kimun_core::note::scan::target_looks_like_image(&target) {
let parent = self.path.get_parent_path().0;
let resolved = parent.append(&VaultPath::new(target.trim()));
let os_path = self.vault.path_to_pathbuf(&resolved);
match open::that_detached(&os_path) {
Ok(()) => self.footer.flash(format!("Opening {target}"), tx),
Err(e) => self.footer.flash(format!("Cannot open image: {e}"), tx),
}
return;
}
// Note reference — look it up in the vault.
// Strip any `#fragment` suffix before resolving (e.g. `notes/design.md#goals`
// should resolve to `notes/design.md`, not `notes/design.md#goals.md`).
let target_clean = target.split('#').next().unwrap_or(&target).trim_end();
// Resolve the (possibly relative, e.g. `../work/anton.md`) target
// against this note's directory so the existence lookup uses the same
// absolute path the note is stored under. Bare names stay name-lookups.
let path = kimun_core::nfs::VaultPath::note_path_from(target_clean)
.resolve_link_in_note(&self.path);
match self.vault.open_or_search(&path).await {
Ok(results) if results.is_empty() => {
self.present_overlay(Box::new(ActiveDialog::create_note(
path,
self.vault.clone(),
None,
)));
}
Ok(mut results) if results.len() == 1 => {
let (entry, _) = results.remove(0);
self.open_path(entry.path, None, tx).await;
}
Ok(results) => {
use crate::components::note_browser::link_results_provider::LinkResultsProvider;
let provider = LinkResultsProvider::from_results(results);
let s = self.settings.read().unwrap();
let modal = NoteBrowserModal::new(
format!("Follow: {target}"),
BrowserScope::Files,
provider,
self.vault.clone(),
s.key_bindings.clone(),
s.icons(),
tx.clone(),
);
drop(s);
self.present_overlay(Box::new(modal));
}
Err(e) => {
self.footer.flash(format!("Link error: {e}"), tx);
}
}
}
pub async fn open_path(&mut self, path: VaultPath, emphasis: Option<Vec<String>>, tx: &AppTx) {
if !path.is_note() {
// A non-note path is either an attachment (show it in place of the
// editor) or a directory (browse it). Classify so a stray
// attachment open here still lands in the attachment view rather
// than the directory browser.
if let Ok(kimun_core::EntryKind::Attachment) = self.vault.entry_kind(&path).await {
self.open_attachment(path, tx).await;
return;
}
tx.send(AppEvent::OpenScreen(ScreenEvent::OpenBrowse(
self.vault.clone(),
path,
)))
.ok();
return;
}
// Save current note before switching
self.try_save().await;
{
let mut s = self.settings.write().unwrap();
s.add_path_history(&path);
}
let settings_snapshot = self.settings.read().unwrap().clone();
tokio::spawn(async move {
settings_snapshot.save_to_disk().ok();
});
self.path = path.clone();
// Returning to a note swaps the editor area back from any attachment or
// the Ask workspace. `clear_attachment` and `hide_ask_if_shown` each
// only touch their own content, so both are needed to guarantee the
// note editor is what shows (carry-forward: open note over Ask/attach).
self.hide_ask_if_shown();
self.panels.clear_attachment();
// Mark this note's row in the sidebar (clears the previous one).
self.panels
.sidebar_mut()
.set_open_note(Some(self.path.clone()));
match self.vault.get_note_text(&self.path).await {
Ok(content) => {
self.doc_meta.note_opened(&self.path, tx);
if let Some(ed) = self.panels.editor_mut() {
ed.set_text(content);
// Arrive-from-query emphasis: apply after the load so the
// buffer's new revision owns the needles.
if let Some(needles) = emphasis {
ed.set_search_needles(needles);
}
ed.set_redraw_tx(tx);
}
tx.send(AppEvent::Redraw).ok();
// FIND / LINKS / OUTLINE reflect the open note; keep them in
// step. Shared with `on_note_renamed` via the helper.
self.reflect_open_note_in_drawers(tx);
}
Err(e) => {
if matches!(e, VaultError::FSError(FSError::VaultPathNotFound { .. })) {
self.present_overlay(Box::new(ActiveDialog::create_note(
self.path.clone(),
self.vault.clone(),
None,
)));
} else {
tracing::error!("Failed to read note {}: {e}", self.path);
let parent = self.path.get_parent_path().0;
tx.send(AppEvent::OpenScreen(ScreenEvent::OpenBrowse(
self.vault.clone(),
parent,
)))
.ok();
}
return;
}
}
// Load the sidebar on first open only; refreshes happen via explicit
// create/rename/delete/move events, not on every note open.
let note_parent = path.get_parent_path().0;
if self.panels.sidebar().is_empty() {
self.navigate_sidebar(note_parent, tx);
}
// Abort any existing timer and spawn a fresh one for the new note.
let interval = self.settings.read().unwrap().autosave_interval_secs;
self.autosave.restart(interval, tx.clone());
}
/// Take the editor area off the Ask workspace before it's swapped to
/// another view (a note or an attachment). `clear_attachment` and
/// `show_attachment` both leave Ask content alone, so this is what
/// guarantees the new view actually shows (see
/// `AskCoordinator::hide_if_shown` for the drawer-view rules).
fn hide_ask_if_shown(&mut self) {
self.ask.hide_if_shown(&mut self.panels);
}
/// Show the attachment at `path` in the editor area's read-only attachment
/// view. Saves and unmounts the open note first; while an
/// attachment is shown there is no open note, so the autosave task is
/// aborted and the sidebar's open-note marker cleared. The next periodic
/// autosave tick no-ops because the note editor is absent.
async fn open_attachment(&mut self, path: VaultPath, tx: &AppTx) {
// Persist the current note before swapping the editor area away from it.
self.try_save().await;
self.autosave_task.abort();
match self.vault.get_attachment_details(&path).await {
Ok(details) => {
let (icons, kb) = {
let s = self.settings.read().unwrap();
(s.icons(), s.key_bindings.clone())
};
let view = AttachmentView::new(details, icons, kb);
self.path = path;
// Take the area off Ask so the attachment actually replaces it
// (show_attachment leaves Ask content alone).
self.hide_ask_if_shown();
self.panels.show_attachment(view);
self.panels.sidebar_mut().set_open_note(None);
tx.send(AppEvent::Redraw).ok();
}
Err(e) => {
self.footer
.flash(format!("Cannot open attachment: {e}"), tx);
}
}
}
fn navigate_sidebar(&mut self, dir: VaultPath, tx: &AppTx) {
// The sidebar hosts a streamed `SearchList`; (re)building its engine for
// `dir` runs `browse_vault` inside the source and emits rows as they
// arrive (with a redraw on each).
self.panels.sidebar_mut().navigate(dir, tx);
}
/// Rebuild the sidebar listing only when it is currently showing `dir` —
/// used after entry create/rename/move ops so the change appears without
/// yanking the user away from an unrelated directory they browsed to.
/// Deliberately the inverse of `reveal_note_dir_in_sidebar`, which
/// navigates when the sidebar is NOT on the target dir.
fn refresh_sidebar_if_showing(&mut self, dir: &VaultPath, tx: &AppTx) {
self.panels.sidebar_mut().refresh_if_showing(dir, tx);
}
/// A note at `path` was just saved with raw title `raw_title`; update its
/// sidebar row in place. Keyed by the saved path, not the open note, so a
/// just-saved-then-deselected note's row updates too.
fn note_saved(&mut self, path: &VaultPath, raw_title: String) {
let title = FileListEntry::display_title(raw_title);
self.panels.sidebar_mut().update_note_row(path, &title);
}
async fn try_save(&mut self) {
// Wait out any background autosave so two concurrent `vault.save_note`
// calls cannot race on the same path. Capped at 5s so a wedged
// filesystem (NFS hang, fsync stall, SQLite lock contention) does
// not freeze app-quit indefinitely.
//
// If the timeout fires we MUST abort the prior task and bail
// without issuing our own save: dropping a JoinHandle detaches
// the tokio task rather than cancelling it, so the spawned
// vault.save_note keeps running. Calling our own vault.save_note
// on the same path on top of that is the exact two-writer race
// the in-flight serialisation is meant to prevent. abort() is
// best-effort (will not unwind an in-progress syscall) but it
// stops any further await points in the spawned task. The editor
// stays dirty so the next session retries; the spawned task
// either finishes against the disk on its own or is killed when
// the process exits.
if self.autosave_task.is_in_flight() {
match self.autosave_task.await_with_timeout(SAVE_TIMEOUT).await {
Some(_) => {} // completed (success or panic) — slot already cleared
None => {
// Timeout: abort the spawned task and bail.
self.autosave_task.abort();
return;
}
}
}
// No note editor mounted (an attachment is shown) → nothing to save.
let Some(text) = self
.panels
.editor()
.filter(|e| e.is_dirty())
.map(|e| e.get_text())
else {
return;
};
// Same cap on our own save so quit cannot hang on a stuck
// disk. A timeout returns Err(_); we skip mark_saved so the
// editor stays dirty for any subsequent retry.
let save = self.vault.save_note(&self.path, &text);
if let Ok(Ok((_, content))) = tokio::time::timeout(SAVE_TIMEOUT, save).await {
if let Some(ed) = self.panels.editor_mut() {
ed.mark_saved(text);
}
let path = self.path.clone();
self.note_saved(&path, content.title);
}
}
/// Fire-and-forget autosave used by the periodic timer. The save runs in
/// a spawned tokio task so the main event loop is never blocked by the
/// filesystem + SQLite write. Completion is reported back as
/// `AppEvent::AutosaveCompleted`, which marks the editor clean iff the
/// editor is still at the revision that was written. `is_in_flight()`
/// on the `SingleSlotTask` slot is the "is a save in flight" signal;
/// it flips to false on both successful completion AND panic, so a
/// single panicked task can never permanently disable autosave.
fn spawn_autosave(&mut self, tx: &AppTx) {
// A previous task that hasn't reported completion yet still holds the
// lock on the file system + SQLite path; let it finish first.
if self.autosave_task.is_in_flight() {
return;
}
let Some(ed) = self.panels.editor() else {
return;
};
if !ed.is_dirty() {
return;
}
let text = ed.get_text();
let revision = ed.content_revision();
let vault = self.vault.clone();
let path = self.path.clone();
let tx = tx.clone();
self.autosave_task.spawn(async move {
let (saved_revision, title) = match vault.save_note(&path, &text).await {
Ok((_, content)) => (Some(revision), Some(content.title)),
Err(_) => (None, None),
};
let _ = tx.send(AppEvent::AutosaveCompleted {
path,
saved_revision,
title,
});
});
}
/// The panel to restore focus to when the active overlay closes — the
/// panel that was focused when the overlay opened.
fn opener_focus(&self) -> PanelKind {
self.panels.focused()
}
/// Present `overlay`, recording the currently focused panel as its opener so
/// `dismiss_overlay` can return there on close. The single way the editor
/// opens an overlay — the focus contract lives here, not at each call site.
fn present_overlay(&mut self, overlay: Box<dyn Overlay>) {
// An overlay taking input must never leave a leader sequence armed —
// its keys would be eaten by the leader intercept.
self.leader.cancel();
let opener = self.opener_focus();
self.overlays.open(overlay, opener);
}
/// Close the active overlay and restore focus to the panel that opened it.
/// The close-side mirror of `present_overlay`. `OverlayHost::close` returns
/// `None` when nothing is open, so this is a no-op then — which is also why
/// a selection that closed the overlay itself (and chose its own focus) is
/// not re-restored by a trailing `CloseOverlay`.
fn dismiss_overlay(&mut self) {
if let Some(opener) = self.overlays.close() {
self.panels.focus(opener);
}
}
async fn on_entry_op(&mut self, from: VaultPath, tx: &AppTx) {
self.dismiss_overlay();
// `is_like` ignores the vault-relative/absolute distinction: `from` (from
// a sidebar/query row) is index-absolute while `self.path` may be relative.
// A plain `==` would miss, leaving the stale autosave to
// recreate a deleted/moved note.
if from.is_like(&self.path) {
self.autosave.stop();
self.try_save().await;
let parent = self.path.get_parent_path().0;
tx.send(AppEvent::OpenScreen(ScreenEvent::OpenBrowse(
self.vault.clone(),
parent,
)))
.ok();
} else {
self.refresh_sidebar_if_showing(&from.get_parent_path().0, tx);
}
}
/// A note was renamed. Update its sidebar row in place; if it is the note
/// currently open, retarget the editor to the new path and reload the body
/// from disk so any self-link rewrites from the rename land in the buffer
/// (the in-memory text still holds the pre-rename self-links). We
/// deliberately do NOT `try_save` — the old path no longer exists on disk.
async fn on_note_renamed(&mut self, from: VaultPath, to: VaultPath, tx: &AppTx) {
self.dismiss_overlay();
self.panels.sidebar_mut().rename_note_row(&from, &to);
// `is_like` so an absolute `from` (index row) matches a possibly-relative
// `self.path` — otherwise the retarget + autosave-abort below
// are skipped and the stale save resurrects the old path.
if from.is_like(&self.path) {
// The open note was renamed. Kill any in-flight autosave still
// targeting the OLD path before retargeting (spawn_autosave bakes
// the path in; vault.save_note writes unconditionally, so a stale
// save would recreate the renamed-away file). abort() is
// best-effort (can't unwind a syscall already in progress).
self.autosave_task.abort();
match self.vault.get_note_text(&to).await {
Ok(text) => {
self.path = to.clone();
if let Some(ed) = self.panels.editor_mut() {
ed.set_text(text.clone());
ed.mark_saved(text);
}
self.panels
.sidebar_mut()
.set_open_note(Some(self.path.clone()));
self.doc_meta.note_opened(&self.path, tx);
self.reflect_open_note_in_drawers(tx);
// Fresh autosave timer for the new path (mirrors open_path).
let interval = self.settings.read().unwrap().autosave_interval_secs;
self.autosave.restart(interval, tx.clone());
}
Err(_) => {
// Couldn't load the renamed note — do NOT keep a dirty
// buffer pointed at it (autosave would clobber the
// on-disk rewrite). Fall back to Browse on the new
// parent dir.
self.autosave.stop();
let parent = to.get_parent_path().0;
tx.send(AppEvent::OpenScreen(ScreenEvent::OpenBrowse(
self.vault.clone(),
parent,
)))
.ok();
}
}
}
}
}
impl EditorScreen {
/// Snapshot of the screen state the input classifier reads. Built per
/// classification — cheap field reads only.
///
/// `double_click` comes from [`Self::track_click`] rather than a field read
/// because feeding the click run mutates it; a snapshot is taken from
/// `&self` and cannot.
fn input_ctx(&self, double_click: bool) -> InputCtx {
InputCtx {
overlay: self.overlays.active_kind(),
leader_pending: self.leader.is_pending(),
focused: self.panels.focused(),
drawer_view: self.panels.active_drawer_view(),
space_leads: self.panels.editor().is_some_and(|e| e.space_leads()),
claim: self.panels.editor().map(|e| e.claim()).unwrap_or_default(),
double_click,
}
}
/// Feed an event to the click run and report whether it completes a
/// double-click on the note buffer.
///
/// The screen answers only what a `ClickRun` cannot answer for itself:
/// whether the event is a mouse event at all, whether an overlay is in the
/// way, and whether the press landed on the note buffer. Which *mouse*
/// events end a run is `ClickRun`'s policy and lives there, where it can be
/// tested against a real event sequence.
///
/// An open overlay ends the run rather than merely failing to extend it.
/// The classifier already gives an overlay precedence, so no follow can
/// fire *while* one is open — but a modal is drawn over the editor column,
/// and a `SearchList` activates a row on a click-click of its own. Without
/// ending it here, those presses stay in the run and pair with the first
/// press that lands after the overlay closes.
///
/// `now` is passed in for the same reason [`ClickRun`] takes it rather than
/// reading a clock: a test describes a gap instead of sleeping through one.
/// The seam matters more here than there — this half of the rule is the part
/// that hit-tests, and the frame around the editor was counted as buffer
/// until it could be asserted against.
///
/// [`ClickRun`]: crate::app_screen::click_run::ClickRun
fn track_click(&mut self, event: &InputEvent, now: std::time::Instant) -> bool {
let InputEvent::Mouse(mouse) = event else {
self.clicks.end();
return false;
};
if self.overlays.is_open() {
self.clicks.end();
return false;
}
// Only a press consults the hit-test; `observe` discards the flag for
// every other kind. Motion is the reason to care — any-event tracking
// delivers one per cell of travel, and this would otherwise scan the
// column rects twice for each.
let on_buffer = matches!(
mouse.kind,
ratatui::crossterm::event::MouseEventKind::Down(_)
) && self.panels.is_note_buffer_cell(mouse.column, mouse.row);
self.clicks.observe(mouse, on_buffer, now)
}
/// Apply a classification: pre-effects first (footer chord flash, leader
/// cancel), then the intent. The classifier decides *what* an event
/// means; everything that mutates happens here.
fn apply_classification(
&mut self,
classification: Classification,
event: &InputEvent,
tx: &AppTx,
) -> EventState {
if let Some(chord) = classification.flash {
self.footer.flash(chord, tx);
}
if classification.cancel_leader {
self.leader.cancel();
}
self.execute_intent(classification.intent, event, tx)
}
fn execute_intent(
&mut self,
intent: EditorIntent,
event: &InputEvent,
tx: &AppTx,
) -> EventState {
match intent {
EditorIntent::Consume => EventState::Consumed,
EditorIntent::EditorPaste => {
if !self.try_paste_image(tx)
&& let InputEvent::Paste(text) = event
&& !text.is_empty()
&& let Some(ed) = self.panels.editor_mut()
{
ed.paste_text(text, tx);
}
EventState::Consumed
}
EditorIntent::ImageProbe => {
if self.try_paste_image(tx) {
EventState::Consumed
} else {
// No image: the rest of the ladder decides. Reclassify
// the tail against fresh state — any leader cancel was
// already applied by the probe classification, so the
// tail must not re-cancel (`cancel_leader = false`).
// A key path (Ctrl+V): no press to pair, so no double.
let ctx = self.input_ctx(false);
let classification = {
let s = self.settings.read().unwrap();
crate::app_screen::editor_input::classify_tail(
event,
&s.key_bindings,
&ctx,
false,
)
};
self.apply_classification(classification, event, tx)
}
}
EditorIntent::FollowLink => {
if self.follow_link_at_cursor(tx) {
EventState::Consumed
} else if matches!(event, InputEvent::Mouse(_)) {
// Nothing under the cursor to follow, and this arrived as a
// press. Swallowing it would make the second click of a
// double a silent no-op anywhere but on a link, and would
// claim the gesture buffer-wide for a follow that did not
// happen. Hand it back to the panels as the press it is —
// the same fallback-on-runtime-outcome shape `ImageProbe`
// uses when the clipboard turns out to hold no image.
self.execute_intent(EditorIntent::Mouse, event, tx)
} else {
EventState::Consumed
}
}
EditorIntent::LeaderKey(key) => self.handle_leader_key(&key, tx),
EditorIntent::LeaderStart => {
self.leader.start();
self.schedule_whichkey_reveal(tx);
EventState::Consumed
}
EditorIntent::Op(op) => {
self.run_op(op, tx);
EventState::Consumed
}
EditorIntent::ToggleOverlay { kind, open } => {
if self.overlays.active_kind() == Some(kind) {
self.dismiss_overlay();
} else {
self.open_overlay(open, tx);
}
EventState::Consumed
}
EditorIntent::OpenOverlay(open) => {
self.open_overlay(open, tx);
EventState::Consumed
}
EditorIntent::Overlay => self.overlays.handle_input(event, tx),
EditorIntent::Mouse => {
// `PanelSet` hit-tests the panel columns: a click focuses the
// panel under the cursor (one rule for every panel) and the
// event is forwarded to that panel for its internal behavior.
let state = self.panels.handle_mouse(event, tx);
// Ask clicks (turn select, citation) move the drawer's Sources.
self.ask.sync_sources(&mut self.panels, tx);
// A selectionless right-click in the editor asks for the
// note's context menu — the screen owns the path, so it
// opens it here.
if self.panels.editor().is_some_and(|e| e.wants_context_menu) {
if let Some(ed) = self.panels.editor_mut() {
ed.wants_context_menu = false;
}
tx.send(AppEvent::FileOp(FileOp::ShowMenu(self.path.clone())))
.ok();
}
state
}
EditorIntent::Panel { fallback } => {
let state = self.panels.handle_input(event, tx);
// Ask keys (j/k select, i/composer, submit) move the drawer's
// Sources in step with the thread's selected turn.
self.ask.sync_sources(&mut self.panels, tx);
if state == EventState::NotConsumed {
match fallback {
PanelFallback::None => state,
PanelFallback::FocusCycle(CycleDir::Right) => {
self.focus_right(tx);
EventState::Consumed
}
PanelFallback::FocusCycle(CycleDir::Left) => {
self.focus_left(tx);
EventState::Consumed
}
PanelFallback::FocusEditor => {
self.focus_editor();
EventState::Consumed
}
}
} else {
state
}
}
}
}
fn run_op(&mut self, op: EditorOp, tx: &AppTx) {
match op {
EditorOp::ToggleDrawer => self.toggle_drawer(tx),
EditorOp::FocusLeft => self.focus_left(tx),
EditorOp::FocusRight => self.focus_right(tx),
EditorOp::OpenJournal => {
tx.send(AppEvent::OpenJournal).ok();
}
EditorOp::ShowFileOps => {
tx.send(AppEvent::FileOp(FileOp::ShowMenu(self.path.clone())))
.ok();
}
EditorOp::ToggleQueryPanel => self.toggle_backlinks(tx),
EditorOp::OpenFileBrowserReveal => {
self.open_drawer_view(DrawerView::Files, tx);
self.reveal_note_dir_in_sidebar(tx);
}
EditorOp::SaveCurrentQuery => {
if let Some((query, provenance, source)) = self.save_query_source() {
// Opening the save dialog replaces the note browser (if
// any); the chained-open guard preserves the original
// opener focus.
self.present_overlay(Box::new(ActiveDialog::save_search(
query,
provenance,
source,
self.vault.clone(),
tx,
)));
}
}
EditorOp::FindInBuffer => {
if let Some(ed) = self.panels.editor_mut() {
ed.open_or_advance_search();
}
}
EditorOp::ReplaceInBuffer => {
if let Some(ed) = self.panels.editor_mut() {
ed.open_replace();
}
}
EditorOp::ApplyText(text_action) => {
if let Some(ed) = self.panels.editor_mut() {
ed.apply_text_action(text_action);
}
}
EditorOp::OpenAsk => self.open_ask_workspace(tx),
}
}
/// The one door for every overlay the screen can open: guard (no overlay
/// over an open overlay), build the recipe, present it. Opens that need
/// more than construction (the Ask workspace's capability gate, drawer
/// views) are not overlays and keep their own methods.
fn open_overlay(&mut self, open: OverlayOpen, tx: &AppTx) {
if self.overlays.is_open() {
return;
}
let overlay = self.build_overlay(open, tx);
self.present_overlay(overlay);
}
/// Construction recipes for [`OverlayOpen`] — the single site answering
/// "what overlays exist and how is each built". Reads screen state (vault,
/// settings, open note, panel sort/order seeds) but never mutates it;
/// presentation and the open-guard live in [`Self::open_overlay`].
fn build_overlay(&self, open: OverlayOpen, tx: &AppTx) -> Box<dyn Overlay> {
let s = self.settings.read().unwrap();
match open {
// The note-browser modal over the full-text search provider
// (Ctrl-K and the leader's find paths).
OverlayOpen::SearchBrowser => {
let provider = resolving_search_source(
self.vault.clone(),
s.current_last_paths(),
Some(self.path.clone()),
);
Box::new(NoteBrowserModal::new(
"Note Browser",
BrowserScope::Query,
provider,
self.vault.clone(),
s.key_bindings.clone(),
s.icons(),
tx.clone(),
))
}
// The note-browser modal over the fuzzy file finder (Ctrl-O and
// the leader's `f f`).
OverlayOpen::FileFinder => {
let current_dir = self.path.get_parent_path().0;
let provider = FileFinderProvider::new(self.vault.clone(), current_dir);
Box::new(NoteBrowserModal::new(
"Find Note",
BrowserScope::Files,
provider,
self.vault.clone(),
s.key_bindings.clone(),
s.icons(),
tx.clone(),
))
}
// F3 and leader `f s`.
OverlayOpen::SavedSearches => Box::new(SavedSearchesModal::new(
self.vault.clone(),
s.key_bindings.clone(),
s.icons(),
tx.clone(),
)),
// Ctrl+Shift+P and leader `p`.
OverlayOpen::CommandPalette => {
let gateway = s
.key_bindings
.first_combo_for(&ActionShortcuts::Leader)
.unwrap_or_else(|| "leader".to_string());
Box::new(
crate::components::command_palette::CommandPaletteModal::new(
&s.leader_tree(),
&gateway,
s.icons(),
tx.clone(),
),
)
}
// SwitchWorkspace action and leader `v s`.
OverlayOpen::WorkspaceSwitcher => Box::new(ActiveDialog::workspace_switcher(&s)),
// Leader `v t` and inside CFG via `t`; the full settings screen
// stays on the OpenSettings binding.
OverlayOpen::ThemePicker => Box::new(ActiveDialog::theme_picker(&s)),
OverlayOpen::Help => Box::new(ActiveDialog::help(&s.key_bindings)),
OverlayOpen::QueryHelp => Box::new(ActiveDialog::query_syntax()),
OverlayOpen::Cheatsheet => Box::new(ActiveDialog::cheatsheet(&s)),
OverlayOpen::SortQuery => {
let (field, order) = self.panels.query().current_order();
Box::new(ActiveDialog::sort(SortTarget::Query, field, order, false))
}
OverlayOpen::SortSidebar => {
let (field, order) = self.panels.sidebar().current_sort();
Box::new(ActiveDialog::sort(
SortTarget::Sidebar,
field,
order,
self.panels.sidebar().group_dirs(),
))
}
OverlayOpen::QuickNote => Box::new(ActiveDialog::quick_note(self.vault.clone())),
}
}
/// One owner for the self-update lifecycle's display half; the
/// app-global half (persisting dismissals, seeding later screens) lives
/// in main.rs.
fn handle_update(&mut self, flow: UpdateFlow, tx: &AppTx) {
match flow {
UpdateFlow::Available(status) => {
self.update = Some(status);
}
UpdateFlow::ShowDialog => {
if let Some(status) = self.update.clone() {
self.present_overlay(Box::new(ActiveDialog::update(&status)));
}
}
UpdateFlow::Dismiss(_) => {
// Persistence happens in main; here we just drop the indicator.
self.update = None;
}
UpdateFlow::Applied => {
// Installed — drop the notice so the footer/dialog stop offering
// the version we just wrote (restart still required to run it).
self.update = None;
}
UpdateFlow::Apply => {
let tx2 = tx.clone();
tx.send(AppEvent::FlashMessage("Downloading update…".into()))
.ok();
tokio::spawn(async move {
let result = async {
let latest = crate::update::latest_release().await?;
crate::update::install(latest).await
}
.await;
let msg = match result {
Ok(()) => {
tx2.send(AppEvent::Update(UpdateFlow::Applied)).ok();
"Update installed — restart kimün to apply".to_string()
}
Err(e) => format!("Update failed: {e}"),
};
tx2.send(AppEvent::FlashMessage(msg)).ok();
});
}
}
}
/// One owner for file operations: requests present the matching dialog,
/// confirmations keep the sidebar and the open note in step.
async fn handle_file_op(&mut self, op: FileOp, tx: &AppTx) {
match op {
FileOp::ShowMenu(path) => {
self.present_overlay(Box::new(ActiveDialog::file_ops_menu(path)));
}
FileOp::ShowDelete(path) => {
self.present_overlay(Box::new(ActiveDialog::delete(path, self.vault.clone())));
}
FileOp::ShowRename(path) => {
self.present_overlay(Box::new(ActiveDialog::rename(path, self.vault.clone())));
}
FileOp::ShowMove(path) => {
self.present_overlay(Box::new(ActiveDialog::move_to(
path,
self.vault.clone(),
tx,
)));
}
FileOp::ShowCreateWithContent { path, content } => {
// The suggested path is derived from a title (an Ask question),
// so unlike the other create-note entry points it is not known
// to be free — and the create behind this dialog avoids
// conflicts by incrementing the name. Resolve that name here so
// the dialog shows the note the user is actually confirming,
// instead of promising `ask/foo.md` and quietly writing
// `ask/foo_0.md`.
let path = self.vault.free_note_path(&path).await;
self.present_overlay(Box::new(ActiveDialog::create_note(
path,
self.vault.clone(),
Some(content),
)));
}
FileOp::Created(path) => {
// Pure notification: a note now exists at `path`. Opening is the
// creator's job (via OpenPath); here we only keep the sidebar in
// step when it is browsing the new note's directory.
self.refresh_sidebar_if_showing(&path.get_parent_path().0, tx);
}
FileOp::Deleted(path) => {
self.on_entry_op(path, tx).await;
}
FileOp::Renamed { from, to } => {
// Note rename → targeted row update (and retarget the editor if
// it is the open note). Directory rename keeps the full reload.
if from.is_note() {
self.on_note_renamed(from, to, tx).await;
} else {
self.on_entry_op(from, tx).await;
}
}
FileOp::Moved { from, .. } => {
self.on_entry_op(from, tx).await;
}
}
}
/// One owner for the saved-search save/select flow.
fn handle_saved_search(&mut self, flow: SavedSearchFlow, tx: &AppTx) {
match flow {
SavedSearchFlow::Selected { query, name } => {
// Deliberate non-restoring close: the selection lands in the
// Query panel (set by apply_saved_search), not back on the
// overlay's opener — so close the overlay without dismiss_overlay.
self.overlays.close();
self.apply_saved_search(query, name, tx);
}
SavedSearchFlow::Confirmed {
name,
query,
source,
} => {
// Write in the background; the breadcrumb re-pin waits for
// the success event so the UI never claims an unpersisted
// save (see `Persisted` below).
let vault = self.vault.clone();
let tx = tx.clone();
tokio::spawn(async move {
match vault.save_search(&name, &query).await {
Ok(()) => {
tx.send(AppEvent::SavedSearch(SavedSearchFlow::Persisted {
name,
query,
source,
}))
.ok();
}
Err(e) => {
tracing::warn!("failed to save search '{}': {}", name, e);
tx.send(AppEvent::SavedSearch(SavedSearchFlow::SaveFailed { name }))
.ok();
}
}
});
}
// Re-pin the panel breadcrumb to the saved identity: the edited
// marker drops on an update, the name switches on a save-as-new.
// Only for panel-sourced saves (a note-browser save must not
// steal the panel's provenance, even when the query text
// coincides), and not for the query-as-name fallback (a
// breadcrumb that echoes the query is noise).
SavedSearchFlow::Persisted {
name,
query,
source: SaveSource::QueryPanel,
} if name.trim() != query.trim() => {
self.panels.query_mut().repin_saved_search(name, &query);
}
SavedSearchFlow::Persisted { .. } => {}
SavedSearchFlow::SaveFailed { name } => {
self.footer
.flash(format!("Failed to save search '{name}'"), tx);
}
}
}
/// The editor-owned singles: everything with exactly one arm and no
/// family. Family events never reach this match.
async fn handle_owned_message(&mut self, msg: AppEvent, tx: &AppTx) {
match msg {
AppEvent::RagStatus(status) => {
let ask_was = self.rag_status.llm_available();
let sem_was = self.rag_status.search_available();
self.rag_status = status;
// Both rail entries are live-status-driven: ASK on whether the
// server can answer questions, SEM on whether it can search.
// Rebuild the rail when either flips (an active view
// stays put when its capability drops — only the rail entry
// goes). The Ask client only needs refreshing on the ASK flip.
let ask_now = status.llm_available();
let sem_now = status.search_available();
if ask_was != ask_now || sem_was != sem_now {
let (kb, icons) = {
let s = self.settings.read().unwrap();
(s.key_bindings.clone(), s.icons())
};
self.panels.rebuild_rail(
kb,
icons,
crate::components::activity_rail::RailCaps {
semantic: sem_now,
ask: ask_now,
},
);
}
if ask_was != ask_now {
self.ask
.refresh_capability(&mut self.panels, self.rag_status)
.await;
}
}
AppEvent::Ask(data) => self.ask.handle_data(&mut self.panels, data, tx),
// Stale completions (for notes we've navigated away from) fall
// through to the catch-all and are dropped.
AppEvent::FlashMessage(msg) => {
self.footer.flash(msg, tx);
}
AppEvent::ExecuteLeaderAction(action) => {
if self.overlays.is_open() {
// The palette closes itself before sending, so this is
// unreachable from it — but never drop an action silently.
tracing::warn!("ExecuteLeaderAction({action:?}) dropped: overlay open");
} else {
self.execute_leader_action(action, tx);
}
}
AppEvent::ApplyTheme { theme, persist } => {
// The picker resolved the theme already — no disk re-read,
// just adapt to the terminal and swap.
{
let mut s = self.settings.write().unwrap();
s.set_theme(theme.name.clone());
}
self.theme = (*theme).adapt_to_terminal();
if persist {
let snapshot = self.settings.read().unwrap().clone();
tokio::spawn(async move {
snapshot.save_to_disk().ok();
});
}
tx.send(AppEvent::Redraw).ok();
}
// Drawer panels can't emit these under an overlay, but guard
// anyway: never mutate panels while an overlay owns input.
AppEvent::RunTagQuery(label) if !self.overlays.is_open() => {
self.open_find_with_query(format!("#{label}"), None, tx);
}
AppEvent::JumpToHeading(heading) if !self.overlays.is_open() => {
if let Some(ed) = self.panels.editor_mut() {
ed.jump_to_heading(&heading);
}
self.focus_editor();
}
AppEvent::OpenDrawerView(view) => {
// The rail hides SEM unless the server is reachable for search,
// but the leader path (`drawer.semantic`) can still request it —
// gate here so every route gets the same answer.
if view == DrawerView::Semantic && !self.rag_status.search_available() {
let msg = if crate::rag::rag_configured(&self.settings) {
"Semantic search needs a reachable server with an embedder"
} else {
"Set kimun_server_url in config to use semantic search"
};
tx.send(AppEvent::FlashMessage(msg.into())).ok();
}
// ASK needs an LLM-configured server (the rail hides its entry
// otherwise); gate every route the same way.
else if view == DrawerView::Ask && !self.rag_status.llm_available() {
tx.send(AppEvent::FlashMessage(
"Ask needs an LLM-configured server; this one is semantic-search only"
.into(),
))
.ok();
}
// Selecting the already-active view toggles the drawer closed
// (spec §3: clicking the active rail item toggles).
else if self.panels.is_visible(PanelKind::Drawer)
&& self.panels.active_drawer_view() == view
{
self.panels.hide(PanelKind::Drawer);
} else {
self.open_drawer_view(view, tx);
}
}
AppEvent::CloseOverlay => {
// Dismiss-to-opener. Guarded by is_open() on purpose: a
// selection that wants a specific post-close focus
// (OpenPath -> editor, SavedSearchSelected -> Query panel)
// closes the overlay itself first, so a later/!dialog
// CloseOverlay must not re-restore and clobber that focus.
self.dismiss_overlay();
}
AppEvent::SortChanged {
target,
field,
order,
group_directories,
persist,
} => {
match target {
SortTarget::Sidebar if persist => {
// Update the sidebar's in-session per-context default AND
// apply live. `is_current_journal()` is the single source
// of truth for which context this save targets — reused
// for the on-disk settings write below.
let is_journal = self.panels.sidebar().is_current_journal();
self.panels
.sidebar_mut()
.save_default(field, order, group_directories);
{
let mut s = self.settings.write().unwrap();
if is_journal {
s.journal_sort_field =
crate::settings::SortFieldSetting::from(field);
s.journal_sort_order =
crate::settings::SortOrderSetting::from(order);
} else {
s.default_sort_field =
crate::settings::SortFieldSetting::from(field);
s.default_sort_order =
crate::settings::SortOrderSetting::from(order);
}
s.group_directories = group_directories;
}
let snapshot = self.settings.read().unwrap().clone();
tokio::spawn(async move {
snapshot.save_to_disk().ok();
});
}
SortTarget::Sidebar => {
self.panels
.sidebar_mut()
.apply_sort(field, order, group_directories)
}
// The query panel has no persisted default (the order lives
// in the query string); `persist` is always false here.
SortTarget::Query => self.panels.query_mut().apply_sort(field, order, tx),
}
}
AppEvent::Autosave => {
self.spawn_autosave(tx);
}
AppEvent::AutosaveCompleted {
path,
saved_revision,
title,
} => {
if path == self.path
&& let Some(rev) = saved_revision
&& let Some(ed) = self.panels.editor_mut()
{
ed.mark_saved_at_revision(rev);
}
if let Some(raw_title) = title {
self.note_saved(&path, raw_title);
}
// The write changed the working tree — refresh the git
// segment (throttled).
self.doc_meta.refresh_git(tx);
// `SingleSlotTask::is_in_flight()` flips to false the
// moment the spawned future returns (success or panic),
// so we don't have to clear the slot manually here —
// the next `spawn_autosave` tick will overwrite it.
// Skip explicit cleanup; was previously racy because a
// stale completion arriving after `try_save` had
// already cleared and respawned could wipe the fresh
// handle.
}
AppEvent::FocusSidebar => {
self.focus_sidebar(tx);
}
AppEvent::FollowLink(target) => {
self.follow_link(target, tx).await;
}
AppEvent::FollowLabel(name) => {
let initial = format!("#{name}");
let s = self.settings.read().unwrap();
let provider = resolving_search_source(
self.vault.clone(),
s.current_last_paths(),
Some(self.path.clone()),
);
let modal = NoteBrowserModal::with_initial_query(
"Note Browser",
BrowserScope::Query,
provider,
self.vault.clone(),
s.key_bindings.clone(),
s.icons(),
tx.clone(),
initial,
);
drop(s);
self.present_overlay(Box::new(modal));
}
AppEvent::InsertAtCursor(text) if self.panels.focused() == PanelKind::Editor => {
if let Some(ed) = self.panels.editor_mut() {
ed.insert_at_cursor(&text, tx);
}
}
_ => {}
}
}
pub fn focus_editor(&mut self) {
self.panels.focus(PanelKind::Editor);
}
/// Whether the drawer is open showing `view`.
fn drawer_open_on(&self, view: DrawerView) -> bool {
self.panels.is_visible(PanelKind::Drawer) && self.panels.active_drawer_view() == view
}
/// Reflect the currently-open note (`self.path`) into whichever drawer view
/// is visible (FIND/LINKS/OUTLINE). Shared by `open_path` and
/// `on_note_renamed` so a rename keeps the drawers in step, not just a
/// fresh open.
fn reflect_open_note_in_drawers(&mut self, tx: &AppTx) {
let path = self.path.clone();
if self.drawer_open_on(DrawerView::Find) {
self.panels.query_mut().set_note(path.clone(), tx.clone());
}
if self.panels.is_visible(PanelKind::Drawer) {
match self.panels.active_drawer_view() {
DrawerView::Links => self.panels.links_mut().set_note(path.clone(), tx),
DrawerView::Outline => self.panels.outline_mut().set_note(path, tx),
_ => {}
}
}
}
/// Point the sidebar at the current note's directory. Skips the engine
/// rebuild when the sidebar is already there so an in-progress filter
/// and selection survive a re-open.
fn reveal_note_dir_in_sidebar(&mut self, tx: &AppTx) {
let note_parent = self.path.get_parent_path().0;
if self.panels.sidebar().is_empty()
|| !note_parent.is_like(self.panels.sidebar().current_dir())
{
self.navigate_sidebar(note_parent, tx);
}
}
/// Focus the drawer, revealing it on FILES if hidden — but never clobber
/// the view the user already has open (e.g. a FIND query in progress).
/// Sent by the nvim backend's leave-editor motions.
pub fn focus_sidebar(&mut self, tx: &AppTx) {
if !self.panels.is_visible(PanelKind::Drawer) {
// Routed through the host opener so the FILES view reveals the
// current note's directory like any other drawer open (it also
// focuses the drawer).
self.open_drawer_view(DrawerView::Files, tx);
} else {
self.panels.focus(PanelKind::Drawer);
}
}
/// Switch the drawer to `view`, reveal it, and focus it. The per-view
/// reveal side effects live in `drawer_view_revealed` (the heavy work
/// that keeps the reveal in the host rather than in `PanelSet`).
fn open_drawer_view(&mut self, view: DrawerView, tx: &AppTx) {
// Keep the editor-area Ask content in lockstep with the drawer view:
// entering ASK restores the stashed thread; leaving it stashes the
// live one (rules 1 & 2 — thread survives every view switch).
self.ask.transition(&mut self.panels, view, tx);
let newly_shown = !self.drawer_open_on(view);
self.panels.open_drawer_view(view);
self.drawer_view_revealed(view, newly_shown, tx);
// The ASK workspace lives in the editor area; drop the user on the
// composer rather than the Sources drawer. Every other view focuses
// the drawer as before.
if view == DrawerView::Ask {
self.panels.focus(PanelKind::Editor);
} else {
self.panels.focus(PanelKind::Drawer);
}
}
/// Ensure the Ask workspace is the editor-area content, for the leader
/// `a` conversation actions. Ungated: managing an existing thread works
/// even when the server can't answer (the composer stays disabled).
fn ensure_ask_workspace(&mut self, tx: &AppTx) {
if !self.panels.is_showing_ask() {
self.open_drawer_view(DrawerView::Ask, tx);
}
}
/// Ensure the Ask workspace is showing, then run `f` against its live
/// panel — the shared shape behind the leader `a n`/`a y`/`a e`/`a r`
/// conversation actions.
fn with_ask_panel(&mut self, tx: &AppTx, f: impl FnOnce(&mut ThreadPanel, &AppTx)) {
self.ensure_ask_workspace(tx);
f(self.panels.ask_mut(), tx);
}
/// Per-view side effects to run when `view` becomes visible in the
/// drawer — the single table shared by every reveal path (rail/leader
/// opens, the Ctrl-T toggle restore) so a view cannot go stale on one
/// path and refresh on another. `newly_shown` gates the effects that
/// must not clobber state the user already has on screen (an
/// in-progress FIND query, a browsed sidebar directory); the rest
/// refresh unconditionally. Never touches focus — callers decide that.
fn drawer_view_revealed(&mut self, view: DrawerView, newly_shown: bool, tx: &AppTx) {
match view {
DrawerView::Find if newly_shown => {
self.panels
.query_mut()
.set_note(self.path.clone(), tx.clone());
}
DrawerView::Files if newly_shown => {
self.reveal_note_dir_in_sidebar(tx);
}
DrawerView::Config => {
let info = {
let s = self.settings.read().unwrap();
let key_of = |a: &ActionShortcuts| {
s.key_bindings
.first_combo_for(a)
.unwrap_or_else(|| "unbound".to_string())
};
crate::components::drawer::ConfigInfo {
theme_name: s.get_theme().name,
leader_key: key_of(&ActionShortcuts::Leader),
preferences_key: key_of(&ActionShortcuts::OpenPreferences),
leader_timeout_ms: s.leader_timeout_ms,
config_path: s
.config_file
.as_ref()
.map(|p| p.display().to_string())
.unwrap_or_else(|| "default location".to_string()),
}
};
self.panels.drawer_set_config_info(info);
}
DrawerView::Semantic => self.panels.semantic_mut().ensure_source(tx),
DrawerView::Tags => self.panels.tags_mut().refresh(tx),
DrawerView::Links => self.panels.links_mut().set_note(self.path.clone(), tx),
DrawerView::Outline => self.panels.outline_mut().set_note(self.path.clone(), tx),
_ => {}
}
}
/// Move focus one visible panel left, wrapping at the end.
fn focus_left(&mut self, _tx: &AppTx) {
if let Some(kind) = self.panels.prev_kind() {
self.panels.focus(kind);
}
}
/// Move focus one visible panel right, wrapping at the end.
fn focus_right(&mut self, _tx: &AppTx) {
if let Some(kind) = self.panels.next_kind() {
self.panels.focus(kind);
}
}
/// Toggle the drawer (Ctrl-T): hiding it gives the full remaining width
/// to the editor; showing it restores the last view. Restoring is a
/// fresh reveal: the restored view re-targets/refreshes via the shared
/// `drawer_view_revealed` table — the note (or its data) may have
/// changed while hidden. Unlike an explicit open, toggling never moves
/// focus into the drawer.
fn toggle_drawer(&mut self, tx: &AppTx) {
if self.panels.is_visible(PanelKind::Drawer) {
self.panels.hide(PanelKind::Drawer);
} else {
self.panels.show(PanelKind::Drawer);
self.drawer_view_revealed(self.panels.active_drawer_view(), true, tx);
}
}
/// The query the save-current-query action would save, with its
/// saved-search provenance (breadcrumb name) for the dialog's name
/// pre-fill. Sourced from the active note browser if one is open (Ctrl+K
/// modal), otherwise from the Query panel. `None` when there is nothing
/// to save: a blank query, or another overlay is open.
fn save_query_source(&self) -> Option<(String, Option<String>, SaveSource)> {
let (query, provenance, source) = match self.overlays.active_kind() {
Some(OverlayKind::NoteBrowser) => (
self.overlays.active_query().unwrap_or_default().to_string(),
self.overlays
.active_saved_search_provenance()
.map(str::to_string),
SaveSource::NoteBrowser,
),
None => (
self.panels.query().active_query().to_string(),
self.panels.query().saved_search_name().map(str::to_string),
SaveSource::QueryPanel,
),
Some(_) => return None,
};
if query.trim().is_empty() {
None
} else {
Some((query, provenance, source))
}
}
/// Schedule a redraw for when the which-key overlay should reveal: the
/// hesitation timeout after the sequence (re)advanced. Fluent typing
/// never sees the overlay; the timer redraw simply finds the sequence
/// already gone.
fn schedule_whichkey_reveal(&self, tx: &AppTx) {
let timeout = {
let s = self.settings.read().unwrap();
std::time::Duration::from_millis(s.leader_timeout_ms)
};
let tx2 = tx.clone();
tokio::spawn(async move {
tokio::time::sleep(timeout + std::time::Duration::from_millis(10)).await;
let _ = tx2.send(AppEvent::Redraw);
});
}
/// Switch to the Ask workspace and drop the cursor on the composer (the
/// Ask shortcut / leader `a a`). The rail hides the ASK entry when the
/// server can't answer questions, so this shortcut is the only remaining
/// way in — hence the `llm_available` gate. The gate only
/// applies to that enter-from-outside path: when Ask is already showing,
/// focusing the composer is ungated, matching the sibling `a n`/`a
/// y`/`a e`/`a r` actions, which work fine on a degraded (capability-off)
/// thread.
fn open_ask_workspace(&mut self, tx: &AppTx) {
if self.overlays.is_open() {
return;
}
if !self.panels.is_showing_ask() {
if !self.rag_status.llm_available() {
tx.send(AppEvent::FlashMessage(
"Ask needs an LLM-configured server; this one is semantic-search only".into(),
))
.ok();
return;
}
self.open_drawer_view(DrawerView::Ask, tx);
}
self.panels.ask_mut().focus_composer();
self.panels.focus(PanelKind::Editor);
}
/// Follow the **follow target** under the editor cursor (FollowLink action,
/// Ctrl+Enter on kitty-protocol terminals).
///
/// Returns whether anything was actually followed, so a caller that only
/// *guessed* there was something there can fall back. A double-click is
/// exactly that guess: the classifier cannot hit-test the buffer, so it
/// asks and lets the answer decide.
fn follow_link_at_cursor(&mut self, tx: &AppTx) -> bool {
use crate::components::text_editor::FollowTarget;
// In the attachment view, FollowLink (Ctrl+N) opens the attachment with
// the OS default program rather than following a link (there is none).
if self.panels.is_showing_attachment() {
self.open_attachment_externally(tx);
return true;
}
let Some(editor) = self.panels.editor_mut() else {
return false;
};
match editor.follow_target_at_cursor() {
Some(FollowTarget::Link(target)) => {
tx.send(AppEvent::FollowLink(target)).ok();
true
}
Some(FollowTarget::Label(name)) => {
tx.send(AppEvent::FollowLabel(name)).ok();
true
}
None => false,
}
}
/// Opens the attachment currently shown in the editor area with the OS
/// default program (the same handoff `follow_link` uses for image links).
fn open_attachment_externally(&mut self, tx: &AppTx) {
let Some(path) = self.panels.attachment_path() else {
return;
};
let os_path = self.vault.path_to_pathbuf(path);
match open::that_detached(&os_path) {
Ok(()) => self
.footer
.flash(format!("Opening {}", os_path.display()), tx),
Err(e) => self.footer.flash(format!("Cannot open: {e}"), tx),
}
}
/// One key of a pending leader sequence. Esc cancels (focus returns to
/// the editor), Backspace steps up, chars walk the tree, a fired leaf
/// executes. Everything is consumed — a pending sequence owns the
/// keyboard.
fn handle_leader_key(
&mut self,
key: &ratatui::crossterm::event::KeyEvent,
tx: &AppTx,
) -> EventState {
use ratatui::crossterm::event::{KeyCode, KeyModifiers};
match key.code {
KeyCode::Esc => {
self.leader.cancel();
self.focus_editor();
}
KeyCode::Backspace => {
let outcome = self.leader.step_up();
// Stepping past the root cancels — no reveal to re-arm then.
if outcome == LeaderOutcome::SteppedUp {
self.schedule_whichkey_reveal(tx);
}
}
KeyCode::Char(c) if !key.modifiers.contains(KeyModifiers::CONTROL) => {
match self.leader.feed(c) {
LeaderOutcome::Fired(action) => self.execute_leader_action(action, tx),
LeaderOutcome::Invalid => {
// Gentle feedback; the sequence stays pending.
self.footer.flash(format!("leader: no entry for '{c}'"), tx);
self.schedule_whichkey_reveal(tx);
}
LeaderOutcome::Descended => self.schedule_whichkey_reveal(tx),
_ => {}
}
}
// Other keys (arrows, function keys, …) are swallowed; the
// sequence stays pending. Ctrl-chords never reach here — the
// intercept in handle_input cancels and re-dispatches them.
_ => {}
}
tx.send(AppEvent::Redraw).ok();
EventState::Consumed
}
/// Execute a fired leader leaf. Stubs for surfaces that land in later
/// phases flash a "coming soon" notice instead of silently doing nothing.
fn execute_leader_action(&mut self, action: LeaderAction, tx: &AppTx) {
match action {
LeaderAction::OpenDrawer(view) => self.open_drawer_view(view, tx),
LeaderAction::AppCheckUpdates => {
if let Some(status) = self.update.clone() {
self.present_overlay(Box::new(ActiveDialog::update(&status)));
} else {
// No cached notice — run a forced check and report the result.
let tx2 = tx.clone();
tx.send(AppEvent::FlashMessage("Checking for updates…".into()))
.ok();
tokio::spawn(async move {
let Ok(config_dir) = crate::settings::config_dir() else {
return;
};
match crate::update::check_now(config_dir, true).await {
Ok(Some(status)) if status.update_available => {
// Manual check: surface the notice AND open the
// dialog the user explicitly asked for (shown even
// if previously skipped — they asked).
tx2.send(AppEvent::Update(UpdateFlow::Available(status)))
.ok();
tx2.send(AppEvent::Update(UpdateFlow::ShowDialog)).ok();
}
Ok(_) => {
tx2.send(AppEvent::FlashMessage("kimün is up to date".into()))
.ok();
}
Err(e) => {
tx2.send(AppEvent::FlashMessage(format!(
"Update check failed: {e}"
)))
.ok();
}
}
});
}
}
// +find — list-style leaves route to today's pickers; the
// telescope modal takes them over in phase 08.
LeaderAction::FindFiles => self.open_overlay(OverlayOpen::FileFinder, tx),
LeaderAction::FindGrep => self.open_overlay(OverlayOpen::SearchBrowser, tx),
LeaderAction::FindTags => self.open_drawer_view(DrawerView::Tags, tx),
LeaderAction::FindBacklinks => {
self.open_find_with_query("<{note}".to_string(), None, tx)
}
LeaderAction::FindSaved => self.open_overlay(OverlayOpen::SavedSearches, tx),
LeaderAction::FindRecent => self.open_overlay(OverlayOpen::SearchBrowser, tx),
LeaderAction::FindHeadings => self.open_drawer_view(DrawerView::Outline, tx),
// +note
LeaderAction::NoteNew => {
// The FILES filter doubles as the create field (typing a new
// name offers "Create: …"); the telescope picker (08) gives
// this a dedicated door.
self.open_drawer_view(DrawerView::Files, tx);
self.footer
.flash("type a name — Enter creates".to_string(), tx);
}
LeaderAction::NoteDaily => {
tx.send(AppEvent::OpenJournal).ok();
}
LeaderAction::NoteFromTemplate => {
self.footer.flash("templates — coming soon".to_string(), tx);
}
LeaderAction::NoteRename => {
tx.send(AppEvent::FileOp(FileOp::ShowRename(self.path.clone())))
.ok();
}
LeaderAction::NoteMove => {
tx.send(AppEvent::FileOp(FileOp::ShowMove(self.path.clone())))
.ok();
}
LeaderAction::NoteDelete => {
tx.send(AppEvent::FileOp(FileOp::ShowDelete(self.path.clone())))
.ok();
}
// +links
LeaderAction::LinksTab(tab) => {
self.open_drawer_view(DrawerView::Links, tx);
self.panels.links_mut().show_tab(tab, tx);
}
LeaderAction::LinksGraph => {
self.footer
.flash("local graph — coming soon".to_string(), tx);
}
// +git/sync — status is live; the rest are display-only stubs
// (spec §12 keeps git interactions out of scope).
LeaderAction::GitStatus => {
self.doc_meta.refresh_git(tx);
let msg = self
.doc_meta
.git()
.cloned()
.unwrap_or_else(|| "not a git repository".to_string());
self.footer.flash(msg, tx);
}
LeaderAction::GitSync | LeaderAction::GitLog | LeaderAction::GitDiff => {
self.footer
.flash("git is display-only for now".to_string(), tx);
}
// +vault
LeaderAction::VaultSwitch => self.open_overlay(OverlayOpen::WorkspaceSwitcher, tx),
LeaderAction::VaultReindex => {
// Fast reindex right here — the same pipeline the Settings
// screen runs, result surfaced as a footer flash.
let vault = self.vault.clone();
let tx2 = tx.clone();
self.footer.flash("reindexing…".to_string(), tx);
tokio::spawn(async move {
let started = std::time::Instant::now();
let result = vault.index_notes(kimun_core::NotesValidation::Fast).await;
let msg = match result {
Ok(_) => format!("reindexed in {:.1?}", started.elapsed()),
Err(e) => format!("reindex failed: {e}"),
};
tx2.send(AppEvent::FlashMessage(msg)).ok();
});
}
// `v c` opens the config panel (the CFG drawer); `v t` opens the
// theme picker directly (also reachable inside CFG via `t`).
LeaderAction::VaultConfig => self.open_drawer_view(DrawerView::Config, tx),
LeaderAction::VaultTheme => self.open_overlay(OverlayOpen::ThemePicker, tx),
LeaderAction::VaultPreferences => {
tx.send(AppEvent::OpenScreen(ScreenEvent::OpenPreferences))
.ok();
}
LeaderAction::AppOnboarding => {
tx.send(AppEvent::OpenScreen(ScreenEvent::OpenOnboarding))
.ok();
}
// +window
LeaderAction::WindowZen => {
self.panels.hide(PanelKind::Drawer);
self.focus_editor();
}
LeaderAction::WindowSplit => {
self.footer
.flash("editor splits — coming soon".to_string(), tx);
}
LeaderAction::WindowGrowDrawer => self.panels.adjust_drawer_width(4),
LeaderAction::WindowShrinkDrawer => self.panels.adjust_drawer_width(-4),
// +this note
LeaderAction::NoteToggleTodo => {
self.footer
.flash("toggle todo — coming soon".to_string(), tx);
}
LeaderAction::NotePreview => {
self.footer
.flash("preview — lands with phase 09".to_string(), tx);
}
LeaderAction::NoteCopyWikilink => {
let link = format!("[[{}]]", self.path.get_clean_name());
crate::components::yank(link, "wikilink copied", tx);
}
LeaderAction::NoteExport => {
self.footer.flash("export — coming soon".to_string(), tx);
}
LeaderAction::NoteYankPath => {
let path = self.path.to_string();
crate::components::yank(path, "note path copied", tx);
}
// +ask — the Ask workspace's conversation actions.
LeaderAction::AskFocus => self.open_ask_workspace(tx),
LeaderAction::AskNew => {
self.with_ask_panel(tx, |panel, _tx| {
panel.thread_mut().clear();
panel.focus_composer();
});
self.panels.ask_sources_mut().reset(tx);
}
LeaderAction::AskCopy => {
self.with_ask_panel(tx, |panel, tx| panel.copy_selected(tx));
}
LeaderAction::AskSave => {
self.with_ask_panel(tx, |panel, tx| panel.save_selected(tx));
}
LeaderAction::AskRegenerate => {
self.with_ask_panel(tx, |panel, tx| panel.regenerate_selected(tx));
self.ask.sync_sources(&mut self.panels, tx);
}
LeaderAction::AskSource => {
self.ensure_ask_workspace(tx);
// The top source of the selected turn — sync the drawer to the
// current turn first, then open its first source in the reader.
self.ask.sync_sources_from_selected(&mut self.panels, tx);
self.panels.ask_sources_mut().open_reader(0, tx);
self.panels.focus(PanelKind::Drawer);
}
LeaderAction::Palette => self.open_overlay(OverlayOpen::CommandPalette, tx),
LeaderAction::Help => self.open_overlay(OverlayOpen::Cheatsheet, tx),
LeaderAction::NoteSave => {
// Flush the periodic autosave immediately (no manual-save
// concept; this force-persists the current buffer if dirty).
self.spawn_autosave(tx);
}
LeaderAction::AppQuit => {
tx.send(AppEvent::Quit).ok();
}
}
}
/// Kick off the async loads behind status line 2: the open note's
/// backlink count and the workspace git summary. Results return as
/// `BacklinkCountLoaded` / `GitStatusLoaded`; stale backlink completions
/// are dropped by path. Contract: this runs when a note is *opened* (and
/// the git half on autosave) — counts can go stale while a note stays
/// open and another note adds a link to it; accepted for now.
/// The one path that reveals FIND with a concrete query: used by saved
/// searches and tag queries so they cannot drift on what "open FIND"
/// means.
fn open_find_with_query(&mut self, query: String, name: Option<String>, tx: &AppTx) {
self.panels.open_drawer_view(DrawerView::Find);
self.panels.query_mut().apply_query(query, name, tx.clone());
self.panels.focus(PanelKind::Drawer);
}
fn apply_saved_search(&mut self, query: String, name: String, tx: &AppTx) {
// The virtual backlinks entry's name should not override the
// default "Backlinks" title — but the panel's title logic already
// shows "Backlinks" whenever the active query is `<{note}`, so it's
// safe to always pass the name through.
self.open_find_with_query(query, Some(name), tx);
}
fn toggle_backlinks(&mut self, tx: &AppTx) {
if self.drawer_open_on(DrawerView::Find) {
self.panels.hide(PanelKind::Drawer);
} else {
self.open_drawer_view(DrawerView::Find, tx);
}
}
}
#[async_trait]
impl AppScreen for EditorScreen {
fn get_kind(&self) -> ScreenKind {
ScreenKind::Editor
}
async fn on_enter(&mut self, tx: &AppTx) {
self.app_tx = Some(tx.clone());
self.open_path(self.path.clone(), None, tx).await;
}
fn handle_input(&mut self, event: &InputEvent, tx: &AppTx) -> EventState {
// Classify first, mutate after: the pure classifier resolves the
// event against the input precedence (see `editor_input`), and the
// executor methods below apply the resulting intent.
//
// The click run is fed ahead of the snapshot — it is the one piece of
// input-relevant state the event itself advances, and the classifier
// cannot advance it and stay pure. Nothing user-visible moves here.
let double_click = self.track_click(event, std::time::Instant::now());
let ctx = self.input_ctx(double_click);
// The settings lock guards the key bindings, which only the
// shortcut tier reads — never lock for mouse/paste traffic (mouse
// motion is high-frequency).
let classification = if matches!(event, InputEvent::Key(_)) {
let s = self.settings.read().unwrap();
classify(event, &s.key_bindings, &ctx)
} else {
classify(event, &KeyBindings::empty(), &ctx)
};
self.apply_classification(classification, event, tx)
}
fn render(&mut self, f: &mut ratatui::Frame) {
let theme = &self.theme;
f.render_widget(
ratatui::widgets::Block::default().style(theme.base_style()),
f.area(),
);
let rows = Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Length(1),
Constraint::Min(0),
Constraint::Length(crate::components::footer_bar::STATUS_BAR_HEIGHT),
])
.split(f.area());
// ── Title bar (1 line): Kimün · note breadcrumb · workspace badge ──
// Build the badge line once; its column width comes from the same
// value that gets rendered, so glyph/separator tweaks can't drift.
let workspace_badge = {
let s = self.settings.read().unwrap();
s.workspace_config.as_ref().map(|wc| {
ratatui::text::Line::from(vec![
ratatui::text::Span::styled(
self.icons.workspace,
Style::default().fg(theme.accent.to_ratatui()),
),
ratatui::text::Span::styled(
format!(" {}", wc.global.current_workspace),
Style::default().fg(theme.gray.to_ratatui()),
),
])
})
};
let workspace_label_width = workspace_badge
.as_ref()
.map(ratatui::text::Line::width)
.unwrap_or_default();
let breadcrumb = self
.path
.to_string()
.trim_start_matches('/')
.replace('/', " / ");
let title_cols = Layout::default()
.direction(Direction::Horizontal)
.constraints([
Constraint::Min(0),
Constraint::Length(workspace_label_width as u16 + 2),
])
.split(rows[0]);
f.render_widget(
Paragraph::new(ratatui::text::Line::from(vec![
ratatui::text::Span::styled(
" Kimün ",
Style::default()
.fg(theme.accent.to_ratatui())
.add_modifier(ratatui::style::Modifier::BOLD),
),
ratatui::text::Span::styled(
format!("─ {breadcrumb}"),
Style::default().fg(theme.fg_secondary.to_ratatui()),
),
])),
title_cols[0],
);
if let Some(badge) = workspace_badge {
f.render_widget(
Paragraph::new(badge).alignment(ratatui::layout::Alignment::Right),
title_cols[1],
);
}
// The panels lay themselves out and render. No panel shows its
// focused highlight while an overlay sits over them.
self.panels
.render(f, rows[1], theme, !self.overlays.is_open());
// Status bar reflects the overlay if one is open, otherwise the
// focused panel. `editing` drives the ⌨/≣ focus-context indicator —
// true when a text field holds the cursor.
let (focus_label, hints) = if let Some(kind) = self.overlays.active_kind() {
(kind.label(), self.overlays.hint_shortcuts())
} else {
(self.panels.focused_label(), self.panels.focused_hints())
};
let editing = if let Some(kind) = self.overlays.active_kind() {
// Browsers and the saved-searches modal host a query input;
// dialogs are button/list selections.
!matches!(kind, OverlayKind::Dialog)
} else {
match self.panels.focused() {
PanelKind::Editor => true,
PanelKind::Drawer => self.panels.drawer_is_text_input(),
PanelKind::Rail => false,
}
};
let path_str = self.path.to_string();
// Link-under-cursor affordance (spec §5.2): `→ target · N backlinks`.
// The backlink count loads async, cached per target.
let link_segment = if self.panels.focused() == PanelKind::Editor && !self.overlays.is_open()
{
let link = self
.panels
.editor()
.and_then(|e| e.follow_target_at_cursor());
self.doc_meta
.link_segment(link.as_ref(), &self.path, self.app_tx.as_ref())
} else {
None
};
// ln/col only when the editor buffer holds the cursor (not the
// attachment view, which has none).
let ln_col = (self.panels.focused() == PanelKind::Editor && !self.overlays.is_open())
.then(|| {
self.panels.editor().map(|e| {
let (row, col) = e.cursor_pos();
(row + 1, col + 1)
})
})
.flatten();
// Match count when the FIND drawer is the focused query context.
let matches = (self.panels.focused() == PanelKind::Drawer
&& self.panels.active_drawer_view() == DrawerView::Find)
.then(|| self.panels.query().result_count());
let (global_hints, leader_timeout, gateway_label) = {
let s = self.settings.read().unwrap();
(
crate::components::hints::global_hints(&s.key_bindings),
std::time::Duration::from_millis(s.leader_timeout_ms),
s.key_bindings
.first_combo_for(&ActionShortcuts::Leader)
.unwrap_or_else(|| "leader".to_string()),
)
};
let ctx = crate::components::footer_bar::StatusContext {
focus_label,
editing,
hints: &hints,
global_hints: &global_hints,
doc: crate::components::footer_bar::DocState {
path: &path_str,
dirty: self.panels.editor().is_some_and(|e| e.is_dirty()),
ln_col,
backlinks: self.doc_meta.backlinks(),
git: self.doc_meta.git().cloned(),
matches,
link: link_segment,
update: self
.update
.as_ref()
.map(|u| format!("⬆ {} available", u.latest)),
rag: self.rag_status.label().map(|s| s.to_string()),
},
};
self.footer.render(f, rows[2], theme, &ctx);
// which-key overlay — docked above the status bar once the user
// hesitates mid-sequence (spec §8b).
let whichkey_visible = self
.leader
.pending_since()
.is_some_and(|since| since.elapsed() >= leader_timeout);
if whichkey_visible {
let gateway = gateway_label;
let area = f.area();
let h = crate::components::which_key::desired_height(&self.leader, area.width)
.min(rows[1].height);
let rect =
ratatui::layout::Rect::new(area.x, rows[2].y.saturating_sub(h), area.width, h);
crate::components::which_key::render(f, rect, theme, &self.leader, &gateway);
}
// Overlay — rendered last so it appears on top of everything.
self.overlays.render(f, f.area(), &self.theme);
}
async fn handle_app_message(&mut self, msg: AppEvent, tx: &AppTx) {
match msg {
// Overlay data belongs to the open overlay alone (see CONTEXT.md):
// route it there and stop. `NotConsumed` — no overlay open, or not
// the kind the data was addressed to — means the result is stale;
// it is dropped here and nothing else ever sees it.
AppEvent::OverlayData(data) => {
self.overlays.handle_data(&data, &self.vault, tx);
}
AppEvent::Update(flow) => self.handle_update(flow, tx),
AppEvent::FileOp(op) => self.handle_file_op(op, tx).await,
AppEvent::SavedSearch(flow) => self.handle_saved_search(flow, tx),
msg => {
// Async status results (backlink count, git, link meta) are
// DocMeta's; everything else reaches the owned match.
let Some(msg) = self.doc_meta.handle(msg, &self.path) else {
return;
};
self.handle_owned_message(msg, tx).await;
}
}
}
/// The editor handles every path itself: notes open in the buffer,
/// directories navigate the sidebar. Always consumes.
async fn try_open_path(
&mut self,
path: VaultPath,
emphasis: Option<Vec<String>>,
tx: &AppTx,
) -> Option<VaultPath> {
self.dismiss_overlay();
if path.is_note() {
self.open_path(path, emphasis, tx).await;
self.focus_editor();
} else {
self.navigate_sidebar(path, tx);
}
None
}
async fn try_open_attachment(&mut self, path: VaultPath, tx: &AppTx) -> Option<VaultPath> {
self.dismiss_overlay();
self.open_attachment(path, tx).await;
None
}
async fn on_exit(&mut self, _tx: &AppTx) {
self.try_save().await;
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::keys::key_event_to_combo;
/// Compile-time test: `PanelKind` and `OverlayKind` are usable here.
#[test]
fn panel_kind_labels_and_overlay_kind_compile() {
assert_eq!(PanelKind::Editor.label(), "EDITOR");
assert_eq!(PanelKind::Rail.label(), "RAIL");
assert_eq!(DrawerView::Files.label(), "FILES");
assert_eq!(DrawerView::Find.label(), "FIND");
let _kind = OverlayKind::Dialog;
}
/// One screen over a fresh temp vault. Returns the `TempDir` so the vault
/// directory outlives the test body.
async fn test_screen() -> (
EditorScreen,
Arc<NoteVault>,
SharedSettings,
tempfile::TempDir,
) {
use crate::settings::AppSettings;
use kimun_core::VaultConfig;
use std::sync::RwLock;
let dir = tempfile::TempDir::new().unwrap();
let vault = Arc::new(
NoteVault::new(VaultConfig::new(crate::test_support::sys(dir.path())))
.await
.unwrap(),
);
let settings: SharedSettings = Arc::new(RwLock::new(AppSettings::default()));
let screen = EditorScreen::new(vault.clone(), VaultPath::root(), settings.clone());
(screen, vault, settings, dir)
}
fn key_event(code: ratatui::crossterm::event::KeyCode) -> InputEvent {
use ratatui::crossterm::event::{KeyEvent, KeyModifiers};
InputEvent::Key(KeyEvent::new(code, KeyModifiers::NONE))
}
fn ctrl_key(c: char) -> InputEvent {
use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
InputEvent::Key(KeyEvent::new(KeyCode::Char(c), KeyModifiers::CONTROL))
}
fn chr(c: char) -> InputEvent {
key_event(ratatui::crossterm::event::KeyCode::Char(c))
}
/// Ctrl-G (leader) then `o` `f` opens the FILES drawer — the full
/// sequence fires with no menu drawn and no timeout wait.
#[tokio::test]
async fn leader_sequence_opens_drawer_view() {
let (mut screen, _, _, _dir) = test_screen().await;
let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
// Start from a non-Files view so the switch is observable.
screen.panels.open_drawer_view(DrawerView::Tags);
screen.handle_input(&ctrl_key('g'), &tx);
assert!(screen.leader.is_pending());
screen.handle_input(&chr('o'), &tx);
screen.handle_input(&chr('f'), &tx);
assert!(!screen.leader.is_pending());
assert_eq!(screen.panels.active_drawer_view(), DrawerView::Files);
assert_eq!(screen.panels.focused(), PanelKind::Drawer);
}
/// Opening the FILES drawer points the sidebar at the current note's
/// directory, not the stale dir it was last left on.
#[tokio::test]
async fn opening_files_drawer_reveals_current_note_dir() {
let (mut screen, _, _, _dir) = test_screen().await;
let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
screen.path = VaultPath::new("projects").append(&VaultPath::note_path_from("plan"));
// Sidebar left on an unrelated directory, drawer hidden.
screen
.panels
.sidebar_mut()
.navigate(VaultPath::new("other"), &tx);
screen.panels.hide(PanelKind::Drawer);
screen.open_drawer_view(DrawerView::Files, &tx);
assert!(
screen
.panels
.sidebar()
.current_dir()
.is_like(&VaultPath::new("projects"))
);
}
/// With FILES already open but browsed elsewhere, the open-file-browser
/// shortcut is the "where is my note" gesture: it re-reveals the current
/// note's directory.
#[tokio::test]
async fn file_browser_shortcut_rereveals_note_dir_when_already_open() {
let (mut screen, _, _, _dir) = test_screen().await;
let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
screen.path = VaultPath::new("projects").append(&VaultPath::note_path_from("plan"));
screen.open_drawer_view(DrawerView::Files, &tx);
// User browses away while FILES stays open.
screen
.panels
.sidebar_mut()
.navigate(VaultPath::new("other"), &tx);
screen.handle_input(&ctrl_key('e'), &tx);
assert!(
screen
.panels
.sidebar()
.current_dir()
.is_like(&VaultPath::new("projects"))
);
}
/// The gateway works mid-typing: with the editor focused, Ctrl-G arms
/// the sequence and the next chars are consumed, not inserted.
#[tokio::test]
async fn leader_consumes_keys_while_editor_focused() {
let (mut screen, _, _, _dir) = test_screen().await;
let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
screen.panels.editor_mut().unwrap().set_text(String::new());
assert_eq!(screen.panels.focused(), PanelKind::Editor);
screen.handle_input(&ctrl_key('g'), &tx);
assert!(screen.leader.is_pending());
// 'w' is a group key; it must not land in the buffer.
screen.handle_input(&chr('w'), &tx);
screen.handle_input(&chr('z'), &tx); // zen: hides the drawer
assert_eq!(screen.panels.editor().unwrap().get_text(), "");
assert!(!screen.panels.is_visible(PanelKind::Drawer));
}
/// Esc cancels a pending sequence and returns focus to the editor.
#[tokio::test]
async fn leader_esc_cancels_and_focuses_editor() {
let (mut screen, _, _, _dir) = test_screen().await;
let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
screen.panels.focus(PanelKind::Rail);
screen.handle_input(&ctrl_key('g'), &tx);
screen.handle_input(&chr('f'), &tx);
screen.handle_input(&key_event(ratatui::crossterm::event::KeyCode::Esc), &tx);
assert!(!screen.leader.is_pending());
assert_eq!(screen.panels.focused(), PanelKind::Editor);
}
/// Bare Space never leads — the leader is only the configured gateway.
/// Space types a space in the editor and never arms the sequence, whatever
/// panel is focused (rail, a list drawer, or a text-input drawer).
#[tokio::test]
async fn space_never_leads() {
let (mut screen, _, _, _dir) = test_screen().await;
let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
// Editor focused: Space must insert a space.
screen.panels.editor_mut().unwrap().set_text(String::new());
screen.handle_input(&chr(' '), &tx);
assert!(!screen.leader.is_pending());
assert_eq!(screen.panels.editor().unwrap().get_text(), " ");
// Rail focused: Space must NOT lead.
screen.panels.focus(PanelKind::Rail);
screen.handle_input(&chr(' '), &tx);
assert!(!screen.leader.is_pending());
// FIND drawer (a text input): Space must NOT lead.
screen.panels.open_drawer_view(DrawerView::Find);
screen.panels.focus(PanelKind::Drawer);
screen.handle_input(&chr(' '), &tx);
assert!(!screen.leader.is_pending());
}
#[tokio::test]
async fn persist_saved_search_writes_via_core() {
let (screen, _, _, _dir) = test_screen().await;
screen.persist_saved_search("t", "#todo").await.unwrap();
let all = screen.vault.list_saved_searches().await.unwrap();
assert!(all.iter().any(|s| s.name == "t" && s.query == "#todo"));
}
#[tokio::test]
async fn applying_saved_search_sets_panel_query_and_focuses_it() {
let (mut screen, _, _, _dir) = test_screen().await;
let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
screen.apply_saved_search(
"<{note}".to_string(),
"Backlinks (current note)".to_string(),
&tx,
);
assert!(screen.panels.is_visible(PanelKind::Drawer));
assert_eq!(screen.panels.active_drawer_view(), DrawerView::Find);
assert_eq!(screen.panels.query().active_query(), "<{note}");
assert_eq!(screen.panels.focused(), PanelKind::Drawer);
}
#[tokio::test]
async fn saved_search_persisted_repins_panel_breadcrumb() {
let (mut screen, _, _, _dir) = test_screen().await;
let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
screen.apply_saved_search("#todo".to_string(), "todo".to_string(), &tx);
screen
.panels
.query_mut()
.set_active_query("#todo and #urgent".to_string());
screen
.handle_app_message(
AppEvent::SavedSearch(SavedSearchFlow::Persisted {
name: "urgent-todos".to_string(),
query: "#todo and #urgent".to_string(),
source: SaveSource::QueryPanel,
}),
&tx,
)
.await;
assert_eq!(
screen.panels.query().saved_search_breadcrumb().as_deref(),
Some("urgent-todos"),
"a persisted panel-sourced save re-pins the breadcrumb"
);
}
#[tokio::test]
async fn persisted_note_browser_save_does_not_repin_even_on_equal_query() {
let (mut screen, _, _, _dir) = test_screen().await;
let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
screen.apply_saved_search("#todo".to_string(), "todo".to_string(), &tx);
// A note-browser-sourced save whose query text happens to equal the
// panel's live query: source identity, not text equality, decides.
screen
.handle_app_message(
AppEvent::SavedSearch(SavedSearchFlow::Persisted {
name: "inbox".to_string(),
query: "#todo".to_string(),
source: SaveSource::NoteBrowser,
}),
&tx,
)
.await;
assert_eq!(
screen.panels.query().saved_search_breadcrumb().as_deref(),
Some("todo"),
"a note-browser save must not steal the panel's provenance"
);
}
#[tokio::test]
async fn persisted_query_as_name_save_skips_repin() {
let (mut screen, _, _, _dir) = test_screen().await;
let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
screen.apply_saved_search("#todo".to_string(), "todo".to_string(), &tx);
// The empty-name fallback saved the query under its own text. Pinning
// that as the breadcrumb name would just echo the query (CONTEXT.md:
// the breadcrumb is a distinct provenance tag, not the query).
screen
.handle_app_message(
AppEvent::SavedSearch(SavedSearchFlow::Persisted {
name: "#todo".to_string(),
query: "#todo".to_string(),
source: SaveSource::QueryPanel,
}),
&tx,
)
.await;
assert_eq!(
screen.panels.query().saved_search_breadcrumb().as_deref(),
Some("todo"),
"a query-as-name save leaves the breadcrumb alone"
);
}
#[tokio::test]
async fn save_search_confirmed_persists_then_emits_persisted() {
let (mut screen, vault, _, _dir) = test_screen().await;
let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
screen
.handle_app_message(
AppEvent::SavedSearch(SavedSearchFlow::Confirmed {
name: "mine".to_string(),
query: "#todo".to_string(),
source: SaveSource::QueryPanel,
}),
&tx,
)
.await;
// The write runs in a spawned task; Persisted arrives only on success.
let event = tokio::time::timeout(std::time::Duration::from_secs(5), async {
loop {
match rx.recv().await {
Some(e @ AppEvent::SavedSearch(SavedSearchFlow::Persisted { .. })) => break e,
Some(_) => continue,
None => panic!("channel closed before SavedSearchPersisted"),
}
}
})
.await
.expect("SavedSearchPersisted within timeout");
let AppEvent::SavedSearch(SavedSearchFlow::Persisted {
name,
query,
source,
}) = event
else {
unreachable!()
};
assert_eq!((name.as_str(), query.as_str()), ("mine", "#todo"));
assert_eq!(source, SaveSource::QueryPanel);
let all = vault.list_saved_searches().await.unwrap();
assert!(all.iter().any(|s| s.name == "mine" && s.query == "#todo"));
}
#[tokio::test]
async fn save_query_source_carries_panel_provenance() {
let (mut screen, _, _, _dir) = test_screen().await;
let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
screen.apply_saved_search("#todo".to_string(), "todo".to_string(), &tx);
assert_eq!(
screen.save_query_source(),
Some((
"#todo".to_string(),
Some("todo".to_string()),
SaveSource::QueryPanel
)),
"the save dialog opens pre-filled with the breadcrumb provenance"
);
}
// The try_save timeout-abort regression tests (commits 55eb49ed +
// 5e28b796) previously lived here against `await_or_abort`. The
// logic now lives in `SingleSlotTask::await_with_timeout` and is
// covered by `single_slot_task_timeout_returns_none_keeps_handle`
// in `crate::util::single_slot_task`.
#[tokio::test]
async fn saved_search_selected_then_close_overlay_keeps_backlinks_focus() {
use crate::settings::AppSettings;
use kimun_core::VaultConfig;
use std::sync::RwLock;
let dir = tempfile::TempDir::new().unwrap();
let vault = Arc::new(
NoteVault::new(VaultConfig::new(crate::test_support::sys(dir.path())))
.await
.unwrap(),
);
let settings: SharedSettings = Arc::new(RwLock::new(AppSettings::default()));
let mut screen = EditorScreen::new(vault, VaultPath::root(), settings);
let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
// Replay the exact sequence the saved-searches modal emits on select.
screen
.handle_app_message(
AppEvent::SavedSearch(SavedSearchFlow::Selected {
query: "<{note}".to_string(),
name: "Backlinks (current note)".to_string(),
}),
&tx,
)
.await;
screen.handle_app_message(AppEvent::CloseOverlay, &tx).await;
assert!(
screen.panels.focused() == PanelKind::Drawer
&& screen.panels.active_drawer_view() == DrawerView::Find,
"focus should remain on the FIND drawer after select + close"
);
assert!(!screen.overlays.is_open(), "overlay should be closed");
}
/// Capture-all guard: while an overlay is open, an opener action
/// (QuickNote) must NOT replace it. Drives a real QuickNote keypress
/// through `handle_input` so the guard in the action arm is exercised
/// end-to-end.
#[tokio::test]
async fn opener_action_does_not_replace_open_overlay() {
use crate::settings::AppSettings;
use kimun_core::VaultConfig;
use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use std::sync::RwLock;
let dir = tempfile::TempDir::new().unwrap();
let vault = Arc::new(
NoteVault::new(VaultConfig::new(crate::test_support::sys(dir.path())))
.await
.unwrap(),
);
let settings: SharedSettings = Arc::new(RwLock::new(AppSettings::default()));
let mut screen = EditorScreen::new(vault.clone(), VaultPath::root(), settings.clone());
let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
// Force a SavedSearches overlay open and focus it, as if the user had
// opened it via its action.
{
let s = settings.read().unwrap();
let modal = SavedSearchesModal::new(
vault.clone(),
s.key_bindings.clone(),
s.icons(),
tx.clone(),
);
drop(s);
screen.overlays.open(Box::new(modal), screen.opener_focus());
}
assert_eq!(
screen.overlays.active_kind(),
Some(OverlayKind::SavedSearches),
"precondition: SavedSearches overlay is active"
);
// The QuickNote action key (Ctrl+W by default). Assert the binding
// resolves to QuickNote so this test fails loudly if the default
// rebinds, rather than silently exercising the wrong path.
let quick_note_event = KeyEvent::new(KeyCode::Char('w'), KeyModifiers::CONTROL);
{
let s = settings.read().unwrap();
let combo = key_event_to_combo(&quick_note_event).expect("Ctrl+W maps to a combo");
assert_eq!(
s.key_bindings.get_action(&combo),
Some(ActionShortcuts::QuickNote),
"test assumes Ctrl+W is bound to QuickNote"
);
}
screen.handle_input(&InputEvent::Key(quick_note_event), &tx);
// The guard must have suppressed the open: the SavedSearches overlay
// is still active, NOT replaced by the QuickNote dialog.
assert_eq!(
screen.overlays.active_kind(),
Some(OverlayKind::SavedSearches),
"open overlay must not be replaced by a QuickNote opener action"
);
}
/// Focus actions are inert while an overlay owns input: pressing
/// FocusEditor (Ctrl+L) with a dialog open must not reveal or move the
/// panels underneath, so closing the dialog leaves the layout unchanged.
#[tokio::test]
async fn focus_action_is_noop_while_overlay_open() {
use crate::settings::AppSettings;
use kimun_core::VaultConfig;
use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use std::sync::RwLock;
let dir = tempfile::TempDir::new().unwrap();
let vault = Arc::new(
NoteVault::new(VaultConfig::new(crate::test_support::sys(dir.path())))
.await
.unwrap(),
);
let settings: SharedSettings = Arc::new(RwLock::new(AppSettings::default()));
let mut screen = EditorScreen::new(vault.clone(), VaultPath::root(), settings.clone());
let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
// Open a SavedSearches overlay (Query panel starts hidden).
{
let s = settings.read().unwrap();
let modal = SavedSearchesModal::new(
vault.clone(),
s.key_bindings.clone(),
s.icons(),
tx.clone(),
);
drop(s);
screen.overlays.open(Box::new(modal), screen.opener_focus());
}
assert_ne!(screen.panels.active_drawer_view(), DrawerView::Find);
let focused_before = screen.panels.focused();
// Ctrl+L (FocusEditor / focus right) must be consumed but do nothing.
let focus_right = KeyEvent::new(KeyCode::Char('l'), KeyModifiers::CONTROL);
{
let s = settings.read().unwrap();
let combo = key_event_to_combo(&focus_right).expect("Ctrl+L maps to a combo");
assert_eq!(
s.key_bindings.get_action(&combo),
Some(ActionShortcuts::FocusEditor),
"test assumes Ctrl+L is bound to FocusEditor"
);
}
screen.handle_input(&InputEvent::Key(focus_right), &tx);
assert_eq!(
screen.panels.focused(),
focused_before,
"focus action must not move focus while an overlay is open"
);
assert_ne!(
screen.panels.active_drawer_view(),
DrawerView::Find,
"focus action must not switch the drawer view while an overlay is open"
);
assert_eq!(
screen.overlays.active_kind(),
Some(OverlayKind::SavedSearches),
"overlay stays active"
);
}
/// Opening the journal while an overlay is up dismisses the overlay, so the
/// journal note isn't loaded behind it. OpenJournal is now resolved at the
/// app level into an OpenPath, which lands here in `try_open_path` — that's
/// the door that must dismiss the overlay.
#[tokio::test(flavor = "multi_thread")]
async fn open_journal_dismisses_open_overlay() {
let vault = crate::test_support::temp_vault("editor-journal").await;
vault.validate_and_init().await.unwrap();
let settings = std::sync::Arc::new(std::sync::RwLock::new(
crate::settings::AppSettings::default(),
));
let mut screen = EditorScreen::new(vault.clone(), VaultPath::root(), settings.clone());
let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
{
let s = settings.read().unwrap();
let modal = SavedSearchesModal::new(
vault.clone(),
s.key_bindings.clone(),
s.icons(),
tx.clone(),
);
drop(s);
screen.present_overlay(Box::new(modal));
}
assert!(screen.overlays.is_open(), "precondition: overlay open");
let (details, _, _) = vault.journal_entry().await.unwrap();
screen.try_open_path(details.path, None, &tx).await;
assert!(
!screen.overlays.is_open(),
"opening the journal must dismiss the overlay before loading the note"
);
}
/// Opening an attachment swaps the editor area to the read-only attachment
/// view: the note editor accessor reports absent, and FollowLink in that
/// state opens externally rather than touching the (absent) editor.
#[tokio::test(flavor = "multi_thread")]
async fn opening_attachment_shows_attachment_view() {
let vault = crate::test_support::temp_vault("editor-attachment").await;
vault.validate_and_init().await.unwrap();
vault
.save_attachment(&VaultPath::new("assets/diagram.png"), &[1, 2, 3])
.await
.unwrap();
let settings = std::sync::Arc::new(std::sync::RwLock::new(
crate::settings::AppSettings::default(),
));
let mut screen = EditorScreen::new(vault.clone(), VaultPath::root(), settings);
let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
// Precondition: a note editor is mounted.
assert!(screen.panels.editor().is_some());
screen
.try_open_attachment(VaultPath::new("assets/diagram.png"), &tx)
.await;
assert!(
screen.panels.is_showing_attachment(),
"the editor area shows the attachment view"
);
assert!(
screen.panels.editor().is_none(),
"no note editor is mounted while an attachment is shown"
);
assert_eq!(
screen.panels.attachment_path(),
Some(&VaultPath::new("assets/diagram.png"))
);
// Returning to a note swaps the editor area back.
vault
.create_note(&VaultPath::new("note.md"), "hi")
.await
.unwrap();
screen.open_path(VaultPath::new("note.md"), None, &tx).await;
assert!(!screen.panels.is_showing_attachment());
assert!(screen.panels.editor().is_some());
}
#[tokio::test]
async fn save_query_from_note_browser_opens_save_dialog() {
use crate::settings::AppSettings;
use kimun_core::VaultConfig;
use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use std::sync::RwLock;
let dir = tempfile::TempDir::new().unwrap();
let vault = Arc::new(
NoteVault::new(VaultConfig::new(crate::test_support::sys(dir.path())))
.await
.unwrap(),
);
let settings: SharedSettings = Arc::new(RwLock::new(AppSettings::default()));
let mut screen = EditorScreen::new(vault.clone(), VaultPath::root(), settings.clone());
let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
// Open a note browser carrying a query, as if the user typed "#todo".
{
let s = settings.read().unwrap();
let provider = resolving_search_source(vault.clone(), s.current_last_paths(), None);
let modal = NoteBrowserModal::with_initial_query(
"Note Browser",
BrowserScope::Query,
provider,
vault.clone(),
s.key_bindings.clone(),
s.icons(),
tx.clone(),
"#todo",
);
drop(s);
screen.overlays.open(Box::new(modal), screen.opener_focus());
}
assert_eq!(
screen.overlays.active_kind(),
Some(OverlayKind::NoteBrowser),
"precondition: note browser is active with a query"
);
assert_eq!(screen.overlays.active_query(), Some("#todo"));
// Ctrl+D (SaveCurrentQuery) while the note browser is active should
// replace it with the save-search dialog, sourcing the browser's query.
let save_event = KeyEvent::new(KeyCode::Char('d'), KeyModifiers::CONTROL);
{
let s = settings.read().unwrap();
let combo = key_event_to_combo(&save_event).expect("Ctrl+D maps to a combo");
assert_eq!(
s.key_bindings.get_action(&combo),
Some(ActionShortcuts::SaveCurrentQuery),
"test assumes Ctrl+D is bound to SaveCurrentQuery"
);
}
screen.handle_input(&InputEvent::Key(save_event), &tx);
assert_eq!(
screen.overlays.active_kind(),
Some(OverlayKind::Dialog),
"saving from the note browser opens the save-search dialog"
);
}
/// Renaming the open note keeps it open under the new path (retarget in
/// place) instead of navigating away, and reloads the buffer clean.
#[tokio::test(flavor = "multi_thread")]
async fn renaming_open_note_retargets_in_place() {
let vault = crate::test_support::temp_vault("editor-rename").await;
vault.validate_and_init().await.unwrap();
let from = VaultPath::note_path_from("old");
vault.create_note(&from, "# Old\n\nbody").await.unwrap();
let settings = std::sync::Arc::new(std::sync::RwLock::new(
crate::settings::AppSettings::default(),
));
let mut screen = EditorScreen::new(vault.clone(), from.clone(), settings);
let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
screen.on_enter(&tx).await;
let to = VaultPath::note_path_from("new");
vault.rename_note(&from, &to).await.unwrap();
screen
.handle_app_message(
AppEvent::FileOp(FileOp::Renamed {
from: from.clone(),
to: to.clone(),
}),
&tx,
)
.await;
assert_eq!(screen.path, to, "editor retargets to the new path");
assert!(
!screen.panels.editor().unwrap().is_dirty(),
"reloaded buffer is clean (won't clobber the renamed file)"
);
}
/// Opening a note marks its sidebar row; saving it (AutosaveCompleted with a
/// new title) updates that row's title in place.
#[tokio::test(flavor = "multi_thread")]
async fn open_then_save_marks_and_retitles_sidebar_row() {
let vault = crate::test_support::temp_vault("editor-marksave").await;
vault.validate_and_init().await.unwrap();
vault
.create_note(&VaultPath::note_path_from("alpha"), "# Alpha\n\nbody")
.await
.unwrap();
let settings = std::sync::Arc::new(std::sync::RwLock::new(
crate::settings::AppSettings::default(),
));
let path = VaultPath::note_path_from("alpha");
let mut screen = EditorScreen::new(vault.clone(), path.clone(), settings);
let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
screen.on_enter(&tx).await;
for _ in 0..50 {
screen.panels.sidebar_mut().poll_for_test();
if !screen.panels.sidebar().is_loading_for_test() {
break;
}
tokio::time::sleep(std::time::Duration::from_millis(5)).await;
}
assert!(
screen
.panels
.sidebar()
.note_row_is_open_for_test("alpha.md"),
"the open note's row is marked"
);
screen
.handle_app_message(
AppEvent::AutosaveCompleted {
path: path.clone(),
saved_revision: None,
title: Some("New First Line".to_string()),
},
&tx,
)
.await;
assert_eq!(
screen.panels.sidebar().note_row_title_for_test("alpha.md"),
Some("New First Line".to_string()),
"the saved note's row title updated in place"
);
}
/// Switching the drawer view Ask → Files → Ask preserves the conversation:
/// the resident thread panel is never dropped, so its turns are intact on
/// the way back in (rules 1 & 2, CONTEXT.md: Thread lifetime).
#[tokio::test]
async fn ask_drawer_switch_preserves_thread() {
let (mut screen, _, _, _dir) = test_screen().await;
let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
// Enter the Ask workspace and seed a couple of turns.
screen.open_drawer_view(DrawerView::Ask, &tx);
assert!(screen.panels.is_showing_ask());
{
let panel = screen.panels.ask_mut();
panel.thread_mut().ask("first?".into());
panel.thread_mut().ask("second?".into());
}
assert_eq!(screen.panels.ask().thread().turns().len(), 2);
// Switch away: the editor area leaves Ask, but the resident thread
// panel keeps the conversation.
screen.open_drawer_view(DrawerView::Files, &tx);
assert!(!screen.panels.is_showing_ask());
assert_eq!(screen.panels.ask().thread().turns().len(), 2);
// Switch back: the same conversation is on screen.
screen.open_drawer_view(DrawerView::Ask, &tx);
assert!(screen.panels.is_showing_ask());
assert_eq!(
screen.panels.ask().thread().turns().len(),
2,
"the conversation survives the round trip"
);
}
/// An `AskData::AnswerReady` delivered through the screen's real message
/// pump (`handle_app_message`, the same entry point the app loop uses —
/// not the coordinator's `handle_data` called directly) must still land on
/// the thread: it should route through `handle_owned_message`'s
/// `AppEvent::Ask(data)` arm to `AskCoordinator::handle_data` end to end.
#[tokio::test]
async fn ask_answer_ready_reaches_the_thread_via_the_owned_message_path() {
let (mut screen, _, _, _dir) = test_screen().await;
let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
screen.open_drawer_view(DrawerView::Ask, &tx);
let id = screen.panels.ask_mut().thread_mut().ask("q?".into());
screen
.handle_app_message(
AppEvent::Ask(crate::components::events::AskData::AnswerReady {
turn_id: id,
result: Ok(("the answer".into(), vec![])),
}),
&tx,
)
.await;
let panel = screen.panels.ask_mut();
let turn = panel.thread().selected().expect("a turn is selected");
assert!(matches!(turn.status, crate::ask::TurnStatus::Done));
assert_eq!(turn.answer, "the answer");
}
/// Opening a note from the browser while the Ask workspace is shown must
/// swap the editor area to the note (carry-forward: `open_path` calls
/// `clear_attachment`, which no-ops on Ask, so the stash is the only thing
/// that gets the note on screen) — and the thread survives to be re-shown.
#[tokio::test]
async fn opening_a_note_over_ask_shows_the_note_and_keeps_the_thread() {
let vault = crate::test_support::temp_vault("editor-ask-open").await;
vault.validate_and_init().await.unwrap();
vault
.create_note(&VaultPath::note_path_from("alpha"), "# Alpha\n\nbody")
.await
.unwrap();
let settings = std::sync::Arc::new(std::sync::RwLock::new(
crate::settings::AppSettings::default(),
));
let mut screen = EditorScreen::new(vault, VaultPath::root(), settings);
let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
screen.open_drawer_view(DrawerView::Ask, &tx);
screen
.panels
.ask_mut()
.thread_mut()
.ask("a question?".into());
assert!(screen.panels.is_showing_ask());
// Open a note: the editor area must show it, not the thread.
screen
.open_path(VaultPath::note_path_from("alpha"), None, &tx)
.await;
assert!(!screen.panels.is_showing_ask(), "the note replaced Ask");
assert!(screen.panels.editor().is_some(), "the note editor is shown");
assert_eq!(
screen.panels.active_drawer_view(),
DrawerView::Files,
"the Sources drawer must not linger on a hidden conversation"
);
// Re-enter Ask: the resident conversation comes back intact.
screen.open_drawer_view(DrawerView::Ask, &tx);
assert_eq!(
screen.panels.ask().thread().turns().len(),
1,
"the thread survived opening the note"
);
}
/// Opening a note while Ask is shown but the drawer was explicitly hidden
/// must switch the drawer's view to FILES *without* re-revealing it — the
/// view switch preserves visibility (fold-in #4). Before the fix the
/// FILES switch went through `open_drawer_view`, which force-showed a
/// drawer the user had hidden.
#[tokio::test]
async fn opening_a_note_over_ask_with_hidden_drawer_keeps_it_hidden() {
let vault = crate::test_support::temp_vault("editor-ask-hidden-drawer").await;
vault.validate_and_init().await.unwrap();
vault
.create_note(&VaultPath::note_path_from("alpha"), "# Alpha\n\nbody")
.await
.unwrap();
let settings = std::sync::Arc::new(std::sync::RwLock::new(
crate::settings::AppSettings::default(),
));
let mut screen = EditorScreen::new(vault, VaultPath::root(), settings);
let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
// Enter Ask, then hide the drawer while the workspace stays on screen.
screen.open_drawer_view(DrawerView::Ask, &tx);
screen.panels.hide(PanelKind::Drawer);
assert!(!screen.panels.is_visible(PanelKind::Drawer));
assert!(screen.panels.is_showing_ask());
// Open a note: Ask leaves the editor area and the drawer view switches
// to FILES, but the drawer must stay hidden.
screen
.open_path(VaultPath::note_path_from("alpha"), None, &tx)
.await;
assert!(!screen.panels.is_showing_ask(), "the note replaced Ask");
assert!(
!screen.panels.is_visible(PanelKind::Drawer),
"a hidden drawer must not be force-revealed"
);
assert_eq!(
screen.panels.active_drawer_view(),
DrawerView::Files,
"the view switched off Ask to FILES"
);
}
/// Regression for the rail-click toggle bug: before the fix, opening a
/// note over Ask left the drawer's active view stuck on `Ask` (only the
/// editor-area content moved), so the next `OpenDrawerView(Ask)` — what a
/// rail click sends — read as "already showing, toggle it closed"
/// instead of "reopen it", requiring a second click. Drives the real
/// `AppEvent::OpenDrawerView` path (not the direct `open_drawer_view`
/// helper) so this test actually exercises that toggle branch.
#[tokio::test]
async fn rail_click_reenters_ask_in_one_click_after_a_note_stashed_it() {
let vault = crate::test_support::temp_vault("editor-ask-rail-reentry").await;
vault.validate_and_init().await.unwrap();
vault
.create_note(&VaultPath::note_path_from("alpha"), "# Alpha\n\nbody")
.await
.unwrap();
let settings = std::sync::Arc::new(std::sync::RwLock::new(
crate::settings::AppSettings::default(),
));
let mut screen = EditorScreen::new(vault, VaultPath::root(), settings);
screen.rag_status = crate::rag::RagStatus::Online {
llm_available: true,
};
let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
screen
.handle_app_message(AppEvent::OpenDrawerView(DrawerView::Ask), &tx)
.await;
assert!(screen.panels.is_showing_ask());
screen
.panels
.ask_mut()
.thread_mut()
.ask("a question?".into());
screen
.open_path(VaultPath::note_path_from("alpha"), None, &tx)
.await;
assert!(!screen.panels.is_showing_ask());
// One click — one `OpenDrawerView(Ask)` — must land back on Ask.
screen
.handle_app_message(AppEvent::OpenDrawerView(DrawerView::Ask), &tx)
.await;
assert!(
screen.panels.is_showing_ask(),
"a single reopen must not read as a toggle-off"
);
assert_eq!(
screen.panels.ask().thread().turns().len(),
1,
"the thread survived the round trip"
);
}
/// Opening an attachment while the Ask workspace is shown must swap the
/// editor area to the attachment view (`show_attachment` leaves Ask content
/// alone, so the stash is the only thing that gets it off screen) — and the
/// thread survives to be re-shown. Mirrors the open-note-over-Ask case for
/// the attachment entry point.
#[tokio::test]
async fn opening_an_attachment_over_ask_shows_it_and_keeps_the_thread() {
let vault = crate::test_support::temp_vault("editor-ask-open-att").await;
vault.validate_and_init().await.unwrap();
let att_path = VaultPath::new("pic.png");
vault
.save_attachment(&att_path, b"\x89PNG\r\n\x1a\n")
.await
.unwrap();
let settings = std::sync::Arc::new(std::sync::RwLock::new(
crate::settings::AppSettings::default(),
));
let mut screen = EditorScreen::new(vault, VaultPath::root(), settings);
let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
screen.open_drawer_view(DrawerView::Ask, &tx);
screen
.panels
.ask_mut()
.thread_mut()
.ask("a question?".into());
assert!(screen.panels.is_showing_ask());
// Open an attachment: the editor area must show it, not the thread.
screen.open_attachment(att_path, &tx).await;
assert!(
!screen.panels.is_showing_ask(),
"the attachment replaced Ask"
);
// Re-enter Ask: the stashed conversation comes back intact.
screen.open_drawer_view(DrawerView::Ask, &tx);
assert_eq!(
screen.panels.ask().thread().turns().len(),
1,
"the thread survived opening the attachment"
);
}
/// Client presence at the screen seam: with no LLM-capable server there is
/// no client, so the resident Ask panel's composer is disabled (never a
/// forever-`Thinking` turn; carry-forward #2).
#[tokio::test]
async fn refresh_ask_capability_disables_without_a_client() {
let (mut screen, _, _, _dir) = test_screen().await;
// rag_status is Disabled here → no client → composer disabled.
screen
.ask
.refresh_capability(&mut screen.panels, screen.rag_status)
.await;
assert!(
!screen.panels.ask().has_client(),
"the resident Ask panel loses its client without an LLM server"
);
}
/// An answer that lands while the user is browsing FILES (Ask not shown) is
/// delivered to the resident thread, not dropped (rule 3).
#[tokio::test]
async fn answer_lands_on_the_thread_while_browsing_files() {
let (mut screen, _, _, _dir) = test_screen().await;
let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
screen.open_drawer_view(DrawerView::Ask, &tx);
let turn_id = screen.panels.ask_mut().thread_mut().ask("q?".into());
// Leave Ask: the in-flight turn stays on the resident panel.
screen.open_drawer_view(DrawerView::Files, &tx);
assert!(!screen.panels.is_showing_ask());
screen.ask.handle_data(
&mut screen.panels,
crate::components::events::AskData::AnswerReady {
turn_id,
result: Ok(("the answer".into(), vec![])),
},
&tx,
);
let thread = screen.panels.ask().thread();
let turn = thread.turns().iter().find(|t| t.id == turn_id).unwrap();
assert!(
matches!(turn.status, crate::ask::TurnStatus::Done),
"the answer completed the turn"
);
}
/// SEM's rail entry is live-status-driven, exactly like ASK: hidden until a
/// health probe reports the server reachable for search, shown for a
/// semantic-only server (search works, ASK stays hidden), and hidden again
/// when the server drops offline.
#[tokio::test]
async fn sem_rail_entry_tracks_search_availability() {
let (mut screen, _, _, _dir) = test_screen().await;
let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
// Startup: no status yet → SEM (and ASK) hidden.
assert!(!screen.panels.rail_shows(DrawerView::Semantic));
assert!(!screen.panels.rail_shows(DrawerView::Ask));
// Semantic-only server comes online: SEM appears, ASK stays hidden.
screen
.handle_owned_message(
AppEvent::RagStatus(crate::rag::RagStatus::Online {
llm_available: false,
}),
&tx,
)
.await;
assert!(screen.panels.rail_shows(DrawerView::Semantic));
assert!(!screen.panels.rail_shows(DrawerView::Ask));
// Server drops offline: SEM disappears too (not driven by config).
screen
.handle_owned_message(AppEvent::RagStatus(crate::rag::RagStatus::Offline), &tx)
.await;
assert!(!screen.panels.rail_shows(DrawerView::Semantic));
// LLM-capable server: both SEM and ASK appear.
screen
.handle_owned_message(
AppEvent::RagStatus(crate::rag::RagStatus::Online {
llm_available: true,
}),
&tx,
)
.await;
assert!(screen.panels.rail_shows(DrawerView::Semantic));
assert!(screen.panels.rail_shows(DrawerView::Ask));
}
/// Leader `a a` (`open_ask_workspace`) gates on `llm_available` only for
/// the enter-from-outside path. Once Ask is already showing, the
/// sibling `a n`/`a y`/`a e`/`a r` actions all work on a degraded
/// (capability-off) thread, so re-focusing the composer must be
/// consistent with them rather than flashing the gate message again.
#[tokio::test]
async fn ask_focus_skips_the_llm_gate_when_already_showing_ask() {
let (mut screen, _, _, _dir) = test_screen().await;
let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
screen.rag_status = crate::rag::RagStatus::Online {
llm_available: true,
};
screen.open_ask_workspace(&tx);
assert!(screen.panels.is_showing_ask());
// Capability drops mid-conversation: the thread stays on screen with
// the composer merely disabled, never evicted.
screen.rag_status = crate::rag::RagStatus::Offline;
screen.open_ask_workspace(&tx);
assert!(screen.panels.is_showing_ask(), "still showing Ask");
assert_eq!(screen.panels.focused(), PanelKind::Editor);
assert!(
rx.try_recv().is_err(),
"no gate flash while Ask is already showing"
);
}
// ── Following a link with the mouse: the screen's half of the rule ──────
//
// `ClickRun` owns which *mouse* events are one gesture and is tested
// against a real event sequence there. What `track_click` owns is
// everything the run cannot answer for itself — is this a mouse event, is
// an overlay in the way, did the press land on the note buffer — and that
// last one is a hit-test, which is where the frame-counted-as-buffer defect
// lived.
/// Lay the screen out by rendering it, so the hit-test reads the rects a
/// real frame produced rather than defaults.
fn lay_out(screen: &mut EditorScreen) {
let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(120, 40)).unwrap();
term.draw(|f| screen.render(f)).unwrap();
}
/// The buffer's top-left cell, found by asking the screen's own gate — so
/// the coordinates cannot drift from the layout the way a literal would.
fn buffer_origin(screen: &EditorScreen) -> (u16, u16) {
(0..40u16)
.flat_map(|row| (0..120u16).map(move |col| (col, row)))
.find(|(col, row)| screen.panels.is_note_buffer_cell(*col, *row))
.expect("a laid-out screen always shows the note buffer")
}
/// A cell on the frame `PanelSet::render` draws around the editor: the
/// corner one row above and one column left of the buffer's first cell.
///
/// The assert is the point, not a formality. Deriving the probe from
/// [`buffer_origin`] means the gate picks where the test looks, so a gate
/// that answered "the editor column" would slide this probe out of the
/// column with it and every frame assertion below would hold vacuously.
/// Focus is the independent witness: `PanelSet::handle_mouse` focuses the
/// panel whose *column* contains the press, and it is the column, not the
/// buffer, that this cell has to be inside for the tests to mean anything.
fn frame_corner(screen: &mut EditorScreen, tx: &AppTx) -> (u16, u16) {
let (col, row) = buffer_origin(screen);
let corner = (col - 1, row - 1);
screen.panels.focus(PanelKind::Drawer);
screen.handle_input(&press_at(corner.0, corner.1), tx);
assert_eq!(
screen.panels.focused(),
PanelKind::Editor,
"precondition: the frame is inside the editor column"
);
// That probe was a real press. Drop it so the run starts clean.
screen.clicks.end();
corner
}
fn press_at(col: u16, row: u16) -> InputEvent {
use ratatui::crossterm::event::{KeyModifiers, MouseButton, MouseEvent, MouseEventKind};
InputEvent::Mouse(MouseEvent {
kind: MouseEventKind::Down(MouseButton::Left),
column: col,
row,
modifiers: KeyModifiers::NONE,
})
}
fn moved_at(col: u16, row: u16) -> InputEvent {
use ratatui::crossterm::event::{KeyModifiers, MouseEvent, MouseEventKind};
InputEvent::Mouse(MouseEvent {
kind: MouseEventKind::Moved,
column: col,
row,
modifiers: KeyModifiers::NONE,
})
}
/// A fixed origin, so the tests describe gaps rather than wall-clock time.
fn at(millis: u64) -> std::time::Instant {
static ORIGIN: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new();
*ORIGIN.get_or_init(std::time::Instant::now) + std::time::Duration::from_millis(millis)
}
#[tokio::test]
async fn two_presses_on_the_buffer_are_a_double_click() {
let (mut screen, _, _, _dir) = test_screen().await;
lay_out(&mut screen);
let (col, row) = buffer_origin(&screen);
assert!(!screen.track_click(&press_at(col, row), at(0)));
assert!(screen.track_click(&press_at(col, row), at(120)));
}
/// The gate is not the editor *column*: `PanelSet::render` frames the
/// component, and a press on that frame never reaches the component's
/// `handle_mouse`, so the cursor stays where it was. Counting those cells
/// let two clicks on the `─ Editor` title bar follow whichever link the
/// cursor was parked on — a note the user never pointed at.
#[tokio::test]
async fn a_press_on_the_editor_frame_is_never_half_of_a_double() {
let (mut screen, _, _, _dir) = test_screen().await;
let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
lay_out(&mut screen);
let (col, row) = frame_corner(&mut screen, &tx);
assert!(!screen.track_click(&press_at(col, row), at(0)));
assert!(
!screen.track_click(&press_at(col, row), at(120)),
"two clicks on the frame are not a follow"
);
}
/// A frame press does not merely fail to pair — it ends the run, so it
/// cannot sit unnoticed between two buffer presses and let them pair
/// across it.
#[tokio::test]
async fn a_frame_press_separates_two_buffer_presses() {
let (mut screen, _, _, _dir) = test_screen().await;
let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
lay_out(&mut screen);
let (frame_col, frame_row) = frame_corner(&mut screen, &tx);
let (col, row) = buffer_origin(&screen);
screen.track_click(&press_at(col, row), at(0));
screen.track_click(&press_at(frame_col, frame_row), at(40));
assert!(!screen.track_click(&press_at(col, row), at(80)));
}
/// Only a press consults the hit-test. Any-event tracking delivers a
/// `Moved` per cell of travel, including over the frame, and the pointer
/// crossing the border mid-gesture is not the user doing anything.
#[tokio::test]
async fn motion_over_the_frame_does_not_break_a_double() {
let (mut screen, _, _, _dir) = test_screen().await;
let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
lay_out(&mut screen);
let (frame_col, frame_row) = frame_corner(&mut screen, &tx);
let (col, row) = buffer_origin(&screen);
screen.track_click(&press_at(col, row), at(0));
assert!(!screen.track_click(&moved_at(frame_col, frame_row), at(40)));
assert!(screen.track_click(&press_at(col, row), at(120)));
}
#[tokio::test]
async fn a_key_between_presses_ends_the_click_run() {
let (mut screen, _, _, _dir) = test_screen().await;
lay_out(&mut screen);
let (col, row) = buffer_origin(&screen);
screen.track_click(&press_at(col, row), at(0));
assert!(!screen.track_click(&chr('x'), at(40)));
assert!(!screen.track_click(&press_at(col, row), at(80)));
}
/// An overlay ends the run rather than merely failing to extend it. A modal
/// is drawn over the editor column and a `SearchList` activates a row on a
/// click-click of its own; without ending it, those presses stay in the run
/// and pair with the first one that lands after the overlay closes.
#[tokio::test]
async fn an_overlay_ends_the_click_run() {
let (mut screen, _, _, _dir) = test_screen().await;
lay_out(&mut screen);
let (col, row) = buffer_origin(&screen);
let vault = screen.vault.clone();
screen.track_click(&press_at(col, row), at(0));
screen.present_overlay(Box::new(ActiveDialog::create_note(
VaultPath::note_path_from("x"),
vault,
None,
)));
assert!(
!screen.track_click(&press_at(col, row), at(40)),
"a press under an overlay is the overlay's"
);
screen.dismiss_overlay();
assert!(
!screen.track_click(&press_at(col, row), at(80)),
"and neither press survives to pair with the next one"
);
}
/// End to end: the second press of a pair over a wikilink emits the same
/// `FollowLink` the bound shortcut does. The first press is what placed the
/// cursor the second one asks about, which is why one path serves both.
#[tokio::test]
async fn a_double_click_on_a_wikilink_follows_it() {
let (mut screen, _, _, _dir) = test_screen().await;
let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
screen
.panels
.editor_mut()
.unwrap()
.set_text("[[target note]]".to_string());
lay_out(&mut screen);
// Mid-link, so the exact gutter width the editor renders cannot move
// the press off the span.
let (col, row) = buffer_origin(&screen);
let (col, row) = (col + 6, row);
screen.handle_input(&press_at(col, row), &tx);
screen.handle_input(&press_at(col, row), &tx);
let followed = std::iter::from_fn(|| rx.try_recv().ok())
.find_map(|ev| match ev {
AppEvent::FollowLink(target) => Some(target),
_ => None,
})
.expect("the double-click emitted no FollowLink");
assert_eq!(followed, "target note");
}
/// The first press only places the cursor. Following on a single click is
/// the behaviour this replaced: a stray click while reading would navigate.
#[tokio::test]
async fn a_single_press_on_a_wikilink_only_places_the_cursor() {
let (mut screen, _, _, _dir) = test_screen().await;
let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
screen
.panels
.editor_mut()
.unwrap()
.set_text("[[target note]]".to_string());
lay_out(&mut screen);
let (col, row) = buffer_origin(&screen);
screen.handle_input(&press_at(col + 6, row), &tx);
assert!(
!std::iter::from_fn(|| rx.try_recv().ok())
.any(|ev| matches!(ev, AppEvent::FollowLink(_))),
"one click is a cursor placement, not a navigation"
);
assert!(
screen
.panels
.editor()
.unwrap()
.follow_target_at_cursor()
.is_some(),
"but it did land on the link, so the next press has something to follow"
);
}
}
#[cfg(test)]
mod sort_routing_tests {
use super::*;
use crate::app_screen::AppScreen;
use crate::components::events::SortTarget;
use crate::components::file_list::{SortField, SortOrder};
async fn make_editor() -> (
EditorScreen,
AppTx,
tokio::sync::mpsc::UnboundedReceiver<AppEvent>,
) {
let vault = crate::test_support::temp_vault("editor-sort").await;
vault.validate_and_init().await.unwrap();
let settings = std::sync::Arc::new(std::sync::RwLock::new(
crate::settings::AppSettings::default(),
));
let screen = EditorScreen::new(vault, VaultPath::root(), settings);
let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
(screen, tx, rx)
}
#[tokio::test(flavor = "multi_thread")]
async fn sort_save_default_persists_to_settings() {
let (mut screen, tx, _rx) = make_editor().await;
screen
.handle_app_message(
AppEvent::SortChanged {
target: SortTarget::Sidebar,
field: SortField::Title,
order: SortOrder::Descending,
group_directories: true,
persist: true,
},
&tx,
)
.await;
let s = screen.settings.read().unwrap();
assert_eq!(
s.default_sort_field,
crate::settings::SortFieldSetting::Title
);
assert_eq!(
s.default_sort_order,
crate::settings::SortOrderSetting::Descending
);
assert!(s.group_directories);
}
#[tokio::test(flavor = "multi_thread")]
async fn sort_save_default_journal_dir_writes_journal_settings() {
let (mut screen, tx, _rx) = make_editor().await;
// Point the sidebar at the journal directory (current_dir set synchronously).
let journal = screen.vault.journal_path().clone();
screen.panels.sidebar_mut().navigate(journal, &tx);
screen
.handle_app_message(
AppEvent::SortChanged {
target: SortTarget::Sidebar,
field: SortField::Title,
order: SortOrder::Ascending,
group_directories: false,
persist: true,
},
&tx,
)
.await;
let s = screen.settings.read().unwrap();
assert_eq!(
s.journal_sort_field,
crate::settings::SortFieldSetting::Title
);
assert_eq!(
s.journal_sort_order,
crate::settings::SortOrderSetting::Ascending
);
// Default (non-journal) settings must be untouched from their defaults.
assert_eq!(
s.default_sort_field,
crate::settings::SortFieldSetting::Name
);
}
/// A non-persisting SortChanged (a plain dialog toggle) applies live but
/// must NOT write settings.
#[tokio::test(flavor = "multi_thread")]
async fn sort_changed_without_persist_leaves_settings() {
let (mut screen, tx, _rx) = make_editor().await;
screen
.handle_app_message(
AppEvent::SortChanged {
target: SortTarget::Sidebar,
field: SortField::Title,
order: SortOrder::Descending,
group_directories: true,
persist: false,
},
&tx,
)
.await;
let s = screen.settings.read().unwrap();
assert_eq!(
s.default_sort_field,
crate::settings::SortFieldSetting::Name
);
assert_eq!(
s.default_sort_order,
crate::settings::SortOrderSetting::Ascending
);
assert!(!s.group_directories);
}
}