tomesole 0.1.2

A terminal client (TUI and CLI) for searching and downloading from Library Genesis
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
//! The full-screen interface.
//!
//! Everything slow — resolving a mirror, searching, downloading — happens on a
//! worker thread and reports back over a channel. The UI thread only ever waits
//! on that channel, so the interface stays responsive while a 40 MB file is
//! coming down, and a mirror that takes ten seconds to answer never freezes the
//! display.
//!
//! Downloads run one at a time. That is deliberate: firing off eight parallel
//! requests at a volunteer-run mirror is a good way to get rate-limited, and it
//! makes the progress display much easier to read.

use std::collections::{HashMap, HashSet};
use std::io::{self, Write};
use std::sync::mpsc::{self, Receiver, RecvTimeoutError, Sender};
use std::time::{Duration, Instant};

use crossterm::event::{self, Event as CtEvent, KeyCode, KeyEvent, KeyEventKind, KeyModifiers};
use crossterm::{ExecutableCommand, terminal::SetTitle};
use ratatui::prelude::*;
use ratatui::widgets::{
    Block, BorderType, Cell, Clear, Paragraph, Row, Scrollbar, ScrollbarOrientation,
    ScrollbarState, Table, TableState, Wrap,
};
use ureq::http::Uri;

use crate::cover::Cover;
use crate::error::Result;
use crate::graphics::{self, Protocol};
use crate::mirror::{Pool, ResolveOptions};
use crate::model::{Book, SearchQuery, human_bytes};
use crate::net::Http;
use std::path::PathBuf;

use crate::config::Config;
use crate::model::Topic;
use crate::{Settings, cover, download, history, launch, libgen, mirror, net, query};

/// The visual language, in one place so the whole interface stays coherent.
///
/// The interface paints its own canvas — a deep blue-grey — rather than
/// inheriting the terminal background, so contrast is something it owns.
/// Colour then carries meaning: teal is interactive (the cursor, the keys, the
/// active tab), amber is emphasis (a narrowed count, a marked row), every file
/// format keeps one hue of its own so a column of results reads at a glance,
/// and languages share one calm blue because they are the other thing people
/// narrow by. Text sits on three levels, primary through faint, so hierarchy
/// comes from weight rather than a rainbow. Colours are true-colour on
/// purpose: the interface commits to a look rather than inheriting whatever
/// sixteen colours the terminal happened to be set to.
mod theme {
    use ratatui::style::{Color, Modifier, Style};

    /// The canvas painted under every frame. Deep navy-black: the darker the
    /// ground, the harder the true-colour accents pop off it.
    pub const BG: Color = Color::Rgb(13, 17, 25);
    /// Every other table row, one step off the canvas: enough for the eye to
    /// track a row across a wide screen, not enough to read as stripes.
    pub const BG_ALT: Color = Color::Rgb(23, 29, 42);
    pub const ACCENT: Color = Color::Rgb(58, 232, 219); // aqua — interactive
    pub const ACCENT_DEEP: Color = Color::Rgb(96, 202, 210);
    pub const AMBER: Color = Color::Rgb(255, 197, 92); // emphasis
    pub const TEXT: Color = Color::Rgb(241, 245, 251);
    pub const MUTED: Color = Color::Rgb(186, 196, 214);
    pub const FAINT: Color = Color::Rgb(139, 150, 172);
    pub const SUCCESS: Color = Color::Rgb(102, 231, 145);
    pub const DANGER: Color = Color::Rgb(255, 110, 122);
    /// Languages get one colour of their own — a bright cornflower blue —
    /// because they are one of the two facets the interface filters by.
    pub const LANG: Color = Color::Rgb(135, 184, 255);
    /// The wash behind the highlighted row: a teal tint, bright enough to be
    /// plainly the cursor, dim enough to sit under white text.
    pub const SELECT_BG: Color = Color::Rgb(28, 62, 72);

    /// The gutter that marks the selected row. A solid bar reads as "here" even
    /// when the list holds a single item, which a mere background tint does not.
    pub const CURSOR: &str = "";

    pub fn text() -> Style {
        Style::new().fg(TEXT)
    }
    pub fn muted() -> Style {
        Style::new().fg(MUTED)
    }
    pub fn faint() -> Style {
        Style::new().fg(FAINT)
    }
    pub fn accent() -> Style {
        Style::new().fg(ACCENT)
    }

    /// Each format keeps one hue everywhere it appears, so "the green ones are
    /// epubs" becomes something the eye learns in seconds.
    pub fn format_color(ext: &str) -> Color {
        match ext.to_ascii_lowercase().as_str() {
            "epub" => Color::Rgb(88, 226, 140),
            "pdf" => Color::Rgb(255, 126, 110),
            "mobi" | "azw" | "azw3" => Color::Rgb(250, 190, 80),
            "djvu" => Color::Rgb(196, 150, 255),
            "cbz" | "cbr" => Color::Rgb(250, 142, 206),
            _ => Color::Rgb(154, 166, 188),
        }
    }

    /// A format as a small solid chip: dark text on the format's hue.
    pub fn format_chip(ext: &str) -> Style {
        Style::new()
            .fg(BG)
            .bg(format_color(ext))
            .add_modifier(Modifier::BOLD)
    }

    /// The wash behind the selected row — and only the wash. The highlight is
    /// applied over every cell, so anything set here would repaint the row's
    /// own colours; the white title, the blue language and the format's hue
    /// are the information, and selection must not flatten them into teal.
    pub fn selected_row() -> Style {
        Style::new().bg(SELECT_BG)
    }

    /// A column header: quiet, so the data below it does the talking.
    pub fn header() -> Style {
        Style::new().fg(ACCENT_DEEP).add_modifier(Modifier::BOLD)
    }
}

/// Messages the UI thread waits on.
enum Ev {
    Key(KeyEvent),
    Redraw,
    /// Mirror selection finished; carries the ranked pool or a failure.
    Mirrors(std::result::Result<Vec<Uri>, String>),
    /// A search finished; the generation lets the UI discard stale workers.
    Results {
        generation: u64,
        result: std::result::Result<(Vec<Book>, String), String>,
    },
    Progress {
        md5: String,
        done: u64,
        total: Option<u64>,
    },
    Finished {
        md5: String,
        outcome: std::result::Result<String, String>,
    },
    /// A cover lookup finished. `None` means the book has no cover.
    Cover {
        md5: String,
        result: std::result::Result<Option<Cover>, String>,
    },
}

/// Per-download state, keyed by MD5.
#[derive(Clone)]
enum Job {
    Queued,
    Running {
        done: u64,
        total: Option<u64>,
        /// When the transfer began, so the detail pane can show a live speed
        /// and estimate. Averaged over the whole transfer rather than sampled
        /// instantaneously — steadier to read, and it needs no extra state.
        started: Instant,
    },
    Saved(String),
    Failed(String),
}

/// What is known about one book's cover.
#[derive(Clone)]
enum Slot {
    Looking,
    /// Looked, and there is nothing to show.
    Nothing,
    Ready(Box<Art>),
}

/// A cover, in whichever forms this terminal can use.
#[derive(Clone)]
struct Art {
    /// The file as served, for iTerm2, which takes it directly.
    encoded: Vec<u8>,
    /// Decoded pixels, for kitty and for the half-block fallback.
    pixels: Option<graphics::Image>,
}

/// The two halves of the program: finding books, and reading the ones you have.
///
/// They are peers rather than a view and a detour off it, which is why `q`
/// quits from either and the tab bar is always visible.
#[derive(Debug, PartialEq, Clone, Copy)]
enum Tab {
    Search,
    Library,
    Settings,
}

impl Tab {
    /// The next tab in the rotation `Tab` steps through; wraps around.
    fn next(self) -> Self {
        match self {
            Tab::Search => Tab::Library,
            Tab::Library => Tab::Settings,
            Tab::Settings => Tab::Search,
        }
    }

    /// The previous tab, for `BackTab`.
    fn prev(self) -> Self {
        match self {
            Tab::Search => Tab::Settings,
            Tab::Library => Tab::Search,
            Tab::Settings => Tab::Library,
        }
    }
}

/// What the keyboard is doing, independently of which tab is showing.
#[derive(Debug, PartialEq, Clone, Copy)]
enum Mode {
    Editing,
    Browsing,
    Help,
}

/// How a list is ordered. A Libgen search comes back as a ragged pile — forty
/// editions of one book, scattered years, sizes and formats — so being able to
/// impose an order is as much a part of finding a book as the filters are.
///
/// `Relevance` is the order the mirror returned (its own guess at the best
/// match) on the Search tab, and newest-first on the Library tab; the rest sort
/// by one visible column. The two tabs share the machinery so the key means the
/// same thing on both.
#[derive(Debug, PartialEq, Clone, Copy)]
enum Sort {
    Relevance,
    Title,
    Author,
    Year,
    Size,
}

impl Sort {
    /// The cycle `s` walks through, ending back at the mirror's own order.
    const CYCLE: [Sort; 5] = [
        Sort::Relevance,
        Sort::Title,
        Sort::Author,
        Sort::Year,
        Sort::Size,
    ];

    /// What the control strip calls this order. `Relevance` reads differently
    /// depending on the tab, since a library has no relevance to speak of.
    fn label(self, tab: Tab) -> &'static str {
        match self {
            Sort::Relevance => match tab {
                Tab::Search => "relevance",
                Tab::Library => "recent",
                // The Settings tab has no list to sort; never reached in practice.
                Tab::Settings => "relevance",
            },
            Sort::Title => "title",
            Sort::Author => "author",
            Sort::Year => "year",
            Sort::Size => "size",
        }
    }

    /// The direction that key is most useful in the first time it is chosen:
    /// names read A→Z, but "sort by size" almost always means "biggest first",
    /// and "by year" means "newest first". `S` overrides this afterwards.
    fn natural_desc(self) -> bool {
        matches!(self, Sort::Year | Sort::Size)
    }
}

/// One of the columns the results can be narrowed by after they arrive.
///
/// A Libgen search brings back a ragged pile — forty editions of one book in a
/// dozen languages, its authors repeating down the list. Format and language
/// are low-cardinality, a handful of values, so they read as a menu; author is
/// high-cardinality, so the same overlay leans on its type-to-narrow line.
/// Treating all three the same way is what lets one gesture — open, type or
/// arrow, Enter — stand in for the blind cycle that came before and could not
/// touch the author column at all.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Facet {
    Format,
    Language,
    Author,
}

impl Facet {
    const ALL: [Facet; 3] = [Facet::Format, Facet::Language, Facet::Author];

    fn label(self) -> &'static str {
        match self {
            Facet::Format => "format",
            Facet::Language => "language",
            Facet::Author => "author",
        }
    }

    /// The key that opens this facet's picker, echoed in the strip and hints.
    fn key(self) -> char {
        match self {
            Facet::Format => 'e',
            Facet::Language => 'l',
            Facet::Author => 'a',
        }
    }

    fn next(self) -> Self {
        let at = Self::ALL.iter().position(|f| *f == self).unwrap_or(0);
        Self::ALL[(at + 1) % Self::ALL.len()]
    }

    fn prev(self) -> Self {
        let at = Self::ALL.iter().position(|f| *f == self).unwrap_or(0);
        Self::ALL[(at + Self::ALL.len() - 1) % Self::ALL.len()]
    }

    /// The value this facet reads off a record, as the menu and the counts see
    /// it. Format is lowercased so `EPUB` and `epub` fold into one row; the
    /// others keep the mirror's own casing.
    fn value_of(self, book: &Book) -> String {
        match self {
            Facet::Format => book.ext().to_ascii_lowercase(),
            Facet::Language => book.language.as_deref().unwrap_or("unknown").to_string(),
            Facet::Author => book.authors_or_unknown().to_string(),
        }
    }

    /// Does `book` satisfy a filter set to `want`? Format and language match a
    /// whole value exactly — they are picked from a fixed menu — while author
    /// matches a substring, so a fragment of a name narrows the list.
    fn admits(self, want: &str, book: &Book) -> bool {
        match self {
            Facet::Format => book.ext().eq_ignore_ascii_case(want),
            Facet::Language => book
                .language
                .as_deref()
                .unwrap_or("unknown")
                .eq_ignore_ascii_case(want),
            Facet::Author => book
                .authors_or_unknown()
                .to_lowercase()
                .contains(&want.to_lowercase()),
        }
    }
}

/// The pop-over that carves the results by one facet.
///
/// It holds the menu of values present — each with the count that choosing it
/// would leave on screen — and a type-to-narrow line, so picking "epub" or
/// "Le Guin" is one gesture whether there are three formats or eighty authors.
/// The list you are aiming at stays on screen the whole time, rather than
/// flashing past one value per keypress the way the old cycle did.
struct Picker {
    facet: Facet,
    /// The type-to-narrow text, matched case-insensitively as a substring
    /// against every row's value.
    query: String,
    /// Every value present for this facet, most common first — the unfiltered
    /// menu. Recomputed when the facet changes, not on every keystroke.
    options: Vec<(String, usize)>,
    /// Where the highlight sits, as an index into the rows on show: row 0 is
    /// always "all", the surviving options follow.
    cursor: usize,
}

impl Picker {
    /// The options that survive the type-to-narrow text, in menu order.
    fn shown(&self) -> Vec<&(String, usize)> {
        if self.query.trim().is_empty() {
            return self.options.iter().collect();
        }
        let needle = self.query.to_lowercase();
        self.options
            .iter()
            .filter(|(v, _)| v.to_lowercase().contains(&needle))
            .collect()
    }

    /// Selectable rows: the surviving options plus the leading "all" row.
    fn rows(&self) -> usize {
        self.shown().len() + 1
    }

    /// Where the highlight belongs after the query changes: the first real
    /// option when the narrowing left any, otherwise the "all" row.
    fn first_match_row(&self) -> usize {
        if self.shown().is_empty() { 0 } else { 1 }
    }
}

/// The little menu behind `s`: which column orders the list, and which way.
///
/// Sort is the other thing that used to step one keypress at a time — `s`
/// walked relevance → title → author → year → size and back. Like the facet
/// picker, this floats the whole set of orders over the results so the one you
/// want is a single choice, with its direction shown and flippable in place.
struct SortPick {
    /// Index into `Sort::CYCLE` of the highlighted key.
    cursor: usize,
    /// The direction Enter would apply for the highlighted key. It follows the
    /// key's natural default as the highlight moves; `←`/`→` overrides it.
    desc: bool,
}

/// The image id used for the cover. Reusing one id means each new cover
/// replaces the last rather than piling up in the terminal's store.
const COVER_ID: u32 = 0x636C_6267;

/// How long the selection has to sit still before a cover is worth fetching.
/// Long enough that holding a cursor key down does not fire a request per row.
const COVER_DELAY: Duration = Duration::from_millis(250);

/// The wordmark over the empty search landing — a figlet "ANSI Shadow" banner of
/// the app name. Six rows, every line padded to exactly `WORDMARK_W` columns so
/// the block stays rigid under centred alignment rather than drifting a row.
const WORDMARK: &str = "\
████████╗ ██████╗ ███╗   ███╗███████╗███████╗ ██████╗ ██╗     ███████╗
╚══██╔══╝██╔═══██╗████╗ ████║██╔════╝██╔════╝██╔═══██╗██║     ██╔════╝
   ██║   ██║   ██║██╔████╔██║█████╗  ███████╗██║   ██║██║     █████╗
   ██║   ██║   ██║██║╚██╔╝██║██╔══╝  ╚════██║██║   ██║██║     ██╔══╝
   ██║   ╚██████╔╝██║ ╚═╝ ██║███████╗███████║╚██████╔╝███████╗███████╗
   ╚═╝    ╚═════╝ ╚═╝     ╚═╝╚══════╝╚══════╝ ╚═════╝ ╚══════╝╚══════╝";
const WORDMARK_W: u16 = 70;
const WORDMARK_H: u16 = 6;

/// One editable row on the Settings tab. The order of the variants is the order
/// they are shown; the runtime-live ones lead, the startup-only ones follow.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Field {
    Covers,
    History,
    Verify,
    MaxSize,
    Reader,
    DownloadDir,
    Limit,
    Topics,
    Mirrors,
    AllowHttp,
}

/// How a field is edited, which decides what a keypress on it means.
enum FieldKind {
    /// A yes/no toggle.
    Bool,
    /// A single line of text, committed through a validator.
    Line,
    /// The six-way collection multi-select.
    Topics,
    /// The ordered mirror list, with add and delete.
    Mirrors,
}

impl Field {
    /// Every field, in display order.
    const ALL: [Field; 10] = [
        Field::Covers,
        Field::History,
        Field::Verify,
        Field::MaxSize,
        Field::Reader,
        Field::DownloadDir,
        Field::Limit,
        Field::Topics,
        Field::Mirrors,
        Field::AllowHttp,
    ];

    fn label(self) -> &'static str {
        match self {
            Field::Covers => "cover art",
            Field::History => "history",
            Field::Verify => "verify downloads",
            Field::MaxSize => "max download size",
            Field::Reader => "reader",
            Field::DownloadDir => "download dir",
            Field::Limit => "result limit",
            Field::Topics => "collections",
            Field::Mirrors => "mirrors",
            Field::AllowHttp => "allow http",
        }
    }

    fn help(self) -> &'static str {
        match self {
            Field::Covers => "fetch and draw cover art in the interface",
            Field::History => "record what gets downloaded",
            Field::Verify => "check each download against its catalogued MD5 — leave on",
            Field::MaxSize => "refuse to save a file larger than this, e.g. 4 GB",
            Field::Reader => "app to open books with; blank means the system default",
            Field::DownloadDir => "where downloads are saved",
            Field::Limit => "how many results a search shows",
            Field::Topics => "which collections a search covers",
            Field::Mirrors => "mirrors to try first, before auto-discovery",
            Field::AllowHttp => "permit cleartext http mirrors — off unless you must",
        }
    }

    fn kind(self) -> FieldKind {
        match self {
            Field::Covers | Field::History | Field::Verify | Field::AllowHttp => FieldKind::Bool,
            Field::MaxSize | Field::Reader | Field::DownloadDir | Field::Limit => FieldKind::Line,
            Field::Topics => FieldKind::Topics,
            Field::Mirrors => FieldKind::Mirrors,
        }
    }

    /// True for settings baked in at startup (net policy, mirror pool, search
    /// defaults): editing them writes the file but only bites next launch.
    fn deferred(self) -> bool {
        matches!(
            self,
            Field::Limit | Field::Topics | Field::Mirrors | Field::AllowHttp
        )
    }
}

/// Which sub-list, if any, currently has the keyboard on the Settings tab. The
/// collection and mirror rows have their own vertical cursor, so focusing one
/// hands `j`/`k` to it until Esc steps back out to the field list.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
enum SubFocus {
    #[default]
    None,
    Topics,
    Mirrors,
}

/// A line being typed into a `Line` field, or a new mirror URL.
#[derive(Debug, Clone, Default)]
struct Edit {
    buffer: String,
    caret: usize,
}

/// Cursor and edit state for the Settings tab.
#[derive(Debug, Default)]
struct SettingsForm {
    /// Index into [`Field::ALL`] of the highlighted row.
    selected: usize,
    /// Which sub-list has focus, if any.
    sub: SubFocus,
    /// Cursor within the collections multi-select.
    topic_row: usize,
    /// Cursor within the mirror list.
    mirror_row: usize,
    /// The line being typed, when a field (or a new mirror) is being edited.
    editing: Option<Edit>,
    /// The last validation failure, shown until the next successful edit.
    error: Option<String>,
}

pub struct App {
    settings: Settings,
    /// The config file's own values, as loaded — what the Settings tab edits and
    /// writes back. Distinct from `settings`, where command-line flags have
    /// already won, so editing here never rewrites a flag-supplied value.
    config: Config,
    /// Cursor and edit state for the Settings tab's form.
    form: SettingsForm,
    /// Where the Settings tab writes the config back to. Held as a field, rather
    /// than read from [`crate::config::config_path`] each time, so a test can
    /// redirect the write to a throwaway file.
    config_path: PathBuf,
    tab: Tab,
    mode: Mode,
    query: String,
    /// Narrows the library to matching titles, authors and filenames.
    filter: String,
    /// Caret position within whichever of the two boxes is showing, as a
    /// character index. Clamped when the tab changes.
    caret: usize,
    results: Vec<Book>,
    /// Indices into `results` that survive the format and language filters, in
    /// display order. What the table actually shows.
    visible: Vec<usize>,
    /// Narrow the results to one file format, e.g. `epub`. Survives a new
    /// search on purpose: "epubs only" is a standing preference, not a remark
    /// about one result set.
    fmt_filter: Option<String>,
    /// Narrow the results to one language, matched exactly against what the
    /// mirror reported.
    lang_filter: Option<String>,
    /// Narrow the results to authors whose name contains this, matched as a
    /// case-insensitive substring so part of a name is enough.
    author_filter: Option<String>,
    /// The open facet pop-over, when one is up. A modal that carves the results
    /// by format, language or author — the interactive answer to "epubs only"
    /// or "just the Le Guin ones" without re-running the search.
    picker: Option<Picker>,
    /// The open sort menu, when one is up. Like the facet picker, a modal that
    /// takes every key while it is showing.
    sort_menu: Option<SortPick>,
    /// How the visible list is ordered, and which way. Shared by both tabs and,
    /// like the filters, a standing preference that survives the next search.
    sort: Sort,
    sort_desc: bool,
    table: TableState,
    marked: Vec<bool>,
    jobs: HashMap<String, Job>,
    mirrors: Vec<Uri>,
    mirror_label: String,
    status: String,
    error: Option<String>,
    busy: bool,
    downloading: bool,
    /// A search typed before the mirror pool was ready, run once it is.
    pending_search: bool,
    /// Monotonically identifies the newest search worker.
    search_generation: u64,
    quit: bool,
    tx: Sender<Ev>,

    /// Every past download, newest first. Read from disk at startup and again
    /// whenever one finishes, so the tab is never stale.
    library: Vec<history::Entry>,
    /// Indices into `library` that survive the filter, in display order.
    shown: Vec<usize>,
    /// The MD5s of every book already in the library, so a search result you
    /// have downloaded before can be recognised at a glance and not fetched
    /// twice. Rebuilt whenever the library is reloaded.
    owned: HashSet<String>,
    library_table: TableState,

    /// How this terminal can draw a picture, if at all.
    protocol: Protocol,
    covers: HashMap<String, Slot>,
    /// The selection is only worth a cover request once it stops moving.
    cover_due: Option<Instant>,
    /// What is currently painted on the screen by escape code, and where, so
    /// it is only redrawn when it actually changes.
    painted: Option<(String, Rect)>,
    /// Where the last frame left room for the picture. Set during rendering,
    /// read afterwards by the code that writes the escape sequence.
    cover_area: Option<Rect>,
    /// A frame counter, bumped once per draw, that drives the small animated
    /// spinner shown while something is in flight. The event loop wakes on a
    /// 250 ms timer even when idle, so it turns at a calm few frames a second.
    spinner: usize,
}

const PUSH_TERMINAL_TITLE: &[u8] = b"\x1b[22;0t";
const POP_TERMINAL_TITLE: &[u8] = b"\x1b[23;0t";

struct TerminalTitle {
    active: bool,
}

impl TerminalTitle {
    fn set(title: &str) -> Self {
        let mut stdout = io::stdout();
        let active = push_and_set_title(&mut stdout, title).is_ok();
        Self { active }
    }
}

impl Drop for TerminalTitle {
    fn drop(&mut self) {
        if self.active {
            let _ = restore_title(&mut io::stdout());
        }
    }
}

fn push_and_set_title(out: &mut impl Write, title: &str) -> io::Result<()> {
    out.write_all(PUSH_TERMINAL_TITLE)?;
    if let Err(error) = out.execute(SetTitle(title)) {
        let _ = restore_title(out);
        return Err(error);
    }
    Ok(())
}

fn restore_title(out: &mut impl Write) -> io::Result<()> {
    out.write_all(POP_TERMINAL_TITLE)?;
    out.flush()
}

/// Byte offset of a character index within `s`, for editing in place.
fn char_byte(s: &str, chars: usize) -> usize {
    s.char_indices().nth(chars).map(|(i, _)| i).unwrap_or(s.len())
}

/// Run the interface until the user quits.
pub fn run(settings: Settings, config: Config, initial_query: Option<String>) -> Result<()> {
    let (tx, rx) = mpsc::channel();

    // Keyboard events arrive on the same channel as worker results, so the UI
    // loop has a single thing to wait on.
    {
        let tx = tx.clone();
        std::thread::spawn(move || {
            loop {
                match event::read() {
                    // `Press` only: Windows also reports key releases, which
                    // would otherwise double every keystroke.
                    Ok(CtEvent::Key(key)) if key.kind == KeyEventKind::Press => {
                        if tx.send(Ev::Key(key)).is_err() {
                            return;
                        }
                    }
                    Ok(CtEvent::Resize(_, _)) => {
                        if tx.send(Ev::Redraw).is_err() {
                            return;
                        }
                    }
                    Ok(_) => {}
                    Err(_) => return,
                }
            }
        });
    }

    let query = initial_query.unwrap_or_default();
    let protocol = if settings.covers {
        graphics::detect()
    } else {
        Protocol::None
    };
    let mut app = App {
        settings,
        config,
        form: SettingsForm::default(),
        config_path: crate::config::config_path(),
        tab: Tab::Search,
        mode: if query.is_empty() {
            Mode::Editing
        } else {
            Mode::Browsing
        },
        caret: query.chars().count(),
        query,
        filter: String::new(),
        results: Vec::new(),
        visible: Vec::new(),
        fmt_filter: None,
        lang_filter: None,
        author_filter: None,
        picker: None,
        sort_menu: None,
        sort: Sort::Relevance,
        sort_desc: false,
        table: TableState::default(),
        marked: Vec::new(),
        jobs: HashMap::new(),
        mirrors: Vec::new(),
        mirror_label: "connecting…".into(),
        status: "finding a working mirror".into(),
        error: None,
        busy: true,
        downloading: false,
        pending_search: false,
        search_generation: 0,
        quit: false,
        tx,
        library: Vec::new(),
        shown: Vec::new(),
        owned: HashSet::new(),
        library_table: TableState::default(),
        protocol,
        covers: HashMap::new(),
        cover_due: None,
        painted: None,
        cover_area: None,
        spinner: 0,
    };
    app.pending_search = !app.query.is_empty();
    // Read the library up front rather than when the tab is first opened: it
    // costs one small file read, and it means the tab bar can say how many
    // books are there before anybody goes looking.
    app.reload_library();
    app.spawn_mirror_resolve(app.settings.refresh_mirrors);

    let mut terminal = ratatui::try_init()?;
    // Keep the app's title scoped to the full-screen session. The guard also
    // restores it when the event loop or terminal teardown returns an error.
    let _title = TerminalTitle::set("tomesole");
    let outcome = app.event_loop(&mut terminal, &rx);
    app.erase_cover();
    ratatui::try_restore()?;
    outcome
}

impl App {
    fn event_loop(
        &mut self,
        terminal: &mut ratatui::DefaultTerminal,
        rx: &Receiver<Ev>,
    ) -> Result<()> {
        terminal.draw(|frame| self.render(frame))?;
        loop {
            match rx.recv_timeout(Duration::from_millis(250)) {
                Ok(ev) => self.handle(ev),
                Err(RecvTimeoutError::Timeout) => {}
                Err(RecvTimeoutError::Disconnected) => break,
            }
            if self.quit {
                break;
            }
            // The selection may have stopped moving long enough to be worth a
            // cover; checked here rather than on the keypress so that holding a
            // cursor key down costs nothing.
            self.poll_cover();
            terminal.draw(|frame| self.render(frame))?;
            // Pixel protocols write outside ratatui's buffer, so the picture is
            // placed after the frame it belongs to has been drawn.
            self.paint_cover();
        }
        Ok(())
    }

    // --- background work -------------------------------------------------

    fn spawn_mirror_resolve(&mut self, refresh: bool) {
        self.busy = true;
        self.mirror_label = "connecting…".into();
        self.status = "finding a working mirror".into();

        let tx = self.tx.clone();
        let settings = self.settings.clone();
        std::thread::spawn(move || {
            let result = mirror::resolve(
                &settings.policy,
                ResolveOptions {
                    explicit: &settings.mirrors,
                    refresh,
                    progress: &|_| {},
                },
            );
            let payload = result
                .map(|pool| pool.mirrors().to_vec())
                .map_err(|e| e.to_string());
            let _ = tx.send(Ev::Mirrors(payload));
        });
    }

    fn spawn_search(&mut self) {
        let terms = self.query.trim().to_string();
        if terms.is_empty() {
            self.error = Some("type something to search for".into());
            return;
        }
        if self.mirrors.is_empty() {
            // No mirror yet; run this as soon as one turns up.
            self.pending_search = true;
            self.status = "waiting for a mirror".into();
            return;
        }

        // `author:herbert dune ext:epub` — the box is the only input this
        // interface has, so the tags do the work the CLI's flags do.
        let query = self.search_query(&terms);
        if query.terms.trim().is_empty() {
            self.error = Some("that is all filters and no search terms".into());
            return;
        }

        self.busy = true;
        self.error = None;
        self.status = format!("searching for “{}", query.terms);
        self.search_generation = self.search_generation.wrapping_add(1);
        let generation = self.search_generation;

        let tx = self.tx.clone();
        let settings = self.settings.clone();
        let mirrors = self.mirrors.clone();
        std::thread::spawn(move || {
            let payload = Http::new(settings.policy)
                .and_then(|http| {
                    Pool::new(mirrors)
                        .try_each(
                            |base| net::with_retry(2, |_| libgen::search(&http, base, &query)),
                            |_, _| {},
                        )
                        .map(|(books, used)| (books, net::host_of(&used).unwrap_or_default()))
                })
                .map_err(|e| e.to_string());
            let _ = tx.send(Ev::Results {
                generation,
                result: payload,
            });
        });
    }

    /// Build a TUI search from the defaults captured at startup, then let
    /// inline tags add the same refinements they do for CLI searches.
    fn search_query(&self, terms: &str) -> SearchQuery {
        let mut query = SearchQuery::new(String::new());
        query.limit = self.settings.search_limit;
        query.topics = self.settings.search_topics.clone();
        query::apply(terms, &mut query);
        query
    }

    /// Download every marked record, or the highlighted one when none are.
    fn spawn_downloads(&mut self) {
        if self.downloading {
            self.error = Some("a download is already running".into());
            return;
        }
        let chosen: Vec<Book> = if self.marked.iter().any(|m| *m) {
            self.results
                .iter()
                .zip(&self.marked)
                .filter(|(_, m)| **m)
                .map(|(b, _)| b.clone())
                .collect()
        } else {
            match self.selected() {
                Some(book) => vec![book.clone()],
                None => return,
            }
        };
        if chosen.is_empty() {
            return;
        }

        for book in &chosen {
            self.jobs.insert(book.md5.clone(), Job::Queued);
        }
        self.downloading = true;
        self.error = None;
        self.status = format!("downloading {} file(s)", chosen.len());

        let tx = self.tx.clone();
        let settings = self.settings.clone();
        let mirrors = self.mirrors.clone();
        std::thread::spawn(move || {
            let http = match Http::new(settings.policy) {
                Ok(h) => h,
                Err(e) => {
                    for book in &chosen {
                        let _ = tx.send(Ev::Finished {
                            md5: book.md5.clone(),
                            outcome: Err(e.to_string()),
                        });
                    }
                    return;
                }
            };
            let pool = Pool::new(mirrors);

            for book in chosen {
                let opts = download::Options {
                    dest_dir: settings.dest_dir.clone(),
                    filename: None,
                    max_bytes: settings.max_bytes,
                    verify: settings.verify,
                    force: settings.force,
                    resume: settings.resume,
                };

                // Progress arrives per 64 KB chunk; throttle it so a fast
                // transfer cannot flood the UI thread with redraws.
                let mut last = Instant::now() - Duration::from_secs(1);
                let md5 = book.md5.clone();
                let progress_tx = tx.clone();
                let mut report = |done: u64, total: Option<u64>| {
                    if last.elapsed() >= Duration::from_millis(100) {
                        last = Instant::now();
                        let _ = progress_tx.send(Ev::Progress {
                            md5: md5.clone(),
                            done,
                            total,
                        });
                    }
                };

                let result = pool.try_each(
                    |base| {
                        let resolved = libgen::resolve_download(&http, base, &book.md5)?;
                        download::fetch(&http, &resolved.url, &book, &opts, &mut report)
                    },
                    |_, _| {},
                );

                let outcome = match result {
                    Ok((outcome, _)) => {
                        history::record(settings.history, &book, &outcome);
                        Ok(outcome
                            .path
                            .file_name()
                            .map(|n| n.to_string_lossy().to_string())
                            .unwrap_or_default())
                    }
                    Err(e) => Err(e.to_string()),
                };
                let _ = tx.send(Ev::Finished {
                    md5: book.md5.clone(),
                    outcome,
                });
            }
        });
    }

    // --- cover art --------------------------------------------------------

    /// The record the detail pane is describing.
    fn selected(&self) -> Option<&Book> {
        self.table
            .selected()
            .and_then(|i| self.visible.get(i))
            .and_then(|&i| self.results.get(i))
    }

    // --- narrowing the results --------------------------------------------
    //
    // A search brings back whatever the mirror has — Das Kapital is forty
    // German editions with the English translations scattered among them.
    // Rather than make people re-search with `lang:` tags, three facets carve
    // the results in place: `e` for format, `l` for language, `a` for author,
    // each opening a pop-over menu of the values actually present with a live
    // count of what choosing one would leave.

    /// The filter value currently set on a facet, if any.
    fn filter_for(&self, facet: Facet) -> Option<&str> {
        match facet {
            Facet::Format => self.fmt_filter.as_deref(),
            Facet::Language => self.lang_filter.as_deref(),
            Facet::Author => self.author_filter.as_deref(),
        }
    }

    /// Set (or, with `None`, clear) a facet's filter.
    fn set_filter(&mut self, facet: Facet, value: Option<String>) {
        match facet {
            Facet::Format => self.fmt_filter = value,
            Facet::Language => self.lang_filter = value,
            Facet::Author => self.author_filter = value,
        }
    }

    /// Whether any facet is narrowing the results at all.
    fn any_filter(&self) -> bool {
        Facet::ALL.iter().any(|&f| self.filter_for(f).is_some())
    }

    /// Does every active filter admit this record?
    fn admits(&self, book: &Book) -> bool {
        Facet::ALL.iter().all(|&f| self.facet_admits(f, book))
    }

    /// Does the filter on one facet — if it has one — admit this record?
    fn facet_admits(&self, facet: Facet, book: &Book) -> bool {
        match self.filter_for(facet) {
            Some(want) => facet.admits(want, book),
            None => true,
        }
    }

    /// Whether `book` survives every filter *except* the one on `facet` — the
    /// set a facet's own menu counts against, so its numbers say what choosing
    /// a value would leave once the other facets have had their say.
    fn admits_except(&self, facet: Facet, book: &Book) -> bool {
        Facet::ALL
            .iter()
            .filter(|&&f| f != facet)
            .all(|&f| self.facet_admits(f, book))
    }

    /// Recompute which rows show, keeping the highlight on the same book when
    /// it survives the cut and on the top row when it does not.
    fn refine(&mut self) {
        let keep = self.selected().map(|b| b.md5.clone());
        self.visible = (0..self.results.len())
            .filter(|&i| self.admits(&self.results[i]))
            .collect();
        self.sort_visible();
        let position = keep.and_then(|md5| {
            self.visible
                .iter()
                .position(|&i| self.results[i].md5 == md5)
        });
        self.table.select(if self.visible.is_empty() {
            None
        } else {
            Some(position.unwrap_or(0))
        });
        self.selection_moved();
    }

    /// Order the visible results by the active sort. The vector already carries
    /// the mirror's own order, so `Relevance` only ever reverses it; the other
    /// keys sort stably, so books with an equal key keep that underlying order.
    fn sort_visible(&mut self) {
        use std::cmp::Ordering;
        if self.sort == Sort::Relevance {
            if self.sort_desc {
                self.visible.reverse();
            }
            return;
        }
        // Sort a detached copy so the closure can read the rest of `self`.
        let mut visible = std::mem::take(&mut self.visible);
        let (sort, desc) = (self.sort, self.sort_desc);
        visible.sort_by(|&a, &b| {
            let (x, y) = (&self.results[a], &self.results[b]);
            let ord = match sort {
                Sort::Title => x.title.to_lowercase().cmp(&y.title.to_lowercase()),
                Sort::Author => first_author_of(x.authors.as_deref())
                    .cmp(&first_author_of(y.authors.as_deref())),
                Sort::Year => year_num(x.year.as_deref()).cmp(&year_num(y.year.as_deref())),
                Sort::Size => x.size_bytes.unwrap_or(0).cmp(&y.size_bytes.unwrap_or(0)),
                Sort::Relevance => Ordering::Equal,
            };
            if desc { ord.reverse() } else { ord }
        });
        self.visible = visible;
    }

    /// Raise the sort menu, opened on the order in force so a glance says how
    /// the list is arranged and Enter on it changes nothing. Works from either
    /// tab, since both share the one sort.
    fn open_sort_menu(&mut self) {
        let cursor = Sort::CYCLE.iter().position(|s| *s == self.sort).unwrap_or(0);
        self.sort_menu = Some(SortPick {
            cursor,
            desc: self.sort_desc,
        });
    }

    /// Commit the highlighted order and close the menu. `Relevance` is the
    /// list's own order and carries no direction, so it always applies ascending.
    fn apply_sort_menu(&mut self) {
        let Some(menu) = self.sort_menu.take() else {
            return;
        };
        self.sort = Sort::CYCLE[menu.cursor];
        self.sort_desc = self.sort != Sort::Relevance && menu.desc;
        self.resort();
    }

    /// Flip the current sort's direction, leaving the key alone.
    fn reverse_sort(&mut self) {
        self.sort_desc = !self.sort_desc;
        self.resort();
    }

    /// Re-apply the sort to whichever list the visible tab owns.
    fn resort(&mut self) {
        match self.tab {
            Tab::Search => self.refine(),
            Tab::Library => self.refilter(),
            Tab::Settings => {}
        }
        self.selection_moved();
    }

    /// The values a facet could take, most common first, each counted with the
    /// *other* facets still applied — so the numbers say what picking that value
    /// would actually leave on screen.
    fn facet_options(&self, facet: Facet) -> Vec<(String, usize)> {
        let mut counts: Vec<(String, usize)> = Vec::new();
        for book in &self.results {
            if !self.admits_except(facet, book) {
                continue;
            }
            let value = facet.value_of(book);
            match counts
                .iter_mut()
                .find(|(name, _)| name.eq_ignore_ascii_case(&value))
            {
                Some((_, n)) => *n += 1,
                None => counts.push((value, 1)),
            }
        }
        counts.sort_by(|a, b| {
            b.1.cmp(&a.1)
                .then_with(|| a.0.to_lowercase().cmp(&b.0.to_lowercase()))
        });
        counts
    }

    /// How many records survive once a facet's filter joins the others — the
    /// number shown beside the active value in the strip.
    fn facet_count(&self, facet: Facet) -> Option<usize> {
        self.filter_for(facet)?;
        Some(
            self.results
                .iter()
                .filter(|b| self.admits_except(facet, b) && self.facet_admits(facet, b))
                .count(),
        )
    }

    /// Raise the pop-over that narrows the results by one facet. There is
    /// nothing to pick from until a search returns, so it stays shut on an
    /// empty list. The highlight opens on the value already chosen, if any, so
    /// reopening a facet lands where it was left.
    fn open_picker(&mut self, facet: Facet) {
        if self.results.is_empty() {
            return;
        }
        let options = self.facet_options(facet);
        // Open on the value already chosen; with none set, land on the most
        // common value rather than the "all" row, so "open, Enter" grabs the
        // obvious pick and clearing is a deliberate step up to "all".
        let cursor = self
            .filter_for(facet)
            .and_then(|cur| options.iter().position(|(n, _)| n.eq_ignore_ascii_case(cur)))
            .map(|i| i + 1)
            .unwrap_or(if options.is_empty() { 0 } else { 1 });
        self.picker = Some(Picker {
            facet,
            query: String::new(),
            options,
            cursor,
        });
    }

    /// Commit whatever the picker is pointing at and close it. The "all" row at
    /// the top clears the facet; any other row sets it to that value. Typing a
    /// fragment first is how a value is reached without arrowing — the fragment
    /// narrows the menu, and the highlight lands on the match it commits.
    fn apply_picker(&mut self) {
        let Some(picker) = self.picker.take() else {
            return;
        };
        let facet = picker.facet;
        let value = if picker.cursor == 0 {
            None
        } else {
            picker.shown().get(picker.cursor - 1).map(|(v, _)| v.clone())
        };
        self.set_filter(facet, value);
        self.refine();
    }

    /// Clear every facet at once.
    fn clear_filters(&mut self) {
        for facet in Facet::ALL {
            self.set_filter(facet, None);
        }
        self.refine();
    }

    /// Note that the selection moved, so a cover becomes due shortly.
    fn selection_moved(&mut self) {
        if self.protocol != Protocol::None {
            self.cover_due = Some(Instant::now() + COVER_DELAY);
        }
    }

    /// Start a cover lookup once the selection has been still long enough.
    ///
    /// The two tabs source a cover differently: a search result has only its
    /// MD5, so its cover comes off a mirror; a library book is a file on disk
    /// that usually carries its own jacket, so that is read straight out of the
    /// file with no network at all — falling back to the cache from a past
    /// search, and then to a mirror, when the file has none of its own.
    fn poll_cover(&mut self) {
        let Some(due) = self.cover_due else {
            return;
        };
        if Instant::now() < due {
            return;
        }
        self.cover_due = None;

        let Some(md5) = self.focused_md5() else {
            return;
        };
        if self.covers.contains_key(&md5) {
            return;
        }

        match self.tab {
            Tab::Search => self.spawn_search_cover(md5),
            Tab::Library => self.spawn_library_cover(md5),
            // The Settings tab shows no cover, so nothing is ever due for one.
            Tab::Settings => {}
        }
    }

    /// Fetch the highlighted search result's cover from a mirror.
    fn spawn_search_cover(&mut self, md5: String) {
        if self.mirrors.is_empty() {
            return;
        }
        let Some(book) = self.selected().cloned() else {
            return;
        };
        self.covers.insert(md5, Slot::Looking);

        let tx = self.tx.clone();
        let settings = self.settings.clone();
        let mirrors = self.mirrors.clone();
        std::thread::spawn(move || {
            let result = Http::new(settings.policy).and_then(|http| {
                // One mirror only. A cover is not worth walking the pool for,
                // and a mirror that cannot serve one is usually about to fail
                // the next search anyway.
                let base = mirrors
                    .first()
                    .cloned()
                    .ok_or_else(|| crate::err!("no mirror available"))?;
                cover::fetch(&http, &base, &book)
            });
            let _ = tx.send(Ev::Cover {
                md5: book.md5,
                result: result.map_err(|e| e.to_string()),
            });
        });
    }

    /// Find the highlighted library book's cover, cheapest source first.
    ///
    /// Three places, in order: the jacket embedded in the file you downloaded
    /// (no network, and it is the book you actually have); a cover cached from a
    /// past search of the same book; and finally the mirror, the same way the
    /// Search tab does it. The mirror fallback matters because most formats
    /// carry no cover this can extract — a PDF has no embedded jacket at all,
    /// and plenty of real EPUBs and MOBIs hide theirs where the heuristics miss
    /// — so without it those books would sit in the library with a blank frame
    /// forever. The fetch caches to disk, so a book is only pulled off a mirror
    /// once.
    fn spawn_library_cover(&mut self, md5: String) {
        let Some(entry) = self.selected_entry().cloned() else {
            return;
        };
        self.covers.insert(md5.clone(), Slot::Looking);

        let tx = self.tx.clone();
        let settings = self.settings.clone();
        let mirrors = self.mirrors.clone();
        std::thread::spawn(move || {
            // The file's own cover first, then a cover cached from a past search.
            let local = entry
                .present()
                .then(|| crate::embedded::cover(&entry.path))
                .flatten()
                .or_else(|| cover::cached(&md5).flatten());

            // Nothing on disk: ask a mirror, exactly as the Search tab would,
            // building a lookup key out of what the history row remembers.
            let result = match local {
                Some(cover) => Ok(Some(cover)),
                None => Self::fetch_library_cover(&settings, &mirrors, &entry),
            };
            let _ = tx.send(Ev::Cover {
                md5,
                result: result.map_err(|e| e.to_string()),
            });
        });
    }

    /// Pull a library book's cover off a mirror, keyed by its MD5. Returns
    /// `Ok(None)` when there is simply no mirror to ask or the record has no
    /// cover; both leave the frame empty rather than showing an error over a
    /// book someone already has.
    fn fetch_library_cover(
        settings: &Settings,
        mirrors: &[Uri],
        entry: &history::Entry,
    ) -> Result<Option<Cover>> {
        let Some(base) = mirrors.first().cloned() else {
            return Ok(None);
        };
        let book = Book {
            md5: entry.md5.clone(),
            title: entry.title.clone(),
            authors: entry.authors.clone(),
            extension: entry.extension.clone(),
            ..Default::default()
        };
        let http = Http::new(settings.policy)?;
        cover::fetch(&http, &base, &book)
    }

    /// The MD5 of whatever is highlighted on the current tab — a search result
    /// or a library entry. Covers are keyed by it regardless of where the book
    /// is being looked at, so a book downloaded and then found again in the
    /// library reuses the cover already in hand.
    fn focused_md5(&self) -> Option<String> {
        match self.tab {
            Tab::Search => self.selected().map(|b| b.md5.clone()),
            Tab::Library => self.selected_entry().map(|e| e.md5.clone()),
            Tab::Settings => None,
        }
    }

    /// The cover to show right now, if there is one.
    fn current_art(&self) -> Option<&Art> {
        match self.covers.get(&self.focused_md5()?) {
            Some(Slot::Ready(art)) => Some(art),
            _ => None,
        }
    }

    /// Whether the detail pane should make room for a picture.
    fn cover_visible(&self) -> bool {
        self.protocol != Protocol::None
            && match self.covers.get(self.focused_md5().as_deref().unwrap_or("")) {
                // Space is reserved while looking too, so the pane does not
                // jump about when the picture arrives.
                Some(Slot::Looking) => true,
                Some(Slot::Ready(_)) => true,
                _ => false,
            }
    }

    /// Draw the cover with an escape sequence, for terminals that do pixels.
    ///
    /// Half-block art goes through ratatui instead and never reaches here.
    fn paint_cover(&mut self) {
        if let Some(escape) = self.cover_escape() {
            use std::io::Write;
            let mut stdout = std::io::stdout();
            let _ = write!(stdout, "{escape}");
            let _ = stdout.flush();
        }
    }

    /// The escape sequence that brings the screen up to date with what should
    /// be showing, or `None` when it already is.
    ///
    /// Separate from writing it so the decision — what to place, where, and
    /// whether anything needs to change at all — can be tested without a
    /// terminal to write to.
    fn cover_escape(&mut self) -> Option<String> {
        if !self.protocol.is_pixels() {
            return None;
        }
        let want = self
            .cover_rect()
            .zip(self.focused_md5())
            .filter(|_| self.current_art().is_some())
            .map(|(rect, md5)| (md5, rect));

        if want == self.painted {
            return None;
        }

        let mut out = String::new();
        if self.painted.is_some() {
            out.push_str(&graphics::kitty_delete(COVER_ID));
        }
        if let Some((md5, rect)) = &want
            && let Some(art) = self.covers.get(md5).and_then(|slot| match slot {
                Slot::Ready(art) => Some(art),
                _ => None,
            })
        {
            // Terminal coordinates are one-based; ratatui's are not.
            out.push_str(&format!("\x1b[{};{}H", rect.y + 1, rect.x + 1));
            out.push_str(&match self.protocol {
                Protocol::ITerm2 => graphics::iterm_image(&art.encoded, rect.width, rect.height),
                _ => match &art.pixels {
                    Some(image) => graphics::kitty_image(
                        COVER_ID,
                        &image.fit(400, 600),
                        rect.width,
                        rect.height,
                    ),
                    // Kitty decodes PNG itself, so it can have the file.
                    None => graphics::kitty_png(COVER_ID, &art.encoded, rect.width, rect.height),
                },
            });
        }

        self.painted = want;
        if out.is_empty() { None } else { Some(out) }
    }

    /// Take any painted cover off the screen.
    fn erase_cover(&mut self) {
        if self.painted.take().is_some() && self.protocol.is_pixels() {
            use std::io::Write;
            let mut stdout = std::io::stdout();
            let _ = write!(stdout, "{}", graphics::kitty_delete(COVER_ID));
            let _ = stdout.flush();
        }
    }

    // --- the library ------------------------------------------------------

    /// Switch tabs, carrying the caret somewhere valid for the box that is now
    /// showing.
    fn show(&mut self, tab: Tab) {
        if self.tab == tab {
            return;
        }
        self.tab = tab;
        self.error = None;
        match tab {
            Tab::Library => {
                self.caret = self.input().chars().count();
                // Downloads made elsewhere since we started belong here too.
                self.reload_library();
                // Whatever is painted belongs to the tab we are leaving; the
                // library's own cover is then armed like any selection.
                self.erase_cover();
                self.selection_moved();
                self.status = match self.library.len() {
                    0 => "nothing downloaded yet".into(),
                    1 => "1 book in the library".into(),
                    n => format!("{n} books in the library"),
                };
            }
            Tab::Search => {
                self.caret = self.input().chars().count();
                // The detail pane is back, so its cover has to be placed again.
                self.selection_moved();
                self.status = match self.results.len() {
                    0 => "press / to search".into(),
                    n => format!("{n} result(s)"),
                };
            }
            Tab::Settings => {
                // The form has no search box, so `Editing` — the mode a fresh
                // session Tabs in with — would send arrows and j/k to the search
                // editor instead of the field list. Browsing is the only mode
                // the form runs under. Also drop whatever the previous tab
                // painted, since there is no cover band here.
                self.mode = Mode::Browsing;
                self.erase_cover();
                self.form.editing = None;
                self.form.sub = SubFocus::None;
                self.form.error = None;
                self.status = "settings — ↑↓ move, enter edits, tab leaves".into();
            }
        }
    }

    /// Re-read the library from disk and reapply the filter, keeping the
    /// highlight on something sensible.
    fn reload_library(&mut self) {
        self.library = history::load();
        self.owned = self.library.iter().map(|e| e.md5.clone()).collect();
        self.refilter();
    }

    /// Work out which entries the filter admits.
    ///
    /// Matching is the same rule the `tomesole open` selector uses — title,
    /// author or filename, case-insensitively — so the two agree about what
    /// "dune" means.
    fn refilter(&mut self) {
        let keep = self.selected_entry().map(|e| e.md5.clone());
        let needle = self.filter.trim().to_lowercase();
        self.shown = self
            .library
            .iter()
            .enumerate()
            .filter(|(_, e)| {
                needle.is_empty()
                    || e.title.to_lowercase().contains(&needle)
                    || e.filename().to_lowercase().contains(&needle)
                    || e.authors
                        .as_deref()
                        .is_some_and(|a| a.to_lowercase().contains(&needle))
            })
            .map(|(i, _)| i)
            .collect();
        self.sort_shown();

        self.library_table.select(if self.shown.is_empty() {
            None
        } else {
            // Keep the highlight on the same book when it is still shown; else
            // pull it back in rather than leaving it pointing past the end.
            let position = keep.and_then(|md5| {
                self.shown.iter().position(|&i| self.library[i].md5 == md5)
            });
            Some(position.unwrap_or_else(|| {
                self.library_table
                    .selected()
                    .unwrap_or(0)
                    .min(self.shown.len() - 1)
            }))
        });
    }

    /// Order the shown library entries by the active sort. `Relevance` is the
    /// newest-first order the list already arrives in, so it only reverses.
    fn sort_shown(&mut self) {
        use std::cmp::Ordering;
        if self.sort == Sort::Relevance {
            if self.sort_desc {
                self.shown.reverse();
            }
            return;
        }
        let mut shown = std::mem::take(&mut self.shown);
        let (sort, desc) = (self.sort, self.sort_desc);
        shown.sort_by(|&a, &b| {
            let (x, y) = (&self.library[a], &self.library[b]);
            let ord = match sort {
                Sort::Title => x.title.to_lowercase().cmp(&y.title.to_lowercase()),
                Sort::Author => first_author_of(x.authors.as_deref())
                    .cmp(&first_author_of(y.authors.as_deref())),
                // A library entry has no year column, so "year" falls back to
                // when the book was added — the nearest thing it knows.
                Sort::Year => x.at.cmp(&y.at),
                Sort::Size => x.size.cmp(&y.size),
                Sort::Relevance => Ordering::Equal,
            };
            if desc { ord.reverse() } else { ord }
        });
        self.shown = shown;
    }

    fn selected_entry(&self) -> Option<&history::Entry> {
        self.library_table
            .selected()
            .and_then(|i| self.shown.get(i))
            .and_then(|&i| self.library.get(i))
    }

    /// Hand a past download to a reader, or to the file manager.
    fn launch_selected(&mut self, reveal: bool) {
        let Some(entry) = self.selected_entry().cloned() else {
            return;
        };
        let reader = self.settings.reader.clone();
        let result = if reveal {
            launch::reveal(&entry.path)
        } else {
            launch::open(&entry.path, reader.as_deref())
        };
        match result {
            Ok(()) => {
                self.error = None;
                self.status = format!(
                    "{} {}",
                    if reveal { "showing" } else { "opened" },
                    entry.filename()
                );
            }
            Err(e) => self.error = Some(first_line(&e.to_string())),
        }
    }

    /// Open the file for the highlighted search result, if it was downloaded.
    fn launch_result(&mut self, reveal: bool) {
        let Some(md5) = self.selected().map(|b| b.md5.clone()) else {
            return;
        };
        let entry = history::load().into_iter().find(|e| e.md5 == md5);
        let Some(entry) = entry else {
            self.error = Some("that one has not been downloaded yet".into());
            return;
        };
        let reader = self.settings.reader.clone();
        let result = if reveal {
            launch::reveal(&entry.path)
        } else {
            launch::open(&entry.path, reader.as_deref())
        };
        match result {
            Ok(()) => {
                self.error = None;
                self.status = format!("opened {}", entry.filename());
            }
            Err(e) => self.error = Some(first_line(&e.to_string())),
        }
    }

    /// Copy the focused book's MD5 to the system clipboard.
    ///
    /// The MD5 is the one handle that identifies a book everywhere — it is what
    /// `tomesole get` takes, and how a book is quoted to someone else — so it is
    /// the thing worth lifting out of the interface without reaching for a
    /// mouse. It goes out over OSC 52, the clipboard channel a terminal offers
    /// with no platform dependency: honoured by kitty, iTerm2, WezTerm, Ghostty
    /// and tmux, and harmlessly ignored elsewhere, so the status line reports
    /// what was sent rather than claiming a guaranteed paste.
    fn yank_md5(&mut self) {
        let Some(md5) = self.focused_md5() else {
            return;
        };
        copy_to_clipboard(&md5);
        self.error = None;
        self.status = format!("copied md5 {md5} to the clipboard");
    }

    /// Forget the highlighted entry. The file itself is left alone.
    fn forget_selected(&mut self) {
        let Some(entry) = self.selected_entry().cloned() else {
            return;
        };
        match history::remove(&entry.path) {
            Ok(_) => {
                self.reload_library();
                self.status = format!("forgot {} — the file is still there", entry.filename());
            }
            Err(e) => self.error = Some(first_line(&e.to_string())),
        }
    }

    // --- the text box -----------------------------------------------------
    //
    // One box, two meanings: search terms on one tab, a filter on the other.
    // Sharing the editing code means the caret, word deletion and multi-byte
    // handling only exist once.

    fn input(&self) -> &str {
        match self.tab {
            Tab::Search => &self.query,
            Tab::Library => &self.filter,
            // The Settings tab edits through its own buffer, never this box; the
            // arm is a harmless fallback so the shared editor code stays total.
            Tab::Settings => &self.query,
        }
    }

    fn input_mut(&mut self) -> &mut String {
        match self.tab {
            Tab::Search => &mut self.query,
            Tab::Library => &mut self.filter,
            Tab::Settings => &mut self.query,
        }
    }

    /// Called after every edit; the library narrows as you type, whereas a
    /// search waits for ⏎ because it costs a request.
    fn input_changed(&mut self) {
        if self.tab == Tab::Library {
            self.refilter();
        }
    }

    // --- event handling ---------------------------------------------------

    fn handle(&mut self, ev: Ev) {
        match ev {
            // A resize moves everything, so whatever was painted is now in the
            // wrong place and has to be placed again.
            Ev::Redraw => self.erase_cover(),
            Ev::Key(key) => self.on_key(key),
            Ev::Mirrors(Ok(mirrors)) => {
                self.busy = false;
                self.mirror_label = mirrors
                    .first()
                    .and_then(|u| net::host_of(u).ok())
                    .unwrap_or_else(|| "none".into());
                let count = mirrors.len();
                let first_mirror = self.mirrors.is_empty() && count > 0;
                self.mirrors = mirrors;
                self.status = format!("{count} mirror(s) available");
                if self.pending_search {
                    self.pending_search = false;
                    self.spawn_search();
                }
                // A library cover that came up empty while there was no mirror
                // to ask deserves another go now that there is one; drop those
                // blanks and re-arm the selection so it looks again.
                if first_mirror {
                    self.covers.retain(|_, slot| !matches!(slot, Slot::Nothing));
                    self.selection_moved();
                }
            }
            Ev::Mirrors(Err(e)) => {
                self.busy = false;
                self.mirror_label = "unavailable".into();
                self.status = "no mirror available".into();
                self.error = Some(first_line(&e));
            }
            Ev::Results { generation, .. } if generation != self.search_generation => {}
            Ev::Results {
                result: Ok((books, host)),
                ..
            } => {
                self.busy = false;
                self.mirror_label = host;
                self.marked = vec![false; books.len()];
                self.table.select(None);
                self.results = books;
                // A picker open over the old results is now describing a menu
                // that no longer exists; close it rather than let it commit a
                // stale value against the fresh set.
                self.picker = None;
                self.refine();
                self.status = match (self.results.len(), self.visible.len()) {
                    (0, _) => "nothing found — try fewer words".into(),
                    (total, shown) if shown < total => {
                        format!("{shown} of {total} match the filters")
                    }
                    (total, _) => format!("{total} result(s)"),
                };
                self.mode = Mode::Browsing;
            }
            Ev::Results { result: Err(e), .. } => {
                self.busy = false;
                self.status = "search failed".into();
                self.error = Some(first_line(&e));
            }
            Ev::Progress { md5, done, total } => {
                // Keep the start time across updates so the speed and estimate
                // are averaged over the whole transfer, not the last chunk.
                let started = match self.jobs.get(&md5) {
                    Some(Job::Running { started, .. }) => *started,
                    _ => Instant::now(),
                };
                self.jobs.insert(md5, Job::Running { done, total, started });
            }
            Ev::Finished { md5, outcome } => {
                let job = match outcome {
                    Ok(name) => {
                        self.status = format!("saved {name}");
                        // The book is in the library now; the tab should say so
                        // without being asked to reload.
                        self.reload_library();
                        Job::Saved(name)
                    }
                    Err(e) => {
                        let message = first_line(&e);
                        self.error = Some(message.clone());
                        Job::Failed(message)
                    }
                };
                self.jobs.insert(md5, job);
                // The worker finishes the whole batch before going quiet, so
                // the flag clears once nothing is left queued or running.
                self.downloading = self
                    .jobs
                    .values()
                    .any(|j| matches!(j, Job::Queued | Job::Running { .. }));
            }
            Ev::Cover { md5, result } => {
                let slot = match result {
                    // What each protocol needs from a cover differs: iTerm2
                    // takes the encoded file and wants nothing decoded, kitty
                    // takes either, and half blocks can only draw pixels — so
                    // a cover it cannot decode is no cover at all.
                    Ok(Some(cover)) => match self.protocol {
                        Protocol::ITerm2 => Slot::Ready(Box::new(Art {
                            encoded: cover.encoded,
                            pixels: None,
                        })),
                        Protocol::Kitty => {
                            let pixels = cover.pixels();
                            Slot::Ready(Box::new(Art {
                                encoded: cover.encoded,
                                pixels,
                            }))
                        }
                        Protocol::Blocks => match cover.pixels() {
                            Some(pixels) => Slot::Ready(Box::new(Art {
                                encoded: Vec::new(),
                                pixels: Some(pixels),
                            })),
                            None => Slot::Nothing,
                        },
                        Protocol::None => Slot::Nothing,
                    },
                    // A cover that will not come is not an error worth putting
                    // in front of someone who asked for a book.
                    Ok(None) | Err(_) => Slot::Nothing,
                };
                self.covers.insert(md5, slot);
            }
        }
    }

    fn on_key(&mut self, key: KeyEvent) {
        // Ctrl-C always quits, whatever is on screen.
        if key.modifiers.contains(KeyModifiers::CONTROL) && key.code == KeyCode::Char('c') {
            self.quit = true;
            return;
        }
        // The facet pop-over is modal: while it is up it takes every key, so a
        // letter narrows its list rather than leaking out to the results below.
        if self.picker.is_some() {
            self.on_key_picker(key);
            return;
        }
        // The sort menu is modal in the same way.
        if self.sort_menu.is_some() {
            self.on_key_sort(key);
            return;
        }
        // A field being typed on the Settings tab captures the tab-switch keys
        // (Tab, the digits) the same way the search box captures a digit: while
        // it is up they are text or list movement, not navigation.
        let settings_editing = self.tab == Tab::Settings
            && (self.form.editing.is_some() || self.form.sub != SubFocus::None);

        // Switching tabs works from everywhere, including mid-typing. The
        // library used to be reachable only from the results list, which meant
        // you had to run a search before you could look at books you already
        // had — exactly backwards.
        if !settings_editing {
            match key.code {
                KeyCode::Tab => {
                    if self.mode == Mode::Help {
                        self.mode = Mode::Browsing;
                    }
                    self.show(self.tab.next());
                    return;
                }
                KeyCode::BackTab => {
                    if self.mode == Mode::Help {
                        self.mode = Mode::Browsing;
                    }
                    self.show(self.tab.prev());
                    return;
                }
                // Direct jumps, for when you know where you are going. Not while
                // typing, where a digit is a digit.
                KeyCode::Char('1') if self.mode != Mode::Editing => return self.show(Tab::Search),
                KeyCode::Char('2') if self.mode != Mode::Editing => return self.show(Tab::Library),
                KeyCode::Char('3') if self.mode != Mode::Editing => {
                    return self.show(Tab::Settings);
                }
                _ => {}
            }
        }
        match self.mode {
            Mode::Help => self.mode = Mode::Browsing,
            Mode::Editing => self.on_key_editing(key),
            Mode::Browsing => match self.tab {
                Tab::Search => self.on_key_results(key),
                Tab::Library => self.on_key_library(key),
                Tab::Settings => self.on_key_settings(key),
            },
        }
    }

    fn on_key_editing(&mut self, key: KeyEvent) {
        let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
        let len = self.input().chars().count();
        match key.code {
            KeyCode::Enter => {
                self.mode = Mode::Browsing;
                // A filter has already been applied on every keystroke; only a
                // search has anything left to do.
                if self.tab == Tab::Search {
                    self.spawn_search();
                }
            }
            KeyCode::Esc => self.mode = Mode::Browsing,
            KeyCode::Char('u') if ctrl => {
                self.input_mut().clear();
                self.caret = 0;
                self.input_changed();
            }
            KeyCode::Char('w') if ctrl => self.delete_word(),
            KeyCode::Char(c) => {
                let at = self.byte_offset(self.caret);
                self.input_mut().insert(at, c);
                self.caret += 1;
                self.input_changed();
            }
            KeyCode::Backspace if self.caret > 0 => {
                let at = self.byte_offset(self.caret - 1);
                self.input_mut().remove(at);
                self.caret -= 1;
                self.input_changed();
            }
            KeyCode::Delete if self.caret < len => {
                let at = self.byte_offset(self.caret);
                self.input_mut().remove(at);
                self.input_changed();
            }
            KeyCode::Left => self.caret = self.caret.saturating_sub(1),
            KeyCode::Right => self.caret = (self.caret + 1).min(len),
            KeyCode::Home => self.caret = 0,
            KeyCode::End => self.caret = len,
            // The lists are still navigable while the box has focus, so you can
            // narrow and pick without reaching for Esc first.
            KeyCode::Down => self.move_selection(1),
            KeyCode::Up => self.move_selection(-1),
            _ => {}
        }
    }

    /// Move whichever list the visible tab owns.
    fn move_selection(&mut self, delta: isize) {
        match self.tab {
            Tab::Search => self.move_by(delta),
            Tab::Library => self.move_library_by(delta),
            // The Settings tab never enters `Mode::Editing`, so this is unreached
            // from there; the arm keeps the match total.
            Tab::Settings => {}
        }
    }

    fn on_key_results(&mut self, key: KeyEvent) {
        match key.code {
            KeyCode::Char('q') | KeyCode::Esc => self.quit = true,
            KeyCode::Char('/') | KeyCode::Char('i') => {
                self.mode = Mode::Editing;
                self.caret = self.query.chars().count();
            }
            KeyCode::Char('?') => self.mode = Mode::Help,
            KeyCode::Down | KeyCode::Char('j') => self.move_by(1),
            KeyCode::Up | KeyCode::Char('k') => self.move_by(-1),
            KeyCode::PageDown => self.move_by(10),
            KeyCode::PageUp => self.move_by(-10),
            KeyCode::Home | KeyCode::Char('g') if !self.visible.is_empty() => {
                self.table.select(Some(0));
                self.selection_moved();
            }
            KeyCode::End | KeyCode::Char('G') if !self.visible.is_empty() => {
                self.table.select(Some(self.visible.len() - 1));
                self.selection_moved();
            }
            KeyCode::Char(' ') => {
                if let Some(&i) = self.table.selected().and_then(|i| self.visible.get(i))
                    && let Some(flag) = self.marked.get_mut(i)
                {
                    *flag = !*flag;
                }
                self.move_by(1);
            }
            KeyCode::Char('A') => {
                // "Everything" means everything showing: filters carve the
                // batch too, which is the whole point of them.
                let all = self
                    .visible
                    .iter()
                    .all(|&i| self.marked.get(i).copied().unwrap_or(false));
                for &i in &self.visible {
                    if let Some(flag) = self.marked.get_mut(i) {
                        *flag = !all;
                    }
                }
            }
            KeyCode::Char('e') => self.open_picker(Facet::Format),
            KeyCode::Char('l') => self.open_picker(Facet::Language),
            KeyCode::Char('a') => self.open_picker(Facet::Author),
            KeyCode::Char('x') if self.any_filter() => self.clear_filters(),
            KeyCode::Char('s') => self.open_sort_menu(),
            KeyCode::Char('S') => self.reverse_sort(),
            KeyCode::Char('y') => self.yank_md5(),
            KeyCode::Enter => self.spawn_downloads(),
            KeyCode::Char('r') => self.spawn_search(),
            KeyCode::Char('m') => self.spawn_mirror_resolve(true),
            KeyCode::Char('o') => self.launch_result(false),
            KeyCode::Char('f') => self.launch_result(true),
            _ => {}
        }
    }

    /// Keys while the facet pop-over is up. Letters type into its narrow line;
    /// the arrows (and Ctrl-N/P, so the home row keeps typing) walk the menu;
    /// Tab rotates to the next facet without leaving the overlay; Enter commits
    /// and Esc backs out leaving the results as they were.
    fn on_key_picker(&mut self, key: KeyEvent) {
        let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
        // These need `self` whole — a facet switch recomputes the menu, apply
        // re-sorts the results — so they run before the mutable borrow below.
        match key.code {
            KeyCode::Esc => {
                self.picker = None;
                return;
            }
            KeyCode::Enter => {
                self.apply_picker();
                return;
            }
            KeyCode::Tab => {
                if let Some(next) = self.picker.as_ref().map(|p| p.facet.next()) {
                    self.open_picker(next);
                }
                return;
            }
            KeyCode::BackTab => {
                if let Some(prev) = self.picker.as_ref().map(|p| p.facet.prev()) {
                    self.open_picker(prev);
                }
                return;
            }
            _ => {}
        }
        let Some(picker) = self.picker.as_mut() else {
            return;
        };
        let last = picker.rows() - 1;
        match key.code {
            KeyCode::Up => picker.cursor = picker.cursor.saturating_sub(1),
            KeyCode::Char('p') if ctrl => picker.cursor = picker.cursor.saturating_sub(1),
            KeyCode::Down => picker.cursor = (picker.cursor + 1).min(last),
            KeyCode::Char('n') if ctrl => picker.cursor = (picker.cursor + 1).min(last),
            KeyCode::Home => picker.cursor = 0,
            KeyCode::End => picker.cursor = last,
            KeyCode::Char('u') if ctrl => {
                picker.query.clear();
                picker.cursor = 0;
            }
            KeyCode::Backspace => {
                picker.query.pop();
                picker.cursor = picker.first_match_row();
            }
            KeyCode::Char(c) if !ctrl => {
                picker.query.push(c);
                picker.cursor = picker.first_match_row();
            }
            _ => {}
        }
    }

    /// Keys while the sort menu is up. The list is short and takes no text, so
    /// the arrows and `j`/`k` both walk it; `←`/`→` (and `h`/`l`) flip the
    /// highlighted key's direction; Enter commits and Esc — or `s` again —
    /// backs out.
    fn on_key_sort(&mut self, key: KeyEvent) {
        match key.code {
            KeyCode::Esc | KeyCode::Char('s') | KeyCode::Char('q') => {
                self.sort_menu = None;
                return;
            }
            KeyCode::Enter => {
                self.apply_sort_menu();
                return;
            }
            _ => {}
        }
        let Some(menu) = self.sort_menu.as_mut() else {
            return;
        };
        let last = Sort::CYCLE.len() - 1;
        match key.code {
            KeyCode::Up | KeyCode::Char('k') => {
                menu.cursor = menu.cursor.saturating_sub(1);
                menu.desc = Sort::CYCLE[menu.cursor].natural_desc();
            }
            KeyCode::Down | KeyCode::Char('j') => {
                menu.cursor = (menu.cursor + 1).min(last);
                menu.desc = Sort::CYCLE[menu.cursor].natural_desc();
            }
            // Relevance is the mirror's own order; there is no ascending or
            // descending to choose, so the direction keys leave it alone.
            KeyCode::Left | KeyCode::Right | KeyCode::Char('h') | KeyCode::Char('l')
                if Sort::CYCLE[menu.cursor] != Sort::Relevance =>
            {
                menu.desc = !menu.desc;
            }
            _ => {}
        }
    }

    fn on_key_library(&mut self, key: KeyEvent) {
        match key.code {
            // The library is a peer of the search tab, not a detour off it, so
            // `q` means the same thing on both.
            KeyCode::Char('q') | KeyCode::Esc => self.quit = true,
            KeyCode::Char('/') | KeyCode::Char('i') => {
                self.mode = Mode::Editing;
                self.caret = self.filter.chars().count();
            }
            KeyCode::Char('?') => self.mode = Mode::Help,
            KeyCode::Down | KeyCode::Char('j') => self.move_library_by(1),
            KeyCode::Up | KeyCode::Char('k') => self.move_library_by(-1),
            KeyCode::PageDown => self.move_library_by(10),
            KeyCode::PageUp => self.move_library_by(-10),
            KeyCode::Home | KeyCode::Char('g') if !self.shown.is_empty() => {
                self.library_table.select(Some(0));
                self.selection_moved();
            }
            KeyCode::End | KeyCode::Char('G') if !self.shown.is_empty() => {
                self.library_table.select(Some(self.shown.len() - 1));
                self.selection_moved();
            }
            KeyCode::Char('s') => self.open_sort_menu(),
            KeyCode::Char('S') => self.reverse_sort(),
            KeyCode::Char('y') => self.yank_md5(),
            KeyCode::Enter | KeyCode::Char('o') => self.launch_selected(false),
            KeyCode::Char('f') => self.launch_selected(true),
            KeyCode::Char('d') => self.forget_selected(),
            KeyCode::Char('r') => {
                self.reload_library();
                self.status = format!("{} book(s)", self.library.len());
            }
            _ => {}
        }
    }

    // --- the settings form ------------------------------------------------

    /// The field the cursor is on.
    fn current_field(&self) -> Field {
        Field::ALL[self.form.selected.min(Field::ALL.len() - 1)]
    }

    fn on_key_settings(&mut self, key: KeyEvent) {
        // A line being typed takes precedence over everything else.
        if self.form.editing.is_some() {
            self.on_key_settings_edit(key);
            return;
        }
        match self.form.sub {
            SubFocus::Topics => self.on_key_topics(key),
            SubFocus::Mirrors => self.on_key_mirrors(key),
            SubFocus::None => match key.code {
                KeyCode::Char('q') => self.quit = true,
                KeyCode::Char('?') => self.mode = Mode::Help,
                KeyCode::Down | KeyCode::Char('j') => self.move_field(1),
                KeyCode::Up | KeyCode::Char('k') => self.move_field(-1),
                KeyCode::Home | KeyCode::Char('g') => self.select_field(0),
                KeyCode::End | KeyCode::Char('G') => self.select_field(Field::ALL.len() - 1),
                KeyCode::Enter | KeyCode::Char(' ') => self.activate_field(),
                _ => {}
            },
        }
    }

    fn move_field(&mut self, delta: isize) {
        let last = (Field::ALL.len() - 1) as isize;
        let next = (self.form.selected as isize + delta).clamp(0, last) as usize;
        self.select_field(next);
    }

    fn select_field(&mut self, index: usize) {
        self.form.selected = index.min(Field::ALL.len() - 1);
        self.form.error = None;
    }

    /// Enter, or space, on the highlighted field: toggle a bool, open a line
    /// editor, or step into a sub-list.
    fn activate_field(&mut self) {
        let field = self.current_field();
        self.form.error = None;
        match field.kind() {
            FieldKind::Bool => self.toggle_bool(field),
            FieldKind::Line => {
                self.form.editing = Some(Edit {
                    caret: self.field_value(field).chars().count(),
                    buffer: self.field_value(field),
                });
            }
            FieldKind::Topics => {
                self.form.sub = SubFocus::Topics;
                self.form.topic_row = 0;
            }
            FieldKind::Mirrors => {
                self.form.sub = SubFocus::Mirrors;
                self.form.mirror_row = 0;
            }
        }
    }

    /// Editing a `Line` field: a small self-contained line editor whose buffer
    /// lives on the form, kept apart from the search box's own caret.
    fn on_key_settings_edit(&mut self, key: KeyEvent) {
        let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
        let Some(edit) = self.form.editing.as_mut() else {
            return;
        };
        match key.code {
            KeyCode::Enter => {
                let text = edit.buffer.clone();
                self.commit_edit(text);
            }
            KeyCode::Esc => {
                self.form.editing = None;
            }
            KeyCode::Char('u') if ctrl => {
                edit.buffer.clear();
                edit.caret = 0;
            }
            KeyCode::Char(c) => {
                let at = char_byte(&edit.buffer, edit.caret);
                edit.buffer.insert(at, c);
                edit.caret += 1;
            }
            KeyCode::Backspace if edit.caret > 0 => {
                let at = char_byte(&edit.buffer, edit.caret - 1);
                edit.buffer.remove(at);
                edit.caret -= 1;
            }
            KeyCode::Left => edit.caret = edit.caret.saturating_sub(1),
            KeyCode::Right => edit.caret = (edit.caret + 1).min(edit.buffer.chars().count()),
            KeyCode::Home => edit.caret = 0,
            KeyCode::End => edit.caret = edit.buffer.chars().count(),
            _ => {}
        }
    }

    /// Validate and store a committed line, or keep the editor open with an
    /// error. The mirror sub-mode uses this too, to add a typed URL.
    fn commit_edit(&mut self, text: String) {
        if self.form.sub == SubFocus::Mirrors {
            let url = text.trim();
            if url.is_empty() {
                self.form.editing = None;
                return;
            }
            self.config.mirrors.push(url.to_string());
            self.form.mirror_row = self.config.mirrors.len() - 1;
            self.form.editing = None;
            self.persist();
            return;
        }

        let field = self.current_field();
        match self.set_field(field, &text) {
            Ok(()) => {
                self.form.editing = None;
                self.form.error = None;
                self.persist();
                self.apply_live(field);
            }
            Err(message) => self.form.error = Some(message),
        }
    }

    /// Parse `text` for `field` and write it into the config, or return why not.
    /// An empty line clears an optional field back to its default.
    fn set_field(&mut self, field: Field, text: &str) -> std::result::Result<(), String> {
        let text = text.trim();
        match field {
            Field::MaxSize => {
                self.config.max_size = if text.is_empty() {
                    None
                } else {
                    Some(
                        crate::model::parse_size(text)
                            .ok_or_else(|| format!("`{text}` is not a size, try e.g. 4 GB"))?,
                    )
                };
            }
            Field::Limit => {
                self.config.limit = if text.is_empty() {
                    None
                } else {
                    Some(
                        text.parse::<usize>()
                            .map_err(|_| format!("`{text}` is not a whole number"))?,
                    )
                };
            }
            Field::Reader => {
                self.config.reader = (!text.is_empty()).then(|| text.to_string());
            }
            Field::DownloadDir => {
                self.config.download_dir =
                    (!text.is_empty()).then(|| crate::config::expand_tilde(text));
            }
            _ => {}
        }
        Ok(())
    }

    fn toggle_bool(&mut self, field: Field) {
        let now = match field {
            Field::Covers => !self.config.covers.unwrap_or(true),
            Field::History => !self.config.history.unwrap_or(true),
            Field::Verify => !self.config.verify.unwrap_or(true),
            Field::AllowHttp => !self.config.allow_http,
            _ => return,
        };
        match field {
            Field::Covers => self.config.covers = Some(now),
            Field::History => self.config.history = Some(now),
            Field::Verify => self.config.verify = Some(now),
            Field::AllowHttp => self.config.allow_http = now,
            _ => {}
        }
        self.persist();
        self.apply_live(field);
    }

    fn on_key_topics(&mut self, key: KeyEvent) {
        match key.code {
            KeyCode::Esc | KeyCode::Enter => self.form.sub = SubFocus::None,
            KeyCode::Down | KeyCode::Char('j') => {
                self.form.topic_row = (self.form.topic_row + 1).min(Topic::ALL.len() - 1);
            }
            KeyCode::Up | KeyCode::Char('k') => {
                self.form.topic_row = self.form.topic_row.saturating_sub(1);
            }
            KeyCode::Char(' ') => self.toggle_topic(Topic::ALL[self.form.topic_row]),
            _ => {}
        }
    }

    /// Flip one collection's membership. The set starts from the effective
    /// default the first time it is touched, so a toggle reads as a toggle.
    fn toggle_topic(&mut self, topic: Topic) {
        let mut topics = self
            .config
            .topics
            .clone()
            .unwrap_or_else(|| vec![Topic::Libgen, Topic::Fiction]);
        if let Some(i) = topics.iter().position(|&t| t == topic) {
            topics.remove(i);
        } else {
            // Keep the canonical order so the file reads tidily.
            topics.push(topic);
            topics.sort_by_key(|t| Topic::ALL.iter().position(|x| x == t).unwrap_or(0));
        }
        self.config.topics = Some(topics);
        self.persist();
    }

    fn on_key_mirrors(&mut self, key: KeyEvent) {
        match key.code {
            KeyCode::Esc => self.form.sub = SubFocus::None,
            KeyCode::Down | KeyCode::Char('j') => {
                let last = self.config.mirrors.len().saturating_sub(1);
                self.form.mirror_row = (self.form.mirror_row + 1).min(last);
            }
            KeyCode::Up | KeyCode::Char('k') => {
                self.form.mirror_row = self.form.mirror_row.saturating_sub(1);
            }
            KeyCode::Char('a') => {
                // Add a mirror: an empty line editor, committed as a new URL.
                self.form.editing = Some(Edit::default());
            }
            KeyCode::Char('d') | KeyCode::Delete
                if self.form.mirror_row < self.config.mirrors.len() =>
            {
                self.config.mirrors.remove(self.form.mirror_row);
                let last = self.config.mirrors.len().saturating_sub(1);
                self.form.mirror_row = self.form.mirror_row.min(last);
                self.persist();
            }
            _ => {}
        }
    }

    /// Write the config to disk, reporting the outcome in the status line.
    fn persist(&mut self) {
        match self.config.save_to(&self.config_path) {
            Ok(()) => {
                self.form.error = None;
                self.status = format!("saved to {}", self.config_path.display());
            }
            Err(e) => self.form.error = Some(e.to_string()),
        }
    }

    /// Fold a just-saved change into the running session where it is safe to.
    /// The startup-established settings (net policy, mirror pool, search
    /// defaults) are left for next launch; the form flags those.
    fn apply_live(&mut self, field: Field) {
        match field {
            Field::Covers => {
                let on = self.config.covers.unwrap_or(true);
                if !self.settings.overrides.covers {
                    self.settings.covers = on;
                }
                if !self.settings.covers {
                    self.erase_cover();
                    self.covers.clear();
                    self.cover_due = None;
                } else if self.protocol == Protocol::None {
                    self.protocol = graphics::detect();
                }
            }
            Field::History => self.settings.history = self.config.history.unwrap_or(true),
            Field::Verify if !self.settings.overrides.verify => {
                self.settings.verify = self.config.verify.unwrap_or(true);
            }
            Field::Reader if !self.settings.overrides.reader => {
                self.settings.reader = self.config.reader.clone();
            }
            Field::MaxSize if !self.settings.overrides.max_bytes => {
                self.settings.max_bytes =
                    self.config.max_size.unwrap_or(crate::DEFAULT_MAX_BYTES);
            }
            Field::DownloadDir if !self.settings.overrides.dest_dir => {
                self.settings.dest_dir = self
                    .config
                    .download_dir
                    .clone()
                    .unwrap_or_else(crate::config::default_download_dir);
            }
            // Deferred: only takes effect next launch.
            _ => {}
        }
    }

    /// The row's value as shown in the form (friendly, not the raw edit text).
    fn field_display(&self, field: Field) -> String {
        let on_off = |b: bool| if b { "on" } else { "off" }.to_string();
        match field {
            Field::Covers => on_off(self.config.covers.unwrap_or(true)),
            Field::History => on_off(self.config.history.unwrap_or(true)),
            Field::Verify => on_off(self.config.verify.unwrap_or(true)),
            Field::AllowHttp => on_off(self.config.allow_http),
            Field::MaxSize => match self.config.max_size {
                Some(n) => crate::model::human_bytes(n),
                None => "4 GB (default)".into(),
            },
            Field::Reader => self
                .config
                .reader
                .clone()
                .unwrap_or_else(|| "system default".into()),
            Field::DownloadDir => match &self.config.download_dir {
                Some(p) => p.display().to_string(),
                None => format!("{} (default)", crate::config::default_download_dir().display()),
            },
            Field::Limit => match self.config.limit {
                Some(n) => n.to_string(),
                None => "25 (default)".into(),
            },
            Field::Topics => {
                let topics = self
                    .config
                    .topics
                    .clone()
                    .unwrap_or_else(|| vec![Topic::Libgen, Topic::Fiction]);
                topics
                    .iter()
                    .map(|t| t.name())
                    .collect::<Vec<_>>()
                    .join(", ")
            }
            Field::Mirrors => match self.config.mirrors.len() {
                0 => "auto".into(),
                1 => "1 mirror".into(),
                n => format!("{n} mirrors"),
            },
        }
    }

    /// The raw editable text for a `Line` field.
    fn field_value(&self, field: Field) -> String {
        match field {
            Field::MaxSize => self.config.max_size.map(|n| n.to_string()).unwrap_or_default(),
            Field::Reader => self.config.reader.clone().unwrap_or_default(),
            Field::DownloadDir => self
                .config
                .download_dir
                .as_ref()
                .map(|p| p.display().to_string())
                .unwrap_or_default(),
            Field::Limit => self.config.limit.map(|n| n.to_string()).unwrap_or_default(),
            _ => String::new(),
        }
    }

    fn move_library_by(&mut self, delta: isize) {
        if self.shown.is_empty() {
            return;
        }
        let last = self.shown.len() - 1;
        let current = self.library_table.selected().unwrap_or(0) as isize;
        let next = (current + delta).clamp(0, last as isize) as usize;
        if Some(next) != self.library_table.selected() {
            self.selection_moved();
        }
        self.library_table.select(Some(next));
    }

    fn move_by(&mut self, delta: isize) {
        if self.visible.is_empty() {
            return;
        }
        let last = self.visible.len() - 1;
        let current = self.table.selected().unwrap_or(0) as isize;
        let next = (current + delta).clamp(0, last as isize) as usize;
        if Some(next) != self.table.selected() {
            self.selection_moved();
        }
        self.table.select(Some(next));
    }

    fn delete_word(&mut self) {
        let text = self.input();
        let head: String = text.chars().take(self.caret).collect();
        let trimmed = head.trim_end();
        let cut = match trimmed.rfind(' ') {
            Some(i) => trimmed[..i + 1].chars().count(),
            None => 0,
        };
        let tail: String = text.chars().skip(self.caret).collect();
        let kept: String = text.chars().take(cut).collect();
        *self.input_mut() = format!("{kept}{tail}");
        self.caret = cut;
        self.input_changed();
    }

    /// Byte offset of the given character index, for editing in place.
    fn byte_offset(&self, chars: usize) -> usize {
        let text = self.input();
        text.char_indices()
            .nth(chars)
            .map(|(i, _)| i)
            .unwrap_or(text.len())
    }

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

    /// How tall the detail pane is, borders included.
    ///
    /// A cover needs more room than the six lines of text, but only when there
    /// is one to show, and never so much that the results list is squeezed out.
    fn details_height(&self, area: Rect) -> u16 {
        let plain = 8u16;
        // Leave the list at least four rows plus its header, whatever else we
        // do — the details pane must never crowd out the results.
        let ceiling = area.height.saturating_sub(3 + 1 + 5).max(3);
        let floor = plain.min(ceiling);
        if !self.cover_visible() {
            return floor;
        }
        let wanted = 13;
        wanted.min(area.height.saturating_sub(3 + 1 + 5)).max(floor)
    }

    /// Where the picture goes, in screen coordinates.
    fn cover_rect(&self) -> Option<Rect> {
        self.cover_area
    }

    fn render(&mut self, frame: &mut Frame) {
        // One tick per frame drives every animated glyph on screen. The loop
        // wakes on a 250 ms timer even when idle, so it advances calmly.
        self.spinner = self.spinner.wrapping_add(1);
        let area = frame.area();
        // The canvas goes down first; everything after patches colour onto it.
        frame.render_widget(
            Block::new().style(Style::new().bg(theme::BG).fg(theme::TEXT)),
            area,
        );
        self.cover_area = None;

        // A terminal is a bottom-up place, so the interface is too. With nothing
        // to browse yet the search box floats near the middle — where the eye
        // already rests and a keystroke from the hints below. The moment a
        // search lands something to look at, the box settles to the bottom and
        // the results take the screen.
        let landing = match self.tab {
            Tab::Search => self.results.is_empty(),
            Tab::Library => self.library.is_empty(),
            Tab::Settings => false,
        };
        if self.tab == Tab::Settings {
            // The form is its own thing: a full-height list of fields with the
            // hints at the foot, and no landing state, cover band or search box.
            self.render_settings(frame, area);
        } else if landing {
            self.render_landing(frame, area);
        } else {
            // The record for the selected row lies as a horizontal band across
            // the bottom rather than a column down the side, so the results keep
            // the full width of the screen and the table never fights a panel
            // for room. A control strip rides directly on top of the search box:
            // the facets, sort and counts on Search; the sort and a one-line
            // shelf summary on Library. Gathering everything you type with at the
            // foot is what keeps the two tabs reading as one interface.
            let filter_bar = match self.tab {
                Tab::Search => !self.results.is_empty(),
                Tab::Library => !self.library.is_empty(),
                Tab::Settings => false,
            } as u16;
            let empty_tab = match self.tab {
                Tab::Search => self.visible.is_empty(),
                Tab::Library => self.shown.is_empty(),
                Tab::Settings => false,
            };
            let details = if empty_tab && self.error.is_none() {
                0
            } else {
                self.details_height(area)
            };
            let chunks = Layout::vertical([
                Constraint::Min(3),             // results / library body
                Constraint::Length(details),    // details band
                Constraint::Length(filter_bar), // facets / shelf summary + sort
                Constraint::Length(3),          // search box
                Constraint::Length(1),          // key hints
            ])
            .split(area);

            match self.tab {
                Tab::Search => {
                    self.render_results(frame, chunks[0]);
                    self.render_details(frame, chunks[1]);
                }
                Tab::Library => {
                    self.render_library(frame, chunks[0]);
                    self.render_library_details(frame, chunks[1]);
                }
                // Handled by the `Tab::Settings` branch above; this arm is dead.
                Tab::Settings => {}
            }
            if filter_bar == 1 {
                match self.tab {
                    Tab::Search => self.render_filters(frame, chunks[2]),
                    Tab::Library => self.render_library_strip(frame, chunks[2]),
                    Tab::Settings => {}
                }
            }
            self.render_input(frame, chunks[3]);
            self.render_hints(frame, chunks[4]);
        }

        if self.mode == Mode::Help {
            self.render_help(frame);
        }
        if self.picker.is_some() {
            self.render_picker(frame);
        }
        if self.sort_menu.is_some() {
            self.render_sort_menu(frame);
        }
    }

    /// The opening state: the search box near the middle with a line of guidance
    /// under it, and the hints pinned to the foot of the screen. This is where a
    /// terminal's cursor wants to be — not craned up to the top edge — and it
    /// keeps the box next to the keys that explain it.
    fn render_landing(&self, frame: &mut Frame, area: Rect) {
        // The wordmark is the Search tab's face; the empty Library keeps its own
        // "your library is empty" note with no banner. It shows only when the
        // screen can hold it whole — a short or narrow terminal falls back to
        // just the box, so the art never has to clip or wrap.
        let show_mark =
            self.tab == Tab::Search && area.height >= 16 && area.width >= WORDMARK_W + 2;
        let mark_rows = if show_mark { WORDMARK_H + 1 } else { 0 }; // +1 breathing row

        let rows = Layout::vertical([
            Constraint::Fill(4),
            Constraint::Length(mark_rows), // wordmark + gap (0 when hidden)
            Constraint::Length(3),         // search box
            Constraint::Length(1),         // breathing room
            Constraint::Length(4),         // guidance / status / error
            Constraint::Fill(5),
            Constraint::Length(1),         // key hints
        ])
        .split(area);

        if show_mark {
            self.render_wordmark(frame, rows[1]);
        }
        // A capped width so it reads as a search field rather than a full-bleed
        // bar; centred so it sits under the eye, not off in a corner.
        let box_w = area.width.saturating_sub(6).clamp(24, 76);
        self.render_input(frame, centered(rows[2], box_w, rows[2].height));
        let guide_w = area.width.saturating_sub(4).min(80);
        self.render_landing_guide(frame, centered(rows[4], guide_w, rows[4].height));
        self.render_hints(frame, rows[6]);
    }

    /// Paint the big ASCII wordmark, centred, in the theme accent. Each line is
    /// padded to the banner's full width before it goes down, so centred
    /// alignment holds the block square rather than nudging the two short rows.
    /// No `Wrap` is set, so a line can only ever clip — never fold — but the
    /// caller gates on width so even that does not happen.
    fn render_wordmark(&self, frame: &mut Frame, area: Rect) {
        let lines: Vec<Line> = WORDMARK
            .lines()
            .map(|l| {
                Line::from(Span::styled(
                    format!("{l:<width$}", width = WORDMARK_W as usize),
                    theme::accent(),
                ))
            })
            .collect();
        let spot = centered(area, WORDMARK_W, WORDMARK_H);
        frame.render_widget(Paragraph::new(lines).alignment(Alignment::Center), spot);
    }

    /// What sits under the box before there is a list: an error if a search just
    /// failed, the live status while one runs, or a quiet word on how to begin.
    fn render_landing_guide(&self, frame: &mut Frame, area: Rect) {
        let lines: Vec<Line> = if let Some(err) = &self.error {
            vec![Line::from(vec![
                Span::styled("", Style::new().fg(theme::DANGER)),
                Span::styled(err.clone(), Style::new().fg(theme::DANGER)),
            ])]
        } else if self.busy {
            vec![Line::from(vec![
                Span::styled(format!("{} ", spinner_frame(self.spinner)), theme::accent()),
                Span::styled(self.status.clone(), theme::muted()),
            ])]
        } else if !self.status.is_empty() {
            vec![Line::from(Span::styled(self.status.clone(), theme::muted()))]
        } else {
            match self.tab {
                Tab::Search => vec![
                    Line::from(Span::styled(
                        "Search millions of books on Library Genesis.",
                        theme::muted(),
                    )),
                    Line::from(""),
                    Line::from(vec![
                        Span::styled("try ", theme::faint()),
                        Span::styled("author:", theme::accent()),
                        Span::styled("  ", theme::faint()),
                        Span::styled("title:", theme::accent()),
                        Span::styled("  ", theme::faint()),
                        Span::styled("ext:", theme::accent()),
                        Span::styled(" to narrow a search", theme::faint()),
                    ]),
                ],
                Tab::Library => vec![
                    Line::from(Span::styled(
                        "Your library is empty.",
                        theme::text().add_modifier(Modifier::BOLD),
                    )),
                    Line::from(""),
                    Line::from(vec![
                        Span::styled("Books you download land here. Press ", theme::faint()),
                        Span::styled("Tab", theme::accent()),
                        Span::styled(" to go find one.", theme::faint()),
                    ]),
                ],
                // The Settings tab has no landing state, so this is never drawn.
                Tab::Settings => Vec::new(),
            }
        };
        frame.render_widget(Paragraph::new(lines).alignment(Alignment::Center), area);
    }

    /// The refinement bar: the three facets and what they leave showing.
    ///
    /// It lives on its own row, under the search box, so the counts update in
    /// place as a facet is picked — filters you can watch working, rather than
    /// tags you have to re-type into a new search.
    /// The sort indicator for the control strip: the key that cycles it, the
    /// active order, and a caret for the direction — dropped for `Relevance`,
    /// which is the list's own order and has no up or down.
    fn sort_indicator(&self) -> Vec<Span<'static>> {
        let caret = match (self.sort, self.sort_desc) {
            (Sort::Relevance, _) => "",
            (_, true) => "",
            (_, false) => "",
        };
        vec![
            Span::styled("s", theme::accent().add_modifier(Modifier::BOLD)),
            Span::styled(" sort ", theme::faint()),
            Span::styled(self.sort.label(self.tab).to_string(), theme::muted()),
            Span::styled(caret.to_string(), Style::new().fg(theme::AMBER)),
        ]
    }

    /// How many results are marked, and their combined size, when any are — so
    /// the strip can say what a batch download is about to pull.
    fn marked_summary(&self) -> Option<(usize, u64)> {
        let mut count = 0usize;
        let mut bytes = 0u64;
        for (book, marked) in self.results.iter().zip(&self.marked) {
            if *marked {
                count += 1;
                bytes += book.size_bytes.unwrap_or(0);
            }
        }
        (count > 0).then_some((count, bytes))
    }

    fn render_filters(&self, frame: &mut Frame, area: Rect) {
        if area.height == 0 {
            return;
        }
        // Right side first: the sort, then either what a marked batch would
        // pull, or how much of the catch is on screen. Amber comes out only
        // when something is being narrowed or gathered.
        let mut right = self.sort_indicator();
        right.push(Span::styled("     ", theme::faint()));
        match self.marked_summary() {
            Some((n, bytes)) => {
                let amber = Style::new().fg(theme::AMBER).add_modifier(Modifier::BOLD);
                right.push(Span::styled(format!("{n} marked"), amber));
                if bytes > 0 {
                    right.push(Span::styled(format!("  {} ", human_bytes(bytes)), theme::muted()));
                } else {
                    right.push(Span::raw(" "));
                }
            }
            None if self.visible.len() < self.results.len() => right.push(Span::styled(
                format!("{} of {} shown ", self.visible.len(), self.results.len()),
                Style::new().fg(theme::AMBER).add_modifier(Modifier::BOLD),
            )),
            None => right.push(Span::styled(
                format!("{} results ", self.results.len()),
                theme::faint(),
            )),
        }
        frame.render_widget(
            Paragraph::new(Line::from(right)).alignment(Alignment::Right),
            area,
        );

        let key = |k: char| {
            Span::styled(k.to_string(), theme::accent().add_modifier(Modifier::BOLD))
        };
        let label = |l: &str| Span::styled(format!(" {l} "), theme::faint());

        // The three facets, each showing its active value with a count of what
        // it leaves — or a muted "all" when it is not narrowing anything.
        let mut spans = vec![Span::raw(" ")];
        for (n, &facet) in Facet::ALL.iter().enumerate() {
            if n > 0 {
                spans.push(Span::raw("   "));
            }
            spans.push(key(facet.key()));
            spans.push(label(facet.label()));
            match self.filter_for(facet) {
                Some(value) => {
                    spans.push(facet_value_span(facet, value));
                    if let Some(c) = self.facet_count(facet) {
                        spans.push(Span::styled(format!(" {c}"), theme::faint()));
                    }
                }
                None => spans.push(Span::styled("all", theme::muted())),
            }
        }
        if self.any_filter() {
            spans.push(Span::raw("   "));
            spans.push(key('x'));
            spans.push(label("clear"));
        }
        frame.render_widget(Paragraph::new(Line::from(spans)), area);
    }

    /// The facet pop-over: a narrow line you type into and a menu of the values
    /// present, each with the count picking it would leave. It floats over the
    /// results rather than replacing them, so the list you are carving stays in
    /// view — and a search that returned eighty authors is one substring away
    /// from the one you want, not eighty presses of a cycle key.
    fn render_picker(&self, frame: &mut Frame) {
        let Some(picker) = &self.picker else {
            return;
        };
        let facet = picker.facet;
        let shown = picker.shown();

        // The "all" row plus one per surviving option, capped so the overlay
        // never grows past a comfortable slice of the screen.
        let want_rows = shown.len() + 1;
        let screen = frame.area();
        let max_list = (screen.height.saturating_sub(9)).clamp(3, 16) as usize;
        let list_rows = want_rows.min(max_list);
        // input(1) + rule(1) + list + footer(1), plus the border's two rows.
        let height = (list_rows as u16 + 5).min(screen.height.saturating_sub(2));
        let width = 52u16.min(screen.width.saturating_sub(4));
        let area = centered(screen, width, height);

        frame.render_widget(Clear, area);
        let block = Block::bordered()
            .border_type(BorderType::Rounded)
            .border_style(Style::new().fg(theme::ACCENT))
            .style(Style::new().bg(theme::BG_ALT))
            .title(Span::styled(
                format!(" filter · {} ", facet.label()),
                Style::new().fg(theme::ACCENT).add_modifier(Modifier::BOLD),
            ));
        let inner = block.inner(area);
        frame.render_widget(block, area);

        let rows = Layout::vertical([
            Constraint::Length(1), // the type-to-narrow line
            Constraint::Length(1), // a faint rule
            Constraint::Min(1),    // the menu
            Constraint::Length(1), // the key legend
        ])
        .split(inner);

        // The narrow line, with a live "n of m" once it is doing anything.
        let mut top = vec![Span::styled(
            "",
            Style::new().fg(theme::ACCENT).add_modifier(Modifier::BOLD),
        )];
        if picker.query.is_empty() {
            top.push(Span::styled("type to narrow", theme::faint()));
        } else {
            top.push(Span::styled(picker.query.clone(), theme::text()));
            top.push(Span::styled("", theme::accent()));
        }
        let mut top_line = Paragraph::new(Line::from(top));
        if !picker.query.is_empty() {
            let count = Line::from(Span::styled(
                format!("{} of {} ", shown.len(), picker.options.len()),
                theme::faint(),
            ));
            frame.render_widget(Paragraph::new(count).alignment(Alignment::Right), rows[0]);
        }
        top_line = top_line.style(Style::new().bg(theme::BG_ALT));
        frame.render_widget(top_line, rows[0]);
        frame.render_widget(
            Paragraph::new("".repeat(rows[1].width as usize)).style(theme::faint()),
            rows[1],
        );

        // Keep the highlight in view by scrolling the menu under it.
        let cap = rows[2].height as usize;
        let total = shown.len() + 1;
        let offset = if picker.cursor >= cap {
            (picker.cursor - cap + 1).min(total.saturating_sub(cap))
        } else {
            0
        };

        let active = self.filter_for(facet);
        let mut lines: Vec<Line> = Vec::new();
        for row in offset..(offset + cap).min(total) {
            let selected = row == picker.cursor;
            let gutter = if selected {
                Span::styled(theme::CURSOR, theme::accent())
            } else {
                Span::raw("  ")
            };
            let mut spans = vec![gutter];
            if row == 0 {
                // The clearing row. It carries a mark when nothing is filtered,
                // so "all" reads as the current state and not just an option.
                let on = active.is_none();
                spans.push(Span::styled(
                    if on { "" } else { "  " },
                    theme::accent(),
                ));
                spans.push(Span::styled(
                    "all",
                    if on {
                        theme::text().add_modifier(Modifier::BOLD)
                    } else {
                        theme::muted()
                    },
                ));
                spans.push(Span::styled("  clear filter", theme::faint()));
            } else {
                let (value, count) = shown[row - 1];
                let on = active.is_some_and(|a| a.eq_ignore_ascii_case(value));
                spans.push(Span::styled(if on { "" } else { "  " }, theme::accent()));
                spans.push(facet_value_span(facet, value));
                spans.push(Span::styled(format!("  {count}"), theme::faint()));
            }
            let mut line = Line::from(spans);
            if selected {
                line = line.style(theme::selected_row());
            }
            lines.push(line);
        }
        frame.render_widget(Paragraph::new(lines), rows[2]);

        let legend = |k: &str, l: &str| {
            [
                Span::styled(
                    format!("{k} "),
                    theme::accent().add_modifier(Modifier::BOLD),
                ),
                Span::styled(format!("{l}   "), theme::faint()),
            ]
        };
        let footer: Vec<Span> = [
            legend("", "choose"),
            legend("↑↓", "move"),
            legend("", "facet"),
            legend("esc", "close"),
        ]
        .into_iter()
        .flatten()
        .collect();
        frame.render_widget(Paragraph::new(Line::from(footer)), rows[3]);
    }

    /// The sort menu: the orders the list can take, the active one marked, and
    /// a direction caret on the highlighted row that `←`/`→` flips. Small and
    /// fixed — five keys, no typing — so it needs neither a search line nor
    /// scrolling, just the list and its legend.
    fn render_sort_menu(&self, frame: &mut Frame) {
        let Some(menu) = &self.sort_menu else {
            return;
        };
        let screen = frame.area();
        // Border(2) + the five orders + the legend row.
        let height = (Sort::CYCLE.len() as u16 + 3).min(screen.height.saturating_sub(2));
        let width = 42u16.min(screen.width.saturating_sub(4));
        let area = centered(screen, width, height);

        frame.render_widget(Clear, area);
        let block = Block::bordered()
            .border_type(BorderType::Rounded)
            .border_style(Style::new().fg(theme::ACCENT))
            .style(Style::new().bg(theme::BG_ALT))
            .title(Span::styled(
                " sort by ",
                Style::new().fg(theme::ACCENT).add_modifier(Modifier::BOLD),
            ));
        let inner = block.inner(area);
        frame.render_widget(block, area);

        let rows = Layout::vertical([Constraint::Min(1), Constraint::Length(1)]).split(inner);

        let amber = Style::new().fg(theme::AMBER);
        let mut lines: Vec<Line> = Vec::new();
        for (i, &order) in Sort::CYCLE.iter().enumerate() {
            let selected = i == menu.cursor;
            let active = order == self.sort;
            let gutter = if selected {
                Span::styled(theme::CURSOR, theme::accent())
            } else {
                Span::raw("  ")
            };
            // A dot on the order the list is arranged by right now.
            let mark = Span::styled(if active { "" } else { "  " }, theme::accent());
            let label = Span::styled(
                order.label(self.tab).to_string(),
                if selected || active {
                    theme::text().add_modifier(Modifier::BOLD)
                } else {
                    theme::muted()
                },
            );
            // The caret rides the highlighted row (the direction Enter would
            // apply) and the active row (how it is sorted now); Relevance, the
            // mirror's own order, shows none.
            let caret = if order == Sort::Relevance {
                ""
            } else if selected {
                if menu.desc { "" } else { "" }
            } else if active {
                if self.sort_desc { "" } else { "" }
            } else {
                ""
            };
            let mut line = Line::from(vec![gutter, mark, label, Span::styled(caret, amber)]);
            if selected {
                line = line.style(theme::selected_row());
            }
            lines.push(line);
        }
        frame.render_widget(Paragraph::new(lines), rows[0]);

        let legend = |k: &str, l: &str| {
            [
                Span::styled(format!("{k} "), theme::accent().add_modifier(Modifier::BOLD)),
                Span::styled(format!("{l}  "), theme::faint()),
            ]
        };
        let footer: Vec<Span> = [
            legend("", "sort"),
            legend("↑↓", "move"),
            legend("←→", "dir"),
            legend("esc", "close"),
        ]
        .into_iter()
        .flatten()
        .collect();
        frame.render_widget(Paragraph::new(Line::from(footer)), rows[1]);
    }

    /// The Library tab's control strip: the sort on the right, and on the left
    /// a one-line account of the shelf — how many books, how much disk, and the
    /// handful of formats they are in — so the tab answers "what have I got"
    /// before anyone scrolls. Each format word wears its own hue, the same one
    /// the chips and the search results use.
    fn render_library_strip(&self, frame: &mut Frame, area: Rect) {
        if area.height == 0 {
            return;
        }

        // Right: the sort, and the filter count when a filter is hiding books.
        let mut right = self.sort_indicator();
        if !self.filter.trim().is_empty() {
            right.push(Span::styled("     ", theme::faint()));
            right.push(Span::styled(
                format!("{} of {} shown ", self.shown.len(), self.library.len()),
                Style::new().fg(theme::AMBER).add_modifier(Modifier::BOLD),
            ));
        } else {
            right.push(Span::raw(" "));
        }
        frame.render_widget(
            Paragraph::new(Line::from(right)).alignment(Alignment::Right),
            area,
        );

        // Left: the count, the total on disk, then the format breakdown.
        let count = self.library.len();
        let total: u64 = self.library.iter().map(|e| e.size).sum();
        let mut spans = vec![
            Span::raw(" "),
            Span::styled(
                format!("{count} book{}", if count == 1 { "" } else { "s" }),
                theme::muted(),
            ),
        ];
        if total > 0 {
            spans.push(Span::styled(format!("  ·  {}", human_bytes(total)), theme::faint()));
        }
        for (ext, n) in self.format_breakdown().into_iter().take(4) {
            spans.push(Span::styled("    ", theme::faint()));
            spans.push(Span::styled(format!("{n} "), theme::faint()));
            spans.push(Span::styled(ext.clone(), Style::new().fg(theme::format_color(&ext))));
        }
        frame.render_widget(Paragraph::new(Line::from(spans)), area);
    }

    /// The library's formats, most common first, for the summary strip.
    fn format_breakdown(&self) -> Vec<(String, usize)> {
        let mut counts: Vec<(String, usize)> = Vec::new();
        for entry in &self.library {
            let ext = entry.ext().to_ascii_lowercase();
            if ext.is_empty() {
                continue;
            }
            match counts.iter_mut().find(|(name, _)| *name == ext) {
                Some((_, n)) => *n += 1,
                None => counts.push((ext, 1)),
            }
        }
        counts.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
        counts
    }

    /// The tab bar and the text box under it.
    ///
    /// The two tabs are drawn as the box's title so they cost no rows of their
    /// own — on an eighty by twenty-four terminal every line spent on chrome is
    /// a line of results not shown.
    fn render_input(&self, frame: &mut Frame, area: Rect) {
        let editing = self.mode == Mode::Editing;
        // The box border lights up in the accent while you type, and rests at
        // faint otherwise — a quiet cue for where the keyboard is going.
        let border = if editing {
            theme::ACCENT
        } else {
            theme::FAINT
        };

        let block = Block::bordered()
            .border_type(BorderType::Rounded)
            .border_style(Style::new().fg(border))
            .title(Line::from(self.tab_chips()))
            .title_top(
                Line::from(vec![
                    Span::styled("", match self.tab {
                        // A green dot when a mirror is answering, amber while we
                        // are still looking — status you can read at a glance.
                        Tab::Search if !self.mirrors.is_empty() => theme::accent(),
                        Tab::Search => Style::new().fg(theme::AMBER),
                        Tab::Library | Tab::Settings => theme::accent(),
                    }),
                    Span::styled(
                        match self.tab {
                            Tab::Search => format!("{} ", self.mirror_label),
                            // The mirror is irrelevant to books already on disk.
                            Tab::Library => "on this machine ".to_string(),
                            Tab::Settings => String::new(),
                        },
                        theme::muted(),
                    ),
                ])
                .right_aligned(),
            );

        let inner = block.inner(area);
        frame.render_widget(block, area);

        let prompt = Span::styled(
            if editing { "" } else { "  " },
            Style::new().fg(theme::ACCENT).add_modifier(Modifier::BOLD),
        );
        let text = if self.input().is_empty() && !editing {
            Span::styled(
                match self.tab {
                    Tab::Search => "press / to search Library Genesis",
                    Tab::Library => "press / to filter your books",
                    Tab::Settings => "",
                },
                theme::faint(),
            )
        } else {
            Span::styled(self.input().to_string(), theme::text())
        };
        frame.render_widget(Paragraph::new(Line::from(vec![prompt, text])), inner);

        if editing {
            // Place the real terminal cursor so it blinks in the right column,
            // past the two-cell "❯ " prompt.
            let offset: usize = 2 + self
                .input()
                .chars()
                .take(self.caret)
                .map(|c| crate::term::display_width(&c.to_string()))
                .sum::<usize>();
            frame.set_cursor_position((inner.x + offset as u16, inner.y));
        }
    }

    /// Reserve a slim scrollbar down the right edge of `area` when the list is
    /// taller than the rows on show, and return the area left for the list. A
    /// list that fits keeps the full width and gets no bar — the indicator only
    /// appears when there is somewhere else to be. The thumb rides in
    /// the accent over a faint track, and skips the header row so it lines up
    /// with the rows it is measuring.
    fn with_scrollbar(&self, frame: &mut Frame, area: Rect, len: usize, pos: usize) -> Rect {
        let rows = area.height.saturating_sub(1) as usize;
        if len <= rows || rows == 0 || area.width < 4 {
            return area;
        }
        let track = Rect {
            x: area.right() - 1,
            y: area.y + 1,
            width: 1,
            height: area.height - 1,
        };
        let mut state = ScrollbarState::new(len)
            .viewport_content_length(rows)
            .position(pos);
        let bar = Scrollbar::new(ScrollbarOrientation::VerticalRight)
            .begin_symbol(None)
            .end_symbol(None)
            .track_symbol(Some(""))
            .thumb_symbol("")
            .track_style(theme::faint())
            .thumb_style(theme::accent());
        frame.render_stateful_widget(bar, track, &mut state);
        Rect {
            width: area.width - 1,
            ..area
        }
    }

    fn render_results(&mut self, frame: &mut Frame, area: Rect) {
        if self.visible.is_empty() {
            self.render_empty(frame, area);
            return;
        }
        let area = self.with_scrollbar(
            frame,
            area,
            self.visible.len(),
            self.table.selected().unwrap_or(0),
        );

        // Titles carry the screen, so they are the last thing to lose room and
        // never the first: the trimmable columns fall away as the list narrows,
        // widest and least essential going soonest.
        let w = area.width;
        let show_year = w >= 56;
        let show_lang = w >= 84;
        let show_status = w >= 98;

        let mut head = vec![Cell::from(""), Cell::from("TITLE"), Cell::from("AUTHOR")];
        if show_year {
            head.push(Cell::from("YEAR"));
        }
        if show_lang {
            head.push(Cell::from("LANGUAGE"));
        }
        head.push(Cell::from("SIZE"));
        head.push(Cell::from("FMT"));
        if show_status {
            head.push(Cell::from("STATUS"));
        }
        let header = Row::new(head).style(theme::header()).height(1);

        // Titles carry the information; authors repeat. Weight the room so the
        // title always wins the slack the fixed columns leave behind.
        let mut widths = vec![Constraint::Length(1), Constraint::Fill(6), Constraint::Fill(2)];
        if show_year {
            widths.push(Constraint::Length(4));
        }
        if show_lang {
            widths.push(Constraint::Length(10));
        }
        widths.push(Constraint::Length(8)); // SIZE
        widths.push(Constraint::Length(6)); // FMT
        if show_status {
            widths.push(Constraint::Length(7)); // STATUS
        }
        // The width the title and author columns will actually get, so a row can
        // decide for itself whether it needs a second line — the highlight
        // gutter eats two cells on the left of every row.
        let gutter = crate::term::display_width(theme::CURSOR) as u16;
        let cols = Layout::horizontal(widths.clone())
            .spacing(1)
            .split(Rect::new(0, 0, area.width.saturating_sub(gutter), 1));
        let title_w = cols[1].width as usize;
        let author_w = cols[2].width as usize;

        let selected = self.table.selected();
        let rows: Vec<Row> = self
            .visible
            .iter()
            .enumerate()
            .filter_map(|(row, &i)| self.results.get(i).map(|b| (row, i, b)))
            .map(|(row, i, book)| {
                let marked = self.marked.get(i).copied().unwrap_or(false);
                let job = self.jobs.get(&book.md5);
                // A book already on the shelf — from any past session, not just
                // this one — is worth knowing before you download it again. It
                // yields to a mark (you are clearly about to act on it) and to
                // this session's own download state.
                let owned = job.is_none() && !marked && self.owned.contains(&book.md5);
                let (marker, marker_style) = match job {
                    Some(Job::Saved(_)) => ("", Style::new().fg(theme::SUCCESS)),
                    Some(Job::Failed(_)) => ("", Style::new().fg(theme::DANGER)),
                    Some(Job::Running { .. }) | Some(Job::Queued) => {
                        ("", Style::new().fg(theme::ACCENT))
                    }
                    None if marked => ("", Style::new().fg(theme::AMBER)),
                    None if owned => ("", Style::new().fg(theme::SUCCESS)),
                    None => (" ", Style::new()),
                };
                // The status column carries this session's download state, and
                // otherwise a quiet note that the book is already in the library.
                let (status_text, status_style) = if owned {
                    ("library".to_string(), Style::new().fg(theme::SUCCESS))
                } else {
                    (job_label(job), job_style(job))
                };

                let author = {
                    let all = book.authors_or_unknown();
                    all.split(';').next().unwrap_or(all).trim().to_string()
                };

                // The highlighted title goes bold; every title stays at full
                // strength, because the titles are what the screen is for.
                let title_style = if Some(row) == selected {
                    theme::text().add_modifier(Modifier::BOLD)
                } else {
                    theme::text()
                };
                // The selection wash replaces every background, so the chip
                // trades its solid for the same hue as bold text there.
                let chip = if Some(row) == selected {
                    Style::new()
                        .fg(theme::format_color(book.ext()))
                        .add_modifier(Modifier::BOLD)
                } else {
                    theme::format_chip(book.ext())
                };

                // Title and author each spill onto a second line only when they
                // outrun their column; a row that fits stays one line, so the
                // list keeps its density and spends the extra row only where a
                // long title would otherwise be cut.
                let title_lines = wrap_two(&book.title, title_w);
                let author_lines = wrap_two(&author, author_w);
                let row_h = title_lines.len().max(author_lines.len()) as u16;

                let mut cells = vec![
                    Cell::from(marker).style(marker_style),
                    Cell::from(as_text(title_lines)).style(title_style),
                    Cell::from(as_text(author_lines)).style(theme::muted()),
                ];
                if show_year {
                    cells.push(
                        Cell::from(book.year.clone().unwrap_or_default()).style(theme::faint()),
                    );
                }
                if show_lang {
                    cells.push(
                        Cell::from(book.language.clone().unwrap_or_default())
                            .style(Style::new().fg(theme::LANG)),
                    );
                }
                cells.push(Cell::from(book.size_human()).style(theme::muted()));
                cells.push(Cell::from(format!(" {} ", book.ext())).style(chip));
                if show_status {
                    cells.push(Cell::from(status_text).style(status_style));
                }
                // The zebra: alternate rows sit one step off the canvas, so a
                // wide row can be followed without a ruler.
                Row::new(cells).height(row_h).style(Style::new().bg(if row % 2 == 1 {
                    theme::BG_ALT
                } else {
                    theme::BG
                }))
            })
            .collect();

        let table = Table::new(rows, widths)
            .header(header)
            .column_spacing(1)
            .row_highlight_style(theme::selected_row())
            .highlight_symbol(Span::styled(
                theme::CURSOR,
                theme::accent().add_modifier(Modifier::BOLD),
            ));

        frame.render_stateful_widget(table, area, &mut self.table);
    }

    /// The results area before or between searches: the status, and once a
    /// mirror is up, a few words on how to begin. Centred rather than tucked in
    /// a corner, so an empty screen still looks composed.
    fn render_empty(&self, frame: &mut Frame, area: Rect) {
        // Results exist but the filters admit none of them — say which lever
        // to pull, not just "nothing here".
        if !self.results.is_empty() {
            let carved: Vec<String> = Facet::ALL
                .iter()
                .filter_map(|&f| self.filter_for(f).map(str::to_string))
                .collect();
            let lines = vec![
                Line::from(Span::styled(
                    format!(
                        "none of the {} results are {}",
                        self.results.len(),
                        carved.join(" + ")
                    ),
                    theme::muted(),
                )),
                Line::from(""),
                Line::from(vec![
                    Span::styled("x", theme::accent().add_modifier(Modifier::BOLD)),
                    Span::styled(" clears the filters   ", theme::faint()),
                    Span::styled("e l a", theme::accent().add_modifier(Modifier::BOLD)),
                    Span::styled(" adjust them", theme::faint()),
                ]),
            ];
            let block = area.inner(Margin {
                horizontal: 2,
                vertical: area.height.saturating_sub(lines.len() as u16) / 2,
            });
            frame.render_widget(Paragraph::new(lines).alignment(Alignment::Center), block);
            return;
        }

        let mut lines = vec![if self.busy {
            // A turning spinner beside the status says "working", where a
            // trailing ellipsis only ever sat still.
            Line::from(vec![
                Span::styled(format!("{} ", spinner_frame(self.spinner)), theme::accent()),
                Span::styled(self.status.clone(), theme::muted()),
            ])
        } else {
            Line::from(Span::styled(self.status.clone(), theme::muted()))
        }];
        if !self.busy && self.results.is_empty() && self.mode != Mode::Editing {
            lines.push(Line::from(""));
            lines.push(Line::from(vec![
                Span::styled("press ", theme::faint()),
                Span::styled("/", theme::accent().add_modifier(Modifier::BOLD)),
                Span::styled(" and type a title or author", theme::faint()),
            ]));
        }
        let block = area.inner(Margin {
            horizontal: 2,
            vertical: area.height.saturating_sub(lines.len() as u16) / 2,
        });
        frame.render_widget(
            Paragraph::new(lines).alignment(Alignment::Center),
            block,
        );
    }

    fn render_details(&mut self, frame: &mut Frame, area: Rect) {
        let block = Block::bordered()
            .border_type(BorderType::Rounded)
            .border_style(Style::new().fg(theme::FAINT));
        let whole = block.inner(area);
        frame.render_widget(block, area);

        // Split off a column for the picture when there is one coming.
        self.cover_area = None;
        let inner = if self.cover_visible() && whole.width > 30 {
            // Roughly two by three, given a character cell about twice as tall
            // as it is wide.
            let width = ((whole.height as u32 * 2 * 2 / 3) as u16).clamp(6, 16);
            let picture = Rect {
                x: whole.x,
                y: whole.y,
                width,
                height: whole.height,
            };
            self.render_cover(frame, picture);
            Rect {
                x: whole.x + width + 2,
                y: whole.y,
                width: whole.width.saturating_sub(width + 2),
                height: whole.height,
            }
        } else {
            whole
        };

        let Some(book) = self.selected().cloned() else {
            let hint = self
                .error
                .clone()
                .unwrap_or_else(|| "no selection".to_string());
            let style = if self.error.is_some() {
                Style::new().fg(theme::DANGER)
            } else {
                theme::faint()
            };
            frame.render_widget(
                Paragraph::new(hint).style(style).wrap(Wrap { trim: true }),
                inner,
            );
            return;
        };

        let mut facts: Vec<String> = Vec::new();
        if let Some(p) = book.publisher.as_deref().filter(|s| !s.is_empty()) {
            facts.push(p.to_string());
        }
        if let Some(y) = book.year.as_deref().filter(|s| !s.is_empty()) {
            facts.push(y.to_string());
        }
        if let Some(l) = book.language.as_deref().filter(|s| !s.is_empty()) {
            facts.push(l.to_string());
        }
        if let Some(p) = book.pages.as_deref().filter(|s| !s.is_empty() && *s != "0") {
            facts.push(format!("{p} pages"));
        }
        facts.push(book.size_human());

        let mut lines = vec![
            Line::from(Span::styled(
                book.title.clone(),
                theme::text().add_modifier(Modifier::BOLD),
            )),
            Line::from(Span::styled(
                book.authors_or_unknown().to_string(),
                theme::muted(),
            )),
            Line::from(vec![
                Span::styled("md5 ", theme::faint()),
                Span::styled(book.md5.clone(), theme::faint()),
            ]),
        ];
        let facts = facts.join("  ·  ");
        if !facts.trim().is_empty() {
            lines.insert(2, Line::from(Span::styled(facts, theme::muted())));
        }

        // A blank line, then the most urgent thing about the selection, where
        // the eye lands: an error, else this file's download state.
        lines.push(Line::from(""));
        if let Some(error) = &self.error {
            lines.push(Line::from(Span::styled(
                error.clone(),
                Style::new().fg(theme::DANGER),
            )));
        } else {
            match self.jobs.get(&book.md5) {
                Some(Job::Saved(name)) => lines.push(Line::from(Span::styled(
                    format!("✓ saved as {name} — MD5 verified"),
                    Style::new().fg(theme::SUCCESS),
                ))),
                Some(Job::Failed(e)) => lines.push(Line::from(Span::styled(
                    format!("{e}"),
                    Style::new().fg(theme::DANGER),
                ))),
                Some(Job::Running {
                    done,
                    total,
                    started,
                }) => lines.push(progress_line(*done, *total, *started, 24)),
                Some(Job::Queued) => lines.push(Line::from(vec![
                    Span::styled(spinner_frame(self.spinner), theme::accent()),
                    Span::styled(" queued", theme::faint()),
                ])),
                None => lines.push(Line::from(vec![
                    Span::styled("⏎ download → ", theme::accent()),
                    Span::styled(self.settings.dest_dir.display().to_string(), theme::faint()),
                ])),
            }
        }

        frame.render_widget(Paragraph::new(lines).wrap(Wrap { trim: true }), inner);
    }

    /// Draw the cover, or reserve the space it is about to occupy.
    ///
    /// For the two pixel protocols this only records where the picture goes;
    /// the escape sequence that actually places it is written after the frame,
    /// because it lives outside ratatui's buffer. Half-block art, being text,
    /// is drawn here like anything else.
    fn render_cover(&mut self, frame: &mut Frame, area: Rect) {
        if area.width == 0 || area.height == 0 {
            return;
        }
        self.cover_area = Some(area);

        match self.covers.get(self.focused_md5().as_deref().unwrap_or("")) {
            Some(Slot::Looking) => {
                // The spinner sits on the row that a cover's centre would fall
                // on, so the frame reads as "loading" rather than empty.
                let middle = Rect {
                    x: area.x,
                    y: area.y + area.height / 2,
                    width: area.width,
                    height: 1,
                };
                frame.render_widget(
                    Paragraph::new(spinner_frame(self.spinner))
                        .style(theme::faint())
                        .alignment(Alignment::Center),
                    middle,
                );
            }
            Some(Slot::Ready(art)) if !self.protocol.is_pixels() => {
                let Some(image) = &art.pixels else {
                    return;
                };
                let rows = graphics::half_blocks(image, area.width, area.height);
                let lines: Vec<Line> = rows
                    .iter()
                    .map(|row| {
                        Line::from(
                            row.iter()
                                .map(|(upper, lower)| {
                                    Span::styled(
                                        graphics::UPPER_HALF.to_string(),
                                        Style::new()
                                            .fg(Color::Rgb(upper.0, upper.1, upper.2))
                                            .bg(Color::Rgb(lower.0, lower.1, lower.2)),
                                    )
                                })
                                .collect::<Vec<_>>(),
                        )
                    })
                    .collect();
                frame.render_widget(Paragraph::new(lines), area);
            }
            // Pixels are placed after the draw; leave the cells blank so the
            // image shows through.
            _ => {}
        }
    }

    /// Every book downloaded so far, filtered by whatever is in the box.
    fn render_library(&mut self, frame: &mut Frame, area: Rect) {
        if self.shown.is_empty() {
            self.render_empty_library(frame, area);
            return;
        }
        let area = self.with_scrollbar(
            frame,
            area,
            self.shown.len(),
            self.library_table.selected().unwrap_or(0),
        );
        let now = history::now();

        // The shelf trims the same way the results do: title and author hold on,
        // the date and size step aside when the column runs short.
        let w = area.width;
        let show_added = w >= 84;
        let show_size = w >= 60;

        let mut head = vec![Cell::from(""), Cell::from("TITLE"), Cell::from("AUTHOR")];
        if show_added {
            head.push(Cell::from("ADDED"));
        }
        if show_size {
            head.push(Cell::from("SIZE"));
        }
        head.push(Cell::from("FMT"));
        let header = Row::new(head).style(theme::header()).height(1);

        let mut widths = vec![Constraint::Length(1), Constraint::Fill(6), Constraint::Fill(2)];
        if show_added {
            widths.push(Constraint::Length(12));
        }
        if show_size {
            widths.push(Constraint::Length(9));
        }
        widths.push(Constraint::Length(6)); // FMT
        // The real title and author widths, so a shelf row wraps to a second
        // line only when its own title or author overruns the column.
        let gutter = crate::term::display_width(theme::CURSOR) as u16;
        let cols = Layout::horizontal(widths.clone())
            .spacing(1)
            .split(Rect::new(0, 0, area.width.saturating_sub(gutter), 1));
        let title_w = cols[1].width as usize;
        let author_w = cols[2].width as usize;

        let selected = self.library_table.selected();
        let rows: Vec<Row> = self
            .shown
            .iter()
            .enumerate()
            .filter_map(|(row, &i)| self.library.get(i).map(|e| (row, e)))
            .map(|(row, entry)| {
                let present = entry.present();
                let here = Some(row) == selected;
                // A present book leads with a small dot; a missing one with a
                // warning, and everything about its row reads as unavailable.
                let (marker, marker_style) = if present {
                    ("", Style::new().fg(theme::SUCCESS))
                } else {
                    ("!", Style::new().fg(theme::DANGER))
                };
                let title_style = if !present {
                    theme::faint()
                } else if here {
                    theme::text().add_modifier(Modifier::BOLD)
                } else {
                    theme::text()
                };
                let title = if present {
                    entry.title.clone()
                } else {
                    format!("{} (missing)", entry.title)
                };

                let chip = if !present {
                    theme::faint()
                } else if here {
                    Style::new()
                        .fg(theme::format_color(entry.ext()))
                        .add_modifier(Modifier::BOLD)
                } else {
                    theme::format_chip(entry.ext())
                };

                let author = entry.first_author();
                let title_lines = wrap_two(&title, title_w);
                let author_lines = wrap_two(&author, author_w);
                let row_h = title_lines.len().max(author_lines.len()) as u16;

                let mut cells = vec![
                    Cell::from(marker).style(marker_style),
                    Cell::from(as_text(title_lines)).style(title_style),
                    Cell::from(as_text(author_lines)).style(theme::muted()),
                ];
                if show_added {
                    cells.push(Cell::from(history::when(entry.at, now)).style(theme::muted()));
                }
                if show_size {
                    cells.push(Cell::from(human_bytes(entry.size)).style(theme::faint()));
                }
                cells.push(Cell::from(format!(" {} ", entry.ext())).style(chip));
                Row::new(cells).height(row_h).style(Style::new().bg(if row % 2 == 1 {
                    theme::BG_ALT
                } else {
                    theme::BG
                }))
            })
            .collect();

        let table = Table::new(rows, widths)
            .header(header)
            .column_spacing(1)
            .row_highlight_style(theme::selected_row())
            .highlight_symbol(Span::styled(
                theme::CURSOR,
                theme::accent().add_modifier(Modifier::BOLD),
            ));

        frame.render_stateful_widget(table, area, &mut self.library_table);
    }

    /// An empty library and an over-narrow filter are different problems and
    /// deserve different words; both are centred so the tab looks intended
    /// rather than broken.
    fn render_empty_library(&self, frame: &mut Frame, area: Rect) {
        let lines: Vec<Line> = if self.library.is_empty() {
            vec![
                Line::from(Span::styled(
                    "Your library is empty",
                    theme::text().add_modifier(Modifier::BOLD),
                )),
                Line::from(""),
                Line::from(Span::styled(
                    "Books you download land here and stay between sessions.",
                    theme::muted(),
                )),
                Line::from(vec![
                    Span::styled("Press ", theme::faint()),
                    Span::styled("Tab", theme::accent()),
                    Span::styled(" to go and find one.", theme::faint()),
                ]),
            ]
        } else {
            vec![
                Line::from(Span::styled(
                    format!("No book matches “{}", self.filter.trim()),
                    theme::muted(),
                )),
                Line::from(""),
                Line::from(vec![
                    Span::styled("^u", theme::accent()),
                    Span::styled(" clears the filter", theme::faint()),
                ]),
            ]
        };
        let block = area.inner(Margin {
            horizontal: 2,
            vertical: area.height.saturating_sub(lines.len() as u16) / 2,
        });
        frame.render_widget(
            Paragraph::new(lines).alignment(Alignment::Center),
            block,
        );
    }

    /// Where the highlighted book went, and whether it is still there.
    fn render_library_details(&mut self, frame: &mut Frame, area: Rect) {
        let block = Block::bordered()
            .border_type(BorderType::Rounded)
            .border_style(Style::new().fg(theme::FAINT));
        let whole = block.inner(area);
        frame.render_widget(block, area);

        // A cover column on the left when the book has one to show, exactly as
        // the search detail strip does — the library reads its cover out of the
        // file rather than off a mirror, but the layout is the same.
        self.cover_area = None;
        let inner = if self.cover_visible() && whole.width > 30 {
            let width = ((whole.height as u32 * 2 * 2 / 3) as u16).clamp(6, 16);
            let picture = Rect {
                x: whole.x,
                y: whole.y,
                width,
                height: whole.height,
            };
            self.render_cover(frame, picture);
            Rect {
                x: whole.x + width + 2,
                y: whole.y,
                width: whole.width.saturating_sub(width + 2),
                height: whole.height,
            }
        } else {
            whole
        };

        let Some(entry) = self.selected_entry() else {
            let hint = self
                .error
                .clone()
                .unwrap_or_else(|| "⏎ opens a book in your reader".to_string());
            frame.render_widget(
                Paragraph::new(hint)
                    .style(if self.error.is_some() {
                        Style::new().fg(theme::DANGER)
                    } else {
                        theme::faint()
                    })
                    .wrap(Wrap { trim: true }),
                inner,
            );
            return;
        };

        let verified = if entry.verified {
            Span::styled("✓ MD5 verified", Style::new().fg(theme::SUCCESS))
        } else {
            Span::styled("unverified", theme::faint())
        };
        let mut lines = vec![
            Line::from(Span::styled(
                entry.title.clone(),
                theme::text().add_modifier(Modifier::BOLD),
            )),
            Line::from(Span::styled(
                entry.authors.clone().unwrap_or_default(),
                theme::muted(),
            )),
            Line::from(Span::styled(entry.path.display().to_string(), theme::faint())),
            Line::from(vec![
                Span::styled(format!(" {} ", entry.ext()), theme::format_chip(entry.ext())),
                Span::styled(
                    format!(
                        "  {}  ·  {}  ·  ",
                        human_bytes(entry.size),
                        history::timestamp(entry.at),
                    ),
                    theme::muted(),
                ),
                verified,
            ]),
            Line::from(""),
        ];

        if let Some(error) = &self.error {
            lines.push(Line::from(Span::styled(
                error.clone(),
                Style::new().fg(theme::DANGER),
            )));
        } else if !entry.present() {
            lines.push(Line::from(Span::styled(
                "⚠ the file is no longer there — press d to forget it",
                Style::new().fg(theme::DANGER),
            )));
        } else {
            lines.push(Line::from(vec![
                Span::styled("⏎ open", theme::accent()),
                Span::styled("   f reveal in file manager", theme::faint()),
            ]));
        }

        frame.render_widget(Paragraph::new(lines).wrap(Wrap { trim: true }), inner);
    }

    /// The row of tab chips shown as the box title on every tab: the active one
    /// a solid accent chip, the rest faint.
    fn tab_chips(&self) -> Vec<Span<'static>> {
        fn chip(label: &str, count: Option<usize>, active: bool) -> Span<'static> {
            let text = match count {
                Some(n) => format!("  {label} {n}  "),
                None => format!("  {label}  "),
            };
            Span::styled(
                text,
                if active {
                    // Colour and reverse together, so the active chip is
                    // unmistakable even without truecolour.
                    Style::new()
                        .fg(Color::Rgb(18, 24, 28))
                        .bg(theme::ACCENT)
                        .add_modifier(Modifier::BOLD)
                } else {
                    theme::faint()
                },
            )
        }
        vec![
            chip("1 SEARCH", None, self.tab == Tab::Search),
            Span::raw(" "),
            chip("2 LIBRARY", Some(self.library.len()), self.tab == Tab::Library),
            Span::raw(" "),
            chip("3 SETTINGS", None, self.tab == Tab::Settings),
        ]
    }

    /// The Settings tab: a list of every config key with its current value, the
    /// highlighted field's help beneath, and — while one is being changed — an
    /// inline editor or an expanded sub-list.
    fn render_settings(&self, frame: &mut Frame, area: Rect) {
        let rows = Layout::vertical([
            Constraint::Min(3),     // the form
            Constraint::Length(2),  // help / error for the current field
            Constraint::Length(1),  // key hints
        ])
        .split(area);

        let block = Block::bordered()
            .border_type(BorderType::Rounded)
            .border_style(Style::new().fg(theme::FAINT))
            .title(Line::from(self.tab_chips()));
        let inner = block.inner(rows[0]);
        frame.render_widget(block, rows[0]);

        let editing_line = self.form.editing.is_some();
        let mut lines: Vec<Line> = vec![Line::from("")];
        let mut active_line = 0usize;

        for (i, &field) in Field::ALL.iter().enumerate() {
            let selected = i == self.form.selected;
            if selected {
                active_line = lines.len();
            }
            let marker = if selected { "" } else { "   " };
            let label_style = if selected {
                theme::text().add_modifier(Modifier::BOLD)
            } else {
                theme::muted()
            };
            let label = Span::styled(format!("{marker}{:<20}", field.label()), label_style);

            if selected && editing_line && matches!(field.kind(), FieldKind::Line) {
                let mut spans = vec![label];
                spans.extend(self.edit_spans());
                lines.push(Line::from(spans));
            } else {
                let value_style = if selected {
                    theme::accent()
                } else {
                    theme::faint()
                };
                lines.push(Line::from(vec![
                    label,
                    Span::styled(self.field_display(field), value_style),
                ]));
            }

            // The collections and mirror lists expand under their row while they
            // hold focus, each with its own cursor.
            if selected && self.form.sub == SubFocus::Topics && field == Field::Topics {
                let chosen = self.topics_effective();
                for (ti, &topic) in Topic::ALL.iter().enumerate() {
                    if ti == self.form.topic_row {
                        active_line = lines.len();
                    }
                    let cursor = if ti == self.form.topic_row { "" } else { "   " };
                    let mark = if chosen.contains(&topic) { "[x] " } else { "[ ] " };
                    let style = if ti == self.form.topic_row {
                        theme::text()
                    } else {
                        theme::faint()
                    };
                    lines.push(Line::from(Span::styled(
                        format!("     {cursor}{mark}{}", topic.name()),
                        style,
                    )));
                }
            }
            if selected && self.form.sub == SubFocus::Mirrors && field == Field::Mirrors {
                if self.config.mirrors.is_empty() && !editing_line {
                    lines.push(Line::from(Span::styled(
                        "        (none — press a to add one)",
                        theme::faint(),
                    )));
                }
                for (mi, mirror) in self.config.mirrors.iter().enumerate() {
                    if mi == self.form.mirror_row {
                        active_line = lines.len();
                    }
                    let cursor = if mi == self.form.mirror_row { "" } else { "   " };
                    let style = if mi == self.form.mirror_row {
                        theme::text()
                    } else {
                        theme::faint()
                    };
                    lines.push(Line::from(Span::styled(
                        format!("     {cursor}{mirror}"),
                        style,
                    )));
                }
                if editing_line {
                    active_line = lines.len();
                    let mut spans = vec![Span::styled("        ", theme::faint())];
                    spans.extend(self.edit_spans());
                    lines.push(Line::from(spans));
                }
            }
        }

        let viewport = usize::from(inner.height);
        let scroll = active_line
            .saturating_add(1)
            .saturating_sub(viewport)
            .min(usize::from(u16::MAX)) as u16;
        frame.render_widget(Paragraph::new(lines).scroll((scroll, 0)), inner);

        // The current field's help, or the last validation error in its place.
        let field = self.current_field();
        let help = if let Some(err) = &self.form.error {
            Line::from(Span::styled(
                format!("{err}"),
                Style::new().fg(theme::DANGER),
            ))
        } else {
            let mut spans = vec![Span::styled(format!(" {}", field.help()), theme::muted())];
            if field.deferred() {
                spans.push(Span::styled("  (applies next launch)", theme::faint()));
            }
            Line::from(spans)
        };
        frame.render_widget(Paragraph::new(help), rows[1]);

        self.render_hints(frame, rows[2]);
    }

    /// The spans for the line currently being typed, with a reversed cell at the
    /// caret so it reads as a cursor.
    fn edit_spans(&self) -> Vec<Span<'static>> {
        let Some(edit) = &self.form.editing else {
            return Vec::new();
        };
        let chars: Vec<char> = edit.buffer.chars().collect();
        let mut spans = Vec::new();
        for (i, c) in chars.iter().enumerate() {
            let style = if i == edit.caret {
                theme::text().add_modifier(Modifier::REVERSED)
            } else {
                theme::text()
            };
            spans.push(Span::styled(c.to_string(), style));
        }
        if edit.caret >= chars.len() {
            spans.push(Span::styled(
                " ",
                theme::text().add_modifier(Modifier::REVERSED),
            ));
        }
        spans
    }

    /// The collections currently in force: the config's set, or the default.
    fn topics_effective(&self) -> Vec<Topic> {
        self.config
            .topics
            .clone()
            .unwrap_or_else(|| vec![Topic::Libgen, Topic::Fiction])
    }

    fn render_hints(&self, frame: &mut Frame, area: Rect) {
        // Each hint is a (key, label) pair; the key rides in the accent, the
        // label sits faint beneath it, so the bar reads as a legend rather than
        // a grey sentence. `tab` leads every line — it is the one key that gets
        // you out of wherever you are.
        let hints: &[(&str, &str)] = match (self.mode, self.tab) {
            (Mode::Help, _) => &[("", "any key to close")],
            (Mode::Editing, Tab::Search) => &[
                ("tab", "library"),
                ("", "search"),
                ("esc", "done"),
                ("^u", "clear"),
                ("", "try author: title: ext:"),
            ],
            (Mode::Editing, Tab::Library) => &[
                ("tab", "search"),
                ("esc", "done"),
                ("^u", "clear"),
                ("", "filtering as you type"),
            ],
            (Mode::Browsing, Tab::Search) => &[
                ("tab", "library"),
                ("↑↓", "move"),
                ("space", "mark"),
                ("", "download"),
                ("e", "format"),
                ("l", "lang"),
                ("a", "author"),
                ("s", "sort"),
                ("/", "search"),
                ("?", "help"),
                ("q", "quit"),
            ],
            (Mode::Browsing, Tab::Library) => &[
                ("tab", "search"),
                ("↑↓", "move"),
                ("", "open"),
                ("f", "reveal"),
                ("s", "sort"),
                ("/", "filter"),
                ("d", "forget"),
                ("?", "help"),
                ("q", "quit"),
            ],
            // The Settings tab stays in `Browsing`; its state lives on the form,
            // so the hints follow what the form is doing.
            (_, Tab::Settings) if self.form.editing.is_some() => {
                &[("", "save"), ("esc", "cancel"), ("^u", "clear")]
            }
            (_, Tab::Settings) if self.form.sub == SubFocus::Topics => {
                &[("↑↓", "move"), ("space", "toggle"), ("esc", "done")]
            }
            (_, Tab::Settings) if self.form.sub == SubFocus::Mirrors => {
                &[("↑↓", "move"), ("a", "add"), ("d", "delete"), ("esc", "done")]
            }
            (_, Tab::Settings) => &[
                ("tab", "search"),
                ("↑↓", "move"),
                ("", "edit"),
                ("space", "toggle"),
                ("?", "help"),
                ("q", "quit"),
            ],
        };

        let mut spans = vec![Span::raw(" ")];
        for (key, label) in hints {
            if !key.is_empty() {
                spans.push(Span::styled(
                    (*key).to_string(),
                    theme::accent().add_modifier(Modifier::BOLD),
                ));
                spans.push(Span::styled(format!(" {label}"), theme::muted()));
            } else {
                spans.push(Span::styled((*label).to_string(), theme::faint()));
            }
            spans.push(Span::styled("   ", theme::faint()));
        }
        frame.render_widget(Paragraph::new(Line::from(spans)), area);
    }

    fn render_help(&self, frame: &mut Frame) {
        // Grouped by tab, because which keys apply depends on where you are.
        let sections: [(&str, &[(&str, &str)]); 4] = [
            (
                "anywhere",
                &[
                    ("tab", "cycle Search · Library · Settings"),
                    ("1  2  3", "go straight to a tab"),
                    ("/  i", "type in the box"),
                    ("↑ ↓  k j", "move the selection"),
                    ("PgUp PgDn", "move ten at a time"),
                    ("g  G", "jump to first / last"),
                    ("s", "open the sort menu; S reverses in place"),
                    ("y", "copy the MD5 to the clipboard"),
                    ("?", "this help"),
                    ("q  esc", "quit"),
                    ("^c", "quit from anywhere"),
                ],
            ),
            (
                "search tab",
                &[
                    ("", "run the search, or download the selection"),
                    ("e  l  a", "filter by format / language / author"),
                    ("", "  a menu: type to narrow, ⏎ to choose"),
                    ("x", "clear every filter"),
                    ("space", "mark a result for batch download"),
                    ("A", "mark or unmark everything showing"),
                    ("o  f", "open a downloaded result / reveal it"),
                    ("r", "run the search again"),
                    ("m", "re-probe mirrors and pick a new one"),
                ],
            ),
            (
                "library tab",
                &[
                    ("⏎  o", "open the book in your reader"),
                    ("f", "show the file in the file manager"),
                    ("/", "filter by title, author or filename"),
                    ("d", "forget an entry (the file stays)"),
                    ("r", "re-read the library from disk"),
                ],
            ),
            (
                "settings tab",
                &[
                    ("↑ ↓", "move between settings"),
                    ("", "edit a value, or step into a list"),
                    ("space", "toggle a yes/no setting"),
                    ("", "  collections: space toggles, esc leaves"),
                    ("a  d", "mirrors: add a URL / delete the marked one"),
                    ("esc", "cancel an edit or leave a list"),
                    ("", "every change is saved as you make it"),
                ],
            ),
        ];

        // A section header sits in amber above its keys, with a blank line
        // before it (except the first) so the groups breathe.
        let section_title = |title: &str, first: bool| {
            let text = if first {
                title.to_uppercase()
            } else {
                format!("\n{}", title.to_uppercase())
            };
            Line::from(Span::styled(
                text,
                Style::new()
                    .fg(theme::AMBER)
                    .add_modifier(Modifier::BOLD),
            ))
        };
        let key_row = |keys: &str, what: &str| {
            Line::from(vec![
                Span::styled(format!("  {keys:<11}"), theme::accent()),
                Span::styled(what.to_string(), theme::muted()),
            ])
        };

        let lines: Vec<Line> = sections
            .iter()
            .enumerate()
            .flat_map(|(s, (title, keys))| {
                std::iter::once(section_title(title, s == 0))
                    .chain(keys.iter().map(|(k, what)| key_row(k, what)))
            })
            // The search box takes tags as well as words, and this is the only
            // place that says so.
            .chain(std::iter::once(section_title("search tags", false)))
            .chain(query::TAGS.iter().map(|(tag, what)| key_row(tag, what)))
            .collect();

        let width = 60u16.min(frame.area().width.saturating_sub(4));
        let height = (lines.len() as u16 + 2).min(frame.area().height.saturating_sub(2));
        let area = centered(frame.area(), width, height);

        frame.render_widget(Clear, area);
        let block = Block::bordered()
            .border_type(BorderType::Rounded)
            .border_style(Style::new().fg(theme::ACCENT))
            // One step off the canvas, so the overlay reads as a raised
            // surface rather than a hole cut in the screen.
            .style(Style::new().bg(theme::BG_ALT))
            .title(Span::styled(
                " tomesole · keys ",
                Style::new().fg(theme::ACCENT).add_modifier(Modifier::BOLD),
            ));
        let inner = block.inner(area);
        frame.render_widget(block, area);
        frame.render_widget(Paragraph::new(lines), inner);
    }
}

/// A centred rectangle of the given size.
fn centered(area: Rect, width: u16, height: u16) -> Rect {
    let x = area.x + (area.width.saturating_sub(width)) / 2;
    let y = area.y + (area.height.saturating_sub(height)) / 2;
    Rect {
        x,
        y,
        width: width.min(area.width),
        height: height.min(area.height),
    }
}

/// A facet's value dressed in its own colour, the same one it wears in the
/// results: a format as a solid chip, a language in its calm blue, an author in
/// plain bold text (clipped, since author strings run long). Used by both the
/// strip and the picker so a value looks the same wherever it is shown.
fn facet_value_span(facet: Facet, value: &str) -> Span<'static> {
    match facet {
        Facet::Format => Span::styled(format!(" {value} "), theme::format_chip(value)),
        Facet::Language => Span::styled(
            value.to_string(),
            Style::new().fg(theme::LANG).add_modifier(Modifier::BOLD),
        ),
        Facet::Author => Span::styled(
            clip(value, 30),
            theme::text().add_modifier(Modifier::BOLD),
        ),
    }
}

/// A run of lines as cell text, so a table cell can hold a wrapped title.
fn as_text(lines: Vec<String>) -> Text<'static> {
    Text::from(lines.into_iter().map(Line::from).collect::<Vec<Line>>())
}

/// Wrap `s` into at most two lines of `width` display cells, breaking on
/// spaces. A string that already fits comes back as a single line, so a table
/// row only grows to two lines when its own text would otherwise be cut; a
/// third line's worth spills onto the second and is clipped with an ellipsis.
fn wrap_two(s: &str, width: usize) -> Vec<String> {
    use crate::term::{display_width, truncate};
    if width == 0 || display_width(s) <= width {
        return vec![s.to_string()];
    }
    let mut line = String::new();
    let mut used = 0usize;
    let mut rest = String::new();
    let mut spilling = false;
    for word in s.split(' ') {
        if spilling {
            rest.push(' ');
            rest.push_str(word);
            continue;
        }
        let ww = display_width(word);
        if line.is_empty() && ww > width {
            // A single word wider than the whole line: hard-break it so the
            // overflow still has somewhere to land.
            for c in word.chars() {
                let cw = display_width(&c.to_string());
                if used + cw > width {
                    rest.push(c);
                } else {
                    line.push(c);
                    used += cw;
                }
            }
            spilling = true;
        } else if !line.is_empty() && used + 1 + ww > width {
            rest.push_str(word);
            spilling = true;
        } else {
            if !line.is_empty() {
                line.push(' ');
                used += 1;
            }
            line.push_str(word);
            used += ww;
        }
    }
    if rest.is_empty() {
        vec![line]
    } else {
        vec![line, truncate(&rest, width)]
    }
}

/// Shorten `s` to at most `max` characters, ending in an ellipsis when cut, so
/// a long author string cannot push a row off the edge of its box.
fn clip(s: &str, max: usize) -> String {
    if s.chars().count() <= max {
        return s.to_string();
    }
    let head: String = s.chars().take(max.saturating_sub(1)).collect();
    format!("{head}")
}

/// The first of several semicolon-separated authors, lowercased for sorting
/// and comparison. Empty when there is no author at all.
fn first_author_of(authors: Option<&str>) -> String {
    let all = authors.unwrap_or("");
    all.split(';').next().unwrap_or(all).trim().to_lowercase()
}

/// The leading four-ish digits of a year string as a number, zero when there
/// is nothing parseable — so undated books sink to one end rather than
/// scattering. Libgen years are ragged (`1965`, `1965-01`, `c. 1965`).
fn year_num(year: Option<&str>) -> u32 {
    let s = year.unwrap_or("");
    let digits: String = s
        .trim_start_matches(|c: char| !c.is_ascii_digit())
        .chars()
        .take_while(|c| c.is_ascii_digit())
        .collect();
    digits.parse().unwrap_or(0)
}

fn job_label(job: Option<&Job>) -> String {
    match job {
        Some(Job::Queued) => "queued".into(),
        Some(Job::Running { done, total, .. }) => match total {
            Some(t) if *t > 0 => format!("{:>3}%", (*done as f64 / *t as f64 * 100.0) as u32),
            _ => human_bytes(*done),
        },
        Some(Job::Saved(_)) => "saved".into(),
        Some(Job::Failed(_)) => "failed".into(),
        None => String::new(),
    }
}

fn job_style(job: Option<&Job>) -> Style {
    match job {
        Some(Job::Saved(_)) => Style::new().fg(theme::SUCCESS),
        Some(Job::Failed(_)) => Style::new().fg(theme::DANGER),
        Some(_) => Style::new().fg(theme::ACCENT),
        None => Style::new(),
    }
}

/// The frames of the small in-flight spinner, one braille cell each. Picked to
/// read as a smooth rotation at the few-frames-a-second the loop redraws at.
const SPINNER: [&str; 10] = ["", "", "", "", "", "", "", "", "", ""];

/// The spinner glyph for a given frame count.
fn spinner_frame(tick: usize) -> &'static str {
    SPINNER[tick % SPINNER.len()]
}

/// A fractional-block meter `width` cells wide. The fill is measured in
/// eighths of a cell and the boundary drawn with a partial block, so the bar
/// moves a step at a time rather than jumping a whole character — the extra
/// resolution is free and reads as far smoother.
fn meter(fraction: f64, width: usize) -> String {
    const PARTIAL: [char; 8] = [' ', '', '', '', '', '', '', ''];
    let eighths = (fraction.clamp(0.0, 1.0) * (width * 8) as f64).round() as usize;
    let full = eighths / 8;
    let rem = eighths % 8;
    let mut bar = "".repeat(full.min(width));
    let mut used = full.min(width);
    if rem > 0 && used < width {
        bar.push(PARTIAL[rem]);
        used += 1;
    }
    bar.push_str(&"".repeat(width.saturating_sub(used)));
    bar
}

/// The download line for a detail pane: a fractional-block meter, the
/// transferred and total size, and — once enough has come down to judge one —
/// a live speed and estimate of the time left. The meter rides in the accent;
/// the figures beside it stay faint, so the bar is what the eye tracks.
fn progress_line(done: u64, total: Option<u64>, started: Instant, width: usize) -> Line<'static> {
    let secs = started.elapsed().as_secs_f64();
    // A speed judged in the first half-second swings wildly; wait for it.
    let speed = (secs > 0.5).then(|| done as f64 / secs);
    let rate = match speed {
        Some(bytes) if bytes >= 1.0 => format!("{}/s", human_bytes(bytes as u64)),
        _ => String::new(),
    };

    match total {
        Some(total) if total > 0 => {
            let fraction = done as f64 / total as f64;
            // Whole seconds left at the current average, once there is a rate.
            let eta = speed
                .filter(|s| *s > 0.0)
                .map(|s| ((total.saturating_sub(done)) as f64 / s) as u64)
                .map(|left| format!("  ·  {} left", short_duration(left)))
                .unwrap_or_default();
            let tail = format!(
                "  {} / {}{}{}",
                human_bytes(done),
                human_bytes(total),
                if rate.is_empty() {
                    String::new()
                } else {
                    format!("  ·  {rate}")
                },
                eta,
            );
            Line::from(vec![
                Span::styled(meter(fraction, width), theme::accent()),
                Span::styled(tail, theme::faint()),
            ])
        }
        // No total advertised: no bar to draw, just what has arrived so far.
        _ => {
            let tail = if rate.is_empty() {
                String::new()
            } else {
                format!("  ·  {rate}")
            };
            Line::from(vec![
                Span::styled(format!("downloading… {}", human_bytes(done)), theme::accent()),
                Span::styled(tail, theme::faint()),
            ])
        }
    }
}

/// A compact duration for an ETA: `45s`, `3m 20s`, `1h 05m`.
fn short_duration(secs: u64) -> String {
    match secs {
        0..=59 => format!("{secs}s"),
        60..=3599 => format!("{}m {:02}s", secs / 60, secs % 60),
        _ => format!("{}h {:02}m", secs / 3600, (secs % 3600) / 60),
    }
}

/// Put text on the system clipboard with an OSC 52 escape. Base64 is the
/// encoding the sequence mandates, and the crate already has an encoder for the
/// image protocols, so this borrows it rather than growing a dependency.
fn copy_to_clipboard(text: &str) {
    use std::io::Write;
    let escape = format!("\x1b]52;c;{}\x07", graphics::base64(text.as_bytes()));
    let mut stdout = std::io::stdout();
    let _ = write!(stdout, "{escape}");
    let _ = stdout.flush();
}

/// Error chains get long; the pane has one line for them.
fn first_line(message: &str) -> String {
    let line = message.lines().next().unwrap_or(message).trim();
    if line.len() > 200 {
        format!("{}", &line[..line.floor_char_boundary(200)])
    } else {
        line.to_string()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn app() -> App {
        let (tx, _rx) = mpsc::channel();
        App {
            settings: Settings {
                policy: Default::default(),
                dest_dir: std::path::PathBuf::from("/tmp"),
                max_bytes: 1 << 30,
                verify: true,
                force: false,
                resume: true,
                mirrors: Vec::new(),
                refresh_mirrors: false,
                quiet: false,
                json: false,
                output: None,
                reader: None,
                history: false,
                covers: false,
                search_limit: 25,
                search_topics: vec![Topic::Libgen, Topic::Fiction],
                overrides: Default::default(),
            },
            config: Config::default(),
            form: SettingsForm::default(),
            config_path: std::env::temp_dir().join(format!(
                "tomesole-cfg-test-{}-{:?}.conf",
                std::process::id(),
                std::thread::current().id()
            )),
            tab: Tab::Search,
            mode: Mode::Editing,
            query: String::new(),
            filter: String::new(),
            caret: 0,
            results: Vec::new(),
            visible: Vec::new(),
            fmt_filter: None,
            lang_filter: None,
            author_filter: None,
            picker: None,
            sort_menu: None,
            sort: Sort::Relevance,
            sort_desc: false,
            table: TableState::default(),
            marked: Vec::new(),
            jobs: HashMap::new(),
            mirrors: Vec::new(),
            mirror_label: String::new(),
            status: String::new(),
            error: None,
            busy: false,
            downloading: false,
            pending_search: false,
            search_generation: 0,
            quit: false,
            tx,
            library: Vec::new(),
            shown: Vec::new(),
            owned: HashSet::new(),
            library_table: TableState::default(),
            // Tests draw to an off-screen buffer, so nothing may try to write
            // an escape sequence to a terminal that is not there.
            protocol: Protocol::None,
            covers: HashMap::new(),
            cover_due: None,
            painted: None,
            cover_area: None,
            spinner: 0,
        }
    }

    fn press(app: &mut App, code: KeyCode) {
        app.on_key(KeyEvent::new(code, KeyModifiers::NONE));
    }

    /// Drive the facet picker the way a person would: its key opens the menu,
    /// the typed text narrows it, and Enter commits the highlighted row (the
    /// first match once anything is typed).
    fn pick(app: &mut App, facet_key: char, query: &str) {
        press(app, KeyCode::Char(facet_key));
        for c in query.chars() {
            press(app, KeyCode::Char(c));
        }
        press(app, KeyCode::Enter);
    }

    /// Drive the sort menu: open it, walk the highlight to the wanted order, and
    /// commit — taking that order's natural direction, the same default the old
    /// `s` cycle used.
    fn sort_to(app: &mut App, want: Sort) {
        press(app, KeyCode::Char('s'));
        let target = Sort::CYCLE.iter().position(|s| *s == want).unwrap();
        loop {
            let at = app.sort_menu.as_ref().unwrap().cursor;
            if at == target {
                break;
            }
            press(app, if at < target { KeyCode::Down } else { KeyCode::Up });
        }
        press(app, KeyCode::Enter);
    }

    fn books(n: usize) -> Vec<Book> {
        (0..n)
            .map(|i| Book {
                md5: format!("{i:032x}"),
                title: format!("Book {i}"),
                ..Default::default()
            })
            .collect()
    }

    /// Put results in place the way `Ev::Results` would, so the visible-index
    /// mapping is always consistent with what the table believes.
    fn install(a: &mut App, list: Vec<Book>) {
        a.marked = vec![false; list.len()];
        a.results = list;
        a.table.select(None);
        a.refine();
    }

    /// The titles currently on screen, in display order.
    fn titles(a: &App) -> Vec<String> {
        a.visible
            .iter()
            .map(|&i| a.results[i].title.clone())
            .collect()
    }

    fn book(md5: &str, title: &str, year: &str, size: u64) -> Book {
        Book {
            md5: md5.into(),
            title: title.into(),
            year: Some(year.into()),
            size_bytes: Some(size),
            ..Default::default()
        }
    }

    #[test]
    fn typing_builds_the_query() {
        let mut a = app();
        for c in "dune".chars() {
            press(&mut a, KeyCode::Char(c));
        }
        assert_eq!(a.query, "dune");
        assert_eq!(a.caret, 4);
    }

    #[test]
    fn editing_respects_the_caret() {
        let mut a = app();
        for c in "dune".chars() {
            press(&mut a, KeyCode::Char(c));
        }
        press(&mut a, KeyCode::Home);
        press(&mut a, KeyCode::Char('_'));
        assert_eq!(a.query, "_dune");
        press(&mut a, KeyCode::End);
        press(&mut a, KeyCode::Backspace);
        assert_eq!(a.query, "_dun");
    }

    /// Editing is by character, so a multi-byte query must not panic or split.
    #[test]
    fn editing_handles_multibyte_text() {
        let mut a = app();
        for c in "naïve 日本".chars() {
            press(&mut a, KeyCode::Char(c));
        }
        assert_eq!(a.query, "naïve 日本");
        press(&mut a, KeyCode::Backspace);
        assert_eq!(a.query, "naïve 日");
        press(&mut a, KeyCode::Home);
        press(&mut a, KeyCode::Delete);
        assert_eq!(a.query, "aïve 日");
    }

    #[test]
    fn ctrl_w_deletes_a_word() {
        let mut a = app();
        for c in "the rust book".chars() {
            press(&mut a, KeyCode::Char(c));
        }
        a.on_key(KeyEvent::new(KeyCode::Char('w'), KeyModifiers::CONTROL));
        assert_eq!(a.query, "the rust ");
    }

    #[test]
    fn ctrl_u_clears_the_line() {
        let mut a = app();
        for c in "dune".chars() {
            press(&mut a, KeyCode::Char(c));
        }
        a.on_key(KeyEvent::new(KeyCode::Char('u'), KeyModifiers::CONTROL));
        assert_eq!(a.query, "");
        assert_eq!(a.caret, 0);
    }

    #[test]
    fn navigation_stays_in_bounds() {
        let mut a = app();
        a.mode = Mode::Browsing;
        install(&mut a, books(3));

        press(&mut a, KeyCode::Up); // already at the top
        assert_eq!(a.table.selected(), Some(0));
        for _ in 0..10 {
            press(&mut a, KeyCode::Down);
        }
        assert_eq!(a.table.selected(), Some(2), "must not run off the end");
        press(&mut a, KeyCode::Home);
        assert_eq!(a.table.selected(), Some(0));
        press(&mut a, KeyCode::End);
        assert_eq!(a.table.selected(), Some(2));
    }

    #[test]
    fn navigation_on_an_empty_list_is_harmless() {
        let mut a = app();
        a.mode = Mode::Browsing;
        press(&mut a, KeyCode::Down);
        press(&mut a, KeyCode::Up);
        press(&mut a, KeyCode::Enter);
        assert_eq!(a.table.selected(), None);
        assert!(!a.quit);
    }

    #[test]
    fn space_marks_and_advances() {
        let mut a = app();
        a.mode = Mode::Browsing;
        install(&mut a, books(3));

        press(&mut a, KeyCode::Char(' '));
        assert_eq!(a.marked, [true, false, false]);
        assert_eq!(
            a.table.selected(),
            Some(1),
            "space moves on for fast marking"
        );
    }

    #[test]
    fn capital_a_toggles_every_mark() {
        let mut a = app();
        a.mode = Mode::Browsing;
        install(&mut a, books(3));
        press(&mut a, KeyCode::Char('A'));
        assert_eq!(a.marked, [true, true, true]);
        press(&mut a, KeyCode::Char('A'));
        assert_eq!(a.marked, [false, false, false]);
    }

    #[test]
    fn sorting_reorders_the_list_and_keeps_the_selection() {
        let mut a = app();
        a.mode = Mode::Browsing;
        install(
            &mut a,
            vec![
                book("00000000000000000000000000000001", "Charlie", "2001", 300),
                book("00000000000000000000000000000002", "alpha", "1999", 100),
                book("00000000000000000000000000000003", "Bravo", "2010", 200),
            ],
        );
        // Relevance is the order the mirror returned.
        assert_eq!(titles(&a), ["Charlie", "alpha", "Bravo"]);

        // Rest the cursor on a book, then sort by title: it must follow.
        a.table.select(Some(1));
        assert_eq!(a.selected().unwrap().title, "alpha");
        sort_to(&mut a, Sort::Title); // ascending, case-insensitive
        assert_eq!(a.sort, Sort::Title);
        assert_eq!(titles(&a), ["alpha", "Bravo", "Charlie"]);
        assert_eq!(
            a.selected().unwrap().title,
            "alpha",
            "the highlight tracks its book across a re-sort"
        );

        sort_to(&mut a, Sort::Year); // newest first by default
        assert_eq!(a.sort, Sort::Year);
        assert_eq!(titles(&a), ["Bravo", "Charlie", "alpha"]);

        sort_to(&mut a, Sort::Size); // biggest first by default
        assert_eq!(titles(&a), ["Charlie", "Bravo", "alpha"]);
        a.reverse_sort(); // smallest first
        assert_eq!(titles(&a), ["alpha", "Bravo", "Charlie"]);

        sort_to(&mut a, Sort::Relevance); // the mirror's own order again
        assert_eq!(a.sort, Sort::Relevance);
        assert_eq!(titles(&a), ["Charlie", "alpha", "Bravo"]);
    }

    #[test]
    fn a_result_already_in_the_library_is_flagged() {
        let mut a = app();
        a.mode = Mode::Browsing;
        let owned = "1b9159991f7fb1b3910c0be9ebf7e595";
        a.owned.insert(owned.into());
        install(
            &mut a,
            vec![
                Book {
                    md5: owned.into(),
                    title: "Owned Book".into(),
                    extension: Some("epub".into()),
                    ..Default::default()
                },
                Book {
                    md5: "00000000000000000000000000000009".into(),
                    title: "New Book".into(),
                    extension: Some("epub".into()),
                    ..Default::default()
                },
            ],
        );
        let screen = draw(&mut a, 100, 20);
        let owned_row = screen
            .lines()
            .find(|l| l.contains("Owned Book"))
            .unwrap_or("");
        let new_row = screen.lines().find(|l| l.contains("New Book")).unwrap_or("");
        assert!(
            owned_row.contains("library"),
            "an owned result should say so: {screen}"
        );
        assert!(
            !new_row.contains("library"),
            "a fresh result must not: {screen}"
        );
    }

    #[test]
    fn a_marked_batch_reports_its_combined_size() {
        let mut a = app();
        a.mode = Mode::Browsing;
        install(
            &mut a,
            vec![
                book("00000000000000000000000000000001", "A", "2000", 1024 * 1024),
                book(
                    "00000000000000000000000000000002",
                    "B",
                    "2000",
                    3 * 1024 * 1024,
                ),
            ],
        );
        assert!(a.marked_summary().is_none());
        a.marked = vec![true, true];
        assert_eq!(a.marked_summary(), Some((2, 4 * 1024 * 1024)));
        let screen = draw(&mut a, 100, 20);
        assert!(screen.contains("2 marked"), "{screen}");
    }

    #[test]
    fn y_copies_the_md5_to_the_status_line() {
        let mut a = app();
        a.mode = Mode::Browsing;
        install(&mut a, books(2));
        a.table.select(Some(1));
        press(&mut a, KeyCode::Char('y'));
        assert!(
            a.status.contains(&a.results[1].md5),
            "the md5 should be named: {}",
            a.status
        );
        assert!(a.status.contains("clipboard"));
    }

    #[test]
    fn the_library_strip_summarises_the_shelf() {
        let mut a = app();
        a.mode = Mode::Browsing;
        a.tab = Tab::Library;
        a.library = entries(3); // three 1 MB epubs
        a.owned = a.library.iter().map(|e| e.md5.clone()).collect();
        a.refilter();
        let screen = draw(&mut a, 100, 20);
        assert!(screen.contains("3 books"), "count missing: {screen}");
        assert!(screen.contains("epub"), "format breakdown missing: {screen}");
    }

    #[test]
    fn a_list_taller_than_the_screen_grows_a_scroll_indicator() {
        let mut a = app();
        a.mode = Mode::Browsing;
        install(&mut a, books(50));
        // A short terminal cannot show fifty rows, so the thumb appears. The
        // full block is drawn nowhere else when no download is in flight.
        let screen = draw(&mut a, 80, 12);
        assert!(screen.contains(''), "scroll thumb missing: {screen}");
        // A list that fits keeps the whole width — no thumb.
        install(&mut a, books(3));
        let roomy = draw(&mut a, 80, 24);
        assert!(!roomy.contains(''), "no scrollbar when it all fits: {roomy}");
    }

    #[test]
    fn mode_switching_and_quitting() {
        let mut a = app();
        a.mode = Mode::Browsing;
        press(&mut a, KeyCode::Char('/'));
        assert_eq!(a.mode, Mode::Editing);
        press(&mut a, KeyCode::Esc);
        assert_eq!(a.mode, Mode::Browsing);

        press(&mut a, KeyCode::Char('?'));
        assert_eq!(a.mode, Mode::Help);
        press(&mut a, KeyCode::Char('x'));
        assert_eq!(a.mode, Mode::Browsing, "any key closes help");

        press(&mut a, KeyCode::Char('q'));
        assert!(a.quit);
    }

    #[test]
    fn ctrl_c_quits_from_editing_too() {
        let mut a = app();
        a.mode = Mode::Editing;
        a.on_key(KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL));
        assert!(a.quit);
    }

    /// Letters must reach the query rather than triggering browse shortcuts.
    #[test]
    fn shortcut_letters_are_literal_while_editing() {
        let mut a = app();
        a.mode = Mode::Editing;
        for c in "qajm".chars() {
            press(&mut a, KeyCode::Char(c));
        }
        assert_eq!(a.query, "qajm");
        assert!(!a.quit);
    }

    #[test]
    fn search_without_a_mirror_is_deferred_not_lost() {
        let mut a = app();
        a.query = "dune".into();
        a.spawn_search();
        assert!(
            a.pending_search,
            "the search should run once a mirror appears"
        );
    }

    #[test]
    fn empty_search_is_reported_not_sent() {
        let mut a = app();
        a.query = "   ".into();
        a.spawn_search();
        assert!(a.error.is_some());
        assert!(!a.pending_search);
    }

    #[test]
    fn tui_searches_use_the_startup_config_defaults() {
        let mut a = app();
        a.settings.search_limit = 50;
        a.settings.search_topics = vec![Topic::Comics, Topic::Magazines];

        let query = a.search_query("dune");

        assert_eq!(query.limit, 50);
        assert_eq!(query.topics, [Topic::Comics, Topic::Magazines]);
    }

    #[test]
    fn results_reset_selection_and_marks() {
        let mut a = app();
        a.marked = vec![true, true];
        a.handle(Ev::Results {
            generation: 0,
            result: Ok((books(2), "libgen.li".into())),
        });
        assert_eq!(a.marked, [false, false]);
        assert_eq!(a.table.selected(), Some(0));
        assert_eq!(a.mirror_label, "libgen.li");
        assert_eq!(a.mode, Mode::Browsing);
    }

    #[test]
    fn empty_results_leave_nothing_selected() {
        let mut a = app();
        a.handle(Ev::Results {
            generation: 0,
            result: Ok((Vec::new(), "libgen.li".into())),
        });
        assert_eq!(a.table.selected(), None);
        assert!(a.status.contains("nothing found"));
    }

    #[test]
    fn a_superseded_search_cannot_replace_newer_results() {
        let mut a = app();
        a.search_generation = 2;
        a.busy = true;
        install(&mut a, books(1));

        a.handle(Ev::Results {
            generation: 1,
            result: Ok((books(3), "old.example".into())),
        });

        assert_eq!(a.results.len(), 1);
        assert!(a.busy, "the current search is still running");
        assert_ne!(a.mirror_label, "old.example");
    }

    #[test]
    fn finishing_the_last_job_clears_the_busy_flag() {
        let mut a = app();
        a.downloading = true;
        a.jobs.insert(
            "abc".into(),
            Job::Running {
                done: 1,
                total: None,
                started: Instant::now(),
            },
        );
        a.handle(Ev::Finished {
            md5: "abc".into(),
            outcome: Ok("book.epub".into()),
        });
        assert!(!a.downloading);
        assert!(matches!(a.jobs.get("abc"), Some(Job::Saved(_))));
    }

    #[test]
    fn a_failure_is_surfaced_rather_than_swallowed() {
        let mut a = app();
        a.handle(Ev::Finished {
            md5: "abc".into(),
            outcome: Err("integrity check failed\nsecond line".into()),
        });
        assert_eq!(a.error.as_deref(), Some("integrity check failed"));
        assert!(matches!(a.jobs.get("abc"), Some(Job::Failed(_))));
    }

    /// Draw the app to an off-screen buffer and return it as text.
    fn draw(a: &mut App, width: u16, height: u16) -> String {
        use ratatui::backend::TestBackend;
        let mut terminal = Terminal::new(TestBackend::new(width, height)).unwrap();
        terminal.draw(|f| a.render(f)).unwrap();
        let buffer = terminal.backend().buffer().clone();
        (0..buffer.area.height)
            .map(|y| {
                (0..buffer.area.width)
                    .map(|x| buffer[(x, y)].symbol().to_string())
                    .collect::<String>()
            })
            .collect::<Vec<_>>()
            .join("\n")
    }

    #[test]
    fn the_sort_menu_opens_on_the_current_order() {
        let mut a = app();
        a.mode = Mode::Browsing;
        install(&mut a, polyglot());
        a.sort = Sort::Year;
        press(&mut a, KeyCode::Char('s'));
        let menu = a.sort_menu.as_ref().expect("menu is up");
        assert_eq!(Sort::CYCLE[menu.cursor], Sort::Year, "highlight starts on the order in force");
        let screen = draw(&mut a, 90, 24);
        assert!(screen.contains("sort by"), "{screen}");
        assert!(screen.contains("relevance") && screen.contains("size"), "{screen}");
    }

    #[test]
    fn the_sort_menu_selects_a_column_directly() {
        let mut a = app();
        a.mode = Mode::Browsing;
        install(&mut a, polyglot());
        // From relevance, open and jump straight to Size — one choice, not four
        // steps through the orders in between.
        sort_to(&mut a, Sort::Size);
        assert_eq!(a.sort, Sort::Size);
        assert!(a.sort_desc, "size opens biggest-first by default");
        assert!(a.sort_menu.is_none(), "committing closes the menu");
    }

    #[test]
    fn the_sort_menu_flips_direction_in_place() {
        let mut a = app();
        a.mode = Mode::Browsing;
        install(&mut a, polyglot());
        a.sort = Sort::Title;
        press(&mut a, KeyCode::Char('s')); // opens on Title, ascending
        press(&mut a, KeyCode::Left); // flip to descending
        press(&mut a, KeyCode::Enter);
        assert_eq!(a.sort, Sort::Title);
        assert!(a.sort_desc, "the direction key set it descending");
    }

    #[test]
    fn esc_leaves_the_sort_untouched() {
        let mut a = app();
        a.mode = Mode::Browsing;
        install(&mut a, polyglot());
        press(&mut a, KeyCode::Char('s'));
        press(&mut a, KeyCode::Down);
        press(&mut a, KeyCode::Down);
        press(&mut a, KeyCode::Esc);
        assert!(a.sort_menu.is_none());
        assert_eq!(a.sort, Sort::Relevance, "backing out changes nothing");
    }

    #[test]
    fn the_picker_lists_the_values_present_with_counts() {
        let mut a = app();
        a.mode = Mode::Browsing;
        install(&mut a, polyglot());
        press(&mut a, KeyCode::Char('a')); // author picker
        let screen = draw(&mut a, 100, 30);
        assert!(screen.contains("filter · author"), "{screen}");
        assert!(screen.contains("clear filter"), "{screen}");
        // Every author present, most common first, each with its count.
        assert!(screen.contains("Marx, Karl"), "{screen}");
        assert!(screen.contains("Le Guin, Ursula"), "{screen}");
        assert!(screen.contains("choose"), "the key legend is shown: {screen}");

        // Typing narrows the menu in place rather than cycling values past:
        // "guin" leaves one of the three authors on the menu.
        for c in "guin".chars() {
            press(&mut a, KeyCode::Char(c));
        }
        let screen = draw(&mut a, 100, 30);
        assert!(screen.contains("Le Guin, Ursula"), "{screen}");
        assert!(screen.contains("1 of 3"), "the live match count: {screen}");
    }

    #[test]
    fn tab_rotates_the_open_picker_between_facets() {
        let mut a = app();
        a.mode = Mode::Browsing;
        install(&mut a, polyglot());
        press(&mut a, KeyCode::Char('e'));
        assert_eq!(a.picker.as_ref().map(|p| p.facet), Some(Facet::Format));
        press(&mut a, KeyCode::Tab);
        assert_eq!(a.picker.as_ref().map(|p| p.facet), Some(Facet::Language));
        press(&mut a, KeyCode::Tab);
        assert_eq!(a.picker.as_ref().map(|p| p.facet), Some(Facet::Author));
        press(&mut a, KeyCode::Tab);
        assert_eq!(a.picker.as_ref().map(|p| p.facet), Some(Facet::Format), "wraps");
    }

    #[test]
    fn renders_results_and_details() {
        let mut a = app();
        a.mode = Mode::Browsing;
        a.mirror_label = "libgen.li".into();
        install(
            &mut a,
            vec![Book {
                md5: "1b9159991f7fb1b3910c0be9ebf7e595".into(),
                title: "The Rust Programming Language".into(),
                authors: Some("Klabnik, Steve;Nichols, Carol".into()),
                year: Some("2019".into()),
                language: Some("English".into()),
                extension: Some("epub".into()),
                size_bytes: Some(3 * 1024 * 1024),
                ..Default::default()
            }],
        );

        let screen = draw(&mut a, 100, 24);
        assert!(screen.contains("SEARCH"), "tab bar missing: {screen}");
        assert!(screen.contains("libgen.li"), "{screen}");
        assert!(screen.contains("The Rust Programming Language"), "{screen}");
        assert!(screen.contains("Klabnik"), "{screen}");
        assert!(screen.contains("epub"), "{screen}");
        // The details pane shows the hash of the highlighted row.
        assert!(
            screen.contains("1b9159991f7fb1b3910c0be9ebf7e595"),
            "{screen}"
        );
        assert!(screen.contains("download"), "hints missing: {screen}");
    }

    #[test]
    fn renders_at_awkward_sizes_without_panicking() {
        // A layout that assumes it has room is a crash waiting for a small
        // terminal, so exercise the extremes.
        for (w, h) in [(20u16, 8u16), (40, 10), (80, 24), (200, 60), (250, 12)] {
            let mut a = app();
            a.mode = Mode::Browsing;
            install(&mut a, books(30));
            a.table.select(Some(29));
            let _ = draw(&mut a, w, h);

            a.mode = Mode::Help;
            let _ = draw(&mut a, w, h);

            // The settings form has its own layout — a long field list, a sub-
            // list and an active editor — so exercise those at the extremes too.
            a.mode = Mode::Browsing;
            a.tab = Tab::Settings;
            let _ = draw(&mut a, w, h);
            a.form.selected = Field::ALL.iter().position(|&f| f == Field::Mirrors).unwrap();
            a.form.sub = SubFocus::Mirrors;
            a.config.mirrors = vec!["https://a.example".into(), "https://b.example".into()];
            let _ = draw(&mut a, w, h);
        }
    }

    #[test]
    fn renders_the_empty_and_error_states() {
        let mut a = app();
        a.status = "finding a working mirror".into();
        a.busy = true;
        let screen = draw(&mut a, 80, 20);
        assert!(screen.contains("finding a working mirror"), "{screen}");

        a.error = Some("every mirror failed".into());
        let screen = draw(&mut a, 80, 20);
        assert!(screen.contains("every mirror failed"), "{screen}");
    }

    #[test]
    fn help_overlay_lists_the_keys() {
        let mut a = app();
        a.mode = Mode::Help;
        let screen = draw(&mut a, 90, 24);
        assert!(screen.contains("keys"), "{screen}");
        assert!(screen.contains("download"), "{screen}");
        assert!(screen.contains("quit"), "{screen}");
    }

    #[test]
    fn download_state_is_visible_in_the_row_and_detail() {
        let mut a = app();
        a.mode = Mode::Browsing;
        install(&mut a, books(1));
        a.jobs.insert(
            a.results[0].md5.clone(),
            Job::Running {
                done: 512 * 1024,
                total: Some(1024 * 1024),
                started: Instant::now(),
            },
        );
        let screen = draw(&mut a, 100, 20);
        assert!(screen.contains("50%"), "row progress missing: {screen}");
        assert!(screen.contains(""), "detail bar missing: {screen}");
    }

    #[test]
    fn the_meter_stays_within_its_width() {
        // A half-full ten-cell meter is five full blocks and five track cells.
        let bar = meter(0.5, 10);
        assert_eq!(bar.chars().filter(|c| *c == '').count(), 5);
        assert_eq!(bar.chars().filter(|c| *c == '').count(), 5);
        // The fractional boundary never overruns the requested width.
        assert_eq!(meter(0.37, 10).chars().count(), 10);
        assert_eq!(meter(0.0, 8).chars().filter(|c| *c == '').count(), 8);
        assert_eq!(meter(1.0, 8).chars().filter(|c| *c == '').count(), 8);
        // Over-full is clamped rather than panicking.
        assert_eq!(meter(2.0, 6).chars().count(), 6);
    }

    #[test]
    fn an_eta_reads_compactly() {
        assert_eq!(short_duration(45), "45s");
        assert_eq!(short_duration(200), "3m 20s");
        assert_eq!(short_duration(3900), "1h 05m");
    }

    fn entries(n: usize) -> Vec<history::Entry> {
        (0..n)
            .map(|i| history::Entry {
                at: history::now() - (i as u64 * 3600),
                md5: format!("{i:032x}"),
                path: std::path::PathBuf::from(format!("/books/Book {i}.epub")),
                size: 1024 * 1024,
                verified: true,
                title: format!("Book {i}"),
                authors: Some("Frank Herbert".into()),
                extension: Some("epub".into()),
            })
            .collect()
    }

    /// Put the app on the library tab with a fixed set of books, bypassing the
    /// disk read that `reload_library` would do.
    fn with_library(a: &mut App, entries: Vec<history::Entry>) {
        a.tab = Tab::Library;
        a.mode = Mode::Browsing;
        a.library = entries;
        a.refilter();
    }

    #[test]
    fn moving_in_the_library_arms_a_cover_lookup() {
        let mut a = app();
        a.protocol = Protocol::Blocks;
        with_library(&mut a, entries(3));
        a.cover_due = None;
        press(&mut a, KeyCode::Down);
        assert!(
            a.cover_due.is_some(),
            "a settled library selection is worth a cover, just like search"
        );
    }

    #[test]
    fn a_library_book_shows_its_cover_in_both_layouts() {
        let mut a = app();
        a.protocol = Protocol::Blocks;
        with_library(&mut a, entries(3));
        a.library_table.select(Some(0));

        // Stand in for a cover pulled out of the file on disk.
        let image = crate::jpeg::decode(include_bytes!("../tests/fixtures/cover.jpg")).unwrap();
        let md5 = a.selected_entry().unwrap().md5.clone();
        a.covers.insert(
            md5,
            Slot::Ready(Box::new(Art {
                encoded: Vec::new(),
                pixels: Some(image),
            })),
        );

        // The bottom band grows a cover column beside the file facts, wide or
        // narrow — the same horizontal layout at either size.
        for (w, h) in [(130u16, 40u16), (90, 24)] {
            let screen = draw(&mut a, w, h);
            assert!(
                screen.contains(graphics::UPPER_HALF),
                "{w}x{h}: the library cover should draw as half blocks: {screen}"
            );
            assert!(screen.contains("Book 0"), "{w}x{h}: {screen}");
        }
    }

    #[test]
    fn a_library_cover_with_no_local_source_falls_back_to_a_mirror() {
        // The whole point of the fallback: a book whose file carries no jacket
        // and that was never searched must still get a cover off a mirror, the
        // same way the Search tab does. With no mirror there is nothing to ask,
        // so it comes back empty rather than erroring.
        let a = app();
        let entry = &entries(1)[0];
        assert!(
            App::fetch_library_cover(&a.settings, &[], entry)
                .unwrap()
                .is_none(),
            "no mirror, no cover, but no error either"
        );
    }

    #[test]
    fn a_mirror_arriving_revives_library_covers_that_had_none_to_ask() {
        // Open the library before the mirror pool resolves: a book with no
        // local cover comes up blank because there was nobody to ask. When the
        // mirror lands, that blank must be dropped and the selection re-armed so
        // the cover is looked up for real.
        let mut a = app();
        a.protocol = Protocol::Kitty;
        with_library(&mut a, entries(1));
        a.library_table.select(Some(0));
        let md5 = a.selected_entry().unwrap().md5.clone();

        // Stands in for the empty result of a mirror-less first look.
        a.covers.insert(md5.clone(), Slot::Nothing);
        a.cover_due = None;

        a.handle(Ev::Mirrors(Ok(vec!["https://libgen.li".parse().unwrap()])));

        assert!(
            !a.covers.contains_key(&md5),
            "the blank cover should be dropped so it can be looked up again"
        );
        assert!(
            a.cover_due.is_some(),
            "the selection should be re-armed to fetch now a mirror exists"
        );
    }

    #[test]
    fn the_library_reuses_a_cover_across_tabs_by_md5() {
        // A cover fetched while searching is keyed by MD5; the same book in the
        // library must find it under the same key rather than looking again.
        let mut a = app();
        a.protocol = Protocol::Blocks;
        let md5 = format!("{:032x}", 0);
        a.covers.insert(md5.clone(), Slot::Nothing);
        with_library(&mut a, entries(1));
        a.library_table.select(Some(0));
        assert_eq!(a.selected_entry().unwrap().md5, md5);
        // Already known, so a poll starts no new lookup and leaves it be.
        a.cover_due = Some(Instant::now());
        a.poll_cover();
        assert!(matches!(a.covers.get(&md5), Some(Slot::Nothing)));
    }

    #[test]
    fn the_library_tab_lists_past_downloads() {
        let mut a = app();
        with_library(&mut a, entries(3));

        let screen = draw(&mut a, 100, 24);
        assert!(screen.contains("Book 0"), "{screen}");
        assert!(screen.contains("Herbert"), "{screen}");
        assert!(screen.contains("/books/Book 0.epub"), "{screen}");
        // These files do not exist, and the view says so rather than pretending.
        assert!(screen.contains("missing"), "{screen}");
        assert!(screen.contains("forget"), "hints missing: {screen}");
    }

    #[test]
    fn the_library_tab_navigates() {
        let mut a = app();
        with_library(&mut a, entries(3));

        press(&mut a, KeyCode::Up); // already at the top
        assert_eq!(a.library_table.selected(), Some(0));
        for _ in 0..10 {
            press(&mut a, KeyCode::Down);
        }
        assert_eq!(
            a.library_table.selected(),
            Some(2),
            "must not run off the end"
        );
        press(&mut a, KeyCode::Home);
        assert_eq!(a.library_table.selected(), Some(0));
    }

    /// The bug that started all this: the library was reachable only from the
    /// results list, so a fresh session — which opens in the editor with no
    /// results — had no way to reach it at all. Tab must always work.
    #[test]
    fn the_library_is_reachable_before_any_search() {
        let mut a = app();
        assert_eq!(a.tab, Tab::Search);
        assert_eq!(a.mode, Mode::Editing, "a fresh session starts typing");

        // Tab reaches the library even mid-edit, with nothing searched yet, and
        // then rotates on through Settings and back to Search.
        press(&mut a, KeyCode::Tab);
        assert_eq!(a.tab, Tab::Library);
        press(&mut a, KeyCode::Tab);
        assert_eq!(a.tab, Tab::Settings);
        press(&mut a, KeyCode::Tab);
        assert_eq!(a.tab, Tab::Search);

        // And the number keys jump straight there when not typing.
        a.mode = Mode::Browsing;
        press(&mut a, KeyCode::Char('2'));
        assert_eq!(a.tab, Tab::Library);
        press(&mut a, KeyCode::Char('3'));
        assert_eq!(a.tab, Tab::Settings);
        press(&mut a, KeyCode::Char('1'));
        assert_eq!(a.tab, Tab::Search);
    }

    #[test]
    fn q_quits_from_the_library_tab_too() {
        let mut a = app();
        with_library(&mut a, entries(3));
        press(&mut a, KeyCode::Char('q'));
        assert!(a.quit, "the library is a peer of search, not a detour");
    }

    // --- the settings tab -------------------------------------------------

    /// Open the Settings tab from a fresh browsing session.
    fn open_settings(a: &mut App) {
        a.mode = Mode::Browsing;
        press(a, KeyCode::Char('3'));
        assert_eq!(a.tab, Tab::Settings);
    }

    /// Walk the field cursor to a given field.
    fn go_to(a: &mut App, field: Field) {
        let target = Field::ALL.iter().position(|&f| f == field).unwrap();
        while a.form.selected < target {
            press(a, KeyCode::Down);
        }
        while a.form.selected > target {
            press(a, KeyCode::Up);
        }
        assert_eq!(a.current_field(), field);
    }

    fn type_str(a: &mut App, s: &str) {
        for c in s.chars() {
            press(a, KeyCode::Char(c));
        }
    }

    #[test]
    fn arrows_move_the_field_cursor_after_tabbing_in_from_a_fresh_session() {
        // A fresh session opens in the search box (Mode::Editing). Tabbing all
        // the way round to Settings must hand the arrows to the field list, not
        // leave them driving the search editor.
        let mut a = app();
        assert_eq!(a.mode, Mode::Editing, "a fresh session starts typing");
        press(&mut a, KeyCode::Tab); // Library
        press(&mut a, KeyCode::Tab); // Settings
        assert_eq!(a.tab, Tab::Settings);
        assert_eq!(a.mode, Mode::Browsing, "the form never runs while editing");

        assert_eq!(a.form.selected, 0);
        press(&mut a, KeyCode::Down);
        assert_eq!(a.form.selected, 1, "down moves the field cursor");
        press(&mut a, KeyCode::Char('j'));
        assert_eq!(a.form.selected, 2, "j moves it too");
        press(&mut a, KeyCode::Up);
        assert_eq!(a.form.selected, 1);
        let _ = std::fs::remove_file(&a.config_path);
    }

    #[test]
    fn toggling_a_bool_updates_the_config_applies_live_and_saves() {
        let mut a = app();
        a.settings.covers = true;
        open_settings(&mut a);
        go_to(&mut a, Field::Covers);

        press(&mut a, KeyCode::Char(' '));
        assert_eq!(a.config.covers, Some(false), "the file value flips");
        assert!(!a.settings.covers, "and the running session follows");
        // Autosave landed the change on disk.
        let written = std::fs::read_to_string(&a.config_path).unwrap();
        assert!(written.contains("covers = false"), "got: {written}");
        let _ = std::fs::remove_file(&a.config_path);
    }

    #[test]
    fn a_line_field_rejects_junk_and_accepts_a_valid_value() {
        let mut a = app();
        open_settings(&mut a);
        go_to(&mut a, Field::MaxSize);

        // Enter the editor and type something that is not a size.
        press(&mut a, KeyCode::Enter);
        type_str(&mut a, "bogus");
        press(&mut a, KeyCode::Enter);
        assert!(a.form.editing.is_some(), "a bad value keeps the editor open");
        assert!(a.form.error.is_some(), "and reports why");
        assert_eq!(a.config.max_size, None, "nothing is stored");

        // Clear it and type a real size.
        a.on_key(KeyEvent::new(KeyCode::Char('u'), KeyModifiers::CONTROL));
        type_str(&mut a, "2 GB");
        press(&mut a, KeyCode::Enter);
        assert!(a.form.editing.is_none(), "a good value commits");
        assert_eq!(a.config.max_size, Some(2 * 1024 * 1024 * 1024));
        assert_eq!(a.settings.max_bytes, 2 * 1024 * 1024 * 1024, "applied live");
        let _ = std::fs::remove_file(&a.config_path);
    }

    #[test]
    fn editing_a_path_field_expands_a_tilde() {
        let mut a = app();
        open_settings(&mut a);
        go_to(&mut a, Field::DownloadDir);
        press(&mut a, KeyCode::Enter);
        type_str(&mut a, "~/Books");
        press(&mut a, KeyCode::Enter);
        let dir = a.config.download_dir.clone().unwrap();
        assert!(dir.ends_with("Books"));
        assert!(!dir.to_string_lossy().starts_with('~'), "tilde is expanded");
        assert_eq!(a.settings.dest_dir, dir, "the session downloads there now");
        let _ = std::fs::remove_file(&a.config_path);
    }

    #[test]
    fn clearing_live_fields_restores_built_in_defaults() {
        let mut a = app();
        a.config.max_size = Some(2 * 1024 * 1024 * 1024);
        a.settings.max_bytes = 2 * 1024 * 1024 * 1024;
        a.config.download_dir = Some(PathBuf::from("/old/downloads"));
        a.settings.dest_dir = PathBuf::from("/old/downloads");
        open_settings(&mut a);

        go_to(&mut a, Field::MaxSize);
        press(&mut a, KeyCode::Enter);
        a.on_key(KeyEvent::new(KeyCode::Char('u'), KeyModifiers::CONTROL));
        press(&mut a, KeyCode::Enter);
        assert_eq!(a.config.max_size, None);
        assert_eq!(a.settings.max_bytes, crate::DEFAULT_MAX_BYTES);

        go_to(&mut a, Field::DownloadDir);
        press(&mut a, KeyCode::Enter);
        a.on_key(KeyEvent::new(KeyCode::Char('u'), KeyModifiers::CONTROL));
        press(&mut a, KeyCode::Enter);
        assert_eq!(a.config.download_dir, None);
        assert_eq!(a.settings.dest_dir, crate::config::default_download_dir());
        let _ = std::fs::remove_file(&a.config_path);
    }

    #[test]
    fn live_config_edits_do_not_override_cli_values() {
        let mut a = app();
        a.settings.dest_dir = PathBuf::from("/cli/downloads");
        a.settings.max_bytes = 123;
        a.settings.verify = false;
        a.settings.reader = Some("cli-reader".into());
        a.settings.covers = false;
        a.settings.overrides = crate::SettingsOverrides {
            dest_dir: true,
            max_bytes: true,
            verify: true,
            reader: true,
            covers: true,
        };

        a.config.download_dir = Some(PathBuf::from("/config/downloads"));
        a.config.max_size = Some(456);
        a.config.verify = Some(true);
        a.config.reader = Some("config-reader".into());
        a.config.covers = Some(true);
        for field in [
            Field::DownloadDir,
            Field::MaxSize,
            Field::Verify,
            Field::Reader,
            Field::Covers,
        ] {
            a.apply_live(field);
        }

        assert_eq!(a.settings.dest_dir, PathBuf::from("/cli/downloads"));
        assert_eq!(a.settings.max_bytes, 123);
        assert!(!a.settings.verify);
        assert_eq!(a.settings.reader.as_deref(), Some("cli-reader"));
        assert!(!a.settings.covers);
    }

    #[test]
    fn enabling_covers_live_initializes_the_graphics_protocol() {
        let mut a = app();
        a.config.covers = Some(true);
        a.settings.covers = false;
        a.protocol = Protocol::None;

        a.apply_live(Field::Covers);

        assert!(a.settings.covers);
        assert_eq!(a.protocol, graphics::detect());
    }

    #[test]
    fn collections_can_be_toggled_in_a_sub_list() {
        let mut a = app();
        open_settings(&mut a);
        go_to(&mut a, Field::Topics);
        // Default is libgen + fiction; step into the list.
        press(&mut a, KeyCode::Enter);
        assert_eq!(a.form.sub, SubFocus::Topics);
        // Cursor starts on libgen — turn it off.
        assert_eq!(Topic::ALL[a.form.topic_row], Topic::Libgen);
        press(&mut a, KeyCode::Char(' '));
        let topics = a.config.topics.clone().unwrap();
        assert!(!topics.contains(&Topic::Libgen));
        assert!(topics.contains(&Topic::Fiction));
        press(&mut a, KeyCode::Esc);
        assert_eq!(a.form.sub, SubFocus::None);
        let _ = std::fs::remove_file(&a.config_path);
    }

    #[test]
    fn mirrors_can_be_added_and_deleted() {
        let mut a = app();
        open_settings(&mut a);
        go_to(&mut a, Field::Mirrors);
        press(&mut a, KeyCode::Enter);
        assert_eq!(a.form.sub, SubFocus::Mirrors);

        // Add one.
        press(&mut a, KeyCode::Char('a'));
        type_str(&mut a, "https://libgen.example");
        press(&mut a, KeyCode::Enter);
        assert_eq!(a.config.mirrors, ["https://libgen.example"]);

        // Delete it again.
        press(&mut a, KeyCode::Char('d'));
        assert!(a.config.mirrors.is_empty());
        let _ = std::fs::remove_file(&a.config_path);
    }

    #[test]
    fn a_field_edit_captures_the_tab_key_instead_of_switching() {
        let mut a = app();
        open_settings(&mut a);
        go_to(&mut a, Field::Reader);
        press(&mut a, KeyCode::Enter); // start editing
        press(&mut a, KeyCode::Tab); // must be swallowed, not a tab switch
        assert_eq!(a.tab, Tab::Settings, "tab does not leave mid-edit");
        assert!(a.form.editing.is_some());
        let _ = std::fs::remove_file(&a.config_path);
    }

    #[test]
    fn the_settings_tab_renders_with_its_fields_and_sub_lists() {
        let mut a = app();
        open_settings(&mut a);
        // Expand the collections list so the checkboxes render too.
        go_to(&mut a, Field::Topics);
        press(&mut a, KeyCode::Enter);
        let screen = draw(&mut a, 80, 24);
        assert!(screen.contains("SETTINGS"), "the tab bar names the tab");
        assert!(screen.contains("cover art"), "a field label shows");
        assert!(screen.contains("[x] libgen"), "the collections sub-list expands");
        assert!(screen.contains("applies next launch"), "deferred fields say so");
        let _ = std::fs::remove_file(&a.config_path);
    }

    #[test]
    fn the_settings_form_scrolls_to_keep_the_selection_visible() {
        let mut a = app();
        open_settings(&mut a);
        go_to(&mut a, Field::AllowHttp);

        let screen = draw(&mut a, 80, 12);

        assert!(
            screen.contains("allow http"),
            "selected row was clipped:\n{screen}"
        );
        let _ = std::fs::remove_file(&a.config_path);
    }

    #[test]
    fn the_settings_form_scrolls_within_a_long_mirror_list() {
        let mut a = app();
        a.config.mirrors = (0..12)
            .map(|i| format!("https://mirror-{i}.example"))
            .collect();
        open_settings(&mut a);
        go_to(&mut a, Field::Mirrors);
        press(&mut a, KeyCode::Enter);
        for _ in 0..11 {
            press(&mut a, KeyCode::Down);
        }

        let screen = draw(&mut a, 80, 12);

        assert!(
            screen.contains("https://mirror-11.example"),
            "active mirror was clipped:\n{screen}"
        );
        let _ = std::fs::remove_file(&a.config_path);
    }

    #[test]
    fn the_filter_narrows_the_library_as_you_type() {
        let mut a = app();
        with_library(&mut a, entries(3));
        // entries() titles are "Book 0", "Book 1", "Book 2"; filter to one.
        press(&mut a, KeyCode::Char('/'));
        assert_eq!(a.mode, Mode::Editing);
        for c in "Book 1".chars() {
            press(&mut a, KeyCode::Char(c));
        }
        assert_eq!(a.shown.len(), 1, "only one title matches");
        assert_eq!(a.selected_entry().map(|e| e.title.clone()).as_deref(), Some("Book 1"));

        let screen = draw(&mut a, 100, 24);
        assert!(screen.contains("Book 1"), "{screen}");
        assert!(!screen.contains("Book 0"), "filtered out: {screen}");

        // Clearing the box brings everyone back.
        a.on_key(KeyEvent::new(KeyCode::Char('u'), KeyModifiers::CONTROL));
        assert_eq!(a.shown.len(), 3);
    }

    #[test]
    fn a_filter_that_matches_nothing_says_so() {
        let mut a = app();
        with_library(&mut a, entries(3));
        a.filter = "nonesuch".into();
        a.refilter();
        assert!(a.shown.is_empty());
        assert!(a.selected_entry().is_none());
        let screen = draw(&mut a, 100, 24);
        assert!(screen.contains("No book matches"), "{screen}");
    }

    #[test]
    fn an_empty_library_tab_is_harmless_and_explains_itself() {
        let mut a = app();
        a.tab = Tab::Library;
        a.mode = Mode::Browsing;
        press(&mut a, KeyCode::Down);
        press(&mut a, KeyCode::Enter);
        press(&mut a, KeyCode::Char('d'));
        assert_eq!(a.library_table.selected(), None);
        let screen = draw(&mut a, 80, 20);
        assert!(screen.contains("library is empty"), "{screen}");
        // It points the way out rather than leaving a dead end.
        assert!(screen.contains("Tab"), "{screen}");
    }

    #[test]
    fn the_tab_bar_shows_both_tabs_and_the_count() {
        let mut a = app();
        a.library = entries(4);
        let screen = draw(&mut a, 100, 24);
        assert!(screen.contains("SEARCH"), "{screen}");
        assert!(screen.contains("LIBRARY"), "{screen}");
        // The count rides along in the tab label so it is visible before you go.
        assert!(screen.contains("LIBRARY 4"), "{screen}");
    }

    #[test]
    fn opening_a_result_that_was_never_downloaded_says_so() {
        let mut a = app();
        a.mode = Mode::Browsing;
        install(&mut a, books(1));
        press(&mut a, KeyCode::Char('o'));
        assert_eq!(
            a.error.as_deref(),
            Some("that one has not been downloaded yet")
        );
    }

    #[test]
    fn a_query_of_nothing_but_filters_is_refused() {
        let mut a = app();
        a.query = "ext:epub lang:english".into();
        a.mirrors = vec!["https://libgen.li".parse().unwrap()];
        a.spawn_search();
        assert!(a.error.is_some(), "there is nothing here to search for");
        assert!(!a.busy);
    }

    /// The half-block path is the one that renders through ratatui, so it is
    /// the one that can be checked on an off-screen buffer.
    #[test]
    fn a_cover_is_drawn_as_blocks_when_there_is_no_image_protocol() {
        let mut a = app();
        a.mode = Mode::Browsing;
        a.protocol = Protocol::Blocks;
        install(&mut a, books(1));

        let image = crate::jpeg::decode(include_bytes!("../tests/fixtures/cover.jpg")).unwrap();
        a.covers.insert(
            a.results[0].md5.clone(),
            Slot::Ready(Box::new(Art {
                encoded: Vec::new(),
                pixels: Some(image),
            })),
        );

        let screen = draw(&mut a, 100, 28);
        assert!(
            screen.contains(graphics::UPPER_HALF),
            "the cover should be drawn as half blocks: {screen}"
        );
        // The book's details are still there beside it.
        assert!(screen.contains("Book 0"), "{screen}");
    }

    /// The kitty and iTerm2 paths write outside ratatui's buffer, so what they
    /// would write is checked directly.
    #[test]
    fn a_pixel_cover_is_placed_once_and_not_repainted() {
        let mut a = app();
        a.mode = Mode::Browsing;
        a.protocol = Protocol::Kitty;
        install(&mut a, books(2));

        let image = crate::jpeg::decode(include_bytes!("../tests/fixtures/cover.jpg")).unwrap();
        a.covers.insert(
            a.results[0].md5.clone(),
            Slot::Ready(Box::new(Art {
                encoded: Vec::new(),
                pixels: Some(image),
            })),
        );

        // Nothing is placed until a frame has said where the space is.
        assert_eq!(a.cover_escape(), None);

        let _ = draw(&mut a, 100, 30);
        let escape = a.cover_escape().expect("a cover should be placed");
        assert!(escape.contains("\x1b["), "no cursor placement: {escape:?}");
        assert!(escape.contains("\x1b_Ga=T"), "no kitty image: {escape:?}");
        assert!(
            !escape.contains("a=d"),
            "nothing was on screen to delete yet"
        );

        // An unchanged screen must not be redrawn — the picture would flicker
        // on every keystroke and every 250 ms tick.
        let _ = draw(&mut a, 100, 30);
        assert_eq!(a.cover_escape(), None, "a settled cover is left alone");

        // Moving to a book with no cover takes the old one down.
        press(&mut a, KeyCode::Down);
        let _ = draw(&mut a, 100, 30);
        let escape = a.cover_escape().expect("the old cover must be removed");
        assert!(escape.contains("a=d"), "no delete: {escape:?}");
        assert!(!escape.contains("a=T"), "nothing to draw: {escape:?}");
    }

    #[test]
    fn a_cover_never_squeezes_out_the_results() {
        let mut a = app();
        a.mode = Mode::Browsing;
        a.protocol = Protocol::Blocks;
        install(&mut a, books(20));
        a.covers.insert(a.results[0].md5.clone(), Slot::Looking);

        for (w, h) in [(20u16, 8u16), (40, 10), (80, 24), (200, 60)] {
            let area = Rect {
                x: 0,
                y: 0,
                width: w,
                height: h,
            };
            let details = a.details_height(area);
            assert!(
                details <= h.saturating_sub(4).max(7),
                "{w}×{h} gave a {details}-row detail pane"
            );
            let _ = draw(&mut a, w, h);
        }
    }

    #[test]
    fn covers_are_only_looked_up_after_the_selection_settles() {
        let mut a = app();
        a.protocol = Protocol::Blocks;
        a.mode = Mode::Browsing;
        install(&mut a, books(3));

        press(&mut a, KeyCode::Down);
        assert!(a.cover_due.is_some(), "moving should arm the lookup");
        // Nothing is due yet, so nothing is started.
        a.poll_cover();
        assert!(a.covers.is_empty());

        // With no mirror there is nothing to ask, and it must not spin.
        a.cover_due = Some(Instant::now());
        a.poll_cover();
        assert!(a.covers.is_empty(), "a lookup needs a mirror first");
    }

    #[test]
    fn a_terminal_without_graphics_never_reserves_cover_space() {
        let mut a = app();
        a.mode = Mode::Browsing;
        install(&mut a, books(1));
        a.covers.insert(
            a.results[0].md5.clone(),
            Slot::Ready(Box::new(Art {
                encoded: Vec::new(),
                pixels: None,
            })),
        );
        assert!(!a.cover_visible());
        press(&mut a, KeyCode::Down);
        assert!(a.cover_due.is_none(), "no protocol, no lookups");
    }

    /// A result set shaped like the Das Kapital problem: one work, many
    /// languages, formats and authors mixed together.
    fn polyglot() -> Vec<Book> {
        let entry = |i: usize, lang: &str, ext: &str, author: &str| Book {
            md5: format!("{i:032x}"),
            title: format!("Das Kapital {i}"),
            language: Some(lang.into()),
            extension: Some(ext.into()),
            authors: Some(author.into()),
            ..Default::default()
        };
        vec![
            entry(0, "German", "pdf", "Marx, Karl"),
            entry(1, "German", "epub", "Marx, Karl"),
            entry(2, "English", "epub", "Le Guin, Ursula"),
            entry(3, "German", "pdf", "Marx, Karl"),
            entry(4, "English", "pdf", "Engels, Friedrich"),
            entry(5, "Spanish", "djvu", "Le Guin, Ursula"),
        ]
    }

    #[test]
    fn the_language_picker_narrows_the_results() {
        let mut a = app();
        a.mode = Mode::Browsing;
        install(&mut a, polyglot());
        assert_eq!(a.visible.len(), 6);

        // One gesture reaches any value: open, type a fragment, Enter — no
        // stepping through the languages in between.
        pick(&mut a, 'l', "english");
        assert_eq!(a.lang_filter.as_deref(), Some("English"));
        assert_eq!(a.visible.len(), 2);
        assert!(a.visible.iter().all(|&i| a.results[i].language.as_deref() == Some("English")));

        // Reopen and take the "all" row at the top to clear it.
        press(&mut a, KeyCode::Char('l'));
        press(&mut a, KeyCode::Home);
        press(&mut a, KeyCode::Enter);
        assert_eq!(a.lang_filter, None);
        assert_eq!(a.visible.len(), 6);
    }

    #[test]
    fn open_then_enter_takes_the_most_common_value() {
        let mut a = app();
        a.mode = Mode::Browsing;
        install(&mut a, polyglot());
        // No filter set yet: the highlight opens on the top value, so the
        // quickest gesture — open, Enter — grabs the obvious pick.
        press(&mut a, KeyCode::Char('l'));
        press(&mut a, KeyCode::Enter);
        assert_eq!(a.lang_filter.as_deref(), Some("German"));
        assert_eq!(a.visible.len(), 3);
    }

    #[test]
    fn opening_a_picker_does_not_leak_keys_to_the_list() {
        let mut a = app();
        a.mode = Mode::Browsing;
        install(&mut a, polyglot());
        press(&mut a, KeyCode::Char('l')); // picker up
        assert!(a.picker.is_some());
        // A letter narrows the menu; it must not also start a search or move
        // the list underneath.
        press(&mut a, KeyCode::Char('g'));
        assert_eq!(a.picker.as_ref().unwrap().query, "g");
        press(&mut a, KeyCode::Esc);
        assert!(a.picker.is_none());
        assert_eq!(a.lang_filter, None, "esc backs out without applying");
    }

    #[test]
    fn the_author_picker_filters_by_name() {
        let mut a = app();
        a.mode = Mode::Browsing;
        install(&mut a, polyglot());
        // Three editions are Marx's; a fragment of the name is enough.
        pick(&mut a, 'a', "marx");
        assert_eq!(a.author_filter.as_deref(), Some("Marx, Karl"));
        assert_eq!(a.visible.len(), 3);
        assert!(a.visible.iter().all(|&i| a.results[i]
            .authors
            .as_deref()
            .unwrap()
            .contains("Marx")));
    }

    #[test]
    fn an_author_fragment_reaches_the_full_name() {
        let mut a = app();
        a.mode = Mode::Browsing;
        install(&mut a, polyglot());
        // "guin" is only part of the listed "Le Guin, Ursula", but typing it
        // narrows the menu to that one row and Enter commits the whole value —
        // which then matches both Le Guin editions.
        pick(&mut a, 'a', "guin");
        assert_eq!(a.author_filter.as_deref(), Some("Le Guin, Ursula"));
        assert_eq!(a.visible.len(), 2);
    }

    #[test]
    fn the_three_filters_compose_and_x_clears_them() {
        let mut a = app();
        a.mode = Mode::Browsing;
        install(&mut a, polyglot());

        pick(&mut a, 'l', "german");
        pick(&mut a, 'e', "pdf");
        pick(&mut a, 'a', "marx");
        assert_eq!(a.fmt_filter.as_deref(), Some("pdf"));
        assert_eq!(a.visible.len(), 2, "German Marx pdfs only");

        press(&mut a, KeyCode::Char('x'));
        assert!(!a.any_filter());
        assert_eq!(a.visible.len(), 6);
    }

    #[test]
    fn facet_counts_respect_the_other_filter() {
        let mut a = app();
        install(&mut a, polyglot());
        a.lang_filter = Some("English".into());
        a.refine();
        // With English active there is 1 epub and 1 pdf to offer, not 2 and 3.
        let formats = a.facet_options(Facet::Format);
        assert!(formats.iter().all(|(_, n)| *n == 1), "{formats:?}");
    }

    #[test]
    fn filters_survive_a_new_search() {
        let mut a = app();
        a.mode = Mode::Browsing;
        install(&mut a, polyglot());
        pick(&mut a, 'l', "english");
        assert_eq!(a.lang_filter.as_deref(), Some("English"));

        a.handle(Ev::Results {
            generation: 0,
            result: Ok((polyglot(), "libgen.li".into())),
        });
        assert_eq!(a.lang_filter.as_deref(), Some("English"), "a standing preference");
        assert_eq!(a.visible.len(), 2);
        assert!(a.status.contains("2 of 6"), "{}", a.status);
    }

    #[test]
    fn selection_downloads_and_marks_follow_the_visible_rows() {
        let mut a = app();
        a.mode = Mode::Browsing;
        install(&mut a, polyglot());
        pick(&mut a, 'l', "english"); // English: results 2 and 4

        assert_eq!(a.selected().map(|b| b.md5.clone()).as_deref(), Some("00000000000000000000000000000002"));
        press(&mut a, KeyCode::Down);
        assert_eq!(a.selected().map(|b| b.md5.clone()).as_deref(), Some("00000000000000000000000000000004"));
        press(&mut a, KeyCode::Down);
        assert_eq!(a.table.selected(), Some(1), "two rows showing, no further");

        // `A` marks only what is showing.
        press(&mut a, KeyCode::Char('A'));
        assert_eq!(a.marked, [false, false, true, false, true, false]);
    }

    #[test]
    fn the_filter_keeps_the_highlighted_book_when_it_survives() {
        let mut a = app();
        a.mode = Mode::Browsing;
        install(&mut a, polyglot());
        // Highlight the English pdf (index 4), then filter to pdfs: the book
        // survives the cut, so the highlight must stay on it.
        for _ in 0..4 {
            press(&mut a, KeyCode::Down);
        }
        pick(&mut a, 'e', "pdf");
        assert_eq!(a.fmt_filter.as_deref(), Some("pdf"));
        assert_eq!(
            a.selected().map(|b| b.md5.clone()).as_deref(),
            Some("00000000000000000000000000000004"),
            "the highlight should follow the book, not the row number"
        );
        assert_eq!(a.table.selected(), Some(2), "the book moved up the list");
    }

    #[test]
    fn the_filter_bar_reports_the_narrowing() {
        let mut a = app();
        a.mode = Mode::Browsing;
        install(&mut a, polyglot());
        let screen = draw(&mut a, 100, 24);
        assert!(screen.contains("6 results"), "{screen}");
        assert!(screen.contains("format"), "{screen}");
        assert!(screen.contains("language"), "{screen}");
        assert!(screen.contains("author"), "{screen}");

        pick(&mut a, 'l', "english");
        let screen = draw(&mut a, 100, 24);
        assert!(screen.contains("English"), "{screen}");
        assert!(screen.contains("2 of 6 shown"), "{screen}");
        assert!(screen.contains("clear"), "{screen}");
    }

    #[test]
    fn an_over_narrow_filter_pair_explains_itself() {
        let mut a = app();
        a.mode = Mode::Browsing;
        install(&mut a, polyglot());
        a.lang_filter = Some("Spanish".into());
        a.fmt_filter = Some("epub".into());
        a.refine();
        assert!(a.visible.is_empty());
        let screen = draw(&mut a, 100, 24);
        assert!(screen.contains("none of the 6 results"), "{screen}");
        assert!(screen.contains("epub + Spanish"), "{screen}");
        assert!(screen.contains("clears"), "{screen}");
    }

    #[test]
    fn the_selection_reads_along_the_bottom_band() {
        let mut a = app();
        a.mode = Mode::Browsing;
        install(
            &mut a,
            vec![Book {
                md5: "1b9159991f7fb1b3910c0be9ebf7e595".into(),
                title: "The Dispossessed".into(),
                authors: Some("Ursula K. Le Guin".into()),
                publisher: Some("Harper & Row".into()),
                year: Some("1974".into()),
                language: Some("English".into()),
                extension: Some("epub".into()),
                pages: Some("341".into()),
                size_bytes: Some(2 * 1024 * 1024),
                ..Default::default()
            }],
        );

        // The record for the selected row lies in the horizontal band across the
        // bottom, so the results keep the whole width — at any terminal size the
        // title, the publisher and the checksum are all there to read.
        for (w, h) in [(130u16, 40u16), (90, 24)] {
            let screen = draw(&mut a, w, h);
            assert!(screen.contains("The Dispossessed"), "{w}x{h}: {screen}");
            assert!(screen.contains("Harper & Row"), "{w}x{h}: {screen}");
            assert!(
                screen.contains("1b9159991f7fb1b3910c0be9ebf7e595"),
                "{w}x{h}: {screen}"
            );
        }
    }

    /// Render the app to styled HTML for out-of-terminal design review.
    /// Dev-only: runs when TOMESOLE_PREVIEW_DIR is set, via `--ignored`.
    #[test]
    #[ignore]
    fn dump_design_previews() {
        use ratatui::backend::TestBackend;
        use std::fmt::Write as _;

        let Some(dir) = std::env::var_os("TOMESOLE_PREVIEW_DIR") else {
            return;
        };
        let dir = std::path::PathBuf::from(dir);

        fn html(a: &mut App, width: u16, height: u16, title: &str) -> String {
            let mut terminal = Terminal::new(TestBackend::new(width, height)).unwrap();
            terminal.draw(|f| a.render(f)).unwrap();
            let buffer = terminal.backend().buffer().clone();
            let css = |c: ratatui::style::Color, fallback: &str| match c {
                Color::Rgb(r, g, b) => format!("rgb({r},{g},{b})"),
                _ => fallback.to_string(),
            };
            let mut out = format!(
                "<div class='shot'><h2>{title} <small>{width}×{height}</small></h2><pre>"
            );
            for y in 0..buffer.area.height {
                for x in 0..buffer.area.width {
                    let cell = &buffer[(x, y)];
                    let fg = css(cell.style().fg.unwrap_or(Color::Reset), "rgb(238,241,246)");
                    let bg = css(cell.style().bg.unwrap_or(Color::Reset), "rgb(16,20,27)");
                    let bold = if cell.style().add_modifier.contains(Modifier::BOLD) {
                        "font-weight:bold;"
                    } else {
                        ""
                    };
                    let symbol = cell
                        .symbol()
                        .replace('&', "&amp;")
                        .replace('<', "&lt;")
                        .replace('>', "&gt;");
                    let _ = write!(
                        out,
                        "<span style='color:{fg};background:{bg};{bold}'>{symbol}</span>"
                    );
                }
                out.push('\n');
            }
            out.push_str("</pre></div>\n");
            out
        }

        fn kapital() -> Vec<Book> {
            let b = |i: usize,
                     title: &str,
                     authors: &str,
                     publisher: &str,
                     year: &str,
                     lang: &str,
                     pages: &str,
                     size: u64,
                     ext: &str| Book {
                md5: format!("{i:032x}"),
                title: title.into(),
                authors: Some(authors.into()),
                publisher: Some(publisher.into()),
                year: Some(year.into()),
                language: Some(lang.into()),
                pages: Some(pages.into()),
                size_bytes: Some(size),
                extension: Some(ext.into()),
                file_id: None,
            };
            vec![
                b(0, "Das Kapital. Kritik der politischen Ökonomie. Erster Band", "Karl Marx", "Otto Meissner", "1867", "German", "784", 24_600_000, "pdf"),
                b(1, "Capital: A Critique of Political Economy, Volume I", "Karl Marx; Ben Fowkes (transl.)", "Penguin Classics", "1990", "English", "1152", 2_400_000, "epub"),
                b(2, "Das Kapital, Band 1", "Karl Marx", "Dietz Verlag", "1962", "German", "955", 18_100_000, "pdf"),
                b(3, "Capital, Vol. 1: A Critical Analysis of Capitalist Production", "Karl Marx; Samuel Moore", "Progress Publishers", "1887", "English", "802", 5_200_000, "pdf"),
                b(4, "Das Kapital: Kritik der politischen Ökonomie (Gesamtausgabe)", "Karl Marx; Friedrich Engels", "Akademie Verlag", "1991", "German", "1420", 41_000_000, "pdf"),
                b(5, "Capital: A Critique of Political Economy, Volume II", "Karl Marx; David Fernbach (transl.)", "Penguin Classics", "1992", "English", "624", 1_900_000, "epub"),
                b(6, "El Capital: Crítica de la economía política, Tomo I", "Karl Marx", "Siglo XXI Editores", "1975", "Spanish", "381", 9_800_000, "pdf"),
                b(7, "Das Kapital (Volksausgabe)", "Karl Marx; Karl Kautsky (ed.)", "J.H.W. Dietz", "1914", "German", "698", 31_400_000, "djvu"),
                b(8, "Капитал. Критика политической экономии. Том 1", "Карл Маркс", "Политиздат", "1983", "Russian", "905", 14_200_000, "djvu"),
                b(9, "Capital: An Abridged Edition", "Karl Marx; David McLellan (ed.)", "Oxford University Press", "2008", "English", "608", 1_100_000, "epub"),
                b(10, "Das Kapital, Band 2: Der Zirkulationsprozess des Kapitals", "Karl Marx; Friedrich Engels (ed.)", "Dietz Verlag", "1963", "German", "559", 12_700_000, "pdf"),
                b(11, "Le Capital, Livre I", "Karl Marx; Joseph Roy (trad.)", "Éditions sociales", "1976", "French", "716", 7_300_000, "pdf"),
            ]
        }

        // A plausible 2:3 jacket: a deep vertical gradient with a pale title
        // band, so the preview judges layout the way a real cover would.
        let cover = {
            let (w, h) = (120usize, 180usize);
            let mut pixels = Vec::with_capacity(w * h * 3);
            for y in 0..h {
                for x in 0..w {
                    let t = y as f32 / h as f32;
                    let (mut r, mut g, mut b) = (
                        18.0 + 60.0 * t,
                        52.0 + 30.0 * (1.0 - t),
                        84.0 + 90.0 * t,
                    );
                    if (30..48).contains(&y) {
                        (r, g, b) = (226.0, 218.0, 200.0);
                    }
                    if x < 4 {
                        (r, g, b) = (r * 0.6, g * 0.6, b * 0.6);
                    }
                    pixels.extend([r as u8, g as u8, b as u8]);
                }
            }
            graphics::Image::new(w, h, pixels)
        };
        let mut page = String::from(
            "<!doctype html><meta charset='utf-8'><style>\
             body{background:#0a0d12;color:#eef1f6;font-family:system-ui;padding:24px}\
             h2{font-weight:600;margin:32px 0 8px} h2 small{color:#8892a4;font-weight:400}\
             pre{font:13px/1.15 'SF Mono',Menlo,monospace;display:inline-block;\
                 border-radius:8px;overflow:hidden;margin:0;box-shadow:0 8px 40px rgba(0,0,0,.5)}\
             </style><h1>tomesole — TUI states</h1>",
        );

        // 1. Wide search, cover art, one download running, one saved.
        let mut a = app();
        a.mode = Mode::Browsing;
        a.mirror_label = "libgen.li".into();
        a.protocol = Protocol::Blocks;
        a.library = entries(7); // so the tab bar carries a believable count
        // The first few library entries share the leading MD5s with the search
        // results, so those editions show as already on the shelf.
        a.owned = a.library.iter().map(|e| e.md5.clone()).collect();
        install(&mut a, kapital());
        a.covers.insert(
            "00000000000000000000000000000000".into(),
            Slot::Ready(Box::new(Art {
                encoded: Vec::new(),
                pixels: Some(cover.clone()),
            })),
        );
        a.jobs.insert(
            "00000000000000000000000000000001".into(),
            Job::Saved("capital-vol-1.epub".into()),
        );
        a.jobs.insert(
            "00000000000000000000000000000003".into(),
            Job::Running {
                done: 2_400_000,
                total: Some(5_200_000),
                started: Instant::now(),
            },
        );
        a.marked[9] = true;
        page.push_str(&html(&mut a, 132, 42, "Search — wide, unfiltered"));

        // 2. The Das Kapital case: English only.
        a.lang_filter = Some("English".into());
        a.refine();
        a.covers.insert(
            "00000000000000000000000000000001".into(),
            Slot::Ready(Box::new(Art {
                encoded: Vec::new(),
                pixels: Some(cover.clone()),
            })),
        );
        page.push_str(&html(&mut a, 132, 42, "Search — filtered to English"));

        // 3. Both filters: English epubs, sorted biggest-first to show the
        // sort indicator carrying a direction.
        a.fmt_filter = Some("epub".into());
        a.sort = Sort::Size;
        a.sort_desc = true;
        a.refine();
        page.push_str(&html(&mut a, 132, 42, "Search — English epubs, by size"));

        // 4. Narrow terminal, bottom strip.
        page.push_str(&html(&mut a, 90, 28, "Search — narrow (80–100 col) layout"));

        // 5. Library: real files on disk so `present()` reports the normal
        // case, and exactly one book gone missing.
        let mut a = app();
        with_library(&mut a, {
            let mut es = entries(6);
            for (e, (t, au, ext, mb)) in es.iter_mut().zip([
                ("Capital: A Critique of Political Economy, Volume I", "Karl Marx", "epub", 2.4),
                ("The Dispossessed", "Ursula K. Le Guin", "epub", 1.1),
                ("Dune Messiah", "Frank Herbert", "epub", 0.9),
                ("The Rust Programming Language", "Steve Klabnik; Carol Nichols", "pdf", 11.2),
                ("Gödel, Escher, Bach", "Douglas Hofstadter", "djvu", 24.0),
                ("A Wizard of Earthsea", "Ursula K. Le Guin", "mobi", 0.7),
            ]) {
                e.title = t.into();
                e.authors = Some(au.into());
                e.extension = Some(ext.into());
                e.size = (mb * 1024.0 * 1024.0) as u64;
                e.path = dir.join(format!("{t}.{ext}"));
                std::fs::write(&e.path, "x").unwrap();
            }
            es
        });
        a.library[4].path = std::path::PathBuf::from("/nonexistent/missing.djvu");
        a.refilter();
        page.push_str(&html(&mut a, 100, 26, "Library — narrow"));

        // 5b. Library, wide, with the highlighted book's own cover showing —
        // the thing the file itself carries, read off disk with no network.
        a.protocol = Protocol::Blocks;
        a.library_table.select(Some(0));
        a.covers.insert(
            a.library[0].md5.clone(),
            Slot::Ready(Box::new(Art {
                encoded: Vec::new(),
                pixels: Some(cover.clone()),
            })),
        );
        page.push_str(&html(&mut a, 132, 40, "Library — wide, cover from the file"));

        // 6. Help overlay.
        let mut a = app();
        a.mode = Mode::Help;
        install(&mut a, kapital());
        page.push_str(&html(&mut a, 132, 42, "Help overlay"));

        // 7. First launch, nothing searched yet.
        let mut a = app();
        a.mode = Mode::Browsing;
        a.status = "press / to search".into();
        a.mirror_label = "libgen.li".into();
        page.push_str(&html(&mut a, 100, 26, "Empty — first launch"));

        std::fs::write(dir.join("preview.html"), page).unwrap();
    }

    #[test]
    fn job_labels_cover_every_state() {
        assert_eq!(job_label(None), "");
        assert_eq!(job_label(Some(&Job::Queued)), "queued");
        assert_eq!(job_label(Some(&Job::Saved("x".into()))), "saved");
        assert_eq!(job_label(Some(&Job::Failed("x".into()))), "failed");
        assert_eq!(
            job_label(Some(&Job::Running {
                done: 25,
                total: Some(100),
                started: Instant::now(),
            })),
            " 25%"
        );
    }

    #[test]
    fn terminal_title_is_pushed_set_and_restored() {
        let mut output = Vec::new();
        push_and_set_title(&mut output, "tomesole").unwrap();
        restore_title(&mut output).unwrap();

        assert_eq!(output, b"\x1b[22;0t\x1b]0;tomesole\x07\x1b[23;0t");
    }
}