zdbview 0.11.1

Terminal inspector and CRUD editor for rkyv archives and SQLite databases
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
//! The interactive terminal application: state, key handling, and rendering.

use anyhow::Result;
use crossterm::event::{
    self, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers, MouseButton, MouseEvent,
    MouseEventKind,
};
use ratatui::layout::{Constraint, Layout, Rect};
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{
    Block, Borders, Cell, Clear, List, ListItem, ListState, Paragraph, Row, Table, TableState,
};
use ratatui::{DefaultTerminal, Frame};

use std::collections::HashSet;
use std::path::{Path, PathBuf};

use crate::formats::{self, Decoded, FormatKind};
use crate::hexedit::{self, HexEdit};
use crate::mru::{self, Entry};
use crate::overlay::{HelpCtx, Overlays};
use crate::rkyv_inspect::RkyvStore;
use crate::sqlite::{RowsView, Sort, SqliteStore};
use crate::store::{Kind, Store};
use crate::theme::{Theme, ThemeName};

/// How many rows per SQLite page.
const PAGE: i64 = 500;
/// How long a page fetch may hold the render thread before it is left to finish
/// in the background. Long enough that a page which is already fast arrives
/// before the frame is drawn, short enough to be under one frame either way.
const PAGE_GRACE: std::time::Duration = std::time::Duration::from_millis(30);
/// Minimum length for an extracted rkyv string run.
const MIN_STRING: usize = 4;
/// How many values a column's frequency table shows.
const FREQUENCY_ROWS: i64 = 20;
/// Idle wake-up interval: how often the loop redraws with no input pending, so a
/// toast dismisses itself on time (iftoprs's `event::poll` tick).
const TICK: std::time::Duration = std::time::Duration::from_millis(250);

/// What `.help` prints in the SQL editor. Every line here is a command `run_dot`
/// implements; the completion list in [`crate::sqledit::DOT_COMMANDS`] is the same
/// set.
const DOT_HELP: &str = "\
.tables                 list the tables
.schema [TABLE]         CREATE statements
.indexes [TABLE]        indexes on a table, with their columns
.dump [TABLE]           schema and data as replayable SQL
.databases              attached databases
.attach FILE ALIAS      attach another database
.detach ALIAS           detach it again
.mode MODE              list csv tsv markdown line insert json
.headers on|off         column names in redirected output
.output FILE            send results to a file
.once FILE              send the next result to a file
.timer on|off           report how long a statement took
.eqp on|off             print the query plan before each statement
.import FILE TABLE      load a CSV or TSV
.read FILE              run the statements in a file
.backup FILE            copy the database with VACUUM INTO
.expert                 index advice for the statement just run
.recover [FILE]         salvage rows page by page into a script
.vacuum .analyze .reindex   maintenance
.quit                   leave zdbview";

/// How a result set is rendered — the sqlite3 shell's `.mode`, over the writers in
/// [`crate::export`]. `List` is zdbview's own: the grid the editor draws.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum OutputMode {
    List,
    Csv,
    Tsv,
    Markdown,
    Line,
    Insert,
    Json,
}

impl OutputMode {
    fn parse(name: &str) -> Option<Self> {
        Some(match name.to_lowercase().as_str() {
            "list" | "column" | "box" | "table" => OutputMode::List,
            "csv" => OutputMode::Csv,
            "tsv" | "tabs" => OutputMode::Tsv,
            "markdown" => OutputMode::Markdown,
            "line" => OutputMode::Line,
            "insert" => OutputMode::Insert,
            "json" => OutputMode::Json,
            _ => return None,
        })
    }

    fn label(self) -> &'static str {
        match self {
            OutputMode::List => "list",
            OutputMode::Csv => "csv",
            OutputMode::Tsv => "tsv",
            OutputMode::Markdown => "markdown",
            OutputMode::Line => "line",
            OutputMode::Insert => "insert",
            OutputMode::Json => "json",
        }
    }

    /// Render a result set. `table` names the target of `insert` mode, and
    /// `literals` are the same cells as SQL literals — `insert` mode has to use
    /// those, since a display string describes a blob rather than carrying it.
    fn render(
        self,
        columns: &[String],
        rows: &[Vec<String>],
        literals: &[Vec<String>],
        table: &str,
        headers: bool,
    ) -> String {
        use crate::export::*;
        match self {
            OutputMode::Csv => {
                let out = rows_to_csv(columns, rows);
                if headers {
                    out
                } else {
                    out.split_once('\n')
                        .map(|(_, r)| r.to_string())
                        .unwrap_or(out)
                }
            }
            OutputMode::Tsv => {
                let out = rows_to_tsv(columns, rows);
                if headers {
                    out
                } else {
                    out.split_once('\n')
                        .map(|(_, r)| r.to_string())
                        .unwrap_or(out)
                }
            }
            OutputMode::Markdown => rows_to_markdown(columns, rows),
            OutputMode::Line => rows_to_lines(columns, rows),
            OutputMode::Insert => rows_to_inserts_exact(table, columns, literals),
            OutputMode::Json => rows_to_json(columns, rows),
            // The grid has no text form; a redirect falls back to CSV, which is
            // what the shell's default list mode is closest to.
            OutputMode::List => rows_to_csv(columns, rows),
        }
    }
}

/// What the hex editor has open, which decides where `^s` writes.
#[derive(Clone, PartialEq, Eq, Debug)]
enum HexTarget {
    /// A rkyv record's value, written through the archive's re-serialization.
    Record,
    /// A SQLite cell, written back as a blob parameter. Blob cells have no text
    /// form, so the line editor cannot express them. Addressed by key, so a
    /// `WITHOUT ROWID` table's cells are editable too.
    Cell {
        table: String,
        key: crate::sqlite::RowKey,
        column: String,
    },
}

/// Which pane has keyboard focus.
#[derive(PartialEq, Eq, Clone, Copy)]
enum Focus {
    Left,
    Right,
}

/// Modal input state layered over Normal browsing.
enum Mode {
    Normal,
    /// Editing a SQLite cell in place; buffer holds the pending value.
    EditCell(String),
    /// A `/` search prompt; buffer holds the pattern being typed.
    Search(String),
    /// Adding a new rkyv record; buffer holds the key being typed.
    AddRecord(String),
    /// Renaming a rkyv record's key; buffer holds the new key.
    RenameRecord(String),
    /// Confirm a destructive action (delete row).
    ConfirmDelete,
}

/// The views for a rkyv/binary file. `Records` is only available when the
/// archive was recognized and decoded to key/value.
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
enum RkyvView {
    Records,
    Info,
    Strings,
    Hex,
}

/// Where the cursor was when `/` was pressed. An incremental search always looks
/// from here, so the match moves with the pattern instead of walking forward one
/// hop per keystroke, and Esc puts things back.
#[derive(Debug, Clone, Copy)]
struct SearchOrigin {
    table_idx: usize,
    page_offset: i64,
    row_idx: usize,
    record_idx: usize,
    string_idx: usize,
    hex_row: usize,
}

/// Why the app loop ended: the user quit, or asked for the file picker again.
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum Outcome {
    Quit,
    /// `o` — back to the picker to open another file.
    Reopen,
}

/// Top-level screen. Overlaid modals (`Mode`) and the help overlay sit on top.
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
enum Screen {
    Main,
    /// Full-screen detail of one row/record with a scrollable value pane.
    Detail,
    /// Hex editor over one record's value bytes.
    HexEdit,
    /// Live write monitor over every store zdbview knows about.
    Top,
    /// The SQL editor: multi-line input, transcript, completion.
    Sql,
    /// Database facts, integrity check and foreign-key lint (`.dbinfo`, `.intck`,
    /// `.lint fkey-indexes` in the sqlite3 shell).
    DbInfo,
    /// Per-column statistics for the current table, and one column's frequency
    /// table (VisiData's `describe` and frequency sheet, sqlite-utils'
    /// `analyze-tables`).
    Stats,
    /// The write-ahead log, frame by frame, with the rows each frame wrote.
    Frames,
    /// SQLite schema (CREATE statements) view.
    Schema,
}

/// How the value pane renders raw bytes.
#[derive(PartialEq, Eq, Clone, Copy)]
enum ValueRender {
    Auto,
    Hex,
    Text,
    /// Disassemble the value as a fusevm::Chunk (requires the `disasm` feature).
    Disasm,
}

impl ValueRender {
    fn label(self) -> &'static str {
        match self {
            ValueRender::Auto => "auto",
            ValueRender::Hex => "hex",
            ValueRender::Text => "text",
            ValueRender::Disasm => "disasm",
        }
    }
    fn next(self) -> Self {
        match self {
            ValueRender::Auto => ValueRender::Hex,
            ValueRender::Hex => ValueRender::Text,
            ValueRender::Text => ValueRender::Disasm,
            ValueRender::Disasm => ValueRender::Auto,
        }
    }
}

pub struct App {
    store: Store,
    focus: Focus,
    mode: Mode,
    status: String,
    quit: bool,

    // SQLite state
    table_idx: usize,
    rows: Option<RowsView>,
    page_offset: i64,
    row_idx: usize,
    col_idx: usize,

    // rkyv state
    rkyv_view: RkyvView,
    strings: Vec<crate::rkyv_inspect::StringHit>,
    string_idx: usize,
    hex_row: usize,
    /// Decoded key/value records when the archive was recognized.
    decoded: Option<Decoded>,
    record_idx: usize,

    /// True after a lone `g`, awaiting the second `g` of a `gg` motion.
    pending_g: bool,
    /// Active search pattern (empty = no search); `n`/`N` cycle its matches.
    search: String,

    // Screens / overlays
    screen: Screen,
    value_render: ValueRender,
    /// Cached bytes shown in the Detail value pane.
    detail_value: Vec<u8>,
    detail_scroll: usize,
    schema_scroll: usize,
    /// SQLite schema objects `(type, name, sql)`, loaded lazily.
    schema: Vec<(String, String, String)>,

    // Mouse hit-testing: the on-screen rect and scroll offset of each clickable
    // list/grid, captured during render so a click maps to the right index.
    click_left: Rect,
    click_right: Rect,
    click_records: Rect,
    off_left: usize,
    off_right: usize,
    off_records: usize,
    /// Byte offset of the text cursor within the active input modal's buffer.
    input_cursor: usize,
    /// The open hex editor, while `screen` is `Screen::HexEdit`.
    hex: Option<HexEdit>,
    /// Rect the hex editor last rendered into, for click hit-testing.
    hex_area: Rect,
    /// The write monitor, while `screen` is `Screen::Top`.
    top: Option<crate::monitor::Monitor>,
    /// Rect the monitor last rendered into, for its header hit test.
    top_area: Rect,
    /// The SQL editor, while `screen` is `Screen::Sql`.
    sql: Option<crate::sqledit::SqlEdit>,
    /// The log walker, while `screen` is `Screen::Frames`.
    walk: Option<crate::frames::FrameView>,
    /// Which screen the hex editor was opened from, so closing it goes back there
    /// rather than always to the grid.
    hex_from: Screen,
    /// What the open hex editor writes back to. A rkyv record by default; a
    /// SQLite blob cell when the grid's cell could not be edited as text.
    hex_target: HexTarget,
    /// A statistics pass running on another thread, with the table it is for.
    stats_pending: Option<(String, std::sync::mpsc::Receiver<StatsResult>)>,
    /// Per-column statistics, built when the statistics screen opens.
    stats: Vec<crate::sqlite::ColumnStat>,
    stats_idx: usize,
    /// The column whose frequency table is shown, with its top values.
    stats_freq: Option<(String, Vec<(String, i64)>)>,
    /// Lines of the database-info screen, built when it opens.
    dbinfo: Vec<(String, String)>,
    /// Integrity-check and lint output, filled on demand (both can be slow).
    dbinfo_checks: Vec<String>,
    dbinfo_scroll: usize,
    /// Rect the SQL editor last rendered into, for paging.
    sql_area: Rect,
    /// How the editor renders a result set — the shell's `.mode`.
    sql_mode: OutputMode,
    /// `.output` / `.once`: where results go instead of the transcript, and
    /// whether the redirect ends after the next statement.
    sql_out: Option<(PathBuf, bool)>,
    /// `.headers off` drops the column names from redirected output.
    sql_headers: bool,
    /// `.timer off` stops reporting how long a statement took.
    sql_timer: bool,
    /// `.eqp on` prints each statement's plan before running it.
    sql_eqp: bool,
    /// Set by `o`: leave the app loop and show the file picker again.
    reopen: bool,
    /// A file the monitor asked to open, taking precedence over the picker.
    open_next: Option<PathBuf>,
    /// Position `/` started from, while a search prompt is open.
    search_origin: Option<SearchOrigin>,
    /// Active `/` filter: only matching rows/records/strings are listed. Empty
    /// when nothing is filtered.
    filter: String,
    /// The extracted string list hit its bounds, so it is not exhaustive.
    strings_truncated: bool,
    /// Bytes the string scan covered (the whole file unless it was bounded).
    strings_scanned: usize,
    /// A decode running on another thread, for an archive too big to validate
    /// while the user waits.
    decoding: Option<std::sync::mpsc::Receiver<Option<Decoded>>>,
    /// Rows of the focused scrollable region in the last frame. Paging moves by
    /// this much, so PageUp/PageDown match what is actually on screen instead of
    /// a fixed guess.
    page_rows: usize,
    /// Active row-grid ordering, or `None` for the table's natural `rowid`
    /// order. Reset when another table is selected.
    sort: Option<Sort>,

    /// Themed overlays (help / scheme chooser / palette editor / toast),
    /// shared with the recent-files picker.
    ov: Overlays,

    /// Off-thread page and count queries, for a SQLite store. `None` for rkyv,
    /// which holds its whole archive in memory and needs no query at all.
    engine: Option<crate::query::Engine>,
    /// Generation of the page request the grid is waiting for. A result tagged
    /// with anything older describes a table, filter or page that has since been
    /// replaced.
    page_generation: u64,
    /// `G` was pressed before the exact total was known, so the jump to the last
    /// page is owed as soon as the count lands.
    pending_bottom: bool,
    /// Offset of the page actually loaded, which lags `page_offset` while a fetch
    /// is in flight. Paging by cursor needs to know which page the rows on screen
    /// are.
    loaded_offset: i64,
    /// `(table, filter, rows)` from the last exact count, kept while it still
    /// describes the grid so the scan is not repeated for every page.
    exact_total: Option<(String, String, i64)>,
}

impl App {
    /// Open `store` with an already-resolved scheme. The picker hands its own
    /// scheme over this way, so opening a file cannot re-read prefs and land on a
    /// different one.
    pub fn with_theme(store: Store, theme: Theme) -> Self {
        let mut app = App {
            store,
            focus: Focus::Left,
            mode: Mode::Normal,
            status: String::new(),
            quit: false,
            table_idx: 0,
            rows: None,
            page_offset: 0,
            row_idx: 0,
            col_idx: 0,
            rkyv_view: RkyvView::Info,
            strings: Vec::new(),
            string_idx: 0,
            hex_row: 0,
            decoded: None,
            record_idx: 0,
            pending_g: false,
            search: String::new(),
            screen: Screen::Main,
            value_render: ValueRender::Auto,
            detail_value: Vec::new(),
            detail_scroll: 0,
            schema_scroll: 0,
            schema: Vec::new(),
            click_left: Rect::ZERO,
            click_right: Rect::ZERO,
            click_records: Rect::ZERO,
            off_left: 0,
            off_right: 0,
            off_records: 0,
            input_cursor: 0,
            sort: None,
            hex: None,
            hex_area: Rect::ZERO,
            top: None,
            top_area: Rect::ZERO,
            sql: None,
            walk: None,
            hex_from: Screen::Main,
            hex_target: HexTarget::Record,
            stats_pending: None,
            stats: Vec::new(),
            stats_idx: 0,
            stats_freq: None,
            dbinfo: Vec::new(),
            dbinfo_checks: Vec::new(),
            dbinfo_scroll: 0,
            sql_area: Rect::ZERO,
            sql_mode: OutputMode::List,
            sql_out: None,
            sql_headers: true,
            sql_timer: true,
            sql_eqp: false,
            reopen: false,
            open_next: None,
            search_origin: None,
            filter: String::new(),
            strings_truncated: false,
            strings_scanned: 0,
            decoding: None,
            page_rows: 10,
            ov: Overlays::new(theme),
            engine: None,
            page_generation: 0,
            pending_bottom: false,
            loaded_offset: 0,
            exact_total: None,
        };
        // The grid's queries run on their own connections, so a scan the user
        // cannot see never blocks the render thread.
        if let Store::Sqlite(s) = &app.store {
            app.engine = Some(crate::query::Engine::new(&s.path));
        }
        app.init();
        app
    }

    /// Leave the open file and ask for the picker again (`o`, or `Esc` on the
    /// first level).
    fn back_to_files(&mut self) {
        self.reopen = true;
        self.quit = true;
    }

    /// A file the write monitor asked to open next, if any.
    pub fn open_next(&mut self) -> Option<PathBuf> {
        self.open_next.take()
    }

    /// The scheme currently in use, to carry back to the picker.
    pub fn theme(&self) -> Theme {
        self.ov.theme
    }

    /// Screens that take every printable key for themselves, so the global
    /// bindings must stay out of the way: the hex editor (letters are hex digits
    /// and motions) and the SQL editor (letters are the statement).
    fn screen_owns_keys(&self) -> bool {
        matches!(self.screen, Screen::HexEdit | Screen::Sql)
    }

    /// Which key sections the help overlay lists for what is on screen.
    fn help_ctx(&self) -> HelpCtx {
        if self.screen == Screen::HexEdit {
            return HelpCtx::HexEdit;
        }
        if self.screen == Screen::Top {
            return HelpCtx::Top;
        }
        if self.screen == Screen::Sql {
            return HelpCtx::Sql;
        }
        if self.screen == Screen::DbInfo {
            return HelpCtx::DbInfo;
        }
        if self.screen == Screen::Stats {
            return HelpCtx::Stats;
        }
        if self.screen == Screen::Frames {
            return HelpCtx::Frames;
        }
        match &self.store {
            Store::Sqlite(_) => HelpCtx::Sqlite,
            Store::Rkyv(_) => HelpCtx::Rkyv,
        }
    }

    /// Report an action's result: a transient toast over the UI plus the same
    /// text in the status bar, so it stays readable after the toast fades.
    fn notify(&mut self, msg: impl Into<String>) {
        let msg = msg.into();
        self.ov.toast(msg.clone());
        self.status = msg;
    }

    fn init(&mut self) {
        match &self.store {
            Store::Sqlite(s) => {
                if !s.tables.is_empty() {
                    self.load_table();
                }
                self.status = "j/k ←/→ move · Tab focus · / filter · ^f/^b page · e edit · a add · d delete · : SQL · s sort · c scheme · o/Esc files · h help · q quit".into();
            }
            Store::Rkyv(r) => {
                let s = r.strings(MIN_STRING);
                self.strings_truncated = s.truncated;
                self.strings_scanned = s.scanned;
                self.strings = s.hits;
                // Validating a large archive is slow — 25s for a 382MB shard —
                // so it runs on a thread and the structural view opens at once.
                // The Records view appears when the decode lands.
                if r.bytes.len() > DECODE_INLINE_MAX {
                    self.decoding = Some(spawn_decode(r.bytes.clone()));
                    self.rkyv_view = RkyvView::Info;
                    self.status = format!(
                        "decoding {} in the background · 1 Info · 2 Strings · 3 Hex · o/Esc files · q quit",
                        human_size(r.bytes.len() as u64)
                    );
                    return;
                }
                self.decoded = formats::try_decode(&r.bytes);
                if let Some(d) = &self.decoded {
                    self.rkyv_view = RkyvView::Records;
                    self.status = format!(
                        "{} · {} records · Enter detail · a add e hex-edit r rename d delete · / filter · 0/1/2/3 views · c scheme · o/Esc files · h help · q quit",
                        d.format,
                        d.records.len()
                    );
                } else {
                    self.status = "1 Info · 2 Strings · 3 Hex · j/k scroll · / filter · c scheme · o/Esc files · h help · q quit  (rkyv: unrecognized)".into();
                }
            }
        }
    }

    pub fn run(&mut self, terminal: &mut DefaultTerminal) -> Result<Outcome> {
        while !self.quit {
            self.poll_decode();
            self.poll_stats();
            self.poll_query();
            if let Some(w) = self.top.as_mut() {
                w.tick();
            }
            terminal.draw(|f| self.render(f))?;
            if !event::poll(TICK)? {
                self.ov.expire_toast();
                continue;
            }
            match event::read()? {
                Event::Key(key) if key.kind == KeyEventKind::Press => self.on_key(key),
                Event::Mouse(m) => self.on_mouse(m),
                _ => {}
            }
            self.ov.expire_toast();
        }
        Ok(if self.reopen {
            Outcome::Reopen
        } else {
            Outcome::Quit
        })
    }

    // ----- key handling -----------------------------------------------------

    fn on_key(&mut self, key: KeyEvent) {
        let code = key.code;

        // An open overlay owns the key.
        if self.ov.active() {
            self.ov.on_key(code);
            return;
        }

        // Modal input first. Snapshot the buffer into a local so no borrow of
        // `self.mode` is held across the `&mut self` dispatch call.
        enum Modal {
            Edit(String),
            Search(String),
            Add(String),
            Rename(String),
            Confirm,
            None,
        }
        let modal = match &self.mode {
            Mode::EditCell(buf) => Modal::Edit(buf.clone()),
            Mode::Search(buf) => Modal::Search(buf.clone()),
            Mode::AddRecord(buf) => Modal::Add(buf.clone()),
            Mode::RenameRecord(buf) => Modal::Rename(buf.clone()),
            Mode::ConfirmDelete => Modal::Confirm,
            Mode::Normal => Modal::None,
        };
        match modal {
            Modal::Edit(buf) => {
                return self.key_input(key, buf, Mode::EditCell, App::commit_edit_cell)
            }
            Modal::Search(buf) => {
                // The arrows (and paging) move through the filtered list while the
                // prompt stays open — the pattern only takes Left/Right for its
                // own cursor.
                match code {
                    KeyCode::Up => {
                        self.move_selection(-1);
                        return;
                    }
                    KeyCode::Down => {
                        self.move_selection(1);
                        return;
                    }
                    KeyCode::PageUp => {
                        let step = self.page_step() as isize;
                        self.move_selection(-step);
                        return;
                    }
                    KeyCode::PageDown => {
                        let step = self.page_step() as isize;
                        self.move_selection(step);
                        return;
                    }
                    _ => {}
                }
                return self.key_input(key, buf, Mode::Search, App::commit_search);
            }
            Modal::Add(buf) => {
                return self.key_input(key, buf, Mode::AddRecord, App::commit_add_record)
            }
            Modal::Rename(buf) => {
                return self.key_input(key, buf, Mode::RenameRecord, App::commit_rename_record)
            }
            Modal::Confirm => return self.key_confirm_delete(code),
            Modal::None => {}
        }

        // The overlay openers (`h`/`?` help, `c` chooser, `C` editor) work from
        // every screen, exactly as on the recent-files picker — except on the
        // screens that own their keys: the hex editor's motions and the SQL
        // editor's text.
        if !self.screen_owns_keys() && self.ov.on_key(code) {
            return;
        }

        // `w` opens the write monitor from any screen that does not own its keys,
        // and not from the monitor itself, where it closes.
        if code == KeyCode::Char('w') && !self.screen_owns_keys() && self.screen != Screen::Top {
            self.open_top();
            return;
        }

        // `o` goes back to the file picker from any screen but the hex editor,
        // where it inserts a byte.
        if code == KeyCode::Char('o') && !self.screen_owns_keys() {
            self.back_to_files();
            return;
        }

        match self.screen {
            // The hex editor is modal: it owns every key, including `h` and `c`,
            // because those are its own motions and data.
            Screen::HexEdit => return self.key_hex(key),
            Screen::Top => return self.key_top(code),
            Screen::Sql => return self.key_sql(key),
            Screen::DbInfo => return self.key_dbinfo(code),
            Screen::Stats => return self.key_stats(code),
            Screen::Frames => return self.key_frames(code),
            Screen::Detail => return self.key_detail(code),
            Screen::Schema => return self.key_schema(code),
            Screen::Main => {}
        }

        match &self.store {
            Store::Sqlite(_) => self.key_sqlite(key),
            Store::Rkyv(_) => self.key_rkyv(key),
        }
    }

    // ----- mouse (ported from iftoprs `handle_mouse`) -----------------------

    fn on_mouse(&mut self, m: MouseEvent) {
        // An open overlay owns the event (wheel drives it, a click confirms).
        if self.ov.on_mouse(m) {
            return;
        }
        // The write monitor takes the wheel and clicks (its header sorts).
        if self.screen == Screen::Top {
            let area = self.top_area;
            if let Some(mon) = self.top.as_mut() {
                mon.on_mouse(m, area);
                if let Some(note) = mon.note.take() {
                    self.notify(note);
                }
            }
            return;
        }
        // In the hex editor the wheel scrolls the dump and a click places the
        // cursor on the byte under it.
        if self.screen == Screen::HexEdit {
            let area = self.hex_area;
            if let Some(ed) = self.hex.as_mut() {
                ed.on_mouse(m, area);
            }
            return;
        }
        // Scroll wheel reuses the existing up/down navigation for the active
        // screen/view (rows, records, hex, strings, detail, schema).
        match m.kind {
            MouseEventKind::ScrollDown => self.scroll_select(true),
            MouseEventKind::ScrollUp => self.scroll_select(false),
            MouseEventKind::Down(MouseButton::Left) => self.click_at(m.column, m.row, false),
            MouseEventKind::Down(MouseButton::Right) => self.click_at(m.column, m.row, true),
            _ => {}
        }
    }

    fn scroll_select(&mut self, down: bool) {
        if !matches!(self.mode, Mode::Normal) {
            return;
        }
        let code = if down { KeyCode::Down } else { KeyCode::Up };
        self.on_key(KeyEvent::new(code, KeyModifiers::empty()));
    }

    /// Left/right click at `(col,row)`: select the item under the cursor. Right
    /// click additionally opens the detail screen for it (like iftoprs's
    /// right-click-shows-details). The clickable rects and their scroll offsets
    /// are captured during render, so the mapping is correct even when scrolled.
    fn click_at(&mut self, col: u16, row: u16, right: bool) {
        if !matches!(self.mode, Mode::Normal) || self.screen != Screen::Main {
            return;
        }
        match &self.store {
            Store::Sqlite(_) => {
                if hit(self.click_left, col, row) {
                    self.focus = Focus::Left;
                    let idx = self.off_left + row.saturating_sub(self.click_left.y + 1) as usize;
                    self.select_table(idx);
                } else if hit(self.click_right, col, row) {
                    self.focus = Focus::Right;
                    // +2 for the top border and the header row.
                    let idx = self.off_right + row.saturating_sub(self.click_right.y + 2) as usize;
                    let n = self.rows.as_ref().map(|r| r.rows.len()).unwrap_or(0);
                    if idx < n {
                        self.row_idx = idx;
                        if right {
                            self.enter_detail();
                        }
                    }
                }
            }
            Store::Rkyv(_) => {
                if self.rkyv_view == RkyvView::Records && hit(self.click_records, col, row) {
                    let idx =
                        self.off_records + row.saturating_sub(self.click_records.y + 1) as usize;
                    let n = self.decoded.as_ref().map(|d| d.records.len()).unwrap_or(0);
                    if idx < n {
                        self.record_idx = idx;
                        if right {
                            self.enter_detail();
                        }
                    }
                }
            }
        }
    }

    // ----- Detail / Schema / export / clipboard screens ---------------------

    fn key_detail(&mut self, code: KeyCode) {
        let max_scroll = self.detail_value.len() / 16;
        match code {
            KeyCode::Char('q') => self.quit = true,
            KeyCode::Esc | KeyCode::Enter => {
                self.screen = Screen::Main;
                self.detail_scroll = 0;
            }
            KeyCode::Char('v') => self.value_render = self.value_render.next(),
            KeyCode::Char('y') => self.copy_detail_value(),
            // The detail screen shows the whole value, which is where you want to
            // change it — `e` edits the highlighted field without going back, and
            // the arrows pick which field that is.
            KeyCode::Char('e') => self.edit_current_value(),
            KeyCode::Char('E') => self.edit_cell_as_bytes(),
            KeyCode::Right => {
                let n = self
                    .rows
                    .as_ref()
                    .map(|r| r.columns.len())
                    .unwrap_or(0)
                    .saturating_sub(1);
                if self.col_idx < n {
                    self.col_idx += 1;
                    self.detail_scroll = 0;
                    self.load_detail_value(false);
                }
            }
            KeyCode::Left => {
                if self.col_idx > 0 {
                    self.col_idx -= 1;
                    self.detail_scroll = 0;
                    self.load_detail_value(false);
                }
            }
            KeyCode::Down | KeyCode::Char('j') => {
                if self.detail_scroll < max_scroll {
                    self.detail_scroll += 1;
                }
            }
            KeyCode::Up | KeyCode::Char('k') => {
                self.detail_scroll = self.detail_scroll.saturating_sub(1)
            }
            KeyCode::Char('g') => self.detail_scroll = 0,
            KeyCode::Char('G') => self.detail_scroll = max_scroll,
            KeyCode::PageDown => {
                self.detail_scroll = (self.detail_scroll + self.page_step()).min(max_scroll)
            }
            KeyCode::PageUp => {
                self.detail_scroll = self.detail_scroll.saturating_sub(self.page_step())
            }
            _ => {}
        }
    }

    fn key_schema(&mut self, code: KeyCode) {
        match code {
            KeyCode::Char('q') => self.quit = true,
            KeyCode::Esc | KeyCode::Char('S') => {
                self.screen = Screen::Main;
                self.schema_scroll = 0;
            }
            KeyCode::Down | KeyCode::Char('j') => self.schema_scroll += 1,
            KeyCode::Up | KeyCode::Char('k') => {
                self.schema_scroll = self.schema_scroll.saturating_sub(1)
            }
            KeyCode::Char('g') => self.schema_scroll = 0,
            KeyCode::PageDown => self.schema_scroll += self.page_step(),
            KeyCode::PageUp => {
                self.schema_scroll = self.schema_scroll.saturating_sub(self.page_step())
            }
            _ => {}
        }
    }

    /// Enter the detail screen for the current SQLite row or rkyv record.
    fn enter_detail(&mut self) {
        self.detail_scroll = 0;
        self.load_detail_value(true);
    }

    /// Read the selected cell / record value into `detail_value`. `enter` also
    /// switches to the screen; a reload after an edit leaves the screen alone.
    fn load_detail_value(&mut self, enter: bool) {
        match &self.store {
            Store::Sqlite(_) => {
                let bytes = match (self.current_table(), self.current_rowid()) {
                    (Some(t), Some(rid)) => {
                        let col = self
                            .rows
                            .as_ref()
                            .and_then(|r| r.columns.get(self.col_idx).cloned())
                            .unwrap_or_default();
                        self.sqlite()
                            .and_then(|s| {
                                s.cell_bytes_keyed(&t, &crate::sqlite::RowKey::Rowid(rid), &col)
                                    .ok()
                            })
                            .unwrap_or_default()
                    }
                    _ => self
                        .rows
                        .as_ref()
                        .and_then(|r| r.rows.get(self.row_idx))
                        .and_then(|row| row.get(self.col_idx))
                        .map(|s| s.clone().into_bytes())
                        .unwrap_or_default(),
                };
                self.detail_value = bytes;
                if enter {
                    self.screen = Screen::Detail;
                }
            }
            Store::Rkyv(_) => {
                if let Some(rec) = self
                    .decoded
                    .as_ref()
                    .and_then(|d| d.records.get(self.record_idx))
                {
                    self.detail_value = rec.value.clone();
                    if enter {
                        self.screen = Screen::Detail;
                    }
                }
            }
        }
    }

    fn open_schema(&mut self) {
        if let Some(s) = self.sqlite() {
            self.schema = s.schema().unwrap_or_default();
            self.schema_scroll = 0;
            self.screen = Screen::Schema;
        }
    }

    fn copy_detail_value(&mut self) {
        let text = match self.value_render {
            ValueRender::Text | ValueRender::Auto if looks_textual(&self.detail_value) => {
                String::from_utf8_lossy(&self.detail_value).into_owned()
            }
            _ => hex_string(&self.detail_value),
        };
        let ok = crate::clipboard::copy(&text);
        self.notify(if ok {
            format!("copied {} bytes to clipboard", self.detail_value.len())
        } else {
            "clipboard unavailable (no tty)".into()
        });
    }

    /// Export the current view to a file in the working directory.
    fn export_current(&mut self) {
        match &self.store {
            Store::Sqlite(_) => self.export_sqlite(),
            Store::Rkyv(_) => self.export_rkyv(),
        }
    }

    fn export_sqlite(&mut self) {
        let table = match self.current_table() {
            Some(t) => t,
            None => return,
        };
        // Whatever the grid is showing, in the order and under the filter it is
        // showing it: the counted total when there is one, else the page's bound.
        let total = self
            .known_total()
            .or_else(|| self.rows.as_ref().map(|r| r.total))
            .unwrap_or(0);
        let view = match self.sqlite().unwrap().rows(&crate::sqlite::PageQuery {
            table: &table,
            limit: total.max(1),
            offset: 0,
            sort: self.sort.as_ref(),
            filter: &self.filter,
            hint: None,
            known_total: None,
        }) {
            Ok(v) => v,
            Err(e) => {
                self.notify(format!("export failed: {}", e));
                return;
            }
        };
        let csv = crate::export::rows_to_csv(&view.columns, &view.rows);
        let path = format!("{}.csv", sanitize(&table));
        match std::fs::write(&path, csv) {
            Ok(()) => self.status = format!("exported {} rows → {}", view.rows.len(), path),
            Err(e) => self.status = format!("write failed: {}", e),
        }
    }

    fn export_rkyv(&mut self) {
        let d = match &self.decoded {
            Some(d) => d,
            None => {
                self.notify("nothing to export (unrecognized archive)");
                return;
            }
        };
        let recs: Vec<crate::export::RecordExport> = d
            .records
            .iter()
            .map(|r| crate::export::RecordExport {
                key: &r.key,
                fields: &r.fields,
                value: &r.value,
            })
            .collect();
        let json = crate::export::records_to_json(&recs);
        let base = match &self.store {
            Store::Rkyv(r) => r
                .path
                .file_stem()
                .and_then(|s| s.to_str())
                .unwrap_or("records")
                .to_string(),
            _ => "records".into(),
        };
        let path = format!("{}.records.json", sanitize(&base));
        match std::fs::write(&path, json) {
            Ok(()) => self.status = format!("exported {} records → {}", d.records.len(), path),
            Err(e) => self.status = format!("write failed: {}", e),
        }
    }

    fn key_sqlite(&mut self, key: KeyEvent) {
        let code = key.code;
        let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);

        // Ctrl-f / Ctrl-b page forward / back (vim page motions).
        if ctrl {
            match code {
                KeyCode::Char('f') => self.page_sqlite(true),
                KeyCode::Char('b') => self.page_sqlite(false),
                _ => {}
            }
            return;
        }

        // `gg` motion: a lone `g` arms, the next `g` fires. Any other key
        // disarms.
        if code == KeyCode::Char('g') {
            if self.pending_g {
                self.pending_g = false;
                self.goto_top();
            } else {
                self.pending_g = true;
            }
            return;
        }
        self.pending_g = false;

        match code {
            KeyCode::Char('G') => self.goto_bottom(),
            KeyCode::Char('/') => self.open_modal(Mode::Search(String::new())),
            KeyCode::Char('n') => self.search_next(true),
            KeyCode::Char('N') => self.search_next(false),
            KeyCode::Char('q') => self.quit = true,
            // First level: Esc backs out to the file list, as it does from any
            // nested screen; `q` is the one that quits.
            KeyCode::Esc => self.back_to_files(),
            KeyCode::Tab => {
                self.focus = if self.focus == Focus::Left {
                    Focus::Right
                } else {
                    Focus::Left
                };
            }
            KeyCode::Up | KeyCode::Char('k') => match self.focus {
                Focus::Left => {
                    let visible = self.visible_tables();
                    if let Some(i) = Self::step_visible(&visible, self.table_idx, -1) {
                        self.select_table(i);
                    }
                }
                Focus::Right => self.row_idx = self.row_idx.saturating_sub(1),
            },
            KeyCode::Down | KeyCode::Char('j') => match self.focus {
                Focus::Left => {
                    let visible = self.visible_tables();
                    if let Some(i) = Self::step_visible(&visible, self.table_idx, 1) {
                        self.select_table(i);
                    }
                }
                Focus::Right => {
                    if let Some(r) = &self.rows {
                        if self.row_idx + 1 < r.rows.len() {
                            self.row_idx += 1;
                        }
                    }
                }
            },
            // Columns move with the arrows only: `h` is the help overlay (as in
            // iftoprs) and `l` is left free so the pair stays consistent.
            KeyCode::Left => {
                if self.focus == Focus::Right {
                    self.col_idx = self.col_idx.saturating_sub(1);
                }
            }
            KeyCode::Right => {
                if self.focus == Focus::Right {
                    if let Some(r) = &self.rows {
                        if self.col_idx + 1 < r.columns.len() {
                            self.col_idx += 1;
                        }
                    }
                }
            }
            KeyCode::Enter => match self.focus {
                Focus::Left => self.focus = Focus::Right,
                Focus::Right => self.enter_detail(),
            },
            KeyCode::PageDown => self.page_sqlite(true),
            KeyCode::PageUp => self.page_sqlite(false),
            KeyCode::Char('e') => self.begin_edit_cell(),
            // `E` edits any cell as bytes, which is the only way to put binary
            // into one that does not already hold a blob.
            KeyCode::Char('E') => self.edit_cell_as_bytes(),
            KeyCode::Char('a') => self.insert_row(),
            KeyCode::Char('d') => {
                if self.focus == Focus::Right && self.current_rowid().is_some() {
                    self.mode = Mode::ConfirmDelete;
                }
            }
            KeyCode::Char('S') => self.open_schema(),
            // `D` for the database's own facts, the shell's `.dbinfo`.
            KeyCode::Char('D') => self.open_dbinfo(),
            // `A` analyzes the table's columns, `Y` copies the row as an INSERT.
            KeyCode::Char('A') => self.open_stats(),
            KeyCode::Char('Y') => self.copy_row_as_insert(),
            // `F` follows the foreign key under the cursor to the row it points
            // at, which is the one navigation a schema gives you for free.
            KeyCode::Char('F') => self.follow_foreign_key(),
            // Sorting: `s` toggles the cursor column (asc → desc → off), and
            // `<`/`>` walk the sort across columns keeping the direction.
            KeyCode::Char('s') => self.sort_by_current_column(),
            KeyCode::Char('<') => self.sort_shift_column(false),
            KeyCode::Char('>') => self.sort_shift_column(true),
            KeyCode::Char('x') => self.export_current(),
            KeyCode::Char('y') => self.copy_sqlite_cell(),
            // `:` opens the SQL editor (multi-line, completion, transcript).
            KeyCode::Char(':') => self.open_sql(),
            _ => {}
        }
    }

    fn copy_rkyv_key(&mut self) {
        let key = self
            .decoded
            .as_ref()
            .and_then(|d| d.records.get(self.record_idx))
            .map(|r| r.key.clone());
        if let Some(k) = key {
            let ok = crate::clipboard::copy(&k);
            self.status = if ok {
                "copied key to clipboard".into()
            } else {
                "clipboard unavailable (no tty)".into()
            };
        }
    }

    fn copy_sqlite_cell(&mut self) {
        let cell = self
            .rows
            .as_ref()
            .and_then(|r| r.rows.get(self.row_idx))
            .and_then(|row| row.get(self.col_idx))
            .cloned()
            .unwrap_or_default();
        let ok = crate::clipboard::copy(&cell);
        self.notify(if ok {
            "copied cell to clipboard"
        } else {
            "clipboard unavailable (no tty)"
        });
    }

    fn key_rkyv(&mut self, key: KeyEvent) {
        let code = key.code;
        if code == KeyCode::Char('g') {
            if self.pending_g {
                self.pending_g = false;
                self.rkyv_goto_top();
            } else {
                self.pending_g = true;
            }
            return;
        }
        self.pending_g = false;

        match code {
            KeyCode::Char('G') => self.rkyv_goto_bottom(),
            KeyCode::Char('/') => self.open_modal(Mode::Search(String::new())),
            KeyCode::Char('n') => self.search_next(true),
            KeyCode::Char('N') => self.search_next(false),
            KeyCode::Char('q') => self.quit = true,
            // First level: Esc backs out to the file list, as it does from any
            // nested screen; `q` is the one that quits.
            KeyCode::Esc => self.back_to_files(),
            KeyCode::Char('0') => {
                if self.decoded.is_some() {
                    self.rkyv_view = RkyvView::Records;
                } else if self.decoding.is_some() {
                    self.notify("still decoding — Records will open when it lands");
                }
            }
            KeyCode::Char('1') => self.rkyv_view = RkyvView::Info,
            KeyCode::Char('2') => self.rkyv_view = RkyvView::Strings,
            KeyCode::Char('3') => self.rkyv_view = RkyvView::Hex,
            KeyCode::Up | KeyCode::Char('k') => self.move_rkyv(-1),
            KeyCode::Down | KeyCode::Char('j') => self.move_rkyv(1),
            KeyCode::PageDown => self.page_rkyv(true),
            KeyCode::PageUp => self.page_rkyv(false),
            KeyCode::Enter => {
                if self.rkyv_view == RkyvView::Records {
                    self.enter_detail();
                }
            }
            KeyCode::Char('d') => {
                if self.rkyv_view == RkyvView::Records && self.has_current_record() {
                    self.mode = Mode::ConfirmDelete;
                }
            }
            KeyCode::Char('a') => {
                if self.rkyv_view == RkyvView::Records && self.decoded.is_some() {
                    self.open_modal(Mode::AddRecord(String::new()));
                }
            }
            KeyCode::Char('e') => {
                if self.rkyv_view == RkyvView::Records && self.has_current_record() {
                    self.open_hex_editor();
                }
            }
            KeyCode::Char('r') => {
                let renamable = matches!(
                    self.decoded.as_ref().map(|d| d.kind),
                    Some(
                        FormatKind::Script
                            | FormatKind::Stryke
                            | FormatKind::Autoload
                            | FormatKind::Elisp
                    )
                );
                if self.rkyv_view == RkyvView::Records && self.has_current_record() && renamable {
                    let key = self
                        .decoded
                        .as_ref()
                        .and_then(|d| d.records.get(self.record_idx))
                        .map(|r| r.key.clone())
                        .unwrap_or_default();
                    self.open_modal(Mode::RenameRecord(key));
                }
            }
            KeyCode::Char('x') => self.export_current(),
            KeyCode::Char('y') => self.copy_rkyv_key(),
            _ => {}
        }
    }

    /// Cursor-aware text-input handler shared by every input modal. The cursor
    /// model (UTF-8-safe left/right/word-nav/home/end/kill) is ported from
    /// iftoprs's `FilterState`. `mk` rebuilds the mode from the edited buffer,
    /// `commit` runs on Enter.
    fn key_input(
        &mut self,
        key: KeyEvent,
        mut buf: String,
        mk: fn(String) -> Mode,
        commit: fn(&mut App, &str),
    ) {
        let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
        let mut cur = self.input_cursor.min(buf.len());
        match key.code {
            KeyCode::Esc => {
                self.mode = Mode::Normal;
                // A cancelled `/` drops the filter and puts the cursor back.
                if let Some(o) = self.search_origin.take() {
                    self.set_filter(String::new());
                    self.restore_position(o);
                    self.status.clear();
                }
                return;
            }
            KeyCode::Enter => {
                self.mode = Mode::Normal;
                // Enter keeps the filter the typing already applied.
                if self.search_origin.take().is_some() {
                    return;
                }
                commit(self, &buf);
                return;
            }
            KeyCode::Left => cur = input_left(&buf, cur),
            KeyCode::Right => cur = input_right(&buf, cur),
            KeyCode::Home => cur = 0,
            KeyCode::End => cur = buf.len(),
            KeyCode::Char('a') if ctrl => cur = 0,
            KeyCode::Char('e') if ctrl => cur = buf.len(),
            KeyCode::Char('b') if ctrl => cur = input_left(&buf, cur),
            KeyCode::Char('f') if ctrl => cur = input_right(&buf, cur),
            KeyCode::Char('w') if ctrl => cur = input_delete_word(&mut buf, cur),
            KeyCode::Char('u') if ctrl => {
                buf.drain(..cur);
                cur = 0;
            }
            KeyCode::Char('k') if ctrl => buf.truncate(cur),
            KeyCode::Backspace => {
                if cur > 0 {
                    let p = input_left(&buf, cur);
                    buf.drain(p..cur);
                    cur = p;
                }
            }
            KeyCode::Delete => {
                if cur < buf.len() {
                    let n = input_right(&buf, cur);
                    buf.drain(cur..n);
                }
            }
            KeyCode::Char(c) => {
                buf.insert(cur, c);
                cur += c.len_utf8();
            }
            _ => {}
        }
        self.input_cursor = cur;
        self.mode = mk(buf);
        // A `/` prompt filters the list as it is typed.
        if let Mode::Search(pattern) = &self.mode {
            let pattern = pattern.clone();
            self.filter_preview(&pattern);
        }
    }

    fn snapshot_position(&self) -> SearchOrigin {
        SearchOrigin {
            table_idx: self.table_idx,
            page_offset: self.page_offset,
            row_idx: self.row_idx,
            record_idx: self.record_idx,
            string_idx: self.string_idx,
            hex_row: self.hex_row,
        }
    }

    fn restore_position(&mut self, o: SearchOrigin) {
        self.table_idx = o.table_idx;
        self.record_idx = o.record_idx;
        self.string_idx = o.string_idx;
        self.hex_row = o.hex_row;
        self.row_idx = o.row_idx;
        // Only reload when the page actually moved: a query per keystroke would
        // make typing feel heavy on a large table.
        if self.page_offset != o.page_offset {
            self.page_offset = o.page_offset;
            self.load_table();
            self.row_idx = o.row_idx;
        }
    }

    /// Apply `pattern` as the list filter, on every keystroke. Only matching
    /// rows/records/strings stay listed — the same model as iftoprs's `/`, rather
    /// than hopping between matches.
    ///
    /// For SQLite the filter is a `WHERE` over every column, so it covers the
    /// whole table and not just the loaded page.
    fn filter_preview(&mut self, pattern: &str) {
        self.set_filter(pattern.to_string());
    }

    /// Set the active filter and rebuild whatever the current view lists.
    fn set_filter(&mut self, pattern: String) {
        if self.filter == pattern {
            return;
        }
        self.filter = pattern;
        match &self.store {
            Store::Sqlite(_) => {
                // With the table list focused, follow the filter onto a listed
                // table; otherwise the grid keeps showing a hidden one.
                if self.focus == Focus::Left {
                    let visible = self.visible_tables();
                    if !visible.contains(&self.table_idx) {
                        if let Some(&first) = visible.first() {
                            self.table_idx = first;
                        }
                    }
                }
                // The row grid is filtered in SQL, so the page restarts.
                self.page_offset = 0;
                self.row_idx = 0;
                self.load_table();
            }
            Store::Rkyv(_) => {
                // Keep the selection on a listed row.
                self.record_idx = self.first_visible_record().unwrap_or(0);
                self.string_idx = self.first_visible_string().unwrap_or(0);
            }
        }
        self.status = if self.filter.is_empty() {
            String::new()
        } else {
            let n = self.visible_count();
            format!(
                "/{}  ({} match{})",
                self.filter,
                n,
                if n == 1 { "" } else { "es" }
            )
        };
    }

    /// Does `hay` pass the active filter? An empty filter passes everything.
    fn passes(&self, hay: &str) -> bool {
        self.filter.is_empty() || hay.to_lowercase().contains(&self.filter.to_lowercase())
    }

    /// Indices of the records the filter leaves listed.
    fn visible_records(&self) -> Vec<usize> {
        match &self.decoded {
            Some(d) => d
                .records
                .iter()
                .enumerate()
                .filter(|(_, r)| self.passes(&r.key))
                .map(|(i, _)| i)
                .collect(),
            None => Vec::new(),
        }
    }

    /// Indices of the extracted strings the filter leaves listed.
    fn visible_strings(&self) -> Vec<usize> {
        self.strings
            .iter()
            .enumerate()
            .filter(|(_, s)| self.passes(&s.text))
            .map(|(i, _)| i)
            .collect()
    }

    /// Table names the filter leaves listed (the left pane).
    fn visible_tables(&self) -> Vec<usize> {
        let tables = self.sqlite().map(|s| s.tables.clone()).unwrap_or_default();
        tables
            .iter()
            .enumerate()
            .filter(|(_, t)| self.passes(t))
            .map(|(i, _)| i)
            .collect()
    }

    fn first_visible_record(&self) -> Option<usize> {
        self.visible_records().first().copied()
    }

    fn first_visible_string(&self) -> Option<usize> {
        self.visible_strings().first().copied()
    }

    /// How many rows the current view lists under the filter, for the status line.
    fn visible_count(&self) -> usize {
        match &self.store {
            Store::Sqlite(_) => match self.focus {
                Focus::Left => self.visible_tables().len(),
                Focus::Right => self.rows.as_ref().map(|r| r.total as usize).unwrap_or(0),
            },
            Store::Rkyv(_) => match self.rkyv_view {
                RkyvView::Records => self.visible_records().len(),
                RkyvView::Strings => self.visible_strings().len(),
                _ => 0,
            },
        }
    }

    /// Open a text-input modal, placing the cursor at the end of its buffer.
    fn open_modal(&mut self, mode: Mode) {
        if matches!(mode, Mode::Search(_)) {
            self.search_origin = Some(self.snapshot_position());
        }
        self.input_cursor = match &mode {
            Mode::EditCell(s) | Mode::Search(s) | Mode::AddRecord(s) | Mode::RenameRecord(s) => {
                s.len()
            }
            _ => 0,
        };
        self.mode = mode;
    }

    fn commit_search(&mut self, pattern: &str) {
        self.search = pattern.to_string();
        self.search_next(true);
    }

    fn key_confirm_delete(&mut self, code: KeyCode) {
        match code {
            KeyCode::Char('y') | KeyCode::Char('Y') => {
                match &self.store {
                    Store::Sqlite(_) => self.delete_current_row(),
                    Store::Rkyv(_) => self.delete_current_record(),
                }
                self.mode = Mode::Normal;
            }
            _ => self.mode = Mode::Normal,
        }
    }

    // ----- rkyv record CRUD -------------------------------------------------

    fn has_current_record(&self) -> bool {
        self.decoded
            .as_ref()
            .is_some_and(|d| self.record_idx < d.records.len())
    }

    /// (kind, shard bytes) for the current rkyv archive, if decoded. The bytes are
    /// shared, not copied — see [`RkyvStore::bytes`].
    fn rkyv_kind_bytes(&self) -> Option<(FormatKind, std::sync::Arc<[u8]>)> {
        let kind = self.decoded.as_ref().map(|d| d.kind)?;
        match &self.store {
            Store::Rkyv(r) => Some((kind, r.bytes.clone())),
            _ => None,
        }
    }

    /// (display key, del_key, kind, shard bytes) for the selected record.
    fn rkyv_ctx(&self) -> Option<(String, String, FormatKind, std::sync::Arc<[u8]>)> {
        let (key, del_key, kind) = self.decoded.as_ref().and_then(|d| {
            d.records
                .get(self.record_idx)
                .map(|r| (r.key.clone(), r.del_key.clone(), d.kind))
        })?;
        match &self.store {
            Store::Rkyv(r) => Some((key, del_key, kind, r.bytes.clone())),
            _ => None,
        }
    }

    /// Apply a shard edit: write the new bytes back atomically and reload.
    fn rkyv_apply(&mut self, result: Result<Vec<u8>, String>, ok_msg: String) {
        let new_bytes = match result {
            Ok(b) => b,
            Err(e) => {
                self.notify(format!("failed: {}", e));
                return;
            }
        };
        let path = match &self.store {
            Store::Rkyv(r) => r.path.clone(),
            _ => return,
        };
        let tmp = path.with_extension("zdbview.tmp");
        let write = std::fs::write(&tmp, &new_bytes).and_then(|_| std::fs::rename(&tmp, &path));
        if let Err(e) = write {
            let _ = std::fs::remove_file(&tmp);
            self.notify(format!("write failed: {}", e));
            return;
        }
        if let Store::Rkyv(r) = &mut self.store {
            r.bytes = new_bytes.into();
        }
        self.reload_rkyv();
        self.notify(ok_msg);
    }

    /// Delete the selected rkyv record and write the shard back.
    fn delete_current_record(&mut self) {
        let (key, del_key, kind, bytes) = match self.rkyv_ctx() {
            Some(v) => v,
            None => return,
        };
        self.rkyv_apply(
            crate::formats::delete_record(&bytes, kind, &del_key),
            format!("deleted: {}", key),
        );
    }

    fn commit_add_record(&mut self, key: &str) {
        if key.is_empty() {
            self.notify("add cancelled: empty key");
            return;
        }
        let (kind, bytes) = match self.rkyv_kind_bytes() {
            Some(v) => v,
            None => return,
        };
        self.rkyv_apply(
            crate::formats::add_record(&bytes, kind, key, Vec::new()),
            format!("added: {}", key),
        );
    }

    /// Open the hex editor on the selected record's value, pre-filled with its
    /// current bytes (ported editor; see `crate::hexedit`).
    fn open_hex_editor(&mut self) {
        let (key, value) = match self
            .decoded
            .as_ref()
            .and_then(|d| d.records.get(self.record_idx))
        {
            Some(rec) => (rec.key.clone(), rec.value.clone()),
            None => return,
        };
        self.hex = Some(HexEdit::new(key, value));
        self.hex_from = self.screen;
        self.hex_target = HexTarget::Record;
        self.screen = Screen::HexEdit;
    }

    fn key_hex(&mut self, key: KeyEvent) {
        let action = match self.hex.as_mut() {
            Some(ed) => ed.on_key(key),
            None => {
                self.screen = Screen::Main;
                return;
            }
        };
        match action {
            hexedit::Action::None => {}
            hexedit::Action::Save => self.commit_hex_value(),
            hexedit::Action::Close => {
                self.hex = None;
                self.screen = self.hex_from;
                if self.screen == Screen::Detail {
                    // The value it was editing may have changed under it.
                    self.load_detail_value(false);
                }
            }
        }
    }

    /// Write the edited bytes back into the archive (same write-back path the
    /// other record edits use), leaving the editor open on the saved value.
    fn commit_hex_value(&mut self) {
        let value = match self.hex.as_ref() {
            Some(ed) => ed.bytes.clone(),
            None => return,
        };
        if let HexTarget::Cell { table, key, column } = self.hex_target.clone() {
            let n = value.len();
            let written = match self.sqlite() {
                Some(s) => s.update_cell_blob_keyed(&table, &key, &column, &value),
                None => return,
            };
            match written {
                Ok(0) => self.notify("the row that cell belonged to is gone".to_string()),
                Ok(_) => {
                    self.load_table();
                    self.notify(format!("{column} set ({n} bytes)"));
                    if let Some(ed) = self.hex.as_mut() {
                        ed.mark_saved();
                    }
                }
                Err(e) => self.notify(format!("write failed: {e}")),
            }
            return;
        }
        let (_, del_key, kind, bytes) = match self.rkyv_ctx() {
            Some(v) => v,
            None => return,
        };
        let n = value.len();
        self.rkyv_apply(
            crate::formats::set_value(&bytes, kind, &del_key, value),
            format!("value set ({} bytes)", n),
        );
        if let Some(ed) = self.hex.as_mut() {
            ed.mark_saved();
        }
    }

    fn commit_rename_record(&mut self, new_key: &str) {
        if new_key.is_empty() {
            self.notify("rename cancelled");
            return;
        }
        let (_, del_key, kind, bytes) = match self.rkyv_ctx() {
            Some(v) => v,
            None => return,
        };
        self.rkyv_apply(
            crate::formats::rename_record(&bytes, kind, &del_key, new_key),
            format!("renamed → {}", new_key),
        );
    }

    /// Recompute rkyv-derived state (strings + decoded records) after a write.
    fn reload_rkyv(&mut self) {
        let (strings, decoded) = match &self.store {
            Store::Rkyv(r) => (r.strings(MIN_STRING), crate::formats::try_decode(&r.bytes)),
            _ => return,
        };
        self.strings_truncated = strings.truncated;
        self.strings_scanned = strings.scanned;
        self.strings = strings.hits;
        self.decoded = decoded;
        let n = self.decoded.as_ref().map(|d| d.records.len()).unwrap_or(0);
        if self.record_idx >= n {
            self.record_idx = n.saturating_sub(1);
        }
        if n == 0 {
            self.rkyv_view = RkyvView::Info;
        }
    }

    // ----- SQLite operations ------------------------------------------------

    fn sqlite(&self) -> Option<&SqliteStore> {
        match &self.store {
            Store::Sqlite(s) => Some(s),
            _ => None,
        }
    }

    fn current_table(&self) -> Option<String> {
        self.sqlite()
            .and_then(|s| s.tables.get(self.table_idx).cloned())
    }

    fn current_rowid(&self) -> Option<i64> {
        self.rows
            .as_ref()
            .and_then(|r| r.rowids.get(self.row_idx).copied().flatten())
    }

    /// How to address the selected row for a write: its rowid where the table has
    /// one, else its primary key read from the row on screen. `None` when neither
    /// exists — a `WITHOUT ROWID` table with no primary key cannot be edited in
    /// place at all, and neither can one whose key column holds a blob, since the
    /// key is matched as text.
    fn current_key(&self) -> Option<crate::sqlite::RowKey> {
        if let Some(id) = self.current_rowid() {
            return Some(crate::sqlite::RowKey::Rowid(id));
        }
        let view = self.rows.as_ref()?;
        if view.primary_key.is_empty() {
            return None;
        }
        let row = view.rows.get(self.row_idx)?;
        let mut pairs = Vec::with_capacity(view.primary_key.len());
        for name in &view.primary_key {
            let i = view.columns.iter().position(|c| c == name)?;
            let value = row.get(i)?;
            if value.starts_with("<blob ") {
                return None;
            }
            pairs.push((name.clone(), value.clone()));
        }
        Some(crate::sqlite::RowKey::Primary(pairs))
    }

    /// Why the selected row cannot be written to, for a message that says which of
    /// the two reasons it is.
    fn no_key_reason(&self) -> &'static str {
        match self.rows.as_ref() {
            Some(v) if v.primary_key.is_empty() => {
                "row has no rowid and the table has no primary key — cannot edit in place"
            }
            _ => "the primary key of this row holds a blob — cannot address it as text",
        }
    }

    fn select_table(&mut self, idx: usize) {
        let n = self.sqlite().map(|s| s.tables.len()).unwrap_or(0);
        if n == 0 {
            return;
        }
        self.table_idx = idx.min(n - 1);
        self.page_offset = 0;
        self.row_idx = 0;
        self.col_idx = 0;
        // The sort column belongs to the table that was open.
        self.sort = None;
        self.load_table();
    }

    /// Sort the row grid by the column under the cursor. Pressing it again on
    /// the same column flips the direction; a third press clears the sort and
    /// returns to the table's natural `rowid` order.
    fn sort_by_current_column(&mut self) {
        let col = match self
            .rows
            .as_ref()
            .and_then(|r| r.columns.get(self.col_idx))
            .cloned()
        {
            Some(c) => c,
            None => return,
        };
        self.sort = match self.sort.take() {
            Some(s) if s.column == col && !s.desc => Some(Sort {
                column: col.clone(),
                desc: true,
            }),
            Some(s) if s.column == col => None,
            _ => Some(Sort {
                column: col.clone(),
                desc: false,
            }),
        };
        // A different ordering means a different first page.
        self.page_offset = 0;
        self.row_idx = 0;
        self.load_table();
        match &self.sort {
            Some(s) => {
                let dir = if s.desc { "descending" } else { "ascending" };
                self.notify(format!("sorted by {} {}", s.column, dir))
            }
            None => self.notify("sort cleared (rowid order)"),
        }
    }

    /// Move the sort to the next / previous column, keeping the direction.
    fn sort_shift_column(&mut self, forward: bool) {
        let columns = match self.rows.as_ref().map(|r| r.columns.clone()) {
            Some(c) if !c.is_empty() => c,
            _ => return,
        };
        let desc = self.sort.as_ref().is_some_and(|s| s.desc);
        let cur = self
            .sort
            .as_ref()
            .and_then(|s| columns.iter().position(|c| *c == s.column));
        let next = match cur {
            Some(i) if forward => (i + 1) % columns.len(),
            Some(i) => (i + columns.len() - 1) % columns.len(),
            // No sort yet: start from the column the cursor is on.
            None => self.col_idx.min(columns.len() - 1),
        };
        self.col_idx = next;
        self.sort = Some(Sort {
            column: columns[next].clone(),
            desc,
        });
        self.page_offset = 0;
        self.row_idx = 0;
        self.load_table();
        let dir = if desc { "descending" } else { "ascending" };
        self.notify(format!("sorted by {} {}", columns[next], dir));
    }

    /// Ask for the page the current position describes. Returns immediately; the
    /// rows arrive through [`Self::poll_query`].
    fn load_table(&mut self) {
        let Some(table) = self.current_table() else {
            return;
        };
        // The page on screen is what lets the fetch step by cursor instead of by
        // offset — the difference between one index seek and re-walking every
        // matching row that comes before this page. Its offset is
        // `loaded_offset`, not `page_offset`: callers move `page_offset` to the
        // page they want before asking for it.
        let loaded_offset = self.loaded_offset;
        let hint = self.rows.as_ref().and_then(|r| {
            Some(crate::sqlite::PageHint {
                offset: loaded_offset,
                first: r.rowids.first().copied().flatten()?,
                last: r.rowids.last().copied().flatten()?,
                len: r.rows.len() as i64,
            })
        });
        let page = crate::query::PageReq {
            table: table.clone(),
            limit: PAGE,
            offset: self.page_offset,
            sort: self.sort.clone(),
            filter: self.filter.clone(),
            hint,
            known_total: self.known_total(),
        };
        // The exact total is only worth a scan once per table+filter; while it
        // still describes the grid it is kept.
        let count = match self.exact_total {
            Some((ref t, ref f, _)) if *t == table && *f == self.filter => None,
            _ => Some(crate::query::CountReq {
                table,
                filter: self.filter.clone(),
            }),
        };
        if let Some(engine) = self.engine.as_mut() {
            self.page_generation = engine.request(page, count);
            // A cheap page — the common case now that the count is bounded and
            // paging uses a cursor — arrives inside this grace period, so the
            // grid is drawn once with its rows instead of blank and then filled.
            if let Some(done) = engine.wait_page(PAGE_GRACE) {
                self.install_page(done);
            }
        }
    }

    /// Put a finished page on screen.
    fn install_page(&mut self, done: crate::query::PageDone) {
        match done.result {
            Ok(v) => {
                self.loaded_offset = self.page_offset;
                self.rows = Some(v);
                let loaded = self.rows.as_ref().map(|r| r.rows.len()).unwrap_or(0);
                if self.row_idx >= loaded {
                    self.row_idx = loaded.saturating_sub(1);
                }
                // A total already counted for this table and filter is better
                // than the page's bound.
                if let (Some(n), Some(rows)) = (self.known_total(), self.rows.as_mut()) {
                    rows.total = n;
                    rows.total_exact = true;
                }
            }
            // A cancelled query is the normal case while typing, and the
            // generation check already dropped its result; what reaches here is a
            // real failure.
            Err(e) => self.status = format!("load: {e}"),
        }
    }

    /// Install whatever the query threads have finished.
    fn poll_query(&mut self) {
        let Some(engine) = self.engine.as_mut() else {
            return;
        };
        let page = engine.poll_page();
        let count = engine.poll_count();
        let found = engine.poll_search();
        if let Some(done) = page {
            self.install_page(done);
        }
        if let Some(done) = found {
            self.install_search(done);
        }
        if let Some(done) = count {
            if let Ok(n) = done.result {
                self.exact_total = Some((done.table.clone(), done.filter.clone(), n));
                // The count is what `G` was waiting for.
                if self.pending_bottom {
                    self.pending_bottom = false;
                    self.goto_bottom_at(n);
                }
                if let Some(rows) = self.rows.as_mut() {
                    rows.total = n;
                    rows.total_exact = true;
                }
            }
        }
    }

    /// The database changed shape, so every cached fact about it is suspect —
    /// including the ones held by the query threads on their own connections,
    /// which is why they are replaced rather than notified.
    fn schema_changed(&mut self) {
        let path = match &mut self.store {
            Store::Sqlite(s) => {
                s.invalidate();
                Some(s.path.clone())
            }
            Store::Rkyv(_) => None,
        };
        if let Some(path) = path {
            self.engine = Some(crate::query::Engine::new(&path));
        }
        self.exact_total = None;
    }

    /// Rows were added or removed, so a counted total no longer holds.
    fn rows_changed(&mut self) {
        self.exact_total = None;
    }

    /// An exact count is still running, so the total on screen is a lower bound.
    fn counting(&self) -> bool {
        self.engine.as_ref().is_some_and(|e| e.count_inflight())
    }

    /// A page fetch is still running, so the rows on screen are the previous
    /// page.
    fn loading(&self) -> bool {
        self.engine.as_ref().is_some_and(|e| e.page_inflight())
    }

    /// A whole-table search is still scanning.
    fn searching(&self) -> bool {
        self.engine.as_ref().is_some_and(|e| e.searching())
    }

    /// The exact total for the table and filter on screen, if it has arrived.
    fn known_total(&self) -> Option<i64> {
        let table = self.current_table()?;
        match &self.exact_total {
            Some((t, f, n)) if *t == table && *f == self.filter => Some(*n),
            _ => None,
        }
    }

    /// Step `cur` by `delta` positions through `visible`, clamped to its ends.
    /// Navigation has to walk the filtered list, or j/k would land on rows the
    /// filter has hidden.
    fn step_visible(visible: &[usize], cur: usize, delta: isize) -> Option<usize> {
        if visible.is_empty() {
            return None;
        }
        let pos = visible.iter().position(|&i| i == cur).unwrap_or(0) as isize;
        let next = (pos + delta).clamp(0, visible.len() as isize - 1) as usize;
        Some(visible[next])
    }

    /// Install a background decode's result once it arrives.
    fn poll_decode(&mut self) {
        let result = match self.decoding.as_ref() {
            Some(rx) => match rx.try_recv() {
                Ok(d) => d,
                Err(std::sync::mpsc::TryRecvError::Empty) => return,
                // The thread died without sending: treat it as undecodable.
                Err(std::sync::mpsc::TryRecvError::Disconnected) => None,
            },
            None => return,
        };
        self.decoding = None;
        self.decoded = result;
        match &self.decoded {
            Some(d) => {
                let (format, records) = (d.format.clone(), d.records.len());
                self.rkyv_view = RkyvView::Records;
                self.notify(format!("{} · {} records", format, records));
            }
            None => self.notify("unrecognized archive — structural view"),
        }
    }

    /// A screenful, never zero.
    fn page_step(&self) -> usize {
        self.page_rows.max(1)
    }

    /// PageUp/PageDown (and `^F`/`^B`) for the SQLite panes: move the selection by
    /// a screenful, stepping to the next/previous SQL page at the edges.
    fn page_sqlite(&mut self, down: bool) {
        let step = self.page_step();
        match self.focus {
            Focus::Left => {
                let visible = self.visible_tables();
                let delta = if down {
                    step as isize
                } else {
                    -(step as isize)
                };
                if let Some(i) = Self::step_visible(&visible, self.table_idx, delta) {
                    self.select_table(i);
                }
            }
            Focus::Right => {
                let (loaded, total) = match &self.rows {
                    Some(r) => (r.rows.len(), r.total),
                    None => return,
                };
                if loaded == 0 {
                    return;
                }
                if down {
                    if self.row_idx + step < loaded {
                        self.row_idx += step;
                    } else if self.page_offset + PAGE < total {
                        self.page(PAGE);
                    } else {
                        self.row_idx = loaded - 1;
                    }
                } else if self.row_idx >= step {
                    self.row_idx -= step;
                } else if self.page_offset > 0 {
                    self.page(-PAGE);
                    // Land at the bottom of the page we just came back to.
                    self.row_idx = self.rows.as_ref().map(|r| r.rows.len()).unwrap_or(1) - 1;
                } else {
                    self.row_idx = 0;
                }
            }
        }
    }

    /// Move the selection by `delta` listed rows, whichever screen is showing.
    /// Used by the filter prompt, where the list stays navigable while typing.
    fn move_selection(&mut self, delta: isize) {
        match &self.store {
            Store::Sqlite(_) => match self.focus {
                Focus::Left => {
                    let visible = self.visible_tables();
                    if let Some(i) = Self::step_visible(&visible, self.table_idx, delta) {
                        self.select_table(i);
                    }
                }
                Focus::Right => {
                    let loaded = self.rows.as_ref().map(|r| r.rows.len()).unwrap_or(0);
                    if loaded == 0 {
                        return;
                    }
                    let next = (self.row_idx as isize + delta).clamp(0, loaded as isize - 1);
                    self.row_idx = next as usize;
                }
            },
            Store::Rkyv(_) => self.move_rkyv(delta),
        }
    }

    /// Move the rkyv selection by `delta` listed rows (the Hex view scrolls
    /// instead, since bytes are not filtered).
    fn move_rkyv(&mut self, delta: isize) {
        match self.rkyv_view {
            RkyvView::Records => {
                let visible = self.visible_records();
                if let Some(i) = Self::step_visible(&visible, self.record_idx, delta) {
                    self.record_idx = i;
                }
            }
            RkyvView::Strings => {
                let visible = self.visible_strings();
                if let Some(i) = Self::step_visible(&visible, self.string_idx, delta) {
                    self.string_idx = i;
                }
            }
            RkyvView::Hex => {
                let rows = match &self.store {
                    Store::Rkyv(r) => r.len().div_ceil(16),
                    _ => 0,
                };
                let next = (self.hex_row as isize + delta).max(0) as usize;
                self.hex_row = next.min(rows.saturating_sub(1));
            }
            RkyvView::Info => {}
        }
    }

    /// The same for the rkyv views, a screenful at a time.
    fn page_rkyv(&mut self, down: bool) {
        let step = self.page_step() as isize;
        self.move_rkyv(if down { step } else { -step });
    }

    fn page(&mut self, delta: i64) {
        if self.focus != Focus::Right {
            return;
        }
        let total = self.rows.as_ref().map(|r| r.total).unwrap_or(0);
        let next = (self.page_offset + delta).max(0);
        if next < total {
            self.page_offset = next;
            self.row_idx = 0;
            self.load_table();
        }
    }

    fn begin_edit_cell(&mut self) {
        if self.focus != Focus::Right {
            return;
        }
        self.edit_current_value()
    }

    /// `E`: open the selected cell in the hex editor whatever it holds. `e` only
    /// does that for a cell that is already a blob, so without this there is no way
    /// to turn a NULL or a string into bytes.
    fn edit_cell_as_bytes(&mut self) {
        if matches!(self.store, Store::Rkyv(_)) {
            return self.open_hex_editor();
        }
        let column = self
            .rows
            .as_ref()
            .and_then(|r| r.columns.get(self.col_idx).cloned());
        let (table, column, key) = match (self.current_table(), column, self.current_key()) {
            (Some(t), Some(c), Some(k)) => (t, c, k),
            _ => {
                let why = self.no_key_reason();
                self.notify(why);
                return;
            }
        };
        // Whatever the cell holds becomes the starting bytes: a string's own bytes,
        // a number's digits, nothing at all for NULL.
        let bytes = match self.sqlite() {
            Some(s) => s
                .cell_bytes_keyed(&table, &key, &column)
                .unwrap_or_default(),
            None => return,
        };
        let n = bytes.len();
        self.hex = Some(HexEdit::new(format!("{table}.{column}"), bytes));
        self.hex_from = self.screen;
        self.hex_target = HexTarget::Cell {
            table,
            key,
            column: column.clone(),
        };
        self.screen = Screen::HexEdit;
        self.notify(format!(
            "{column} as bytes — {n} to start, ^s writes it back as a blob"
        ));
    }

    /// Edit whatever is selected: a SQLite cell (in the hex editor when it holds a
    /// blob, inline otherwise) or a rkyv record's value. Reached from the grid via
    /// `e` and from the detail screen, which has no pane focus of its own.
    fn edit_current_value(&mut self) {
        if matches!(self.store, Store::Rkyv(_)) {
            self.open_hex_editor();
            return;
        }
        let cur = self
            .rows
            .as_ref()
            .and_then(|r| r.rows.get(self.row_idx))
            .and_then(|row| row.get(self.col_idx))
            .cloned()
            .unwrap_or_default();
        let key = match self.current_key() {
            Some(k) => k,
            None => {
                let why = self.no_key_reason();
                self.notify(why);
                return;
            }
        };
        // A blob has no text form: editing it as a string would replace the bytes
        // with their own description. Those cells open in the hex editor instead,
        // which is what DB Browser's binary cell editor does.
        let column = self
            .rows
            .as_ref()
            .and_then(|r| r.columns.get(self.col_idx).cloned());
        if let (Some(table), Some(column), Some(store)) =
            (self.current_table(), column, self.sqlite())
        {
            if store
                .cell_is_blob_keyed(&table, &key, &column)
                .unwrap_or(false)
            {
                match store.cell_bytes_keyed(&table, &key, &column) {
                    Ok(bytes) => {
                        let n = bytes.len();
                        self.hex = Some(HexEdit::new(format!("{table}.{column}"), bytes));
                        self.hex_from = self.screen;
                        self.hex_target = HexTarget::Cell { table, key, column };
                        self.screen = Screen::HexEdit;
                        self.notify(format!("blob cell — {n} bytes in the hex editor"));
                        return;
                    }
                    Err(e) => {
                        self.notify(format!("cannot read the blob: {e}"));
                        return;
                    }
                }
            }
        }
        self.open_modal(Mode::EditCell(cur));
    }

    fn commit_edit_cell(&mut self, val: &str) {
        let (table, key, col) = match (
            self.current_table(),
            self.current_key(),
            self.rows
                .as_ref()
                .and_then(|r| r.columns.get(self.col_idx).cloned()),
        ) {
            (Some(t), Some(rid), Some(c)) => (t, rid, c),
            _ => return,
        };
        let res = self
            .sqlite()
            .unwrap()
            .update_cell_keyed(&table, &key, &col, val);
        match res {
            Ok(0) => self.notify("that row is no longer there".to_string()),
            Ok(_) => {
                self.notify(format!("updated {}.{}", table, col));
                self.load_table();
                // Edited from the detail screen: it is still showing the old bytes.
                if self.screen == Screen::Detail {
                    self.load_detail_value(false);
                }
            }
            Err(e) => self.status = format!("update failed: {}", e),
        }
    }

    fn insert_row(&mut self) {
        let table = match self.current_table() {
            Some(t) => t,
            None => return,
        };
        match self.sqlite().unwrap().insert_blank(&table) {
            Ok(()) => {
                self.notify(format!("inserted default row into {}", table));
                self.rows_changed();
                self.load_table();
            }
            Err(e) => self.status = format!("insert failed: {}", e),
        }
    }

    fn delete_current_row(&mut self) {
        let (table, key) = match (self.current_table(), self.current_key()) {
            (Some(t), Some(k)) => (t, k),
            _ => {
                let why = self.no_key_reason();
                self.notify(why);
                return;
            }
        };
        let what = match &key {
            crate::sqlite::RowKey::Rowid(id) => format!("row {id}"),
            crate::sqlite::RowKey::Primary(pairs) => pairs
                .iter()
                .map(|(c, v)| format!("{c}={v}"))
                .collect::<Vec<_>>()
                .join(", "),
        };
        match self.sqlite().unwrap().delete_row_keyed(&table, &key) {
            Ok(0) => self.notify("that row is no longer there".to_string()),
            Ok(_) => {
                self.notify(format!("deleted {what} from {table}"));
                self.row_idx = self.row_idx.saturating_sub(1);
                self.rows_changed();
                self.load_table();
            }
            Err(e) => self.status = format!("delete failed: {}", e),
        }
    }

    /// `gg` — jump to the first table (left) or first row of the first page
    /// (right).
    fn goto_top(&mut self) {
        match self.focus {
            Focus::Left => self.select_table(0),
            Focus::Right => {
                self.page_offset = 0;
                self.row_idx = 0;
                self.load_table();
            }
        }
    }

    /// `G` — jump to the last table (left) or the last row of the last page
    /// (right).
    fn goto_bottom(&mut self) {
        match self.focus {
            Focus::Left => {
                let n = self.sqlite().map(|s| s.tables.len()).unwrap_or(0);
                if n > 0 {
                    self.select_table(n - 1);
                }
            }
            Focus::Right => match self.known_total() {
                Some(total) => self.goto_bottom_at(total),
                // Only an exact count says which page the last one is, and that
                // is a full scan on a filtered grid. Ask for it and jump when it
                // lands, rather than freezing here.
                None => {
                    self.pending_bottom = true;
                    if let (Some(table), Some(engine)) =
                        (self.current_table(), self.engine.as_mut())
                    {
                        engine.request_count(crate::query::CountReq {
                            table,
                            filter: self.filter.clone(),
                        });
                    }
                    self.status = "counting rows for the last page…".into();
                }
            },
        }
    }

    /// Jump to the last page of a grid known to hold `total` rows.
    fn goto_bottom_at(&mut self, total: i64) {
        if total <= 0 {
            return;
        }
        self.page_offset = ((total - 1) / PAGE) * PAGE;
        self.row_idx = ((total - 1) % PAGE) as usize;
        self.load_table();
    }

    // ----- rkyv navigation --------------------------------------------------

    fn rkyv_goto_top(&mut self) {
        match self.rkyv_view {
            RkyvView::Records => self.record_idx = 0,
            RkyvView::Strings => self.string_idx = 0,
            RkyvView::Hex => self.hex_row = 0,
            RkyvView::Info => {}
        }
    }

    fn rkyv_goto_bottom(&mut self) {
        match self.rkyv_view {
            RkyvView::Records => {
                self.record_idx = self
                    .decoded
                    .as_ref()
                    .map(|d| d.records.len().saturating_sub(1))
                    .unwrap_or(0);
            }
            RkyvView::Strings => self.string_idx = self.strings.len().saturating_sub(1),
            RkyvView::Hex => {
                let len = match &self.store {
                    Store::Rkyv(r) => r.len(),
                    _ => 0,
                };
                self.hex_row = len.saturating_sub(1) / 16;
            }
            RkyvView::Info => {}
        }
    }

    // ----- search (`/`, `n`, `N`) -------------------------------------------

    /// Move to the next (`forward`) or previous match of `self.search`.
    /// SQLite search scans the loaded page across all columns; rkyv search
    /// scans the string list or the raw bytes depending on the active view.
    fn search_next(&mut self, forward: bool) {
        if self.search.is_empty() {
            return;
        }
        match &self.store {
            Store::Sqlite(_) => self.search_sqlite(forward),
            Store::Rkyv(_) => self.search_rkyv(forward),
        }
    }

    fn search_sqlite(&mut self, forward: bool) {
        let term = self.search.to_lowercase();
        match self.focus {
            Focus::Left => {
                let tables = self.sqlite().map(|s| s.tables.clone()).unwrap_or_default();
                // Only what the filter leaves listed: jumping to a hidden table
                // would leave the pane showing a selection nobody can see.
                let visible = self.visible_tables();
                match find_next_visible(&visible, self.table_idx, forward, |i| {
                    tables[i].to_lowercase().contains(&term)
                }) {
                    Some(i) => self.select_table(i),
                    None => self.status = format!("not found: {}", self.search),
                }
            }
            Focus::Right => self.search_sqlite_table(forward),
        }
    }

    /// Whole-table SQLite search (SQL-backed, not limited to the loaded page).
    /// Wraps around from the opposite edge when nothing is found ahead.
    fn search_sqlite_table(&mut self, forward: bool) {
        let (table, columns) = match (
            self.current_table(),
            self.rows.as_ref().map(|r| r.columns.clone()),
        ) {
            (Some(t), Some(c)) => (t, c),
            _ => return,
        };
        // A search scans until it matches and then counts to find out which page
        // that is, so on a large table it is two full scans in the worst case —
        // both on the query thread, from where it cannot freeze the grid.
        let req = crate::query::SearchReq {
            table,
            columns,
            term: self.search.clone(),
            sort: self.sort.clone(),
            filter: self.filter.clone(),
            // From the selected row, else from the edge the scan comes in from.
            from: self.current_rowid(),
            forward,
        };
        let Some(engine) = self.engine.as_mut() else {
            return;
        };
        engine.request_search(req);
        self.status = format!("searching for {}", self.search);
    }

    /// Move to what a finished search found.
    fn install_search(&mut self, done: crate::query::SearchDone) {
        match done.result {
            Ok(Some((_rowid, ordinal))) => {
                let idx0 = (ordinal - 1).max(0);
                self.page_offset = (idx0 / PAGE) * PAGE;
                self.load_table();
                self.row_idx = (idx0 - self.page_offset) as usize;
                let total = self
                    .known_total()
                    .or_else(|| self.rows.as_ref().map(|r| r.total))
                    .unwrap_or(0);
                self.notify(format!("/{}  (row {} of {})", self.search, ordinal, total));
            }
            Ok(None) => self.status = format!("not found: {}", self.search),
            Err(e) => self.status = format!("search error: {}", e),
        }
    }

    fn search_rkyv(&mut self, forward: bool) {
        let term = self.search.to_lowercase();
        match self.rkyv_view {
            RkyvView::Records => {
                let keys: Vec<String> = self
                    .decoded
                    .as_ref()
                    .map(|d| d.records.iter().map(|r| r.key.to_lowercase()).collect())
                    .unwrap_or_default();
                let visible = self.visible_records();
                match find_next_visible(&visible, self.record_idx, forward, |i| {
                    keys[i].contains(&term)
                }) {
                    Some(i) => self.record_idx = i,
                    None => self.status = format!("not found: {}", self.search),
                }
            }
            RkyvView::Strings => {
                let visible = self.visible_strings();
                match find_next_visible(&visible, self.string_idx, forward, |i| {
                    self.strings[i].text.to_lowercase().contains(&term)
                }) {
                    Some(i) => self.string_idx = i,
                    None => self.status = format!("not found: {}", self.search),
                }
            }
            RkyvView::Hex => {
                let bytes = match &self.store {
                    Store::Rkyv(r) => r.bytes.clone(),
                    _ => return,
                };
                let cur = self.hex_row * 16;
                match find_bytes(&bytes, self.search.as_bytes(), cur, forward) {
                    Some(off) => {
                        self.hex_row = off / 16;
                        self.notify(format!("/{}  (offset {:#x})", self.search, off));
                    }
                    None => self.status = format!("not found: {}", self.search),
                }
            }
            RkyvView::Info => {}
        }
    }

    // ----- rendering --------------------------------------------------------

    fn render(&mut self, f: &mut Frame) {
        let outer = Layout::vertical([Constraint::Min(1), Constraint::Length(1)]).split(f.area());
        // A screenful for paging: the body minus borders, and minus the header
        // row of whichever screen has one. Recomputed every frame so a resize is
        // picked up without any extra plumbing.
        let body = outer[0].height as usize;
        self.page_rows = match self.screen {
            // The detail screen's value pane sits under a 9-row field list.
            Screen::Detail => body.saturating_sub(11),
            // The row grid has a header row on top of its borders.
            Screen::Main if matches!(self.store, Store::Sqlite(_)) => body.saturating_sub(3),
            _ => body.saturating_sub(2),
        }
        .max(1);

        match self.screen {
            Screen::Detail => self.render_detail(f, outer[0]),
            Screen::HexEdit => self.render_hex(f, outer[0]),
            Screen::Top => {
                let t = self.ov.theme;
                self.top_area = outer[0];
                if let Some(m) = self.top.as_ref() {
                    m.render(f, outer[0], &t);
                }
            }
            Screen::Sql => {
                let t = self.ov.theme;
                self.sql_area = outer[0];
                if let Some(e) = self.sql.as_mut() {
                    e.render(f, outer[0], &t);
                }
            }
            Screen::DbInfo => self.render_dbinfo(f, outer[0]),
            Screen::Stats => self.render_stats(f, outer[0]),
            Screen::Frames => {
                let t = self.ov.theme;
                if let Some(w) = self.walk.as_mut() {
                    w.render(f, outer[0], &t);
                }
            }
            Screen::Schema => self.render_schema(f, outer[0]),
            Screen::Main => match &self.store {
                Store::Sqlite(_) => self.render_sqlite(f, outer[0]),
                Store::Rkyv(_) => self.render_rkyv(f, outer[0]),
            },
        }
        self.render_status(f, outer[1]);

        // Modal overlays.
        match &self.mode {
            Mode::EditCell(buf) => self.render_input(f, "edit cell (Enter=save, Esc=cancel)", buf),
            Mode::Search(buf) => self.render_input(f, "search / (Enter, Esc)", buf),
            Mode::AddRecord(buf) => self.render_input(f, "new record key (Enter=add, Esc)", buf),
            Mode::RenameRecord(buf) => self.render_input(f, "rename key to (Enter, Esc)", buf),
            Mode::ConfirmDelete => {
                let what = match self.store {
                    Store::Sqlite(_) => "row",
                    Store::Rkyv(_) => "record (rewrites the cache file)",
                };
                self.render_input(f, &format!("delete this {}? (y = yes, any = no)", what), "")
            }
            Mode::Normal => {}
        }

        self.ov.render(f, self.help_ctx());
    }

    fn render_detail(&self, f: &mut Frame, area: Rect) {
        let rows = Layout::vertical([Constraint::Length(9), Constraint::Min(3)]).split(area);

        // Top: field list for the current row/record.
        let mut fields: Vec<Line> = Vec::new();
        let title;
        match &self.store {
            Store::Sqlite(_) => {
                title = " row detail ".to_string();
                if let Some(rv) = &self.rows {
                    if let Some(row) = rv.rows.get(self.row_idx) {
                        for (i, col) in rv.columns.iter().enumerate() {
                            let sel = i == self.col_idx;
                            fields.push(Line::from(vec![
                                Span::styled(
                                    format!("{:<20}", truncate(col, 20)),
                                    Style::default().fg(if sel {
                                        self.ov.theme.accent
                                    } else {
                                        self.ov.theme.dim
                                    }),
                                ),
                                Span::raw(truncate(
                                    row.get(i).map(|s| s.as_str()).unwrap_or(""),
                                    80,
                                )),
                            ]));
                        }
                    }
                }
            }
            Store::Rkyv(_) => {
                title = " record detail ".to_string();
                if let Some(rec) = self
                    .decoded
                    .as_ref()
                    .and_then(|d| d.records.get(self.record_idx))
                {
                    fields.push(Line::from(vec![
                        Span::styled(
                            format!("{:<20}", "key"),
                            Style::default().fg(self.ov.theme.accent),
                        ),
                        Span::raw(truncate(&rec.key, 80)),
                    ]));
                    for (name, val) in &rec.fields {
                        fields.push(Line::from(vec![
                            Span::styled(
                                format!("{:<20}", truncate(name, 20)),
                                Style::default().fg(self.ov.theme.dim),
                            ),
                            Span::raw(val.clone()),
                        ]));
                    }
                }
            }
        }
        f.render_widget(
            Paragraph::new(fields).block(Block::default().borders(Borders::ALL).title(title)),
            rows[0],
        );

        // Bottom: value pane.
        let height = rows[1].height.saturating_sub(2) as usize;
        let lines = value_lines(
            &self.detail_value,
            self.value_render,
            self.detail_scroll,
            height,
        );
        f.render_widget(
            Paragraph::new(lines).block(Block::default().borders(Borders::ALL).title(format!(
                " value — {} bytes — render: {} (v to cycle · y copy · Esc back) ",
                self.detail_value.len(),
                self.value_render.label()
            ))),
            rows[1],
        );
    }

    /// Open the write monitor over everything zdbview knows about, with the open
    /// file first since that is the one being edited.
    fn open_top(&mut self) {
        let mut targets = vec![match &self.store {
            Store::Sqlite(s) => (s.path.clone(), Kind::Sqlite),
            Store::Rkyv(r) => (r.path.clone(), Kind::Rkyv),
        }];
        targets.extend(watch_targets());
        let m = crate::monitor::Monitor::new(targets);
        if m.is_empty() {
            self.notify("nothing to watch yet");
            return;
        }
        let n = m.len();
        self.top = Some(m);
        self.screen = Screen::Top;
        self.notify(format!("watching {} files for writes", n));
    }

    /// Open the statistics screen for the current table: one row per column with
    /// its nulls, distinct values, extremes and mean — VisiData's `describe`,
    /// sqlite-utils' `analyze-tables`. Every column costs one pass over the table,
    /// so this runs on request rather than alongside the grid.
    fn open_stats(&mut self) {
        let table = match self.current_table() {
            Some(t) => t,
            None => return,
        };
        let path = match self.sqlite() {
            Some(s) => s.path.clone(),
            None => return,
        };
        self.stats.clear();
        self.stats_freq = None;
        self.stats_idx = 0;
        self.screen = Screen::Stats;
        // Each column costs a pass over the table, and on a real database a wide
        // blob column costs more than a second of it — so the pass runs on its own
        // connection on another thread and the screen fills in when it lands.
        self.stats_pending = Some((table.clone(), spawn_stats(path, table.clone())));
        self.status = format!("{table} · analyzing columns …");
    }

    /// Install a finished statistics pass. Called from the event loop, like the
    /// archive decode.
    fn poll_stats(&mut self) {
        let (table, result) = match self.stats_pending.as_ref() {
            Some((t, rx)) => match rx.try_recv() {
                Ok(r) => (t.clone(), r),
                Err(std::sync::mpsc::TryRecvError::Empty) => return,
                Err(std::sync::mpsc::TryRecvError::Disconnected) => {
                    (t.clone(), Err("the analysis thread stopped".into()))
                }
            },
            None => return,
        };
        self.stats_pending = None;
        match result {
            Ok(v) => {
                let n = v.len();
                self.stats = v;
                self.stats_idx = self.col_idx.min(n.saturating_sub(1));
                self.status =
                    format!("{table} · {n} columns · Enter frequency · j/k move · Esc back");
            }
            Err(e) => {
                self.screen = Screen::Main;
                self.notify(format!("stats failed: {e}"));
            }
        }
    }

    fn key_stats(&mut self, code: KeyCode) {
        match code {
            KeyCode::Char('q') => self.quit = true,
            KeyCode::Esc | KeyCode::Char('A') => {
                // The frequency table is a step deeper, so Esc closes that first.
                if self.stats_freq.is_some() {
                    self.stats_freq = None;
                } else {
                    self.screen = Screen::Main;
                }
            }
            KeyCode::Down | KeyCode::Char('j') => {
                self.stats_idx = (self.stats_idx + 1).min(self.stats.len().saturating_sub(1));
                self.stats_freq = None;
            }
            KeyCode::Up | KeyCode::Char('k') => {
                self.stats_idx = self.stats_idx.saturating_sub(1);
                self.stats_freq = None;
            }
            KeyCode::Char('g') => {
                self.stats_idx = 0;
                self.stats_freq = None;
            }
            KeyCode::Char('G') => {
                self.stats_idx = self.stats.len().saturating_sub(1);
                self.stats_freq = None;
            }
            // A frequency table needs the column list the pass is still building.
            KeyCode::Enter | KeyCode::Char('f') if self.stats_pending.is_none() => {
                self.open_frequency()
            }
            _ => {}
        }
    }

    /// The selected column's most common values with their counts.
    fn open_frequency(&mut self) {
        let (table, column) = match (
            self.current_table(),
            self.stats.get(self.stats_idx).map(|c| c.name.clone()),
        ) {
            (Some(t), Some(c)) => (t, c),
            _ => return,
        };
        let rows = match self.sqlite() {
            Some(s) => s.frequency(&table, &column, FREQUENCY_ROWS),
            None => return,
        };
        match rows {
            Ok(v) => self.stats_freq = Some((column, v)),
            Err(e) => self.notify(format!("frequency failed: {e}")),
        }
    }

    fn render_stats(&mut self, f: &mut Frame, area: Rect) {
        let t = self.ov.theme;
        let mut lines: Vec<Line> = Vec::new();
        let head = format!(
            "  {:<16} {:<8} {:>7} {:>6} {:>8} {:>7} {:>7} {:>9} {:>9} {:>9}",
            "column",
            "type",
            "rows",
            "nulls",
            "distinct",
            "numeric",
            "longest",
            "min",
            "max",
            "mean"
        );
        lines.push(Line::from(Span::styled(
            head,
            Style::default().fg(t.primary).add_modifier(Modifier::BOLD),
        )));
        for (i, c) in self.stats.iter().enumerate() {
            // `numeric` is how many cells SQLite actually stores as a number,
            // which is the only way to see that a column declared INTEGER is
            // holding text — the declared type is an affinity hint, not a rule.
            let mean = match c.avg {
                Some(a) => format!("{a:.3}"),
                None => "".to_string(),
            };
            let text = format!(
                "  {:<16} {:<8} {:>7} {:>6} {:>8} {:>7} {:>7} {:>9} {:>9} {:>9}",
                truncate(&c.name, 16),
                truncate(&c.declared, 8),
                c.rows,
                c.nulls,
                c.distinct,
                c.numeric,
                c.longest,
                truncate(&c.min, 9),
                truncate(&c.max, 9),
                truncate(&mean, 9),
            );
            // Same selection styling as every other list in the app.
            let style = if i == self.stats_idx {
                Style::default().add_modifier(Modifier::REVERSED)
            } else {
                Style::default().fg(t.primary)
            };
            lines.push(Line::from(Span::styled(text, style)));
        }
        if let Some((col, freq)) = &self.stats_freq {
            lines.push(Line::from(""));
            lines.push(Line::from(Span::styled(
                format!("  {col} — most common values"),
                Style::default().fg(t.primary).add_modifier(Modifier::BOLD),
            )));
            let widest = freq.iter().map(|(_, n)| *n).max().unwrap_or(1).max(1);
            for (v, n) in freq {
                // The bar is the point: a glance says whether a column is skewed.
                let bar = "#".repeat(((*n as f64 / widest as f64) * 24.0).round() as usize);
                lines.push(Line::from(vec![
                    Span::styled(
                        format!("  {:<32} {:>9}  ", truncate(v, 32), n),
                        Style::default().fg(t.primary),
                    ),
                    Span::styled(bar, Style::default().fg(t.accent)),
                ]));
            }
        }
        let height = area.height.saturating_sub(2) as usize;
        // Keep the cursor row on screen without a separate scroll offset: the
        // header plus the selected row is what must be visible.
        let first = (self.stats_idx + 2).saturating_sub(height);
        let shown: Vec<Line> = lines.into_iter().skip(first).take(height).collect();
        let title = match (&self.stats_pending, self.current_table()) {
            (Some((t, _)), _) => format!(" columns of {t} — analyzing … "),
            (None, Some(t)) => format!(" columns of {t} — Enter frequency · Esc back "),
            (None, None) => " columns ".to_string(),
        };
        f.render_widget(
            Paragraph::new(shown).block(
                Block::default()
                    .borders(Borders::ALL)
                    .border_style(Style::default().fg(t.accent))
                    .title(title),
            ),
            area,
        );
    }

    /// `F`: follow the foreign key on the cursor column to the row it references,
    /// the way DB Browser and Datasette link a child row to its parent. Jumps to
    /// the parent table, selects the row, and leaves the column on the key.
    fn follow_foreign_key(&mut self) {
        let (table, columns, value) = match (self.current_table(), self.rows.as_ref()) {
            (Some(t), Some(v)) => {
                let value = match v.rows.get(self.row_idx).and_then(|r| r.get(self.col_idx)) {
                    Some(v) => v.clone(),
                    None => return,
                };
                (t, v.columns.clone(), value)
            }
            _ => return,
        };
        let column = match columns.get(self.col_idx) {
            Some(c) => c.clone(),
            None => return,
        };
        let keys = match self.sqlite() {
            Some(s) => s.foreign_keys(&table).unwrap_or_default(),
            None => return,
        };
        let (parent, parent_col) = match keys
            .iter()
            .find(|(child, _, _)| child.eq_ignore_ascii_case(&column))
        {
            Some((_, parent, parent_col)) => (parent.clone(), parent_col.clone()),
            None => {
                self.notify(format!("{column} is not a foreign key"));
                return;
            }
        };
        if value == "NULL" {
            self.notify(format!("{column} is NULL — nothing to follow"));
            return;
        }
        // `rowid` as the parent column means the key targets the parent's implicit
        // rowid, which is already what positions a row.
        let found = match self.sqlite() {
            Some(s) => {
                if parent_col == "rowid" {
                    value.parse::<i64>().ok()
                } else {
                    s.rowid_where(&parent, &parent_col, &value).unwrap_or(None)
                }
            }
            None => return,
        };
        let rowid = match found {
            Some(r) => r,
            None => {
                self.notify(format!("no {parent} row with {parent_col} = {value}"));
                return;
            }
        };
        let idx = match self
            .sqlite()
            .and_then(|s| s.tables.iter().position(|t| *t == parent))
        {
            Some(i) => i,
            None => {
                self.notify(format!("{parent} is not listed"));
                return;
            }
        };
        // The filter belongs to the table being left, and the parent row has to be
        // reachable, so clear it before jumping.
        self.filter.clear();
        self.select_table(idx);
        self.focus = Focus::Right;
        self.goto_rowid(rowid, &parent_col);
        self.notify(format!(
            "{table}.{column}{parent}.{parent_col} = {value}"
        ));
    }

    /// Put the cursor on `rowid`, paging to wherever it sits in the display order,
    /// and on `column` if the table has one by that name.
    fn goto_rowid(&mut self, rowid: i64, column: &str) {
        let ord = match (self.current_table(), self.sqlite()) {
            (Some(t), Some(s)) => s
                .rowid_ordinal(&t, rowid, self.sort.as_ref(), &self.filter)
                .unwrap_or(1),
            _ => return,
        };
        let idx0 = (ord - 1).max(0);
        self.page_offset = (idx0 / PAGE) * PAGE;
        self.load_table();
        self.row_idx = (idx0 - self.page_offset) as usize;
        if let Some(i) = self
            .rows
            .as_ref()
            .and_then(|r| r.columns.iter().position(|c| c == column))
        {
            self.col_idx = i;
        }
    }

    /// `Y`: the selected row as an `INSERT`, on the clipboard — DB Browser's
    /// "Copy as INSERT", which is how a row moves into a bug report or a fixture.
    fn copy_row_as_insert(&mut self) {
        let (table, view) = match (self.current_table(), self.rows.as_ref()) {
            (Some(t), Some(v)) => (t, v),
            _ => return,
        };
        let row = match view.rows.get(self.row_idx) {
            Some(r) => r.clone(),
            None => return,
        };
        let sql = crate::export::insert_statement(&table, &view.columns, &row);
        let ok = crate::clipboard::copy(&sql);
        self.notify(if ok {
            format!("copied INSERT ({} chars)", sql.len())
        } else {
            "clipboard unavailable (no tty)".to_string()
        });
    }

    /// Open the database-info screen: the pragmas the sqlite3 shell prints for
    /// `.dbinfo`, with the integrity check and foreign-key lint a keypress away
    /// since both can take a while on a large file.
    fn open_dbinfo(&mut self) {
        let info = match self.sqlite() {
            Some(s) => s.db_info(),
            None => return,
        };
        self.dbinfo = info;
        self.dbinfo_checks.clear();
        self.dbinfo_scroll = 0;
        self.screen = Screen::DbInfo;
        self.status = "database · i integrity · Q quick · f fk lint · v vacuum · z analyze \
                       · r reindex · Esc back"
            .into();
    }

    fn key_dbinfo(&mut self, code: KeyCode) {
        match code {
            KeyCode::Esc | KeyCode::Char('D') => {
                self.screen = Screen::Main;
                self.dbinfo_scroll = 0;
            }
            // `q` still quits, as on every other screen.
            KeyCode::Char('q') => self.quit = true,
            // `i` and `Q` are the shell's two checks; `f` is `.lint fkey-indexes`.
            KeyCode::Char('i') | KeyCode::Char('Q') => {
                let quick = code == KeyCode::Char('Q');
                let out = match self.sqlite() {
                    Some(s) => s.integrity_check(quick),
                    None => return,
                };
                self.dbinfo_checks = match out {
                    Ok(lines) if lines == ["ok".to_string()] => {
                        vec![format!(
                            "{} check: ok",
                            if quick { "quick" } else { "integrity" }
                        )]
                    }
                    Ok(lines) => lines,
                    Err(e) => vec![format!("check failed: {e}")],
                };
            }
            // The maintenance statements DB Browser calls "Compact Database" and
            // sqlite-utils exposes as subcommands. Each rewrites the file, so they
            // report what changed.
            KeyCode::Char('v') => self.maintain(crate::sqlite::Maintenance::Vacuum),
            KeyCode::Char('z') => self.maintain(crate::sqlite::Maintenance::Analyze),
            KeyCode::Char('r') => self.maintain(crate::sqlite::Maintenance::Reindex),
            KeyCode::Char('f') => {
                let out = match self.sqlite() {
                    Some(s) => s.missing_fk_indexes(),
                    None => return,
                };
                self.dbinfo_checks = match out {
                    Ok(v) if v.is_empty() => {
                        vec!["foreign-key lint: every foreign key has an index".into()]
                    }
                    Ok(v) => v,
                    Err(e) => vec![format!("lint failed: {e}")],
                };
            }
            KeyCode::Down | KeyCode::Char('j') => self.dbinfo_scroll += 1,
            KeyCode::Up | KeyCode::Char('k') => {
                self.dbinfo_scroll = self.dbinfo_scroll.saturating_sub(1)
            }
            KeyCode::PageDown => self.dbinfo_scroll += self.page_step(),
            KeyCode::PageUp => {
                self.dbinfo_scroll = self.dbinfo_scroll.saturating_sub(self.page_step())
            }
            KeyCode::Char('g') => self.dbinfo_scroll = 0,
            _ => {}
        }
    }

    /// Run `VACUUM`, `ANALYZE` or `REINDEX` and re-read the pragmas, since all
    /// three change what the screen is showing.
    fn maintain(&mut self, op: crate::sqlite::Maintenance) {
        let result = match self.sqlite() {
            Some(s) => s.maintain(op),
            None => return,
        };
        let line = match result {
            Ok(delta) => {
                let size = if delta == 0 {
                    "no change in size".to_string()
                } else if delta < 0 {
                    format!("{} smaller", human_size((-delta) as u64))
                } else {
                    format!("{} larger", human_size(delta as u64))
                };
                format!("{}: done, {size}", op.label())
            }
            Err(e) => format!("{} failed: {e}", op.label()),
        };
        if let Some(s) = self.sqlite() {
            self.dbinfo = s.db_info();
        }
        self.dbinfo_checks = vec![line.clone()];
        self.notify(line);
    }

    fn render_dbinfo(&mut self, f: &mut Frame, area: Rect) {
        let t = self.ov.theme;
        let mut lines: Vec<Line> = Vec::new();
        let width = self
            .dbinfo
            .iter()
            .map(|(k, _)| k.chars().count())
            .max()
            .unwrap_or(0);
        for (k, v) in &self.dbinfo {
            lines.push(Line::from(vec![
                Span::styled(
                    format!("  {:>width$}  ", k, width = width),
                    Style::default().fg(t.dim),
                ),
                Span::styled(v.clone(), Style::default().fg(t.primary)),
            ]));
        }
        if !self.dbinfo_checks.is_empty() {
            lines.push(Line::from(""));
            for c in &self.dbinfo_checks {
                // A clean result reads as a fact; anything else is a finding.
                let ok =
                    c.ends_with("ok") || c.contains("every foreign key") || c.contains(": done");
                lines.push(Line::from(Span::styled(
                    format!("  {c}"),
                    Style::default().fg(if ok { t.label } else { t.alt }),
                )));
            }
        }
        let height = area.height.saturating_sub(2) as usize;
        let max_scroll = lines.len().saturating_sub(height);
        self.dbinfo_scroll = self.dbinfo_scroll.min(max_scroll);
        let shown: Vec<Line> = lines
            .into_iter()
            .skip(self.dbinfo_scroll)
            .take(height)
            .collect();
        f.render_widget(
            Paragraph::new(shown).block(
                Block::default()
                    .borders(Borders::ALL)
                    .border_style(Style::default().fg(t.accent))
                    .title(" database — i/Q check · f fk lint · v/z/r maintain · Esc back "),
            ),
            area,
        );
    }

    /// Open the SQL editor, seeded with the schema so Tab can complete against
    /// the real tables and columns.
    fn open_sql(&mut self) {
        let schema = match self.sqlite() {
            Some(s) => s.schema_names(),
            None => return,
        };
        if self.sql.is_none() {
            self.sql = Some(crate::sqledit::SqlEdit::new(schema));
        }
        self.screen = Screen::Sql;
        self.status =
            "SQL editor · Tab completes · ^j newline · Enter runs · ↑/↓ history · Esc back".into();
    }

    fn key_sql(&mut self, key: KeyEvent) {
        let page = crate::sqledit::SqlEdit::page_rows(self.sql_area);
        let action = match self.sql.as_mut() {
            Some(e) => e.on_key(key, page),
            None => {
                self.screen = Screen::Main;
                return;
            }
        };
        match action {
            crate::sqledit::Action::None => {}
            // The editor stays alive behind the main screen, so its transcript and
            // history survive a trip back to the data.
            crate::sqledit::Action::Close => self.screen = Screen::Main,
            crate::sqledit::Action::Execute(sql) => self.execute_sql(&sql),
            crate::sqledit::Action::Explain(sql) => self.explain_sql(&sql),
        }
    }

    /// `^e` in the editor: the query plan, as the sqlite3 shell's `.eqp` shows it.
    fn explain_sql(&mut self, sql: &str) {
        use crate::sqledit::Entry;
        let plan = match self.sqlite() {
            Some(s) => s.explain_plan(sql),
            None => return,
        };
        let entry = match plan {
            Ok(steps) if steps.is_empty() => Entry::Plan(vec!["(no plan)".into()]),
            Ok(steps) => Entry::Plan(steps),
            Err(e) => Entry::Error(e.to_string()),
        };
        if let Some(e) = self.sql.as_mut() {
            e.push(entry);
        }
    }

    /// Run a statement from the editor and hand the outcome back to it.
    fn execute_sql(&mut self, sql: &str) {
        use crate::sqledit::{Entry, RESULT_ROWS};
        use crate::sqlite::Outcome;
        // A line starting with `.` is a dot-command, as in the shell.
        if sql.trim_start().starts_with('.') {
            return self.run_dot(sql.trim());
        }
        if self.sql_eqp {
            // `.eqp on`: the plan first, then the statement.
            self.explain_sql(sql);
        }
        let started = std::time::Instant::now();
        let outcome = match self.sqlite() {
            Some(s) => s.run(sql, RESULT_ROWS),
            None => return,
        };
        let took = started.elapsed();
        let entry = match outcome {
            Ok(Outcome::Rows {
                columns,
                rows,
                literals,
                truncated,
            }) => {
                // `.output` / `.once` send the result to a file instead, and
                // `.mode` decides how anything but the grid is written.
                match self.write_result(&columns, &rows, &literals) {
                    Some(note) => Entry::Note(vec![note]),
                    None if self.sql_mode == OutputMode::List => Entry::Rows {
                        columns,
                        rows,
                        truncated,
                    },
                    None => {
                        let text = self.sql_mode.render(
                            &columns,
                            &rows,
                            &literals,
                            &self.current_table().unwrap_or_else(|| "table".into()),
                            self.sql_headers,
                        );
                        Entry::Note(text.lines().map(str::to_string).collect())
                    }
                }
            }
            Ok(Outcome::Changed(n)) => {
                // The statement may have been DDL, so the cached column lists and
                // row counts no longer describe the database.
                self.schema_changed();
                // A write may have changed what the grid is showing.
                self.load_table();
                Entry::Changed(n)
            }
            Err(e) => Entry::Error(e.to_string()),
        };
        let timer = self.sql_timer;
        if let Some(e) = self.sql.as_mut() {
            e.push(entry);
            // The shell prints the duration after the result; so does this, unless
            // `.timer off`.
            if timer {
                e.push(crate::sqledit::Entry::Timing(took));
            }
        }
    }

    /// Carry out a dot-command, the way the sqlite3 shell does. The editor holds no
    /// database access of its own, so this is the host's job — which also keeps
    /// every file path and every write in one place.
    fn run_dot(&mut self, line: &str) {
        use crate::sqledit::Entry;
        let mut parts = line.split_whitespace();
        let cmd = parts.next().unwrap_or("").to_lowercase();
        let args: Vec<&str> = parts.collect();
        let arg = |i: usize| args.get(i).copied();
        let on_off = |v: Option<&str>, current: bool| match v {
            Some("on") | Some("yes") | Some("1") => true,
            Some("off") | Some("no") | Some("0") => false,
            _ => !current,
        };

        let note: Vec<String> = match cmd.as_str() {
            ".help" => DOT_HELP.lines().map(str::to_string).collect(),
            ".tables" => match self.sqlite() {
                Some(s) => s.tables.clone(),
                None => return,
            },
            ".schema" => {
                let only = arg(0);
                match self.sqlite().map(|s| s.schema()) {
                    Some(Ok(objects)) => objects
                        .into_iter()
                        .filter(|(_, name, _)| only.is_none_or(|o| o.eq_ignore_ascii_case(name)))
                        .flat_map(|(_, _, sql)| {
                            let mut lines: Vec<String> = sql.lines().map(str::to_string).collect();
                            lines.push(";".into());
                            lines
                        })
                        .collect(),
                    Some(Err(e)) => vec![format!("{e}")],
                    None => return,
                }
            }
            ".indexes" => {
                let table = match arg(0).map(str::to_string).or_else(|| self.current_table()) {
                    Some(t) => t,
                    None => return,
                };
                match self.sqlite().map(|s| s.indexes(&table)) {
                    Some(Ok(list)) if list.is_empty() => vec![format!("{table}: no indexes")],
                    Some(Ok(list)) => list
                        .into_iter()
                        .map(|(name, cols)| format!("{name}  ({})", cols.join(", ")))
                        .collect(),
                    Some(Err(e)) => vec![format!("{e}")],
                    None => return,
                }
            }
            ".dump" => match self.sqlite().map(|s| s.dump(arg(0))) {
                Some(Ok(text)) => text.lines().map(str::to_string).collect(),
                Some(Err(e)) => vec![format!("{e}")],
                None => return,
            },
            ".databases" => match self.sqlite().map(|s| s.databases()) {
                Some(Ok(list)) => list
                    .into_iter()
                    .map(|(alias, file)| format!("{alias:<10} {file}"))
                    .collect(),
                Some(Err(e)) => vec![format!("{e}")],
                None => return,
            },
            ".attach" => match (arg(0), arg(1)) {
                (Some(file), Some(alias)) => {
                    match self
                        .sqlite()
                        .map(|s| s.attach(std::path::Path::new(file), alias))
                    {
                        Some(Ok(())) => vec![format!("attached {file} as {alias}")],
                        Some(Err(e)) => vec![format!("{e}")],
                        None => return,
                    }
                }
                _ => vec!["usage: .attach FILE ALIAS".into()],
            },
            ".detach" => match (arg(0), self.sqlite()) {
                (Some(alias), Some(s)) => match s.detach(alias) {
                    Ok(()) => vec![format!("detached {alias}")],
                    Err(e) => vec![format!("{e}")],
                },
                (None, _) => vec!["usage: .detach ALIAS".into()],
                _ => return,
            },
            ".mode" => match arg(0) {
                Some(name) => match OutputMode::parse(name) {
                    Some(m) => {
                        self.sql_mode = m;
                        vec![format!("mode: {}", m.label())]
                    }
                    None => vec![format!(
                        "unknown mode {name:?} — list csv tsv markdown line insert json"
                    )],
                },
                None => vec![format!("mode: {}", self.sql_mode.label())],
            },
            ".headers" => {
                self.sql_headers = on_off(arg(0), self.sql_headers);
                vec![format!(
                    "headers: {}",
                    if self.sql_headers { "on" } else { "off" }
                )]
            }
            ".timer" => {
                self.sql_timer = on_off(arg(0), self.sql_timer);
                vec![format!(
                    "timer: {}",
                    if self.sql_timer { "on" } else { "off" }
                )]
            }
            ".eqp" => {
                self.sql_eqp = on_off(arg(0), self.sql_eqp);
                vec![format!("eqp: {}", if self.sql_eqp { "on" } else { "off" })]
            }
            ".output" | ".once" => match arg(0) {
                Some(file) => {
                    let path = PathBuf::from(file);
                    // The shell opens the file fresh and then collects into it, so
                    // truncate here and append per result.
                    match std::fs::write(&path, b"") {
                        Ok(()) => {
                            self.sql_out = Some((path, cmd == ".once"));
                            vec![format!(
                                "{} results to {file}",
                                if cmd == ".once" { "next" } else { "all" }
                            )]
                        }
                        Err(e) => vec![format!("cannot write {file}: {e}")],
                    }
                }
                None => {
                    self.sql_out = None;
                    vec!["output: the transcript".into()]
                }
            },
            ".import" => match (arg(0), arg(1)) {
                (Some(file), Some(table)) => self.import_file(file, table),
                _ => vec!["usage: .import FILE TABLE".into()],
            },
            ".read" => match arg(0) {
                Some(file) => match std::fs::read_to_string(file) {
                    Ok(text) => {
                        // Each statement runs as if typed, so a script's results and
                        // errors land in the transcript in order.
                        let statements: Vec<String> = text
                            .split(';')
                            .map(str::trim)
                            .filter(|s| !s.is_empty())
                            .map(str::to_string)
                            .collect();
                        let n = statements.len();
                        for stmt in statements {
                            self.execute_sql(&stmt);
                        }
                        vec![format!(
                            "ran {n} statement{} from {file}",
                            if n == 1 { "" } else { "s" }
                        )]
                    }
                    Err(e) => vec![format!("cannot read {file}: {e}")],
                },
                None => vec!["usage: .read FILE".into()],
            },
            ".backup" => match (arg(0), self.sqlite()) {
                (Some(file), Some(s)) => {
                    let dest = std::path::Path::new(file);
                    if dest.exists() {
                        vec![format!("{file} already exists")]
                    } else {
                        match s.backup_to(dest) {
                            Ok(()) => vec![format!("wrote {file}")],
                            Err(e) => vec![format!("{e}")],
                        }
                    }
                }
                (None, _) => vec!["usage: .backup FILE".into()],
                _ => return,
            },
            ".recover" => {
                // The script is far too long to read in a transcript, so it goes
                // to a file and the transcript gets the tally.
                let path = match self.sqlite() {
                    Some(s) => s.path.clone(),
                    None => return,
                };
                match crate::recover::recover(&path) {
                    Ok(found) => {
                        let sql = crate::recover::to_sql(&found);
                        let dest = arg(0)
                            .map(PathBuf::from)
                            .unwrap_or_else(|| PathBuf::from("recovered.sql"));
                        let mut lines = vec![format!(
                            "{} rows across {} tables, {} in lost_and_found",
                            found.rows.len(),
                            found.tables.len(),
                            found.orphans()
                        )];
                        lines.extend(found.notes.clone());
                        match std::fs::write(&dest, sql.as_bytes()) {
                            Ok(()) => lines.push(format!("script written to {}", dest.display())),
                            Err(e) => lines.push(format!("cannot write {}: {e}", dest.display())),
                        }
                        lines
                    }
                    Err(e) => vec![format!("recover failed: {e}")],
                }
            }
            ".expert" => {
                // The advice is about the statement above, which is the one the
                // transcript last ran.
                let last = self
                    .sql
                    .as_ref()
                    .and_then(|e| e.last_statement())
                    .unwrap_or_default();
                if last.is_empty() {
                    vec![".expert: run a statement first, then ask about it".into()]
                } else {
                    match self.sqlite().map(|s| s.index_advice(&last)) {
                        Some(Ok(advice)) if advice.is_empty() => {
                            vec![format!("{last}: the planner scans nothing in full")]
                        }
                        Some(Ok(advice)) => advice,
                        Some(Err(e)) => vec![format!("{e}")],
                        None => return,
                    }
                }
            }
            ".vacuum" | ".analyze" | ".reindex" => {
                let op = match cmd.as_str() {
                    ".vacuum" => crate::sqlite::Maintenance::Vacuum,
                    ".analyze" => crate::sqlite::Maintenance::Analyze,
                    _ => crate::sqlite::Maintenance::Reindex,
                };
                match self.sqlite().map(|s| s.maintain(op)) {
                    Some(Ok(delta)) => vec![format!(
                        "{}: done, {}",
                        op.label(),
                        if delta == 0 {
                            "no change in size".to_string()
                        } else if delta < 0 {
                            format!("{} smaller", human_size((-delta) as u64))
                        } else {
                            format!("{} larger", human_size(delta as u64))
                        }
                    )],
                    Some(Err(e)) => vec![format!("{e}")],
                    None => return,
                }
            }
            ".quit" | ".exit" => {
                self.quit = true;
                return;
            }
            other => vec![format!("unknown command {other:?} — .help lists them")],
        };
        if let Some(e) = self.sql.as_mut() {
            e.push(Entry::Note(note));
        }
    }

    /// `.import FILE TABLE`, sharing the reader and the insert path with the
    /// `--import` flag.
    fn import_file(&mut self, file: &str, table: &str) -> Vec<String> {
        let text = match std::fs::read_to_string(file) {
            Ok(t) => t,
            Err(e) => return vec![format!("cannot read {file}: {e}")],
        };
        let sep = match std::path::Path::new(file)
            .extension()
            .and_then(|e| e.to_str())
        {
            Some("tsv") | Some("tab") => '\t',
            _ => ',',
        };
        let csv = match crate::import::parse(&text, sep) {
            Ok(c) => c,
            Err(e) => return vec![format!("{file}: {e}")],
        };
        let done = match self.sqlite() {
            Some(s) => s.import_rows(table, &csv.header, &csv.rows),
            None => return Vec::new(),
        };
        match done {
            Ok(n) => {
                self.load_table();
                vec![format!("imported {n} rows into {table}")]
            }
            Err(e) => vec![format!("{e}")],
        }
    }

    /// Write a result set to wherever `.output` / `.once` points, returning what to
    /// report. `None` when no redirect is active, which leaves the transcript to
    /// show the result itself.
    fn write_result(
        &mut self,
        columns: &[String],
        rows: &[Vec<String>],
        literals: &[Vec<String>],
    ) -> Option<String> {
        let (path, once) = self.sql_out.clone()?;
        let text = self.sql_mode.render(
            columns,
            rows,
            literals,
            &self.current_table().unwrap_or_else(|| "table".into()),
            self.sql_headers,
        );
        // A redirect collects every result until it is reset, as the shell's
        // `.output` does — so the second statement must not erase the first.
        let note = match append_to(&path, text.as_bytes()) {
            Ok(()) => format!(
                "wrote {} row{} to {} as {}",
                rows.len(),
                if rows.len() == 1 { "" } else { "s" },
                path.display(),
                self.sql_mode.label()
            ),
            Err(e) => format!("cannot write {}: {e}", path.display()),
        };
        if once {
            self.sql_out = None;
        }
        Some(note)
    }

    fn key_top(&mut self, code: KeyCode) {
        let action = match self.top.as_mut() {
            Some(m) => m.on_key(code, self.page_rows.max(1)),
            None => {
                self.screen = Screen::Main;
                return;
            }
        };
        if let Some(note) = self.top.as_mut().and_then(|m| m.note.take()) {
            self.notify(note);
        }
        match action {
            crate::monitor::Action::None => {}
            crate::monitor::Action::Back => {
                self.top = None;
                self.screen = Screen::Main;
            }
            crate::monitor::Action::Quit => self.quit = true,
            // Opening from the monitor leaves the app the way `o` does, with the
            // chosen file carried out.
            crate::monitor::Action::Open(path) => {
                self.open_next = Some(path);
                self.back_to_files();
            }
            crate::monitor::Action::Frames(path) => self.open_frames(&path),
        }
    }

    /// Open the log walker for `path`. Column names come from the open database
    /// when it is the same file, so a decoded row can be labelled.
    fn open_frames(&mut self, path: &std::path::Path) {
        let columns: std::collections::HashMap<String, Vec<String>> = match self.sqlite() {
            Some(s) if s.path == path => s.schema_names().into_iter().collect(),
            _ => match crate::sqlite::SqliteStore::open(path) {
                Ok(s) => s.schema_names().into_iter().collect(),
                Err(_) => Default::default(),
            },
        };
        match crate::frames::FrameView::open(path, columns) {
            Some(view) => {
                let n = view.frames.len();
                self.walk = Some(view);
                self.screen = Screen::Frames;
                self.status =
                    format!("{n} frames · j/k step · [ ] commits · Esc back to the monitor");
            }
            None => self.notify("no write-ahead log to walk (journal_mode is not WAL)"),
        }
    }

    fn key_frames(&mut self, code: KeyCode) {
        let page = self.page_rows.max(1);
        let action = match self.walk.as_mut() {
            Some(w) => w.on_key(code, page),
            None => {
                self.screen = Screen::Top;
                return;
            }
        };
        match action {
            crate::frames::Action::None => {}
            crate::frames::Action::Back => {
                self.walk = None;
                // Back to the monitor it was opened from, which is still there.
                self.screen = Screen::Top;
            }
            crate::frames::Action::Quit => self.quit = true,
        }
    }

    fn render_hex(&mut self, f: &mut Frame, area: Rect) {
        let theme = self.ov.theme;
        self.hex_area = area;
        if let Some(ed) = self.hex.as_mut() {
            ed.render(f, area, &theme);
        }
    }

    fn render_schema(&self, f: &mut Frame, area: Rect) {
        let mut lines: Vec<Line> = Vec::new();
        for (ty, name, sql) in &self.schema {
            lines.push(Line::from(vec![
                Span::styled(format!("{:<6}", ty), Style::default().fg(self.ov.theme.alt)),
                Span::styled(name.clone(), Style::default().add_modifier(Modifier::BOLD)),
            ]));
            for l in sql.lines() {
                lines.push(Line::from(Span::styled(
                    format!("    {}", l),
                    Style::default().fg(self.ov.theme.dim),
                )));
            }
            lines.push(Line::from(""));
        }
        let height = area.height.saturating_sub(2) as usize;
        let visible: Vec<Line> = lines
            .into_iter()
            .skip(self.schema_scroll)
            .take(height)
            .collect();
        f.render_widget(
            Paragraph::new(visible).block(Block::default().borders(Borders::ALL).title(format!(
                " schema — {} objects (j/k scroll · Esc back) ",
                self.schema.len()
            ))),
            area,
        );
    }

    fn render_sqlite(&mut self, f: &mut Frame, area: Rect) {
        let cols = Layout::horizontal([Constraint::Length(24), Constraint::Min(10)]).split(area);
        let (rect_left, rect_right) = (cols[0], cols[1]);

        let s = self.sqlite().unwrap();
        // Left: the tables the filter leaves listed.
        let visible: Vec<usize> = s
            .tables
            .iter()
            .enumerate()
            .filter(|(_, t)| filter_passes(&self.filter, t))
            .map(|(i, _)| i)
            .collect();
        // A table whose virtual-table module this binary does not have — an FTS
        // index built with a custom tokenizer, say — cannot be read by anyone, so
        // it is marked rather than left to fail on selection.
        let items: Vec<ListItem> = visible
            .iter()
            .map(|&i| {
                let name = &s.tables[i];
                ListItem::new(match s.unreadable_reason(name) {
                    Some(_) => format!("{name}"),
                    None => name.clone(),
                })
            })
            .collect();
        let mut lstate = ListState::default();
        lstate.select(
            visible
                .iter()
                .position(|&i| i == self.table_idx)
                .or(Some(0)),
        );
        let left_border = self.pane_style(Focus::Left);
        let list = List::new(items)
            .block(
                Block::default()
                    .borders(Borders::ALL)
                    .border_style(left_border)
                    .title(if self.filter.is_empty() {
                        format!(
                            " {} — tables ({}) ",
                            s.path.file_name().and_then(|n| n.to_str()).unwrap_or("db"),
                            s.tables.len()
                        )
                    } else {
                        format!(
                            " tables {}/{}  /{} ",
                            visible.len(),
                            s.tables.len(),
                            self.filter
                        )
                    }),
            )
            .highlight_style(Style::default().add_modifier(Modifier::REVERSED));
        f.render_stateful_widget(list, cols[0], &mut lstate);
        let off_left = lstate.selected().map(|_| lstate.offset()).unwrap_or(0);
        let mut off_right = 0usize;

        // Right: row grid.
        let title = match self.current_table() {
            Some(t) => {
                let (total, exact) = self
                    .rows
                    .as_ref()
                    .map(|r| (r.total, r.total_exact))
                    .unwrap_or((0, true));
                let sorted = match &self.sort {
                    Some(s) => format!(" — sorted {} {}", s.column, arrow(s.desc)),
                    None => String::new(),
                };
                // `500+` rather than a wrong number: counting the rest is a full
                // scan, so it runs in the background and the title firms up when
                // it lands. The trailing `…` says that scan is still running.
                let of = match (exact, self.counting()) {
                    (true, _) => total.to_string(),
                    (false, true) => format!("{total}+ …"),
                    (false, false) => format!("{total}+"),
                };
                // Work that outran its grace period is still coming.
                let loading = match (self.loading(), self.searching()) {
                    (_, true) => " · searching",
                    (true, false) => " · loading",
                    (false, false) => "",
                };
                format!(
                    " {} — rows {}..{} of {}{}{} ",
                    t,
                    self.page_offset,
                    self.page_offset + self.rows.as_ref().map(|r| r.rows.len() as i64).unwrap_or(0),
                    of,
                    sorted,
                    loading
                )
            }
            None => " (no table) ".into(),
        };

        if let Some(rv) = &self.rows {
            let header = Row::new(
                rv.columns
                    .iter()
                    .enumerate()
                    .map(|(i, c)| {
                        let st = if i == self.col_idx && self.focus == Focus::Right {
                            Style::default()
                                .fg(self.ov.theme.accent)
                                .add_modifier(Modifier::BOLD)
                        } else {
                            Style::default().add_modifier(Modifier::BOLD)
                        };
                        // Mark the sorted column in its header.
                        let label = match &self.sort {
                            Some(s) if s.column == *c => format!("{} {}", c, arrow(s.desc)),
                            _ => c.clone(),
                        };
                        Cell::from(label).style(st)
                    })
                    .collect::<Vec<_>>(),
            );
            let body = rv.rows.iter().map(|row| {
                Row::new(
                    row.iter()
                        .map(|c| Cell::from(truncate(c, 40)))
                        .collect::<Vec<_>>(),
                )
            });
            let widths: Vec<Constraint> =
                rv.columns.iter().map(|_| Constraint::Length(20)).collect();
            let mut tstate = TableState::default();
            tstate.select(Some(self.row_idx));
            let table = Table::new(body, widths)
                .header(header)
                .block(
                    Block::default()
                        .borders(Borders::ALL)
                        .border_style(self.pane_style(Focus::Right))
                        .title(title),
                )
                .row_highlight_style(Style::default().add_modifier(Modifier::REVERSED));
            f.render_stateful_widget(table, cols[1], &mut tstate);
            off_right = tstate.offset();
        } else {
            let p = Paragraph::new("no rows").block(
                Block::default()
                    .borders(Borders::ALL)
                    .border_style(self.pane_style(Focus::Right))
                    .title(title),
            );
            f.render_widget(p, cols[1]);
        }

        // Capture hit-test geometry for mouse clicks.
        self.click_left = rect_left;
        self.click_right = rect_right;
        self.off_left = off_left;
        self.off_right = off_right;
    }

    fn render_rkyv(&mut self, f: &mut Frame, area: Rect) {
        // Records mutates click geometry, so handle it before borrowing the store.
        if self.rkyv_view == RkyvView::Records {
            self.render_rkyv_records(f, area);
            return;
        }
        let r = match &self.store {
            Store::Rkyv(r) => r,
            _ => return,
        };
        match self.rkyv_view {
            RkyvView::Info => self.render_rkyv_info(f, area, r),
            RkyvView::Strings => self.render_rkyv_strings(f, area),
            RkyvView::Hex => self.render_rkyv_hex(f, area, r),
            RkyvView::Records => {}
        }
    }

    fn render_rkyv_records(&mut self, f: &mut Frame, area: Rect) {
        let cols =
            Layout::horizontal([Constraint::Percentage(45), Constraint::Min(10)]).split(area);
        self.click_records = cols[0];
        let d = match &self.decoded {
            Some(d) => d,
            None => return,
        };

        // Left: keys the filter leaves listed.
        let visible: Vec<usize> = d
            .records
            .iter()
            .enumerate()
            .filter(|(_, r)| filter_passes(&self.filter, &r.key))
            .map(|(i, _)| i)
            .collect();
        let items: Vec<ListItem> = visible
            .iter()
            .map(|&i| ListItem::new(truncate(&d.records[i].key, 60)))
            .collect();
        let mut st = ListState::default();
        st.select(
            visible
                .iter()
                .position(|&i| i == self.record_idx)
                .or(Some(0)),
        );
        let title = if self.filter.is_empty() {
            format!(" {}{} keys ", d.format, d.records.len())
        } else {
            format!(
                " {}{}/{} keys  /{} ",
                d.format,
                visible.len(),
                d.records.len(),
                self.filter
            )
        };
        let list = List::new(items)
            .block(
                Block::default()
                    .borders(Borders::ALL)
                    .border_style(Style::default().fg(self.ov.theme.accent))
                    .title(title),
            )
            .highlight_style(Style::default().add_modifier(Modifier::REVERSED));
        f.render_stateful_widget(list, cols[0], &mut st);
        let off_records = st.offset();

        // Right: selected value — decoded scalar fields, then a hex dump.
        let mut lines: Vec<Line> = Vec::new();
        if let Some(rec) = d.records.get(self.record_idx) {
            for (name, val) in &rec.fields {
                lines.push(Line::from(vec![
                    Span::styled(
                        format!("{:<22}", name),
                        Style::default().fg(self.ov.theme.dim),
                    ),
                    Span::raw(val.clone()),
                ]));
            }
            lines.push(Line::from(""));
            lines.push(Line::from(Span::styled(
                format!("value — {} bytes (hex):", rec.value.len()),
                Style::default().fg(self.ov.theme.primary),
            )));
            let rows = area.height.saturating_sub(6) as usize;
            for i in 0..rows {
                let off = i * 16;
                if off >= rec.value.len() {
                    break;
                }
                lines.push(Line::from(hexedit::hex_dump_line(
                    off,
                    &rec.value[off.min(rec.value.len())..(off + 16).min(rec.value.len())],
                )));
            }
        }
        let p =
            Paragraph::new(lines).block(Block::default().borders(Borders::ALL).title(" value "));
        f.render_widget(p, cols[1]);
        self.off_records = off_records;
    }

    fn render_rkyv_info(&self, f: &mut Frame, area: Rect, r: &RkyvStore) {
        let mut lines = vec![
            Line::from(vec![
                Span::styled("file:    ", Style::default().fg(self.ov.theme.dim)),
                Span::raw(r.path.display().to_string()),
            ]),
            Line::from(vec![
                Span::styled("size:    ", Style::default().fg(self.ov.theme.dim)),
                Span::raw(format!("{} bytes", r.len())),
            ]),
            Line::from(vec![
                Span::styled("strings: ", Style::default().fg(self.ov.theme.dim)),
                Span::raw(if self.strings_truncated {
                    // Say so rather than implying the list is everything.
                    format!(
                        "{} runs (>= {} printable bytes) — capped, scanned first {}",
                        self.strings.len(),
                        MIN_STRING,
                        human_size(self.strings_scanned as u64)
                    )
                } else {
                    format!(
                        "{} runs (>= {} printable bytes)",
                        self.strings.len(),
                        MIN_STRING
                    )
                }),
            ]),
        ];

        match &self.decoded {
            Some(d) => {
                lines.push(Line::from(""));
                lines.push(Line::from(vec![
                    Span::styled("format:  ", Style::default().fg(self.ov.theme.dim)),
                    Span::styled(d.format.clone(), Style::default().fg(self.ov.theme.label)),
                ]));
                lines.push(Line::from(vec![
                    Span::styled("records: ", Style::default().fg(self.ov.theme.dim)),
                    Span::raw(d.records.len().to_string()),
                ]));
                lines.push(Line::from(""));
                for (name, val) in &d.header {
                    lines.push(Line::from(vec![
                        Span::styled(
                            format!("  {:<16}", name),
                            Style::default().fg(self.ov.theme.dim),
                        ),
                        Span::raw(val.clone()),
                    ]));
                }
                lines.push(Line::from(""));
                lines.push(Line::from(Span::styled(
                    "Views:  0 Records (key/value)  2 Strings  3 Hex",
                    Style::default().fg(self.ov.theme.dim),
                )));
            }
            None => {
                lines.push(Line::from(""));
                lines.push(Line::from(Span::styled(
                    "unrecognized rkyv archive: no matching format decoder.",
                    Style::default().fg(self.ov.theme.primary),
                )));
                lines.push(Line::from(Span::styled(
                    "rkyv stores no field names or type tags, so an unknown type",
                    Style::default().fg(self.ov.theme.primary),
                )));
                lines.push(Line::from(Span::styled(
                    "cannot be decoded generically — showing raw structure.",
                    Style::default().fg(self.ov.theme.primary),
                )));
                lines.push(Line::from(Span::styled(
                    "Views:  2 Strings (embedded text)  3 Hex (raw bytes)",
                    Style::default().fg(self.ov.theme.dim),
                )));
            }
        }
        let p = Paragraph::new(lines).block(
            Block::default()
                .borders(Borders::ALL)
                .title(" rkyv / binary — Info "),
        );
        f.render_widget(p, area);
    }

    fn render_rkyv_strings(&self, f: &mut Frame, area: Rect) {
        let visible = self.visible_strings();
        let items: Vec<ListItem> = visible
            .iter()
            .map(|&i| {
                let h = &self.strings[i];
                ListItem::new(Line::from(vec![
                    Span::styled(
                        format!("{:08x}  ", h.offset),
                        Style::default().fg(self.ov.theme.dim),
                    ),
                    Span::raw(truncate(&h.text, 200)),
                ]))
            })
            .collect();
        let mut st = ListState::default();
        st.select(
            visible
                .iter()
                .position(|&i| i == self.string_idx)
                .or(Some(0)),
        );
        let capped = if self.strings_truncated { "+" } else { "" };
        let title = if self.filter.is_empty() {
            format!(" Strings ({}{}) ", self.strings.len(), capped)
        } else {
            format!(
                " Strings ({}/{}{})  /{} ",
                visible.len(),
                self.strings.len(),
                capped,
                self.filter
            )
        };
        let list = List::new(items)
            .block(Block::default().borders(Borders::ALL).title(title))
            .highlight_style(Style::default().add_modifier(Modifier::REVERSED));
        f.render_stateful_widget(list, area, &mut st);
    }

    fn render_rkyv_hex(&self, f: &mut Frame, area: Rect, r: &RkyvStore) {
        let rows_visible = area.height.saturating_sub(2) as usize;
        let start = self.hex_row * 16;
        let mut lines = Vec::new();
        for i in 0..rows_visible {
            let off = start + i * 16;
            if off >= r.len() {
                break;
            }
            lines.push(Line::from(r.hex_row(off)));
        }
        let p = Paragraph::new(lines).block(Block::default().borders(Borders::ALL).title(format!(
            " Hex — offset {:#x} / {} bytes ",
            start,
            r.len()
        )));
        f.render_widget(p, area);
    }

    fn render_status(&self, f: &mut Frame, area: Rect) {
        let p = Paragraph::new(self.status.clone())
            .style(Style::default().fg(Color::Black).bg(Color::Gray));
        f.render_widget(p, area);
    }

    fn render_input(&self, f: &mut Frame, title: &str, buf: &str) {
        let area = centered(f.area(), 60, 3);
        f.render_widget(Clear, area);
        // Draw the buffer with a reversed block cursor over the char at the
        // cursor (or a trailing space when the cursor is at the end).
        let cur = self.input_cursor.min(buf.len());
        let (pre, rest) = buf.split_at(cur);
        let (at, post) = match rest.char_indices().nth(1) {
            Some((i, _)) => rest.split_at(i),
            None => (rest, ""),
        };
        let at_disp = if at.is_empty() { " " } else { at };
        let line = Line::from(vec![
            Span::raw(pre.to_string()),
            Span::styled(
                at_disp.to_string(),
                Style::default().add_modifier(Modifier::REVERSED),
            ),
            Span::raw(post.to_string()),
        ]);
        let p = Paragraph::new(line).block(
            Block::default()
                .borders(Borders::ALL)
                .border_style(Style::default().fg(self.ov.theme.accent))
                .title(format!(" {} ", title)),
        );
        f.render_widget(p, area);
    }

    fn pane_style(&self, which: Focus) -> Style {
        if self.focus == which {
            Style::default().fg(self.ov.theme.accent)
        } else {
            Style::default().fg(self.ov.theme.dim)
        }
    }
}

/// Recent-files picker shown when zdbview is launched with no file argument.
/// Returns the chosen file, or `None` if the user quits.
/// One row of the picker: a remembered file, or one the startup scan found.
pub struct Choice {
    pub path: PathBuf,
    pub kind: Kind,
    /// When this file was last opened (recent files only).
    pub opened: Option<std::time::SystemTime>,
    /// Recognized rkyv format, when the scan's magic sniff named one.
    pub format: Option<&'static str>,
    /// File size, for scan hits (recent rows show their age instead).
    pub size: Option<u64>,
    /// Last modification time, used to order scan hits newest-first.
    pub modified: Option<std::time::SystemTime>,
    /// Scan display priority (see `scan::Hit::rank`).
    rank: u8,
}

impl Choice {
    fn from_entry(e: &Entry) -> Self {
        Choice {
            path: e.path.clone(),
            kind: e.kind,
            opened: Some(e.opened),
            format: None,
            size: None,
            modified: None,
            rank: 0,
        }
    }

    fn from_hit(h: crate::scan::Hit) -> Self {
        Choice {
            path: h.path,
            kind: h.kind,
            opened: None,
            format: h.format,
            size: Some(h.size),
            modified: Some(h.modified),
            rank: h.rank,
        }
    }

    fn name(&self) -> &str {
        self.path
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or("?")
    }
}

/// What the picker returned: the file to open and the scheme it was showing.
pub struct Picked {
    pub path: PathBuf,
    pub theme: Theme,
}

/// The path a row is recognized by: symlinks resolved, so the same file reached
/// two ways is one row, falling back to the path itself when it cannot be
/// resolved (a file that has gone away is still worth listing once).
fn canon(path: &Path) -> PathBuf {
    path.canonicalize().unwrap_or_else(|_| path.to_path_buf())
}

/// Merge scan hits into the list, dropping any path already present (a recent
/// file the scan also found stays a recent file, keeping its age column).
///
/// `seen` holds the resolved path of every row already listed. It is the caller's
/// so the resolution is paid once per row: an index of the whole disk is hundreds
/// of rows, merged again on every return to the picker and once per frame while a
/// walk streams, and resolving each listed row against each incoming hit made
/// coming back from a file take most of a second.
fn merge_hits(choices: &mut Vec<Choice>, seen: &mut HashSet<PathBuf>, hits: Vec<crate::scan::Hit>) {
    for hit in hits {
        if seen.insert(canon(&hit.path)) {
            choices.push(Choice::from_hit(hit));
        }
    }
    // Recent files keep their recency order at the top. Scan hits below them go
    // by rank first (recognized shards, then other rkyv archives, then
    // databases), newest-first within a rank, shallowest path breaking ties.
    let first_scanned = choices
        .iter()
        .position(|c| c.opened.is_none())
        .unwrap_or(choices.len());
    choices[first_scanned..].sort_by_key(|c| {
        (
            c.rank,
            std::cmp::Reverse(c.modified),
            c.path.components().count(),
        )
    });
}

/// Everything the picker needs: the remembered files, the scheme override, and
/// where its scan rows come from.
pub struct Picker<'a> {
    pub recent: &'a [Entry],
    /// The scheme to show. Carried from the previous screen when there was one,
    /// so a concurrent prefs write cannot change it mid-session.
    pub theme: Theme,
    /// Rows restored from the saved scan (appdata), shown immediately.
    pub cached: Vec<crate::scan::Hit>,
    /// How old those rows are, for the title.
    pub cache_age: Option<std::time::Duration>,
    /// A walk already in progress, when the index was missing or out of date.
    pub scan: Option<crate::scan::Scan>,
    /// The roots that walk was given: the changed directories when it is a
    /// refresh, the default set otherwise.
    pub walking: Vec<crate::scan::Root>,
    /// Whether that walk is a refresh of an index that is otherwise complete.
    pub refresh: bool,
    /// Roots to walk when the user asks for a rescan with `r`.
    pub roots: Vec<crate::scan::Root>,
    /// Whether a finished walk may be written to appdata (not for `--scan`,
    /// whose roots are not the default set).
    pub persist: bool,
}

/// The walk currently running, and what kind it is.
struct Walking {
    scan: Option<crate::scan::Scan>,
    /// The roots this walk was given: the changed directories for a refresh, the
    /// default set for a full walk.
    roots: Vec<crate::scan::Root>,
    /// Whether the index being updated is otherwise complete, i.e. this walk is
    /// a refresh rather than a walk of everything.
    refresh: bool,
    /// The default root set, watched by the index whatever this walk covers.
    default: Vec<crate::scan::Root>,
}

impl Walking {
    /// Every directory the saved index watches: the default roots, plus whatever
    /// this walk covered.
    fn watched(&self) -> Vec<crate::scan::Root> {
        let mut all = self.default.clone();
        all.extend(self.roots.iter().cloned());
        all
    }

    /// Write the index as it stands after a walk that ran to the end.
    fn save_finished(&self, hits: &[crate::scan::Hit]) {
        crate::scan::save_cache(crate::scan::Save {
            hits,
            roots: &self.watched(),
            complete: true,
            unfinished: &[],
        });
    }
}

/// Stop a walk that is still running and keep what it found so far.
///
/// A walk of the whole filesystem takes minutes, so throwing it away because a
/// file was picked in the first second means paying for all of it again on the
/// next start. What the save records depends on which walk was cut short: a
/// refresh leaves the index whole and re-flags only the directories it did not
/// finish reading, while a full walk that never finished has to run again.
fn park_scan(walk: &mut Walking, scanned: &mut Vec<crate::scan::Hit>, persist: bool) {
    let Some(sc) = walk.scan.as_mut() else { return };
    sc.cancel();
    scanned.extend(sc.drain());
    if persist && !scanned.is_empty() {
        crate::scan::save_cache(crate::scan::Save {
            hits: scanned,
            roots: &walk.watched(),
            complete: walk.refresh,
            unfinished: if walk.refresh { &walk.roots } else { &[] },
        });
    }
}

pub fn pick_mru(terminal: &mut DefaultTerminal, mut p: Picker<'_>) -> Result<Option<Picked>> {
    let entries = p.recent;
    let mut walk = Walking {
        scan: p.scan.take(),
        roots: std::mem::take(&mut p.walking),
        refresh: p.refresh,
        default: p.roots.clone(),
    };
    let mut cache_age = p.cache_age;
    // Hits are kept as well as merged so a finished walk can be saved.
    let mut scanned: Vec<crate::scan::Hit> = std::mem::take(&mut p.cached);
    // Recent files first, then whatever the scan turns up.
    let mut choices: Vec<Choice> = entries.iter().map(Choice::from_entry).collect();
    let mut listed: HashSet<PathBuf> = choices.iter().map(|c| canon(&c.path)).collect();
    merge_hits(&mut choices, &mut listed, scanned.clone());

    // `/` filters the list: `view` holds the indices still listed and `sel` is a
    // position within it, so navigation and clicks address rows that are visible.
    let mut filter = String::new();
    let mut typing = false;
    let mut sel = 0usize;
    let mut pending_g = false;
    // The row `/` was pressed on, restored when the filter is cancelled.
    let mut before_filter = 0usize;
    // First row the list drew last frame, for mapping a click to an entry.
    let mut list_offset = 0usize;
    // The write monitor, when `w` has opened it over the list.
    let mut monitor: Option<crate::monitor::Monitor> = None;

    // The picker carries the same overlay layer as the main screens, so `h`,
    // `c` and `C` work here too — and the scheme it is showing is the one the
    // opened file gets, handed over rather than re-read.
    let mut ov = Overlays::new(p.theme);

    loop {
        // Pull in whatever the scan thread produced since the last frame, and
        // save the finished list so the next start does not walk again.
        let scanning = match walk.scan.as_mut() {
            Some(sc) => {
                let hits = sc.drain();
                scanned.extend(hits.iter().cloned());
                merge_hits(&mut choices, &mut listed, hits);
                if sc.running {
                    Some(sc.found)
                } else {
                    if p.persist {
                        walk.save_finished(&scanned);
                        cache_age = Some(std::time::Duration::ZERO);
                    }
                    walk.scan = None;
                    None
                }
            }
            None => None,
        };

        // Rows the filter leaves listed, and a selection inside that list.
        let view: Vec<usize> = choices
            .iter()
            .enumerate()
            .filter(|(_, c)| filter_passes(&filter, c.path.to_str().unwrap_or("")))
            .map(|(i, _)| i)
            .collect();
        sel = sel.min(view.len().saturating_sub(1));

        // List height for paging: the body minus its borders.
        let page = terminal
            .size()
            .map(|s| s.height.saturating_sub(3) as usize)
            .unwrap_or(10)
            .max(1);
        let prompt = typing.then_some(filter.as_str());
        // The monitor takes the whole screen while it is up; the overlay layer
        // still draws on top of either.
        if let Some(m) = monitor.as_mut() {
            m.tick();
        }
        let ctx = if monitor.is_some() {
            HelpCtx::Top
        } else {
            HelpCtx::Picker
        };
        terminal.draw(|f| {
            match monitor.as_ref() {
                Some(m) => m.render(f, f.area(), &ov.theme),
                None => {
                    list_offset = render_picker(
                        f, &choices, &view, sel, &filter, prompt, scanning, cache_age, &ov.theme,
                    );
                }
            }
            ov.render(f, ctx);
        })?;
        if !event::poll(TICK)? {
            ov.expire_toast();
            continue;
        }
        let ev = event::read()?;
        ov.expire_toast();

        // While the monitor is up it owns the keys, except the overlay's own.
        if let Some(m) = monitor.as_mut() {
            match ev {
                Event::Key(key) if key.kind == KeyEventKind::Press => {
                    if ov.on_key(key.code) {
                        continue;
                    }
                    let size = terminal.size().unwrap_or_default();
                    let page = crate::monitor::Monitor::page_rows(Rect::new(
                        0,
                        0,
                        size.width,
                        size.height,
                    ));
                    let action = m.on_key(key.code, page);
                    if let Some(note) = m.note.take() {
                        ov.toast(note);
                    }
                    match action {
                        crate::monitor::Action::None => {}
                        crate::monitor::Action::Back => monitor = None,
                        crate::monitor::Action::Quit => {
                            park_scan(&mut walk, &mut scanned, p.persist);
                            return Ok(None);
                        }
                        crate::monitor::Action::Open(path) => {
                            park_scan(&mut walk, &mut scanned, p.persist);
                            return Ok(Some(Picked {
                                path,
                                theme: ov.theme,
                            }));
                        }
                        // The log walker lives on a file that is open, so from the
                        // picker `F` opens the database and lands in the monitor
                        // there instead of walking from nowhere.
                        crate::monitor::Action::Frames(path) => {
                            park_scan(&mut walk, &mut scanned, p.persist);
                            return Ok(Some(Picked {
                                path,
                                theme: ov.theme,
                            }));
                        }
                    }
                }
                Event::Mouse(mouse) if !ov.on_mouse(mouse) => {
                    let size = terminal.size().unwrap_or_default();
                    m.on_mouse(mouse, Rect::new(0, 0, size.width, size.height));
                    if let Some(note) = m.note.take() {
                        ov.toast(note);
                    }
                }
                _ => {}
            }
            continue;
        }

        let last = view.len().saturating_sub(1);
        let pick = |i: usize| -> Option<PathBuf> { view.get(i).map(|&c| choices[c].path.clone()) };

        // Mouse: wheel moves the selection, a click opens the entry under it.
        if let Event::Mouse(m) = ev {
            if ov.on_mouse(m) {
                continue;
            }
            match m.kind {
                MouseEventKind::ScrollDown => sel = (sel + 1).min(last),
                MouseEventKind::ScrollUp => sel = sel.saturating_sub(1),
                MouseEventKind::Down(_) => {
                    // The list starts one row below the block's top border and is
                    // scrolled by `list_offset`; rows past the last entry select
                    // nothing.
                    let row = (m.row as usize).saturating_sub(1);
                    let clicked = row + list_offset;
                    if row < page && clicked < view.len() {
                        park_scan(&mut walk, &mut scanned, p.persist);
                        // Hand over the scheme on screen, so the file opens in it.
                        return Ok(pick(clicked).map(|path| Picked {
                            path,
                            theme: ov.theme,
                        }));
                    }
                }
                _ => {}
            }
            continue;
        }
        if let Event::Key(key) = ev {
            if key.kind != KeyEventKind::Press {
                continue;
            }
            // Ctrl-f / Ctrl-b page like the app's grids do.
            if key.modifiers.contains(KeyModifiers::CONTROL) {
                match key.code {
                    KeyCode::Char('f') => sel = (sel + page).min(last),
                    KeyCode::Char('b') => sel = sel.saturating_sub(page),
                    _ => {}
                }
                continue;
            }

            // While the `/` prompt is open every key edits the filter, and the
            // list shrinks to the matches as it is typed.
            if typing {
                match filter_prompt_key(key.code, &mut filter, &mut sel, last, page) {
                    Prompt::Open => {}
                    Prompt::Accept => typing = false,
                    Prompt::Cancel => {
                        // Drop the filter and go back to the row `/` was pressed on.
                        typing = false;
                        filter.clear();
                        sel = before_filter;
                    }
                }
                continue;
            }

            // Overlay keys (open or drive: h/? c C) come before the picker's own.
            if ov.on_key(key.code) {
                continue;
            }

            if key.code == KeyCode::Char('g') {
                if pending_g {
                    pending_g = false;
                    sel = 0;
                } else {
                    pending_g = true;
                }
                continue;
            }
            pending_g = false;
            match key.code {
                // Esc clears an applied filter first, then quits.
                KeyCode::Esc if !filter.is_empty() => {
                    filter.clear();
                    sel = 0;
                }
                KeyCode::Char('q') | KeyCode::Esc => {
                    park_scan(&mut walk, &mut scanned, p.persist);
                    return Ok(None);
                }
                KeyCode::Char('/') => {
                    typing = true;
                    filter.clear();
                    before_filter = sel;
                    sel = 0;
                }
                // The same write monitor the app screens show, over the files
                // listed here plus the rest of the watched set.
                KeyCode::Char('w') => {
                    let mut targets: Vec<(PathBuf, Kind)> = view
                        .iter()
                        .map(|&i| (choices[i].path.clone(), choices[i].kind))
                        .collect();
                    targets.extend(watch_targets());
                    let m = crate::monitor::Monitor::new(targets);
                    if m.is_empty() {
                        ov.toast("nothing to watch yet");
                    } else {
                        ov.toast(format!("watching {} files for writes", m.len()));
                        monitor = Some(m);
                    }
                }
                // Within a filtered list every row matches, so n/N simply step.
                KeyCode::Char('n') => sel = (sel + 1).min(last),
                KeyCode::Char('N') => sel = sel.saturating_sub(1),
                // `r` walks again (keeping the rows on screen until new ones
                // arrive); `R` also drops the saved scan first.
                KeyCode::Char('r') | KeyCode::Char('R') => {
                    if key.code == KeyCode::Char('R') {
                        crate::scan::clear_cache();
                    }
                    // Not parked: a rescan replaces the index rather than adding
                    // to it, and `R` has just deleted the saved one on purpose.
                    if let Some(sc) = &walk.scan {
                        sc.cancel();
                    }
                    scanned.clear();
                    choices.retain(|c| c.opened.is_some());
                    listed = choices.iter().map(|c| canon(&c.path)).collect();
                    sel = 0;
                    cache_age = None;
                    // Everything again, from nothing: a walk of every root, whose
                    // result is the whole index rather than a patch to one.
                    walk.roots = p.roots.clone();
                    walk.refresh = false;
                    walk.scan = Some(crate::scan::spawn(p.roots.clone()));
                    ov.toast("rescanning");
                }
                KeyCode::Char('G') => sel = last,
                // A screenful, from the height this frame was drawn at.
                KeyCode::PageDown => sel = (sel + page).min(last),
                KeyCode::PageUp => sel = sel.saturating_sub(page),
                KeyCode::Up | KeyCode::Char('k') => sel = sel.saturating_sub(1),
                KeyCode::Down | KeyCode::Char('j') => sel = (sel + 1).min(last),
                KeyCode::Enter => {
                    if let Some(path) = pick(sel) {
                        // Nothing more to walk once a file is chosen.
                        park_scan(&mut walk, &mut scanned, p.persist);
                        return Ok(Some(Picked {
                            path,
                            theme: ov.theme,
                        }));
                    }
                }
                _ => {}
            }
        }
    }
}

/// Archives up to this size are decoded inline; bigger ones go to a thread.
/// 12MB takes ~0.8s to validate, 382MB takes ~25s, so the line sits below the
/// point where a person would notice the wait.
const DECODE_INLINE_MAX: usize = 4 * 1024 * 1024;

/// Append `bytes` to `path`, creating it if it is not there. `.output` collects
/// results until it is reset, and `.once` writes exactly one — which is the same
/// operation, since the file it writes to is fresh.
fn append_to(path: &std::path::Path, bytes: &[u8]) -> std::io::Result<()> {
    use std::io::Write;
    let mut f = std::fs::OpenOptions::new()
        .create(true)
        .append(true)
        .open(path)?;
    f.write_all(bytes)
}

/// What a background statistics pass returns: the columns, or why it could not.
type StatsResult = std::result::Result<Vec<crate::sqlite::ColumnStat>, String>;

/// Describe `table`'s columns on another thread, over a connection of its own —
/// `SqliteStore`'s connection belongs to the UI thread.
fn spawn_stats(path: std::path::PathBuf, table: String) -> std::sync::mpsc::Receiver<StatsResult> {
    let (tx, rx) = std::sync::mpsc::channel();
    std::thread::spawn(move || {
        let result = SqliteStore::open(&path)
            .and_then(|s| s.column_stats(&table))
            .map_err(|e| e.to_string());
        let _ = tx.send(result);
    });
    rx
}

/// Validate and decode `bytes` on another thread.
fn spawn_decode(bytes: std::sync::Arc<[u8]>) -> std::sync::mpsc::Receiver<Option<Decoded>> {
    let (tx, rx) = std::sync::mpsc::channel();
    std::thread::spawn(move || {
        let _ = tx.send(formats::try_decode(&bytes));
    });
    rx
}

/// What a key did to a `/` filter prompt. Shared by the picker and the write
/// monitor so both prompts behave identically.
#[derive(Debug, PartialEq, Eq)]
pub enum Prompt {
    /// Still typing.
    Open,
    /// Enter: keep the filter and close the prompt.
    Accept,
    /// Esc: discard it.
    Cancel,
}

/// Handle one key of a `/` filter prompt. The list stays navigable while the
/// pattern is typed, so the arrows and paging move the selection instead of being
/// swallowed; only Left/Right belong to the pattern itself.
pub fn filter_prompt_key(
    code: KeyCode,
    filter: &mut String,
    sel: &mut usize,
    last: usize,
    page: usize,
) -> Prompt {
    match code {
        KeyCode::Esc => return Prompt::Cancel,
        KeyCode::Enter => return Prompt::Accept,
        KeyCode::Backspace => {
            filter.pop();
            *sel = 0;
        }
        KeyCode::Up => *sel = sel.saturating_sub(1),
        KeyCode::Down => *sel = (*sel + 1).min(last),
        KeyCode::PageUp => *sel = sel.saturating_sub(page),
        KeyCode::PageDown => *sel = (*sel + page).min(last),
        KeyCode::Home => *sel = 0,
        KeyCode::End => *sel = last,
        KeyCode::Char(c) => {
            filter.push(c);
            // A changed pattern means a different list; start at its top.
            *sel = 0;
        }
        _ => {}
    }
    Prompt::Open
}

#[allow(clippy::too_many_arguments)]
fn render_picker(
    f: &mut Frame,
    choices: &[Choice],
    view: &[usize],
    sel: usize,
    filter: &str,
    prompt: Option<&str>,
    scanning: Option<usize>,
    cache_age: Option<std::time::Duration>,
    t: &Theme,
) -> usize {
    let outer = Layout::vertical([Constraint::Min(1), Constraint::Length(1)]).split(f.area());
    let mut offset = 0usize;

    if view.is_empty() {
        let body = if !filter.is_empty() {
            vec![
                Line::from(""),
                Line::from(format!("  Nothing matches /{}", filter)),
                Line::from(""),
                Line::from(Span::styled(
                    "  Esc clears the filter",
                    Style::default().fg(t.dim),
                )),
            ]
        } else if scanning.is_some() {
            vec![
                Line::from(""),
                Line::from("  Scanning for databases and rkyv shards…"),
            ]
        } else {
            vec![
                Line::from(""),
                Line::from("  Nothing found."),
                Line::from(""),
                Line::from(Span::styled(
                    "  Open one with:  zdbview <file>",
                    Style::default().fg(t.dim),
                )),
                Line::from(Span::styled(
                    "  Or scan elsewhere:  zdbview --scan <dir>",
                    Style::default().fg(t.dim),
                )),
            ]
        };
        let p = Paragraph::new(body).block(
            Block::default()
                .borders(Borders::ALL)
                .border_style(Style::default().fg(t.accent))
                .title(" zdbview — files "),
        );
        f.render_widget(p, outer[0]);
    } else {
        let items: Vec<ListItem> = view
            .iter()
            .map(|&i| {
                let c = &choices[i];
                let dir = c.path.parent().and_then(|p| p.to_str()).unwrap_or("");
                let (badge, color) = match c.kind {
                    Kind::Sqlite => ("sqlite", t.primary),
                    Kind::Rkyv => ("rkyv  ", t.alt),
                };
                // Recent files show their age; scanned ones their size.
                let (age, age_style) = match (c.opened, c.size) {
                    (Some(when), _) => (mru::rel_age(when), Style::default().fg(t.dim)),
                    (None, Some(size)) => (human_size(size), Style::default().fg(t.label)),
                    (None, None) => ("found".to_string(), Style::default().fg(t.label)),
                };
                ListItem::new(Line::from(vec![
                    Span::styled(format!(" {} ", badge), Style::default().fg(color)),
                    Span::styled(
                        format!("{:<28}", truncate(c.name(), 28)),
                        Style::default().fg(t.accent).add_modifier(Modifier::BOLD),
                    ),
                    Span::styled(format!("{:>10}  ", age), age_style),
                    Span::styled(truncate(dir, 52), Style::default().fg(t.label)),
                ]))
            })
            .collect();
        let mut st = ListState::default();
        st.select(Some(sel.min(view.len() - 1)));
        let recent = view
            .iter()
            .filter(|&&i| choices[i].opened.is_some())
            .count();
        let title = if !filter.is_empty() {
            // A filtered list says how much of the whole it is showing.
            format!(
                " zdbview — {}/{} files  /{} ",
                view.len(),
                choices.len(),
                filter
            )
        } else {
            match (scanning, cache_age) {
                (Some(found), _) => format!(
                    " zdbview — {} files ({} recent, scanning… {} found) ",
                    view.len(),
                    recent,
                    found
                ),
                // Saved scans are reused, so say how old the rows are.
                (None, Some(age)) => format!(
                    " zdbview — {} files ({} recent, scan {} · r rescans) ",
                    view.len(),
                    recent,
                    age_label(age)
                ),
                (None, None) => format!(" zdbview — {} files ({} recent) ", view.len(), recent),
            }
        };
        let list = List::new(items)
            .block(
                Block::default()
                    .borders(Borders::ALL)
                    .border_style(Style::default().fg(t.accent))
                    .title(title),
            )
            .highlight_style(Style::default().add_modifier(Modifier::REVERSED));
        f.render_stateful_widget(list, outer[0], &mut st);
        offset = st.offset();
    }

    // Bottom line: the filter prompt while typing, else the selected row's
    // format, else the keys.
    let help = match prompt {
        Some(q) => {
            Paragraph::new(format!("/{}_", q)).style(Style::default().fg(Color::Black).bg(t.accent))
        }
        None => {
            let detail = view
                .get(sel)
                .and_then(|&i| choices[i].format)
                .map(|fmt| format!("  ·  {}", fmt))
                .unwrap_or_default();
            // Kept short so the selected row's format still fits beside it on a
            // narrow terminal; `h` lists the rest.
            Paragraph::new(format!(
                "j/k move · / filter · Enter open · c scheme · h help · q quit{}",
                detail
            ))
            .style(Style::default().fg(Color::Black).bg(t.help_key))
        }
    };
    f.render_widget(help, outer[1]);
    offset
}

/// Everything the write monitor watches besides the open file: the recent-files
/// list and the saved scan. Shared by the app and the picker so both watch the
/// same set.
pub fn watch_targets() -> Vec<(PathBuf, Kind)> {
    let mut targets: Vec<(PathBuf, Kind)> = crate::mru::load()
        .into_iter()
        .map(|e| (e.path, e.kind))
        .collect();
    if let Some(c) = crate::scan::load_cache() {
        targets.extend(c.hits.into_iter().map(|h| (h.path, h.kind)));
    }
    targets.retain(|(p, _)| p.is_file());
    targets
}

/// The scheme to start from: `--theme` wins, else the saved preference (with any
/// custom palette), else the default.
pub fn resolve_theme(theme_override: Option<ThemeName>) -> Theme {
    let prefs = crate::prefs::load();
    match (theme_override, prefs.custom) {
        (Some(name), _) => Theme::from_name(name),
        (None, Some(c)) => Theme::from_palette(prefs.theme, c),
        (None, None) => Theme::from_name(prefs.theme),
    }
}

/// Whether `hay` passes `filter` (case-insensitive substring; empty passes all).
fn filter_passes(filter: &str, hay: &str) -> bool {
    filter.is_empty() || hay.to_lowercase().contains(&filter.to_lowercase())
}

/// Find the next index (wrapping) from `from` for which `pred` holds, scanning
/// `forward` or backward. Returns `None` if nothing matches.
/// `find_next` over a filtered list: `visible` holds the indices still listed, in
/// display order, and the walk wraps inside it. `from` is an index into the full
/// list — the cursor may sit on a row the filter has since hidden, in which case
/// the walk starts from where that row would be.
fn find_next_visible(
    visible: &[usize],
    from: usize,
    forward: bool,
    pred: impl Fn(usize) -> bool,
) -> Option<usize> {
    if visible.is_empty() {
        return None;
    }
    let pos = match visible.binary_search(&from) {
        Ok(p) => p,
        // Not listed: `p` is where it would sit, so stepping forward from `p - 1`
        // reaches it, and stepping back from `p` reaches the one before.
        Err(p) if forward => p.saturating_sub(1),
        Err(p) => p.min(visible.len() - 1),
    };
    find_next(visible.len(), pos, forward, |i| pred(visible[i])).map(|i| visible[i])
}

fn find_next(
    len: usize,
    from: usize,
    forward: bool,
    pred: impl Fn(usize) -> bool,
) -> Option<usize> {
    if len == 0 {
        return None;
    }
    for step in 1..=len {
        let i = if forward {
            (from + step) % len
        } else {
            (from + len - (step % len)) % len
        };
        if pred(i) {
            return Some(i);
        }
    }
    None
}

/// Find the byte offset of `needle` in `hay`, searching from just past `cur`
/// (or just before it, when not `forward`). Case-sensitive. `None` if absent.
fn find_bytes(hay: &[u8], needle: &[u8], cur: usize, forward: bool) -> Option<usize> {
    if needle.is_empty() || hay.len() < needle.len() {
        return None;
    }
    let last = hay.len() - needle.len();
    if forward {
        let start = (cur + 1).min(last + 1);
        (start..=last).find(|&i| &hay[i..i + needle.len()] == needle)
    } else {
        let start = cur.min(last + 1);
        (0..start)
            .rev()
            .find(|&i| &hay[i..i + needle.len()] == needle)
    }
}

/// Whether the point `(col,row)` falls inside `r`.
fn hit(r: Rect, col: u16, row: u16) -> bool {
    col >= r.x
        && col < r.x.saturating_add(r.width)
        && row >= r.y
        && row < r.y.saturating_add(r.height)
}

/// Move the cursor one char left (UTF-8-safe). Ported from iftoprs `FilterState::left`.
fn input_left(buf: &str, cur: usize) -> usize {
    if cur > 0 {
        buf[..cur]
            .char_indices()
            .next_back()
            .map(|(i, _)| i)
            .unwrap_or(0)
    } else {
        0
    }
}

/// Move the cursor one char right (UTF-8-safe). Ported from iftoprs `FilterState::right`.
fn input_right(buf: &str, cur: usize) -> usize {
    if cur < buf.len() {
        buf[cur..]
            .char_indices()
            .nth(1)
            .map(|(i, _)| cur + i)
            .unwrap_or(buf.len())
    } else {
        buf.len()
    }
}

/// Delete the word before the cursor (Ctrl+W). Ported from iftoprs
/// `FilterState::delete_word` — skips trailing whitespace, then the word,
/// stepping by real UTF-8 widths. Returns the new cursor position.
fn input_delete_word(buf: &mut String, cur: usize) -> usize {
    let s = &buf[..cur];
    let trimmed = s.trim_end();
    let word_start = match trimmed
        .char_indices()
        .rev()
        .find(|(_, c)| c.is_whitespace())
    {
        Some((i, c)) => i + c.len_utf8(),
        None => 0,
    };
    buf.drain(word_start..cur);
    word_start
}

/// Parse a value-input string: a `0x…` prefix is decoded as hex bytes (spaces
/// Lowercase hex of a byte slice.
/// Whether a byte slice is mostly printable/UTF-8 text (heuristic for Auto
/// value rendering): valid UTF-8 and < 10% control bytes.
fn looks_textual(bytes: &[u8]) -> bool {
    if bytes.is_empty() {
        return true;
    }
    if std::str::from_utf8(bytes).is_err() {
        return false;
    }
    let ctrl = bytes
        .iter()
        .filter(|&&b| b < 0x09 || (0x0e..0x20).contains(&b))
        .count();
    ctrl * 10 < bytes.len()
}

fn hex_string(bytes: &[u8]) -> String {
    let mut s = String::with_capacity(bytes.len() * 2);
    for b in bytes {
        s.push_str(&format!("{:02x}", b));
    }
    s
}

/// Make a filename-safe token from a table/base name.
fn sanitize(name: &str) -> String {
    name.chars()
        .map(|c| {
            if c.is_alphanumeric() || c == '-' || c == '_' {
                c
            } else {
                '_'
            }
        })
        .collect()
}

/// Build the value-pane lines for `bytes` under `render`, starting at row
/// `scroll` (16 bytes/row), up to `height` rows.
fn value_lines(
    bytes: &[u8],
    render: ValueRender,
    scroll: usize,
    height: usize,
) -> Vec<Line<'static>> {
    if render == ValueRender::Disasm {
        return disasm_lines(bytes, scroll, height);
    }
    let as_text = match render {
        ValueRender::Text => true,
        ValueRender::Hex => false,
        ValueRender::Auto => looks_textual(bytes),
        ValueRender::Disasm => unreachable!(),
    };
    let mut lines = Vec::new();
    if as_text {
        let text = String::from_utf8_lossy(bytes);
        for line in text.lines().skip(scroll).take(height) {
            lines.push(Line::from(line.to_string()));
        }
    } else {
        for i in 0..height {
            let off = (scroll + i) * 16;
            if off >= bytes.len() {
                break;
            }
            lines.push(Line::from(hexedit::hex_dump_line(
                off,
                &bytes[off.min(bytes.len())..(off + 16).min(bytes.len())],
            )));
        }
    }
    lines
}

/// Disassemble the value as a fusevm::Chunk. Only functional with the `disasm`
/// feature; otherwise a one-line note.
#[cfg(feature = "disasm")]
fn disasm_lines(bytes: &[u8], scroll: usize, height: usize) -> Vec<Line<'static>> {
    match crate::disasm::disassemble(bytes) {
        Ok(all) => all
            .into_iter()
            .skip(scroll)
            .take(height)
            .map(Line::from)
            .collect(),
        Err(e) => vec![Line::from(format!("not a fusevm chunk: {e}"))],
    }
}

#[cfg(not(feature = "disasm"))]
fn disasm_lines(_bytes: &[u8], _scroll: usize, _height: usize) -> Vec<Line<'static>> {
    vec![Line::from(
        "rebuild with `--features disasm` for bytecode disassembly",
    )]
}

/// Truncate a display string to `max` chars, appending an ellipsis.
/// A saved scan's age, phrased for the picker title.
fn age_label(age: std::time::Duration) -> String {
    let secs = age.as_secs();
    match secs {
        0..=90 => "just now".to_string(),
        _ if secs < 3600 => format!("{}m old", secs / 60),
        _ if secs < 86_400 => format!("{}h old", secs / 3600),
        _ => format!("{}d old", secs / 86_400),
    }
}

/// Byte count in the largest unit that keeps it under four digits.
pub fn human_size(n: u64) -> String {
    const UNITS: [&str; 5] = ["B", "K", "M", "G", "T"];
    let mut size = n as f64;
    let mut unit = 0;
    while size >= 1024.0 && unit + 1 < UNITS.len() {
        size /= 1024.0;
        unit += 1;
    }
    if unit == 0 {
        format!("{} {}", n, UNITS[0])
    } else if size < 10.0 {
        format!("{:.1} {}", size, UNITS[unit])
    } else {
        format!("{:.0} {}", size, UNITS[unit])
    }
}

/// Sort-direction marker for a column header.
fn arrow(desc: bool) -> &'static str {
    if desc {
        ""
    } else {
        ""
    }
}

pub fn truncate(s: &str, max: usize) -> String {
    if s.chars().count() <= max {
        s.to_string()
    } else {
        let mut out: String = s.chars().take(max.saturating_sub(1)).collect();
        out.push('');
        out
    }
}

/// A centered rect `w` cols wide and `h` rows tall inside `area`.
fn centered(area: Rect, w: u16, h: u16) -> Rect {
    let w = w.min(area.width);
    let h = h.min(area.height);
    Rect {
        x: area.x + (area.width - w) / 2,
        y: area.y + (area.height - h) / 2,
        width: w,
        height: h,
    }
}

#[cfg(test)]
mod tests {
    use super::{
        find_bytes, find_next, hit, input_delete_word, input_left, input_right, App, Store,
    };
    use crate::mru::Entry;
    use crate::overlay::HelpCtx;
    use crate::rkyv_inspect::RkyvStore;
    use crate::sqlite::SqliteStore;
    use crate::store::Kind;
    use crate::theme::{Theme, ThemeName};
    use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
    use ratatui::backend::TestBackend;
    use ratatui::layout::Rect;
    use ratatui::Terminal;

    /// Merge hits into a list the way the picker does: the set of paths already
    /// listed comes from the rows themselves.
    fn merge(choices: &mut Vec<super::Choice>, hits: Vec<crate::scan::Hit>) {
        let mut listed = choices.iter().map(|c| super::canon(&c.path)).collect();
        super::merge_hits(choices, &mut listed, hits);
    }

    /// A unique scratch path per call — these tests run concurrently.
    fn scratch(ext: &str) -> std::path::PathBuf {
        static N: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
        let seq = N.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        let mut path = std::env::temp_dir();
        path.push(format!(
            "zdbview_app_{}_{}.{}",
            std::process::id(),
            seq,
            ext
        ));
        let _ = std::fs::remove_file(&path);
        path
    }

    /// An App over a throwaway binary file, on a fixed scheme so assertions
    /// don't depend on the developer's saved prefs.
    fn rkyv_app() -> App {
        let path = scratch("bin");
        std::fs::write(&path, b"zdbview overlay render test payload").unwrap();
        let store = Store::Rkyv(RkyvStore::open(&path).unwrap());
        let _ = std::fs::remove_file(&path);
        App::with_theme(store, Theme::from_name(ThemeName::NeonSprawl))
    }

    /// An App over a SQLite table with `n` rows, for paging tests.
    fn sqlite_app_rows(n: usize) -> (App, std::path::PathBuf) {
        let path = scratch("db");
        let conn = rusqlite::Connection::open(&path).unwrap();
        conn.execute("CREATE TABLE t (a TEXT, b TEXT)", []).unwrap();
        for i in 0..n {
            conn.execute("INSERT INTO t VALUES (?1, 'y')", [i.to_string()])
                .unwrap();
        }
        drop(conn);
        let store = Store::Sqlite(SqliteStore::open(&path).unwrap());
        (
            App::with_theme(store, Theme::from_name(ThemeName::NeonSprawl)),
            path,
        )
    }

    /// An App over arbitrary binary content.
    fn rkyv_app_with(bytes: &[u8]) -> App {
        let path = scratch("bin");
        std::fs::write(&path, bytes).unwrap();
        let store = Store::Rkyv(RkyvStore::open(&path).unwrap());
        let _ = std::fs::remove_file(&path);
        App::with_theme(store, Theme::from_name(ThemeName::NeonSprawl))
    }

    /// An App over a two-column SQLite table, for column-motion tests.
    fn sqlite_app() -> (App, std::path::PathBuf) {
        let path = scratch("db");
        let conn = rusqlite::Connection::open(&path).unwrap();
        conn.execute("CREATE TABLE t (a TEXT, b TEXT, c TEXT)", [])
            .unwrap();
        conn.execute("INSERT INTO t VALUES ('x', 'y', 'z')", [])
            .unwrap();
        drop(conn);
        let store = Store::Sqlite(SqliteStore::open(&path).unwrap());
        (
            App::with_theme(store, Theme::from_name(ThemeName::NeonSprawl)),
            path,
        )
    }

    /// Render one frame and flatten the buffer into per-row strings.
    fn frame_rows(app: &mut App, w: u16, h: u16) -> Vec<String> {
        let mut term = Terminal::new(TestBackend::new(w, h)).unwrap();
        term.draw(|f| app.render(f)).unwrap();
        let buf = term.backend().buffer().clone();
        (0..buf.area().height)
            .map(|y| {
                (0..buf.area().width)
                    .map(|x| buf[(x, y)].symbol())
                    .collect::<String>()
            })
            .collect()
    }

    fn contains(rows: &[String], needle: &str) -> bool {
        rows.iter().any(|r| r.contains(needle))
    }

    fn press(app: &mut App, c: char) {
        app.on_key(KeyEvent::from(KeyCode::Char(c)));
    }

    /// Wait for the query threads to go idle, the way the event loop does on its
    /// tick. Pages, counts and searches all arrive this way.
    fn await_queries(app: &mut App) {
        for _ in 0..5000 {
            app.poll_query();
            let busy = app
                .engine
                .as_ref()
                .is_some_and(|e| e.page_inflight() || e.count_inflight() || e.searching());
            if !busy {
                return;
            }
            std::thread::sleep(std::time::Duration::from_millis(1));
        }
        panic!("a query never finished");
    }

    /// Wait for a background statistics pass, the way the event loop does.
    fn await_stats(app: &mut App) {
        for _ in 0..2000 {
            app.poll_stats();
            if app.stats_pending.is_none() {
                return;
            }
            std::thread::sleep(std::time::Duration::from_millis(1));
        }
        panic!("the statistics pass never finished");
    }

    /// The dot-commands, which is what makes the editor a stand-in for the shell:
    /// output modes, redirects, schema queries, import, scripts and index advice.
    #[test]
    fn the_sql_editor_runs_dot_commands() {
        use crate::sqledit::Entry;
        let path = scratch("db");
        let conn = rusqlite::Connection::open(&path).unwrap();
        conn.execute_batch(
            "CREATE TABLE t (a TEXT, b INTEGER);
             CREATE INDEX t_a ON t(a);
             INSERT INTO t VALUES ('x', 1), ('y', 2);",
        )
        .unwrap();
        drop(conn);
        let mut app = App::with_theme(
            Store::Sqlite(SqliteStore::open(&path).unwrap()),
            Theme::from_name(ThemeName::NeonSprawl),
        );
        press(&mut app, ':');
        let note = |app: &App| -> Vec<String> {
            app.sql
                .as_ref()
                .unwrap()
                .transcript()
                .iter()
                .rev()
                .find_map(|e| match e {
                    Entry::Note(lines) => Some(lines.clone()),
                    _ => None,
                })
                .expect("a note")
        };

        app.execute_sql(".tables");
        assert_eq!(note(&app), vec!["t".to_string()]);

        app.execute_sql(".indexes t");
        assert!(note(&app)[0].starts_with("t_a  (a)"), "{:?}", note(&app));

        app.execute_sql(".help");
        assert!(
            note(&app).iter().any(|l| l.starts_with(".expert")),
            "the help lists every command it implements"
        );

        // `.mode` changes how a result set is rendered: no grid, formatted text.
        app.execute_sql(".mode csv");
        app.execute_sql("SELECT a, b FROM t ORDER BY a");
        assert_eq!(note(&app), vec!["a,b", "x,1", "y,2"]);
        app.execute_sql(".headers off");
        app.execute_sql("SELECT a, b FROM t ORDER BY a");
        assert_eq!(
            note(&app),
            vec!["x,1", "y,2"],
            "headers off drops the names"
        );
        app.execute_sql(".mode list");
        app.execute_sql("SELECT a FROM t");
        assert!(
            matches!(
                app.sql.as_ref().unwrap().transcript().iter().rev().nth(1),
                Some(Entry::Rows { .. })
            ),
            "list mode is the grid again"
        );

        // `.once` writes the next result only.
        let out = scratch("csv");
        app.execute_sql(".mode csv");
        app.execute_sql(".headers on"); // still off from the toggle above
        app.execute_sql(&format!(".once {}", out.display()));
        app.execute_sql("SELECT a FROM t ORDER BY a");
        assert!(note(&app)[0].contains("wrote 2 rows"), "{:?}", note(&app));
        assert_eq!(std::fs::read_to_string(&out).unwrap(), "a\nx\ny\n");
        assert!(
            app.sql_out.is_none(),
            "a once redirect ends after one result"
        );

        // `.output` collects every result until it is reset, as the shell does — the
        // second statement must not erase the first.
        let all = scratch("all.csv");
        app.execute_sql(&format!(".output {}", all.display()));
        app.execute_sql("SELECT a FROM t WHERE a = 'x'");
        app.execute_sql("SELECT a FROM t WHERE a = 'y'");
        let collected = std::fs::read_to_string(&all).unwrap();
        assert_eq!(
            collected, "a\nx\na\ny\n",
            "both results are in the file, in order"
        );
        // Pointing it at the same file again starts fresh rather than appending to
        // what was there.
        app.execute_sql(&format!(".output {}", all.display()));
        app.execute_sql("SELECT a FROM t WHERE a = 'x'");
        assert_eq!(std::fs::read_to_string(&all).unwrap(), "a\nx\n");
        app.execute_sql(".output");
        assert!(
            app.sql_out.is_none(),
            "bare .output goes back to the transcript"
        );
        let _ = std::fs::remove_file(&all);

        // `.import` shares the reader with --import; `.read` runs a script.
        let csv = scratch("in.csv");
        std::fs::write(&csv, "a,b\nz,3\n").unwrap();
        app.execute_sql(&format!(".import {} t", csv.display()));
        assert_eq!(note(&app), vec!["imported 1 rows into t".to_string()]);
        let script = scratch("sql");
        std::fs::write(
            &script,
            "UPDATE t SET b = 9 WHERE a = 'z';\nSELECT count(*) FROM t;",
        )
        .unwrap();
        app.execute_sql(&format!(".read {}", script.display()));
        assert!(
            note(&app).iter().any(|l| l.contains("ran 2 statements")),
            "{:?}",
            note(&app)
        );

        // `.expert` asks about the statement the transcript last ran, so this one
        // goes through the editor: typing and Enter is what records it.
        app.execute_sql(".mode list");
        for c in "SELECT a FROM t WHERE b = 1".chars() {
            app.on_key(KeyEvent::from(KeyCode::Char(c)));
        }
        app.on_key(KeyEvent::from(KeyCode::Enter));
        app.execute_sql(".expert");
        let advice = note(&app);
        assert!(
            advice[0].contains("full scan") && advice[0].contains("CREATE INDEX"),
            "{advice:?}"
        );
        assert!(
            advice[0].contains("\"b\""),
            "the column compared: {advice:?}"
        );

        // An unknown command says so instead of reaching SQLite.
        app.execute_sql(".nope");
        assert!(
            note(&app)[0].contains("unknown command"),
            "{:?}",
            note(&app)
        );
        for f in [path, out, csv, script] {
            let _ = std::fs::remove_file(f);
        }
    }

    /// The monitor's two novel views, driven end to end: `t` swaps to the per-table
    /// breakdown, and `F` opens the log walker on the selected database.
    #[test]
    fn the_monitor_opens_the_table_pane_and_the_log_walker() {
        let path = scratch("db");
        for suffix in ["-wal", "-shm"] {
            let mut n = path.as_os_str().to_os_string();
            n.push(suffix);
            let _ = std::fs::remove_file(std::path::PathBuf::from(n));
        }
        let conn = rusqlite::Connection::open(&path).unwrap();
        conn.pragma_update(None, "journal_mode", "WAL").unwrap();
        conn.pragma_update(None, "wal_autocheckpoint", 0).unwrap();
        conn.execute_batch("CREATE TABLE t (v TEXT)").unwrap();
        for i in 0..120 {
            conn.execute("INSERT INTO t VALUES (?1)", [format!("row {i} padded out")])
                .unwrap();
        }

        let mut app = App::with_theme(
            Store::Sqlite(SqliteStore::open(&path).unwrap()),
            Theme::from_name(ThemeName::NeonSprawl),
        );
        // The monitor watches every file zdbview knows of, which on a real machine
        // means whatever else is writing right now — this test is about the panes,
        // so it watches only the database it just wrote.
        press(&mut app, 'w'); // the write monitor
        assert_eq!(app.screen, super::Screen::Top);
        app.top = Some(crate::monitor::Monitor::new([(path.clone(), Kind::Sqlite)]));
        // Sample twice so the second tick has frames to attribute.
        if let Some(m) = app.top.as_mut() {
            m.watcher.interval = std::time::Duration::from_millis(0);
            m.tick();
            m.tick();
        }
        press(&mut app, 't');
        assert_eq!(
            app.top.as_ref().unwrap().pane,
            crate::monitor::Pane::Tables,
            "t swaps the bottom pane"
        );
        let rows = frame_rows(&mut app, 120, 30);
        assert!(contains(&rows, "tables —"), "{:?}", rows.last());
        assert!(
            contains(&rows, " t ") || contains(&rows, "sqlite_schema"),
            "the pane names what was written: {rows:?}"
        );

        // `F` walks the log: frames on the left, the selected frame's rows right.
        press(&mut app, 'F');
        assert_eq!(app.screen, super::Screen::Frames);
        let walk = app.walk.as_ref().expect("a log walker");
        assert!(!walk.frames.is_empty());
        assert_eq!(app.help_ctx(), HelpCtx::Frames);
        let rows = frame_rows(&mut app, 120, 30);
        assert!(contains(&rows, "what this frame wrote"), "{:?}", rows[0]);
        assert!(
            contains(&rows, "commits"),
            "the frame list is titled with its commit count"
        );

        // Esc returns to the monitor rather than to the grid.
        app.on_key(KeyEvent::from(KeyCode::Esc));
        assert_eq!(app.screen, super::Screen::Top);
        assert!(app.walk.is_none());
        drop(conn);
        for suffix in ["", "-wal", "-shm"] {
            let mut n = path.as_os_str().to_os_string();
            n.push(suffix);
            let _ = std::fs::remove_file(std::path::PathBuf::from(n));
        }
    }

    /// `F` follows the foreign key under the cursor into the parent table and puts
    /// the cursor on the row it references.
    #[test]
    fn f_follows_a_foreign_key_to_its_parent_row() {
        let path = scratch("db");
        let conn = rusqlite::Connection::open(&path).unwrap();
        conn.execute_batch(
            // Enforcement off so the fixture can hold a dangling key, which is
            // exactly the case `F` has to report rather than follow.
            "PRAGMA foreign_keys=OFF;
             CREATE TABLE author (id INTEGER PRIMARY KEY, name TEXT);
             CREATE TABLE book (title TEXT, author_id INTEGER REFERENCES author(id));
             INSERT INTO author VALUES (1, 'first'), (2, 'second'), (3, 'third');
             INSERT INTO book VALUES ('a book', 3), ('orphan', 99), ('unknown', NULL);",
        )
        .unwrap();
        drop(conn);
        let mut app = App::with_theme(
            Store::Sqlite(SqliteStore::open(&path).unwrap()),
            Theme::from_name(ThemeName::NeonSprawl),
        );
        // `book` is the second table; focus its grid and put the cursor on the key.
        let book = app
            .sqlite()
            .unwrap()
            .tables
            .iter()
            .position(|t| t == "book")
            .unwrap();
        app.select_table(book);
        app.on_key(KeyEvent::from(KeyCode::Tab));
        app.on_key(KeyEvent::from(KeyCode::Right)); // author_id

        press(&mut app, 'F');
        assert_eq!(
            app.current_table().as_deref(),
            Some("author"),
            "it jumps to the parent table"
        );
        let row = &app.rows.as_ref().unwrap().rows[app.row_idx];
        assert_eq!(row[1], "third", "and lands on the referenced row");
        assert_eq!(
            app.rows.as_ref().unwrap().columns[app.col_idx],
            "id",
            "with the cursor on the key column"
        );

        // A key with no matching parent row says so and stays put. (Focus is
        // already on the grid here, so Tab would move it away.)
        app.select_table(book);
        app.on_key(KeyEvent::from(KeyCode::Right));
        app.on_key(KeyEvent::from(KeyCode::Down)); // the orphan row
        press(&mut app, 'F');
        assert_eq!(app.current_table().as_deref(), Some("book"));
        assert!(app.status.contains("no author row"), "got {:?}", app.status);

        // A NULL key, and a column that is not a key at all.
        app.on_key(KeyEvent::from(KeyCode::Down)); // the NULL row
        press(&mut app, 'F');
        assert!(app.status.contains("NULL"), "got {:?}", app.status);
        app.on_key(KeyEvent::from(KeyCode::Left)); // title
        press(&mut app, 'F');
        assert!(
            app.status.contains("not a foreign key"),
            "got {:?}",
            app.status
        );
        let _ = std::fs::remove_file(path);
    }

    /// `Y` puts the row on the clipboard as an `INSERT`. With no tty the copy
    /// cannot land, and the toast has to say so rather than claim success.
    #[test]
    fn y_copies_the_row_as_an_insert_statement() {
        let (mut app, path) = sqlite_app();
        app.on_key(KeyEvent::from(KeyCode::Tab)); // focus the row grid
        press(&mut app, 'Y');
        assert!(
            app.status.contains("copied INSERT") || app.status.contains("clipboard unavailable"),
            "got {:?}",
            app.status
        );
        // The statement itself is built by the same writer the dump uses.
        let view = app.rows.as_ref().unwrap();
        let sql = crate::export::insert_statement("t", &view.columns, &view.rows[0]);
        assert_eq!(
            sql,
            r#"INSERT INTO "t" ("a", "b", "c") VALUES ('x', 'y', 'z');"#
        );
        let _ = std::fs::remove_file(path);
    }

    /// The detail screen shows the whole value, so it is where you edit it: `e`
    /// opens the editor there, the arrows pick the field, and the pane shows the
    /// new bytes without a trip back to the grid.
    #[test]
    fn the_detail_screen_edits_the_field_it_is_showing() {
        let path = scratch("db");
        let conn = rusqlite::Connection::open(&path).unwrap();
        conn.execute_batch("CREATE TABLE t (a TEXT, b TEXT)")
            .unwrap();
        conn.execute("INSERT INTO t VALUES ('one', 'two')", [])
            .unwrap();
        drop(conn);
        let mut app = App::with_theme(
            Store::Sqlite(SqliteStore::open(&path).unwrap()),
            Theme::from_name(ThemeName::NeonSprawl),
        );
        app.on_key(KeyEvent::from(KeyCode::Tab)); // focus the row grid
        app.on_key(KeyEvent::from(KeyCode::Enter)); // detail
        assert_eq!(app.screen, super::Screen::Detail);
        assert_eq!(app.detail_value, b"one");

        // Right moves to the next field and reloads what the value pane shows.
        app.on_key(KeyEvent::from(KeyCode::Right));
        assert_eq!(app.col_idx, 1);
        assert_eq!(app.detail_value, b"two");

        // `e` edits that field in place, and the screen stays where it was.
        press(&mut app, 'e');
        assert!(matches!(app.mode, super::Mode::EditCell(_)));
        assert_eq!(app.screen, super::Screen::Detail);
        // The editor opens seeded with the current value, so clear it first.
        app.on_key(KeyEvent::new(KeyCode::Char('u'), KeyModifiers::CONTROL));
        for c in "TWO".chars() {
            app.on_key(KeyEvent::from(KeyCode::Char(c)));
        }
        app.on_key(KeyEvent::from(KeyCode::Enter));
        assert_eq!(
            app.detail_value, b"TWO",
            "the value pane must show what was just written"
        );
        let store = SqliteStore::open(&path).unwrap();
        let view = store.rows(&crate::sqlite::PageQuery::all("t", 10)).unwrap();
        assert_eq!(view.rows[0], vec!["one".to_string(), "TWO".to_string()]);
        let _ = std::fs::remove_file(path);
    }

    /// `E` opens any cell as bytes, which is the only way to put binary into a cell
    /// that is not already a blob — `e` alone would edit it as text.
    #[test]
    fn shift_e_turns_a_text_or_null_cell_into_bytes() {
        let path = scratch("db");
        let conn = rusqlite::Connection::open(&path).unwrap();
        conn.execute_batch(
            "CREATE TABLE t (txt TEXT, empty BLOB);
             INSERT INTO t VALUES ('hi', NULL);",
        )
        .unwrap();
        drop(conn);
        let mut app = App::with_theme(
            Store::Sqlite(SqliteStore::open(&path).unwrap()),
            Theme::from_name(ThemeName::NeonSprawl),
        );
        app.on_key(KeyEvent::from(KeyCode::Tab)); // the row grid

        // `e` on a text cell still edits text.
        press(&mut app, 'e');
        assert!(matches!(app.mode, super::Mode::EditCell(_)));
        app.on_key(KeyEvent::from(KeyCode::Esc));

        // `E` on the same cell opens its bytes instead.
        press(&mut app, 'E');
        assert_eq!(app.screen, super::Screen::HexEdit);
        assert_eq!(
            app.hex.as_ref().unwrap().bytes,
            b"hi",
            "a string starts as its own bytes"
        );
        press(&mut app, 'i');
        press(&mut app, '4');
        press(&mut app, '1');
        app.on_key(KeyEvent::new(KeyCode::Char('s'), KeyModifiers::CONTROL));
        let store = SqliteStore::open(&path).unwrap();
        let key = crate::sqlite::RowKey::Rowid(1);
        assert_eq!(store.cell_bytes_keyed("t", &key, "txt").unwrap(), b"Ai");
        assert!(
            store.cell_is_blob_keyed("t", &key, "txt").unwrap(),
            "it is a blob now, not a string"
        );
        app.on_key(KeyEvent::from(KeyCode::Esc));
        press(&mut app, 'q');

        // And a NULL cell starts empty, so bytes can be authored from nothing.
        app.on_key(KeyEvent::from(KeyCode::Right));
        press(&mut app, 'E');
        assert_eq!(app.screen, super::Screen::HexEdit);
        assert!(
            app.hex.as_ref().unwrap().bytes.is_empty(),
            "NULL has no bytes"
        );
        press(&mut app, 'o'); // insert a byte to have something to write
        app.on_key(KeyEvent::new(KeyCode::Char('s'), KeyModifiers::CONTROL));
        let store = SqliteStore::open(&path).unwrap();
        assert!(
            store.cell_is_blob_keyed("t", &key, "empty").unwrap(),
            "a NULL became a blob"
        );
        let _ = std::fs::remove_file(path);
    }

    /// A blob field edited from the detail screen goes through the hex editor and
    /// comes back to the detail screen, not to the grid.
    #[test]
    fn a_blob_edited_from_the_detail_screen_returns_there() {
        let path = scratch("db");
        let conn = rusqlite::Connection::open(&path).unwrap();
        conn.execute_batch("CREATE TABLE t (raw BLOB)").unwrap();
        conn.execute("INSERT INTO t VALUES (?1)", [&[0x01u8, 0x02][..]])
            .unwrap();
        drop(conn);
        let mut app = App::with_theme(
            Store::Sqlite(SqliteStore::open(&path).unwrap()),
            Theme::from_name(ThemeName::NeonSprawl),
        );
        app.on_key(KeyEvent::from(KeyCode::Tab));
        app.on_key(KeyEvent::from(KeyCode::Enter)); // detail
        press(&mut app, 'e');
        assert_eq!(app.screen, super::Screen::HexEdit);

        press(&mut app, 'i');
        press(&mut app, 'f');
        press(&mut app, 'f');
        app.on_key(KeyEvent::new(KeyCode::Char('s'), KeyModifiers::CONTROL));
        app.on_key(KeyEvent::from(KeyCode::Esc)); // leave EDIT mode
        press(&mut app, 'q'); // close the editor
        assert_eq!(
            app.screen,
            super::Screen::Detail,
            "closing returns to where it opened from"
        );
        assert_eq!(app.detail_value, [0xff, 0x02], "with the new bytes");
        let _ = std::fs::remove_file(path);
    }

    /// Every rkyv edit path needs the whole archive while `self` is borrowed
    /// mutably, which used to mean copying it — 382 MB per operation on a real
    /// shard. The bytes are shared now, so handing them out must not copy.
    #[test]
    fn handing_out_the_archive_bytes_does_not_copy_them() {
        let path = scratch("bin");
        std::fs::write(&path, b"zdbview archive bytes, shared not copied").unwrap();
        let store = RkyvStore::open(&path).unwrap();
        let original = std::sync::Arc::clone(&store.bytes);
        let app = App::with_theme(Store::Rkyv(store), Theme::from_name(ThemeName::NeonSprawl));

        // What every edit path and the background decoder do to get the bytes.
        let handed = match &app.store {
            Store::Rkyv(r) => r.bytes.clone(),
            _ => unreachable!(),
        };
        assert!(
            std::sync::Arc::ptr_eq(&original, &handed),
            "the same allocation must come back, not a copy of it"
        );
        assert_eq!(&*handed, b"zdbview archive bytes, shared not copied");
        let _ = std::fs::remove_file(path);
    }

    /// With a filter active, `n` must step through the listed rows only — in the
    /// grid and in the table pane both.
    #[test]
    fn search_steps_through_filtered_lists_only() {
        let path = scratch("db");
        let conn = rusqlite::Connection::open(&path).unwrap();
        conn.execute_batch(
            "CREATE TABLE keep_a (v TEXT); CREATE TABLE drop_b (v TEXT);
             CREATE TABLE keep_c (v TEXT);
             INSERT INTO keep_a VALUES ('x');",
        )
        .unwrap();
        drop(conn);
        let mut app = App::with_theme(
            Store::Sqlite(SqliteStore::open(&path).unwrap()),
            Theme::from_name(ThemeName::NeonSprawl),
        );

        // Table pane: `/keep` hides drop_b, so searching for a name every table
        // matches must still skip it.
        app.set_filter("keep".to_string());
        app.search = "_".to_string();
        app.table_idx = 0;
        app.search_next(true);
        assert_eq!(
            app.sqlite().unwrap().tables[app.table_idx],
            "keep_c",
            "n skipped the filtered-out table"
        );
        app.search_next(true);
        assert_eq!(
            app.sqlite().unwrap().tables[app.table_idx],
            "keep_a",
            "and wraps inside the filtered list"
        );
        let _ = std::fs::remove_file(path);
    }

    /// `n` in the row grid scans the whole table and then counts to find out which
    /// page the match is on — two full scans on a large table, so it runs on the
    /// query thread and lands through the poll. Pressing it must still scroll to
    /// the match and select it.
    #[test]
    fn n_scrolls_the_grid_to_a_match_on_another_page() {
        let path = scratch("db");
        let conn = rusqlite::Connection::open(&path).unwrap();
        conn.execute_batch("CREATE TABLE t (v TEXT)").unwrap();
        {
            let tx = conn.unchecked_transaction().unwrap();
            let mut stmt = tx.prepare("INSERT INTO t (v) VALUES (?1)").unwrap();
            // One needle, well past the first page of 500.
            for i in 0..1200 {
                stmt.execute(rusqlite::params![if i == 900 {
                    "needle".to_string()
                } else {
                    format!("hay-{i}")
                }])
                .unwrap();
            }
            drop(stmt);
            tx.commit().unwrap();
        }
        drop(conn);
        let mut app = App::with_theme(
            Store::Sqlite(SqliteStore::open(&path).unwrap()),
            Theme::from_name(ThemeName::NeonSprawl),
        );
        app.on_key(KeyEvent::from(KeyCode::Tab)); // focus the row grid
        await_queries(&mut app);
        assert_eq!(app.page_offset, 0, "starts on the first page");

        app.search = "needle".into();
        app.search_next(true);
        await_queries(&mut app);

        // The needle is the 901st row, so it sits 400 rows into the page at 500.
        assert_eq!(app.page_offset, 500, "the grid moved to the match's page");
        assert_eq!(app.row_idx, 400, "and selected the match");
        let row = &app.rows.as_ref().unwrap().rows[app.row_idx];
        assert_eq!(row[0], "needle", "the selected row is the match");
        let _ = std::fs::remove_file(path);
    }

    /// A filter re-queries on every keystroke, so an intermediate result must
    /// never be what ends up on screen.
    #[test]
    fn typing_a_filter_leaves_the_grid_showing_the_final_pattern() {
        let path = scratch("db");
        let conn = rusqlite::Connection::open(&path).unwrap();
        conn.execute_batch(
            "CREATE TABLE t (v TEXT);
             INSERT INTO t VALUES ('alpha'), ('alpine'), ('beta'), ('gamma');",
        )
        .unwrap();
        drop(conn);
        let mut app = App::with_theme(
            Store::Sqlite(SqliteStore::open(&path).unwrap()),
            Theme::from_name(ThemeName::NeonSprawl),
        );
        app.on_key(KeyEvent::from(KeyCode::Tab));
        await_queries(&mut app);

        // Type `alpi` one key at a time, as the prompt does.
        for pattern in ["a", "al", "alp", "alpi"] {
            app.set_filter(pattern.to_string());
        }
        await_queries(&mut app);
        let rows = &app.rows.as_ref().unwrap().rows;
        assert_eq!(rows.len(), 1, "only `alpine` matches `alpi`: {rows:?}");
        assert_eq!(rows[0][0], "alpine");
        let _ = std::fs::remove_file(path);
    }

    /// `A` describes the table's columns, Enter drills into one column's
    /// frequency, and Esc unwinds one step at a time.
    #[test]
    fn stats_screen_describes_columns_and_counts_values() {
        let path = scratch("db");
        let conn = rusqlite::Connection::open(&path).unwrap();
        conn.execute_batch(
            "CREATE TABLE t (tag TEXT, qty INTEGER);
             INSERT INTO t VALUES ('a', 1), ('a', 2), ('b', NULL);",
        )
        .unwrap();
        drop(conn);
        let mut app = App::with_theme(
            Store::Sqlite(SqliteStore::open(&path).unwrap()),
            Theme::from_name(ThemeName::NeonSprawl),
        );
        app.on_key(KeyEvent::from(KeyCode::Tab)); // focus the row grid

        press(&mut app, 'A');
        assert_eq!(app.screen, super::Screen::Stats);
        // The pass runs off-thread, so the screen opens saying so and Enter does
        // nothing until the columns land.
        assert!(app.stats_pending.is_some());
        let rows = frame_rows(&mut app, 110, 20);
        assert!(contains(&rows, "analyzing"), "{:?}", rows[0]);
        app.on_key(KeyEvent::from(KeyCode::Enter));
        assert!(app.stats_freq.is_none(), "nothing to drill into yet");

        await_stats(&mut app);
        assert_eq!(app.stats.len(), 2, "one row per column");
        let rows = frame_rows(&mut app, 110, 20);
        assert!(contains(&rows, "distinct"), "{rows:?}");
        assert!(contains(&rows, "columns of t"), "{:?}", rows[0]);

        // The frequency table is a step deeper: Enter opens it, Esc closes it and
        // only the second Esc leaves the screen.
        app.on_key(KeyEvent::from(KeyCode::Enter));
        let (col, freq) = app.stats_freq.as_ref().expect("a frequency table");
        assert_eq!(col, "tag");
        assert_eq!(freq[0], ("a".to_string(), 2), "the common value leads");
        let rows = frame_rows(&mut app, 110, 20);
        assert!(contains(&rows, "most common values"), "{rows:?}");
        app.on_key(KeyEvent::from(KeyCode::Esc));
        assert!(app.stats_freq.is_none());
        assert_eq!(app.screen, super::Screen::Stats, "still on the screen");
        app.on_key(KeyEvent::from(KeyCode::Esc));
        assert_eq!(app.screen, super::Screen::Main);

        // Moving the selection drops a stale frequency table for the old column.
        press(&mut app, 'A');
        await_stats(&mut app);
        app.on_key(KeyEvent::from(KeyCode::Enter));
        press(&mut app, 'j');
        assert!(
            app.stats_freq.is_none(),
            "the table belonged to the old column"
        );
        assert_eq!(app.stats_idx, 1);
        let _ = std::fs::remove_file(path);
    }

    /// A blob cell cannot be edited as text — `e` must open the hex editor over
    /// its bytes and `^s` must write bytes back, not a string.
    #[test]
    fn a_blob_cell_edits_in_the_hex_editor() {
        let path = scratch("db");
        let conn = rusqlite::Connection::open(&path).unwrap();
        conn.execute_batch("CREATE TABLE t (raw BLOB, txt TEXT)")
            .unwrap();
        conn.execute(
            "INSERT INTO t VALUES (?1, 'plain')",
            [&[0x00u8, 0xffu8][..]],
        )
        .unwrap();
        drop(conn);
        let mut app = App::with_theme(
            Store::Sqlite(SqliteStore::open(&path).unwrap()),
            Theme::from_name(ThemeName::NeonSprawl),
        );
        app.on_key(KeyEvent::from(KeyCode::Tab)); // focus the row grid

        press(&mut app, 'e');
        assert_eq!(
            app.screen,
            super::Screen::HexEdit,
            "blob opens the hex editor"
        );
        assert_eq!(app.hex.as_ref().unwrap().bytes, [0x00, 0xff]);

        // Set the first byte to 0x41 and save.
        press(&mut app, 'i');
        press(&mut app, '4');
        press(&mut app, '1');
        app.on_key(KeyEvent::new(KeyCode::Char('s'), KeyModifiers::CONTROL));
        let store = SqliteStore::open(&path).unwrap();
        assert_eq!(
            store
                .cell_bytes_keyed("t", &crate::sqlite::RowKey::Rowid(1), "raw")
                .unwrap(),
            [0x41, 0xff],
            "the edited byte reached the database"
        );
        assert!(
            store
                .cell_is_blob_keyed("t", &crate::sqlite::RowKey::Rowid(1), "raw")
                .unwrap(),
            "still a blob, not text"
        );

        // A text cell in the same row still uses the line editor.
        app.on_key(KeyEvent::from(KeyCode::Esc)); // leave EDIT mode
        app.on_key(KeyEvent::from(KeyCode::Char('q')));
        app.on_key(KeyEvent::from(KeyCode::Right));
        press(&mut app, 'e');
        assert_eq!(app.screen, super::Screen::Main);
        assert!(
            matches!(app.mode, super::Mode::EditCell(_)),
            "text edits inline"
        );
        let _ = std::fs::remove_file(path);
    }

    /// `D` opens the database screen, its checks run on demand, and `q` still
    /// quits from there like it does everywhere else.
    #[test]
    fn dbinfo_screen_reports_and_checks_on_demand() {
        let (mut app, path) = sqlite_app_rows(3);
        press(&mut app, 'D');
        assert_eq!(app.screen, super::Screen::DbInfo);
        assert!(
            app.dbinfo.iter().any(|(k, _)| k == "page size"),
            "pragmas are read when the screen opens: {:?}",
            app.dbinfo
        );
        assert!(
            app.dbinfo_checks.is_empty(),
            "the slow checks wait for a keypress"
        );
        let rows = frame_rows(&mut app, 100, 24);
        assert!(contains(&rows, "journal mode"), "{rows:?}");
        assert!(contains(&rows, "database —"), "{:?}", rows[0]);

        // Both checks pass on a file this small, and the lint has nothing to say
        // about a table with no foreign keys.
        press(&mut app, 'i');
        assert_eq!(app.dbinfo_checks, vec!["integrity check: ok".to_string()]);
        press(&mut app, 'Q');
        assert_eq!(app.dbinfo_checks, vec!["quick check: ok".to_string()]);
        press(&mut app, 'f');
        assert_eq!(
            app.dbinfo_checks,
            vec!["foreign-key lint: every foreign key has an index".to_string()]
        );
        let rows = frame_rows(&mut app, 100, 24);
        assert!(contains(&rows, "every foreign key"), "{rows:?}");

        // The help overlay follows the screen, and `D` again goes back.
        press(&mut app, 'h');
        assert_eq!(app.help_ctx(), HelpCtx::DbInfo);
        press(&mut app, 'h');
        press(&mut app, 'D');
        assert_eq!(app.screen, super::Screen::Main);

        // The maintenance statements report what they did and refresh the pragmas
        // behind them, since all three rewrite the file.
        press(&mut app, 'D');
        press(&mut app, 'z');
        assert_eq!(app.dbinfo_checks.len(), 1);
        assert!(
            app.dbinfo_checks[0].starts_with("ANALYZE: done"),
            "got {:?}",
            app.dbinfo_checks[0]
        );
        press(&mut app, 'v');
        assert!(
            app.dbinfo_checks[0].starts_with("VACUUM: done"),
            "got {:?}",
            app.dbinfo_checks[0]
        );
        press(&mut app, 'r');
        assert!(
            app.dbinfo_checks[0].starts_with("REINDEX: done"),
            "got {:?}",
            app.dbinfo_checks[0]
        );
        assert!(
            app.dbinfo.iter().any(|(k, _)| k == "page count"),
            "the pragmas are re-read after a rewrite"
        );

        press(&mut app, 'q');
        assert!(app.quit, "q quits from the database screen too");
        let _ = std::fs::remove_file(path);
    }

    /// The overlay openers must work from the app's screens, and keys the
    /// overlay layer doesn't own must still reach the app.
    #[test]
    fn overlay_keys_route_through_the_app() {
        let mut app = rkyv_app();
        press(&mut app, 'h');
        assert!(app.ov.help, "h must open help");
        press(&mut app, 'j');
        assert!(!app.ov.help, "any key closes help");

        press(&mut app, 'c');
        assert!(app.ov.chooser, "c must open the scheme chooser");
        press(&mut app, 'c');
        assert!(!app.ov.chooser);

        press(&mut app, 'C');
        assert!(app.ov.editor, "C must open the palette editor");
        app.on_key(KeyEvent::from(KeyCode::Esc));
        assert!(!app.ov.editor);

        // `e` belongs to the data screens, not the overlays.
        press(&mut app, 'e');
        assert!(!app.ov.active(), "e must not open an overlay");
    }

    /// `h` is the help key, so it must not double as a column motion; the
    /// arrows own that.
    #[test]
    fn columns_move_with_arrows_and_h_opens_help() {
        let (mut app, path) = sqlite_app();
        app.on_key(KeyEvent::from(KeyCode::Tab)); // focus the row grid
        app.on_key(KeyEvent::from(KeyCode::Right));
        assert_eq!(app.col_idx, 1, "Right must move a column");
        app.on_key(KeyEvent::from(KeyCode::Left));
        assert_eq!(app.col_idx, 0, "Left must move back");

        app.on_key(KeyEvent::from(KeyCode::Right));
        press(&mut app, 'h');
        assert_eq!(app.col_idx, 1, "h must not move the column");
        assert!(app.ov.help, "h must open help instead");
        let _ = std::fs::remove_file(&path);
    }

    /// `s` cycles the row grid's sort on the cursor column (ascending →
    /// descending → off), reloads the page, and marks the column in its header.
    #[test]
    fn s_cycles_the_sort_on_the_cursor_column() {
        let (mut app, path) = sqlite_app();
        app.on_key(KeyEvent::from(KeyCode::Tab)); // focus the row grid
        app.on_key(KeyEvent::from(KeyCode::Right)); // cursor on column `b`
        assert!(app.sort.is_none(), "no sort until asked for");

        press(&mut app, 's');
        let sort = app.sort.as_ref().expect("s must sort");
        assert_eq!(sort.column, "b");
        assert!(!sort.desc, "first press sorts ascending");
        let rows = frame_rows(&mut app, 100, 20);
        assert!(contains(&rows, "b ▲"), "ascending marker missing");
        assert!(contains(&rows, "sorted by b ascending"), "no sort toast");

        press(&mut app, 's');
        assert!(app.sort.as_ref().unwrap().desc, "second press flips it");
        let rows = frame_rows(&mut app, 100, 20);
        assert!(contains(&rows, "b ▼"), "descending marker missing");

        press(&mut app, 's');
        assert!(app.sort.is_none(), "third press clears the sort");

        // `>` walks the sort to the next column, keeping the direction.
        press(&mut app, '>');
        assert_eq!(app.sort.as_ref().unwrap().column, "b");
        press(&mut app, '>');
        assert_eq!(app.sort.as_ref().unwrap().column, "c");
        press(&mut app, '<');
        assert_eq!(app.sort.as_ref().unwrap().column, "b");

        // Selecting another table drops a sort that named its columns.
        app.on_key(KeyEvent::from(KeyCode::Tab));
        app.select_table(0);
        assert!(app.sort.is_none(), "sort must not survive a table switch");
        let _ = std::fs::remove_file(&path);
    }

    /// An App over a real recognized shard on disk, so record edits exercise the
    /// actual rkyv write-back.
    fn script_shard_app() -> (App, std::path::PathBuf) {
        let path = scratch("rkyv");
        std::fs::write(
            &path,
            crate::formats::test_script_shard_bytes("/tmp/a.sh", b"old"),
        )
        .unwrap();
        let store = Store::Rkyv(RkyvStore::open(&path).unwrap());
        (
            App::with_theme(store, Theme::from_name(ThemeName::NeonSprawl)),
            path,
        )
    }

    /// `e` on a record opens the ported hex editor pre-filled with the record's
    /// current bytes — the point of the port: no retyping the whole value.
    #[test]
    fn e_opens_the_hex_editor_on_the_current_value() {
        let (mut app, path) = script_shard_app();
        assert_eq!(app.screen, super::Screen::Main);
        press(&mut app, 'e');
        assert_eq!(app.screen, super::Screen::HexEdit);
        let ed = app.hex.as_ref().expect("editor open");
        assert_eq!(ed.bytes, b"old", "pre-filled with the record's value");
        assert_eq!(ed.label, "/tmp/a.sh");

        let rows = frame_rows(&mut app, 90, 16);
        assert!(contains(&rows, "hex editor"), "editor not drawn");
        assert!(contains(&rows, "6f 6c 64"), "hex cells for \"old\"");
        assert!(contains(&rows, "|old"), "ascii gutter");
        let _ = std::fs::remove_file(&path);
    }

    /// Edits written with `^s` go through the real archive write-back and are
    /// visible in the reloaded records.
    #[test]
    fn hex_editor_saves_edited_bytes_back_into_the_archive() {
        let (mut app, path) = script_shard_app();
        press(&mut app, 'e');
        // EDIT mode, ascii column, overwrite "old" with "new".
        press(&mut app, 'i');
        app.on_key(KeyEvent::from(KeyCode::Tab));
        for c in "new".chars() {
            press(&mut app, c);
        }
        assert_eq!(app.hex.as_ref().unwrap().bytes, b"new");
        assert!(app.hex.as_ref().unwrap().dirty);

        app.on_key(KeyEvent::new(KeyCode::Char('s'), KeyModifiers::CONTROL));
        assert!(!app.hex.as_ref().unwrap().dirty, "save clears dirty");
        assert_eq!(
            app.decoded.as_ref().unwrap().records[0].value,
            b"new".to_vec(),
            "the reloaded record must carry the edited bytes"
        );
        // And the file on disk really changed.
        let on_disk = std::fs::read(&path).unwrap();
        assert!(
            crate::formats::try_decode(&on_disk).unwrap().records[0].value == b"new".to_vec(),
            "write-back must reach the file"
        );

        // In EDIT mode letters are data, so leave it first; then `q` closes on a
        // single press because the buffer is clean.
        app.on_key(KeyEvent::from(KeyCode::Esc));
        press(&mut app, 'q');
        assert_eq!(app.screen, super::Screen::Main);
        assert!(app.hex.is_none());
        let _ = std::fs::remove_file(&path);
    }

    /// Inside the editor the overlay openers must not steal `h` or `c` — they are
    /// motions and hex digits there.
    #[test]
    fn hex_editor_keeps_h_and_c_for_itself() {
        let (mut app, path) = script_shard_app();
        press(&mut app, 'e');
        press(&mut app, 'l');
        press(&mut app, 'h'); // motion, not help
        assert!(!app.ov.help, "h must not open help inside the editor");
        assert_eq!(app.screen, super::Screen::HexEdit);

        press(&mut app, 'i');
        press(&mut app, 'c'); // a hex digit, not the chooser
        assert!(
            !app.ov.chooser,
            "c must not open the chooser inside the editor"
        );
        // 'c' set the high nibble of 'o' (0x6f), keeping the low one.
        assert_eq!(app.hex.as_ref().unwrap().bytes[0], 0xcf);
        let _ = std::fs::remove_file(&path);
    }

    fn scan_hit(
        path: &str,
        kind: Kind,
        format: Option<&'static str>,
        secs: u64,
        rank: u8,
    ) -> crate::scan::Hit {
        crate::scan::Hit {
            path: path.into(),
            kind,
            format,
            size: 1024,
            modified: std::time::UNIX_EPOCH + std::time::Duration::from_secs(secs),
            rank,
        }
    }

    /// The list an index of the whole disk hands the picker is hundreds of rows,
    /// and it is merged again every time the picker opens — pressing Esc out of a
    /// file has to come straight back to the list. A per-pair filesystem lookup
    /// made that quadratic in syscalls, which is what this holds down.
    #[test]
    fn merging_a_whole_disk_index_is_not_quadratic() {
        let hits: Vec<crate::scan::Hit> = (0..600)
            .map(|i| {
                scan_hit(
                    &format!("/h/dir{}/file{i}.db", i % 40),
                    Kind::Sqlite,
                    None,
                    i as u64,
                    2,
                )
            })
            .collect();
        let mut choices: Vec<super::Choice> = Vec::new();
        let started = std::time::Instant::now();
        merge(&mut choices, hits.clone());
        // The second merge is the one a running walk repeats every frame: every
        // row is already listed, so every one takes the duplicate path.
        merge(&mut choices, hits);
        let took = started.elapsed();
        assert_eq!(choices.len(), 600);
        assert!(
            took < std::time::Duration::from_millis(50),
            "merging 600 rows twice took {took:?}"
        );
    }

    /// Scan hits are ordered by what the tool is for: recognized shards, then
    /// other rkyv archives, then databases — newest first within each group.
    #[test]
    fn scan_hits_are_ranked_before_being_shown() {
        let mut choices: Vec<super::Choice> = Vec::new();
        merge(
            &mut choices,
            vec![
                scan_hit("/h/.zshrs/compsys.db", Kind::Sqlite, None, 300, 2),
                scan_hit("/h/.zshrs/images/a.rkyv", Kind::Rkyv, None, 100, 1),
                scan_hit(
                    "/h/.zshrs/scripts.rkyv",
                    Kind::Rkyv,
                    Some("zshrs script cache (ZRSC)"),
                    50,
                    0,
                ),
                scan_hit("/h/.zshrs/index.rkyv", Kind::Rkyv, None, 200, 1),
            ],
        );
        let order: Vec<&str> = choices.iter().map(|c| c.name()).collect();
        assert_eq!(
            order,
            vec!["scripts.rkyv", "index.rkyv", "a.rkyv", "compsys.db"],
            "recognized shard first, then rkyv newest-first, then databases"
        );
    }

    /// A recent file the scan also finds must not appear twice, and must keep its
    /// recency position and age column.
    #[test]
    fn scan_hits_do_not_duplicate_recent_files() {
        let path = scratch("db");
        std::fs::write(&path, b"x").unwrap();
        let entry = Entry {
            path: path.clone(),
            kind: Kind::Sqlite,
            opened: std::time::SystemTime::now(),
        };
        let mut choices: Vec<super::Choice> = vec![super::Choice::from_entry(&entry)];
        merge(
            &mut choices,
            vec![
                crate::scan::Hit {
                    path: path.clone(),
                    kind: Kind::Sqlite,
                    format: None,
                    size: 1,
                    modified: std::time::SystemTime::now(),
                    rank: 2,
                },
                scan_hit("/h/other.db", Kind::Sqlite, None, 10, 2),
            ],
        );
        assert_eq!(choices.len(), 2, "the duplicate must be dropped");
        assert_eq!(choices[0].path, path);
        assert!(choices[0].opened.is_some(), "still a recent file");
        assert!(choices[1].path.ends_with("other.db"));
        let _ = std::fs::remove_file(&path);
    }

    /// The picker shows scan progress, the recent/scanned split, and the
    /// recognized format of the selected row.
    #[test]
    fn picker_shows_scan_progress_and_row_details() {
        let theme = crate::theme::Theme::from_name(ThemeName::NeonSprawl);
        let mut choices: Vec<super::Choice> = Vec::new();
        merge(
            &mut choices,
            vec![scan_hit(
                "/h/.zshrs/scripts.rkyv",
                Kind::Rkyv,
                Some("zshrs script cache (ZRSC)"),
                50,
                0,
            )],
        );
        let render = |choices: &[super::Choice], scanning: Option<usize>| -> Vec<String> {
            let mut term = Terminal::new(TestBackend::new(100, 8)).unwrap();
            term.draw(|f| {
                let view: Vec<usize> = (0..choices.len()).collect();
                super::render_picker(f, choices, &view, 0, "", None, scanning, None, &theme);
            })
            .unwrap();
            let buf = term.backend().buffer().clone();
            (0..buf.area().height)
                .map(|y| {
                    (0..buf.area().width)
                        .map(|x| buf[(x, y)].symbol())
                        .collect::<String>()
                })
                .collect()
        };

        let rows = render(&choices, Some(1));
        assert!(
            contains(&rows, "scanning… 1 found"),
            "no progress in the title"
        );
        assert!(contains(&rows, "1 files (0 recent)") || contains(&rows, "1 files"));
        assert!(contains(&rows, "scripts.rkyv"));
        assert!(contains(&rows, "1.0 K"), "size column for a scanned row");
        assert!(
            contains(&rows, "zshrs script cache (ZRSC)"),
            "selected row's format on the bottom line"
        );

        // Once the scan is done the progress text goes away.
        let rows = render(&choices, None);
        assert!(!contains(&rows, "scanning"));

        // With nothing found at all, the empty state explains what to do.
        let rows = render(&[], None);
        assert!(contains(&rows, "Nothing found."));
        assert!(contains(&rows, "--scan"));
        // While still scanning, it says so instead.
        let rows = render(&[], Some(0));
        assert!(contains(&rows, "Scanning for databases"));
    }

    /// `/` filters the list as the pattern is typed — the iftoprs model — instead
    /// of hopping between matches.
    #[test]
    fn slash_filters_the_records_list_while_typing() {
        let path = scratch("rkyv");
        let recs: Vec<(String, Vec<u8>)> = ["alpha", "bravo", "charlie", "delta"]
            .iter()
            .map(|n| (format!("/tmp/{n}.sh"), vec![b'x']))
            .collect();
        std::fs::write(&path, crate::formats::test_script_shard_bytes_many(&recs)).unwrap();
        let store = Store::Rkyv(RkyvStore::open(&path).unwrap());
        let mut app = App::with_theme(store, Theme::from_name(ThemeName::NeonSprawl));
        assert_eq!(app.visible_records().len(), 4);

        press(&mut app, '/');
        press(&mut app, 'a');
        // Only keys containing "a" stay listed: alpha, bravo, charlie, delta all
        // do, so narrow further.
        press(&mut app, 'l');
        let listed: Vec<String> = app
            .visible_records()
            .iter()
            .map(|&i| app.decoded.as_ref().unwrap().records[i].key.clone())
            .collect();
        assert_eq!(listed.len(), 1, "got {listed:?}");
        assert!(listed[0].contains("alpha"));
        assert!(app.status.contains("1 match"), "got {:?}", app.status);
        // The selection sits on a listed row.
        assert!(app.visible_records().contains(&app.record_idx));

        // The rendered list shows only the match.
        let rows = frame_rows(&mut app, 100, 16);
        assert!(contains(&rows, "alpha"));
        assert!(!contains(&rows, "bravo"), "filtered-out key still drawn");
        assert!(contains(&rows, "1/4 keys"), "count missing from the title");

        // Backspacing widens the filter again.
        app.on_key(KeyEvent::from(KeyCode::Backspace));
        assert_eq!(app.visible_records().len(), 4, "'a' matches every key");

        // A pattern matching nothing empties the list and says so.
        for c in "zzz".chars() {
            press(&mut app, c);
        }
        assert!(app.visible_records().is_empty());
        assert!(app.status.contains("0 matches"), "got {:?}", app.status);

        // Esc drops the filter and restores the position.
        app.on_key(KeyEvent::from(KeyCode::Esc));
        assert!(app.filter.is_empty(), "Esc must clear the filter");
        assert_eq!(app.visible_records().len(), 4);
        assert_eq!(app.record_idx, 0);

        // Enter keeps it applied.
        press(&mut app, '/');
        for c in "brav".chars() {
            press(&mut app, c);
        }
        app.on_key(KeyEvent::from(KeyCode::Enter));
        assert_eq!(app.filter, "brav", "Enter keeps the filter");
        assert_eq!(app.visible_records().len(), 1);
        let _ = std::fs::remove_file(&path);
    }

    /// Navigation stays inside the filtered list.
    #[test]
    fn navigation_skips_filtered_out_rows() {
        let path = scratch("rkyv");
        let recs: Vec<(String, Vec<u8>)> = ["a_one", "b_skip", "a_two", "c_skip", "a_three"]
            .iter()
            .map(|n| (format!("/tmp/{n}.sh"), vec![b'x']))
            .collect();
        std::fs::write(&path, crate::formats::test_script_shard_bytes_many(&recs)).unwrap();
        let store = Store::Rkyv(RkyvStore::open(&path).unwrap());
        let mut app = App::with_theme(store, Theme::from_name(ThemeName::NeonSprawl));
        press(&mut app, '/');
        for c in "a_".chars() {
            press(&mut app, c);
        }
        app.on_key(KeyEvent::from(KeyCode::Enter));
        let visible = app.visible_records();
        assert_eq!(visible.len(), 3, "three keys start with a_");
        app.record_idx = visible[0];
        for expected in &visible[1..] {
            press(&mut app, 'j');
            assert_eq!(
                app.record_idx, *expected,
                "j must land on the next listed row"
            );
        }
        // At the end it stays put rather than falling onto a hidden row.
        press(&mut app, 'j');
        assert_eq!(app.record_idx, *visible.last().unwrap());
        press(&mut app, 'k');
        assert_eq!(app.record_idx, visible[1]);
        let _ = std::fs::remove_file(&path);
    }

    /// The Strings view filters the same way.
    #[test]
    fn slash_filters_the_strings_view() {
        let mut app = rkyv_app_with(b"\x00\x00alpha\x00\x00bravo\x00\x00charlie\x00\x00");
        app.on_key(KeyEvent::from(KeyCode::Char('2')));
        let all = app.visible_strings().len();
        assert!(all >= 3, "{:?}", app.strings);
        press(&mut app, '/');
        for c in "brav".chars() {
            press(&mut app, c);
        }
        let listed = app.visible_strings();
        assert_eq!(listed.len(), 1);
        assert!(app.strings[listed[0]].text.contains("bravo"));
        let rows = frame_rows(&mut app, 100, 16);
        assert!(contains(&rows, "bravo") && !contains(&rows, "alpha"));
        app.on_key(KeyEvent::from(KeyCode::Esc));
        assert_eq!(app.visible_strings().len(), all);
    }

    /// SQLite rows are filtered in SQL, so the whole table is covered and the
    /// totals follow the filter rather than the page.
    #[test]
    fn slash_filters_sqlite_rows_across_the_whole_table() {
        let (mut app, path) = sqlite_app_rows(60);
        app.on_key(KeyEvent::from(KeyCode::Tab)); // focus the grid
        assert_eq!(app.rows.as_ref().unwrap().total, 60);
        press(&mut app, '/');
        press(&mut app, '4');
        let view = app.rows.as_ref().unwrap();
        // Rows 4, 14, 24, 34, 40..49, 54 contain a '4'.
        assert_eq!(view.total, 15, "total must count matches, not all rows");
        assert!(
            view.rows.iter().all(|r| r.iter().any(|c| c.contains('4'))),
            "every listed row must match: {:?}",
            view.rows
        );
        assert!(app.status.contains("15 matches"), "got {:?}", app.status);

        // Esc restores the unfiltered grid.
        app.on_key(KeyEvent::from(KeyCode::Esc));
        assert_eq!(app.rows.as_ref().unwrap().total, 60);
        assert!(app.filter.is_empty());
        let _ = std::fs::remove_file(&path);
    }

    /// The table list filters too.
    #[test]
    fn slash_filters_the_table_list() {
        let path = scratch("db");
        let conn = rusqlite::Connection::open(&path).unwrap();
        for t in ["users", "user_roles", "orders"] {
            conn.execute(&format!("CREATE TABLE {t} (x)"), []).unwrap();
        }
        drop(conn);
        let store = Store::Sqlite(SqliteStore::open(&path).unwrap());
        let mut app = App::with_theme(store, Theme::from_name(ThemeName::NeonSprawl));
        assert_eq!(app.visible_tables().len(), 3);
        press(&mut app, '/');
        for c in "user".chars() {
            press(&mut app, c);
        }
        assert_eq!(app.visible_tables().len(), 2);
        let rows = frame_rows(&mut app, 100, 16);
        assert!(contains(&rows, "users"));
        assert!(
            !contains(&rows, "orders"),
            "a filtered-out table is still on screen: {rows:#?}"
        );
        assert!(
            contains(&rows, "tables 2/3"),
            "count missing: {:?}",
            rows[0]
        );
        let _ = std::fs::remove_file(&path);
    }

    /// PageUp/PageDown must move by what is on screen. They used to be bound to
    /// the 500-row SQL window, which did nothing at all on a smaller table, and
    /// were missing outright from the Records and Strings views.
    #[test]
    fn paging_moves_by_a_screenful() {
        let (mut app, path) = sqlite_app_rows(120);
        app.on_key(KeyEvent::from(KeyCode::Tab)); // focus the grid
                                                  // A 24-row terminal keeps 23 rows for the body (one is the status bar),
                                                  // of which the grid shows 20 (two borders and a header row).
        frame_rows(&mut app, 80, 24);
        assert_eq!(app.page_rows, 20);
        app.on_key(KeyEvent::from(KeyCode::PageDown));
        assert_eq!(app.row_idx, 20, "PageDown moves one screenful");
        app.on_key(KeyEvent::from(KeyCode::PageDown));
        assert_eq!(app.row_idx, 40);
        app.on_key(KeyEvent::from(KeyCode::PageUp));
        assert_eq!(app.row_idx, 20);
        // Ctrl-f / Ctrl-b do the same.
        app.on_key(KeyEvent::new(KeyCode::Char('f'), KeyModifiers::CONTROL));
        assert_eq!(app.row_idx, 40);
        app.on_key(KeyEvent::new(KeyCode::Char('b'), KeyModifiers::CONTROL));
        assert_eq!(app.row_idx, 20);
        // Paging down past the end stops on the last row, it does not wrap.
        for _ in 0..20 {
            app.on_key(KeyEvent::from(KeyCode::PageDown));
        }
        assert_eq!(app.row_idx, 119, "clamps to the last loaded row");
        app.on_key(KeyEvent::from(KeyCode::PageUp));
        assert_eq!(app.row_idx, 99);
        // And up past the start stops at the top.
        for _ in 0..20 {
            app.on_key(KeyEvent::from(KeyCode::PageUp));
        }
        assert_eq!(app.row_idx, 0);
        let _ = std::fs::remove_file(&path);

        // A smaller terminal pages by less.
        let (mut app, path) = sqlite_app_rows(120);
        app.on_key(KeyEvent::from(KeyCode::Tab));
        frame_rows(&mut app, 80, 12);
        assert_eq!(app.page_rows, 8);
        app.on_key(KeyEvent::from(KeyCode::PageDown));
        assert_eq!(app.row_idx, 8);
        let _ = std::fs::remove_file(&path);
    }

    /// The rkyv views scroll their own index, and paging must reach all of them.
    #[test]
    fn paging_works_in_every_rkyv_view() {
        let mut app = rkyv_app_with(&vec![b'A'; 4096]);
        frame_rows(&mut app, 80, 24);
        let step = app.page_rows;
        assert!(step > 1);

        // Hex view: pages of rows, not a fixed 16 bytes.
        app.on_key(KeyEvent::from(KeyCode::Char('3')));
        app.on_key(KeyEvent::from(KeyCode::PageDown));
        assert_eq!(app.hex_row, step);
        app.on_key(KeyEvent::from(KeyCode::PageUp));
        assert_eq!(app.hex_row, 0);

        // Strings view: one long run of 'A's makes exactly one entry, so paging
        // clamps rather than running away.
        app.on_key(KeyEvent::from(KeyCode::Char('2')));
        app.on_key(KeyEvent::from(KeyCode::PageDown));
        assert_eq!(app.string_idx, app.strings.len().saturating_sub(1));
        app.on_key(KeyEvent::from(KeyCode::PageUp));
        assert_eq!(app.string_idx, 0);

        // Info scrolls nothing, and must not panic.
        app.on_key(KeyEvent::from(KeyCode::Char('1')));
        app.on_key(KeyEvent::from(KeyCode::PageDown));
    }

    /// Records paging walks the record list.
    #[test]
    fn paging_walks_the_records_view() {
        let path = scratch("rkyv");
        // 40 records, so a page is bounded by the record count.
        let mut keys: Vec<(String, Vec<u8>)> = Vec::new();
        for i in 0..40 {
            keys.push((format!("/tmp/s{i:02}.sh"), vec![b'x']));
        }
        std::fs::write(&path, crate::formats::test_script_shard_bytes_many(&keys)).unwrap();
        let store = Store::Rkyv(RkyvStore::open(&path).unwrap());
        let mut app = App::with_theme(store, Theme::from_name(ThemeName::NeonSprawl));
        frame_rows(&mut app, 80, 14);
        let step = app.page_rows;
        assert_eq!(app.record_idx, 0);
        app.on_key(KeyEvent::from(KeyCode::PageDown));
        assert_eq!(app.record_idx, step);
        app.on_key(KeyEvent::from(KeyCode::PageUp));
        assert_eq!(app.record_idx, 0);
        for _ in 0..20 {
            app.on_key(KeyEvent::from(KeyCode::PageDown));
        }
        assert_eq!(app.record_idx, 39, "clamps to the last record");
        let _ = std::fs::remove_file(&path);
    }

    /// The detail screen's value pane and the schema view page too.
    #[test]
    fn paging_scrolls_the_detail_and_schema_screens() {
        let (mut app, path) = sqlite_app_rows(5);
        app.on_key(KeyEvent::from(KeyCode::Tab));
        app.on_key(KeyEvent::from(KeyCode::Enter)); // detail
        assert_eq!(app.screen, super::Screen::Detail);
        app.detail_value = vec![0u8; 16 * 400];
        frame_rows(&mut app, 80, 30);
        let step = app.page_rows;
        assert!(step > 1);
        app.on_key(KeyEvent::from(KeyCode::PageDown));
        assert_eq!(app.detail_scroll, step);
        app.on_key(KeyEvent::from(KeyCode::PageUp));
        assert_eq!(app.detail_scroll, 0);
        app.on_key(KeyEvent::from(KeyCode::Esc));

        app.on_key(KeyEvent::from(KeyCode::Char('S'))); // schema
        assert_eq!(app.screen, super::Screen::Schema);
        frame_rows(&mut app, 80, 30);
        let step = app.page_rows;
        app.on_key(KeyEvent::from(KeyCode::PageDown));
        assert_eq!(app.schema_scroll, step);
        app.on_key(KeyEvent::from(KeyCode::PageUp));
        assert_eq!(app.schema_scroll, 0);
        let _ = std::fs::remove_file(&path);
    }

    /// Esc on the first level backs out to the file list; `q` is what quits. Esc
    /// inside a nested screen still just leaves that screen.
    #[test]
    fn esc_on_the_first_level_returns_to_the_file_list() {
        // rkyv main screen.
        let mut app = rkyv_app();
        app.on_key(KeyEvent::from(KeyCode::Esc));
        assert!(app.reopen, "Esc must ask for the file list");
        assert!(app.quit, "and end the app loop");

        // `q` still quits outright.
        let mut app = rkyv_app();
        press(&mut app, 'q');
        assert!(app.quit);
        assert!(!app.reopen, "q must not reopen the picker");

        // SQLite main screen behaves the same.
        let (mut app, path) = sqlite_app();
        app.on_key(KeyEvent::from(KeyCode::Esc));
        assert!(app.reopen && app.quit);
        let _ = std::fs::remove_file(&path);

        // A nested screen keeps Esc for backing out of itself.
        let (mut app, path) = script_shard_app();
        app.on_key(KeyEvent::from(KeyCode::Enter)); // detail
        assert_eq!(app.screen, super::Screen::Detail);
        app.on_key(KeyEvent::from(KeyCode::Esc));
        assert_eq!(app.screen, super::Screen::Main);
        assert!(
            !app.reopen,
            "Esc in a nested screen must not leave the file"
        );
        assert!(!app.quit);
        // From the main screen the next Esc does back out.
        app.on_key(KeyEvent::from(KeyCode::Esc));
        assert!(app.reopen && app.quit);
        let _ = std::fs::remove_file(&path);
    }

    /// `o` leaves the app loop asking for the picker again, rather than quitting.
    #[test]
    fn o_returns_to_the_file_picker() {
        let mut app = rkyv_app();
        assert!(!app.reopen);
        press(&mut app, 'o');
        assert!(app.reopen, "o must ask for the picker");
        assert!(app.quit, "and end the app loop");

        // Inside the hex editor `o` is an insert, not a way out.
        let (mut app, path) = script_shard_app();
        press(&mut app, 'e');
        let before = app.hex.as_ref().unwrap().bytes.len();
        press(&mut app, 'o');
        assert!(!app.reopen, "the editor keeps o for inserting a byte");
        assert_eq!(app.hex.as_ref().unwrap().bytes.len(), before + 1);
        let _ = std::fs::remove_file(&path);
    }

    /// `:` opens the SQL editor and a statement runs through it: a SELECT comes
    /// back as rows (the old prompt reported only an affected count), a write
    /// reports what it changed and reloads the grid, and a bad statement shows
    /// SQLite's own message.
    #[test]
    fn sql_editor_runs_statements_and_shows_results() {
        use crate::sqledit::Entry;
        let (mut app, path) = sqlite_app_rows(5);
        press(&mut app, ':');
        assert_eq!(app.screen, super::Screen::Sql);
        assert!(app.sql.is_some(), "the editor is open");

        // A SELECT returns rows.
        app.execute_sql("SELECT a FROM t ORDER BY a LIMIT 2");
        // Each statement is timed, as the shell's `.timer` does, so the rows sit
        // one entry back.
        let log = app.sql.as_ref().unwrap().transcript();
        assert!(
            matches!(log.last(), Some(Entry::Timing(_))),
            "the run is timed: {:?}",
            log.last()
        );
        match &log[log.len() - 2] {
            Entry::Rows {
                columns,
                rows,
                truncated,
            } => {
                assert_eq!(columns, &["a".to_string()]);
                assert_eq!(rows.len(), 2, "two rows for LIMIT 2");
                assert!(!truncated);
            }
            other => panic!("expected rows, got {other:?}"),
        }

        // A write reports its change count and the grid reloads with it.
        app.execute_sql("UPDATE t SET b = 'z'");
        let log = app.sql.as_ref().unwrap().transcript();
        assert_eq!(log[log.len() - 2], Entry::Changed(5));
        assert!(
            app.rows.as_ref().unwrap().rows.iter().all(|r| r[1] == "z"),
            "the grid must show the write"
        );

        // A bad statement surfaces the error rather than a bare status line.
        app.execute_sql("SELECT * FROM nope");
        let log = app.sql.as_ref().unwrap().transcript();
        match &log[log.len() - 2] {
            Entry::Error(msg) => assert!(msg.contains("nope"), "got {msg:?}"),
            other => panic!("expected an error, got {other:?}"),
        }

        // Alt-e explains instead of running: the plan lands in the transcript and
        // the table is untouched.
        app.on_key(KeyEvent::new(KeyCode::Char('a'), KeyModifiers::NONE));
        let mut e = KeyEvent::from(KeyCode::Char('e'));
        e.modifiers = KeyModifiers::ALT;
        app.on_key(KeyEvent::new(KeyCode::Char('g'), KeyModifiers::CONTROL));
        for c in "SELECT * FROM t".chars() {
            app.on_key(KeyEvent::from(KeyCode::Char(c)));
        }
        app.on_key(e);
        let log = app.sql.as_ref().unwrap().transcript();
        let plan = log
            .iter()
            .rev()
            .find_map(|x| match x {
                Entry::Plan(steps) => Some(steps.clone()),
                _ => None,
            })
            .expect("a plan entry");
        assert!(
            plan.iter()
                .any(|s| s.contains("SCAN") || s.contains("TABLE")),
            "plan should name a scan: {plan:?}"
        );

        // The editor draws over the app, and Esc returns to the data with the
        // transcript intact for the next visit.
        let rows = frame_rows(&mut app, 100, 20);
        assert!(contains(&rows, "SQL —"), "editor not drawn: {:?}", rows[0]);
        assert!(contains(&rows, "no such table"), "error not on screen");
        app.on_key(KeyEvent::from(KeyCode::Esc));
        assert_eq!(app.screen, super::Screen::Main);
        press(&mut app, ':');
        assert!(
            !app.sql.as_ref().unwrap().transcript().is_empty(),
            "reopening keeps the transcript"
        );
        let _ = std::fs::remove_file(&path);
    }

    /// The write monitor: `w` opens it, it shows the watched stores, and rows
    /// light up as bytes land.
    #[test]
    fn write_monitor_shows_live_writes() {
        use std::io::Write;
        let mut app = rkyv_app();
        press(&mut app, 'w');
        assert_eq!(app.screen, super::Screen::Top);
        let watcher = app.top.as_ref().expect("watcher running");
        assert!(
            !watcher.is_empty(),
            "the open file must be watched at least"
        );
        assert!(app.status.contains("watching"), "got {:?}", app.status);
        assert_eq!(app.help_ctx(), HelpCtx::Top);

        // Watch a file we can write to, then write to it.
        let path = scratch("rkyv");
        std::fs::write(&path, b"start").unwrap();
        app.top = Some(crate::monitor::Monitor::new([(path.clone(), Kind::Rkyv)]));
        let rows = frame_rows(&mut app, 110, 14);
        assert!(
            contains(&rows, "writes —"),
            "no monitor header: {:?}",
            rows[0]
        );
        assert!(contains(&rows, "activity"), "no column header");
        assert!(contains(&rows, "0 active"), "nothing should be active yet");

        {
            let mut f = std::fs::OpenOptions::new()
                .append(true)
                .open(&path)
                .unwrap();
            f.write_all(&[b'x'; 4096]).unwrap();
        }
        // Force a sample the way the event loop's tick does.
        let m = app.top.as_mut().unwrap();
        m.watcher.interval = std::time::Duration::ZERO;
        assert!(m.tick());
        m.watcher.interval = crate::watch::DEFAULT_INTERVAL;

        let rows = frame_rows(&mut app, 110, 14);
        assert!(contains(&rows, "1 active"), "the write was not noticed");
        assert!(contains(&rows, "4.0 K"), "written bytes missing: {rows:#?}");
        assert!(
            rows.iter().any(|r| r.contains('') || r.contains('')),
            "no activity sparkline drawn"
        );

        // Sorting, pausing and the sample interval are all reachable.
        let before = app.top.as_ref().unwrap().sort;
        press(&mut app, 's');
        assert_ne!(app.top.as_ref().unwrap().sort, before);
        assert!(app.status.contains("sorted by"));
        press(&mut app, 'p');
        assert!(app.top.as_ref().unwrap().watcher.paused);
        assert!(contains(&frame_rows(&mut app, 110, 14), "PAUSED"));
        press(&mut app, 'p');
        assert!(!app.top.as_ref().unwrap().watcher.paused);
        let iv = app.top.as_ref().unwrap().watcher.interval;
        press(&mut app, '+');
        assert!(
            app.top.as_ref().unwrap().watcher.interval < iv,
            "+ samples faster"
        );
        press(&mut app, '-');
        assert_eq!(app.top.as_ref().unwrap().watcher.interval, iv);

        // Enter hands the selected file to the caller instead of opening it here.
        app.on_key(KeyEvent::from(KeyCode::Enter));
        assert_eq!(app.open_next(), Some(path.clone()));
        assert!(app.reopen && app.quit);

        // `w` again (or Esc) leaves the monitor.
        let mut app = rkyv_app();
        press(&mut app, 'w');
        press(&mut app, 'w');
        assert_eq!(app.screen, super::Screen::Main);
        assert!(app.top.is_none(), "the watcher is dropped on the way out");
        let _ = std::fs::remove_file(&path);
    }

    /// Opening a file must keep the scheme the picker was showing. It used to
    /// re-read prefs, so a concurrent write (or any drift) reset the colours on
    /// open — "randomly resetting my colorscheme when I click a file".
    #[test]
    fn opening_a_file_keeps_the_picker_scheme() {
        let path = scratch("rkyv");
        std::fs::write(
            &path,
            crate::formats::test_script_shard_bytes("/tmp/a.sh", b"x"),
        )
        .unwrap();
        let store = Store::Rkyv(RkyvStore::open(&path).unwrap());

        // Whatever prefs say, the handed-over scheme is what the app shows.
        let handed = Theme::from_name(ThemeName::BladeRunner);
        let app = App::with_theme(store, handed);
        assert_eq!(app.theme().name, ThemeName::BladeRunner);
        assert_eq!(app.theme().accent, handed.accent);

        // A custom palette survives the hand-over too, which `Theme::from_name`
        // alone would have flattened back to the scheme's stock colours.
        let store = Store::Rkyv(RkyvStore::open(&path).unwrap());
        let custom = Theme::from_palette(ThemeName::BladeRunner, [10, 20, 30, 40, 50, 60]);
        let app = App::with_theme(store, custom);
        assert_eq!(app.theme().accent, ratatui::style::Color::Indexed(20));
        assert_eq!(app.theme().primary, ratatui::style::Color::Indexed(10));

        // And the app reports back whatever it ended on, so the picker resumes
        // in the same scheme.
        let store = Store::Rkyv(RkyvStore::open(&path).unwrap());
        let mut app = App::with_theme(store, handed);
        press(&mut app, 'c');
        app.on_key(KeyEvent::from(KeyCode::Down));
        let previewed = app.theme().name;
        assert_ne!(previewed, ThemeName::BladeRunner, "chooser previews live");
        assert_eq!(
            app.theme().name,
            previewed,
            "theme() reports the live scheme"
        );
        let _ = std::fs::remove_file(&path);
    }

    /// The arrows must keep working while a filter prompt is open — they were
    /// swallowed by the prompt, so the list froze as soon as `/` was pressed.
    #[test]
    fn arrows_navigate_while_the_filter_prompt_is_open() {
        // rkyv Records: three of five keys match, and Up/Down walk those three.
        let path = scratch("rkyv");
        let recs: Vec<(String, Vec<u8>)> = ["a_one", "b_skip", "a_two", "c_skip", "a_three"]
            .iter()
            .map(|n| (format!("/tmp/{n}.sh"), vec![b'x']))
            .collect();
        std::fs::write(&path, crate::formats::test_script_shard_bytes_many(&recs)).unwrap();
        let store = Store::Rkyv(RkyvStore::open(&path).unwrap());
        let mut app = App::with_theme(store, Theme::from_name(ThemeName::NeonSprawl));
        press(&mut app, '/');
        for c in "a_".chars() {
            press(&mut app, c);
        }
        let visible = app.visible_records();
        assert_eq!(visible.len(), 3);
        assert!(
            matches!(app.mode, super::Mode::Search(_)),
            "prompt must stay open"
        );

        app.on_key(KeyEvent::from(KeyCode::Down));
        assert!(
            matches!(app.mode, super::Mode::Search(_)),
            "Down must not close it"
        );
        assert_eq!(app.record_idx, visible[1], "Down moves within the matches");
        app.on_key(KeyEvent::from(KeyCode::Down));
        assert_eq!(app.record_idx, visible[2]);
        app.on_key(KeyEvent::from(KeyCode::Down));
        assert_eq!(app.record_idx, visible[2], "clamps at the last match");
        app.on_key(KeyEvent::from(KeyCode::Up));
        assert_eq!(app.record_idx, visible[1]);

        // Typing more still narrows from the top.
        press(&mut app, 't');
        assert_eq!(app.visible_records().len(), 2, "a_two and a_three");
        let _ = std::fs::remove_file(&path);

        // SQLite rows: Down moves inside the filtered page.
        let (mut app, path) = sqlite_app_rows(60);
        app.on_key(KeyEvent::from(KeyCode::Tab));
        press(&mut app, '/');
        press(&mut app, '4');
        assert_eq!(app.row_idx, 0);
        app.on_key(KeyEvent::from(KeyCode::Down));
        assert_eq!(app.row_idx, 1, "Down must move the filtered grid");
        app.on_key(KeyEvent::from(KeyCode::Up));
        assert_eq!(app.row_idx, 0);
        // Paging works from the prompt too.
        frame_rows(&mut app, 80, 24);
        app.on_key(KeyEvent::from(KeyCode::PageDown));
        assert!(app.row_idx > 0);
        assert!(matches!(app.mode, super::Mode::Search(_)), "still typing");
        let _ = std::fs::remove_file(&path);
    }

    /// The picker's prompt behaves the same way.
    #[test]
    fn picker_prompt_keys_navigate_and_edit() {
        use super::{filter_prompt_key, Prompt};
        let mut filter = String::new();
        let mut sel = 0usize;
        let (last, page) = (9usize, 4usize);

        // Typing narrows and resets to the top of the new list.
        assert_eq!(
            filter_prompt_key(KeyCode::Char('z'), &mut filter, &mut sel, last, page),
            Prompt::Open
        );
        assert_eq!(filter, "z");
        assert_eq!(sel, 0);

        // Arrows move the selection without touching the pattern.
        filter_prompt_key(KeyCode::Down, &mut filter, &mut sel, last, page);
        filter_prompt_key(KeyCode::Down, &mut filter, &mut sel, last, page);
        assert_eq!((sel, filter.as_str()), (2, "z"));
        filter_prompt_key(KeyCode::Up, &mut filter, &mut sel, last, page);
        assert_eq!(sel, 1);
        filter_prompt_key(KeyCode::PageDown, &mut filter, &mut sel, last, page);
        assert_eq!(sel, 5);
        filter_prompt_key(KeyCode::PageUp, &mut filter, &mut sel, last, page);
        assert_eq!(sel, 1);
        filter_prompt_key(KeyCode::End, &mut filter, &mut sel, last, page);
        assert_eq!(sel, last, "End goes to the last match");
        filter_prompt_key(KeyCode::Home, &mut filter, &mut sel, last, page);
        assert_eq!(sel, 0);
        // Clamped at both ends.
        filter_prompt_key(KeyCode::Up, &mut filter, &mut sel, last, page);
        assert_eq!(sel, 0);
        sel = last;
        filter_prompt_key(KeyCode::Down, &mut filter, &mut sel, last, page);
        assert_eq!(sel, last);

        // Backspace edits and returns to the top.
        filter_prompt_key(KeyCode::Backspace, &mut filter, &mut sel, last, page);
        assert!(filter.is_empty());
        assert_eq!(sel, 0);

        assert_eq!(
            filter_prompt_key(KeyCode::Enter, &mut filter, &mut sel, last, page),
            Prompt::Accept
        );
        assert_eq!(
            filter_prompt_key(KeyCode::Esc, &mut filter, &mut sel, last, page),
            Prompt::Cancel
        );
    }

    /// The picker's `/` must remove rows, not just move the cursor.
    #[test]
    fn picker_filter_removes_rows_from_the_list() {
        let theme = crate::theme::Theme::from_name(ThemeName::NeonSprawl);
        let mut choices: Vec<super::Choice> = Vec::new();
        merge(
            &mut choices,
            vec![
                scan_hit("/h/.zshrs/scripts.rkyv", Kind::Rkyv, None, 30, 1),
                scan_hit("/h/.zshrs/compsys.db", Kind::Sqlite, None, 20, 2),
                scan_hit("/h/.pythonrs/scripts.rkyv", Kind::Rkyv, None, 10, 1),
            ],
        );
        let render = |filter: &str| -> Vec<String> {
            let view: Vec<usize> = choices
                .iter()
                .enumerate()
                .filter(|(_, c)| super::filter_passes(filter, c.path.to_str().unwrap()))
                .map(|(i, _)| i)
                .collect();
            let mut term = Terminal::new(TestBackend::new(100, 10)).unwrap();
            term.draw(|f| {
                super::render_picker(f, &choices, &view, 0, filter, None, None, None, &theme);
            })
            .unwrap();
            let buf = term.backend().buffer().clone();
            (0..buf.area().height)
                .map(|y| {
                    (0..buf.area().width)
                        .map(|x| buf[(x, y)].symbol())
                        .collect::<String>()
                })
                .collect()
        };

        // Unfiltered: all three.
        let rows = render("");
        assert!(contains(&rows, "compsys.db"));
        assert!(contains(&rows, "3 files"));

        // Filtering by directory drops the pythonrs row entirely.
        let rows = render("zshrs");
        assert!(contains(&rows, "scripts.rkyv") && contains(&rows, "compsys.db"));
        assert!(
            !contains(&rows, ".pythonrs"),
            "a filtered-out row is still listed: {rows:#?}"
        );
        assert!(contains(&rows, "2/3 files"), "count missing: {:?}", rows[0]);
        assert!(contains(&rows, "/zshrs"), "the pattern must be shown");

        // Filtering by name works the same way.
        let rows = render("compsys");
        assert!(contains(&rows, "compsys.db") && !contains(&rows, "pythonrs"));
        assert!(contains(&rows, "1/3 files"));

        // No match: the list is empty and says how to get out.
        let rows = render("nothing-matches-this");
        assert!(contains(&rows, "Nothing matches"));
        assert!(contains(&rows, "Esc clears the filter"));
    }

    /// Rows restored from the saved scan are labelled with their age, so it is
    /// clear the list was not just walked.
    #[test]
    fn picker_titles_a_reused_scan_with_its_age() {
        let theme = crate::theme::Theme::from_name(ThemeName::NeonSprawl);
        let mut choices: Vec<super::Choice> = Vec::new();
        merge(
            &mut choices,
            vec![scan_hit("/h/.zshrs/scripts.rkyv", Kind::Rkyv, None, 50, 1)],
        );
        let render = |age: Option<std::time::Duration>| -> Vec<String> {
            let mut term = Terminal::new(TestBackend::new(100, 6)).unwrap();
            term.draw(|f| {
                let view: Vec<usize> = (0..choices.len()).collect();
                super::render_picker(f, &choices, &view, 0, "", None, None, age, &theme);
            })
            .unwrap();
            let buf = term.backend().buffer().clone();
            (0..buf.area().height)
                .map(|y| {
                    (0..buf.area().width)
                        .map(|x| buf[(x, y)].symbol())
                        .collect::<String>()
                })
                .collect()
        };
        let rows = render(Some(std::time::Duration::from_secs(3 * 3600)));
        assert!(contains(&rows, "scan 3h old"), "age missing: {:?}", rows[0]);
        assert!(contains(&rows, "r rescans"), "no way to refresh advertised");
        // A walk that just finished says so instead of showing hours.
        let rows = render(Some(std::time::Duration::ZERO));
        assert!(contains(&rows, "just now"));
        // Without a saved scan the title is plain.
        let rows = render(None);
        assert!(!contains(&rows, "rescans"));
    }

    #[test]
    fn age_labels_read_naturally() {
        use std::time::Duration;
        assert_eq!(super::age_label(Duration::from_secs(5)), "just now");
        assert_eq!(super::age_label(Duration::from_secs(600)), "10m old");
        assert_eq!(super::age_label(Duration::from_secs(7200)), "2h old");
        assert_eq!(super::age_label(Duration::from_secs(3 * 86_400)), "3d old");
    }

    /// Opening a large archive must not block: the 382MB shard here took 25s to
    /// validate, which read as a hang. It now opens on the structural view and
    /// the decode lands later.
    #[test]
    fn a_large_archive_opens_without_blocking() {
        // A buffer past the inline limit that is not a recognized shard, so the
        // background decode returns None.
        let big = vec![0x41u8; super::DECODE_INLINE_MAX + 1024];
        let t0 = std::time::Instant::now();
        let mut app = rkyv_app_with(&big);
        let open = t0.elapsed();
        assert!(
            open < std::time::Duration::from_secs(2),
            "opening took {open:?}"
        );
        assert!(
            app.decoding.is_some(),
            "decode must be running in the background"
        );
        assert!(app.decoded.is_none(), "and not have blocked for the result");
        assert_eq!(app.rkyv_view, super::RkyvView::Info);
        assert!(app.status.contains("decoding"), "got {:?}", app.status);

        // Records is not reachable until it lands, and says so.
        app.on_key(KeyEvent::from(KeyCode::Char('0')));
        assert_eq!(app.rkyv_view, super::RkyvView::Info);
        assert!(
            app.status.contains("still decoding"),
            "got {:?}",
            app.status
        );

        // Wait for the thread, then install the result the way the loop does.
        let rx = app.decoding.as_ref().unwrap();
        let _ = rx.recv_timeout(std::time::Duration::from_secs(30));
        app.poll_decode();
        assert!(
            app.decoding.is_none(),
            "the receiver is dropped once it lands"
        );
        assert!(app.decoded.is_none(), "0x41 filler is not a shard");
        assert!(app.status.contains("unrecognized"), "got {:?}", app.status);

        // A small archive still decodes inline, so nothing changed for shards.
        let (app, path) = script_shard_app();
        assert!(app.decoding.is_none());
        assert!(app.decoded.is_some(), "small shards decode on open");
        let _ = std::fs::remove_file(&path);
    }

    /// String extraction is bounded, so a huge archive cannot stall the open.
    #[test]
    fn string_extraction_is_bounded() {
        // Alternating printable runs and NULs: one run per 8 bytes, far more runs
        // than the cap allows.
        let mut bytes = Vec::new();
        while bytes.len() < 400_000 {
            bytes.extend_from_slice(b"abcdefg\x00");
        }
        let path = scratch("bin");
        std::fs::write(&path, &bytes).unwrap();
        let store = RkyvStore::open(&path).unwrap();
        let t0 = std::time::Instant::now();
        let s = store.strings(4);
        let took = t0.elapsed();
        assert!(took < std::time::Duration::from_secs(1), "took {took:?}");
        assert!(s.hits.len() <= 20_000, "cap ignored: {}", s.hits.len());
        assert!(s.truncated, "truncation must be reported");
        let _ = std::fs::remove_file(&path);

        // A small file is complete, not flagged.
        let path = scratch("bin");
        std::fs::write(&path, b"hello\x00world\x00").unwrap();
        let store = RkyvStore::open(&path).unwrap();
        let s = store.strings(4);
        assert_eq!(s.hits.len(), 2);
        assert!(!s.truncated);
        assert_eq!(s.scanned, 12);
        let _ = std::fs::remove_file(&path);
    }

    /// Help lists the section for what is on screen.
    #[test]
    fn help_ctx_follows_the_screen() {
        assert_eq!(rkyv_app().help_ctx(), HelpCtx::Rkyv);
        let (app, path) = sqlite_app();
        assert_eq!(app.help_ctx(), HelpCtx::Sqlite);
        let _ = std::fs::remove_file(&path);

        let (mut app, path) = script_shard_app();
        press(&mut app, 'e');
        assert_eq!(app.help_ctx(), HelpCtx::HexEdit);
        let _ = std::fs::remove_file(&path);
    }

    /// Action results must raise a toast as well as land in the status bar.
    #[test]
    fn action_results_raise_a_toast() {
        let mut app = rkyv_app();
        assert!(app.ov.toast.is_none(), "no toast before any action");
        // Export on an unrecognized archive: reports that there is nothing to
        // write, without touching the filesystem.
        press(&mut app, 'x');
        let toast = app.ov.toast.as_ref().expect("an action must toast");
        assert!(!toast.text.is_empty());
        assert_eq!(app.status, toast.text, "status bar keeps the same text");
    }

    /// The overlay draws over the app's own screen, including a nested one.
    #[test]
    fn overlays_render_over_the_app_screens() {
        let mut app = rkyv_app();
        app.ov.help = true;
        let rows = frame_rows(&mut app, 100, 40);
        assert!(contains(&rows, "KEYBOARD SHORTCUTS"));
        assert!(contains(&rows, "RKYV"), "store section missing");

        app.ov.help = false;
        app.screen = super::Screen::Detail;
        app.ov.toast("copied 12 bytes to clipboard");
        let rows = frame_rows(&mut app, 100, 40);
        assert!(
            contains(&rows, "copied 12 bytes"),
            "toast missing on detail"
        );
    }

    #[test]
    fn cursor_left_right_utf8() {
        // "aé" — 'é' is 2 bytes, so byte offsets are 0,1,3.
        let s = "";
        assert_eq!(input_right(s, 0), 1); // past 'a'
        assert_eq!(input_right(s, 1), 3); // past 'é'
        assert_eq!(input_right(s, 3), 3); // at end, stays
        assert_eq!(input_left(s, 3), 1); // before 'é'
        assert_eq!(input_left(s, 1), 0);
        assert_eq!(input_left(s, 0), 0);
    }

    #[test]
    fn delete_word_skips_trailing_space() {
        let mut s = String::from("foo bar  ");
        let len = s.len();
        let cur = input_delete_word(&mut s, len);
        assert_eq!(s, "foo ");
        assert_eq!(cur, 4);
    }

    #[test]
    fn hit_testing() {
        let r = Rect::new(2, 3, 10, 5); // x=2..12, y=3..8
        assert!(hit(r, 2, 3));
        assert!(hit(r, 11, 7));
        assert!(!hit(r, 12, 3)); // just past right edge
        assert!(!hit(r, 2, 8)); // just past bottom edge
        assert!(!hit(r, 1, 3));
    }

    #[test]
    fn find_next_forward_wraps() {
        // matches at indices 1 and 3 of a length-5 range
        let pred = |i: usize| i == 1 || i == 3;
        assert_eq!(find_next(5, 0, true, pred), Some(1));
        assert_eq!(find_next(5, 1, true, pred), Some(3));
        assert_eq!(find_next(5, 3, true, pred), Some(1)); // wrap past end
        assert_eq!(find_next(5, 4, true, pred), Some(1));
    }

    #[test]
    fn find_next_backward_wraps() {
        let pred = |i: usize| i == 1 || i == 3;
        assert_eq!(find_next(5, 4, false, pred), Some(3));
        assert_eq!(find_next(5, 3, false, pred), Some(1));
        assert_eq!(find_next(5, 1, false, pred), Some(3)); // wrap past start
        assert_eq!(find_next(5, 0, false, pred), Some(3));
    }

    #[test]
    fn find_next_none_and_empty() {
        assert_eq!(find_next(5, 0, true, |_| false), None);
        assert_eq!(find_next(0, 0, true, |_| true), None);
    }

    #[test]
    fn find_bytes_forward_and_backward() {
        let hay = b"abXYabZZab"; // "ab" at 0, 4, 8
        assert_eq!(find_bytes(hay, b"ab", 0, true), Some(4));
        assert_eq!(find_bytes(hay, b"ab", 4, true), Some(8));
        assert_eq!(find_bytes(hay, b"ab", 8, true), None); // nothing after
        assert_eq!(find_bytes(hay, b"ab", 8, false), Some(4));
        assert_eq!(find_bytes(hay, b"ab", 4, false), Some(0));
        assert_eq!(find_bytes(hay, b"zz", 0, true), None); // case-sensitive
        assert_eq!(find_bytes(hay, b"", 0, true), None);
    }
}