tuigram-cli 1.0.0

Telegram in your terminal: a fast, vim-style Telegram client built on TDLib
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
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::process::{self, Stdio};
use std::time::{Duration, SystemTime};

use anyhow::Result;
use crossterm::event::{Event, EventStream, KeyCode, KeyEvent, KeyEventKind, KeyModifiers};
use futures::StreamExt;
use ratatui::DefaultTerminal;
use ratatui::style::Style;
use ratatui::widgets::Block;
use ratatui_textarea::{DataCursor, TextArea};
use tdlib_rs::enums::{
    AuthenticationCodeType, AuthorizationState, ChatList, ChatMemberStatus, MessageSender,
    NotificationType, OptionValue, Update, UserType,
};
use tdlib_rs::types::{Message, UpdateNotificationGroup};
use tokio::sync::mpsc::UnboundedReceiver;
use tokio::time::{Instant, sleep_until};

use crate::attach::{self, Attachment, Dropped};
use crate::chats::{Badge, Chats, Peer, Presence};
use crate::clipboard::{Clipboard, ClipboardEvent, Copied, Decoded, Paste, Pasted};
use crate::complete::{self, Commands, Completion, Kind, Suggestion};
use crate::config::{self, ApiKeys};
use crate::images::{ImageEvent, Images};
use crate::messages::{
    Editable, Editing, Link, MediaFile, OpenChat, Replied, SendState, Sender, link_host,
};
use crate::notify::{self, Note, Notifications, Notifier};
use crate::picker::{self, ChatPicker, Choice, Purpose};
use crate::poll::{Vote, VoteMenu};
use crate::reactions::{self, ReactMenu, ReactionKind};
use crate::search::{self, MessageSearch};
use crate::settings::{self, Settings, Side};
use crate::stickers::{self, Source, StickerPanel};
use crate::text;
use crate::tg::{Deletable, EditText, Found, Invite, Missed, Page, Tagged, Tg, TgEvent};
use crate::theme::{Colors, Themes};
use crate::ui;

/// Chats requested per `loadChats` call.
const CHAT_PAGE: i32 = 50;
/// Messages requested per `getChatHistory` call.
const HISTORY_PAGE: i32 = 50;
/// Search results requested per `searchChatMessages` call.
const SEARCH_PAGE: i32 = 50;
/// Keep requesting history until at least this many messages are loaded.
/// TDLib often answers the first request with only what it has cached.
const MIN_LOADED: usize = 30;
/// Start loading the next page when the cursor gets this close to the end.
const LOAD_AHEAD: usize = 10;
/// Rows moved by Ctrl-d / Ctrl-u.
const HALF_PAGE: isize = 10;
/// How long to wait for TDLib to flush its database on quit.
const CLOSE_TIMEOUT: Duration = Duration::from_secs(3);
/// How long a toast stays up.
const TOAST_TIME: Duration = Duration::from_secs(2);
/// A confirmation ignores `y` for this long after it comes up.
const CONFIRM_GRACE: Duration = Duration::from_millis(500);
/// Without a key press for this long, you're no longer shown as online.
const IDLE_AFTER: Duration = Duration::from_secs(60);
/// Even in a window the terminal says has focus, nothing is marked read
/// after this long without a key: the screen can be left showing while
/// nobody is at it, or the connection behind it can be gone without the
/// terminal saying so.
const AWAY_AFTER: Duration = Duration::from_secs(5 * 60);
/// While typing, the chat is told again this often: others' apps stop
/// showing it after 5.5 s without a repeat.
const TYPING_EVERY: Duration = Duration::from_secs(5);

/// Where the API key TDLib was given came from.
#[derive(Clone, Copy, PartialEq, Eq)]
enum KeySource {
    Env,
    Saved,
    BuiltIn,
}

pub enum Screen {
    Login(Box<Login>),
    Main,
}

pub enum LoginStep {
    Connecting,
    LoggingOut,
    /// First run without API credentials: ask for them, ID then hash.
    ApiId,
    ApiHash {
        id: i32,
    },
    Phone,
    Code {
        sent_via: &'static str,
    },
    Password {
        hint: String,
    },
    Email,
    EmailCode,
    OtherDevice {
        link: String,
    },
    /// A state this client can't finish; the text says what to do instead.
    Unsupported(&'static str),
}

pub struct Login {
    pub step: LoginStep,
    pub input: TextArea<'static>,
    pub error: Option<String>,
    /// A request is in flight; Enter is ignored until TDLib answers.
    pub busy: bool,
}

impl Login {
    pub fn new(step: LoginStep) -> Self {
        let mut input = TextArea::default();
        input.set_block(Block::bordered());
        input.set_cursor_line_style(Style::default());
        if let LoginStep::Password { .. } = step {
            input.set_mask_char('•');
        }
        Self {
            step,
            input,
            error: None,
            busy: false,
        }
    }

    pub fn takes_input(&self) -> bool {
        !matches!(
            self.step,
            LoginStep::Connecting
                | LoginStep::LoggingOut
                | LoginStep::OtherDevice { .. }
                | LoginStep::Unsupported(_)
        )
    }
}

/// Something in a message that Enter opens or `y` copies.
pub enum Target {
    File(MediaFile),
    Link(Link),
    /// The whole text or caption; only copied.
    Text(String),
}

impl Target {
    pub fn label(&self) -> &str {
        match self {
            Target::File(file) => &file.label,
            Target::Link(link) => &link.url,
            Target::Text(_) => "Whole message",
        }
    }
}

/// Asks before opening something that could hurt: a file that may run code,
/// or a link whose words say something other than where it goes.
pub struct Confirm {
    pub title: String,
    /// Why it asks, and what exactly would open.
    pub lines: Vec<String>,
    /// For a link: the site it goes to, on a line of its own. A site's name
    /// is at the end of its host, so a long one is cut from the left.
    pub site: Option<String>,
    /// For a chat to join: what Telegram says about it, on a line of its
    /// own at the top.
    pub badge: Option<Badge>,
    pub action: Confirmed,
    /// When it came up. A `y` in the first moments was typed for whatever
    /// was on screen before, so it doesn't count.
    pub shown: Instant,
}

impl Confirm {
    pub fn new(title: impl Into<String>, lines: Vec<String>, action: Confirmed) -> Self {
        Self {
            title: title.into(),
            lines,
            site: None,
            badge: None,
            action,
            shown: Instant::now(),
        }
    }
}

/// What `y` does in a [`Confirm`].
pub enum Confirmed {
    OpenFile(String),
    OpenLink(String),
    /// Edit this message, starting from this text, losing the formatting
    /// Markdown can't write.
    Edit {
        id: i64,
        text: String,
    },
    /// Join this public group or channel, to write in it.
    Join(i64),
    /// Join the chat this invite link leads to, then open it.
    JoinLink {
        link: String,
        request: String,
    },
    /// Leave this group or channel.
    Leave(i64),
}

impl Confirmed {
    /// What `y` does, for the key hints.
    pub fn verb(&self) -> &'static str {
        match self {
            Confirmed::OpenFile(_) | Confirmed::OpenLink(_) => "open",
            Confirmed::Edit { .. } => "edit",
            Confirmed::Join(_) | Confirmed::JoinLink { .. } => "join",
            Confirmed::Leave(_) => "leave",
        }
    }
}

/// File types that open in a viewer or player, never as a program. Anything
/// else asks first: `.exe`, `.bat`, `.command`, `.jar`, `.terminal`, `.html`
/// and many more can run code when opened.
const SAFE_TO_OPEN: &[&str] = &[
    "jpg", "jpeg", "png", "gif", "webp", "heic", "heif", "avif", "bmp", "tif", "tiff", "mp4",
    "m4v", "mov", "mkv", "webm", "avi", "3gp", "mpg", "mpeg", "mp3", "m4a", "aac", "ogg", "oga",
    "opus", "wav", "flac", "pdf", "txt", "md", "epub", "docx", "xlsx", "pptx", "odt", "ods", "odp",
    "zip", "rar", "7z", "tar", "gz", "tgz",
];

/// Whether a file opens in a viewer or player, never as a program; see
/// [`SAFE_TO_OPEN`].
fn safe_to_open(path: &str) -> bool {
    Path::new(path)
        .extension()
        .and_then(|e| e.to_str())
        .is_some_and(|e| SAFE_TO_OPEN.contains(&e.to_ascii_lowercase().as_str()))
}

/// What picking from a [`PickMenu`] does.
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum MenuAction {
    Open,
    Copy,
}

/// Menu for picking what to open or copy when a message holds several things.
pub struct PickMenu {
    pub action: MenuAction,
    pub targets: Vec<Target>,
    pub selected: usize,
}

/// A note in the corner that something worked, gone after [`TOAST_TIME`].
pub struct Toast {
    pub title: String,
    /// What it was about, e.g. what got copied.
    pub detail: String,
    pub until: Instant,
}

/// One way to delete a message.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DeleteChoice {
    Everyone,
    OnlyMe,
}

impl DeleteChoice {
    pub fn label(self) -> &'static str {
        match self {
            DeleteChoice::Everyone => "Delete for everyone",
            DeleteChoice::OnlyMe => "Delete for me",
        }
    }
}

/// The `d` popup, confirming which message goes and for whom.
pub struct DeleteMenu {
    pub message_id: i64,
    /// The message on one line, so it's clear which one is deleted.
    pub snippet: String,
    /// What TDLib allows, for everyone first as Telegram lists it. Empty
    /// until TDLib answers.
    pub choices: Vec<DeleteChoice>,
    pub selected: usize,
}

impl DeleteMenu {
    pub fn set_allowed(&mut self, deletable: Deletable) {
        self.choices = [
            (deletable.for_everyone, DeleteChoice::Everyone),
            (deletable.for_me, DeleteChoice::OnlyMe),
        ]
        .into_iter()
        .filter_map(|(allowed, choice)| allowed.then_some(choice))
        .collect();
        // The cursor starts on the choice that's easy to live with, as in
        // Telegram, and also lands there if keys typed while TDLib was still
        // answering went nowhere.
        self.selected = self
            .choices
            .iter()
            .position(|&c| c == DeleteChoice::OnlyMe)
            .unwrap_or(0);
    }
}

/// The tabs of the `?` popup.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum HelpTab {
    Shortcuts,
    Settings,
}

/// The `?` popup: every keyboard shortcut, and the settings. On the settings
/// tab, Enter or Space ticks a checkbox (notifications, gaps in the chat list
/// and in message blocks, Normal mode after sending) or picks a theme, and
/// saves it at once.
pub struct SettingsMenu {
    pub tab: HelpTab,
    /// First row shown on the shortcuts tab. Drawing keeps it in range.
    pub scroll: usize,
    /// Row on the settings tab: one of the checkboxes, then the themes from
    /// [`SettingsMenu::THEMES`] on.
    pub selected: usize,
    /// First line shown on the settings tab. Drawing moves it to show the
    /// selected row.
    pub settings_scroll: usize,
    /// How notifications went out when the popup opened, so turning them
    /// off and on again keeps the way, e.g. "bell".
    pub saved_notifications: Notifications,
}

impl SettingsMenu {
    /// The notifications row, the first one.
    pub const NOTIFICATIONS: usize = 0;
    /// The "gap between chats" row.
    pub const CHAT_GAPS: usize = Self::NOTIFICATIONS + 1;
    /// The "chat list on the right" row.
    pub const LIST_RIGHT: usize = Self::CHAT_GAPS + 1;
    /// The "gap between messages" row.
    pub const BLOCK_GAPS: usize = Self::LIST_RIGHT + 1;
    /// The "Normal mode after sending" row.
    pub const AFTER_SEND: usize = Self::BLOCK_GAPS + 1;
    /// The first theme's row. The themes come last, since the user's own
    /// can make a long list.
    pub const THEMES: usize = Self::AFTER_SEND + 1;

    /// Opens on `tab` with the cursor on the first setting.
    pub fn new(tab: HelpTab, settings: &Settings) -> Self {
        Self {
            tab,
            scroll: 0,
            selected: 0,
            settings_scroll: 0,
            saved_notifications: settings.notifications,
        }
    }
}

/// What the status bar prompt is for: a `/` search through chat titles or the
/// open chat's messages, a `:` command, or the path of a file to attach (`a`).
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum PromptKind {
    Chats,
    Messages,
    Command,
    Attach,
}

/// The prompt in the status bar. Searching chats filters the list as you
/// type; searching messages asks TDLib on Enter, and so does a command.
pub struct Prompt {
    pub kind: PromptKind,
    pub input: TextArea<'static>,
    /// What the last Tab found in the attach prompt, when it was more than
    /// one name. Typing clears it.
    pub completions: Vec<String>,
    /// The chat filter and cursor from before, which Esc puts back.
    previous_filter: String,
    previous_selected: Option<i64>,
}

impl Prompt {
    pub fn query(&self) -> String {
        self.input.lines().concat()
    }
}

/// A chat being looked up to open, with `s` or from a t.me link.
pub struct Finding {
    /// What's looked up (a username, a link, a contact's name), for the
    /// status bar and to match TDLib's answer.
    pub request: String,
    /// The link in a message it came from, which a browser opens instead
    /// if tuigram can't.
    pub link: Option<Link>,
}

impl Finding {
    fn new(request: &str) -> Self {
        Self {
            request: request.to_string(),
            link: None,
        }
    }
}

/// What `:` runs. There are no abbreviations: only the full name runs, so a
/// typo can't log you out.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Command {
    Leave,
    Logout,
}

impl Command {
    pub const ALL: [Command; 2] = [Command::Leave, Command::Logout];

    pub fn name(self) -> &'static str {
        match self {
            Command::Leave => "leave",
            Command::Logout => "logout",
        }
    }

    pub fn about(self) -> &'static str {
        match self {
            Command::Leave => "Leave this group or channel (asks first)",
            Command::Logout => "Log out of Telegram on this computer",
        }
    }

    pub fn parse(text: &str) -> Option<Command> {
        Command::ALL.into_iter().find(|c| c.name() == text)
    }
}

/// Where keys go. `Input` is Insert mode; the others are Normal mode.
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum Focus {
    Chats,
    Messages,
    Input,
}

pub struct App {
    tg: Tg,
    pub screen: Screen,
    pub focus: Focus,
    pub chats: Chats,
    /// Display names by user id, for message senders in groups.
    pub users: HashMap<i64, String>,
    /// Selected chat id, not index, so the cursor stays put when chats reorder.
    pub selected: Option<i64>,
    pub open: Option<OpenChat>,
    /// The message being written. Cleared when switching chats.
    pub composer: TextArea<'static>,
    pub images: Images,
    /// Files being downloaded to open in their default app when done.
    pub opening: HashSet<i32>,
    clipboard: Clipboard,
    /// Files being downloaded to copy when done, by file id.
    pub copying: HashMap<i32, MediaFile>,
    /// The clipboard is being read for `p`.
    pub pasting: bool,
    pub toast: Option<Toast>,
    /// Shown over everything when Enter or `y` finds several things.
    pub menu: Option<PickMenu>,
    pub delete_menu: Option<DeleteMenu>,
    pub react_menu: Option<ReactMenu>,
    /// Enter on a poll: its answers to vote for.
    pub vote_menu: Option<VoteMenu>,
    /// `f` to forward a message, or `s` to find a chat to open.
    pub picker: Option<ChatPicker>,
    /// A chat being looked up to open. Opening another chat meanwhile
    /// drops the answer.
    pub finding: Option<Finding>,
    /// Suggestions for the `@name` or `:emoji` being typed; only in Insert
    /// mode.
    pub completion: Option<Completion>,
    /// Opened with Tab while writing; only open in Insert mode.
    pub stickers: Option<StickerPanel>,
    /// In resize mode (Ctrl-r): the chat list's width before, which Esc
    /// puts back.
    pub resizing: Option<u16>,
    pub confirm: Option<Confirm>,
    pub settings: Settings,
    settings_path: PathBuf,
    /// Every theme, read again whenever `?` opens, so changes to a file show.
    pub themes: Themes,
    /// The colors of the theme in use.
    pub colors: Colors,
    /// You have Telegram Premium, so Premium stickers can be sent.
    premium: bool,
    /// API credentials from the environment, which win over saved ones.
    env_keys: Option<ApiKeys>,
    /// The key TDLib has; `None` until it gets one.
    keys_source: Option<KeySource>,
    /// Telegram refused the built-in key, so it isn't offered to TDLib again.
    built_in_rejected: bool,
    pub settings_menu: Option<SettingsMenu>,
    /// Shown in the status bar while typing a `/` search.
    pub prompt: Option<Prompt>,
    pub chats_loading: bool,
    all_chats_loaded: bool,
    /// Last error, shown in the status bar until the next key press.
    pub status: Option<String>,
    /// First `g` of `gg` was pressed.
    pending_g: bool,
    /// Set once quitting started; we exit at this time even if TDLib never answers.
    pub quit_deadline: Option<Instant>,
    /// The terminal window has focus. Terminals that don't report focus
    /// changes leave this on.
    terminal_focused: bool,
    /// The terminal has reported a focus change, so `terminal_focused` can
    /// be trusted.
    focus_reported: bool,
    /// The last key press or paste, or the window getting focus.
    last_input: Instant,
    /// The same moment by the wall clock. `Instant` stops while the computer
    /// sleeps, so after a wake only this one shows how long you were away.
    last_input_wall: SystemTime,
    /// What TDLib was last told: shown as online to others.
    online: bool,
    /// The chat last told you're typing, and when. `None` once it was told
    /// you stopped.
    typing: Option<(i64, Instant)>,
    /// Tells the user about new messages while they're away from tuigram.
    notifier: Notifier,
    /// How notifications reach this terminal (never `Auto`).
    notify_with: Notifications,
    /// Inside tmux, which passes codes on only when they're wrapped.
    in_tmux: bool,
    /// Counts notifications sent, to tell them apart.
    notifications_sent: u64,
    /// Messages from before this (unix time) aren't announced: they came in
    /// while tuigram wasn't running.
    notify_since: i32,
    /// Unmuted chats with unread messages, shown in the window title.
    unread_chats: i32,
    /// TDLib is logging out (`:logout`, the session ended elsewhere, or
    /// leaving a QR login), and a new client takes over once it has closed.
    relogin: bool,
    exit: bool,
}

impl App {
    pub fn new(
        tg: Tg,
        images: Images,
        clipboard: Clipboard,
        settings: Settings,
        settings_path: PathBuf,
        env_keys: Option<ApiKeys>,
    ) -> Self {
        let mut chats = Chats::default();
        chats.set_highlighted(&settings.highlighted_chats);
        let notify_with = settings
            .notifications
            .resolve(|name| std::env::var(name).ok());
        let mut app = Self {
            tg,
            screen: login_screen(LoginStep::Connecting),
            focus: Focus::Chats,
            chats,
            users: HashMap::new(),
            selected: None,
            open: None,
            composer: new_composer(),
            images,
            opening: HashSet::new(),
            clipboard,
            copying: HashMap::new(),
            pasting: false,
            toast: None,
            menu: None,
            delete_menu: None,
            react_menu: None,
            vote_menu: None,
            picker: None,
            finding: None,
            completion: None,
            stickers: None,
            resizing: None,
            confirm: None,
            settings,
            themes: Themes::load(&settings_path.with_file_name("themes")),
            settings_path,
            colors: Colors::default(),
            premium: false,
            env_keys,
            keys_source: None,
            built_in_rejected: false,
            settings_menu: None,
            prompt: None,
            chats_loading: false,
            all_chats_loaded: false,
            // Only development builds read `.env`; someone expecting it to
            // pick a separate session should know this one didn't.
            status: config::dotenv_ignored()
                .then(|| "./.env is ignored: only development builds read it".into()),
            pending_g: false,
            quit_deadline: None,
            terminal_focused: true,
            focus_reported: false,
            last_input: Instant::now(),
            last_input_wall: SystemTime::now(),
            online: false,
            typing: None,
            notifier: Notifier::default(),
            notify_with,
            in_tmux: std::env::var_os("TMUX").is_some(),
            notifications_sent: 0,
            notify_since: i32::MAX,
            unread_chats: 0,
            relogin: false,
            exit: false,
        };
        app.use_saved_theme();
        app
    }

    /// Uses the theme the settings name, or the default one, saying why, if
    /// it can't be used: a broken file never leaves the app unreadable. The
    /// setting stays, so fixing the file is enough.
    fn use_saved_theme(&mut self) {
        match self.themes.colors(&self.settings.theme) {
            Ok(colors) => self.colors = colors,
            Err(e) => {
                self.colors = Colors::default();
                self.status = Some(format!("Theme not used: {e}"));
            }
        }
    }

    pub async fn run(
        mut self,
        terminal: &mut DefaultTerminal,
        mut events: UnboundedReceiver<Tagged>,
        mut image_events: UnboundedReceiver<ImageEvent>,
        mut clipboard: UnboundedReceiver<ClipboardEvent>,
    ) -> Result<()> {
        let mut keys = EventStream::new();
        let mut signals = quit_signals();
        // What broke the terminal, if it went away: the app then closes as
        // `q` closes it, without drawing, and returns this.
        let mut failed: Option<anyhow::Error> = None;
        while !self.exit {
            if self
                .toast
                .as_ref()
                .is_some_and(|t| t.until <= Instant::now())
            {
                self.toast = None;
            }
            self.chats.refresh();
            if self
                .selected
                .is_none_or(|id| !self.chats.ids().contains(&id))
            {
                self.selected = self.chats.ids().first().copied();
            }
            self.mark_seen();
            self.update_online();
            self.send_notification();
            if let Some(query) = self
                .picker
                .as_mut()
                .and_then(|p| p.due_search(Instant::now()))
            {
                self.tg.find_chats(query);
            }
            if let Some(open) = &self.open
                && let Some(query) = self
                    .completion
                    .as_mut()
                    .and_then(|c| c.due_search(Instant::now()))
            {
                self.tg.find_members(open.chat_id, query);
            }
            if failed.is_none()
                && let Err(e) = terminal.draw(|frame| ui::draw(frame, &mut self))
            {
                failed = Some(e.into());
                self.hang_up();
            }
            // Start downloads/encodes for photos the frame showed but didn't have.
            self.images.fetch(&self.tg);
            if let Some(open) = self.open.as_mut() {
                for id in open.missing_replied() {
                    self.tg.get_replied_message(open.chat_id, id);
                }
            }

            let deadline = self.quit_deadline;
            // Wakes up to take the toast down, to go offline when idle, to
            // send notifications that had to wait, and to search Telegram
            // once typing in the `s` picker pauses.
            let wake = [
                self.toast.as_ref().map(|t| t.until),
                self.online.then_some(self.last_input + IDLE_AFTER),
                self.notifier.next_at(),
                self.picker.as_ref().and_then(ChatPicker::search_at),
                self.completion.as_ref().and_then(Completion::search_at),
            ]
            .into_iter()
            .flatten()
            .min();
            tokio::select! {
                Some(event) = events.recv() => {
                    self.on_tagged(event);
                    // Drain the backlog so a burst of updates costs one redraw.
                    while let Ok(event) = events.try_recv() {
                        self.on_tagged(event);
                    }
                }
                Some(event) = image_events.recv() => self.images.on_built(event),
                Some(event) = clipboard.recv() => self.on_clipboard(event),
                Some(event) = keys.next(), if failed.is_none() => match event {
                    Ok(event) => self.on_terminal_event(event),
                    Err(e) => {
                        failed = Some(e.into());
                        self.hang_up();
                    }
                },
                Some(()) = signals.recv() => self.hang_up(),
                _ = sleep_until(deadline.unwrap_or_else(Instant::now)), if deadline.is_some() => break,
                _ = sleep_until(wake.unwrap_or_else(Instant::now)), if wake.is_some() => {}
                else => break,
            }
        }
        match failed {
            Some(e) => Err(e),
            None => Ok(()),
        }
    }

    /// The terminal is gone (a closed window, a dropped SSH connection), or
    /// tuigram was told to stop: nobody is reading any more, so nothing more
    /// is marked read, and it quits as `q` does, going offline first.
    fn hang_up(&mut self) {
        self.terminal_focused = false;
        self.focus_reported = true;
        if self.quit_deadline.is_none() {
            self.quit();
        }
    }

    fn on_terminal_event(&mut self, event: Event) {
        if matches!(event, Event::Key(_) | Event::Paste(_) | Event::FocusGained) {
            self.last_input = Instant::now();
            self.last_input_wall = SystemTime::now();
        }
        match event {
            Event::Key(key) => self.on_key(key),
            Event::FocusGained => {
                self.terminal_focused = true;
                self.focus_reported = true;
                // Back at tuigram: what was waiting is on screen.
                self.notifier.clear();
            }
            Event::FocusLost => {
                self.terminal_focused = false;
                self.focus_reported = true;
            }
            Event::Paste(text) if matches!(self.screen, Screen::Login(_)) => {
                if let Screen::Login(login) = &mut self.screen
                    && login.takes_input()
                {
                    login.input.insert_str(text.trim());
                }
            }
            Event::Paste(text) if self.picker.is_some() => {
                // A pasted link or name goes into the search, on one line.
                let text = text::clean(&text).replace(['\n', '\t'], " ");
                if let Some(picker) = self.picker.as_mut() {
                    picker.edit_query(|q| q.push_str(text.trim()), Instant::now());
                }
            }
            Event::Paste(text) if self.prompt.is_some() => {
                if let Some(prompt) = self.prompt.as_mut() {
                    prompt.input.insert_str(text.replace(['\r', '\n'], " "));
                }
                self.on_prompt_edit();
            }
            Event::Paste(text) if matches!(self.focus, Focus::Input | Focus::Messages) => {
                self.on_paste(text)
            }
            _ => {}
        }
    }

    /// Late events from a client replaced after logging out are dropped: a
    /// download or error from the old session would land in the new one.
    fn on_tagged(&mut self, (client_id, event): Tagged) {
        if client_id == self.tg.client_id() {
            self.on_tg(event);
        }
    }

    fn on_tg(&mut self, event: TgEvent) {
        match event {
            TgEvent::Update(update) => self.on_update(*update),
            TgEvent::Error(message) if message.contains("API_ID") => self.reject_api_keys(),
            TgEvent::Error(message) => match &mut self.screen {
                Screen::Login(login) => {
                    login.busy = false;
                    login.error = Some(message);
                }
                Screen::Main => self.status = Some(message),
            },
            TgEvent::ChatsLoaded { all, failed } => {
                self.chats_loading = false;
                self.all_chats_loaded |= all;
                // Unread chats go first wherever Telegram has them, so every
                // chat has to be loaded. After an error, scrolling to the end
                // of the list tries again.
                if !failed {
                    self.load_more_chats();
                }
            }
            TgEvent::History {
                chat_id,
                page,
                messages,
            } => self.on_history(chat_id, page, messages),
            TgEvent::Found {
                chat_id,
                query,
                found,
            } => self.on_found(chat_id, &query, found),
            TgEvent::Replied {
                chat_id,
                message_id,
                replied,
            } => {
                if let Some(open) = self.open.as_mut().filter(|o| o.chat_id == chat_id) {
                    open.set_replied(message_id, replied.map(|m| *m));
                }
            }
            TgEvent::Deletable {
                chat_id,
                message_id,
                deletable,
            } => self.on_deletable(chat_id, message_id, deletable),
            TgEvent::Editable {
                chat_id,
                message_id,
                editable,
                text,
            } => self.on_editable(chat_id, message_id, editable, text),
            TgEvent::Reactions {
                chat_id,
                message_id,
                available,
            } => self.on_available_reactions(chat_id, message_id, available),
            TgEvent::Stickers { source, stickers } => self.on_stickers(source, stickers),
            TgEvent::StickerSets(sets) => {
                if let Some(panel) = self.stickers.as_mut() {
                    panel.set_sets(sets.unwrap_or_default());
                    self.load_sticker_set();
                }
            }
            TgEvent::StickersFound { query, stickers } => {
                let premium = self.premium;
                if let Some(panel) = self.stickers.as_mut() {
                    // After an error, TDLib's message is in the status bar.
                    let found = stickers::convert(&stickers.unwrap_or_default(), premium);
                    panel.set_found(&query, found);
                }
            }
            TgEvent::Downloaded { file_id, path } => {
                if self.opening.remove(&file_id) {
                    match &path {
                        Some(path) => self.open_downloaded(path.clone()),
                        None => self.status = Some("Download failed".into()),
                    }
                }
                if let Some(file) = self.copying.remove(&file_id) {
                    match &path {
                        // Pasted in a file manager, the copy keeps the mark,
                        // as the file would if opened with Enter.
                        Some(path) => {
                            mark_downloaded(path);
                            self.copy_downloaded(file, path)
                        }
                        None => self.status = Some("Download failed".into()),
                    }
                }
                self.images.on_downloaded(file_id, path);
            }
            TgEvent::Members {
                chat_id,
                query,
                user_ids,
            } => {
                let open = self.open.as_ref().is_some_and(|o| o.chat_id == chat_id);
                let Some(completion) = self.completion.as_mut().filter(|_| open) else {
                    return;
                };
                if completion.set_found(&query, user_ids) {
                    let (query, found) = (completion.word.query.clone(), completion.found.clone());
                    let items = self.mention_items(&query, &found);
                    if let Some(completion) = self.completion.as_mut() {
                        completion.set_items(items);
                    }
                }
            }
            TgEvent::Commands { chat_id, commands } => {
                let Some(open) = self.open.as_mut().filter(|o| o.chat_id == chat_id) else {
                    return;
                };
                open.commands = Commands::Known(commands);
                let query = self
                    .completion
                    .as_ref()
                    .filter(|c| c.word.kind == Kind::Command)
                    .map(|c| c.word.query.clone());
                if let Some(query) = query {
                    let items = self.command_items(&query);
                    if let Some(completion) = self.completion.as_mut() {
                        completion.set_items(items);
                    }
                }
            }
            TgEvent::ChatsFound {
                query,
                chat_ids,
                user_ids,
            } => {
                if let Some(picker) = self.picker.as_mut() {
                    picker.set_found(&query, chat_ids, user_ids);
                }
            }
            TgEvent::ChatFound { request, found } => {
                // Dropped if another chat was opened meanwhile.
                if !self.finding.as_ref().is_some_and(|f| f.request == request) {
                    return;
                }
                let link = self.finding.take().and_then(|f| f.link);
                // Not while the keys go somewhere (writing, a popup): what
                // was typed would land in the other chat, or a popup act
                // on it.
                if self.busy() {
                    if found.is_ok() {
                        self.status = Some(format!("Found {request}: press s to open it"));
                    }
                    return;
                }
                match (found, link) {
                    (Ok((chat_id, message_id)), _) => {
                        self.open_chat(chat_id);
                        if let Some(id) = message_id {
                            self.jump_to_message(id);
                        }
                    }
                    (Err(Missed::Quiet), _) => {}
                    (Err(Missed::Said(why)), _) => self.status = Some(why),
                    // A link in a message goes to the browser, as before.
                    (Err(Missed::Elsewhere), Some(link)) => self.open_link_outside(link),
                    (Err(Missed::Elsewhere), None) => {
                        self.status = Some("tuigram can't open this kind of link".into());
                    }
                }
            }
            TgEvent::Forwarded { chat_id } => {
                let title = self.chats.title(chat_id).unwrap_or_default().to_string();
                self.show_toast("Forwarded", &format!("to {title}"));
            }
            TgEvent::Joined { chat_id } => {
                let title = self.chats.title(chat_id).unwrap_or_default().to_string();
                self.show_toast("Joined", &title);
            }
            TgEvent::Left { chat_id } => {
                let title = self.chats.title(chat_id).unwrap_or_default().to_string();
                self.show_toast("Left", &title);
            }
            TgEvent::Invite {
                request,
                link,
                invite,
            } => {
                if self.finding.as_ref().is_some_and(|f| f.request == request) && !self.busy() {
                    self.confirm_invite(link, request, invite);
                }
            }
        }
    }

    fn on_history(
        &mut self,
        chat_id: i64,
        page: Page,
        messages: Option<Vec<tdlib_rs::types::Message>>,
    ) {
        // Ignore pages for a chat that was closed, or a request that was
        // replaced (e.g. by jumping elsewhere), while it was in flight.
        let Some(open) = self
            .open
            .as_mut()
            .filter(|o| o.chat_id == chat_id && o.loading == Some(page))
        else {
            return;
        };
        open.loading = None;
        let Some(messages) = messages else {
            return;
        };
        open.add_page(
            page,
            messages.into_iter().map(|m| (m.id, m.into())).collect(),
        );
        if open.messages.len() < MIN_LOADED {
            self.load_older_messages();
        }
    }

    fn on_found(&mut self, chat_id: i64, query: &str, found: Option<Found>) {
        // Ignore results for a search that was replaced or ended meanwhile.
        let Some(open) = self.open.as_mut().filter(|o| o.chat_id == chat_id) else {
            return;
        };
        let Some(search) = open
            .search
            .as_mut()
            .filter(|s| s.query == query && s.loading)
        else {
            return;
        };
        search.loading = false;
        let wanted = search.wanted.take();
        match found {
            Some(found) => {
                search.add(found);
                if let Some(index) = wanted {
                    self.go_to_match(index);
                }
            }
            // The error is in the status bar. Without a match, end the search.
            None if search.results.is_empty() => open.search = None,
            None => {}
        }
    }

    fn on_update(&mut self, update: Update) {
        match update {
            Update::AuthorizationState(u) => self.on_auth_state(u.authorization_state),
            Update::NewChat(u) => self.chats.insert(u.chat),
            Update::ChatPosition(u) => self.chats.set_position(u.chat_id, &u.position),
            Update::ChatLastMessage(u) => {
                self.chats
                    .set_last_message(u.chat_id, u.last_message.as_ref(), &u.positions)
            }
            Update::ChatTitle(u) => self.chats.set_title(u.chat_id, u.title),
            Update::ChatNotificationSettings(u) => self
                .chats
                .set_notifications(u.chat_id, u.notification_settings),
            Update::ScopeNotificationSettings(u) => self
                .chats
                .set_default_mute(&u.scope, u.notification_settings.mute_for),
            Update::ChatAction(u) => self.chats.set_action(u.chat_id, &u.sender_id, &u.action),
            Update::NotificationGroup(u) => self.on_notifications(u),
            Update::UnreadChatCount(u) if matches!(u.chat_list, ChatList::Main) => {
                self.set_unread_chats(u.unread_unmuted_count)
            }
            Update::ChatPhoto(u) => self.chats.set_photo(u.chat_id, u.photo.as_ref()),
            Update::ChatAccentColors(u) => self.chats.set_accent(u.chat_id, u.accent_color_id),
            Update::AccentColors(u) => self.chats.set_accent_colors(&u.colors),
            Update::ChatReadInbox(u) => self.chats.set_unread(u.chat_id, u.unread_count),
            Update::ChatReadOutbox(u) => {
                self.chats
                    .set_read_outbox(u.chat_id, u.last_read_outbox_message_id);
            }
            // TDLib drops the option, rather than setting it false, when
            // Premium ends.
            Update::Option(u) if u.name == "is_premium" => {
                self.premium = matches!(u.value, OptionValue::Boolean(v) if v.value);
            }
            Update::Option(u) if u.name == "my_id" => {
                if let OptionValue::Integer(v) = u.value {
                    self.chats.set_my_id(v.value);
                }
            }
            Update::User(u) => {
                let name = format!("{} {}", u.user.first_name, u.user.last_name);
                self.users.insert(u.user.id, text::clean(name.trim()));
                let badge = Badge::of(u.user.verification_status.as_ref(), u.user.is_support);
                self.chats.set_badge(Peer::User(u.user.id), badge);
                self.chats
                    .set_username(Peer::User(u.user.id), u.user.usernames.as_ref());
                self.chats
                    .set_presence(u.user.id, Presence::of(&u.user.status));
                let bot = matches!(u.user.r#type, UserType::Bot(_));
                self.chats.set_bot(u.user.id, bot);
            }
            Update::UserStatus(u) => {
                self.chats.set_presence(u.user_id, Presence::of(&u.status));
            }
            Update::Supergroup(u) => {
                let group = &u.supergroup;
                let badge = Badge::of(group.verification_status.as_ref(), false);
                self.chats.set_badge(Peer::Supergroup(group.id), badge);
                self.chats
                    .set_username(Peer::Supergroup(group.id), group.usernames.as_ref());
                let member = !matches!(group.status, ChatMemberStatus::Left);
                self.chats.set_member(group.id, member);
            }
            Update::NewMessage(u) => {
                // While older messages are shown, new ones load with the rest.
                if let Some(open) = self
                    .open
                    .as_mut()
                    .filter(|o| o.chat_id == u.message.chat_id && o.at_newest)
                {
                    open.insert(u.message);
                }
            }
            Update::MessageSendSucceeded(u) => {
                if let Some(open) = self
                    .open
                    .as_mut()
                    .filter(|o| o.chat_id == u.message.chat_id)
                {
                    open.replace(u.old_message_id, u.message);
                }
            }
            Update::MessageSendFailed(u) => {
                self.status = Some(format!("Message not sent: {}", u.error.message));
                if let Some(open) = self
                    .open
                    .as_mut()
                    .filter(|o| o.chat_id == u.message.chat_id)
                {
                    open.replace(u.old_message_id, u.message);
                }
            }
            Update::File(u) => {
                if let Some(open) = self.open.as_mut() {
                    open.set_upload(&u.file);
                }
            }
            Update::MessageContent(u) => {
                if let Some(open) = self.open.as_mut().filter(|o| o.chat_id == u.chat_id) {
                    open.set_content(u.message_id, &u.new_content);
                }
            }
            Update::MessageEdited(u) => {
                if let Some(open) = self.open.as_mut().filter(|o| o.chat_id == u.chat_id) {
                    open.set_edited(u.message_id);
                }
            }
            Update::MessageInteractionInfo(u) => {
                if let Some(open) = self.open.as_mut().filter(|o| o.chat_id == u.chat_id) {
                    open.set_reactions(u.message_id, u.interaction_info.as_ref());
                }
            }
            Update::DeleteMessages(u) if u.is_permanent => {
                if let Some(open) = self.open.as_mut().filter(|o| o.chat_id == u.chat_id) {
                    open.remove(&u.message_ids);
                }
            }
            _ => {}
        }
    }

    fn on_auth_state(&mut self, state: AuthorizationState) {
        let step = match state {
            AuthorizationState::WaitTdlibParameters => match self.api_keys() {
                Some((source, keys)) => {
                    self.keys_source = Some(source);
                    self.tg.set_tdlib_parameters(keys);
                    return;
                }
                None => LoginStep::ApiId,
            },
            AuthorizationState::WaitPhoneNumber => LoginStep::Phone,
            AuthorizationState::WaitCode(s) => LoginStep::Code {
                sent_via: code_destination(&s.code_info.r#type),
            },
            AuthorizationState::WaitPassword(s) => LoginStep::Password {
                hint: s.password_hint,
            },
            AuthorizationState::WaitEmailAddress(_) => LoginStep::Email,
            AuthorizationState::WaitEmailCode(_) => LoginStep::EmailCode,
            AuthorizationState::WaitOtherDeviceConfirmation(s) => {
                LoginStep::OtherDevice { link: s.link }
            }
            AuthorizationState::WaitRegistration(_) => LoginStep::Unsupported(
                "This number has no Telegram account. Sign up in the official app first.",
            ),
            AuthorizationState::WaitPremiumPurchase(_) => LoginStep::Unsupported(
                "Telegram requires a Premium purchase to log in with this number. Use the official app.",
            ),
            AuthorizationState::Ready => {
                self.screen = Screen::Main;
                self.load_more_chats();
                // Even when they're off: they can be turned on any time.
                self.tg.enable_notifications();
                self.notify_since = unix_now();
                return;
            }
            // Also when the session was ended from another device: back to
            // the login screen instead of quitting.
            AuthorizationState::LoggingOut => {
                self.relogin = true;
                if let Screen::Login(_) = self.screen {
                    return;
                }
                LoginStep::LoggingOut
            }
            AuthorizationState::Closing => return,
            AuthorizationState::Closed if self.relogin && self.quit_deadline.is_none() => {
                self.relogin = false;
                self.keys_source = None;
                self.forget_session();
                self.tg.reopen();
                self.screen = login_screen(LoginStep::Connecting);
                return;
            }
            AuthorizationState::Closed => {
                self.exit = true;
                return;
            }
        };
        self.screen = login_screen(step);
    }

    fn on_key(&mut self, key: KeyEvent) {
        if key.kind != KeyEventKind::Press {
            return;
        }
        let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
        // Not while typing: in Insert mode, the prompt, or the picker's search.
        if ctrl
            && key.code == KeyCode::Char('c')
            && self.focus != Focus::Input
            && self.prompt.is_none()
            && self.picker.is_none()
        {
            self.quit();
            return;
        }
        self.status = None;
        match self.screen {
            Screen::Login(_) => self.on_login_key(key),
            Screen::Main if self.confirm.is_some() => self.on_confirm_key(key),
            Screen::Main if self.settings_menu.is_some() => self.on_settings_key(key, ctrl),
            Screen::Main if self.delete_menu.is_some() => self.on_delete_key(key),
            Screen::Main if self.react_menu.is_some() => self.on_react_key(key, ctrl),
            Screen::Main if self.vote_menu.is_some() => self.on_vote_key(key),
            Screen::Main if self.menu.is_some() => self.on_menu_key(key),
            Screen::Main if self.picker.is_some() => self.on_picker_key(key, ctrl),
            Screen::Main if self.resizing.is_some() => self.on_resize_key(key, ctrl),
            Screen::Main if self.prompt.is_some() => self.on_prompt_key(key, ctrl),
            Screen::Main if self.focus == Focus::Input && self.stickers.is_some() => {
                self.on_sticker_key(key, ctrl)
            }
            Screen::Main if self.focus == Focus::Input => self.on_insert_key(key, ctrl),
            Screen::Main => self.on_normal_key(key, ctrl),
        }
        // The sticker panel and suggestions are part of Insert mode, and
        // close with it.
        if self.focus != Focus::Input {
            self.stickers = None;
            self.completion = None;
        }
        // Writing or a popup means you moved on: a chat still being looked
        // up won't open over it.
        if self.busy() {
            self.finding = None;
        }
    }

    fn on_login_key(&mut self, key: KeyEvent) {
        let Screen::Login(login) = &mut self.screen else {
            return;
        };
        match (&login.step, key.code) {
            (LoginStep::Phone, KeyCode::Tab) if !login.busy => {
                login.busy = true;
                login.error = None;
                self.tg.request_qr_code();
                return;
            }
            (LoginStep::OtherDevice { .. }, KeyCode::Esc) => {
                self.tg.log_out();
                self.relogin = true;
                self.screen = login_screen(LoginStep::Connecting);
                return;
            }
            _ => {}
        }
        if !login.takes_input() {
            return;
        }
        if key.code != KeyCode::Enter {
            login.input.input(key);
            return;
        }
        let value = login.input.lines().concat().trim().to_string();
        if value.is_empty() || login.busy {
            return;
        }
        // API credentials are checked here; TDLib only gets them once both are in.
        match login.step {
            LoginStep::ApiId => {
                match config::parse_api_id(&value) {
                    Some(id) => self.screen = login_screen(LoginStep::ApiHash { id }),
                    None => login.error = Some("The API ID is a number, like 1234567".into()),
                }
                return;
            }
            LoginStep::ApiHash { id } => {
                if !config::is_api_hash(&value) {
                    login.error = Some("The API hash is 32 letters and digits".into());
                    return;
                }
                let keys = ApiKeys { id, hash: value };
                self.settings.api_keys = Some(keys.clone());
                if let Err(e) = self.settings.save(&self.settings_path) {
                    login.error = Some(format!("Couldn't save them: {e:#}"));
                    return;
                }
                if self.keys_source.is_some() {
                    // TDLib only takes a key at startup, so a new client
                    // starts with the saved one.
                    self.relogin = true;
                    self.tg.close();
                } else {
                    self.keys_source = Some(KeySource::Saved);
                    self.tg.set_tdlib_parameters(keys);
                }
                self.screen = login_screen(LoginStep::Connecting);
                return;
            }
            _ => {}
        }
        login.busy = true;
        login.error = None;
        match login.step {
            LoginStep::Phone => self.tg.send_phone_number(value),
            LoginStep::Code { .. } => self.tg.send_code(value),
            LoginStep::Password { .. } => self.tg.send_password(value),
            LoginStep::Email => self.tg.send_email(value),
            LoginStep::EmailCode => self.tg.send_email_code(value),
            LoginStep::Connecting
            | LoginStep::LoggingOut
            | LoginStep::ApiId
            | LoginStep::ApiHash { .. }
            | LoginStep::OtherDevice { .. }
            | LoginStep::Unsupported(_) => {}
        }
    }

    /// The API key to start TDLib with: from the environment, else saved,
    /// else the one release binaries come with.
    fn api_keys(&self) -> Option<(KeySource, ApiKeys)> {
        let built_in = config::built_in_keys().filter(|_| !self.built_in_rejected);
        let env = self.env_keys.clone().map(|k| (KeySource::Env, k));
        env.or_else(|| {
            self.settings
                .api_keys
                .clone()
                .map(|k| (KeySource::Saved, k))
        })
        .or_else(|| built_in.map(|k| (KeySource::BuiltIn, k)))
    }

    /// Telegram refused the API credentials (`API_ID_INVALID`, or
    /// `API_ID_PUBLISHED_FLOOD` for a key it blocked). On the login screen,
    /// it asks for another key, which a new client then starts with.
    fn reject_api_keys(&mut self) {
        let message = match self.keys_source {
            Some(KeySource::Env) => "Telegram rejected TG_API_ID / TG_API_HASH.".to_string(),
            Some(KeySource::BuiltIn) => {
                self.built_in_rejected = true;
                "Telegram rejected tuigram's built-in key. Use your own.".into()
            }
            Some(KeySource::Saved) | None => {
                self.settings.api_keys = None;
                match self.settings.save(&self.settings_path) {
                    Ok(()) => "Telegram rejected that API ID and hash.".into(),
                    Err(e) => format!("Telegram rejected the API key; can't forget it: {e:#}"),
                }
            }
        };
        match &mut self.screen {
            Screen::Login(_) if self.keys_source != Some(KeySource::Env) => {
                let mut login = Login::new(LoginStep::ApiId);
                login.error = Some(message);
                self.screen = Screen::Login(Box::new(login));
            }
            Screen::Login(login) => {
                login.busy = false;
                login.error = Some(message);
            }
            Screen::Main => self.status = Some(message),
        }
    }

    /// Normal mode: every key is a command, nothing is typed.
    fn on_normal_key(&mut self, key: KeyEvent, ctrl: bool) {
        let pending_g = std::mem::take(&mut self.pending_g);
        // `h` and `l` go toward the pane on that side of the screen, so they
        // swap when the chat list is on the right.
        let (to_chat, to_list) = match self.settings.chat_list_side {
            Side::Left => ('l', 'h'),
            Side::Right => ('h', 'l'),
        };
        // Motions work the same in both panes. In the message pane, down
        // (`j`, `G`) is newer and up (`k`, `gg`) is older, as on screen.
        let motion = match key.code {
            KeyCode::Char('j') | KeyCode::Down => Some(1),
            KeyCode::Char('k') | KeyCode::Up => Some(-1),
            KeyCode::Char('d') if ctrl => Some(HALF_PAGE),
            KeyCode::Char('u') if ctrl => Some(-HALF_PAGE),
            KeyCode::Char('g') if pending_g => Some(isize::MIN),
            KeyCode::Char('G') => Some(isize::MAX),
            _ => None,
        };
        if let Some(delta) = motion {
            match self.focus {
                Focus::Chats => self.move_chat_cursor(delta),
                Focus::Messages => self.move_message_cursor(delta),
                Focus::Input => {}
            }
            return;
        }
        match (self.focus, key.code) {
            // Before `r`, which replies.
            (_, KeyCode::Char('r')) if ctrl => {
                self.resizing = Some(self.settings.chat_list_width);
            }
            (_, KeyCode::Char('g')) => self.pending_g = true,
            (_, KeyCode::Char('q')) => self.quit(),
            (_, KeyCode::Char('H')) => self.toggle_highlight(),
            (_, KeyCode::Char('?')) => {
                if let Some(dir) = self.themes.dir.clone() {
                    self.themes = Themes::load(&dir);
                }
                self.use_saved_theme();
                self.settings_menu = Some(SettingsMenu::new(HelpTab::Shortcuts, &self.settings));
            }
            (_, KeyCode::Char(':')) => self.open_prompt(PromptKind::Command),
            (_, KeyCode::Char('s')) => self.picker = Some(ChatPicker::new(Purpose::Open)),
            (Focus::Chats, KeyCode::Char('/')) => self.open_prompt(PromptKind::Chats),
            (Focus::Messages, KeyCode::Char('/')) => self.open_prompt(PromptKind::Messages),
            (Focus::Messages, KeyCode::Char('n')) => self.next_match(1),
            (Focus::Messages, KeyCode::Char('N')) => self.next_match(-1),
            // Esc stops a lookup with `s`. In the chat pane it then ends a
            // search, then an edit, then removes the files, then ends a
            // reply, before it leaves the pane.
            (_, KeyCode::Esc) if self.finding.is_some() => self.finding = None,
            (Focus::Chats, KeyCode::Esc) => self.chats.set_filter(""),
            (Focus::Chats, KeyCode::Char('p')) if !ctrl => self.toggle_pin(),
            (Focus::Chats, KeyCode::Char('m')) if !ctrl => self.toggle_mute(),
            (Focus::Messages, KeyCode::Esc)
                if self.open.as_ref().is_some_and(|o| o.search.is_some()) =>
            {
                if let Some(open) = self.open.as_mut() {
                    open.search = None;
                }
            }
            (Focus::Messages, KeyCode::Esc)
                if self.open.as_ref().is_some_and(|o| o.editing.is_some()) =>
            {
                self.end_edit();
            }
            (Focus::Messages, KeyCode::Esc)
                if self
                    .open
                    .as_ref()
                    .is_some_and(|o| !o.attachments.is_empty()) =>
            {
                if let Some(open) = self.open.as_mut() {
                    open.attachments.clear();
                    open.dropped = None;
                    open.as_files = false;
                }
            }
            (Focus::Messages, KeyCode::Esc)
                if self.open.as_ref().is_some_and(|o| o.reply.is_some()) =>
            {
                if let Some(open) = self.open.as_mut() {
                    open.reply = None;
                }
            }
            (Focus::Messages, KeyCode::Char('r')) => self.reply_to_selected(),
            (Focus::Messages, KeyCode::Char('e')) => self.edit_selected(),
            (Focus::Messages, KeyCode::Char('y')) => self.copy_selected(),
            (Focus::Messages, KeyCode::Char('a')) => self.open_prompt(PromptKind::Attach),
            (Focus::Messages, KeyCode::Char('p')) => self.paste_clipboard(),
            (Focus::Messages, KeyCode::Char('t')) if ctrl => self.toggle_as_files(),
            (Focus::Messages, KeyCode::Char('d')) if pending_g => self.go_to_replied(),
            (Focus::Messages, KeyCode::Char('d')) => self.open_delete_menu(),
            (Focus::Messages, KeyCode::Char('R')) => self.open_react_menu(),
            (Focus::Messages, KeyCode::Char('X')) => self.remove_reactions(),
            (Focus::Messages, KeyCode::Char('f')) => self.forward_selected(),
            (Focus::Messages, KeyCode::Char('o')) if ctrl => self.jump_back(),
            (Focus::Chats, KeyCode::Enter) => self.open_selected_chat(),
            (Focus::Chats, KeyCode::Char(c)) if c == to_chat => self.open_selected_chat(),
            (Focus::Chats, KeyCode::Char('i')) => {
                self.open_selected_chat();
                self.start_writing();
            }
            (Focus::Messages, KeyCode::Char('i')) => self.start_writing(),
            (Focus::Messages, KeyCode::Enter) => self.open_selected_message(),
            (Focus::Messages, KeyCode::Esc) => self.focus = Focus::Chats,
            (Focus::Messages, KeyCode::Char(c)) if c == to_list => self.focus = Focus::Chats,
            _ => {}
        }
    }

    /// Insert mode: keys type into the composer.
    fn on_insert_key(&mut self, key: KeyEvent, ctrl: bool) {
        let alt = key.modifiers.contains(KeyModifiers::ALT);
        let shift = key.modifiers.contains(KeyModifiers::SHIFT);
        // While there are suggestions, Tab takes one and the arrows move
        // through them. Enter still sends: a suggestion taken by accident
        // would change the message.
        if let Some(completion) = self.completion.as_mut().filter(|c| !c.items.is_empty()) {
            match key.code {
                KeyCode::Tab => {
                    self.accept_completion();
                    return;
                }
                KeyCode::Up | KeyCode::BackTab => {
                    completion.move_by(-1);
                    return;
                }
                KeyCode::Down => {
                    completion.move_by(1);
                    return;
                }
                KeyCode::Char('p') if ctrl => {
                    completion.move_by(-1);
                    return;
                }
                KeyCode::Char('n') if ctrl => {
                    completion.move_by(1);
                    return;
                }
                _ => {}
            }
        }
        match key.code {
            // Ctrl-c leaves Insert mode like in vim, instead of quitting mid-sentence.
            KeyCode::Esc => self.leave_insert(),
            KeyCode::Char('c') if ctrl => self.leave_insert(),
            // Shift-Enter only arrives on terminals with the kitty keyboard protocol;
            // Alt-Enter and Ctrl-j work everywhere.
            KeyCode::Enter if alt || shift => {
                self.composer.insert_newline();
                self.on_composer_edit();
            }
            KeyCode::Char('j') if ctrl => {
                self.composer.insert_newline();
                self.on_composer_edit();
            }
            KeyCode::Enter => self.send(),
            // Ctrl-v pages down in the text area, which a composer this
            // small doesn't need.
            KeyCode::Char('v') if ctrl => self.paste_clipboard(),
            KeyCode::Char('z') if ctrl => self.undo_drop(),
            KeyCode::Char('t') if ctrl => self.toggle_as_files(),
            // Ctrl-u deletes back to the start of the line, as in a shell,
            // instead of the text area's undo.
            KeyCode::Char('u') if ctrl => {
                if self.composer.delete_line_by_head() {
                    self.on_composer_edit();
                }
            }
            KeyCode::Tab => self.open_stickers(),
            _ => {
                if self.composer.input(key) {
                    self.on_composer_edit();
                }
            }
        }
        self.update_completion();
    }

    /// Looks at the word before the cursor after each key in Insert mode,
    /// and suggests ways to finish it: emoji for `:smi`, people in the
    /// group for `@al`.
    fn update_completion(&mut self) {
        let DataCursor(row, col) = self.composer.cursor();
        let word = self
            .composer
            .lines()
            .get(row)
            .and_then(|line| complete::word_at(line, col));
        // Nobody to mention in a chat with one person, and a command only
        // starts a message.
        let group = self
            .open
            .as_ref()
            .and_then(|o| self.chats.get(o.chat_id))
            .is_some_and(|c| !c.is_private);
        let Some(word) = word.filter(|w| match w.kind {
            Kind::Emoji => true,
            Kind::Mention => group,
            Kind::Command => row == 0 && col == w.chars,
        }) else {
            self.completion = None;
            return;
        };
        if word.kind == Kind::Command {
            self.ask_bot_commands();
        }
        if self.completion.as_ref().is_some_and(|c| c.word == word) {
            return;
        }
        let completion = self
            .completion
            .get_or_insert_with(|| Completion::new(word.clone()));
        completion.retype(word.clone(), Instant::now());
        let items = match word.kind {
            Kind::Emoji => complete::emoji(&word.query),
            Kind::Mention => {
                let found = completion.found.clone();
                self.mention_items(&word.query, &found)
            }
            Kind::Command => self.command_items(&word.query),
        };
        if let Some(completion) = self.completion.as_mut() {
            completion.set_items(items);
        }
    }

    /// Asks once per open chat for the commands of its bots: the bot of a
    /// chat with one, or the bots in a group.
    fn ask_bot_commands(&mut self) {
        let Some(open) = self
            .open
            .as_mut()
            .filter(|o| o.commands == Commands::NotAsked)
        else {
            return;
        };
        let peer = self.chats.get(open.chat_id).and_then(|c| c.peer);
        open.commands = match peer {
            // A person takes no commands.
            Some(Peer::User(id)) if !self.chats.is_bot(id) => Commands::Known(Vec::new()),
            Some(peer) => {
                self.tg.bot_commands(open.chat_id, peer);
                Commands::Asked
            }
            None => Commands::Known(Vec::new()),
        };
    }

    /// The commands of the open chat's bots that have `query` in them.
    fn command_items(&self, query: &str) -> Vec<Suggestion> {
        let Some(Commands::Known(list)) = self.open.as_ref().map(|o| &o.commands) else {
            return Vec::new();
        };
        complete::commands(list, query, |bot| {
            self.chats.user_username(bot).map(String::from)
        })
    }

    /// People in the open group whose name or username has `query` in it:
    /// the senders of the messages loaded, newest first, then members
    /// Telegram found. Not you.
    fn mention_items(&self, query: &str, found: &[i64]) -> Vec<Suggestion> {
        let Some(open) = &self.open else {
            return Vec::new();
        };
        let senders = open.messages.values().rev().filter_map(|m| match m.sender {
            Sender::User(id) => Some(id),
            Sender::Chat(_) => None,
        });
        let mut seen = HashSet::new();
        let mut items = Vec::new();
        for user_id in senders.chain(found.iter().copied()) {
            if self.chats.is_saved(user_id) || !seen.insert(user_id) {
                continue;
            }
            let Some(name) = self.users.get(&user_id) else {
                continue;
            };
            let username = self.chats.user_username(user_id);
            let matches = query.is_empty()
                || !search::find(name, query).is_empty()
                || username.is_some_and(|u| !search::find(u, query).is_empty());
            if matches {
                items.push(complete::mention(user_id, name, username));
            }
            if items.len() == complete::MAX_SUGGESTIONS {
                break;
            }
        }
        items
    }

    /// Tab with suggestions up: puts the one under the cursor in place of
    /// the word being typed.
    fn accept_completion(&mut self) {
        let Some(completion) = self.completion.take() else {
            return;
        };
        let Some(suggestion) = completion.current() else {
            return;
        };
        for _ in 0..completion.word.chars {
            self.composer.delete_char();
        }
        self.composer.insert_str(&suggestion.insert);
        self.on_composer_edit();
    }

    /// `i`: Insert mode, in a chat you can write in. In a public group or
    /// channel you're not in, it asks to join first.
    fn start_writing(&mut self) {
        let Some(open) = &self.open else {
            return;
        };
        if self.chats.joined(open.chat_id) {
            self.focus = Focus::Input;
            return;
        }
        let title = self.chats.title(open.chat_id).unwrap_or("this chat");
        // Only a channel's admins write in it; joining one is following it.
        let channel = self.chats.get(open.chat_id).is_some_and(|c| c.is_channel);
        let (ask, why) = if channel {
            (
                "Join this channel?",
                "Join it to have it in your chat list.",
            )
        } else {
            (
                "Join to write here?",
                "Join it to write, and to have it in your chat list.",
            )
        };
        let mut confirm = Confirm::new(
            ask,
            vec![format!("You're not in {title}."), why.into()],
            Confirmed::Join(open.chat_id),
        );
        confirm.badge = self.chats.badge(open.chat_id);
        self.confirm = Some(confirm);
    }

    fn leave_insert(&mut self) {
        self.focus = Focus::Messages;
        self.set_typing(false);
    }

    /// You're typing while the composer has text, and stopped once it's empty.
    /// An edit to a sent message isn't typing.
    fn on_composer_edit(&mut self) {
        let editing = self.open.as_ref().is_some_and(|o| o.editing.is_some());
        let typing = !editing && self.composer.lines().iter().any(|l| !l.trim().is_empty());
        self.set_typing(typing);
    }

    /// Tells the open chat whether you're typing: again every
    /// [`TYPING_EVERY`] while you are, and once when you stop.
    fn set_typing(&mut self, typing: bool) {
        let chat_id = self.open.as_ref().map(|o| o.chat_id);
        if typing && let Some(chat_id) = chat_id {
            let told = self
                .typing
                .is_some_and(|(id, at)| id == chat_id && at.elapsed() < TYPING_EVERY);
            if !told {
                self.tg.send_typing(chat_id, true);
                self.typing = Some((chat_id, Instant::now()));
            }
        } else if let Some((chat_id, _)) = self.typing.take() {
            self.tg.send_typing(chat_id, false);
        }
    }

    fn send(&mut self) {
        if self.open.as_ref().is_some_and(|o| o.editing.is_some()) {
            self.save_edit();
            return;
        }
        let Some(open) = self.open.as_mut() else {
            return;
        };
        let text = self.composer.lines().join("\n");
        let text = text.trim().to_string();
        if text.is_empty() && open.attachments.is_empty() {
            return;
        }
        if let Some(changed) = open.attachments.iter().find(|a| a.swapped()) {
            self.status = Some(format!(
                "{} changed since it was attached. Drop the files (Esc in Normal mode) and attach it again",
                changed.name
            ));
            return;
        }
        let reply_to = open.reply.take().map(|r| r.id);
        if open.attachments.is_empty() {
            self.tg.send_text(open.chat_id, text, reply_to);
        } else {
            let as_files = open.as_files;
            let groups = attach::albums(&open.attachments, as_files)
                .into_iter()
                .map(|album| album.iter().map(|a| a.upload(as_files)).collect())
                .collect();
            self.tg.send_files(open.chat_id, groups, text, reply_to);
            open.attachments.clear();
            open.dropped = None;
            open.as_files = false;
        }
        self.composer = new_composer();
        // The message arriving ends the typing status for everyone.
        self.typing = None;
        if self.settings.normal_after_send {
            self.focus = Focus::Messages;
        }
        // Jump to the bottom to watch it arrive.
        self.jump_to_newest();
    }

    fn open_prompt(&mut self, kind: PromptKind) {
        let input = prompt_input("");
        // Files go into a chat, so one has to be open.
        if kind == PromptKind::Attach && !self.can_attach() {
            return;
        }
        self.prompt = Some(Prompt {
            kind,
            input,
            completions: Vec::new(),
            previous_filter: self.chats.filter().to_string(),
            previous_selected: self.selected,
        });
    }

    /// The prompt takes all keys while it's up.
    fn on_prompt_key(&mut self, key: KeyEvent, ctrl: bool) {
        let Some(prompt) = self.prompt.as_mut() else {
            return;
        };
        match key.code {
            KeyCode::Esc => self.close_prompt(false),
            KeyCode::Char('c') if ctrl => self.close_prompt(false),
            // Ctrl-m and Ctrl-j would add a line to the one-line prompt.
            KeyCode::Enter => self.close_prompt(true),
            KeyCode::Char('m' | 'j') if ctrl => self.close_prompt(true),
            // Like vim, backspace on an empty prompt closes it.
            KeyCode::Backspace if prompt.query().is_empty() => self.close_prompt(false),
            KeyCode::Tab if prompt.kind == PromptKind::Attach => {
                let completion = attach::complete(&prompt.query());
                prompt.input = prompt_input(&completion.text);
                prompt.completions = completion.matches;
            }
            _ => {
                prompt.input.input(key);
                prompt.completions.clear();
                self.on_prompt_edit();
            }
        }
    }

    /// The chat list filters as you type, with the cursor on the top match.
    fn on_prompt_edit(&mut self) {
        let Some(prompt) = self.prompt.as_ref() else {
            return;
        };
        if prompt.kind == PromptKind::Chats {
            self.chats.set_filter(prompt.query().trim());
            self.chats.refresh();
            self.selected = self.chats.ids().first().copied();
        }
    }

    /// Enter (`submit`) runs the search; Esc puts things back as they were.
    fn close_prompt(&mut self, submit: bool) {
        let Some(prompt) = self.prompt.take() else {
            return;
        };
        let query = prompt.query().trim().to_string();
        match prompt.kind {
            PromptKind::Chats => {
                if submit && (query.is_empty() || !self.chats.ids().is_empty()) {
                    return;
                }
                if submit {
                    self.status = Some(format!("No chats match \"{query}\""));
                }
                self.chats.set_filter(&prompt.previous_filter);
                self.selected = prompt.previous_selected;
            }
            PromptKind::Messages => {
                let Some(open) = self.open.as_mut().filter(|_| submit && !query.is_empty()) else {
                    return;
                };
                open.search = Some(MessageSearch::new(query));
                self.go_to_match(0);
            }
            PromptKind::Attach if !submit || query.is_empty() => {}
            PromptKind::Attach => {
                let path = attach::expand_home(&query);
                // A file dropped on the prompt comes quoted.
                let paths = match attach::pasted_paths(&query) {
                    Some(paths) if !path.exists() => paths,
                    _ => vec![path],
                };
                self.attach(paths, None);
            }
            PromptKind::Command if !submit || query.is_empty() => {}
            PromptKind::Command => match Command::parse(&query) {
                Some(Command::Leave) => self.ask_to_leave(),
                Some(Command::Logout) => self.log_out(),
                None => self.status = Some(format!("Not a command: {query}")),
            },
        }
    }

    /// Sends a read receipt for the newest incoming message once you can
    /// see it: the chat pane and the terminal window have focus, and the view
    /// is on the newest message (see [`App::watching`]). Viewing it marks the
    /// whole chat as read.
    fn mark_seen(&mut self) {
        let watched = self.open.as_ref().map(|o| o.chat_id);
        if !watched.is_some_and(|id| self.watching(id)) {
            return;
        }
        let Some(open) = self.open.as_mut() else {
            return;
        };
        let newest = open.messages.iter().rev().find(|(_, m)| !m.outgoing);
        if let Some((&id, _)) = newest
            && id > open.seen
        {
            open.seen = id;
            self.tg.view_messages(open.chat_id, vec![id]);
        }
    }

    /// How long since the last key, by whichever clock says longer: the
    /// monotonic one doesn't count time the computer spent asleep.
    fn idle(&self) -> Duration {
        let wall = SystemTime::now()
            .duration_since(self.last_input_wall)
            .unwrap_or_default();
        self.last_input.elapsed().max(wall)
    }

    /// The chat is open in front of the user, on its newest message, so new
    /// ones are seen as they arrive. Where the terminal never says when its
    /// window loses focus (tmux without `focus-events`, a detached session),
    /// no key press for [`IDLE_AFTER`] counts as the user being away, so
    /// messages aren't marked read, and do notify, while nobody is there.
    /// A window the terminal says has focus gets [`AWAY_AFTER`].
    fn watching(&self, chat_id: i64) -> bool {
        let idle = self.idle();
        matches!(self.screen, Screen::Main)
            && self.terminal_focused
            && (idle < IDLE_AFTER || (self.focus_reported && idle < AWAY_AFTER))
            && matches!(self.focus, Focus::Messages | Focus::Input)
            && self.settings_menu.is_none()
            && self
                .open
                .as_ref()
                .is_some_and(|o| o.chat_id == chat_id && o.at_newest && o.selected.is_none())
    }

    /// The user would see a new message in this chat without being told:
    /// tuigram's window has focus. Where the terminal never reports focus,
    /// only the chat being read counts.
    fn sees(&self, chat_id: i64) -> bool {
        if self.focus_reported {
            self.terminal_focused
        } else {
            self.watching(chat_id)
        }
    }

    /// Online on Telegram while the user is at tuigram: logged in, its window
    /// focused, and a key pressed in the last [`IDLE_AFTER`].
    fn update_online(&mut self) {
        let online = matches!(self.screen, Screen::Main)
            && self.quit_deadline.is_none()
            && self.terminal_focused
            && self.idle() < IDLE_AFTER;
        if online != self.online {
            self.online = online;
            self.tg.set_online(online);
        }
    }

    /// New messages from TDLib, which already left out muted chats and
    /// messages read elsewhere. Those the user sees anyway, or that came in
    /// before tuigram started, are dropped.
    fn on_notifications(&mut self, update: UpdateNotificationGroup) {
        self.notifier.remove(&update.removed_notification_ids);
        if self.notify_with == Notifications::Off {
            return;
        }
        let chat_id = update.chat_id;
        for notification in update.added_notifications {
            let NotificationType::NewMessage(new) = notification.r#type else {
                continue;
            };
            if notification.date < self.notify_since || self.sees(chat_id) {
                continue;
            }
            let text = if new.show_preview {
                self.notification_text(&new.message)
            } else {
                "New message".into()
            };
            let note = Note {
                id: notification.id,
                chat_id,
                chat: format!(
                    "{}{}",
                    self.chats.title(chat_id).unwrap_or("Telegram"),
                    self.chats.badge(chat_id).map_or("", Badge::mark)
                ),
                text,
                silent: notification.is_silent,
            };
            self.notifier.add(note, Instant::now());
        }
    }

    /// "Alice: see you at 5" in groups; just the text in private chats,
    /// where the chat's name says who, and in channels.
    fn notification_text(&self, message: &Message) -> String {
        let text = crate::chats::content_text(&message.content);
        match &message.sender_id {
            MessageSender::User(sender) if sender.user_id != message.chat_id => {
                match self.users.get(&sender.user_id) {
                    Some(name) => format!("{name}: {text}"),
                    None => text,
                }
            }
            _ => text,
        }
    }

    fn send_notification(&mut self) {
        let Some(alert) = self.notifier.due(Instant::now()) else {
            return;
        };
        self.notifications_sent += 1;
        let id = self.notifications_sent;
        if let Some(code) = notify::escape(self.notify_with, &alert, id, self.in_tmux) {
            notify::send(&code);
        }
    }

    fn set_unread_chats(&mut self, count: i32) {
        if count != self.unread_chats {
            self.unread_chats = count;
            notify::send(&notify::title(count));
        }
    }

    /// `:leave`: asks before leaving the chat the command is about, the
    /// selected one in the list or else the open one. Only groups and
    /// channels can be left.
    fn ask_to_leave(&mut self) {
        let chat_id = match self.focus {
            Focus::Chats => self.selected,
            _ => self.open.as_ref().map(|o| o.chat_id),
        };
        let Some((chat_id, chat)) = chat_id.and_then(|id| Some((id, self.chats.get(id)?))) else {
            self.status = Some("Open the group or channel to leave first".into());
            return;
        };
        if chat.is_private {
            self.status = Some("A chat with one person can't be left".into());
            return;
        }
        if !self.chats.joined(chat_id) {
            self.status = Some("You're not in this chat".into());
            return;
        }
        let title = self.chats.title(chat_id).unwrap_or_default();
        let (ask, why) = if chat.is_channel {
            ("Leave this channel?", "Its posts stop coming to you.")
        } else {
            ("Leave this group?", "Its messages stop coming to you.")
        };
        let mut confirm = Confirm::new(
            ask,
            vec![title.to_string(), why.into()],
            Confirmed::Leave(chat_id),
        );
        confirm.badge = self.chats.badge(chat_id);
        self.confirm = Some(confirm);
    }

    /// `:logout`: ends the session on Telegram's side and deletes what TDLib
    /// keeps on this computer. The login screen comes back once TDLib closes.
    fn log_out(&mut self) {
        self.tg.log_out();
        self.relogin = true;
        self.screen = login_screen(LoginStep::LoggingOut);
    }

    /// Drops everything from the old session before a new client starts, so
    /// nothing from it shows up after logging in again, maybe as someone else.
    fn forget_session(&mut self) {
        // Highlights are chat ids of the old account.
        self.settings.highlighted_chats.clear();
        if let Err(e) = self.settings.save(&self.settings_path) {
            self.status = Some(format!("Couldn't save settings: {e:#}"));
        }
        self.chats = Chats::default();
        self.users.clear();
        self.selected = None;
        self.open = None;
        self.focus = Focus::Chats;
        self.composer = new_composer();
        self.images.forget_files();
        self.opening.clear();
        self.copying.clear();
        self.menu = None;
        self.delete_menu = None;
        self.react_menu = None;
        self.vote_menu = None;
        self.picker = None;
        self.finding = None;
        self.completion = None;
        self.stickers = None;
        // The next account says if it has Premium; one without may not.
        self.premium = false;
        self.confirm = None;
        self.settings_menu = None;
        self.prompt = None;
        self.chats_loading = false;
        self.all_chats_loaded = false;
        self.pending_g = false;
        // The client that knew about being online and typing is gone.
        self.online = false;
        self.typing = None;
        self.notifier.clear();
        self.notify_since = i32::MAX;
        self.set_unread_chats(0);
    }

    /// `n` (`step` 1) goes to the next older match, `N` (-1) to the next newer.
    fn next_match(&mut self, step: isize) {
        let Some(search) = self.open.as_ref().and_then(|o| o.search.as_ref()) else {
            return;
        };
        let Some(current) = search.current else {
            return;
        };
        match current.checked_add_signed(step) {
            Some(index) => self.go_to_match(index),
            None => self.status = Some("No newer matches".into()),
        }
    }

    /// Moves the cursor to search match `index` (0 = newest), fetching more
    /// results first if it's past the ones fetched.
    fn go_to_match(&mut self, index: usize) {
        let Some(open) = self.open.as_mut() else {
            return;
        };
        let Some(search) = open.search.as_mut() else {
            return;
        };
        if let Some(&id) = search.results.get(index) {
            search.current = Some(index);
            self.jump_to_message(id);
        } else if !search.done {
            search.wanted = Some(index);
            if !search.loading {
                search.loading = true;
                let (query, from) = (search.query.clone(), search.next_from);
                self.tg
                    .search_messages(open.chat_id, query, from, SEARCH_PAGE);
            }
        } else if search.results.is_empty() {
            self.status = Some(format!("No messages match \"{}\"", search.query));
            open.search = None;
        } else {
            self.status = Some("No older matches".into());
        }
    }

    /// Puts the cursor on a message, loading the history around it if it's
    /// not loaded.
    fn jump_to_message(&mut self, id: i64) {
        let Some(open) = self.open.as_mut() else {
            return;
        };
        if open.messages.contains_key(&id) {
            open.selected = Some(id);
            // A jump still loading elsewhere would move the cursor away.
            if matches!(open.loading, Some(Page::Around(_))) {
                open.loading = None;
            }
            return;
        }
        // The page replaces the loaded messages when it arrives.
        let page = Page::Around(id);
        open.loading = Some(page);
        self.tg.load_history(open.chat_id, page, HISTORY_PAGE);
    }

    /// Back to following the newest message, reloading if an older part of
    /// the chat is shown.
    fn jump_to_newest(&mut self) {
        let Some(open) = self.open.as_mut() else {
            return;
        };
        open.selected = None;
        if open.at_newest {
            return;
        }
        open.messages.clear();
        open.scroll = None;
        open.at_newest = true;
        open.all_loaded = false;
        open.loading = None;
        self.load_older_messages();
    }

    fn open_selected_chat(&mut self) {
        if let Some(chat_id) = self.selected {
            self.open_chat(chat_id);
        }
    }

    /// Opens a chat, in the list or not: one found with `s` may be a
    /// public group you're not in.
    fn open_chat(&mut self, chat_id: i64) {
        // A lookup still on its way would open another chat over this one.
        self.finding = None;
        // Popups about a message of the chat before are no use in this one.
        self.menu = None;
        self.delete_menu = None;
        self.react_menu = None;
        self.vote_menu = None;
        if self.chats.listed(chat_id) && self.selected != Some(chat_id) {
            // The list's cursor goes to it, even if the filter hid it.
            if !self.chats.ids().contains(&chat_id) {
                self.chats.set_filter("");
            }
            self.selected = Some(chat_id);
        }
        self.focus = Focus::Messages;
        if self.open.as_ref().is_some_and(|o| o.chat_id == chat_id) {
            return;
        }
        self.set_typing(false);
        // TDLib only sends some updates (e.g. for channels) while a chat is open.
        if let Some(old) = self.open.take() {
            self.tg.close_chat(old.chat_id);
            self.images.clear();
        }
        self.tg.open_chat(chat_id);
        self.chats.opened(chat_id);
        self.open = Some(OpenChat::new(chat_id));
        self.composer = new_composer();
        self.load_older_messages();
    }

    /// Enter on a message: shows its spoilers first, as a tap does in
    /// Telegram; then opens its file or link right away, or shows a menu when
    /// there's more than one.
    fn open_selected_message(&mut self) {
        let Some(open) = self.open.as_mut() else {
            return;
        };
        if let Some(id) = open.cursor_id()
            && open.reveal_spoilers(id)
        {
            return;
        }
        if let Some((&id, msg)) = open
            .cursor_id()
            .and_then(|id| open.messages.get_key_value(&id))
            && let Some(poll) = &msg.poll
        {
            match (msg.state, poll.cant_vote()) {
                (SendState::Sent, None) => self.vote_menu = Some(VoteMenu::new(id, poll)),
                (SendState::Sent, Some(why)) => self.status = Some(why.into()),
                _ => self.status = Some("Wait until it's sent".into()),
            }
            return;
        }
        let Some(msg) = open.cursor_id().and_then(|id| open.messages.get(&id)) else {
            return;
        };
        let mut targets: Vec<Target> = msg.file.clone().map(Target::File).into_iter().collect();
        targets.extend(msg.links.iter().cloned().map(Target::Link));
        match targets.len() {
            0 => self.status = Some("Nothing to open in this message".into()),
            1 => self.open_target(targets.remove(0)),
            _ => {
                self.menu = Some(PickMenu {
                    action: MenuAction::Open,
                    targets,
                    selected: 0,
                })
            }
        }
    }

    /// `r`: answer the message under the cursor. Goes straight to Insert mode,
    /// keeping whatever was already typed.
    fn reply_to_selected(&mut self) {
        // Its draft and reply come back, and the new reply replaces that one.
        self.end_edit();
        let Some(open) = self.open.as_mut() else {
            return;
        };
        let Some((&id, msg)) = open
            .cursor_id()
            .and_then(|id| open.messages.get_key_value(&id))
        else {
            return;
        };
        if msg.state == SendState::Failed {
            self.status = Some("Can't reply to a message that wasn't sent".into());
            return;
        }
        open.reply = Some(Replied::new(id, msg));
        self.focus = Focus::Input;
    }

    /// `e`: edits the message under the cursor in the composer, once TDLib
    /// says it can be.
    fn edit_selected(&mut self) {
        let Some(open) = &self.open else {
            return;
        };
        let Some(id) = open.edit_target() else {
            return;
        };
        match open.cant_edit(id) {
            Some(why) => self.status = Some(why.into()),
            None => self.tg.check_editable(open.chat_id, id),
        }
    }

    fn on_editable(
        &mut self,
        chat_id: i64,
        message_id: i64,
        editable: Option<bool>,
        text: Option<EditText>,
    ) {
        // Only while the cursor is still on it, so a late answer can't take
        // over the composer.
        let Some(open) = self
            .open
            .as_ref()
            .filter(|o| o.chat_id == chat_id && o.edit_target() == Some(message_id))
        else {
            return;
        };
        let Some(msg) = open.messages.get(&message_id) else {
            return;
        };
        // Without it as Markdown, it's edited as plain text, which loses
        // any formatting.
        let (text, loses) = match text {
            Some(text) => (text.markdown, text.loses),
            None => (msg.source_text.clone(), msg.formatted),
        };
        // On an error, TDLib's message is already in the status bar.
        match editable {
            None => {}
            Some(false) => self.status = Some("You can't edit this message".into()),
            Some(true) if loses => {
                self.confirm = Some(Confirm::new(
                    "Edit and lose some formatting?",
                    vec![
                        "Some of its formatting can't be written in Markdown".into(),
                        "(underline, custom emoji…), so an edit would lose it.".into(),
                    ],
                    Confirmed::Edit {
                        id: message_id,
                        text,
                    },
                ));
            }
            Some(true) => self.start_edit(message_id, text),
        }
    }

    /// Puts the message's text, as Markdown, in the composer, keeping what
    /// was there to give back when the edit is done.
    fn start_edit(&mut self, id: i64, text: String) {
        self.end_edit();
        let Some(open) = self.open.as_mut() else {
            return;
        };
        let Some(msg) = open.messages.get(&id) else {
            return;
        };
        open.editing = Some(Editing {
            id,
            snippet: msg.snippet(),
            original: text.clone(),
            editable: msg.editable,
            draft: self.composer.lines().join("\n"),
            reply: open.reply.take(),
            attachments: std::mem::take(&mut open.attachments),
        });
        open.dropped = None;
        self.set_typing(false);
        self.composer = new_composer();
        self.composer.insert_str(text);
        self.focus = Focus::Input;
    }

    /// Ends an edit, saved or not: the draft and reply from before come back.
    fn end_edit(&mut self) {
        let Some(editing) = self.open.as_mut().and_then(|o| o.editing.take()) else {
            return;
        };
        self.composer = new_composer();
        self.composer.insert_str(editing.draft);
        if let Some(open) = self.open.as_mut() {
            open.reply = editing.reply;
            open.attachments = editing.attachments;
        }
    }

    /// Enter while editing: sends the new text, unless nothing changed.
    fn save_edit(&mut self) {
        let Some(open) = &self.open else {
            return;
        };
        let Some(editing) = &open.editing else {
            return;
        };
        let text = self.composer.lines().join("\n");
        let text = text.trim();
        if text.is_empty() && editing.editable == Editable::Text {
            self.status = Some("A message can't be empty (d deletes it)".into());
            return;
        }
        if text != editing.original.trim() {
            let (chat_id, id, text) = (open.chat_id, editing.id, text.to_string());
            match editing.editable {
                Editable::Text => self.tg.edit_text(chat_id, id, text),
                Editable::Caption { above } => self.tg.edit_caption(chat_id, id, text, above),
                Editable::No => {}
            }
        }
        self.end_edit();
        if self.settings.normal_after_send {
            self.focus = Focus::Messages;
        }
    }

    /// `d`: asks how to delete the message under the cursor. The popup opens
    /// at once and fills in when TDLib says what's allowed.
    fn open_delete_menu(&mut self) {
        let Some(open) = &self.open else {
            return;
        };
        let Some((&message_id, msg)) = open
            .cursor_id()
            .and_then(|id| open.messages.get_key_value(&id))
        else {
            return;
        };
        self.delete_menu = Some(DeleteMenu {
            message_id,
            snippet: msg.snippet(),
            choices: Vec::new(),
            selected: 0,
        });
        self.tg.check_deletable(open.chat_id, message_id);
    }

    fn on_deletable(&mut self, chat_id: i64, message_id: i64, deletable: Option<Deletable>) {
        // Drop answers for a popup that closed, or a chat that changed.
        if self.open.as_ref().is_none_or(|o| o.chat_id != chat_id) {
            return;
        }
        let Some(menu) = self
            .delete_menu
            .as_mut()
            .filter(|m| m.message_id == message_id)
        else {
            return;
        };
        // On an error, TDLib's message is already in the status bar.
        let Some(deletable) = deletable else {
            self.delete_menu = None;
            return;
        };
        menu.set_allowed(deletable);
        if menu.choices.is_empty() {
            self.delete_menu = None;
            self.status = Some("You can't delete this message".into());
        }
    }

    /// The delete popup takes all keys while it's up.
    fn on_delete_key(&mut self, key: KeyEvent) {
        let Some(menu) = self.delete_menu.as_mut() else {
            return;
        };
        let last = menu.choices.len().saturating_sub(1);
        let pick = match key.code {
            KeyCode::Char('j') | KeyCode::Down => {
                menu.selected = (menu.selected + 1).min(last);
                None
            }
            KeyCode::Char('k') | KeyCode::Up => {
                menu.selected = menu.selected.saturating_sub(1);
                None
            }
            KeyCode::Enter | KeyCode::Char('l') => Some(menu.selected),
            KeyCode::Char(c @ '1'..='9') => Some(c as usize - '1' as usize),
            KeyCode::Esc | KeyCode::Char('q' | 'h') => {
                self.delete_menu = None;
                return;
            }
            _ => None,
        };
        // Nothing to pick while TDLib hasn't answered.
        let Some(choice) = pick.and_then(|i| menu.choices.get(i).copied()) else {
            return;
        };
        let message_id = menu.message_id;
        self.delete_menu = None;
        if let Some(open) = &self.open {
            let revoke = choice == DeleteChoice::Everyone;
            self.tg.delete_message(open.chat_id, message_id, revoke);
        }
    }

    /// `R`: the emoji to react to the message under the cursor with. The
    /// popup opens at once and fills in when TDLib says which the chat allows.
    fn open_react_menu(&mut self) {
        let Some(open) = &self.open else {
            return;
        };
        let Some((&message_id, msg)) = open
            .react_target()
            .and_then(|id| open.messages.get_key_value(&id))
        else {
            return;
        };
        match msg.state {
            SendState::Pending => self.status = Some("Wait until it's sent".into()),
            SendState::Failed => self.status = Some("This message wasn't sent".into()),
            SendState::Sent => {
                self.react_menu = Some(ReactMenu::new(message_id, msg.snippet()));
                self.tg.available_reactions(open.chat_id, message_id);
            }
        }
    }

    fn on_available_reactions(
        &mut self,
        chat_id: i64,
        message_id: i64,
        available: Option<reactions::Available>,
    ) {
        // Drop answers for a popup that closed, or a chat that changed.
        if self.open.as_ref().is_none_or(|o| o.chat_id != chat_id)
            || self
                .react_menu
                .as_ref()
                .is_none_or(|m| m.message_id != message_id)
        {
            return;
        }
        // On an error, TDLib's message is already in the status bar.
        let Some(available) = available else {
            self.react_menu = None;
            return;
        };
        if available.emoji.is_empty() {
            self.react_menu = None;
            let reason = available.reason.unwrap_or("Reactions are off in this chat");
            self.status = Some(reason.into());
            return;
        }
        let yours: Vec<String> = self
            .open
            .iter()
            .flat_map(|o| o.your_emoji(message_id))
            .map(|(_, emoji)| emoji)
            .collect();
        if let Some(menu) = self.react_menu.as_mut() {
            menu.set_choices(available.emoji, &yours);
        }
    }

    /// The reaction popup takes all keys while it's up. In the grid, `h/j/k/l`
    /// move; after `/`, keys type the search and the arrows move.
    fn on_react_key(&mut self, key: KeyEvent, ctrl: bool) {
        let Some(menu) = self.react_menu.as_mut() else {
            return;
        };
        let row = reactions::COLUMNS as isize;
        let searching = menu.query.is_some();
        match key.code {
            KeyCode::Enter => self.react_with_selected(),
            KeyCode::Left => menu.move_by(-1),
            KeyCode::Right | KeyCode::Tab => menu.move_by(1),
            KeyCode::BackTab => menu.move_by(-1),
            KeyCode::Up => menu.move_by(-row),
            KeyCode::Down => menu.move_by(row),
            KeyCode::Char('n') if ctrl => menu.move_by(1),
            KeyCode::Char('p') if ctrl => menu.move_by(-1),
            // Esc, or Backspace on an empty search, leaves the search first.
            KeyCode::Esc if searching => menu.leave_search(),
            KeyCode::Backspace if menu.query.as_ref().is_some_and(|q| q.is_empty()) => {
                menu.leave_search();
            }
            KeyCode::Backspace if searching => menu.edit_query(|q| {
                q.pop();
            }),
            KeyCode::Char('u' | 'w') if ctrl && searching => menu.edit_query(String::clear),
            KeyCode::Char(c) if searching && !ctrl => menu.edit_query(|q| q.push(c)),
            KeyCode::Char('h') => menu.move_by(-1),
            KeyCode::Char('l') => menu.move_by(1),
            KeyCode::Char('k') => menu.move_by(-row),
            KeyCode::Char('j') => menu.move_by(row),
            KeyCode::Char('/') => menu.edit_query(|_| {}),
            KeyCode::Char('X') => {
                self.react_menu = None;
                self.remove_reactions();
            }
            KeyCode::Esc | KeyCode::Char('q' | 'R') => self.react_menu = None,
            _ => {}
        }
    }

    /// Enter in the reaction popup: adds the emoji under the cursor, or takes
    /// it back if it's already yours, and closes the popup.
    fn react_with_selected(&mut self) {
        // Nothing to pick while TDLib hasn't answered or nothing matches.
        let Some((message_id, emoji)) = self
            .react_menu
            .as_ref()
            .and_then(|m| Some((m.message_id, m.current()?.to_string())))
        else {
            return;
        };
        self.react_menu = None;
        let Some(open) = &self.open else {
            return;
        };
        // Yours already, on this photo or another of its album: taken back
        // from where it is, rather than added a second time here.
        let yours = open
            .your_emoji(message_id)
            .into_iter()
            .find(|(_, e)| *e == emoji);
        let kind = ReactionKind::Emoji(emoji);
        match yours {
            Some((on, _)) => self.tg.react(open.chat_id, on, &kind, false),
            None => self.tg.react(open.chat_id, message_id, &kind, true),
        }
    }

    /// The vote popup takes all keys while it's up.
    fn on_vote_key(&mut self, key: KeyEvent) {
        let Some(menu) = self.vote_menu.as_mut() else {
            return;
        };
        match key.code {
            KeyCode::Char('j') | KeyCode::Down => menu.move_by(1),
            KeyCode::Char('k') | KeyCode::Up => menu.move_by(-1),
            KeyCode::Char(' ') => menu.tick(),
            KeyCode::Char(c @ '1'..='9') => {
                let index = c as usize - '1' as usize;
                if index < menu.answers.len() {
                    menu.selected = index;
                    if menu.several {
                        menu.tick();
                    } else {
                        self.cast_vote();
                    }
                }
            }
            KeyCode::Enter | KeyCode::Char('l') => self.cast_vote(),
            KeyCode::Esc | KeyCode::Char('q' | 'h') => self.vote_menu = None,
            _ => {}
        }
    }

    /// Enter in the vote popup: votes, or takes your vote back. TDLib then
    /// sends the poll's new counts.
    fn cast_vote(&mut self) {
        let Some(menu) = self.vote_menu.take() else {
            return;
        };
        let Some(open) = &self.open else {
            return;
        };
        let answers = match menu.vote() {
            Vote::For(answers) => answers,
            Vote::Retract => Vec::new(),
        };
        self.tg.vote(open.chat_id, menu.message_id, answers);
    }

    /// `f`: forwards the message under the cursor, or its whole album, to a
    /// chat picked from your list.
    fn forward_selected(&mut self) {
        let Some(open) = &self.open else {
            return;
        };
        let Some((&id, msg)) = open
            .cursor_id()
            .and_then(|id| open.messages.get_key_value(&id))
        else {
            return;
        };
        match msg.state {
            SendState::Pending => self.status = Some("Wait until it's sent".into()),
            SendState::Failed => self.status = Some("This message wasn't sent".into()),
            SendState::Sent => {
                self.picker = Some(ChatPicker::new(Purpose::Forward {
                    from: open.chat_id,
                    message_ids: open.forward_ids(id),
                    snippet: msg.snippet(),
                }));
            }
        }
    }

    /// The picker takes all keys while it's up: they type the search, and
    /// the arrows (or Ctrl-n / Ctrl-p, Tab) move.
    fn on_picker_key(&mut self, key: KeyEvent, ctrl: bool) {
        let choices = self
            .picker
            .as_ref()
            .map_or(Vec::new(), |p| p.choices(&self.chats));
        let Some(picker) = self.picker.as_mut() else {
            return;
        };
        let now = Instant::now();
        match key.code {
            KeyCode::Enter => self.pick_chat(),
            KeyCode::Esc => self.picker = None,
            KeyCode::Char('c') if ctrl => self.picker = None,
            KeyCode::Up | KeyCode::BackTab => picker.move_by(-1, &choices),
            KeyCode::Down | KeyCode::Tab => picker.move_by(1, &choices),
            KeyCode::Char('p') if ctrl => picker.move_by(-1, &choices),
            KeyCode::Char('n') if ctrl => picker.move_by(1, &choices),
            KeyCode::PageUp => picker.move_by(-HALF_PAGE, &choices),
            KeyCode::PageDown => picker.move_by(HALF_PAGE, &choices),
            KeyCode::Backspace => picker.edit_query(
                |q| {
                    q.pop();
                },
                now,
            ),
            KeyCode::Char('u' | 'w') if ctrl => picker.edit_query(String::clear, now),
            KeyCode::Char(c) if !ctrl => picker.edit_query(|q| q.push(c), now),
            _ => {}
        }
    }

    /// Enter in the picker: forwards there, or opens it, looking it up
    /// first if it's a username, a link or a contact with no chat yet.
    fn pick_chat(&mut self) {
        let Some(picker) = self.picker.as_ref() else {
            return;
        };
        let Some(choice) = picker.current(&picker.choices(&self.chats)) else {
            return;
        };
        let Some(picker) = self.picker.take() else {
            return;
        };
        match (picker.purpose, choice) {
            (
                Purpose::Forward {
                    from, message_ids, ..
                },
                Choice::Chat(to),
            ) => self.tg.forward(to, from, message_ids),
            (Purpose::Forward { .. }, _) => {}
            (Purpose::Open, Choice::Chat(id)) => self.open_chat(id),
            (Purpose::Open, Choice::User(user_id)) => {
                let name = self
                    .users
                    .get(&user_id)
                    .cloned()
                    .unwrap_or_else(|| "your contact".into());
                self.finding = Some(Finding::new(&name));
                self.tg.find_private_chat(user_id, name);
            }
            (Purpose::Open, Choice::Username(name)) => {
                let request = format!("@{name}");
                self.finding = Some(Finding::new(&request));
                self.tg.find_username(name, request);
            }
            (Purpose::Open, Choice::Link(link)) => {
                self.finding = Some(Finding::new(&link));
                self.tg.find_link(link.clone(), link);
            }
        }
    }

    /// Asks before joining the chat an invite link leads to, saying what it
    /// is and what Telegram thinks of it.
    fn confirm_invite(&mut self, link: String, request: String, invite: Invite) {
        let kind = if invite.channel { "channel" } else { "group" };
        let mut lines = vec![
            invite.title,
            format!("A {kind} with {} members.", invite.members),
        ];
        if invite.by_request {
            lines.push("An admin has to let you in.".into());
        }
        let title = if invite.by_request {
            format!("Ask to join this {kind}?")
        } else {
            format!("Join this {kind}?")
        };
        let mut confirm = Confirm::new(title, lines, Confirmed::JoinLink { link, request });
        confirm.badge = invite.badge;
        self.confirm = Some(confirm);
    }

    /// `X`: takes back all your reactions on the message under the cursor,
    /// without the popup.
    fn remove_reactions(&mut self) {
        let Some(open) = &self.open else {
            return;
        };
        let yours = open.your_reactions();
        if yours.is_empty() {
            self.status = Some("You haven't reacted to this message".into());
            return;
        }
        for (message_id, kind) in yours {
            self.tg.react(open.chat_id, message_id, &kind, false);
        }
    }

    /// Resize mode takes the keys: `h` and `l` move the line between the
    /// chat list and the chat as you press them, `=` puts it back where it
    /// starts out, Enter keeps it and Esc puts back where it was.
    fn on_resize_key(&mut self, key: KeyEvent, ctrl: bool) {
        let Some(before) = self.resizing else {
            return;
        };
        // `h` and `l` move the line between the panes that way.
        let left = match self.settings.chat_list_side {
            Side::Left => -1,
            Side::Right => 1,
        };
        match key.code {
            KeyCode::Char('h') | KeyCode::Left => self.settings.resize_list(left),
            KeyCode::Char('l') | KeyCode::Right => self.settings.resize_list(-left),
            KeyCode::Char('=') => self.settings.chat_list_width = settings::DEFAULT_LIST_WIDTH,
            KeyCode::Esc => {
                self.settings.chat_list_width = before;
                self.resizing = None;
            }
            KeyCode::Enter => self.end_resize(),
            KeyCode::Char('r') if ctrl => self.end_resize(),
            _ => {}
        }
    }

    /// Leaves resize mode with the panes as they are, saved for next time.
    fn end_resize(&mut self) {
        let before = self.resizing.take();
        if before != Some(self.settings.chat_list_width)
            && let Err(e) = self.settings.save(&self.settings_path)
        {
            self.status = Some(format!("Couldn't save settings: {e:#}"));
        }
    }

    /// Tab while writing: the sticker panel. It opens at once and fills in
    /// as TDLib sends your recent and favorite stickers and your sets.
    fn open_stickers(&mut self) {
        let Some(open) = &self.open else {
            return;
        };
        if open.editing.is_some() {
            self.status = Some("An edit can't change a message into a sticker".into());
            return;
        }
        self.stickers = Some(StickerPanel::new(open.chat_id));
        self.tg.stickers(Source::Recent);
        self.tg.stickers(Source::Favorites);
        self.tg.sticker_sets();
    }

    /// The sticker panel takes the keys while it's open. In the grid,
    /// `h/j/k/l` move and `H/L` switch tabs; after `/`, keys type the search
    /// and the arrows move.
    fn on_sticker_key(&mut self, key: KeyEvent, ctrl: bool) {
        let Some(panel) = self.stickers.as_mut() else {
            return;
        };
        let searching = panel.query.is_some();
        let before = panel.search_query();
        match key.code {
            KeyCode::Enter => self.send_sticker(),
            KeyCode::Char('c') if ctrl => self.leave_insert(),
            KeyCode::Left => panel.move_by(-1),
            KeyCode::Right => panel.move_by(1),
            KeyCode::Up => panel.move_rows(-1),
            KeyCode::Down => panel.move_rows(1),
            KeyCode::Char('n') if ctrl => panel.move_by(1),
            KeyCode::Char('p') if ctrl => panel.move_by(-1),
            // Esc, or Backspace on an empty search, leaves the search first.
            KeyCode::Esc if searching => panel.leave_search(),
            KeyCode::Backspace if panel.query.as_ref().is_some_and(|q| q.is_empty()) => {
                panel.leave_search();
            }
            KeyCode::Backspace if searching => panel.edit_query(|q| {
                q.pop();
            }),
            KeyCode::Char('u' | 'w') if ctrl && searching => panel.edit_query(String::clear),
            KeyCode::Char(c) if searching && !ctrl => panel.edit_query(|q| q.push(c)),
            KeyCode::Char('h') => panel.move_by(-1),
            KeyCode::Char('l') => panel.move_by(1),
            KeyCode::Char('k') => panel.move_rows(-1),
            KeyCode::Char('j') => panel.move_rows(1),
            KeyCode::Char('H') => panel.switch(-1),
            KeyCode::Char('L') => panel.switch(1),
            KeyCode::Char('/') => panel.edit_query(|_| {}),
            // Back to writing.
            KeyCode::Esc | KeyCode::Tab | KeyCode::Char('i' | 'q') => self.stickers = None,
            _ => {}
        }
        self.find_stickers(before);
        self.load_sticker_set();
    }

    /// Asks TDLib for what the panel's search finds, if it's changed from
    /// `before`.
    fn find_stickers(&mut self, before: Option<String>) {
        if let Some(panel) = &self.stickers
            && let Some(query) = panel.search_query()
            && Some(&query) != before.as_ref()
        {
            self.tg.find_stickers(panel.chat_id, query);
        }
    }

    /// Asks for the stickers of the set the panel shows, the first time.
    fn load_sticker_set(&mut self) {
        if let Some(set_id) = self.stickers.as_mut().and_then(StickerPanel::pending_set) {
            self.tg.stickers(Source::Set(set_id));
        }
    }

    fn on_stickers(&mut self, source: Source, stickers: Option<Vec<tdlib_rs::types::Sticker>>) {
        let premium = self.premium;
        let Some(panel) = self.stickers.as_mut() else {
            return;
        };
        // After an error, TDLib's message is in the status bar, and the tab
        // shows no stickers.
        let stickers = stickers::convert(&stickers.unwrap_or_default(), premium);
        panel.set_stickers(source, stickers);
        // An empty Recent going away can show a set.
        self.load_sticker_set();
    }

    /// Enter in the sticker panel: sends the sticker under the cursor, as the
    /// reply if one is being written, and closes the panel. What's written
    /// in the composer stays there.
    fn send_sticker(&mut self) {
        let Some(panel) = &self.stickers else {
            return;
        };
        // Nothing to send while it's loading or nothing was found.
        let Some(sticker) = panel.current().cloned() else {
            return;
        };
        let Some(open) = self.open.as_mut().filter(|o| o.chat_id == panel.chat_id) else {
            return;
        };
        let reply_to = open.reply.take().map(|r| r.id);
        self.tg.send_sticker(open.chat_id, &sticker, reply_to);
        self.stickers = None;
        // The message arriving ends the typing status for everyone.
        self.typing = None;
        if self.settings.normal_after_send {
            self.focus = Focus::Messages;
        }
        self.jump_to_newest();
    }

    /// `gd`: from a reply to the message it answers, loading the history
    /// around it if needed. Ctrl-o comes back.
    fn go_to_replied(&mut self) {
        let Some(open) = self.open.as_mut() else {
            return;
        };
        match open.replied_jump() {
            Ok((from, to)) => {
                open.jumps.push(from);
                self.jump_to_message(to);
            }
            Err(why) => self.status = Some(why.into()),
        }
    }

    /// Ctrl-o: back to the reply the last `gd` left.
    fn jump_back(&mut self) {
        let Some(open) = self.open.as_mut() else {
            return;
        };
        match open.jumps.pop() {
            Some(id) => self.jump_to_message(id),
            None => self.status = Some("Nothing to go back to".into()),
        }
    }

    /// Files open in their default app once downloaded; links in the browser.
    fn open_target(&mut self, target: Target) {
        match target {
            Target::File(file) => {
                // TDLib answers at once if the file is already downloaded.
                if self.opening.insert(file.id) {
                    self.tg.download(file.id);
                }
            }
            // A chat, a message or an invite on Telegram opens here. Where
            // the link really goes decides, not its words, so it can't be
            // disguised; anything tuigram can't open goes to the browser.
            Target::Link(link) if picker::telegram_link(&link.url) => {
                self.finding = Some(Finding {
                    request: link.url.clone(),
                    link: Some(link.clone()),
                });
                self.tg.find_link(link.url.clone(), link.url);
            }
            Target::Link(link) => self.open_link_outside(link),
            Target::Text(_) => {}
        }
    }

    /// Opens a link in the browser, asking first if its words say something
    /// other than where it goes.
    fn open_link_outside(&mut self, link: Link) {
        match link {
            Link {
                url,
                disguise: Some(shown),
            } => {
                // Browsers show other scripts' letters as such, so a look-alike
                // host can pass for a familiar one.
                let site = link_host(&url).map(|host| match host.is_ascii() {
                    true => host,
                    false => format!("{host} (has non-Latin letters)"),
                });
                let mut confirm = Confirm::new(
                    "Open this link?",
                    vec![
                        format!("The text says: {shown}"),
                        format!("Full address:  {url}"),
                    ],
                    Confirmed::OpenLink(url),
                );
                confirm.site = site;
                self.confirm = Some(confirm);
            }
            link => self.open_externally(&link.url),
        }
    }

    /// A file finished downloading for Enter: opened at once if it's a
    /// type that can't run code, else only after a `y`.
    fn open_downloaded(&mut self, path: String) {
        mark_downloaded(&path);
        if safe_to_open(&path) {
            self.open_externally(&path);
            return;
        }
        // The file name is the sender's.
        let name = text::clean(
            &Path::new(&path)
                .file_name()
                .map(|n| n.to_string_lossy().into_owned())
                .unwrap_or_default(),
        );
        // A slow download can finish while you're busy with something else:
        // a warning popping up then would take keys meant for that.
        if self.busy() {
            self.status = Some(format!(
                "{name} downloaded: press Enter on it again to open it"
            ));
            return;
        }
        self.confirm = Some(Confirm::new(
            format!("Open {name}?"),
            vec![
                "Files like this can run programs on your computer.".into(),
                "Only open it if you trust whoever sent it.".into(),
            ],
            Confirmed::OpenFile(path),
        ));
    }

    /// A popup, a prompt or the composer is taking keys.
    fn busy(&self) -> bool {
        self.confirm.is_some()
            || self.settings_menu.is_some()
            || self.delete_menu.is_some()
            || self.react_menu.is_some()
            || self.vote_menu.is_some()
            || self.menu.is_some()
            || self.picker.is_some()
            || self.resizing.is_some()
            || self.prompt.is_some()
            || self.focus == Focus::Input
    }

    fn open_externally(&mut self, target: &str) {
        if let Err(e) = open_externally(target) {
            self.status = Some(format!("Couldn't open it: {e}"));
        }
    }

    /// The confirmation takes all keys while it's up. Only `y` goes ahead, so
    /// an Enter pressed out of habit can't.
    fn on_confirm_key(&mut self, key: KeyEvent) {
        match key.code {
            KeyCode::Char('y')
                if self
                    .confirm
                    .as_ref()
                    .is_some_and(|c| c.shown.elapsed() >= CONFIRM_GRACE) =>
            {
                if let Some(confirm) = self.confirm.take() {
                    match confirm.action {
                        Confirmed::OpenFile(target) | Confirmed::OpenLink(target) => {
                            self.open_externally(&target)
                        }
                        Confirmed::Edit { id, text } => self.start_edit(id, text),
                        Confirmed::Join(chat_id) => self.tg.join_chat(chat_id),
                        Confirmed::Leave(chat_id) => self.tg.leave_chat(chat_id),
                        Confirmed::JoinLink { link, request } => {
                            self.finding = Some(Finding::new(&request));
                            self.tg.join_by_link(link, request);
                        }
                    }
                }
            }
            KeyCode::Char('n' | 'q') | KeyCode::Esc => self.confirm = None,
            _ => {}
        }
    }

    /// `y`: copies what's in the message under the cursor, like Telegram's
    /// Copy. With links or media as well as text, a menu asks which.
    fn copy_selected(&mut self) {
        let Some(open) = &self.open else {
            return;
        };
        let Some(msg) = open.cursor_id().and_then(|id| open.messages.get(&id)) else {
            return;
        };
        let mut targets = Vec::new();
        if !msg.source_text.is_empty() {
            targets.push(Target::Text(msg.source_text.clone()));
        }
        targets.extend(msg.links.iter().cloned().map(Target::Link));
        targets.extend(msg.file.clone().map(Target::File));
        match targets.len() {
            0 => self.status = Some("Nothing to copy in this message".into()),
            1 => self.copy_target(targets.remove(0)),
            _ => {
                self.menu = Some(PickMenu {
                    action: MenuAction::Copy,
                    targets,
                    selected: 0,
                })
            }
        }
    }

    /// Text and links are copied at once. Media is downloaded first (TDLib
    /// answers at once if it already is), then copied by `copy_downloaded`.
    fn copy_target(&mut self, target: Target) {
        let text = match target {
            Target::Text(text) => text,
            Target::Link(link) => link.url,
            Target::File(file) => {
                let id = file.id;
                if self.copying.insert(id, file).is_none() {
                    self.tg.download(id);
                }
                return;
            }
        };
        match self.clipboard.copy_text(&text) {
            Ok(Copied::System) => self.show_toast("Copied", &text),
            Ok(Copied::Terminal) => self.show_toast("Sent to the terminal's clipboard", &text),
            Err(e) => self.status = Some(format!("Couldn't copy: {e}")),
        }
    }

    /// Photos are copied as images, after decoding off the UI thread; other
    /// files as files, so pasting attaches them.
    fn copy_downloaded(&mut self, file: MediaFile, path: &str) {
        if file.photo {
            self.clipboard.decode_image(path.to_string(), file.label);
            return;
        }
        match self.clipboard.copy_file(Path::new(path)) {
            Ok(()) => self.show_toast("Copied", &file.label),
            Err(e) => self.status = Some(format!("Couldn't copy: {e}")),
        }
    }

    fn on_clipboard(&mut self, event: ClipboardEvent) {
        match event {
            ClipboardEvent::Decoded(decoded) => self.on_decoded(decoded),
            ClipboardEvent::Pasted(pasted) => self.on_pasted(pasted),
        }
    }

    /// Whether files can go with the next message: a chat is open, and its
    /// composer isn't editing a message, which can't take any. Says why not
    /// in the status bar.
    fn can_attach(&mut self) -> bool {
        match &self.open {
            None => false,
            Some(open) if open.editing.is_some() => {
                self.status = Some("Files can't be added to an edit".into());
                false
            }
            Some(_) => true,
        }
    }

    /// Adds files to the next message and goes to Insert mode for the
    /// caption. `pasted` is the paste they came from, for Ctrl-z. Files that
    /// can't be sent are left out, and the status bar says why. Returns how
    /// many were added.
    fn attach(&mut self, paths: Vec<PathBuf>, pasted: Option<String>) -> usize {
        if !self.can_attach() {
            return 0;
        }
        let Some(open) = self.open.as_mut() else {
            return 0;
        };
        let mut added = 0;
        for path in paths {
            match Attachment::new(&path) {
                Ok(attachment) => {
                    open.attachments.push(attachment);
                    added += 1;
                }
                Err(e) => self.status = Some(e),
            }
        }
        if added == 0 {
            return 0;
        }
        open.dropped = pasted.map(|text| Dropped { text, count: added });
        self.focus = Focus::Input;
        added
    }

    /// A paste into the chat (Cmd-V, or files dropped on the window). Paths
    /// to files are attached, which Ctrl-z undoes; other text is typed in
    /// Insert mode. While editing, it's all text.
    fn on_paste(&mut self, text: String) {
        let editing = self.open.as_ref().is_some_and(|o| o.editing.is_some());
        if !editing && let Some(paths) = attach::pasted_paths(&text) {
            self.attach(paths, Some(text));
            return;
        }
        if self.focus == Focus::Input
            && let Some(panel) = self.stickers.as_mut()
        {
            // Into the sticker search: pasting an emoji is a quick way to
            // find stickers for it.
            let before = panel.search_query();
            let line = text::clean(&text)
                .split_whitespace()
                .collect::<Vec<_>>()
                .join(" ");
            panel.edit_query(|q| q.push_str(&line));
            self.find_stickers(before);
            return;
        }
        if self.focus == Focus::Input {
            self.composer.insert_str(text.replace('\r', ""));
            self.on_composer_edit();
        }
    }

    /// `p` and Ctrl-v: what's on the system clipboard goes in the message,
    /// once it's been read off the UI thread (`on_pasted`).
    fn paste_clipboard(&mut self) {
        let Some(open) = &self.open else {
            return;
        };
        self.clipboard.paste(open.chat_id);
        self.pasting = true;
    }

    fn on_pasted(&mut self, pasted: Pasted) {
        self.pasting = false;
        // Not into another chat than the one it was meant for.
        if self
            .open
            .as_ref()
            .is_none_or(|o| o.chat_id != pasted.chat_id)
        {
            return;
        }
        match pasted.content {
            Ok(Paste::Files(paths)) => {
                // Copied files have absolute paths; anything else would be
                // looked for wherever tuigram was started.
                let (paths, relative): (Vec<_>, Vec<_>) =
                    paths.into_iter().partition(|p| p.is_absolute());
                if !relative.is_empty() {
                    self.status = Some("Copied files without a full path were left out".into());
                }
                self.attach(paths, None);
            }
            Ok(Paste::Image(path)) => {
                // Not the made-up name it was saved under.
                if self.attach(vec![path], None) == 1
                    && let Some(last) = self.open.as_mut().and_then(|o| o.attachments.last_mut())
                {
                    last.name = "Pasted image".into();
                }
            }
            Ok(Paste::Text(text)) => {
                self.focus = Focus::Input;
                self.on_paste(text);
            }
            Err(e) => self.status = Some(e),
        }
    }

    /// Ctrl-t: the attached photos go as files, uncompressed and with their
    /// names, or back to photos.
    fn toggle_as_files(&mut self) {
        let Some(open) = self.open.as_mut() else {
            return;
        };
        if open.attachments.iter().any(|a| a.kind.is_photo()) {
            open.as_files = !open.as_files;
        } else if !open.attachments.is_empty() {
            self.status = Some("These go as files already: only photos can go either way".into());
        }
    }

    /// Ctrl-z: files a paste just attached go back to being the text that
    /// was pasted, for a path that was meant to be sent as words.
    fn undo_drop(&mut self) {
        let Some(text) = self.open.as_mut().and_then(OpenChat::undo_drop) else {
            return;
        };
        self.composer.insert_str(text.replace('\r', ""));
        self.on_composer_edit();
    }

    fn on_decoded(&mut self, decoded: Decoded) {
        let result = decoded
            .image
            .and_then(|image| self.clipboard.copy_image(image).map_err(|e| e.to_string()));
        match result {
            Ok(()) => self.show_toast("Copied", &decoded.label),
            Err(e) => self.status = Some(format!("Couldn't copy: {e}")),
        }
    }

    fn show_toast(&mut self, title: &str, detail: &str) {
        self.toast = Some(Toast {
            title: title.into(),
            detail: detail.split_whitespace().collect::<Vec<_>>().join(" "),
            until: Instant::now() + TOAST_TIME,
        });
    }

    /// The open menu takes all keys while it's up.
    fn on_menu_key(&mut self, key: KeyEvent) {
        let Some(menu) = self.menu.as_mut() else {
            return;
        };
        let last = menu.targets.len() - 1;
        match key.code {
            KeyCode::Char('j') | KeyCode::Down => menu.selected = (menu.selected + 1).min(last),
            KeyCode::Char('k') | KeyCode::Up => menu.selected = menu.selected.saturating_sub(1),
            KeyCode::Enter | KeyCode::Char('l') => {
                let index = menu.selected;
                self.pick(index);
            }
            // 1-9 pick an item directly.
            KeyCode::Char(c @ '1'..='9') => {
                let index = c as usize - '1' as usize;
                if index <= last {
                    self.pick(index);
                }
            }
            KeyCode::Esc | KeyCode::Char('q' | 'h') => self.menu = None,
            _ => {}
        }
    }

    /// Opens or copies item `index` of the menu, and closes it.
    fn pick(&mut self, index: usize) {
        let Some(mut menu) = self.menu.take() else {
            return;
        };
        let target = menu.targets.swap_remove(index);
        match menu.action {
            MenuAction::Open => self.open_target(target),
            MenuAction::Copy => self.copy_target(target),
        }
    }

    /// The `?` popup takes all keys while it's up. Tab (or h/l) switches
    /// between the shortcuts and the settings. On the settings, Enter or
    /// Space changes the one under the cursor and saves it at once.
    fn on_settings_key(&mut self, key: KeyEvent, ctrl: bool) {
        let Some(menu) = self.settings_menu.as_mut() else {
            return;
        };
        match key.code {
            KeyCode::Tab | KeyCode::BackTab | KeyCode::Char('h' | 'l') => {
                menu.tab = match menu.tab {
                    HelpTab::Shortcuts => HelpTab::Settings,
                    HelpTab::Settings => HelpTab::Shortcuts,
                };
                return;
            }
            KeyCode::Enter | KeyCode::Char(' ') if menu.tab == HelpTab::Settings => {
                self.change_setting();
                return;
            }
            KeyCode::Esc | KeyCode::Char('q' | '?') => {
                self.settings_menu = None;
                return;
            }
            _ => {}
        }
        let delta = match key.code {
            KeyCode::Char('j') | KeyCode::Down => 1,
            KeyCode::Char('k') | KeyCode::Up => -1,
            KeyCode::Char('d') if ctrl => HALF_PAGE,
            KeyCode::Char('u') if ctrl => -HALF_PAGE,
            KeyCode::Char('g') => isize::MIN,
            KeyCode::Char('G') => isize::MAX,
            _ => return,
        };
        match menu.tab {
            // Drawing stops it at the end of the list.
            HelpTab::Shortcuts => menu.scroll = menu.scroll.saturating_add_signed(delta),
            HelpTab::Settings => {
                let last = SettingsMenu::THEMES + self.themes.list.len() - 1;
                menu.selected = menu.selected.saturating_add_signed(delta).min(last);
            }
        }
    }

    /// Enter or Space on the settings tab: picks the theme under the cursor,
    /// or turns the setting under it on or off. Saved at once.
    fn change_setting(&mut self) {
        let Some(menu) = self.settings_menu.as_mut() else {
            return;
        };
        let settings = &mut self.settings;
        match menu.selected {
            i if i >= SettingsMenu::THEMES => {
                let Some(theme) = self.themes.list.get(i - SettingsMenu::THEMES) else {
                    return;
                };
                match &theme.colors {
                    Ok(colors) => {
                        self.colors = *colors;
                        settings.theme = theme.id.clone();
                    }
                    Err(e) => {
                        self.status = Some(format!("Theme not used: {e}"));
                        return;
                    }
                }
            }
            SettingsMenu::NOTIFICATIONS => {
                // Back on, they go out the way they did before, e.g. "bell".
                let on = match menu.saved_notifications {
                    Notifications::Off => Notifications::Auto,
                    saved => saved,
                };
                let next = match settings.notifications {
                    Notifications::Off => on,
                    _ => Notifications::Off,
                };
                self.set_notifications(next);
            }
            SettingsMenu::CHAT_GAPS => settings.chat_gaps = !settings.chat_gaps,
            SettingsMenu::LIST_RIGHT => {
                settings.chat_list_side = match settings.chat_list_side {
                    Side::Left => Side::Right,
                    Side::Right => Side::Left,
                };
            }
            SettingsMenu::BLOCK_GAPS => settings.block_gaps = !settings.block_gaps,
            SettingsMenu::AFTER_SEND => settings.normal_after_send = !settings.normal_after_send,
            _ => return,
        }
        if let Err(e) = self.settings.save(&self.settings_path) {
            self.status = Some(format!("Settings not saved: {e:#}"));
        }
    }

    /// Takes effect at once; the settings popup saves it.
    fn set_notifications(&mut self, notifications: Notifications) {
        self.settings.notifications = notifications;
        self.notify_with = notifications.resolve(|name| std::env::var(name).ok());
        if notifications == Notifications::Off {
            self.notifier.clear();
        }
    }

    fn load_older_messages(&mut self) {
        let Some(open) = self.open.as_mut() else {
            return;
        };
        if open.loading.is_some() || open.all_loaded {
            return;
        }
        let page = open.oldest_id().map_or(Page::Latest, Page::Older);
        open.loading = Some(page);
        self.tg.load_history(open.chat_id, page, HISTORY_PAGE);
    }

    /// Only needed after jumping to an old message.
    fn load_newer_messages(&mut self) {
        let Some(open) = self.open.as_mut() else {
            return;
        };
        if open.loading.is_some() || open.at_newest {
            return;
        }
        let Some(newest) = open.newest_id() else {
            return;
        };
        let page = Page::Newer(newest);
        open.loading = Some(page);
        self.tg.load_history(open.chat_id, page, HISTORY_PAGE);
    }

    fn move_message_cursor(&mut self, delta: isize) {
        let Some(open) = self.open.as_mut() else {
            return;
        };
        // `G` goes to the real newest message, not the newest loaded one.
        if delta == isize::MAX && !open.at_newest {
            self.jump_to_newest();
            return;
        }
        let Some(index) = open.move_cursor(delta) else {
            return;
        };
        let len = open.messages.len();
        if index < LOAD_AHEAD {
            self.load_older_messages();
        }
        if index + LOAD_AHEAD >= len {
            self.load_newer_messages();
        }
    }

    /// Moves the chat list cursor by `delta` rows, clamped to the list.
    fn move_chat_cursor(&mut self, delta: isize) {
        let ids = self.chats.ids();
        if ids.is_empty() {
            return;
        }
        let last = ids.len() - 1;
        let index = match self
            .selected
            .and_then(|id| ids.iter().position(|&x| x == id))
        {
            Some(current) => current.saturating_add_signed(delta).min(last),
            None => 0,
        };
        self.selected = Some(ids[index]);

        if index + LOAD_AHEAD >= last {
            self.load_more_chats();
        }
    }

    fn load_more_chats(&mut self) {
        if self.chats_loading || self.all_chats_loaded {
            return;
        }
        self.chats_loading = true;
        self.tg.load_chats(CHAT_PAGE);
    }

    /// `p` in the list: pins the selected chat to the top, or unpins it, on
    /// Telegram, so your other devices show it too.
    fn toggle_pin(&mut self) {
        let Some(chat_id) = self.selected else {
            return;
        };
        let pinned = self.chats.get(chat_id).is_some_and(|c| c.pinned);
        self.tg.pin_chat(chat_id, !pinned);
    }

    /// `m` in the list: mutes the selected chat for good, or unmutes it, on
    /// Telegram.
    fn toggle_mute(&mut self) {
        let Some(chat_id) = self.selected else {
            return;
        };
        let mute = !self.chats.muted(chat_id);
        if let Some(settings) = self.chats.with_mute(chat_id, mute) {
            self.tg.set_notifications(chat_id, settings);
        }
    }

    /// `H`: marks the selected chat so it's easy to find, or unmarks it.
    fn toggle_highlight(&mut self) {
        let Some(chat_id) = self.selected else {
            return;
        };
        self.settings.highlighted_chats = self.chats.toggle_highlight(chat_id);
        if let Err(e) = self.settings.save(&self.settings_path) {
            self.status = Some(format!("Highlight not saved: {e:#}"));
        }
    }

    fn quit(&mut self) {
        if self.quit_deadline.is_some() {
            // Second press: stop waiting for TDLib.
            self.exit = true;
            return;
        }
        self.tg.close();
        self.quit_deadline = Some(Instant::now() + CLOSE_TIMEOUT);
    }
}

/// SIGHUP (the terminal closed, an SSH connection dropped) and SIGTERM, one
/// message each. They'd otherwise end tuigram on the spot, leaving the user
/// online on Telegram for minutes.
fn quit_signals() -> UnboundedReceiver<()> {
    let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
    #[cfg(unix)]
    tokio::spawn(async move {
        use tokio::signal::unix::{SignalKind, signal};
        let (Ok(mut hangup), Ok(mut terminate)) = (
            signal(SignalKind::hangup()),
            signal(SignalKind::terminate()),
        ) else {
            return;
        };
        loop {
            tokio::select! {
                _ = hangup.recv() => {}
                _ = terminate.recv() => {}
            }
            if tx.send(()).is_err() {
                return;
            }
        }
    });
    #[cfg(not(unix))]
    drop(tx);
    rx
}

/// Hands a file path or web link to the system: the default app for a file
/// (Preview for images on macOS, QuickTime for video…), the browser for a link.
/// No shell is involved, so a `&` or `|` in a link stays part of it: Windows
/// uses ShellExecute rather than `cmd /C start`, which would run what follows.
fn open_externally(target: &str) -> std::io::Result<()> {
    // `open` on macOS waits for LaunchServices, which can take a moment, and
    // reports nothing useful, so it gets a thread of its own.
    if cfg!(target_os = "macos") {
        let target = target.to_string();
        std::thread::spawn(move || open::that_detached(target));
        Ok(())
    } else {
        open::that_detached(target)
    }
}

/// Marks a downloaded file as coming from the internet, as browsers do, so
/// the system's own checks apply when it's opened: Gatekeeper on macOS,
/// SmartScreen and Office's Protected View on Windows. Best effort.
fn mark_downloaded(path: &str) {
    #[cfg(target_os = "macos")]
    {
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map_or(0, |d| d.as_secs());
        let _ = process::Command::new("/usr/bin/xattr")
            .args([
                "-w",
                "com.apple.quarantine",
                &format!("0081;{now:x};tuigram;"),
                path,
            ])
            .stdin(Stdio::null())
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .status();
    }
    #[cfg(windows)]
    {
        let _ = std::fs::write(
            format!("{path}:Zone.Identifier"),
            "[ZoneTransfer]\r\nZoneId=3\r\n",
        );
    }
    #[cfg(not(any(target_os = "macos", windows)))]
    let _ = path;
}

/// A one-line prompt input holding `text`, with the cursor at its end.
fn prompt_input(text: &str) -> TextArea<'static> {
    let mut input = TextArea::new(vec![text.to_string()]);
    input.set_cursor_line_style(Style::default());
    input.set_cursor_style(Style::default().reversed());
    input.move_cursor(ratatui_textarea::CursorMove::End);
    input
}

fn login_screen(step: LoginStep) -> Screen {
    Screen::Login(Box::new(Login::new(step)))
}

pub fn new_composer() -> TextArea<'static> {
    let mut composer = TextArea::default();
    composer.set_cursor_line_style(Style::default());
    composer
}

fn code_destination(kind: &AuthenticationCodeType) -> &'static str {
    match kind {
        AuthenticationCodeType::TelegramMessage(_) => "to your Telegram app on another device",
        AuthenticationCodeType::Sms(_)
        | AuthenticationCodeType::SmsWord(_)
        | AuthenticationCodeType::SmsPhrase(_) => "by SMS",
        AuthenticationCodeType::Call(_) => "by phone call",
        AuthenticationCodeType::MissedCall(_) | AuthenticationCodeType::FlashCall(_) => {
            "as a missed call: enter the last digits of the calling number"
        }
        AuthenticationCodeType::Fragment(_) => "to fragment.com",
        _ => "to one of your devices",
    }
}

/// Seconds since 1970, like the dates TDLib gives.
fn unix_now() -> i32 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map_or(0, |d| d.as_secs() as i32)
}

#[cfg(test)]
mod tests {
    use ratatui::Terminal;
    use ratatui::backend::TestBackend;
    use ratatui::style::Color;
    use ratatui_image::picker::Picker;
    use tokio::sync::mpsc::unbounded_channel;

    use super::*;

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

    /// The screen's rows as text.
    fn screen(app: &mut App) -> Vec<String> {
        screen_of(app, 100)
    }

    fn screen_of(app: &mut App, width: u16) -> Vec<String> {
        let mut terminal = Terminal::new(TestBackend::new(width, 20)).unwrap();
        terminal.draw(|f| ui::draw(f, app)).unwrap();
        let buf = terminal.backend().buffer();
        (0..buf.area.height)
            .map(|y| (0..buf.area.width).map(|x| buf[(x, y)].symbol()).collect())
            .collect()
    }

    #[test]
    fn the_chat_list_can_go_on_the_right_where_h_and_l_follow_it() {
        let dir = std::env::temp_dir().join(format!("tuigram-side-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let images = Images::new(Picker::halfblocks(), unbounded_channel().0);
        let tg = Tg::detached(unbounded_channel().0);
        let mut app = crate::demo::demo_app(tg, images, &dir);
        app.focus = Focus::Chats;
        let none = KeyModifiers::NONE;
        let saved = || Settings::load(&settings::path(&dir)).unwrap();
        // The text left and right of the first pane's top right corner.
        let halves = |app: &mut App| {
            let top = screen(app).remove(0);
            let (left, right) = top.split_once('┐').unwrap();
            (left.to_string(), right.to_string())
        };

        press(&mut app, KeyCode::Char('?'), none);
        press(&mut app, KeyCode::Tab, none);
        app.settings_menu.as_mut().unwrap().selected = SettingsMenu::LIST_RIGHT;
        press(&mut app, KeyCode::Char(' '), none);
        assert_eq!(saved().chat_list_side, Side::Right, "saved at once");
        press(&mut app, KeyCode::Enter, none);
        assert_eq!(saved().chat_list_side, Side::Left, "Enter toggles too");
        assert!(app.settings_menu.is_some(), "the popup stays open");
        press(&mut app, KeyCode::Enter, none);
        press(&mut app, KeyCode::Esc, none);
        assert!(app.settings_menu.is_none());
        assert_eq!(saved().chat_list_side, Side::Right, "Esc keeps it");
        let (left, right) = halves(&mut app);
        assert!(
            left.contains("Weekend Hike") && right.contains("Chats ("),
            "{left}┐{right}"
        );

        press(&mut app, KeyCode::Char('l'), none);
        assert!(app.focus == Focus::Chats, "l points away from the chat");
        press(&mut app, KeyCode::Char('h'), none);
        assert!(
            app.focus == Focus::Messages,
            "h goes to the chat, on the left"
        );
        // Wide enough for every hint.
        let status = screen_of(&mut app, 300).pop().unwrap();
        assert!(
            status.contains("l back") && !status.contains("h back"),
            "{status}"
        );
        press(&mut app, KeyCode::Char('h'), none);
        assert!(app.focus == Focus::Messages);
        press(&mut app, KeyCode::Char('l'), none);
        assert!(app.focus == Focus::Chats, "l goes back to the list");

        // h moves the line left, which widens a list on the right.
        press(&mut app, KeyCode::Char('r'), KeyModifiers::CONTROL);
        press(&mut app, KeyCode::Char('h'), none);
        assert_eq!(app.settings.list_width(), 40);
        press(&mut app, KeyCode::Esc, none);
        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn without_focus_reports_a_minute_without_a_key_counts_as_away() {
        let images = Images::new(Picker::halfblocks(), unbounded_channel().0);
        let tg = Tg::detached(unbounded_channel().0);
        let mut app = crate::demo::demo_app(tg, images, &std::env::temp_dir());
        app.focus = Focus::Messages;
        let chat = app.open.as_ref().unwrap().chat_id;
        assert!(
            app.watching(chat) && app.sees(chat),
            "a key was just pressed"
        );

        // tmux without focus-events, or a detached session.
        // By the wall clock: Instant can't go back past boot on Windows.
        app.last_input_wall = SystemTime::now() - (IDLE_AFTER + Duration::from_secs(1));
        assert!(!app.watching(chat), "new messages aren't marked read");
        assert!(!app.sees(chat), "and they notify");

        // A terminal that reports focus is believed instead, for a while.
        app.focus_reported = true;
        assert!(app.watching(chat) && app.sees(chat));
        app.last_input_wall = SystemTime::now() - AWAY_AFTER;
        assert!(
            !app.watching(chat),
            "not for good: the screen may be left on"
        );
        assert!(app.sees(chat), "the window has focus, so no notification");
        app.last_input_wall = SystemTime::now();
        app.terminal_focused = false;
        assert!(!app.watching(chat) && !app.sees(chat));
    }

    #[test]
    fn time_the_computer_slept_counts_as_time_away() {
        let mut app = test_app("sleep");
        app.focus = Focus::Messages;
        let chat = app.open.as_ref().unwrap().chat_id;
        // A key ten seconds before a two-hour sleep: the monotonic clock
        // didn't run while asleep, the wall clock did.
        app.last_input = Instant::now();
        app.last_input_wall = SystemTime::now() - Duration::from_secs(2 * 3600);
        assert!(!app.watching(chat), "nothing is marked read on waking");
        app.online = false;
        app.update_online();
        assert!(!app.online, "and you aren't shown online");

        // A wall clock set back doesn't make you away.
        app.last_input_wall = SystemTime::now() + Duration::from_secs(3600);
        assert!(app.watching(chat));
    }

    #[test]
    fn once_the_terminal_is_gone_nothing_more_is_marked_read() {
        let images = Images::new(Picker::halfblocks(), unbounded_channel().0);
        let tg = Tg::detached(unbounded_channel().0);
        let mut app = crate::demo::demo_app(tg, images, &std::env::temp_dir());
        app.focus = Focus::Messages;
        let chat = app.open.as_ref().unwrap().chat_id;
        assert!(app.watching(chat));
        // Already closing, so the detached client gets no request.
        app.quit_deadline = Some(Instant::now() + CLOSE_TIMEOUT);
        app.hang_up();
        assert!(!app.watching(chat) && !app.sees(chat));
    }

    #[test]
    fn a_theme_is_used_and_saved_as_soon_as_it_is_picked() {
        let dir = std::env::temp_dir().join(format!("tuigram-theme-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let images = Images::new(Picker::halfblocks(), unbounded_channel().0);
        let tg = Tg::detached(unbounded_channel().0);
        let mut app = crate::demo::demo_app(tg, images, &dir);
        let none = KeyModifiers::NONE;
        press(&mut app, KeyCode::Char('?'), none);
        press(&mut app, KeyCode::Tab, none);
        // The themes are the last rows.
        press(&mut app, KeyCode::Char('G'), none);
        assert_eq!(app.settings.theme, "mocha", "moving doesn't change it");
        press(&mut app, KeyCode::Char(' '), none);
        assert_eq!(app.settings.theme, "rose-pine");
        assert_eq!(app.colors, app.themes.colors("rose-pine").unwrap());
        let saved = Settings::load(&settings::path(&dir)).unwrap();
        assert_eq!(saved.theme, "rose-pine");
        press(&mut app, KeyCode::Char('q'), none);
        assert_eq!(app.settings.theme, "rose-pine", "closing keeps it");
        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn themes_in_the_data_folder_are_read_again_when_the_popup_opens() {
        let dir = std::env::temp_dir().join(format!("tuigram-own-theme-{}", std::process::id()));
        std::fs::create_dir_all(dir.join("themes")).unwrap();
        let images = Images::new(Picker::halfblocks(), unbounded_channel().0);
        let tg = Tg::detached(unbounded_channel().0);
        let mut app = crate::demo::demo_app(tg, images, &dir);
        let none = KeyModifiers::NONE;
        let file = dir.join("themes/mine.toml");
        app.settings.theme = "mine".into();
        std::fs::write(&file, "inherits = \"mocha\"\n[colors]\nbg = \"#000000\"").unwrap();
        press(&mut app, KeyCode::Char('?'), none);
        assert_eq!(app.colors.bg, Color::Rgb(0, 0, 0));
        assert_eq!(app.status, None);
        press(&mut app, KeyCode::Esc, none);

        // A broken file leaves the default theme in use, saying why.
        std::fs::write(&file, "inherits = 3").unwrap();
        press(&mut app, KeyCode::Char('?'), none);
        assert_eq!(app.colors, Colors::default());
        let status = app.status.clone().unwrap();
        assert!(status.contains("mine.toml: line 1"), "{status}");
        assert_eq!(app.settings.theme, "mine", "kept, for when it's fixed");

        // Picking it says why too, and changes nothing.
        press(&mut app, KeyCode::Tab, none);
        press(&mut app, KeyCode::Char('G'), none);
        press(&mut app, KeyCode::Enter, none);
        assert!(app.status.as_ref().unwrap().contains("mine.toml"));
        assert_eq!(app.colors, Colors::default());
        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn ctrl_r_resizes_the_panes_and_enter_keeps_it_for_next_time() {
        let dir = std::env::temp_dir().join(format!("tuigram-resize-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let images = Images::new(Picker::halfblocks(), unbounded_channel().0);
        let tg = Tg::detached(unbounded_channel().0);
        let mut app = crate::demo::demo_app(tg, images, &dir);
        app.focus = Focus::Messages;
        // Where the chat list's top right corner is.
        let edge = |rows: &[String]| rows[0].chars().position(|c| c == '┐').unwrap();
        let none = KeyModifiers::NONE;
        assert_eq!(edge(&screen(&mut app)), 34, "35% of 100 columns");

        press(&mut app, KeyCode::Char('r'), KeyModifiers::CONTROL);
        assert!(app.open.as_ref().unwrap().reply.is_none(), "not a reply");
        press(&mut app, KeyCode::Char('l'), none);
        press(&mut app, KeyCode::Char('l'), none);
        let rows = screen(&mut app);
        assert_eq!(edge(&rows), 44, "wider as you press");
        let status = rows.last().unwrap();
        assert!(
            status.contains(" RESIZE ") && status.contains("chat list 45%"),
            "{status}"
        );

        press(&mut app, KeyCode::Enter, none);
        assert!(app.resizing.is_none());
        let saved = Settings::load(&settings::path(&dir)).unwrap();
        assert_eq!(saved.chat_list_width, 45);

        press(&mut app, KeyCode::Char('r'), KeyModifiers::CONTROL);
        press(&mut app, KeyCode::Char('h'), none);
        assert_eq!(edge(&screen(&mut app)), 39);
        press(&mut app, KeyCode::Esc, none);
        assert_eq!(edge(&screen(&mut app)), 44, "Esc puts it back");
        assert!(app.focus == Focus::Messages, "and stays in the chat");
        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn only_files_that_cant_run_code_open_without_asking() {
        for path in [
            "/d/photo.JPG",
            "/d/clip.mp4",
            "/d/report.pdf",
            "/d/notes.txt",
        ] {
            assert!(safe_to_open(path), "{path}");
        }
        for path in [
            "/d/setup.exe",
            "/d/run.bat",
            "/d/x.command",
            "/d/x.terminal",
            "/d/app.jar",
            "/d/page.html",
            "/d/invoice.pdf.exe",
            "/d/no-extension",
            "/d/data.csv",
        ] {
            assert!(!safe_to_open(path), "{path}");
        }
    }

    /// The demo app, with its data in a temp folder of its own.
    fn test_app(tag: &str) -> App {
        // One folder per test, reused by later runs rather than piling up.
        let dir = std::env::temp_dir().join(format!("tuigram-test-{tag}"));
        std::fs::create_dir_all(&dir).unwrap();
        let images = Images::new(Picker::halfblocks(), unbounded_channel().0);
        crate::demo::demo_app(Tg::detached(unbounded_channel().0), images, &dir)
    }

    #[test]
    fn f_opens_a_list_of_your_chats_to_forward_to_saved_messages_first() {
        let mut app = test_app("forward");
        app.focus = Focus::Messages;
        let none = KeyModifiers::NONE;
        press(&mut app, KeyCode::Char('f'), none);
        let picker = app.picker.as_ref().expect("the picker is open");
        let Purpose::Forward {
            from, message_ids, ..
        } = &picker.purpose
        else {
            panic!("forwarding");
        };
        let open = app.open.as_ref().unwrap();
        assert_eq!(*from, open.chat_id);
        assert_eq!(message_ids, &[open.cursor_id().unwrap()]);
        assert!(
            matches!(picker.choices(&app.chats)[0], Choice::Chat(id) if app.chats.is_saved(id)),
            "Saved Messages first"
        );
        let rows = screen(&mut app);
        assert!(rows.iter().any(|r| r.contains("Forward to")), "{rows:#?}");
        assert!(rows.iter().any(|r| r.contains("Saved Messages")));

        // Letters type the search, even j and k.
        for c in "tokyo".chars() {
            press(&mut app, KeyCode::Char(c), none);
        }
        let picker = app.picker.as_ref().unwrap();
        assert_eq!(picker.query, "tokyo");
        let titles: Vec<&str> = picker
            .choices(&app.chats)
            .iter()
            .map(|c| match c {
                Choice::Chat(id) => app.chats.title(*id).unwrap(),
                _ => "",
            })
            .collect();
        assert_eq!(titles, ["Tokyo Trip"]);
        press(&mut app, KeyCode::Esc, none);
        assert!(app.picker.is_none());
    }

    #[test]
    fn s_finds_a_chat_by_username_or_link_and_pastes_go_into_its_search() {
        let mut app = test_app("find");
        let none = KeyModifiers::NONE;
        press(&mut app, KeyCode::Char('s'), none);
        assert!(app.picker.as_ref().is_some_and(|p| !p.forwarding()));
        for c in "@durov".chars() {
            press(&mut app, KeyCode::Char(c), none);
        }
        let rows = screen(&mut app);
        assert!(rows.iter().any(|r| r.contains("Open @durov")), "{rows:#?}");

        press(&mut app, KeyCode::Char('u'), KeyModifiers::CONTROL);
        app.on_terminal_event(Event::Paste("t.me/+AbCdEf\n".into()));
        let picker = app.picker.as_ref().unwrap();
        assert_eq!(picker.query, "t.me/+AbCdEf", "not attached as a file");
        assert_eq!(
            picker.choices(&app.chats)[0],
            Choice::Link("https://t.me/+AbCdEf".into())
        );
        assert!(picker.search_at().is_none(), "links aren't searched for");
        press(&mut app, KeyCode::Char('c'), KeyModifiers::CONTROL);
        assert!(app.picker.is_none(), "Ctrl-c closes it");
        assert!(app.quit_deadline.is_none(), "without quitting");
    }

    #[test]
    fn ctrl_u_deletes_back_to_the_start_of_the_line_and_then_the_line_break() {
        let mut app = test_app("ctrl-u");
        let chat_id = app.open.as_ref().unwrap().chat_id;
        app.focus = Focus::Input;
        // Typing was already told, so this test sends nothing to TDLib.
        app.typing = Some((chat_id, Instant::now()));
        app.composer.insert_str("first line");
        app.composer.insert_newline();
        app.composer.insert_str("second line");
        app.composer
            .move_cursor(ratatui_textarea::CursorMove::WordBack);
        press(&mut app, KeyCode::Char('u'), KeyModifiers::CONTROL);
        assert_eq!(app.composer.lines(), ["first line", "line"]);

        press(&mut app, KeyCode::Char('u'), KeyModifiers::CONTROL);
        assert_eq!(app.composer.lines(), ["first lineline"]);
        assert!(app.focus == Focus::Input);
    }

    #[test]
    fn a_chat_found_while_you_write_does_not_open_over_what_you_type() {
        let mut app = test_app("late-find");
        let chat_id = app.open.as_ref().unwrap().chat_id;
        app.focus = Focus::Input;
        app.composer.insert_str("see you at 5");
        app.finding = Some(Finding::new("@bob"));
        app.on_tg(TgEvent::ChatFound {
            request: "@bob".into(),
            found: Ok((999, None)),
        });
        assert_eq!(app.open.as_ref().unwrap().chat_id, chat_id);
        assert!(app.focus == Focus::Input);
        assert_eq!(app.composer.lines(), ["see you at 5"]);
        assert!(app.finding.is_none());
        assert_eq!(
            app.status.as_deref(),
            Some("Found @bob: press s to open it")
        );

        // Nor does an invite ask to join over the composer.
        app.finding = Some(Finding::new("https://t.me/+x"));
        let invite = Invite {
            title: "Group".into(),
            members: 3,
            channel: false,
            badge: None,
            by_request: false,
        };
        app.on_tg(TgEvent::Invite {
            request: "https://t.me/+x".into(),
            link: "https://t.me/+x".into(),
            invite,
        });
        assert!(app.confirm.is_none());
    }

    #[test]
    fn writing_a_popup_or_esc_stops_a_lookup() {
        let mut app = test_app("stop-find");
        app.focus = Focus::Messages;
        app.finding = Some(Finding::new("@bob"));
        press(&mut app, KeyCode::Esc, KeyModifiers::NONE);
        assert!(app.finding.is_none());
        assert!(app.focus == Focus::Messages, "only the lookup stopped");

        app.finding = Some(Finding::new("@bob"));
        press(&mut app, KeyCode::Char('i'), KeyModifiers::NONE);
        assert!(app.finding.is_none(), "writing in this chat instead");
    }

    #[test]
    fn e_edits_your_message_as_markdown_and_an_untouched_edit_sends_nothing() {
        let mut app = test_app("edit-markdown");
        app.focus = Focus::Messages;
        let open = app.open.as_ref().unwrap();
        let (chat_id, id) = (open.chat_id, open.edit_target().unwrap());
        let text = EditText {
            markdown: "On my **way**!".into(),
            loses: false,
        };
        app.on_editable(chat_id, id, Some(true), Some(text));
        assert!(app.focus == Focus::Input);
        assert_eq!(app.composer.lines(), ["On my **way**!"]);
        // Unchanged, so Enter only ends the edit: no request.
        press(&mut app, KeyCode::Enter, KeyModifiers::NONE);
        assert!(app.open.as_ref().unwrap().editing.is_none());

        // Formatting Markdown can't write asks first.
        app.focus = Focus::Messages;
        let text = EditText {
            markdown: "On my way!".into(),
            loses: true,
        };
        app.on_editable(chat_id, id, Some(true), Some(text));
        let confirm = app.confirm.as_ref().expect("asks");
        assert!(matches!(&confirm.action, Confirmed::Edit { text, .. } if text == "On my way!"));
    }

    #[test]
    fn at_and_colon_suggest_people_and_emoji_and_tab_puts_one_in() {
        let mut app = test_app("complete");
        let chat_id = app.open.as_ref().unwrap().chat_id;
        app.focus = Focus::Input;
        // Typing was already told, so this test sends nothing to TDLib.
        app.typing = Some((chat_id, Instant::now()));

        app.composer.insert_str("hi @ma");
        app.update_completion();
        let completion = app.completion.as_ref().expect("suggestions");
        let labels: Vec<&str> = completion.items.iter().map(|s| s.label.as_str()).collect();
        assert_eq!(labels, ["Maya Chen"], "senders of the loaded messages");
        assert!(
            completion.search_at().is_some(),
            "members are searched once typing pauses"
        );
        press(&mut app, KeyCode::Tab, KeyModifiers::NONE);
        assert_eq!(app.composer.lines(), ["hi [Maya Chen](tg://user?id=2) "]);
        assert!(
            app.stickers.is_none(),
            "Tab took the suggestion, not the stickers"
        );

        app.composer.insert_str(":tada");
        app.update_completion();
        assert_eq!(app.completion.as_ref().unwrap().items[0].label, "🎉");
        press(&mut app, KeyCode::Tab, KeyModifiers::NONE);
        assert_eq!(app.composer.lines(), ["hi [Maya Chen](tg://user?id=2) 🎉"]);
        assert!(app.completion.is_none());

        app.composer.insert_str(" @sam");
        app.update_completion();
        assert!(
            app.completion.as_ref().is_none_or(|c| c.items.is_empty()),
            "not yourself"
        );
    }

    #[test]
    fn slash_starting_a_message_suggests_the_bots_commands() {
        let mut app = test_app("commands");
        let chat_id = app.open.as_ref().unwrap().chat_id;
        app.focus = Focus::Input;
        app.typing = Some((chat_id, Instant::now()));
        let command = |name: &str| complete::Command {
            bot: 9,
            name: name.into(),
            description: format!("{name} the bot"),
        };
        app.open.as_mut().unwrap().commands =
            Commands::Known(vec![command("start"), command("help")]);

        app.composer.insert_str("/he");
        app.update_completion();
        let completion = app.completion.as_ref().expect("suggestions");
        assert_eq!(completion.items[0].label, "/help");
        assert_eq!(completion.items[0].detail, "help the bot");
        press(&mut app, KeyCode::Tab, KeyModifiers::NONE);
        assert_eq!(app.composer.lines(), ["/help "]);

        app.composer.insert_str("see /st");
        app.update_completion();
        assert!(app.completion.is_none(), "only at the start of a message");
    }

    #[test]
    fn a_telegram_link_tuigram_cant_open_goes_to_the_browser_with_its_warning() {
        let mut app = test_app("link-elsewhere");
        let url = "https://t.me/addstickers/cats";
        app.finding = Some(Finding {
            request: url.into(),
            link: Some(Link {
                url: url.into(),
                disguise: Some("cute cats".into()),
            }),
        });
        app.on_tg(TgEvent::ChatFound {
            request: url.into(),
            found: Err(Missed::Elsewhere),
        });
        let confirm = app.confirm.as_ref().expect("the disguised link asks first");
        assert!(matches!(&confirm.action, Confirmed::OpenLink(u) if u == url));

        // From `s`, there's no browser to fall back on.
        app.confirm = None;
        app.finding = Some(Finding::new(url));
        app.on_tg(TgEvent::ChatFound {
            request: url.into(),
            found: Err(Missed::Elsewhere),
        });
        assert!(app.confirm.is_none());
        assert_eq!(
            app.status.as_deref(),
            Some("tuigram can't open this kind of link")
        );
    }

    #[test]
    fn enter_on_a_poll_opens_its_answers_unless_it_is_closed() {
        let mut app = test_app("poll");
        app.focus = Focus::Messages;
        let open = app.open.as_mut().unwrap();
        let id = open.cursor_id().unwrap();
        let mut poll = crate::poll::Poll {
            question: "Lunch?".into(),
            answers: vec![crate::poll::Answer {
                text: "Pizza".into(),
                voters: 0,
                percent: 0,
                chosen: false,
            }],
            voters: 0,
            several: false,
            quiz: false,
            correct: None,
            anonymous: true,
            closed: false,
        };
        open.messages.get_mut(&id).unwrap().poll = Some(poll.clone());
        press(&mut app, KeyCode::Enter, KeyModifiers::NONE);
        let menu = app.vote_menu.as_ref().expect("the vote popup");
        assert_eq!(menu.answers, ["Pizza"]);
        let rows = screen(&mut app);
        assert!(rows.iter().any(|r| r.contains("Vote")), "{rows:#?}");
        press(&mut app, KeyCode::Esc, KeyModifiers::NONE);
        assert!(app.vote_menu.is_none());

        poll.closed = true;
        let open = app.open.as_mut().unwrap();
        open.messages.get_mut(&id).unwrap().poll = Some(poll);
        press(&mut app, KeyCode::Enter, KeyModifiers::NONE);
        assert!(app.vote_menu.is_none());
        assert_eq!(app.status.as_deref(), Some("This poll is closed"));
    }

    #[test]
    fn leave_asks_first_and_only_for_groups_and_channels() {
        let mut app = test_app("leave");
        let none = KeyModifiers::NONE;
        let leave = |app: &mut App| {
            press(app, KeyCode::Char(':'), none);
            for c in "leave".chars() {
                press(app, KeyCode::Char(c), none);
            }
            press(app, KeyCode::Enter, none);
        };
        app.focus = Focus::Messages;
        leave(&mut app);
        let confirm = app.confirm.as_ref().expect("asks");
        let chat_id = app.open.as_ref().unwrap().chat_id;
        assert!(matches!(confirm.action, Confirmed::Leave(id) if id == chat_id));
        assert_eq!(confirm.title, "Leave this group?");
        press(&mut app, KeyCode::Esc, none);

        // A chat with one person, selected in the list.
        app.focus = Focus::Chats;
        let mom = app
            .chats
            .ids()
            .iter()
            .copied()
            .find(|&id| app.chats.title(id) == Some("Mom"))
            .unwrap();
        app.selected = Some(mom);
        leave(&mut app);
        assert!(app.confirm.is_none());
        assert_eq!(
            app.status.as_deref(),
            Some("A chat with one person can't be left")
        );
    }

    #[test]
    fn i_in_a_public_group_you_are_not_in_asks_to_join_first() {
        let mut app = test_app("join");
        let chat_id = app.open.as_ref().unwrap().chat_id;
        app.chats.add_local(chat_id, "Weekend Hike", None).peer = Some(Peer::Supergroup(77));
        app.chats.set_member(77, false);
        app.focus = Focus::Messages;
        press(&mut app, KeyCode::Char('i'), KeyModifiers::NONE);
        assert!(app.focus == Focus::Messages, "not writing yet");
        let confirm = app.confirm.as_ref().expect("asks");
        assert!(matches!(confirm.action, Confirmed::Join(id) if id == chat_id));
        press(&mut app, KeyCode::Esc, KeyModifiers::NONE);

        app.chats.set_member(77, true);
        press(&mut app, KeyCode::Char('i'), KeyModifiers::NONE);
        assert!(app.focus == Focus::Input, "once you're in");
    }

    #[test]
    fn a_y_typed_just_before_a_warning_came_up_does_not_answer_it() {
        let mut app = test_app("grace");
        let edit = Confirmed::Edit {
            id: -1,
            text: String::new(),
        };
        app.confirm = Some(Confirm::new("Edit?", vec![], edit));
        press(&mut app, KeyCode::Char('y'), KeyModifiers::NONE);
        assert!(app.confirm.is_some(), "too soon to count");
        let confirm = app.confirm.as_mut().unwrap();
        confirm.shown = Instant::now().checked_sub(CONFIRM_GRACE).unwrap();
        press(&mut app, KeyCode::Char('y'), KeyModifiers::NONE);
        assert!(
            app.confirm.is_none(),
            "answered once it has been up a moment"
        );
    }

    #[test]
    fn a_download_finishing_while_you_type_waits_for_enter_instead_of_asking() {
        let mut app = test_app("busy");
        let dir = std::env::temp_dir().join("tuigram-no-such-folder");
        let downloaded = |app: &mut App, name: &str| {
            app.opening.insert(77);
            let path = dir.join(name).to_string_lossy().into_owned();
            app.on_tg(TgEvent::Downloaded {
                file_id: 77,
                path: Some(path),
            });
        };
        app.focus = Focus::Input;
        downloaded(&mut app, "run me.sh");
        assert!(app.confirm.is_none(), "no popup over the composer");
        let status = app.status.clone().unwrap_or_default();
        assert!(status.contains("run me.sh downloaded"), "{status}");

        app.focus = Focus::Messages;
        // Not a safe type, so nothing is opened.
        downloaded(&mut app, "evil\u{202e}txt.sh");
        let title = &app
            .confirm
            .as_ref()
            .expect("asks when nothing else is up")
            .title;
        assert!(
            !title.contains('\u{202e}'),
            "the sender's name is cleaned: {title:?}"
        );
    }
}