termlens 0.8.0

Headless PTY test harness for CLI/TUI apps — spawn in a real PTY, assert on the rendered screen
Documentation
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
//! Inline graphics: the payloads an application transmitted, and — with the
//! `decode` feature — what they depicted.
//!
//! Two protocols reach a terminal as escape strings rather than as cells:
//! kitty's (`APC G <control> ; <base64> ST`) and sixel's
//! (`DCS <params> q <data> ST`). Neither touches the grid, so no content
//! predicate can see one, and until a payload is *captured* the only
//! questions a test can ask are "did anything go out?" and "how big was it?".
//!
//! Capturing is not rendering. termlens draws no pixels and goes on declining
//! both protocols in DA1 unless a test declares otherwise with
//! [`TerminalBuilder::graphics`](crate::TerminalBuilder::graphics) — which is
//! precisely why an application that transmits one anyway is worth catching.
//! What capture adds is the other half of the assertion: *which* image, of
//! what size, placed where, and — decoded — of what colour.
//!
//! This is the same position [`Clipboard`](crate::Clipboard) takes on
//! `OSC 52`. A write is not a question, the application's own toast proves
//! only that the code path ran, and the payload is usually the behaviour
//! actually under test.
//!
//! ```no_run
//! # fn main() -> termlens::Result<()> {
//! # let mut t = termlens::Terminal::builder().spawn("true")?;
//! let screen = t.wait_frame(|s| s.contains("ready"))?;
//! let seen = screen.graphics();
//! let image = seen.payloads().last().expect("the chart went out as an image");
//! // Placed on exactly the character cells the layout reserved.
//! assert_eq!(image.cells(), Some((106, 7)));
//! # Ok(())
//! # }
//! ```

use std::fmt;
use std::sync::Arc;

/// How many payload bytes are kept for inspection by default: enough for a
/// screenful of chart at any plausible cell size, and small enough that a
/// suite which never looks at an image pays nothing it would notice.
///
/// [`TerminalBuilder::capture_graphics`](crate::TerminalBuilder::capture_graphics)
/// moves it, in either direction.
pub(crate) const DEFAULT_CAPTURE: usize = 4 << 20;

/// The most payloads retained at once, however small they are. A sliding
/// window like scrollback's: an application that redraws for an hour must
/// not grow this without limit, and it is the recent ones an assertion is
/// about.
pub(crate) const HISTORY: usize = 512;

/// Which protocol carried a payload.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum GraphicsProtocol {
    /// The kitty graphics protocol: `APC G <control> ; <base64> ST`.
    Kitty,
    /// Sixel: `DCS <params> q <data> ST`.
    Sixel,
}

impl fmt::Display for GraphicsProtocol {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            GraphicsProtocol::Kitty => "kitty",
            GraphicsProtocol::Sixel => "sixel",
        })
    }
}

/// What the application asked the terminal to *do* with an image.
///
/// Only kitty distinguishes these; a sixel is always drawn where the cursor
/// stands, so it reports [`TransmitAndPlace`](Self::TransmitAndPlace).
///
/// The distinction is not cosmetic: a delete carries no picture, and counting
/// one as an image transmitted makes "how many images did this frame send?"
/// answer with the number of *escapes* instead.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum GraphicsAction {
    /// `a=t`: transmit the data, place it later.
    Transmit,
    /// `a=p`: place an image transmitted earlier.
    Place,
    /// `a=T`, and every sixel: transmit and place in one go.
    TransmitAndPlace,
    /// `a=d`: delete an image, or the placements made from one.
    Delete,
    /// `a=f` (transmit a frame), `a=a` (animate), `a=c` (compose) and
    /// anything else the protocol grows. Named rather than folded into
    /// [`Transmit`](Self::Transmit): guessing that an unknown action carries
    /// a picture is how a count starts lying.
    Other,
}

impl GraphicsAction {
    /// Whether this action carries image data — the question
    /// [`GraphicsSeen::total`] is counting.
    #[must_use]
    pub fn carries_image(self) -> bool {
        matches!(
            self,
            GraphicsAction::Transmit | GraphicsAction::TransmitAndPlace
        )
    }
}

/// How the pixels in a payload are encoded.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum GraphicsFormat {
    /// kitty `f=24`: three bytes a pixel.
    Rgb,
    /// kitty `f=32`: four bytes a pixel.
    Rgba,
    /// kitty `f=100`: a PNG file. Decoding one is out of scope — termlens
    /// carries no image codec — so `GraphicsPayload::decode` reports it
    /// as unsupported rather than guessing.
    Png,
    /// The sixel data stream itself.
    Sixel,
    /// A kitty `f=` value this crate does not know.
    Other(u32),
}

impl fmt::Display for GraphicsFormat {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            GraphicsFormat::Rgb => f.write_str("rgb"),
            GraphicsFormat::Rgba => f.write_str("rgba"),
            GraphicsFormat::Png => f.write_str("png"),
            GraphicsFormat::Sixel => f.write_str("sixel"),
            GraphicsFormat::Other(value) => write!(f, "f={value}"),
        }
    }
}

/// One inline image an application transmitted, as observed on the wire.
///
/// Read the list from [`GraphicsSeen::payloads`]. Every field is a fact the
/// application stated or the wire carried — nothing here is inferred from a
/// rendering, because there is no rendering.
#[derive(Clone, PartialEq, Eq)]
pub struct GraphicsPayload {
    protocol: GraphicsProtocol,
    action: GraphicsAction,
    format: GraphicsFormat,
    compressed: bool,
    id: Option<u32>,
    size: Option<(u32, u32)>,
    cells: Option<(u16, u16)>,
    chunks: u32,
    bytes: u64,
    at: (u16, u16),
    data: Option<Arc<[u8]>>,
}

impl fmt::Debug for GraphicsPayload {
    /// Compact on purpose: a `Screen` is embedded in every error, and a
    /// derived `Debug` would put a megabyte of base64 into a CI log —
    /// which is how a failure ends up with no diagnosable output at all.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{} {:?} {}",
            self.protocol,
            self.action,
            match self.size {
                Some((w, h)) => format!("{w}x{h}px"),
                None => "?px".into(),
            }
        )?;
        if let Some((cols, rows)) = self.cells {
            write!(f, " {cols}x{rows}cells")?;
        }
        write!(f, " at {:?}", self.at)?;
        if let Some(id) = self.id {
            write!(f, " i={id}")?;
        }
        write!(f, " {} {} bytes", self.format, self.bytes)?;
        if self.compressed {
            f.write_str(" zlib")?;
        }
        if self.chunks > 1 {
            write!(f, " in {} chunks", self.chunks)?;
        }
        if self.data.is_none() {
            f.write_str(" (not captured)")?;
        }
        Ok(())
    }
}

impl GraphicsPayload {
    /// Which protocol carried it.
    #[must_use]
    pub fn protocol(&self) -> GraphicsProtocol {
        self.protocol
    }

    /// What the application asked the terminal to do with it.
    #[must_use]
    pub fn action(&self) -> GraphicsAction {
        self.action
    }

    /// How the pixels are encoded.
    #[must_use]
    pub fn format(&self) -> GraphicsFormat {
        self.format
    }

    /// Whether the data is zlib-compressed (kitty `o=z`).
    #[must_use]
    pub fn compressed(&self) -> bool {
        self.compressed
    }

    /// The image id the application gave it (kitty `i=`), if any.
    #[must_use]
    pub fn id(&self) -> Option<u32> {
        self.id
    }

    /// The image's size in pixels, as the application *declared* it — kitty
    /// `s=`/`v=`, or a sixel's raster attributes.
    ///
    /// `None` when nothing declared one, which for sixel means the size is
    /// implicit in the data; `GraphicsPayload::decode` computes it there.
    #[must_use]
    pub fn size(&self) -> Option<(u32, u32)> {
        self.size
    }

    /// The placement the application pinned, in character cells (kitty
    /// `c=`/`r=`).
    ///
    /// This is the field that keeps an image in step with the text around it:
    /// an application that lays out a grid in cells and then transmits an
    /// image of the wrong cell extent draws a picture that slides out from
    /// under its own labels, and nothing on screen says so.
    #[must_use]
    pub fn cells(&self) -> Option<(u16, u16)> {
        self.cells
    }

    /// Where the cursor stood when the payload completed, as `(row, col)` —
    /// which for both protocols is the image's top-left corner.
    #[must_use]
    pub fn at(&self) -> (u16, u16) {
        self.at
    }

    /// Escapes the transmission was split across. Kitty caps a payload at
    /// 4096 bytes and continues with `m=1`, so any image of consequence
    /// arrives in several; they are one payload here.
    #[must_use]
    pub fn chunks(&self) -> u32 {
        self.chunks
    }

    /// Bytes this payload occupied on the wire, summed over its chunks:
    /// everything between introducer and terminator, control blocks
    /// included, since that is what the application actually spent.
    #[must_use]
    pub fn bytes(&self) -> u64 {
        self.bytes
    }

    /// The image data as it arrived: the base64 body for kitty with the
    /// control blocks stripped and the chunks joined, and everything after
    /// the `q` that closes the header for sixel.
    ///
    /// `None` when the payload fell past the capture bound — see
    /// [`TerminalBuilder::capture_graphics`](crate::TerminalBuilder::capture_graphics).
    /// Deliberately distinct from `Some(&[])`, which is a real transmission
    /// of nothing.
    #[must_use]
    pub fn data(&self) -> Option<&[u8]> {
        self.data.as_deref()
    }

    /// Decode the payload into pixels.
    ///
    /// Supports kitty `f=24`/`f=32`, zlib-compressed or not, and the sixel
    /// data stream. Everything else — `f=100` (PNG), an action that carries
    /// no image, a payload past the capture bound — is an [error naming the
    /// reason](DecodeError) rather than a `None` a test could mistake for
    /// "the image was empty".
    ///
    /// Decoding is done here, on demand, and never as the bytes arrive: a
    /// test that only counts payloads should not pay for inflating them.
    ///
    /// # Errors
    ///
    /// Returns [`DecodeError::NotCaptured`] when the payload exceeded the
    /// capture bound, [`DecodeError::NoImage`] when the action carries no
    /// image, and [`DecodeError::Unsupported`] when its format is not
    /// supported. [`DecodeError::Malformed`] covers contradictory or invalid
    /// payload data, including data that cannot be decoded within its declared
    /// size. [`DecodeError::TooLarge`] covers declared dimensions or sixel
    /// commands beyond the 4096-pixel and related safety limits.
    #[cfg(feature = "decode")]
    pub fn decode(&self) -> Result<Bitmap, DecodeError> {
        let data = self.data.as_deref().ok_or(DecodeError::NotCaptured)?;
        match self.protocol {
            GraphicsProtocol::Kitty => self.decode_kitty(data),
            GraphicsProtocol::Sixel => decode_sixel(data),
        }
    }

    #[cfg(feature = "decode")]
    fn decode_kitty(&self, data: &[u8]) -> Result<Bitmap, DecodeError> {
        let (channels, has_alpha) = match self.format {
            GraphicsFormat::Rgb => (3usize, false),
            GraphicsFormat::Rgba => (4usize, true),
            GraphicsFormat::Png => return Err(DecodeError::Unsupported("kitty f=100 (PNG)")),
            other => {
                return Err(DecodeError::Unsupported(match other {
                    GraphicsFormat::Sixel => "a sixel stream sent as kitty data",
                    _ => "an unknown kitty f= format",
                }))
            }
        };
        if !self.action.carries_image() {
            return Err(DecodeError::NoImage(self.action));
        }
        let (width, height) = self.size.ok_or(DecodeError::Malformed(
            "a kitty transmission without s= and v=",
        ))?;
        // The declared size is computed *before* the payload is touched,
        // because it is what bounds the inflate below. The other way round —
        // as this was — leaves `decompress_to_vec_zlib` free to allocate
        // whatever the compressed bytes expand to, and zlib reaches about
        // 1000:1, so a payload inside the capture bound could ask for
        // gigabytes.
        if width as usize > MAX_DECODED_WIDTH || height as usize > MAX_DECODED_HEIGHT {
            return Err(DecodeError::TooLarge(
                "a kitty transmission declaring more than 4096x4096",
            ));
        }
        let wanted = (width as usize)
            .checked_mul(height as usize)
            .and_then(|pixels| pixels.checked_mul(channels))
            .ok_or(DecodeError::Malformed("a declared size that overflows"))?;
        let raw = crate::emu::decode_base64(data).ok_or(DecodeError::Malformed("bad base64"))?;
        let raw = if self.compressed {
            // Nothing past the declared size is ever read, so nothing past it
            // needs inflating.
            miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(&raw, wanted).map_err(|_| {
                DecodeError::Malformed("zlib data that would not inflate within the declared size")
            })?
        } else {
            raw
        };
        if raw.len() < wanted {
            return Err(DecodeError::Malformed(
                "fewer bytes than the declared size needs",
            ));
        }
        let mut pixels = Vec::with_capacity(wanted / channels);
        for chunk in raw[..wanted].chunks_exact(channels) {
            pixels.push([
                chunk[0],
                chunk[1],
                chunk[2],
                if has_alpha { chunk[3] } else { 0xff },
            ]);
        }
        Ok(Bitmap {
            width,
            height,
            pixels,
        })
    }

    pub(crate) fn place(&mut self, at: (u16, u16)) {
        self.at = at;
    }
}

/// The pixels one payload depicted.
///
/// A decoded image, not a rendering: termlens never composites this onto the
/// screen grid, and the grid never mentions it. It exists so an assertion can
/// be about the picture — "the day at week 30 is Primer's brightest green" —
/// rather than about its size in bytes.
#[cfg(feature = "decode")]
#[derive(Clone, PartialEq, Eq)]
pub struct Bitmap {
    width: u32,
    height: u32,
    pixels: Vec<[u8; 4]>,
}

#[cfg(feature = "decode")]
impl fmt::Debug for Bitmap {
    /// The dimensions, never the pixels: a screen's worth of them in a
    /// timeout error is a log nobody can read.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Bitmap {}x{}", self.width, self.height)
    }
}

#[cfg(feature = "decode")]
impl Bitmap {
    /// Width in pixels.
    #[must_use]
    pub fn width(&self) -> u32 {
        self.width
    }

    /// Height in pixels.
    #[must_use]
    pub fn height(&self) -> u32 {
        self.height
    }

    /// The pixel at `(x, y)` as RGBA, or `None` when out of bounds.
    ///
    /// Alpha is `0` for a sixel pixel no colour was ever written to — sixel
    /// has no alpha channel, so "transparent" there means "left as the
    /// terminal found it", which is exactly the distinction an assertion
    /// about a rounded corner needs.
    #[must_use]
    pub fn pixel(&self, x: u32, y: u32) -> Option<[u8; 4]> {
        if x >= self.width || y >= self.height {
            return None;
        }
        let index = (y as usize) * (self.width as usize) + (x as usize);
        self.pixels.get(index).copied()
    }

    /// Every distinct colour in the image, with how many pixels carry it,
    /// most common first.
    ///
    /// The shape of most assertions about a chart: how many greens, and is
    /// the brightest one the one the palette names.
    ///
    /// **Ties are broken by first appearance**, in raster order (left to
    /// right, top to bottom), so the result is fully determined by the image
    /// and `colours()[0]` has one answer — a test harness must not hand back
    /// a different order on a different run. Linear in the pixel count: a
    /// 512x512 screenshot costs milliseconds, not the seconds a per-pixel
    /// scan of the distinct set used to.
    #[must_use]
    pub fn colours(&self) -> Vec<([u8; 4], u32)> {
        use std::collections::HashMap;

        // One pass, remembering where each colour first appeared so that
        // equal counts have an order the caller can rely on.
        let mut counts: HashMap<[u8; 4], (u32, usize)> = HashMap::new();
        for (index, pixel) in self.pixels.iter().enumerate() {
            counts
                .entry(*pixel)
                .and_modify(|(count, _)| *count += 1)
                .or_insert((1, index));
        }
        let mut seen: Vec<([u8; 4], u32, usize)> = counts
            .into_iter()
            .map(|(colour, (count, first))| (colour, count, first))
            .collect();
        // Count descending, then first appearance: a total order, so the
        // sort's own stability is not what the determinism rests on.
        seen.sort_unstable_by_key(|&(_, count, first)| (std::cmp::Reverse(count), first));
        seen.into_iter()
            .map(|(colour, count, _)| (colour, count))
            .collect()
    }
}

/// The largest image [`GraphicsPayload::decode`] will build.
///
/// Every size in a payload is chosen by the program under test: kitty
/// declares `s=`/`v=` and may arrive zlib-compressed, and sixel declares its
/// raster attributes, names colour registers by index, and repeats a byte
/// `!n` times. Each of those turns a handful of bytes into a request for
/// tens of gigabytes if it is trusted — `!4294967295~` is twelve bytes, and
/// a declared `65535x65535` is about twenty.
///
/// 4096x4096 is far beyond what any terminal can place, and 64 MiB of RGBA
/// once built, so a real image is never refused by it.
#[cfg(feature = "decode")]
const MAX_DECODED_WIDTH: usize = 4096;
/// See [`MAX_DECODED_WIDTH`].
#[cfg(feature = "decode")]
const MAX_DECODED_HEIGHT: usize = 4096;
/// Colour registers a sixel may name. `#n` gives the index directly, so it
/// is attacker-chosen; the common maximum is 256 and no terminal goes past
/// this.
#[cfg(feature = "decode")]
const MAX_SIXEL_REGISTERS: usize = 65_536;

/// Why a payload could not be decoded.
#[cfg(feature = "decode")]
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum DecodeError {
    /// The payload fell past the capture bound, so its bytes were counted
    /// but not kept. Raise the bound with
    /// [`TerminalBuilder::capture_graphics`](crate::TerminalBuilder::capture_graphics).
    NotCaptured,
    /// The action carries no image at all — a delete, or a bare placement of
    /// something transmitted earlier.
    NoImage(GraphicsAction),
    /// A well-formed payload in an encoding termlens does not decode.
    Unsupported(&'static str),
    /// The payload contradicts itself or the protocol.
    Malformed(&'static str),
    /// The payload asks for more memory than termlens will spend on one
    /// image. Not a judgement about the picture: it is a refusal to let a
    /// size the program under test chose decide how much this allocates.
    TooLarge(&'static str),
}

#[cfg(feature = "decode")]
impl fmt::Display for DecodeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            DecodeError::NotCaptured => f.write_str(
                "the payload was counted but not kept — raise TerminalBuilder::capture_graphics",
            ),
            DecodeError::NoImage(action) => {
                write!(f, "a {action:?} action carries no image data")
            }
            DecodeError::Unsupported(what) => write!(f, "termlens does not decode {what}"),
            DecodeError::Malformed(what) => write!(f, "the payload carries {what}"),
            DecodeError::TooLarge(what) => write!(f, "termlens will not decode {what}"),
        }
    }
}

#[cfg(feature = "decode")]
impl std::error::Error for DecodeError {}

/// Decode a sixel data stream — everything after the `q` that closes the
/// DCS header — into pixels.
///
/// The format in one paragraph: optional raster attributes
/// (`"Pan;Pad;Ph;Pv`) declare the size; `#n;2;r;g;b` defines colour register
/// `n` in percent; `#n` selects it; a byte `?`..`~` paints the six pixels of
/// the current band whose bits it sets; `!<count>` repeats the next such
/// byte; `$` returns to the left margin within the band; `-` ends the band.
#[cfg(feature = "decode")]
fn decode_sixel(data: &[u8]) -> Result<Bitmap, DecodeError> {
    /// A colour register, or `None` where the application never defined one.
    type Registers = Vec<Option<[u8; 4]>>;

    fn percent(value: u32) -> u8 {
        // Sixel colour components are percentages, and the rounding has to
        // match what a terminal does or every assertion lands one off.
        ((value.min(100) * 255 + 50) / 100) as u8
    }

    let mut at = 0usize;
    let mut declared: Option<(u32, u32)> = None;
    let mut registers: Registers = vec![None; 256];
    let mut current = 0usize;
    // Rows of runs, grown as the data addresses them: a sixel need not
    // declare its size, and one that does can still overrun it.
    let mut rows: Vec<Vec<Option<[u8; 4]>>> = Vec::new();
    let mut band_top = 0usize;
    let mut x = 0usize;
    let mut width_seen = 0usize;

    /// Read a `;`-separated run of decimal parameters.
    fn params(data: &[u8], at: &mut usize) -> Vec<u32> {
        let mut out = vec![0u32];
        while *at < data.len() {
            match data[*at] {
                b'0'..=b'9' => {
                    let last = out.last_mut().expect("seeded with one parameter");
                    *last = last
                        .saturating_mul(10)
                        .saturating_add(u32::from(data[*at] - b'0'));
                }
                b';' => out.push(0),
                _ => break,
            }
            *at += 1;
        }
        out
    }

    while at < data.len() {
        match data[at] {
            b'"' => {
                at += 1;
                let raster = params(data, &mut at);
                if let (Some(&width), Some(&height)) = (raster.get(2), raster.get(3)) {
                    declared = Some((width, height));
                }
            }
            b'#' => {
                at += 1;
                let values = params(data, &mut at);
                let index = values.first().copied().unwrap_or(0) as usize;
                if index >= MAX_SIXEL_REGISTERS {
                    return Err(DecodeError::TooLarge(
                        "a sixel colour register index past 65536",
                    ));
                }
                if index >= registers.len() {
                    registers.resize(index + 1, None);
                }
                if values.len() >= 5 {
                    // `#n;1;…` is HLS; only RGB (`2`) is defined here, and a
                    // guessed conversion would put wrong colours into an
                    // assertion that reads as exact.
                    if values[1] != 2 {
                        return Err(DecodeError::Unsupported("sixel HLS colours"));
                    }
                    registers[index] = Some([
                        percent(values[2]),
                        percent(values[3]),
                        percent(values[4]),
                        0xff,
                    ]);
                }
                current = index;
            }
            b'!' => {
                at += 1;
                let counts = params(data, &mut at);
                let count = counts.first().copied().unwrap_or(0) as usize;
                if at < data.len() && (0x3f..=0x7e).contains(&data[at]) {
                    let bits = data[at] - 0x3f;
                    at += 1;
                    paint(
                        &mut rows,
                        &mut width_seen,
                        band_top,
                        &mut x,
                        bits,
                        count,
                        registers.get(current).copied().flatten(),
                    )?;
                }
            }
            0x3f..=0x7e => {
                let bits = data[at] - 0x3f;
                at += 1;
                paint(
                    &mut rows,
                    &mut width_seen,
                    band_top,
                    &mut x,
                    bits,
                    1,
                    registers.get(current).copied().flatten(),
                )?;
            }
            b'$' => {
                at += 1;
                x = 0;
            }
            b'-' => {
                at += 1;
                band_top += 6;
                x = 0;
            }
            // Whitespace between records, and anything else the stream
            // carries that paints nothing.
            _ => at += 1,
        }
    }

    fn paint(
        rows: &mut Vec<Vec<Option<[u8; 4]>>>,
        width_seen: &mut usize,
        band_top: usize,
        x: &mut usize,
        bits: u8,
        count: usize,
        colour: Option<[u8; 4]>,
    ) -> Result<(), DecodeError> {
        for _ in 0..count {
            // Checked every step rather than once against `count`: `!n` gives
            // a `u32`, and the cursor also carries over from earlier runs in
            // the same band. Outside the colour branch because an undefined
            // register still advances the cursor, so a huge repeat would
            // otherwise spin four billion times painting nothing.
            if *x >= MAX_DECODED_WIDTH {
                return Err(DecodeError::TooLarge("a sixel wider than 4096 pixels"));
            }
            if let Some(colour) = colour {
                for bit in 0..6 {
                    if bits & (1 << bit) != 0 {
                        let y = band_top + bit;
                        if y >= MAX_DECODED_HEIGHT {
                            return Err(DecodeError::TooLarge("a sixel taller than 4096 pixels"));
                        }
                        if rows.len() <= y {
                            rows.resize(y + 1, Vec::new());
                        }
                        let row = &mut rows[y];
                        if row.len() <= *x {
                            row.resize(*x + 1, None);
                        }
                        row[*x] = Some(colour);
                    }
                }
            }
            *x += 1;
            *width_seen = (*width_seen).max(*x);
        }
        Ok(())
    }

    let (width, height) = match declared {
        Some((width, height)) if width > 0 && height > 0 => (width, height),
        _ => (width_seen as u32, rows.len() as u32),
    };
    // The declared raster attributes reach this allocation without the pixel
    // data being touched at all, so a payload declaring 65535x65535 and
    // painting nothing still asks for about 17 GB.
    if width as usize > MAX_DECODED_WIDTH || height as usize > MAX_DECODED_HEIGHT {
        return Err(DecodeError::TooLarge(
            "a sixel declaring more than 4096x4096",
        ));
    }
    let mut pixels = Vec::with_capacity((width as usize).saturating_mul(height as usize));
    for y in 0..height as usize {
        for x in 0..width as usize {
            pixels.push(
                rows.get(y)
                    .and_then(|row| row.get(x))
                    .copied()
                    .flatten()
                    // Untouched: sixel has no alpha, so a pixel never
                    // painted is the terminal's own background showing
                    // through, which is not a colour we may invent.
                    .unwrap_or([0, 0, 0, 0]),
            );
        }
    }
    Ok(Bitmap {
        width,
        height,
        pixels,
    })
}

/// Inline graphics payloads the application transmitted, as observed at one
/// snapshot.
///
/// Read it from a [`Screen`](crate::Screen) via
/// [`Screen::graphics`](crate::Screen::graphics). The counters are
/// cumulative and monotonic, so a test takes a delta around an action rather
/// than resetting a gauge; [`payloads`](Self::payloads) is the bounded tail
/// of what was captured.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct GraphicsSeen {
    pub(crate) counts: GraphicsCounts,
    pub(crate) payloads: Arc<Vec<GraphicsPayload>>,
}

impl GraphicsSeen {
    pub(crate) fn new(counts: GraphicsCounts, payloads: Arc<Vec<GraphicsPayload>>) -> Self {
        Self { counts, payloads }
    }
}

/// The cumulative counters, kept by the sequence tracker as bytes arrive.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub(crate) struct GraphicsCounts {
    pub(crate) kitty: u32,
    pub(crate) sixel: u32,
    pub(crate) deletes: u32,
    pub(crate) bytes: u64,
}

impl GraphicsCounts {
    /// Count one completed payload. Bytes are counted for every action —
    /// a delete costs the wire something too — but only an action that
    /// carries a picture counts as an image.
    pub(crate) fn record(&mut self, payload: &GraphicsPayload) {
        self.bytes += payload.bytes();
        if payload.action() == GraphicsAction::Delete {
            self.deletes += 1;
        }
        if !payload.action().carries_image() {
            return;
        }
        match payload.protocol() {
            GraphicsProtocol::Kitty => self.kitty += 1,
            GraphicsProtocol::Sixel => self.sixel += 1,
        }
    }
}

impl GraphicsSeen {
    /// Kitty images transmitted (`APC G … ST`).
    ///
    /// **Images, not escapes.** A transmission split across the protocol's
    /// 4096-byte chunks is one image, and an action carrying no picture — a
    /// delete above all — is not one at all.
    #[must_use]
    pub fn kitty(&self) -> u32 {
        self.counts.kitty
    }

    /// Sixel images transmitted (`DCS q … ST`).
    #[must_use]
    pub fn sixel(&self) -> u32 {
        self.counts.sixel
    }

    /// Images of either protocol.
    #[must_use]
    pub fn total(&self) -> u32 {
        self.counts.kitty + self.counts.sixel
    }

    /// Kitty delete commands (`a=d`) — images taken *off* the screen.
    ///
    /// Counted apart from [`total`](Self::total) because a delete carries no
    /// picture: an application that tears down what it drew and one that
    /// draws twice as much are opposite behaviours, and folding them
    /// together made the difference invisible.
    #[must_use]
    pub fn deletes(&self) -> u32 {
        self.counts.deletes
    }

    /// True when the application has transmitted no inline graphics at all.
    ///
    /// Deletes do not count: an application whose only graphics traffic is a
    /// teardown has drawn nothing.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.total() == 0
    }

    /// Total payload bytes across both protocols and every action, counted
    /// the same way for each: everything between the introducer and the
    /// terminator.
    #[must_use]
    pub fn bytes(&self) -> u64 {
        self.counts.bytes
    }

    /// The payloads themselves, oldest first — what went out, where it was
    /// placed, and, with the `decode` feature, what it depicted.
    ///
    /// Bounded, like scrollback: the most recent payloads within the capture
    /// bound, which
    /// [`TerminalBuilder::capture_graphics`](crate::TerminalBuilder::capture_graphics)
    /// sets. The counters above stay truthful whatever the bound, so a test
    /// that only counts is never affected by one.
    #[must_use]
    pub fn payloads(&self) -> &[GraphicsPayload] {
        &self.payloads
    }

    /// The most recent payload, if any.
    #[must_use]
    pub fn last(&self) -> Option<&GraphicsPayload> {
        self.payloads.last()
    }

    /// Counters without payloads, for tests that assemble a `TermState` by
    /// hand rather than driving an emulator.
    #[cfg(test)]
    pub(crate) fn for_test(kitty: u32, sixel: u32, deletes: u32, bytes: u64) -> Self {
        Self {
            counts: GraphicsCounts {
                kitty,
                sixel,
                deletes,
                bytes,
            },
            payloads: Arc::new(Vec::new()),
        }
    }
}

/// A payload under construction, owned by the sequence tracker: kitty splits
/// one image across escapes, so a payload is not complete until an escape
/// arrives without `m=1`.
#[derive(Debug)]
pub(crate) struct GraphicsBuilder {
    protocol: Option<GraphicsProtocol>,
    action: GraphicsAction,
    format: GraphicsFormat,
    compressed: bool,
    id: Option<u32>,
    size: Option<(u32, u32)>,
    cells: Option<(u16, u16)>,
    chunks: u32,
    bytes: u64,
    data: Vec<u8>,
    /// Set once any chunk arrived past the capture bound. The payload then
    /// reports no data at all rather than a prefix of one.
    dropped: bool,
}

impl Default for GraphicsBuilder {
    fn default() -> Self {
        Self {
            protocol: None,
            action: GraphicsAction::Other,
            format: GraphicsFormat::Rgba,
            compressed: false,
            id: None,
            size: None,
            cells: None,
            chunks: 0,
            bytes: 0,
            data: Vec::new(),
            dropped: false,
        }
    }
}

impl GraphicsBuilder {
    /// True once a kitty escape has opened a transmission that later
    /// escapes continue.
    pub(crate) fn in_progress(&self) -> bool {
        self.protocol.is_some()
    }

    /// Take on the facts of a kitty control block. Only the first escape of
    /// a chunked transmission carries one; the continuations carry `m=` and
    /// nothing else, so nothing here overwrites what is already known.
    pub(crate) fn kitty(&mut self, control: &[u8]) {
        if self.protocol.is_none() {
            self.protocol = Some(GraphicsProtocol::Kitty);
            self.action = match key(control, b"a") {
                Some(b"t") => GraphicsAction::Transmit,
                Some(b"p") => GraphicsAction::Place,
                // `a=T` is the default when a transmission names no action.
                Some(b"T") | None => GraphicsAction::TransmitAndPlace,
                Some(b"d") => GraphicsAction::Delete,
                Some(_) => GraphicsAction::Other,
            };
            self.format = match number(control, b"f") {
                Some(24) => GraphicsFormat::Rgb,
                // 32 is the protocol's default.
                Some(32) | None => GraphicsFormat::Rgba,
                Some(100) => GraphicsFormat::Png,
                Some(other) => GraphicsFormat::Other(other),
            };
            self.compressed = key(control, b"o") == Some(b"z");
            self.id = number(control, b"i");
            self.size = match (number(control, b"s"), number(control, b"v")) {
                (Some(width), Some(height)) => Some((width, height)),
                _ => None,
            };
            self.cells = match (number(control, b"c"), number(control, b"r")) {
                (Some(cols), Some(rows)) => Some((
                    cols.min(u32::from(u16::MAX)) as u16,
                    rows.min(u32::from(u16::MAX)) as u16,
                )),
                _ => None,
            };
        }
    }

    /// Take on the facts of a sixel header: the raster attributes are inside
    /// the data, so only the protocol is settled here.
    pub(crate) fn sixel(&mut self) {
        self.protocol = Some(GraphicsProtocol::Sixel);
        self.action = GraphicsAction::TransmitAndPlace;
        self.format = GraphicsFormat::Sixel;
    }

    /// Add one escape's worth of wire cost and image data.
    ///
    /// `complete` is false when the capture bound cut this chunk short, and
    /// `cap` bounds the payload as a whole — a kitty transmission arrives as
    /// one escape per 4096 bytes, so a bound applied per escape would let a
    /// thousand-chunk image retain a thousand times the budget.
    ///
    /// The counts stay exact either way; past the bound the data is dropped
    /// entirely rather than kept as a prefix that would decode into a
    /// plausible-looking wrong picture.
    pub(crate) fn chunk(&mut self, bytes: u64, data: &[u8], complete: bool, cap: usize) {
        self.chunks += 1;
        self.bytes += bytes;
        let fits = self.data.len().saturating_add(data.len()) <= cap;
        if complete && fits && !self.dropped {
            self.data.extend_from_slice(data);
        } else {
            self.dropped = true;
            self.data = Vec::new();
        }
    }

    /// Finish the payload. `at` is stamped later, by the emulator, once the
    /// grid has caught up with the terminator.
    pub(crate) fn finish(&mut self) -> Option<GraphicsPayload> {
        let protocol = self.protocol.take()?;
        let mut size = self.size;
        if protocol == GraphicsProtocol::Sixel {
            size = raster_size(&self.data).or(size);
        }
        let payload = GraphicsPayload {
            protocol,
            action: self.action,
            format: self.format,
            compressed: self.compressed,
            id: self.id,
            size,
            cells: self.cells,
            chunks: self.chunks,
            bytes: self.bytes,
            at: (0, 0),
            data: (!self.dropped)
                .then(|| Arc::from(std::mem::take(&mut self.data).into_boxed_slice())),
        };
        *self = Self::default();
        Some(payload)
    }
}

/// The `"Pan;Pad;Ph;Pv` raster attributes at the head of a sixel stream, if
/// it declares any.
fn raster_size(data: &[u8]) -> Option<(u32, u32)> {
    let at = data.iter().position(|&b| b == b'"')?;
    // Only a leading raster record describes the whole image; one appearing
    // after pixels have been painted is a different statement.
    if data[..at].iter().any(|b| (0x3f..=0x7e).contains(b)) {
        return None;
    }
    let mut values = vec![0u32];
    for &b in &data[at + 1..] {
        match b {
            b'0'..=b'9' => {
                let last = values.last_mut().expect("seeded with one parameter");
                *last = last.saturating_mul(10).saturating_add(u32::from(b - b'0'));
            }
            b';' => values.push(0),
            _ => break,
        }
    }
    match (values.get(2), values.get(3)) {
        (Some(&width), Some(&height)) if width > 0 && height > 0 => Some((width, height)),
        _ => None,
    }
}

/// The raw value of `name` in a kitty control block (`a=T,i=3,f=32`).
fn key<'a>(control: &'a [u8], name: &[u8]) -> Option<&'a [u8]> {
    control.split(|&b| b == b',').find_map(|pair| {
        let (found, value) = split_once(pair, b'=')?;
        (found == name).then_some(value)
    })
}

/// The numeric value of `name`, if it carries one.
fn number(control: &[u8], name: &[u8]) -> Option<u32> {
    std::str::from_utf8(key(control, name)?).ok()?.parse().ok()
}

fn split_once(bytes: &[u8], separator: u8) -> Option<(&[u8], &[u8])> {
    let at = bytes.iter().position(|&b| b == separator)?;
    Some((&bytes[..at], &bytes[at + 1..]))
}

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

    fn kitty_payload(control: &[u8], data: &[u8]) -> GraphicsPayload {
        let mut builder = GraphicsBuilder::default();
        builder.kitty(control);
        builder.chunk(data.len() as u64, data, true, usize::MAX);
        builder.finish().expect("a payload")
    }

    #[test]
    fn a_kitty_control_block_yields_every_fact_it_states() {
        let payload = kitty_payload(b"a=T,q=2,f=32,o=z,s=954,v=133,i=7,c=106,r=7", b"AAAA");
        assert_eq!(payload.protocol(), GraphicsProtocol::Kitty);
        assert_eq!(payload.action(), GraphicsAction::TransmitAndPlace);
        assert_eq!(payload.format(), GraphicsFormat::Rgba);
        assert!(payload.compressed());
        assert_eq!(payload.id(), Some(7));
        assert_eq!(payload.size(), Some((954, 133)));
        assert_eq!(payload.cells(), Some((106, 7)));
        assert_eq!(payload.data(), Some(&b"AAAA"[..]));
    }

    #[test]
    fn the_protocols_defaults_are_the_protocols_defaults() {
        // A transmission naming neither action nor format is `a=T,f=32`.
        let payload = kitty_payload(b"s=1,v=1", b"AAAA");
        assert_eq!(payload.action(), GraphicsAction::TransmitAndPlace);
        assert_eq!(payload.format(), GraphicsFormat::Rgba);
        assert!(!payload.compressed());
    }

    #[test]
    fn a_delete_is_not_an_image() {
        let payload = kitty_payload(b"a=d,d=I,i=1,q=2", b"");
        assert_eq!(payload.action(), GraphicsAction::Delete);
        assert!(!payload.action().carries_image());
    }

    #[test]
    fn an_unknown_action_is_not_guessed_to_carry_one() {
        let payload = kitty_payload(b"a=z,i=1", b"");
        assert_eq!(payload.action(), GraphicsAction::Other);
        assert!(!payload.action().carries_image());
    }

    #[test]
    fn chunks_join_into_one_payload() {
        let mut builder = GraphicsBuilder::default();
        builder.kitty(b"a=T,f=32,s=2,v=1,m=1");
        builder.chunk(20, b"AAAA", true, usize::MAX);
        builder.chunk(10, b"BBBB", true, usize::MAX);
        let payload = builder.finish().expect("a payload");
        assert_eq!(payload.chunks(), 2);
        assert_eq!(payload.bytes(), 30);
        assert_eq!(payload.data(), Some(&b"AAAABBBB"[..]));
    }

    #[test]
    fn a_payload_past_the_bound_is_counted_and_not_kept() {
        let mut builder = GraphicsBuilder::default();
        builder.kitty(b"a=T,f=32,s=2,v=1");
        builder.chunk(64, b"AAAABBBB", false, usize::MAX);
        let payload = builder.finish().expect("a payload");
        assert_eq!(payload.bytes(), 64, "the cost is still known");
        assert_eq!(payload.data(), None, "and the bytes are not kept");
    }

    #[test]
    fn a_sixel_reads_its_size_off_its_raster_attributes() {
        let mut builder = GraphicsBuilder::default();
        builder.sixel();
        builder.chunk(30, b"\"1;1;18;12#0;2;100;100;100~", true, usize::MAX);
        let payload = builder.finish().expect("a payload");
        assert_eq!(payload.protocol(), GraphicsProtocol::Sixel);
        assert_eq!(payload.size(), Some((18, 12)));
        assert_eq!(payload.format(), GraphicsFormat::Sixel);
    }

    #[test]
    fn a_sixel_that_declares_no_size_says_so_rather_than_guessing() {
        let mut builder = GraphicsBuilder::default();
        builder.sixel();
        builder.chunk(10, b"#0;2;100;100;100~~~", true, usize::MAX);
        assert_eq!(builder.finish().expect("a payload").size(), None);
    }

    #[cfg(feature = "decode")]
    #[test]
    fn a_kitty_rgba_transmission_decodes_to_its_pixels() {
        // Two pixels: opaque red, half-transparent blue.
        let raw = [0xff, 0x00, 0x00, 0xff, 0x00, 0x00, 0xff, 0x80];
        let data = base64(&raw);
        let payload = kitty_payload(b"a=T,f=32,s=2,v=1", data.as_bytes());
        let bitmap = payload.decode().expect("decodes");
        assert_eq!((bitmap.width(), bitmap.height()), (2, 1));
        assert_eq!(bitmap.pixel(0, 0), Some([0xff, 0, 0, 0xff]));
        assert_eq!(bitmap.pixel(1, 0), Some([0, 0, 0xff, 0x80]));
        assert_eq!(bitmap.pixel(2, 0), None, "out of bounds is None");
    }

    #[cfg(feature = "decode")]
    #[test]
    fn an_rgb_transmission_is_opaque() {
        let data = base64(&[0x11, 0x22, 0x33]);
        let payload = kitty_payload(b"a=T,f=24,s=1,v=1", data.as_bytes());
        let bitmap = payload.decode().expect("decodes");
        assert_eq!(bitmap.pixel(0, 0), Some([0x11, 0x22, 0x33, 0xff]));
    }

    #[cfg(feature = "decode")]
    fn sixel_payload(data: &[u8]) -> GraphicsPayload {
        let mut builder = GraphicsBuilder::default();
        builder.sixel();
        builder.chunk(data.len() as u64, data, true, usize::MAX);
        builder.finish().expect("a payload")
    }

    /// Every size in a payload is chosen by the program under test, and each
    /// of these turns a handful of bytes into a request for gigabytes if it
    /// is trusted. All five were live before the ceiling went in.
    ///
    /// One table on purpose, so a sixth path cannot appear without a line
    /// here saying what bounds it.
    #[cfg(feature = "decode")]
    #[test]
    fn a_payload_cannot_choose_how_much_memory_a_decode_spends() {
        // A declared size no terminal could place, refused before any data
        // is read.
        assert!(
            matches!(
                kitty_payload(b"a=T,f=32,s=65535,v=65535", b"AAAA").decode(),
                Err(DecodeError::TooLarge(_))
            ),
            "a 65535x65535 kitty transmission was not refused"
        );

        // A zlib bomb: four declared bytes, four mebibytes inside. The
        // inflate is bounded by the declared size, so it never expands.
        let bomb = miniz_oxide::deflate::compress_to_vec_zlib(&vec![0u8; 4 << 20], 9);
        assert!(bomb.len() < 64 << 10, "the fixture is meant to be small");
        assert!(
            matches!(
                kitty_payload(b"a=T,f=32,o=z,s=1,v=1", base64(&bomb).as_bytes()).decode(),
                Err(DecodeError::Malformed(_))
            ),
            "a payload inflating past its declared size was not refused"
        );

        // A sixel naming a colour register far past any palette.
        assert!(
            matches!(
                sixel_payload(b"#4000000000;2;100;100;100~").decode(),
                Err(DecodeError::TooLarge(_))
            ),
            "a four-billion colour register was not refused"
        );

        // A sixel repeat count. Twelve bytes of input.
        assert!(
            matches!(
                sixel_payload(b"#0;2;100;100;100!4294967295~").decode(),
                Err(DecodeError::TooLarge(_))
            ),
            "a four-billion repeat was not refused"
        );

        // Raster attributes, which reach the final allocation without the
        // pixel data being touched at all.
        assert!(
            matches!(
                sixel_payload(b"\"1;1;65535;65535#0;2;100;100;100~").decode(),
                Err(DecodeError::TooLarge(_))
            ),
            "a 65535x65535 declared sixel was not refused"
        );
    }

    /// The ceiling must not refuse anything real: a terminal-sized image in
    /// either protocol decodes exactly as before.
    #[cfg(feature = "decode")]
    #[test]
    fn an_ordinary_image_is_untouched_by_the_ceiling() {
        let raw = vec![0x40u8; 64 * 32 * 4];
        let bitmap = kitty_payload(b"a=T,f=32,s=64,v=32", base64(&raw).as_bytes())
            .decode()
            .expect("a 64x32 image still decodes");
        assert_eq!((bitmap.width(), bitmap.height()), (64, 32));
        assert_eq!(bitmap.pixel(63, 31), Some([0x40, 0x40, 0x40, 0x40]));

        let sixel = sixel_payload(b"\"1;1;4;6#0;2;100;0;0~~~~")
            .decode()
            .expect("a small sixel still decodes");
        assert_eq!((sixel.width(), sixel.height()), (4, 6));
    }

    #[cfg(feature = "decode")]
    #[test]
    fn a_compressed_transmission_is_inflated_first() {
        let raw = vec![0x40u8; 4 * 16 * 16];
        let data = base64(&miniz_oxide::deflate::compress_to_vec_zlib(&raw, 6));
        let payload = kitty_payload(b"a=T,f=32,o=z,s=16,v=16", data.as_bytes());
        let bitmap = payload.decode().expect("decodes");
        assert_eq!((bitmap.width(), bitmap.height()), (16, 16));
        assert_eq!(bitmap.pixel(15, 15), Some([0x40, 0x40, 0x40, 0x40]));
    }

    #[cfg(feature = "decode")]
    #[test]
    fn every_refusal_names_its_reason() {
        let png = kitty_payload(b"a=T,f=100,s=1,v=1", b"AAAA");
        assert!(matches!(png.decode(), Err(DecodeError::Unsupported(_))));

        let delete = kitty_payload(b"a=d,i=1", b"");
        assert!(matches!(
            delete.decode(),
            Err(DecodeError::NoImage(GraphicsAction::Delete))
        ));

        let short = kitty_payload(b"a=T,f=32,s=64,v=64", b"AAAA");
        assert!(matches!(short.decode(), Err(DecodeError::Malformed(_))));

        let sizeless = kitty_payload(b"a=T,f=32", b"AAAA");
        assert!(matches!(sizeless.decode(), Err(DecodeError::Malformed(_))));

        let mut builder = GraphicsBuilder::default();
        builder.kitty(b"a=T,f=32,s=2,v=1");
        builder.chunk(64, b"AAAABBBB", false, usize::MAX);
        let dropped = builder.finish().expect("a payload");
        assert_eq!(dropped.decode(), Err(DecodeError::NotCaptured));
    }

    #[cfg(feature = "decode")]
    #[test]
    fn a_sixel_decodes_into_the_pixels_it_paints() {
        // A 4x6 image: register 0 is white, and `~` sets all six rows of the
        // band, so a run of four fills the whole thing.
        let mut builder = GraphicsBuilder::default();
        builder.sixel();
        builder.chunk(40, b"\"1;1;4;6#0;2;100;100;100!4~-", true, usize::MAX);
        let bitmap = builder
            .finish()
            .expect("a payload")
            .decode()
            .expect("decodes");
        assert_eq!((bitmap.width(), bitmap.height()), (4, 6));
        for y in 0..6 {
            for x in 0..4 {
                assert_eq!(bitmap.pixel(x, y), Some([255, 255, 255, 255]), "({x},{y})");
            }
        }
    }

    #[cfg(feature = "decode")]
    #[test]
    fn a_sixel_pixel_nothing_painted_is_transparent_rather_than_black() {
        // `@` sets only the top row of the band; the five below it were
        // never written, and sixel has no alpha to say so with.
        let mut builder = GraphicsBuilder::default();
        builder.sixel();
        builder.chunk(30, b"\"1;1;1;6#0;2;0;100;0@-", true, usize::MAX);
        let bitmap = builder
            .finish()
            .expect("a payload")
            .decode()
            .expect("decodes");
        assert_eq!(bitmap.pixel(0, 0), Some([0, 255, 0, 255]));
        assert_eq!(bitmap.pixel(0, 1), Some([0, 0, 0, 0]));
    }

    #[cfg(feature = "decode")]
    #[test]
    fn sixel_bands_stack_downwards_and_carriage_returns_overprint() {
        // Two bands, and a `$` that goes back to paint the second colour
        // over the first band's second column.
        let mut builder = GraphicsBuilder::default();
        builder.sixel();
        builder.chunk(
            60,
            b"\"1;1;2;12#0;2;100;0;0~~$#1;2;0;0;100?~-#0??-",
            true,
            usize::MAX,
        );
        let bitmap = builder
            .finish()
            .expect("a payload")
            .decode()
            .expect("decodes");
        assert_eq!((bitmap.width(), bitmap.height()), (2, 12));
        assert_eq!(bitmap.pixel(0, 0), Some([255, 0, 0, 255]), "first colour");
        assert_eq!(bitmap.pixel(1, 0), Some([0, 0, 255, 255]), "overprinted");
        assert_eq!(bitmap.pixel(0, 6), Some([0, 0, 0, 0]), "second band");
    }

    #[cfg(feature = "decode")]
    #[test]
    fn a_sixel_without_raster_attributes_takes_its_size_from_its_data() {
        let mut builder = GraphicsBuilder::default();
        builder.sixel();
        builder.chunk(20, b"#0;2;100;100;100!3~-", true, usize::MAX);
        let bitmap = builder
            .finish()
            .expect("a payload")
            .decode()
            .expect("decodes");
        assert_eq!((bitmap.width(), bitmap.height()), (3, 6));
    }

    #[cfg(feature = "decode")]
    #[test]
    fn colours_are_counted_most_common_first() {
        let mut raw = vec![0u8; 0];
        for _ in 0..3 {
            raw.extend_from_slice(&[1, 2, 3, 255]);
        }
        raw.extend_from_slice(&[9, 9, 9, 255]);
        let data = base64(&raw);
        let payload = kitty_payload(b"a=T,f=32,s=4,v=1", data.as_bytes());
        let colours = payload.decode().expect("decodes").colours();
        assert_eq!(colours[0], ([1, 2, 3, 255], 3));
        assert_eq!(colours[1], ([9, 9, 9, 255], 1));
    }

    /// Equal counts come out in the order the colours first appear, so the
    /// answer is a property of the image rather than of a hash seed. Both
    /// orders, so a test that happened to agree by luck is ruled out.
    #[cfg(feature = "decode")]
    #[test]
    fn colours_break_ties_by_first_appearance() {
        let a = [1, 1, 1, 255];
        let b = [2, 2, 2, 255];
        let c = [3, 3, 3, 255];
        let image = |pixels: &[[u8; 4]]| {
            let raw: Vec<u8> = pixels.iter().flatten().copied().collect();
            let data = base64(&raw);
            kitty_payload(
                format!("a=T,f=32,s={},v=1", pixels.len()).as_bytes(),
                data.as_bytes(),
            )
            .decode()
            .expect("decodes")
            .colours()
        };
        assert_eq!(image(&[a, b, b, a, c]), vec![(a, 2), (b, 2), (c, 1)]);
        assert_eq!(image(&[b, a, a, b, c]), vec![(b, 2), (a, 2), (c, 1)]);
        // And the count still wins over appearance.
        assert_eq!(image(&[a, b, b]), vec![(b, 2), (a, 1)]);
    }

    /// A 512x512 image with every pixel a distinct colour — the shape of a
    /// photograph or a screenshot, and the one the issue extrapolated to
    /// seven seconds under the old per-pixel scan. The time is not asserted
    /// (a timing assertion is a flake waiting to happen); what is asserted
    /// is that the answer is complete and in raster order, which the
    /// quadratic version also got right, only slowly.
    #[cfg(feature = "decode")]
    #[test]
    fn colours_on_a_photograph_sized_image_completes() {
        let side = 512u32;
        let pixels = (side * side) as usize;
        let mut raw = Vec::with_capacity(pixels * 4);
        for i in 0..pixels {
            // i < 2^24, so the RGB triple is unique per pixel.
            raw.extend_from_slice(&[(i >> 16) as u8, (i >> 8) as u8, i as u8, 0xff]);
        }
        let data = base64(&raw);
        let bitmap = kitty_payload(
            format!("a=T,f=32,s={side},v={side}").as_bytes(),
            data.as_bytes(),
        )
        .decode()
        .expect("decodes");
        let colours = bitmap.colours();
        assert_eq!(colours.len(), pixels, "every pixel is its own colour");
        assert!(colours.iter().all(|&(_, count)| count == 1));
        // All tied at one, so the order is raster order.
        assert_eq!(colours[0].0, [0, 0, 0, 0xff]);
        assert_eq!(colours[1].0, [0, 0, 1, 0xff]);
        assert_eq!(colours[pixels - 1].0, [3, 0xff, 0xff, 0xff]);
    }

    #[cfg(feature = "decode")]
    #[test]
    fn hls_colours_are_refused_rather_than_converted() {
        let mut builder = GraphicsBuilder::default();
        builder.sixel();
        builder.chunk(30, b"\"1;1;1;6#0;1;120;50;100~-", true, usize::MAX);
        assert!(matches!(
            builder.finish().expect("a payload").decode(),
            Err(DecodeError::Unsupported(_))
        ));
    }

    #[test]
    fn the_debug_rendering_stays_short_enough_for_a_log() {
        let payload = kitty_payload(b"a=T,f=32,o=z,s=954,v=133,i=7,c=106,r=7", &[b'A'; 4096]);
        let rendered = format!("{payload:?}");
        assert!(rendered.len() < 120, "{rendered}");
        assert!(rendered.contains("954x133px"), "{rendered}");
        assert!(rendered.contains("106x7cells"), "{rendered}");
        assert!(!rendered.contains("AAAA"), "the data must not be in it");
    }

    /// The encoder side of what `decode_base64` undoes — tests only.
    #[cfg(feature = "decode")]
    fn base64(data: &[u8]) -> String {
        const ALPHABET: &[u8; 64] =
            b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
        let mut out = String::new();
        for group in data.chunks(3) {
            let mut bits = 0u32;
            for (index, byte) in group.iter().enumerate() {
                bits |= u32::from(*byte) << (16 - 8 * index);
            }
            for index in 0..=group.len() {
                out.push(ALPHABET[(bits >> (18 - 6 * index) & 0x3f) as usize] as char);
            }
            for _ in group.len()..3 {
                out.push('=');
            }
        }
        out
    }
}