tuigram-cli 1.10.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
//! Photos, shown inline in chat bubbles, and chat photos in the chat list.
//!
//! Every frame, the message view and the chat list ask for the photos they
//! have on screen. After the frame, [`Images::fetch`] starts whatever is
//! missing: a TDLib download, then decode + encode for the terminal on a
//! blocking thread. Until the real photo is ready, the blurry thumbnail that
//! came with the message (or chat) stands in.

use std::cell::Cell;
use std::collections::{HashMap, HashSet};
use std::panic::{AssertUnwindSafe, catch_unwind};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, PoisonError};

use anyhow::Result;
use image::imageops::FilterType;
use image::{DynamicImage, RgbaImage};
use ratatui::Frame;
use ratatui::buffer::Buffer;
use ratatui::layout::{Rect, Size};
use ratatui::widgets::Widget;
use ratatui_image::picker::cap_parser::Parser;
use ratatui_image::picker::{Capability, Picker, ProtocolType};
use ratatui_image::protocol::kitty::Kitty;
use ratatui_image::sliced::{SignedPosition, SlicedImage, SlicedProtocol};
use ratatui_image::{FontSize, Resize};
use tokio::sync::mpsc::UnboundedSender;

use crate::chats::ChatPhoto;
use crate::lang;
use crate::messages::Preview;
use crate::term::{self, Terminal};
use crate::tg::Tg;

/// Scale both ways (`Fit` never enlarges, which would leave the tiny thumbnail
/// tiny). Triangle filtering keeps the enlarged thumbnail soft, not blocky.
const RESIZE: Resize = Resize::Scale(Some(FilterType::Triangle));

/// Chat photos kept encoded; the ones drawn longest ago go first. Room for
/// a long chat list: past the cap, scrolling back to an evicted one made it
/// a colored square until it decoded again.
const MAX_AVATARS: usize = 512;

/// One encoded image: a photo (or its thumbnail) at one size in cells.
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct Key {
    pub file_id: i32,
    pub cols: u16,
    pub rows: u16,
    /// The blurry thumbnail embedded in the message, not the downloaded photo.
    pub thumbnail: bool,
    /// A chat photo for the chat list, cut to a circle.
    pub avatar: bool,
    /// A video message's still, cut to a circle like the video playing it.
    pub round: bool,
}

/// Caps for decoding images from other people. Telegram's photos are at most
/// 2560px a side and stickers 512px, so a bigger one is only a way to run
/// memory out.
fn limits() -> image::Limits {
    sized(4096)
}

/// Caps of `side` pixels a side. Decoders allocate more than `max_alloc`
/// counts (WebP's scratch and frame buffers), so the side is what bounds it.
fn sized(side: u32) -> image::Limits {
    let mut limits = image::Limits::default();
    limits.max_image_width = Some(side);
    limits.max_image_height = Some(side);
    limits.max_alloc = Some(128 * 1024 * 1024);
    limits
}

/// How a message photo's file is asked for.
#[derive(Debug, PartialEq)]
enum Ask {
    /// The first time: a failure is said in the status bar.
    Reported,
    /// Again, after a failure that was said already.
    Quiet,
}

/// Whether to ask TDLib for a photo's file now, in `state`: not while it
/// downloads or is broken. One that failed is asked again once its cooldown
/// passed, as TDLib reports it no more otherwise.
fn download_to_ask(state: Option<&FileState>) -> Option<Ask> {
    match state {
        None => Some(Ask::Reported),
        Some(FileState::Failed(at)) if at.elapsed() >= RETRY_AFTER => Some(Ask::Quiet),
        _ => None,
    }
}

/// Stickers are 512px a side; this leaves room to spare.
const STICKER_SIDE: u32 = 1024;

/// A sticker's image: the WebP itself, or a video sticker's (WebM) first
/// frame, taken by ffmpeg — the image library doesn't read video.
fn open_sticker(path: &str) -> image::ImageResult<image::DynamicImage> {
    or_still(open_within(path, sized(STICKER_SIDE)), || webm_still(path))
}

/// What the image library `opened`, or for a kind it doesn't read (a WebM)
/// the `still` ffmpeg takes, whose word then says why not. Anything else
/// keeps its own error: ffmpeg could only fail on it too.
fn or_still(
    opened: image::ImageResult<image::DynamicImage>,
    still: impl FnOnce() -> image::ImageResult<image::DynamicImage>,
) -> image::ImageResult<image::DynamicImage> {
    match opened {
        Err(image::ImageError::Unsupported(_)) => still(),
        opened => opened,
    }
}

/// The first frame of the WebM at `path`: ffmpeg writes it as a PNG on its
/// stdout, read as strictly as a video message's (crate::video), and
/// decoded within a sticker's caps.
fn webm_still(path: &str) -> image::ImageResult<image::DynamicImage> {
    let no_frame = |kind| {
        image::ImageError::IoError(std::io::Error::new(kind, "ffmpeg couldn't take a frame"))
    };
    // Looked for once: without it now, there's none this run.
    let ffmpeg = crate::video::ffmpeg().ok_or_else(|| no_frame(std::io::ErrorKind::Unsupported))?;
    let mut command = std::process::Command::new("ffmpeg");
    command
        .args(crate::video::ffmpeg_still_args(
            std::path::Path::new(path),
            ffmpeg.libvpx,
        ))
        .stdin(std::process::Stdio::null())
        .stderr(std::process::Stdio::null());
    let (status, stdout) =
        run_within(command, STILL_TIMEOUT).map_err(image::ImageError::IoError)?;
    // Failing, crashing, or killed (out of memory, or time): a file that
    // did it once would do it again.
    if !status.is_some_and(|status| status.success()) {
        return Err(no_frame(std::io::ErrorKind::InvalidData));
    }
    decode_bytes_within(&stdout, sized(STICKER_SIDE))
}

/// How long ffmpeg gets to take a sticker's still, a fraction of a second's
/// work: a file that keeps it busy longer isn't let to hold a process.
const STILL_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);

/// Runs `command` with its stdout read, and kills it if it's still going
/// after `limit`: its status then is `None`.
fn run_within(
    mut command: std::process::Command,
    limit: std::time::Duration,
) -> std::io::Result<(Option<std::process::ExitStatus>, Vec<u8>)> {
    use std::io::Read;
    let mut child = command.stdout(std::process::Stdio::piped()).spawn()?;
    let mut stdout = child.stdout.take().expect("stdout is piped");
    // Read meanwhile, or a full pipe would stop it.
    let reader = std::thread::spawn(move || {
        let mut out = Vec::new();
        stdout.read_to_end(&mut out).map(|_| out)
    });
    let deadline = std::time::Instant::now() + limit;
    let status = loop {
        match child.try_wait() {
            Ok(Some(status)) => break Some(status),
            Ok(None) if std::time::Instant::now() < deadline => {
                std::thread::sleep(std::time::Duration::from_millis(20));
            }
            _ => {
                let _ = child.kill();
                let _ = child.wait();
                break None;
            }
        }
    };
    let out = reader
        .join()
        .unwrap_or_else(|_| Err(std::io::Error::other("reading it panicked")))?;
    Ok((status, out))
}

/// Like `image::open`, within [`limits`]. The format comes from the file's
/// first bytes, else its extension: a file sent as a file is named by its
/// sender, so a JPEG can be called `.png`.
pub fn open_image(path: &str) -> image::ImageResult<image::DynamicImage> {
    open_within(path, limits())
}

fn open_within(path: &str, limits: image::Limits) -> image::ImageResult<image::DynamicImage> {
    let mut reader = image::ImageReader::open(path)?.with_guessed_format()?;
    reader.limits(limits);
    reader.decode()
}

/// How big an image from this computer may be (see [`from_this_computer`]):
/// as big as Telegram takes a photo, width plus height up to this. A photo
/// you sent is one: TDLib keeps the file you sent as the photo's largest
/// size, where Telegram's own copies are at most 2560px, and a Retina
/// screenshot is wider than 4096px.
const YOUR_SIDES: u32 = crate::attach::PHOTO_MAX_SIDES;

/// A photo, decoded within the caps for where its file is from: one from
/// this computer, such as a photo you sent, within [`YOUR_SIDES`], anyone
/// else's, a download, within [`limits`].
pub fn open_photo(path: &str, tdlib_dirs: &[PathBuf]) -> image::ImageResult<DynamicImage> {
    match from_this_computer(path, tdlib_dirs) {
        // The path it was found at, with the links in it resolved.
        Some(resolved) => open_your_image(&resolved),
        None => open_image(path),
    }
}

/// Like [`open_image`], for an image from this computer: its width plus
/// height within [`YOUR_SIDES`], read from its header, then decoded from the
/// same open file, so one put in its place meanwhile isn't.
fn open_your_image(path: &Path) -> image::ImageResult<DynamicImage> {
    use image::ImageDecoder;
    let mut limits = sized(YOUR_SIDES);
    let mut reader = image::ImageReader::open(path)?.with_guessed_format()?;
    reader.limits(limits.clone());
    let decoder = reader.into_decoder()?;
    let (width, height) = decoder.dimensions();
    if width.saturating_add(height) > YOUR_SIDES {
        return Err(image::ImageError::Limits(
            image::error::LimitError::from_kind(image::error::LimitErrorKind::DimensionError),
        ));
    }
    // As `ImageReader::decode` does: `into_decoder` checks only the sides.
    limits.reserve(decoder.total_bytes())?;
    DynamicImage::from_decoder(decoder)
}

/// The file at `path`, resolved, if it's one TDLib didn't download, in none
/// of `tdlib_dirs` (its database and downloads): you gave it from this
/// computer, as a photo you sent, whose file TDLib keeps as the photo's
/// largest size, or one about to be. Everything from anyone else is a
/// download, decoded within [`limits`]. Unsure (no folders known, or a path
/// that can't be resolved), it isn't. A path on another machine isn't even
/// resolved: on Windows that would hand its server the user's login hash.
fn from_this_computer(path: &str, tdlib_dirs: &[PathBuf]) -> Option<PathBuf> {
    if tdlib_dirs.is_empty() || crate::attach::on_another_machine(Path::new(path)) {
        return None;
    }
    let path = std::fs::canonicalize(path).ok()?;
    let outside = |dir: &PathBuf| match std::fs::canonicalize(dir) {
        Ok(dir) => !path.starts_with(dir),
        // Not made yet, so nothing was downloaded into it: on a new login,
        // until TDLib first needs it. Still not a path in it as written, in
        // case it went away just now.
        Err(e) => e.kind() == std::io::ErrorKind::NotFound && !path.starts_with(dir),
    };
    tdlib_dirs.iter().all(outside).then_some(path)
}

/// At most this many images decode at once; the rest wait for a later frame.
/// Each may take a few hundred MB while it decodes.
const MAX_BUILDING: usize = 4;

/// Encoded photos kept for the open chat; the least recently drawn go first.
const MAX_READY: usize = 200;

/// More cells than any photo in a bubble (40 × 16): only the photo viewer
/// asks for photos this big.
const LARGE_CELLS: u32 = 40 * 16;

/// Of those, at most this many are kept. Each can take tens of MB (a kitty
/// encode keeps the code it sent, the whole image), and the viewer shows one
/// at a time.
const MAX_LARGE: usize = 4;

fn large(key: &Key) -> bool {
    u32::from(key.cols) * u32::from(key.rows) > LARGE_CELLS
}

/// What the photos kept may take in a terminal speaking kitty's protocol, in
/// bytes of pixels. Such a terminal keeps every image it's sent until told
/// to delete it, and past its quota (320 MB in kitty and Ghostty) it drops
/// the ones sent first: the chat photos, sent once at startup and never
/// again, which then leave blanks in the list. Half the quota leaves room
/// for those (at most [`MAX_AVATARS`], tens of KB each).
const KITTY_BUDGET: usize = 160_000_000;

/// Numbers of kitty images dropped since the terminal was last told; see
/// [`Images::send_deletions`].
type Dropped = Arc<Mutex<Vec<u32>>>;

/// An image sent with kitty's protocol: the number the terminal knows it by
/// and the bytes it takes there. Dropping it, wherever that happens, adds
/// its number to those the terminal is told to delete.
struct KittyImage {
    id: u32,
    bytes: usize,
    dropped: Dropped,
}

impl Drop for KittyImage {
    fn drop(&mut self) {
        self.dropped
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .push(self.id);
    }
}

/// An image encoded for the terminal.
struct Encoded {
    image: SlicedProtocol,
    kitty: Option<KittyImage>,
}

impl Encoded {
    fn kitty_bytes(&self) -> usize {
        self.kitty.as_ref().map_or(0, |k| k.bytes)
    }
}

/// `image` encoded to fill `size` cells. With kitty's protocol it's sent as
/// the image numbered by `kitty`, picked here rather than by the picker, so
/// it can be deleted from the terminal once it's dropped.
fn encode(
    picker: &Picker,
    image: DynamicImage,
    size: Size,
    kitty: Option<(u32, Dropped)>,
) -> Result<Encoded> {
    let Some((id, dropped)) = kitty else {
        let image = SlicedProtocol::new_with_resize(picker, image, size, RESIZE)?;
        return Ok(Encoded { image, kitty: None });
    };
    // As the picker's `new_protocol` does with a `Resize::Scale`, which
    // always resizes.
    let font = picker.font_size();
    let size = RESIZE.size_for(&image, font, size);
    let image = RESIZE.resize(&image, font, size, None);
    let bytes = image.width() as usize * image.height() as usize * 4;
    let compress = picker
        .capabilities()
        .contains(&Capability::KittyCompression);
    let image = Kitty::new(image, size, id, picker.tmux_detected(), compress)?;
    Ok(Encoded {
        image: SlicedProtocol::Kitty(image),
        kitty: Some(KittyImage { id, bytes, dropped }),
    })
}

/// Where numbers for kitty's images start: at random, as the picker's own
/// are, since every program drawing in the terminal's window shares them
/// (two tuigrams in panes of one tmux), and one's deletions mustn't take
/// the other's pictures.
fn kitty_id_base() -> u32 {
    use std::hash::{BuildHasher, RandomState};
    RandomState::new().hash_one(std::process::id()) as u32
}

/// What kitty's protocol draws in every cell of an image, after the code
/// that sends the image in the first cell of its first drawing.
pub(crate) const PLACEHOLDER: char = '\u{10EEEE}';

/// The code that sends a kitty image, taken out of `cell`, the first an
/// image was drawn in, if it holds one: its placeholder stays.
fn transmit_in(cell: &mut ratatui::buffer::Cell) -> Option<String> {
    let symbol = cell.symbol();
    if !symbol.starts_with('\x1b') {
        return None;
    }
    let at = symbol.rfind(PLACEHOLDER)?;
    let (code, placeholder) = (symbol[..at].to_string(), symbol[at..].to_string());
    cell.set_symbol(&placeholder);
    Some(code)
}

/// The code that has the terminal delete image number `id` of kitty's
/// protocol. `I` deletes the image itself, not only where it's placed;
/// `q=2` asks for no answer, which would come in as keys.
fn kitty_delete(id: u32, tmux: bool) -> String {
    let (start, escape, end) = Parser::tmux_start_escape_end(tmux);
    format!("{start}{escape}_Ga=d,d=I,i={id},q=2{escape}\\{end}")
}

thread_local! {
    /// Set while this thread decodes another user's image.
    static DECODING: Cell<bool> = const { Cell::new(false) };
}

/// The panic is in an image decoder, where it's caught: the image shows as
/// broken and the app carries on, rather than every chat holding that image
/// becoming one that can't be opened.
pub fn panic_is_contained() -> bool {
    DECODING.with(Cell::get)
}

/// Runs `decode`, with a panic in it caught and turned into an error. Every
/// decode of another user's image goes through this.
pub fn contained<T>(decode: impl FnOnce() -> Result<T>) -> Result<T> {
    DECODING.with(|d| d.set(true));
    let result = catch_unwind(AssertUnwindSafe(decode))
        .unwrap_or_else(|_| Err(anyhow::anyhow!(lang::t("the image couldn't be decoded"))));
    DECODING.with(|d| d.set(false));
    result
}

/// An image still building after this long counts as failed.
const BUILD_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);

/// A failed download is tried again after this long, while the image is
/// still on screen: downloads fail transiently (the network, a proxy
/// change), and TDLib won't be asked again on its own, so without a retry a
/// chat photo that failed once stayed a colored square forever. A file
/// that didn't decode is broken for good: it would fail the same way.
const RETRY_AFTER: std::time::Duration = std::time::Duration::from_secs(60);

/// Like `image::load_from_memory`, within [`limits`].
fn decode_bytes(data: &[u8]) -> image::ImageResult<image::DynamicImage> {
    decode_bytes_within(data, limits())
}

fn decode_bytes_within(
    data: &[u8],
    limits: image::Limits,
) -> image::ImageResult<image::DynamicImage> {
    let mut reader = image::ImageReader::new(std::io::Cursor::new(data)).with_guessed_format()?;
    reader.limits(limits);
    reader.decode()
}

/// `photo` cut to a circle in the middle of a `width`×`height` canvas, which
/// is transparent around it, so the row's background shows there. The edge
/// fades out over a pixel to look round rather than jagged.
pub fn circle(photo: &DynamicImage, width: u32, height: u32) -> RgbaImage {
    let mut canvas = RgbaImage::new(width, height);
    let size = width.min(height);
    let side = photo.width().min(photo.height());
    if size == 0 || side == 0 {
        return canvas;
    }
    let square = photo
        .crop_imm(
            (photo.width() - side) / 2,
            (photo.height() - side) / 2,
            side,
            side,
        )
        .resize_exact(size, size, FilterType::Triangle)
        .to_rgba8();
    let (left, top) = ((width - size) / 2, (height - size) / 2);
    let radius = size as f32 / 2.0;
    for (x, y, pixel) in square.enumerate_pixels() {
        let dx = x as f32 + 0.5 - radius;
        let dy = y as f32 + 0.5 - radius;
        let inside = (radius - (dx * dx + dy * dy).sqrt() + 0.5).clamp(0.0, 1.0);
        let mut pixel = *pixel;
        pixel[3] = (f32::from(pixel[3]) * inside).round() as u8;
        canvas.put_pixel(left + x, top + y, pixel);
    }
    canvas
}

/// An image finished encoding (or failed) on a background thread.
pub struct ImageEvent {
    key: Key,
    /// [`Images::generation`] when it was started.
    generation: u64,
    /// The encoded image, and the size in pixels it was decoded at.
    result: Result<(Encoded, (u32, u32))>,
}

/// What a failed build says about its file.
enum Failure {
    /// Its bytes don't decode: they never will.
    File,
    /// It decoded, but couldn't be drawn at the size asked: others still can.
    Size,
    /// It couldn't be read for now (too many files or processes open), or
    /// it's gone from disk since it was downloaded: another time may go better.
    Later,
}

/// A read that may go better another time: the file gone (TDLib fetches it
/// again), or too many files or processes open.
fn for_now(io: &std::io::Error) -> bool {
    use std::io::ErrorKind::{Interrupted, NotFound, TimedOut, WouldBlock};
    #[cfg(unix)]
    let too_many_open = matches!(io.raw_os_error(), Some(libc::EMFILE | libc::ENFILE));
    #[cfg(not(unix))]
    let too_many_open = false;
    too_many_open || matches!(io.kind(), NotFound | Interrupted | TimedOut | WouldBlock)
}

/// Marks an encode that failed at one size, apart from the file not decoding.
#[derive(Debug)]
struct AtThisSize;

impl std::fmt::Display for AtThisSize {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        f.write_str("it can't be drawn at this size")
    }
}

impl Failure {
    fn of(error: &anyhow::Error) -> Self {
        let passing = |e: &(dyn std::error::Error + 'static)| {
            let io = e
                .downcast_ref::<std::io::Error>()
                .or(match e.downcast_ref() {
                    Some(image::ImageError::IoError(io)) => Some(io),
                    _ => None,
                });
            io.is_some_and(for_now)
        };
        if error.downcast_ref::<AtThisSize>().is_some() {
            Self::Size
        } else if error.chain().any(passing) {
            Self::Later
        } else {
            Self::File
        }
    }
}

enum FileState {
    Downloading,
    Ready(String),
    /// The download failed, when: retried after [`RETRY_AFTER`].
    Failed(std::time::Instant),
    /// Downloaded, but it doesn't decode: never retried.
    Broken,
}

/// An encoded chat photo.
struct Avatar {
    image: Encoded,
    /// When it was last drawn, in calls to [`Images::avatar`].
    used: u64,
}

/// How much a cell's measured width or height must change, as a share of
/// what it was, to count as a new cell size rather than rounding: a window
/// whose pixels include its padding measures a little more per cell the
/// fewer rows it has. A screen of another density changes it by a quarter
/// or more, a step of the font's size by about a fourteenth.
const CELL_CHANGE: u32 = 16;

/// The pixel size of a cell as the terminal's window size says: its size
/// in pixels over its columns and rows. None where it doesn't say, as on
/// Windows, so cells keep the size the terminal answered at startup.
pub fn measure_cells() -> Option<FontSize> {
    let size = crossterm::terminal::window_size().ok()?;
    if size.columns == 0 || size.rows == 0 || size.width == 0 || size.height == 0 {
        return None;
    }
    Some(FontSize::new(
        size.width / size.columns,
        size.height / size.rows,
    ))
}

/// The cells' size in pixels, for a terminal that answered `queried` at
/// startup, when its window measured `then`, and measures `now` (see
/// [`measure_cells`]): as answered, unless they measure noticeably bigger
/// or smaller, then grown or shrunk as much. The answer is kept as the
/// truth, since a window's measure may count its padding.
fn cells_now(queried: FontSize, then: FontSize, now: FontSize) -> FontSize {
    let changed =
        |then: u16, now: u16| u32::from(then.abs_diff(now)) * CELL_CHANGE > u32::from(then);
    if !changed(then.width, now.width) && !changed(then.height, now.height) {
        return queried;
    }
    let scale = |queried: u16, then: u16, now: u16| {
        let (queried, then, now) = (u32::from(queried), u32::from(then.max(1)), u32::from(now));
        ((queried * now + then / 2) / then).clamp(1, u32::from(u16::MAX)) as u16
    };
    FontSize::new(
        scale(queried.width, then.width, now.width),
        scale(queried.height, then.height, now.height),
    )
}

pub struct Images {
    picker: Picker,
    /// The cell size the terminal answered at startup.
    queried: FontSize,
    /// What its window measured its cells as then: see [`Images::measured`].
    measured: Option<FontSize>,
    tx: UnboundedSender<ImageEvent>,
    /// Encoded photos, with the frame each was last drawn in.
    ready: HashMap<Key, (Encoded, u64)>,
    /// Counts frames, for `ready`.
    frame: u64,
    /// Goes up when the files are forgotten, for a new TDLib client: an
    /// image still being built for the old one numbers its file the old way,
    /// and is dropped when it's done. Also when cells change size, which
    /// leaves one being built the wrong size.
    generation: u64,
    /// Kept apart from `ready`: they stay when another chat is opened.
    avatars: HashMap<Key, Avatar>,
    /// Counts calls to [`Images::avatar`], to find the least recently drawn.
    avatar_clock: u64,
    /// Images being built, by the [`Images::generation`] each was started
    /// in, and when. One of an older generation keeps its place until it's
    /// done: its thread still decodes, taking as much memory.
    building: HashMap<(u64, Key), std::time::Instant>,
    /// Keys that failed to decode; never retried.
    failed: HashSet<Key>,
    files: HashMap<i32, FileState>,
    /// Where TDLib keeps its database and downloads: see
    /// [`from_this_computer`]. None known, no file is.
    tdlib_dirs: Arc<[PathBuf]>,
    /// Photos' own size in pixels, learned by decoding them: an image sent
    /// as a file comes without it.
    pixels: HashMap<i32, (u32, u32)>,
    /// Photos the last frame showed, with their size.
    wanted: Vec<(Preview, u16, u16, bool)>,
    /// Chat photos the last frame showed, with their size.
    wanted_avatars: Vec<(ChatPhoto, u16, u16)>,
    /// The number the last image built for kitty's protocol was given.
    kitty_id: u32,
    /// Images dropped since the terminal was last told.
    dropped: Dropped,
    /// See [`KITTY_BUDGET`]; smaller in tests.
    kitty_budget: usize,
    /// The codes of kitty images a frame drew before they were sent ahead
    /// of it: see [`Images::take_transmit`]. None should be, since every
    /// image is queued in [`Images::untransmitted`] as it's encoded.
    transmits: Vec<String>,
    /// Kitty images encoded since the terminal was sent them: kitty draws
    /// a placeholder naming an image it doesn't have yet blank, and
    /// doesn't revisit the cell when the image arrives after the frame,
    /// so they're sent before that frame (see [`Images::prime_transmits`]).
    untransmitted: Vec<Key>,
}

impl Images {
    pub fn new(picker: Picker, tx: UnboundedSender<ImageEvent>) -> Self {
        Self {
            queried: picker.font_size(),
            measured: None,
            picker,
            tx,
            ready: HashMap::new(),
            frame: 0,
            generation: 0,
            avatars: HashMap::new(),
            avatar_clock: 0,
            building: HashMap::new(),
            failed: HashSet::new(),
            files: HashMap::new(),
            tdlib_dirs: Arc::new([]),
            pixels: HashMap::new(),
            wanted: Vec::new(),
            wanted_avatars: Vec::new(),
            kitty_id: kitty_id_base(),
            dropped: Dropped::default(),
            kitty_budget: KITTY_BUDGET,
            transmits: Vec::new(),
            untransmitted: Vec::new(),
        }
    }

    /// False when the terminal shows no real images, only colored blocks
    /// (halfblocks), which are too coarse for a chat photo in a few cells.
    pub fn draws_photos(&self) -> bool {
        self.picker.protocol_type() != ProtocolType::Halfblocks
    }

    /// The terminal paints each image (or each of its rows) from one cell,
    /// and repaints the whole of it whenever that cell is sent again, over
    /// anything drawn on top since: sixel and iTerm2's protocol.
    pub fn paints_over(&self) -> bool {
        matches!(
            self.picker.protocol_type(),
            ProtocolType::Sixel | ProtocolType::Iterm2
        )
    }

    /// Pixel size of one terminal cell, for sizing photos by aspect ratio.
    pub fn font_size(&self) -> FontSize {
        self.picker.font_size()
    }

    /// The terminal speaks kitty's graphics protocol, which video messages
    /// play through.
    pub fn kitty(&self) -> bool {
        self.picker.protocol_type() == ProtocolType::Kitty
    }

    /// Escapes need tmux's passthrough wrapping.
    pub fn tmux(&self) -> bool {
        self.picker.tmux_detected()
    }

    /// The terminal's window measures its cells `now` (see
    /// [`measure_cells`]): first right after the terminal answered at
    /// startup, then whenever its size may have changed. Cells change size
    /// in pixels when the window moves to a screen of another density, or
    /// the font is made bigger or smaller. True if they did: photos and
    /// chat photos are then encoded again at the new size, since sixel and
    /// iTerm2's protocol draw them as many pixels as they were made, too
    /// big or too small for the cells, and kitty's would be blurred or
    /// wasted. The screen must then be drawn afresh.
    pub fn measured(&mut self, now: Option<FontSize>) -> bool {
        let Some(now) = now else {
            return false;
        };
        let Some(then) = self.measured else {
            self.measured = Some(now);
            return false;
        };
        let font = cells_now(self.queried, then, now);
        let old = self.picker.font_size();
        if (font.width, font.height) == (old.width, old.height) {
            return false;
        }
        // A picker takes its cell size only when it's made, from the
        // terminal's answer, which can't be asked for again while keys are
        // read. This one keeps the protocol found then, but not kitty's
        // compression, so kitty is sent its images uncompressed.
        let protocol = self.picker.protocol_type();
        #[allow(deprecated)]
        let mut picker = Picker::from_fontsize(font);
        picker.set_protocol_type(protocol);
        self.picker = picker;
        self.generation += 1;
        self.drop_all();
        // What failed at the old pixels, or ran out of time, may do at the
        // new ones; a broken file stays broken in `files`.
        self.failed.clear();
        true
    }

    /// The best image ready to draw: the photo, else its blurry thumbnail.
    /// `round` cuts it to a circle: a video message's still.
    pub fn get(
        &mut self,
        photo: &Preview,
        cols: u16,
        rows: u16,
        round: bool,
    ) -> Option<&SlicedProtocol> {
        let key = |thumbnail| Key {
            file_id: photo.file_id,
            cols,
            rows,
            thumbnail,
            avatar: false,
            round,
        };
        let key = [key(false), key(true)]
            .into_iter()
            .find(|k| self.ready.contains_key(k))?;
        let frame = self.frame;
        let (encoded, used) = self.ready.get_mut(&key)?;
        *used = frame;
        Some(&encoded.image)
    }

    /// Like [`get`](Self::get), but only the photo itself, not its blurry
    /// thumbnail.
    pub fn sharp(&mut self, photo: &Preview, cols: u16, rows: u16) -> Option<&SlicedProtocol> {
        let key = Key {
            file_id: photo.file_id,
            cols,
            rows,
            thumbnail: false,
            avatar: false,
            round: false,
        };
        let frame = self.frame;
        let (encoded, used) = self.ready.get_mut(&key)?;
        *used = frame;
        Some(&encoded.image)
    }

    /// The photo's file is downloaded.
    pub fn downloaded(&self, photo: &Preview) -> bool {
        matches!(self.files.get(&photo.file_id), Some(FileState::Ready(_)))
    }

    /// True when the photo can't be shown: its download or decode failed.
    pub fn is_broken(&self, photo: &Preview) -> bool {
        matches!(
            self.files.get(&photo.file_id),
            Some(FileState::Failed(_) | FileState::Broken)
        )
    }

    /// `photo` can't be shown at this size: its file is broken, or making
    /// the picture this size failed, which isn't tried again.
    pub fn unavailable(&self, photo: &Preview, cols: u16, rows: u16, round: bool) -> bool {
        let key = Key {
            file_id: photo.file_id,
            cols,
            rows,
            thumbnail: false,
            avatar: false,
            round,
        };
        self.is_broken(photo) || self.failed.contains(&key)
    }

    /// The sizes, in cells, the frame asked for pictures at.
    #[cfg(test)]
    pub fn wanted_sizes(&self) -> Vec<(u16, u16)> {
        self.wanted
            .iter()
            .map(|(_, cols, rows, _)| (*cols, *rows))
            .collect()
    }

    /// Called while drawing, for each photo on screen. `round` cuts it to a
    /// circle: a video message's still.
    pub fn want(&mut self, photo: &Preview, cols: u16, rows: u16, round: bool) {
        self.wanted.push((photo.clone(), cols, rows, round));
    }

    /// TDLib keeps its database and downloads in `dirs`.
    pub fn tdlib_keeps_files_in(&mut self, dirs: Arc<[PathBuf]>) {
        self.tdlib_dirs = dirs;
    }

    /// The best chat photo ready to draw, as for [`get`](Self::get). None
    /// while `covered` (a popup may be over it) with sixel or iTerm2's
    /// protocol: see [`paints_over`](Self::paints_over).
    pub fn avatar(
        &mut self,
        photo: &ChatPhoto,
        cols: u16,
        rows: u16,
        covered: bool,
    ) -> Option<&SlicedProtocol> {
        let key = |thumbnail| Key {
            file_id: photo.file_id,
            cols,
            rows,
            thumbnail,
            avatar: true,
            round: false,
        };
        // See paints_over: a popup may be over the list.
        if covered && self.paints_over() {
            return None;
        }
        let key = [key(false), key(true)]
            .into_iter()
            .find(|k| self.avatars.contains_key(k))?;
        self.avatar_clock += 1;
        let avatar = self.avatars.get_mut(&key)?;
        avatar.used = self.avatar_clock;
        Some(&avatar.image.image)
    }

    /// Called while drawing, for each chat photo on screen.
    pub fn want_avatar(&mut self, photo: &ChatPhoto, cols: u16, rows: u16) {
        self.wanted_avatars.push((photo.clone(), cols, rows));
    }

    /// Starts downloads and encodes for what the last frame wanted.
    pub fn fetch(&mut self, tg: &Tg) {
        self.frame += 1;
        self.fetch_avatars(tg);
        let font = self.picker.font_size();
        for (photo, cols, rows, round) in std::mem::take(&mut self.wanted) {
            let full = Key {
                file_id: photo.file_id,
                cols,
                rows,
                thumbnail: false,
                avatar: false,
                round,
            };
            if self.ready.contains_key(&full) {
                continue;
            }
            // A round one is cut on a canvas of its cells in pixels, as the
            // chat list's avatars are.
            let (width, height) = (
                u32::from(cols) * u32::from(font.width),
                u32::from(rows) * u32::from(font.height),
            );
            match self.files.get(&photo.file_id) {
                Some(FileState::Ready(path)) => {
                    let path = path.clone();
                    let (sticker, tdlib_dirs) = (photo.sticker, Arc::clone(&self.tdlib_dirs));
                    self.build(full, move || match (sticker, round) {
                        (true, _) => Ok(open_sticker(&path)?),
                        (false, true) => {
                            Ok(circle(&open_photo(&path, &tdlib_dirs)?, width, height).into())
                        }
                        (false, false) => Ok(open_photo(&path, &tdlib_dirs)?),
                    });
                }
                state => {
                    if let Some(ask) = download_to_ask(state) {
                        self.files.insert(photo.file_id, FileState::Downloading);
                        match ask {
                            Ask::Reported => tg.download(photo.file_id),
                            Ask::Quiet => tg.download_quiet(photo.file_id),
                        }
                    }
                }
            }
            if let Some(data) = photo.thumbnail {
                let key = Key {
                    thumbnail: true,
                    ..full
                };
                self.build(key, move || match round {
                    true => Ok(circle(&decode_bytes(&data)?, width, height).into()),
                    false => Ok(decode_bytes(&data)?),
                });
            }
        }
    }

    fn fetch_avatars(&mut self, tg: &Tg) {
        let font = self.picker.font_size();
        for (photo, cols, rows) in std::mem::take(&mut self.wanted_avatars) {
            let full = Key {
                file_id: photo.file_id,
                cols,
                rows,
                thumbnail: false,
                avatar: true,
                round: false,
            };
            if self.avatars.contains_key(&full) {
                continue;
            }
            let (width, height) = (
                u32::from(cols) * u32::from(font.width),
                u32::from(rows) * u32::from(font.height),
            );
            // A failed chat photo's download is asked for again once its
            // cooldown passed: it stays a colored square forever otherwise.
            let retry = matches!(
                self.files.get(&photo.file_id),
                Some(FileState::Failed(at)) if at.elapsed() >= RETRY_AFTER
            );
            if retry {
                tg.download_quiet(photo.file_id);
                self.files.insert(photo.file_id, FileState::Downloading);
            }
            let file = self
                .files
                .entry(photo.file_id)
                .or_insert_with(|| match &photo.path {
                    Some(path) => FileState::Ready(path.clone()),
                    None => {
                        tg.download_quiet(photo.file_id);
                        FileState::Downloading
                    }
                });
            if let FileState::Ready(path) = file {
                let path = path.clone();
                self.build(full, move || {
                    Ok(circle(&open_image(&path)?, width, height).into())
                });
            }
            if let Some(data) = photo.thumbnail {
                let key = Key {
                    thumbnail: true,
                    ..full
                };
                self.build(key, move || {
                    Ok(circle(&decode_bytes(&data)?, width, height).into())
                });
            }
        }
    }

    pub fn on_downloaded(&mut self, file_id: i32, path: Option<String>) {
        let state = path.map_or(
            FileState::Failed(std::time::Instant::now()),
            FileState::Ready,
        );
        self.files.insert(file_id, state);
    }

    /// The photo numbered `file_id` is a file on this computer, such as one
    /// about to be sent: it's read from `path`, never downloaded. Called
    /// while drawing, before [`want`](Self::want); a photo that failed to
    /// decode stays broken.
    pub fn local_file(&mut self, file_id: i32, path: &str) {
        self.files
            .entry(file_id)
            .or_insert_with(|| FileState::Ready(path.into()));
    }

    pub fn on_built(&mut self, event: ImageEvent) {
        self.building.remove(&(event.generation, event.key));
        if event.generation != self.generation {
            return;
        }
        // One that took too long to count may still finish: it builds.
        if event.result.is_ok() {
            self.failed.remove(&event.key);
        }
        match event.result {
            Ok((image, _)) if event.key.avatar => self.add_avatar(event.key, image),
            Ok((image, pixels)) => {
                if !event.key.thumbnail {
                    self.pixels.insert(event.key.file_id, pixels);
                }
                self.add_ready(event.key, image);
            }
            // A thumbnail's bytes are in memory: only its decode can fail.
            Err(_) if event.key.thumbnail => {
                self.failed.insert(event.key);
            }
            Err(e) => match Failure::of(&e) {
                Failure::Size => {
                    self.failed.insert(event.key);
                }
                // TDLib's file is asked for again later, as after a failed
                // download; an attachment's (numbered below 0) isn't TDLib's.
                Failure::Later if event.key.file_id > 0 => {
                    let at = std::time::Instant::now();
                    self.files.insert(event.key.file_id, FileState::Failed(at));
                }
                Failure::File | Failure::Later => {
                    self.failed.insert(event.key);
                    self.files.insert(event.key.file_id, FileState::Broken);
                }
            },
        }
    }

    /// `photo` as many pixels as it was decoded at, once it has been: an
    /// image sent as a file comes only with its thumbnail's shape.
    pub fn measured_photo(&self, photo: &Preview) -> Preview {
        let mut photo = photo.clone();
        if let Some(&(width, height)) = self.pixels.get(&photo.file_id) {
            (photo.width, photo.height) = (width.max(1), height.max(1));
        }
        photo
    }

    fn add_ready(&mut self, key: Key, image: Encoded) {
        // One it replaces counts no more.
        self.ready.remove(&key);
        while large(&key)
            && self.ready.keys().filter(|k| large(k)).count() >= MAX_LARGE
            && let Some(oldest) = self.least_used(|k, _| large(k))
        {
            self.ready.remove(&oldest);
        }
        if self.ready.len() >= MAX_READY
            && let Some(oldest) = self.least_used(|_, _| true)
        {
            self.ready.remove(&oldest);
        }
        // Those the last frame drew stay, or the next would build them again
        // and drop others it shows, frame after frame. Window-sized ones go
        // first: they free the most, and the viewer shows one at a time, so
        // zooming in it doesn't take the bubbles' photos behind it.
        let shown = self.frame.saturating_sub(1);
        while self.kitty_bytes() + image.kitty_bytes() > self.kitty_budget
            && let Some(oldest) = self
                .least_used(|k, used| large(k) && used < shown)
                .or_else(|| self.least_used(|_, used| used < shown))
        {
            self.ready.remove(&oldest);
        }
        if image.kitty.is_some() {
            self.untransmitted.push(key);
        }
        self.ready.insert(key, (image, self.frame));
    }

    /// The photo drawn longest ago of those `which` takes, by its key and
    /// the frame it was last drawn in.
    fn least_used(&self, which: impl Fn(&Key, u64) -> bool) -> Option<Key> {
        self.ready
            .iter()
            .filter(|&(key, &(_, used))| which(key, used))
            .min_by_key(|(_, (_, used))| *used)
            .map(|(&key, _)| key)
    }

    /// What the photos kept take in a terminal speaking kitty's protocol.
    fn kitty_bytes(&self) -> usize {
        self.ready.values().map(|(e, _)| e.kitty_bytes()).sum()
    }

    fn add_avatar(&mut self, key: Key, image: Encoded) {
        if self.avatars.len() >= MAX_AVATARS
            && let Some(oldest) = self
                .avatars
                .iter()
                .min_by_key(|(_, a)| a.used)
                .map(|(&k, _)| k)
        {
            self.avatars.remove(&oldest);
        }
        if image.kitty.is_some() {
            self.untransmitted.push(key);
        }
        let avatar = Avatar {
            image,
            used: self.avatar_clock,
        };
        self.avatars.insert(key, avatar);
    }

    /// Drops encoded photos, e.g. when switching chats. Chat photos and
    /// downloads stay.
    pub fn clear(&mut self) {
        self.ready.clear();
    }

    /// Another terminal took the pane over (another tmux client attached):
    /// kitty's protocol keeps images only in the terminal they were sent
    /// to, so the new one would draw the placeholders it's given blank.
    /// Every encode is dropped, to be made and sent again. True if that's
    /// so: the screen must then be drawn afresh.
    pub fn terminal_changed(&mut self) -> bool {
        if !self.kitty() {
            return false;
        }
        self.drop_all();
        true
    }

    /// Drops every encoded image, chat photos too, as tuigram quits: a
    /// terminal speaking kitty's protocol would keep them after it's gone.
    pub fn drop_all(&mut self) {
        self.ready.clear();
        self.avatars.clear();
        // Nor are any of them sent.
        self.transmits.clear();
    }

    /// Has a terminal speaking kitty's protocol delete the images dropped
    /// since it was last told, freeing what they took there; see
    /// [`KITTY_BUDGET`]. Called before each frame, ahead of any image it
    /// sends.
    pub fn send_deletions(&mut self, terminal: &mut Terminal) {
        if let Some(code) = self.deletions() {
            let _ = term::send(terminal, [code]);
        }
    }

    /// Sends the images encoded for kitty's protocol since the last frame,
    /// before the frame that would draw their placeholders: kitty draws a
    /// placeholder naming an image it doesn't have yet blank and doesn't
    /// revisit the cell when the image arrives after it, so a photo that
    /// finished decoding with the viewer open stayed "Loading…" until a
    /// resize redrew every cell.
    pub fn prime_transmits(&mut self, terminal: &mut Terminal) {
        let codes = self.pending_transmits();
        if !codes.is_empty() {
            let _ = term::send(terminal, codes);
        }
    }

    /// The codes sending the [`Images::untransmitted`] images, rendering
    /// each off-screen so its transmit code is made, which its first cell
    /// then holds; the placeholders a frame draws later name an image the
    /// terminal already has.
    fn pending_transmits(&mut self) -> Vec<String> {
        let mut codes = Vec::new();
        for key in std::mem::take(&mut self.untransmitted) {
            let image = if key.avatar {
                self.avatars.get(&key).map(|a| &a.image.image)
            } else {
                self.ready.get(&key).map(|(e, _)| &e.image)
            };
            let Some(image) = image else {
                continue;
            };
            let area = Rect::new(0, 0, key.cols.max(1), key.rows.max(1));
            let mut buf = Buffer::empty(area);
            SlicedImage::new(image, SignedPosition::from((0, 0))).render(area, &mut buf);
            'cells: for y in 0..area.height {
                for x in 0..area.width {
                    if let Some(code) = transmit_in(&mut buf[(x, y)]) {
                        codes.push(code);
                        break 'cells;
                    }
                }
            }
        }
        codes
    }

    /// Draws the image `pick` gives (from [`get`](Self::get),
    /// [`sharp`](Self::sharp) or [`avatar`](Self::avatar)) at `at` in `area`,
    /// if it's ready; false if not. Every image is drawn through here: with
    /// kitty's protocol, its first drawing carries the image itself in the
    /// first cell it covers, where anything drawn over that cell later in
    /// the frame (a popup, the date at the top, a toast) would lose it for
    /// good, and with it the image. Each is sent ahead of the frame that
    /// first draws it ([`prime_transmits`](Self::prime_transmits)), so a
    /// frame draws placeholders only; one that still carries its code has
    /// it taken out of the cell, leaving the placeholder, and sent after
    /// the frame ([`send_pictures`](Self::send_pictures)).
    pub fn draw(
        &mut self,
        frame: &mut Frame,
        area: Rect,
        at: SignedPosition,
        pick: impl for<'a> FnOnce(&'a mut Images) -> Option<&'a SlicedProtocol>,
    ) -> bool {
        let Some(image) = pick(self) else {
            return false;
        };
        frame.render_widget(SlicedImage::new(image, at), area);
        self.take_transmit(frame, area, at);
        true
    }

    /// See [`draw`](Self::draw).
    fn take_transmit(&mut self, frame: &mut Frame, area: Rect, at: SignedPosition) {
        if self.picker.protocol_type() != ProtocolType::Kitty {
            return;
        }
        // ratatui-image puts the code in the first cell of the image in the
        // buffer: from where `SlicedImage` starts drawing it, the first that
        // holds a placeholder. Images to its left are kept out by starting
        // at its column, and those drawn before it have given up theirs.
        let buf = frame.buffer_mut();
        let shown = area.intersection(buf.area);
        let left = area.x.saturating_add(at.x.max(0) as u16).max(shown.left());
        let top = area.y.saturating_add(at.y.max(0) as u16).max(shown.top());
        for y in top..shown.bottom() {
            for x in left..shown.right() {
                let cell = &mut buf[(x, y)];
                if cell.symbol().rfind(PLACEHOLDER).is_some() {
                    self.transmits.extend(transmit_in(cell));
                    return;
                }
            }
        }
    }

    /// Sends the images the frame just drawn still carried the codes of
    /// (see [`draw`](Self::draw)), once it's on the terminal. Too late for
    /// kitty, which leaves a placeholder blank if it came before its image:
    /// the backstop to [`prime_transmits`](Self::prime_transmits).
    pub fn send_pictures(&mut self, terminal: &mut Terminal) {
        if !self.transmits.is_empty() {
            let _ = term::send(terminal, std::mem::take(&mut self.transmits));
        }
    }

    /// How many images are waiting to be sent.
    #[cfg(test)]
    pub fn sending(&self) -> usize {
        self.transmits.len()
    }

    /// The code [`send_deletions`](Self::send_deletions) sends.
    fn deletions(&mut self) -> Option<String> {
        let ids = std::mem::take(&mut *self.dropped.lock().unwrap_or_else(PoisonError::into_inner));
        if ids.is_empty() {
            return None;
        }
        let tmux = self.picker.tmux_detected();
        Some(ids.into_iter().map(|id| kitty_delete(id, tmux)).collect())
    }

    /// Forgets every file, for a new TDLib client: it numbers files afresh.
    pub fn forget_files(&mut self) {
        self.generation += 1;
        self.drop_all();
        self.failed.clear();
        self.files.clear();
        self.pixels.clear();
        self.wanted.clear();
        self.wanted_avatars.clear();
    }

    /// Decodes and encodes on a blocking thread, once per key.
    fn build(
        &mut self,
        key: Key,
        decode: impl FnOnce() -> Result<image::DynamicImage> + Send + 'static,
    ) {
        let built = if key.avatar {
            self.avatars.contains_key(&key)
        } else {
            self.ready.contains_key(&key)
        };
        // One that never finishes mustn't hold its place for good: it counts
        // as failed, and the others get their turn.
        let (failed, generation) = (&mut self.failed, self.generation);
        self.building.retain(|&(started_in, key), started| {
            let alive = started.elapsed() < BUILD_TIMEOUT;
            if !alive && started_in == generation {
                failed.insert(key);
            }
            alive
        });
        // Those still decoding for an older generation count too.
        if built
            || self.building.contains_key(&(generation, key))
            || failed.contains(&key)
            || self.building.len() >= MAX_BUILDING
        {
            return;
        }
        self.building
            .insert((generation, key), std::time::Instant::now());
        let picker = self.picker.clone();
        let tx = self.tx.clone();
        let kitty = self.next_kitty();
        tokio::task::spawn_blocking(move || {
            let result = contained(|| {
                decode().and_then(|image| {
                    let pixels = (image.width(), image.height());
                    let size = Size::new(key.cols, key.rows);
                    let image =
                        encode(&picker, image, size, kitty).map_err(|e| e.context(AtThisSize))?;
                    Ok((image, pixels))
                })
            });
            let _ = tx.send(ImageEvent {
                key,
                generation,
                result,
            });
        });
    }

    /// A number for the next image built with kitty's protocol, and where
    /// it goes once that image is dropped.
    fn next_kitty(&mut self) -> Option<(u32, Dropped)> {
        (self.picker.protocol_type() == ProtocolType::Kitty).then(|| {
            // Never 0, which kitty's protocol takes as no number.
            self.kitty_id = self.kitty_id.wrapping_add(1).max(1);
            (self.kitty_id, self.dropped.clone())
        })
    }

    #[cfg(test)]
    pub fn insert_ready(&mut self, key: Key, image: image::DynamicImage) {
        let size = Size::new(key.cols, key.rows);
        let kitty = self.next_kitty();
        let image = encode(&self.picker, image, size, kitty).unwrap();
        if key.avatar {
            self.add_avatar(key, image);
        } else {
            self.add_ready(key, image);
        }
    }
}

/// Shared thumbnail bytes, so cloning a [`Preview`] each frame is cheap.
pub type Thumbnail = Arc<[u8]>;

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

    fn png(width: u32, height: u32) -> Vec<u8> {
        let mut data = std::io::Cursor::new(Vec::new());
        image::RgbImage::new(width, height)
            .write_to(&mut data, image::ImageFormat::Png)
            .unwrap();
        data.into_inner()
    }

    #[test]
    fn chat_photos_are_cut_to_a_circle_with_see_through_corners() {
        let photo = image::RgbaImage::from_pixel(160, 100, image::Rgba([255, 0, 0, 255])).into();
        let round = circle(&photo, 40, 44);
        let alpha = |x, y| round.get_pixel(x, y)[3];
        assert_eq!(alpha(0, 2), 0, "corner");
        assert_eq!(alpha(39, 41), 0, "corner");
        assert_eq!(alpha(20, 22), 255, "middle");
        assert_eq!(alpha(20, 0), 0, "above the circle: the canvas is taller");
        assert_eq!(alpha(1, 22), 255, "the circle reaches the sides");
        let edge = alpha(6, 7);
        assert!(edge > 0 && edge < 255, "a soft edge: {edge}");
        assert_eq!(circle(&photo, 0, 44).dimensions(), (0, 44), "no panic");
    }

    #[test]
    fn only_a_few_window_sized_photos_are_kept() {
        let tx = tokio::sync::mpsc::unbounded_channel().0;
        let mut images = Images::new(Picker::halfblocks(), tx);
        let at = |file_id, cols| Key {
            file_id,
            cols,
            rows: 50,
            thumbnail: false,
            avatar: false,
            round: false,
        };
        for file_id in 0..10 {
            images.insert_ready(at(file_id, 4), image::RgbImage::new(4, 4).into());
            images.insert_ready(at(file_id, 200), image::RgbImage::new(4, 4).into());
        }
        let large = images.ready.keys().filter(|k| k.cols == 200).count();
        assert_eq!(large, MAX_LARGE);
        let small = images.ready.keys().filter(|k| k.cols == 4).count();
        assert_eq!(small, 10, "bubbles' photos aren't touched");
    }

    fn key(file_id: i32) -> Key {
        Key {
            file_id,
            cols: 4,
            rows: 2,
            thumbnail: false,
            avatar: false,
            round: false,
        }
    }

    fn preview(file_id: i32) -> Preview {
        Preview {
            file_id,
            width: 8,
            height: 8,
            thumbnail: None,
            sticker: false,
        }
    }

    #[tokio::test]
    async fn a_decoder_panic_marks_the_photo_broken_instead_of_ending_the_app() {
        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
        let mut images = Images::new(Picker::halfblocks(), tx);
        images.build(key(7), || panic!("a decoder bug"));
        images.on_built(rx.recv().await.unwrap());
        assert!(images.is_broken(&preview(7)));
        assert!(!panic_is_contained(), "only while decoding");
    }

    #[tokio::test]
    async fn an_image_built_for_a_logged_out_session_is_dropped() {
        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
        let mut images = Images::new(Picker::halfblocks(), tx);
        let (go, wait) = std::sync::mpsc::channel::<()>();
        images.build(key(7), move || {
            wait.recv().ok();
            Ok(DynamicImage::new_rgba8(8, 8))
        });
        images.forget_files();
        go.send(()).unwrap();
        images.on_built(rx.recv().await.unwrap());
        assert!(
            images.get(&preview(7), 4, 2, false).is_none(),
            "not the new session's"
        );
        assert!(!images.is_broken(&preview(7)));
    }

    fn cells_after(queried: (u16, u16), then: (u16, u16), now: (u16, u16)) -> (u16, u16) {
        let font = |(w, h)| FontSize::new(w, h);
        let size = cells_now(font(queried), font(then), font(now));
        (size.width, size.height)
    }

    #[test]
    fn cells_keep_the_size_the_terminal_answered_unless_they_measure_another() {
        assert_eq!(cells_after((20, 40), (20, 40), (20, 40)), (20, 40));
        // A window that counts its padding measures a pixel more per cell
        // with few rows: not a new size.
        assert_eq!(cells_after((20, 40), (20, 40), (20, 41)), (20, 40));
        // Moved from a Retina screen to one of half its density.
        assert_eq!(cells_after((20, 40), (20, 40), (10, 20)), (10, 20));
        assert_eq!(cells_after((10, 20), (10, 20), (20, 40)), (20, 40));
        // Measured with its padding, the answer is scaled, not replaced.
        assert_eq!(cells_after((20, 40), (21, 42), (10, 21)), (10, 20));
        // A step of the font's size.
        assert_eq!(cells_after((14, 28), (14, 28), (15, 30)), (15, 30));
    }

    #[tokio::test]
    async fn photos_are_made_again_once_cells_change_size() {
        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
        let mut images = Images::new(Picker::halfblocks(), tx);
        let start = images.font_size();
        let measure = |w, h| Some(FontSize::new(w, h));
        assert!(
            !images.measured(measure(10, 20)),
            "the first is the startup's"
        );
        assert!(!images.measured(None), "a terminal that doesn't say");
        assert!(!images.measured(measure(10, 20)));
        images.insert_ready(key(1), DynamicImage::new_rgba8(8, 8));
        // Failed at the old pixels, or out of time: another chance at the new.
        images.failed.insert(key(3));

        // One on its way is the old size.
        let (go, wait) = std::sync::mpsc::channel::<()>();
        images.build(key(7), move || {
            wait.recv().ok();
            Ok(DynamicImage::new_rgba8(8, 8))
        });
        assert!(images.measured(measure(20, 40)));
        assert!(!images.failed.contains(&key(3)), "tried again");
        let font = images.font_size();
        assert_eq!(
            (font.width, font.height),
            (start.width * 2, start.height * 2)
        );
        assert!(!images.draws_photos(), "the protocol stays");
        assert!(images.get(&preview(1), 4, 2, false).is_none(), "made again");
        go.send(()).unwrap();
        images.on_built(rx.recv().await.unwrap());
        assert!(images.get(&preview(7), 4, 2, false).is_none(), "dropped");
        assert!(!images.is_broken(&preview(7)));
        assert!(!images.measured(measure(20, 40)), "only once");
        images.build(key(7), || Ok(DynamicImage::new_rgba8(8, 8)));
        images.on_built(rx.recv().await.unwrap());
        assert!(
            images.get(&preview(7), 4, 2, false).is_some(),
            "the new size"
        );
    }

    #[tokio::test]
    async fn only_a_few_images_decode_at_once() {
        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
        let mut images = Images::new(Picker::halfblocks(), tx);
        let (go, wait) = std::sync::mpsc::channel::<()>();
        let wait = std::sync::Arc::new(std::sync::Mutex::new(wait));
        for id in 0..10 {
            let wait = wait.clone();
            images.build(key(id), move || {
                let _ = wait.lock().unwrap().recv();
                Ok(DynamicImage::new_rgba8(8, 8))
            });
        }
        assert_eq!(images.building.len(), MAX_BUILDING);
        drop(go);
    }

    #[tokio::test]
    async fn decodes_left_over_from_another_cell_size_still_take_their_place() {
        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
        let mut images = Images::new(Picker::halfblocks(), tx);
        images.measured(Some(FontSize::new(10, 20)));
        let (go, wait) = std::sync::mpsc::channel::<()>();
        let wait = std::sync::Arc::new(std::sync::Mutex::new(wait));
        for id in 0..MAX_BUILDING as i32 {
            let wait = wait.clone();
            images.build(key(id), move || {
                let _ = wait.lock().unwrap().recv();
                Ok(DynamicImage::new_rgba8(8, 8))
            });
        }
        // Zooming the font a few times shouldn't start four more each time.
        assert!(images.measured(Some(FontSize::new(20, 40))));
        images.build(key(99), || Ok(DynamicImage::new_rgba8(8, 8)));
        assert_eq!(images.building.len(), MAX_BUILDING, "no room yet");
        drop(go);
        images.on_built(rx.recv().await.unwrap());
        images.build(key(99), || Ok(DynamicImage::new_rgba8(8, 8)));
        assert!(
            images.building.contains_key(&(images.generation, key(99))),
            "its turn came once an old one was done"
        );
    }

    #[tokio::test]
    async fn a_decode_that_never_finishes_gives_up_its_place() {
        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
        let mut images = Images::new(Picker::halfblocks(), tx);
        for id in 0..MAX_BUILDING as i32 {
            let long_ago = std::time::Instant::now() - BUILD_TIMEOUT;
            images.building.insert((0, key(id)), long_ago);
        }
        images.build(key(99), || Ok(DynamicImage::new_rgba8(8, 8)));
        assert!(images.building.contains_key(&(0, key(99))), "its turn came");
        assert!(
            images.failed.contains(&key(0)),
            "the stuck one counts as failed"
        );

        // It finishes after all: it builds, so it may be built again.
        let image = DynamicImage::new_rgba8(8, 8);
        let size = Size::new(key(0).cols, key(0).rows);
        let encoded = encode(&images.picker, image, size, None).unwrap();
        images.on_built(ImageEvent {
            generation: 0,
            key: key(0),
            result: Ok((encoded, (8, 8))),
        });
        assert!(
            !images.failed.contains(&key(0)),
            "dropped later, it's made again"
        );
    }

    #[test]
    fn the_photo_cache_keeps_the_ones_drawn_lately() {
        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
        let mut images = Images::new(Picker::halfblocks(), tx);
        images.insert_ready(key(0), DynamicImage::new_rgba8(8, 8));
        for id in 1..MAX_READY as i32 + 10 {
            images.frame += 1;
            assert!(
                images.get(&preview(0), 4, 2, false).is_some(),
                "still drawn"
            );
            images.insert_ready(key(id), DynamicImage::new_rgba8(8, 8));
        }
        assert_eq!(images.ready.len(), MAX_READY);
        assert!(images.get(&preview(0), 4, 2, false).is_some());
        assert!(
            images.get(&preview(1), 4, 2, false).is_none(),
            "the oldest went"
        );
    }

    #[tokio::test]
    async fn a_photo_about_to_be_sent_is_read_from_its_file_not_downloaded() {
        let dir = std::env::temp_dir().join(format!("tuigram-local-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("cat.png");
        std::fs::write(&path, png(80, 60)).unwrap();
        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
        let mut images = Images::new(Picker::halfblocks(), tx);
        let photo = preview(-1);
        images.local_file(-1, path.to_str().unwrap());
        images.want(&photo, 4, 2, false);
        // A detached client makes no requests, so a download would never end.
        images.fetch(&Tg::detached(tokio::sync::mpsc::unbounded_channel().0));
        images.on_built(rx.recv().await.unwrap());
        assert!(images.get(&photo, 4, 2, false).is_some());
        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[tokio::test]
    async fn a_file_named_as_another_format_decodes_and_says_how_big_it_is() {
        let dir = std::env::temp_dir().join(format!("tuigram-misnamed-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        // A PNG its sender named .jpg.
        let path = dir.join("photo.jpg");
        std::fs::write(&path, png(80, 60)).unwrap();
        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
        let mut images = Images::new(Picker::halfblocks(), tx);
        let photo = preview(3);
        let size = |p: Preview| (p.width, p.height);
        assert_eq!(
            size(images.measured_photo(&photo)),
            (8, 8),
            "as said, until decoded"
        );
        images.on_downloaded(3, Some(path.to_str().unwrap().into()));
        images.want(&photo, 4, 2, false);
        images.fetch(&Tg::detached(tokio::sync::mpsc::unbounded_channel().0));
        images.on_built(rx.recv().await.unwrap());
        assert!(
            images.get(&photo, 4, 2, false).is_some(),
            "read by its contents"
        );
        assert_eq!(size(images.measured_photo(&photo)), (80, 60));
        std::fs::remove_dir_all(&dir).unwrap();
    }

    /// Images for a terminal speaking kitty's protocol, its numbers from 1.
    fn kitty() -> Images {
        let mut picker = Picker::halfblocks();
        picker.set_protocol_type(ProtocolType::Kitty);
        let mut images = Images::new(picker, tokio::sync::mpsc::unbounded_channel().0);
        images.kitty_id = 0;
        images
    }

    /// 4 × 2 cells of 10 × 20 px.
    fn photo() -> DynamicImage {
        DynamicImage::new_rgba8(40, 40)
    }

    fn delete(id: u32) -> String {
        format!("\x1b_Ga=d,d=I,i={id},q=2\x1b\\")
    }

    #[test]
    fn a_kitty_terminal_is_told_to_delete_the_photos_dropped_by_the_number_they_were_sent_as() {
        use ratatui::buffer::Buffer;
        use ratatui::layout::Rect;
        use ratatui::widgets::Widget;
        use ratatui_image::sliced::{SignedPosition, SlicedImage};

        let mut images = kitty();
        images.insert_ready(key(7), photo());
        let mut buf = Buffer::empty(Rect::new(0, 0, 4, 2));
        let image = images.get(&preview(7), 4, 2, false).unwrap();
        SlicedImage::new(image, SignedPosition::from((0, 0))).render(buf.area, &mut buf);
        assert!(buf[(0, 0)].symbol().contains("i=1,a=T"), "sent as 1");
        assert_eq!(images.deletions(), None, "nothing dropped yet");

        images.clear();
        assert_eq!(images.deletions(), Some(delete(1)));
        assert_eq!(images.deletions(), None, "told once");
    }

    #[test]
    fn a_kitty_image_is_sent_before_the_frame_drawing_its_placeholders() {
        use ratatui::buffer::Buffer;
        use ratatui::layout::Rect;
        use ratatui::widgets::Widget;
        use ratatui_image::sliced::{SignedPosition, SlicedImage};

        let mut images = kitty();
        images.insert_ready(key(7), photo());
        let codes = images.pending_transmits();
        assert_eq!(codes.len(), 1, "made once, off-screen");
        assert!(codes[0].contains("i=1,a=T"), "{codes:?}");
        assert!(images.pending_transmits().is_empty(), "sent once");

        // The frame then draws placeholders only, naming an image the
        // terminal already has.
        let image = images.get(&preview(7), 4, 2, false).unwrap();
        let mut buf = Buffer::empty(Rect::new(0, 0, 4, 2));
        SlicedImage::new(image, SignedPosition::from((0, 0))).render(buf.area, &mut buf);
        assert!(!buf[(0, 0)].symbol().starts_with('\x1b'), "no code left");
        assert!(buf[(0, 0)].symbol().contains(PLACEHOLDER));

        // A chat photo for the list too.
        let avatar = Key {
            avatar: true,
            ..key(9)
        };
        images.insert_ready(avatar, photo());
        let codes = images.pending_transmits();
        assert_eq!(codes.len(), 1, "{codes:?}");
        assert!(codes[0].contains("i=2,a=T"), "{codes:?}");

        // One dropped before it could be sent is skipped.
        images.insert_ready(key(8), photo());
        images.clear();
        assert!(images.pending_transmits().is_empty());
    }

    #[test]
    fn a_new_terminal_has_every_image_made_and_sent_again() {
        let mut images = kitty();
        images.insert_ready(key(7), photo());
        let avatar = Key {
            avatar: true,
            ..key(9)
        };
        images.insert_ready(avatar, photo());
        assert_eq!(images.pending_transmits().len(), 2, "sent once");

        // The new terminal never got them: they're made again when next
        // drawn, and sent ahead of that frame.
        assert!(images.terminal_changed());
        assert!(images.ready.is_empty() && images.avatars.is_empty());
        images.insert_ready(key(7), photo());
        assert_eq!(images.pending_transmits().len(), 1);
    }

    #[test]
    fn a_halfblocks_terminal_keeps_its_images_for_a_new_one() {
        let tx = tokio::sync::mpsc::unbounded_channel().0;
        let mut images = Images::new(Picker::halfblocks(), tx);
        images.insert_ready(key(7), photo());
        assert!(!images.terminal_changed());
        assert!(!images.ready.is_empty());
    }

    #[test]
    fn chat_photos_are_deleted_too_once_dropped_and_all_of_them_on_quitting() {
        let mut images = kitty();
        let avatar = |file_id| Key {
            avatar: true,
            ..key(file_id)
        };
        for file_id in 0..=MAX_AVATARS as i32 {
            images.avatar_clock += 1;
            images.insert_ready(avatar(file_id), photo());
        }
        assert_eq!(images.avatars.len(), MAX_AVATARS);
        assert_eq!(images.deletions(), Some(delete(1)), "the oldest");
        images.insert_ready(key(1000), photo());
        images.drop_all();
        let code = images.deletions().unwrap();
        assert_eq!(code.matches("a=d").count(), MAX_AVATARS + 1);
        assert!(images.avatars.is_empty() && images.ready.is_empty());
    }

    #[test]
    fn photos_kept_for_a_kitty_terminal_stay_under_its_quota_but_not_by_dropping_those_on_screen() {
        let mut images = kitty();
        images.kitty_budget = 2 * 40 * 40 * 4;
        images.insert_ready(key(1), photo());
        images.frame = 1;
        images.insert_ready(key(2), photo());
        // A frame draws the second, then a third comes.
        images.frame = 3;
        assert!(images.get(&preview(2), 4, 2, false).is_some());
        images.frame = 4;
        images.insert_ready(key(3), photo());
        assert!(!images.ready.contains_key(&key(1)), "drawn longest ago");
        assert!(images.ready.contains_key(&key(2)) && images.ready.contains_key(&key(3)));
        assert_eq!(images.deletions(), Some(delete(1)));

        // Every one kept is on screen: the quota gives way.
        assert!(images.get(&preview(2), 4, 2, false).is_some());
        assert!(images.get(&preview(3), 4, 2, false).is_some());
        images.frame = 5;
        images.insert_ready(key(4), photo());
        assert_eq!(images.ready.len(), 3);
        assert_eq!(images.deletions(), None);
    }

    #[test]
    fn zooming_in_the_viewer_drops_its_other_sizes_before_the_bubbles_photos() {
        let mut images = kitty();
        let window = |file_id| Key {
            cols: 40,
            rows: 17,
            ..key(file_id)
        };
        let picture = || DynamicImage::new_rgba8(400, 340);
        images.kitty_budget = 2 * 400 * 340 * 4;
        // Drawn before the viewer covered it.
        images.insert_ready(key(1), photo());
        images.frame = 2;
        images.insert_ready(window(2), picture());
        images.frame = 4;
        images.insert_ready(window(3), picture());
        assert!(
            images.ready.contains_key(&key(1)),
            "though drawn longest ago"
        );
        assert!(!images.ready.contains_key(&window(2)));
        assert!(images.ready.contains_key(&window(3)));
    }

    #[test]
    fn a_kitty_images_data_goes_apart_from_the_frame_so_what_covers_it_cant_lose_it() {
        use ratatui::Terminal;
        use ratatui::backend::TestBackend;
        use ratatui::widgets::Paragraph;

        let mut images = kitty();
        images.insert_ready(key(7), photo());
        let mut terminal = Terminal::new(TestBackend::new(10, 4)).unwrap();
        let (area, at) = (Rect::new(1, 1, 4, 2), SignedPosition::from((0, 0)));
        let mut draw = |images: &mut Images| {
            terminal
                .draw(|frame| {
                    assert!(images.draw(frame, area, at, |i| i.get(&preview(7), 4, 2, false)));
                    // A popup over its first cell.
                    frame.render_widget(Paragraph::new("popup"), Rect::new(0, 1, 6, 1));
                })
                .unwrap()
                .buffer
                .clone()
        };
        let buf = draw(&mut images);
        assert_eq!(images.sending(), 1);
        assert!(images.transmits[0].contains("i=1,a=T"), "sent as 1");
        assert!(
            buf.content().iter().all(|c| !c.symbol().contains('\x1b')),
            "nothing of it in the frame"
        );
        draw(&mut images);
        assert_eq!(images.sending(), 1, "sent once");
    }

    #[test]
    fn an_images_code_is_found_where_it_starts_drawing_though_its_corner_is_off_the_screen() {
        use ratatui::Terminal;
        use ratatui::backend::TestBackend;

        let mut images = kitty();
        images.insert_ready(key(7), photo());
        let mut terminal = Terminal::new(TestBackend::new(10, 4)).unwrap();
        // Partly past the bottom right, a row scrolled away above.
        let (area, at) = (Rect::new(7, 1, 4, 4), SignedPosition::from((0, -1)));
        terminal
            .draw(|frame| {
                assert!(images.draw(frame, area, at, |i| i.get(&preview(7), 4, 2, false)));
            })
            .unwrap();
        assert_eq!(images.sending(), 1);
    }

    #[test]
    fn inside_tmux_the_code_that_deletes_images_goes_through_it() {
        assert_eq!(
            kitty_delete(1, true),
            "\x1bPtmux;\x1b\x1b_Ga=d,d=I,i=1,q=2\x1b\x1b\\\x1b\\"
        );
    }

    #[test]
    fn terminals_that_keep_no_images_are_told_nothing() {
        let mut images = Images::new(
            Picker::halfblocks(),
            tokio::sync::mpsc::unbounded_channel().0,
        );
        images.insert_ready(key(1), photo());
        images.drop_all();
        assert_eq!(images.deletions(), None);
    }

    #[test]
    fn images_bigger_than_telegram_sends_are_refused() {
        assert!(decode_bytes(&png(512, 512)).is_ok());
        let error = decode_bytes(&png(5000, 1)).unwrap_err();
        assert!(matches!(error, image::ImageError::Limits(_)), "{error}");
    }

    #[test]
    fn a_failed_download_is_tried_again_after_its_cooldown() {
        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
        let mut images = Images::new(Picker::halfblocks(), tx);
        images.on_downloaded(3, None);
        images.want(&preview(3), 4, 2, false);
        images.fetch(&Tg::detached(tokio::sync::mpsc::unbounded_channel().0));
        assert!(
            matches!(images.files.get(&3), Some(FileState::Failed(_))),
            "still cooling down"
        );

        images.files.insert(
            3,
            FileState::Failed(std::time::Instant::now() - RETRY_AFTER),
        );
        images.want(&preview(3), 4, 2, false);
        images.fetch(&Tg::detached(tokio::sync::mpsc::unbounded_channel().0));
        assert!(
            matches!(images.files.get(&3), Some(FileState::Downloading)),
            "tried again"
        );
    }

    #[test]
    fn a_file_that_doesnt_decode_isnt_fetched_or_decoded_again() {
        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
        let mut images = Images::new(Picker::halfblocks(), tx);
        images.on_downloaded(7, Some("/nowhere/7.jpg".into()));
        images.on_built(ImageEvent {
            generation: 0,
            key: key(7),
            result: Err(anyhow::anyhow!("not an image")),
        });
        assert!(images.is_broken(&preview(7)));
        images.want(&preview(7), 4, 2, false);
        images.fetch(&Tg::detached(tokio::sync::mpsc::unbounded_channel().0));
        assert!(
            matches!(images.files.get(&7), Some(FileState::Broken)),
            "not downloaded again: it would fail the same way"
        );
        assert!(!images.building.contains_key(&(0, key(7))), "nor decoded");
    }

    #[test]
    fn a_file_that_only_fails_at_one_size_is_drawn_at_others() {
        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
        let mut images = Images::new(Picker::halfblocks(), tx);
        images.on_downloaded(7, Some("/nowhere/7.jpg".into()));
        images.on_built(ImageEvent {
            generation: 0,
            key: key(7),
            result: Err(anyhow::anyhow!("too big").context(AtThisSize)),
        });
        assert!(!images.is_broken(&preview(7)));
        assert!(
            images.failed.contains(&key(7)),
            "not tried again at that size"
        );
        assert!(matches!(images.files.get(&7), Some(FileState::Ready(_))));
    }

    #[test]
    fn a_file_gone_from_disk_is_downloaded_again_after_a_while() {
        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
        let mut images = Images::new(Picker::halfblocks(), tx);
        images.on_downloaded(7, Some("/nowhere/7.jpg".into()));
        let gone = std::io::Error::from(std::io::ErrorKind::NotFound);
        images.on_built(ImageEvent {
            generation: 0,
            key: key(7),
            result: Err(image::ImageError::IoError(gone).into()),
        });
        assert!(matches!(images.files.get(&7), Some(FileState::Failed(_))));
        assert!(
            !images.failed.contains(&key(7)),
            "built again once it's back"
        );

        // An attachment's file isn't TDLib's to download.
        images.local_file(-1, "/nowhere/mine.jpg");
        let gone = std::io::Error::from(std::io::ErrorKind::NotFound);
        images.on_built(ImageEvent {
            generation: 0,
            key: key(-1),
            result: Err(image::ImageError::IoError(gone).into()),
        });
        assert!(matches!(images.files.get(&-1), Some(FileState::Broken)));
    }

    #[cfg(unix)]
    #[test]
    fn a_program_still_going_past_its_time_is_killed() {
        let command = |program: &str, arg: &str| {
            let mut command = std::process::Command::new(program);
            command.arg(arg);
            command
        };
        let started = std::time::Instant::now();
        let limit = std::time::Duration::from_millis(200);
        let (status, _) = run_within(command("sleep", "5"), limit).unwrap();
        assert!(status.is_none(), "killed");
        assert!(started.elapsed() < std::time::Duration::from_secs(2));

        let (status, out) = run_within(command("printf", "frame"), limit).unwrap();
        assert!(status.is_some_and(|s| s.success()));
        assert_eq!(out, b"frame");
    }

    #[test]
    fn a_picture_that_cant_be_made_at_a_size_says_so_there_not_loading() {
        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
        let mut images = Images::new(Picker::halfblocks(), tx);
        images.on_downloaded(7, Some("/nowhere/7.jpg".into()));
        images.on_built(ImageEvent {
            generation: 0,
            key: key(7),
            result: Err(anyhow::anyhow!("too big").context(AtThisSize)),
        });
        assert!(images.unavailable(&preview(7), 4, 2, false));
        assert!(
            !images.unavailable(&preview(7), 8, 4, false),
            "another size may do"
        );
        assert!(
            !images.unavailable(&preview(8), 4, 2, false),
            "nothing failed"
        );
        images.files.insert(8, FileState::Broken);
        assert!(images.unavailable(&preview(8), 8, 4, false), "at no size");
    }

    #[test]
    fn a_failed_download_is_asked_again_without_saying_its_failure_again() {
        use std::time::Instant;
        assert_eq!(download_to_ask(None), Some(Ask::Reported));
        let long_ago = Instant::now().checked_sub(RETRY_AFTER).unwrap();
        assert_eq!(
            download_to_ask(Some(&FileState::Failed(long_ago))),
            Some(Ask::Quiet)
        );
        let just_now = FileState::Failed(Instant::now());
        assert_eq!(download_to_ask(Some(&just_now)), None, "cooling down");
        assert_eq!(download_to_ask(Some(&FileState::Downloading)), None);
        assert_eq!(download_to_ask(Some(&FileState::Broken)), None);
    }

    #[test]
    fn a_video_stickers_still_fails_with_ffmpegs_word_not_the_image_librarys() {
        let dir = std::env::temp_dir().join(format!("tuigram-sticker-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("sticker.webm");
        // EBML's magic, then nothing a decoder can use.
        std::fs::write(&path, [0x1a, 0x45, 0xdf, 0xa3, 0, 0, 0, 0]).unwrap();
        let error = open_sticker(path.to_str().unwrap()).unwrap_err();
        std::fs::remove_dir_all(&dir).unwrap();
        // ffmpeg's: it failed on the file, or wasn't there to ask.
        assert!(matches!(error, image::ImageError::IoError(_)), "{error:?}");
    }

    #[test]
    fn only_a_kind_the_image_library_doesnt_read_goes_to_ffmpeg() {
        use image::error::{ImageFormatHint, UnsupportedError, UnsupportedErrorKind};
        let asked = std::cell::Cell::new(0);
        let still = || {
            asked.set(asked.get() + 1);
            Err(image::ImageError::IoError(
                std::io::ErrorKind::InvalidData.into(),
            ))
        };
        let gone = image::ImageError::IoError(std::io::ErrorKind::NotFound.into());
        let result = or_still(Err(gone), still);
        assert!(
            matches!(&result, Err(image::ImageError::IoError(e)) if e.kind() == std::io::ErrorKind::NotFound),
            "its own error: {result:?}"
        );
        assert_eq!(asked.get(), 0, "no ffmpeg for a file gone from disk");

        let unknown = UnsupportedError::from_format_and_kind(
            ImageFormatHint::Unknown,
            UnsupportedErrorKind::Format(ImageFormatHint::Unknown),
        );
        assert!(or_still(Err(image::ImageError::Unsupported(unknown)), still).is_err());
        assert_eq!(asked.get(), 1, "a WebM, say");
    }

    #[test]
    fn a_file_that_cant_be_read_for_now_is_tried_again_but_bytes_that_dont_decode_arent() {
        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
        let mut images = Images::new(Picker::halfblocks(), tx);
        let failing = |error: anyhow::Error| ImageEvent {
            generation: 0,
            key: key(7),
            result: Err(error),
        };
        // Too many files open: another time may go better.
        for passing in [
            #[cfg(unix)]
            std::io::Error::from_raw_os_error(libc::EMFILE),
            std::io::ErrorKind::WouldBlock.into(),
        ] {
            images.files.clear();
            images.on_downloaded(7, Some("/nowhere/7.jpg".into()));
            images.on_built(failing(passing.into()));
            assert!(matches!(images.files.get(&7), Some(FileState::Failed(_))));
            assert!(!images.failed.contains(&key(7)));
        }
        // Cut short, failing or killing ffmpeg, not ours to read, no ffmpeg,
        // a decoder's own error: trying again changes nothing.
        for kind in [
            std::io::ErrorKind::UnexpectedEof,
            std::io::ErrorKind::InvalidData,
            std::io::ErrorKind::PermissionDenied,
            std::io::ErrorKind::Unsupported,
            std::io::ErrorKind::Other,
        ] {
            images.files.clear();
            images.failed.clear();
            images.on_downloaded(7, Some("/nowhere/7.jpg".into()));
            let error = image::ImageError::IoError(kind.into());
            images.on_built(failing(error.into()));
            assert!(
                matches!(images.files.get(&7), Some(FileState::Broken)),
                "{kind:?}"
            );
        }
    }

    /// Whether the image at `path` is shown, with TDLib keeping its files
    /// in `tdlib_dirs`.
    async fn shows(path: &std::path::Path, tdlib_dirs: &[PathBuf]) -> bool {
        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
        let mut images = Images::new(Picker::halfblocks(), tx);
        images.tdlib_keeps_files_in(tdlib_dirs.into());
        images.on_downloaded(3, Some(path.to_str().unwrap().into()));
        images.want(&preview(3), 4, 2, false);
        images.fetch(&Tg::detached(tokio::sync::mpsc::unbounded_channel().0));
        images.on_built(rx.recv().await.unwrap());
        images.sharp(&preview(3), 4, 2).is_some()
    }

    /// A folder of its own in the system's temp folder, removed once dropped,
    /// even after an assert failed.
    struct TempDir(PathBuf);

    impl TempDir {
        fn new(name: &str) -> Self {
            let dir = std::env::temp_dir().join(format!("tuigram-{name}-{}", std::process::id()));
            let _ = std::fs::remove_dir_all(&dir);
            std::fs::create_dir_all(&dir).unwrap();
            Self(dir)
        }
    }

    impl Drop for TempDir {
        fn drop(&mut self) {
            let _ = std::fs::remove_dir_all(&self.0);
        }
    }

    #[tokio::test]
    async fn a_photo_you_sent_shows_though_wider_than_anyone_elses_may_be() {
        let temp = TempDir::new("yours");
        let dir = &temp.0;
        let tdlib = [dir.join("db"), dir.join("files")];
        for folder in &tdlib {
            std::fs::create_dir_all(folder).unwrap();
        }
        // A Retina screenshot sent as a photo: TDLib keeps the file sent, where
        // it is, as the photo's largest size.
        let screenshot = dir.join("screenshot.png");
        std::fs::write(&screenshot, png(4259, 1567)).unwrap();
        assert!(shows(&screenshot, &tdlib).await);
        // Someone else's as big can only be a download.
        let downloaded = tdlib[1].join("photo.png");
        std::fs::copy(&screenshot, &downloaded).unwrap();
        assert!(!shows(&downloaded, &tdlib).await, "someone else's");
        // Bigger than Telegram takes a photo: each side is within 10,000px,
        // but not the two together.
        let too_big = dir.join("too-big.png");
        std::fs::write(&too_big, png(9_000, 1_001)).unwrap();
        assert!(!shows(&too_big, &tdlib).await);
        // Not knowing where TDLib's files are, none is yours.
        assert!(!shows(&screenshot, &[]).await);
        // Before TDLib made its downloads folder, nothing is in it.
        let unmade = [tdlib[0].clone(), dir.join("not-yet")];
        assert!(shows(&screenshot, &unmade).await);
        // Copied with `y`.
        let path = screenshot.to_str().unwrap();
        assert!(open_photo(path, &tdlib).is_ok());
        let downloaded = downloaded.to_str().unwrap();
        assert!(open_photo(downloaded, &tdlib).is_err(), "someone else's");
    }
}