tuika 0.4.0

A composable terminal UI toolkit — flexbox layout, overlays, focus, and safe ratatui interoperability.
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
//! Terminal image rendering via the Kitty, iTerm2, and Sixel graphics protocols.
//!
//! A cell in ratatui's buffer carries one grapheme plus a style and nothing
//! else, so a picture has no home there — the same wall [`crate::hyperlink`]
//! (OSC 8), [`crate::clipboard`] (OSC 52), and [`crate::native`] (OSC 9;4) hit.
//! Like them, images are emitted out-of-band as an escape sequence, past the
//! cell buffer. Unlike them, the graphics escape is **not** cursor-neutral — it
//! paints at the cursor — so emission is split from layout:
//!
//! 1. An [`Image`] view reserves a `cols × rows` cell footprint via
//!    [`View::measure`], so the flex solver lays out around it like any leaf.
//! 2. On [`View::render`] it records its absolute painted [`Rect`] plus a
//!    handle to its pixels into a shared [`ImageLayer`] (cheap to clone, cleared
//!    each frame — the ownership shape of [`RectProbe`](crate::probe::RectProbe)),
//!    and paints the reserved cells blank (or the alt-text placeholder when the
//!    terminal can't show the image) so ratatui's diff has stable content there.
//! 3. **After** the frame is painted, the host calls [`ImageLayer::emit`], which
//!    moves the cursor to each image's cell origin and writes its protocol's
//!    escape, wrapped in a cursor save/restore so ratatui's cursor model is
//!    undisturbed.
//!
//! Decoding (PNG/JPEG → RGBA) is intentionally the host's job — it is a heavy
//! dependency, kept out of tuika exactly like syntax highlighting is (see
//! [`mod@crate::highlight`]). tuika owns presentation only: protocol encoding, cell
//! reservation, and the fallback. The host hands in raw RGBA via [`ImageData`].
//!
//! Graphics protocols do not degrade as harmlessly as an unknown OSC — an
//! unsupported terminal may paint the payload as garbage — so this is the first
//! tuika feature to gate on real capability detection ([`ImageSupport::detect`]).
//! See `knowledge/specs/tuika-images.md` for the full design and phased plan.

use std::cell::RefCell;
use std::io::{self, Write};
use std::rc::Rc;
use std::sync::Arc;

use ratatui_core::layout::Rect;
use ratatui_core::style::{Modifier, Style};

use crate::geometry::Size;
use crate::surface::Surface;
use crate::view::{RenderCtx, View};

/// String terminator for an APC sequence: `ESC \`.
const ST: &str = "\x1b\\";

/// Max base64 payload bytes per Kitty transmission chunk, per the protocol.
const CHUNK: usize = 4096;

/// Raw RGBA pixels plus their dimensions — the decoded image a host hands to an
/// [`Image`]. Cheap to clone (the pixel buffer is shared via [`Arc`]), so the
/// same image can back several views or be re-recorded every frame for free.
#[derive(Clone, Debug)]
pub struct ImageData {
    rgba: Arc<[u8]>,
    pixel_width: u32,
    pixel_height: u32,
}

impl ImageData {
    /// Build image data from a `pixel_width × pixel_height` RGBA buffer (4 bytes
    /// per pixel, row-major, no stride padding).
    ///
    /// Returns `None` if the dimensions are zero or `rgba.len()` is not exactly
    /// `pixel_width * pixel_height * 4`, so a malformed buffer can never reach
    /// the encoder.
    pub fn from_rgba(
        pixel_width: u32,
        pixel_height: u32,
        rgba: impl Into<Arc<[u8]>>,
    ) -> Option<Self> {
        let rgba = rgba.into();
        let expected = (pixel_width as usize)
            .checked_mul(pixel_height as usize)?
            .checked_mul(4)?;
        if pixel_width == 0 || pixel_height == 0 || rgba.len() != expected {
            return None;
        }
        Some(Self {
            rgba,
            pixel_width,
            pixel_height,
        })
    }

    /// The image width in pixels.
    pub fn pixel_width(&self) -> u32 {
        self.pixel_width
    }

    /// The image height in pixels.
    pub fn pixel_height(&self) -> u32 {
        self.pixel_height
    }
}

/// Which graphics protocol a terminal is believed to speak.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ImageSupport {
    /// No known graphics protocol — [`Image`] renders its text fallback.
    None,
    /// The Kitty graphics protocol (Kitty, Ghostty, WezTerm, Konsole). Transmits
    /// raw RGBA.
    Kitty,
    /// The iTerm2 inline-image protocol (iTerm2, WezTerm). Transmits an encoded
    /// image file — tuika PNG-encodes the RGBA for it.
    ITerm2,
    /// The Sixel protocol (foot, xterm +sixel, mlterm, contour, …). Transmits a
    /// palette-quantized bitmap. Reliable auto-detection isn't possible from the
    /// environment alone, so hosts on a Sixel terminal usually set this
    /// explicitly rather than relying on [`detect`](Self::detect).
    Sixel,
}

impl ImageSupport {
    /// Probe the environment for graphics support.
    ///
    /// Conservative by design: it reads `TERM`, `TERM_PROGRAM`,
    /// `KITTY_WINDOW_ID`, and the Ghostty resources marker, and returns
    /// [`ImageSupport::None`] when nothing matches, so a terminal that would
    /// paint the payload as garbage gets the text fallback instead. Kitty is
    /// preferred over iTerm2 where a terminal (WezTerm) speaks both, since Kitty
    /// carries raw RGBA and skips the PNG encode. A host that knows better can
    /// override with a literal variant.
    pub fn detect() -> Self {
        Self::detect_from(
            std::env::var("TERM").ok().as_deref(),
            std::env::var("TERM_PROGRAM").ok().as_deref(),
            std::env::var("KITTY_WINDOW_ID").ok().as_deref(),
            std::env::var("GHOSTTY_RESOURCES_DIR").ok().as_deref(),
        )
    }

    /// The pure core of [`detect`](Self::detect), taking the environment
    /// explicitly so the decision is unit-testable without touching the process
    /// environment.
    pub fn detect_from(
        term: Option<&str>,
        term_program: Option<&str>,
        kitty_window_id: Option<&str>,
        ghostty_resources_dir: Option<&str>,
    ) -> Self {
        let program = term_program.map(|p| p.to_ascii_lowercase());
        // Any of these is a positive signal for the Kitty graphics protocol.
        let kitty = kitty_window_id.is_some_and(|s| !s.is_empty())
            || ghostty_resources_dir.is_some_and(|s| !s.is_empty())
            || term.is_some_and(|t| t.contains("kitty"))
            || program
                .as_deref()
                .is_some_and(|p| p == "ghostty" || p == "wezterm");
        if kitty {
            return ImageSupport::Kitty;
        }
        // iTerm2 speaks its own inline-image protocol (TERM_PROGRAM=iTerm.app).
        if program.as_deref().is_some_and(|p| p.contains("iterm")) {
            return ImageSupport::ITerm2;
        }
        // Sixel has no reliable env signal (a DA1 query would be needed), so only
        // the few terminals that advertise themselves in `TERM` are matched here;
        // other Sixel terminals need an explicit `ImageSupport::Sixel`.
        if term.is_some_and(|t| t.contains("foot") || t.contains("mlterm") || t.contains("contour"))
        {
            return ImageSupport::Sixel;
        }
        ImageSupport::None
    }
}

/// One image queued for emission this frame: where it landed, in cells, the
/// pixels to paint there, and which protocol to paint them with.
#[derive(Clone, Debug)]
struct Placement {
    rect: Rect,
    data: ImageData,
    support: ImageSupport,
}

/// A shared collector of the images placed during a frame, and the emitter that
/// paints them after the frame is drawn.
///
/// Cheap to clone (a shared handle), the way [`RectProbe`](crate::probe::RectProbe)
/// is: a host holds one, hands clones to its [`Image`] views via
/// [`Image::in_layer`], then after `terminal.draw()` calls [`emit`](Self::emit)
/// and [`clear`](Self::clear) for the next frame.
#[derive(Clone, Debug, Default)]
pub struct ImageLayer(Rc<RefCell<Vec<Placement>>>);

impl ImageLayer {
    /// Create an empty layer.
    pub fn new() -> Self {
        Self::default()
    }

    /// Record an image at its painted cell rect, to be painted with `support`.
    /// Zero-area rects are dropped — a clipped-away image has nothing to paint.
    fn record(&self, rect: Rect, data: ImageData, support: ImageSupport) {
        if rect.width == 0 || rect.height == 0 {
            return;
        }
        self.0.borrow_mut().push(Placement {
            rect,
            data,
            support,
        });
    }

    /// Drop all recorded placements. Call once per frame, after [`emit`](Self::emit),
    /// so the next frame starts clean.
    pub fn clear(&self) {
        self.0.borrow_mut().clear();
    }

    /// Whether any image was placed this frame.
    pub fn is_empty(&self) -> bool {
        self.0.borrow().is_empty()
    }

    /// Number of images placed this frame.
    pub fn len(&self) -> usize {
        self.0.borrow().len()
    }

    /// Write every recorded image to `out` as its protocol's graphics escape at
    /// its cell origin.
    ///
    /// Call this after `terminal.draw()` has flushed the frame, against the same
    /// sink as the terminal backend. The whole batch is wrapped in a cursor
    /// save/restore (`ESC 7` / `ESC 8`) and each image is positioned with a CUP
    /// (`ESC [ row ; col H`, 1-based) before its escape, so ratatui's cursor
    /// model is left exactly as it was.
    pub fn emit(&self, out: &mut impl Write) -> io::Result<()> {
        let placements = self.0.borrow();
        if placements.is_empty() {
            return Ok(());
        }
        // Save the cursor once, restore once, so nothing between shifts it.
        out.write_all(b"\x1b7")?;
        for p in placements.iter() {
            // CUP is 1-based; the reserved rect is 0-based screen coordinates.
            let (row, col) = (p.rect.y + 1, p.rect.x + 1);
            write!(out, "\x1b[{row};{col}H")?;
            let escape = match p.support {
                ImageSupport::ITerm2 => encode_iterm2(&p.data, p.rect.width, p.rect.height),
                ImageSupport::Sixel => encode_sixel(&p.data, p.rect.width, p.rect.height),
                // None shouldn't record, but Kitty is the safe default encoding.
                _ => encode_kitty(&p.data, p.rect.width, p.rect.height),
            };
            out.write_all(escape.as_bytes())?;
        }
        out.write_all(b"\x1b8")?;
        out.flush()
    }
}

/// A view that displays a decoded image over the cells it reserves.
///
/// It always reserves `cols × rows` cells (bounded by the area it's given) and
/// always paints those cells — blank when the image will cover them, or the alt
/// text when the terminal can't. When [`ImageSupport::Kitty`] and a layer are
/// both set, it additionally records itself into the layer so the host's
/// [`ImageLayer::emit`] paints the picture over the reserved cells.
pub struct Image {
    data: ImageData,
    cols: u16,
    rows: u16,
    alt: String,
    support: ImageSupport,
    layer: Option<ImageLayer>,
}

impl Image {
    /// An image occupying `cols × rows` cells. It renders as a text placeholder
    /// until a graphics [`ImageSupport`] and an [`ImageLayer`] are attached with
    /// [`support`](Self::support) and [`in_layer`](Self::in_layer).
    pub fn new(data: ImageData, cols: u16, rows: u16) -> Self {
        Self {
            data,
            cols,
            rows,
            alt: String::new(),
            support: ImageSupport::None,
            layer: None,
        }
    }

    /// Set the graphics protocol to use (usually [`ImageSupport::detect`]).
    pub fn support(mut self, support: ImageSupport) -> Self {
        self.support = support;
        self
    }

    /// Register this image with a layer so it is emitted after the frame. Without
    /// a layer the view only ever paints its fallback.
    pub fn in_layer(mut self, layer: &ImageLayer) -> Self {
        self.layer = Some(layer.clone());
        self
    }

    /// Text shown (dimmed) when the image can't be painted — a supportless
    /// terminal, or before a layer is attached.
    pub fn alt(mut self, alt: impl Into<String>) -> Self {
        self.alt = alt.into();
        self
    }

    /// Whether this image will be emitted through a graphics protocol (as
    /// opposed to falling back to text).
    fn will_paint(&self) -> bool {
        matches!(
            self.support,
            ImageSupport::Kitty | ImageSupport::ITerm2 | ImageSupport::Sixel
        ) && self.layer.is_some()
    }
}

impl View for Image {
    fn measure(&self, available: Size) -> Size {
        Size::new(self.cols, self.rows).clamp_to(available)
    }

    fn render(&self, area: Rect, surface: &mut Surface, ctx: &RenderCtx) {
        if area.width == 0 || area.height == 0 {
            return;
        }
        if self.will_paint() {
            // The graphics escape will cover these cells after the frame; keep
            // them blank so nothing shows through at the image's edges and the
            // ratatui diff over the region is stable.
            surface.fill(Style::default().bg(ctx.theme.background));
            if let Some(layer) = &self.layer {
                layer.record(area, self.data.clone(), self.support);
            }
        } else {
            self.render_fallback(area, surface, ctx);
        }
    }
}

impl Image {
    /// Paint the alt-text placeholder centered in `area` — what a terminal
    /// without graphics support shows.
    fn render_fallback(&self, area: Rect, surface: &mut Surface, ctx: &RenderCtx) {
        surface.fill(Style::default().bg(ctx.theme.background));
        let label = if self.alt.is_empty() {
            "[image]".to_string()
        } else {
            format!("[image: {}]", self.alt)
        };
        let style = Style::default()
            .fg(ctx.theme.muted)
            .add_modifier(Modifier::ITALIC);
        // Center within the reserved box; truncation is handled by set_string's
        // clip against the surface.
        let width = crate::width::str_cols(&label);
        let x = area.x + area.width.saturating_sub(width) / 2;
        let y = area.y + area.height / 2;
        surface.set_string(x, y, &label, style);
    }
}

/// Encode `data` as a Kitty graphics protocol command that transmits and
/// displays the image scaled into `cols × rows` cells.
///
/// Pure and allocation-only — no I/O — so the wire format is unit-testable, the
/// same as [`crate::hyperlink::osc8`] and [`crate::native::encode`]. The payload
/// is raw RGBA (`f=32`) with its source pixel dimensions (`s`/`v`), displayed at
/// the cursor (`a=T`) across `c`/`r` cells, base64-encoded and split into
/// [`CHUNK`]-sized pieces with the `m` continuation key. `q=2` suppresses the
/// terminal's acknowledgement replies so they can't be read as input.
fn encode_kitty(data: &ImageData, cols: u16, rows: u16) -> String {
    let payload = base64_encode(&data.rgba);
    let chunks: Vec<&str> = split_chunks(&payload, CHUNK);
    let mut out = String::new();
    let last = chunks.len().saturating_sub(1);
    for (i, chunk) in chunks.iter().enumerate() {
        // `m=1` on every chunk but the last signals "more data follows".
        let more = u8::from(i != last);
        out.push_str("\x1b_G");
        if i == 0 {
            // Control keys ride only on the first chunk; continuations carry `m`.
            out.push_str(&format!(
                "f=32,s={},v={},a=T,c={},r={},q=2,m={}",
                data.pixel_width, data.pixel_height, cols, rows, more
            ));
        } else {
            out.push_str(&format!("m={more}"));
        }
        out.push(';');
        out.push_str(chunk);
        out.push_str(ST);
    }
    out
}

/// Split `s` into `size`-byte pieces (the last may be shorter). `s` is base64,
/// which is ASCII, so byte slicing never lands inside a character.
fn split_chunks(s: &str, size: usize) -> Vec<&str> {
    if s.is_empty() {
        return vec![""];
    }
    let mut chunks = Vec::with_capacity(s.len().div_ceil(size));
    let mut i = 0;
    while i < s.len() {
        let end = (i + size).min(s.len());
        chunks.push(&s[i..end]);
        i = end;
    }
    chunks
}

/// Standard base64 (RFC 4648, with `=` padding) — the encoding Kitty expects for
/// the graphics payload. Small and self-contained so tuika keeps its minimal
/// dependency set.
fn base64_encode(bytes: &[u8]) -> String {
    const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
    for group in bytes.chunks(3) {
        let b0 = group[0] as u32;
        let b1 = *group.get(1).unwrap_or(&0) as u32;
        let b2 = *group.get(2).unwrap_or(&0) as u32;
        let n = (b0 << 16) | (b1 << 8) | b2;
        out.push(ALPHABET[(n >> 18) as usize & 0x3f] as char);
        out.push(ALPHABET[(n >> 12) as usize & 0x3f] as char);
        out.push(if group.len() > 1 {
            ALPHABET[(n >> 6) as usize & 0x3f] as char
        } else {
            '='
        });
        out.push(if group.len() > 2 {
            ALPHABET[n as usize & 0x3f] as char
        } else {
            '='
        });
    }
    out
}

/// Encode `data` as an iTerm2 inline-image escape displayed across `cols × rows`
/// cells.
///
/// Pure and allocation-only, like [`encode_kitty`]. iTerm2 wants a full image
/// *file* rather than raw RGBA, so the pixels are PNG-encoded first (see
/// [`png_rgba`]); `width`/`height` are given in cells, `preserveAspectRatio=0`
/// makes the image fill the reserved box, and `inline=1` displays it at the
/// cursor. The sequence is `ESC ] 1337 ; File = <args> : <base64> BEL`.
fn encode_iterm2(data: &ImageData, cols: u16, rows: u16) -> String {
    let png = png_rgba(data.pixel_width, data.pixel_height, &data.rgba);
    let payload = base64_encode(&png);
    format!(
        "\x1b]1337;File=inline=1;width={cols};height={rows};preserveAspectRatio=0;size={}:{payload}\x07",
        png.len()
    )
}

/// Assumed terminal cell pixel size, used only to scale a Sixel image into its
/// reserved `cols × rows` cells: unlike Kitty (`c`/`r`) and iTerm2
/// (`width`/`height`), the Sixel protocol has no cell-based sizing — it paints at
/// the bitmap's pixel size — so tuika resamples to an assumed cell geometry.
const SIXEL_CELL_W: u32 = 10;
const SIXEL_CELL_H: u32 = 20;

/// Encode `data` as a Sixel bitmap scaled to fill `cols × rows` cells.
///
/// Pure and allocation-only, like [`encode_kitty`]. The RGBA is nearest-neighbor
/// resampled to `cols*SIXEL_CELL_W × rows*SIXEL_CELL_H` pixels (Sixel can't scale
/// to cells itself), quantized to a fixed 6×6×6 color cube, and emitted band by
/// band (6 rows each), one color pass per band with run-length encoding. The
/// sequence is `ESC P q "1;1;W;H <palette><data> ESC \`.
fn encode_sixel(data: &ImageData, cols: u16, rows: u16) -> String {
    let tw = (cols as u32 * SIXEL_CELL_W).max(1);
    let th = (rows as u32 * SIXEL_CELL_H).max(1);
    let (sw, sh) = (data.pixel_width.max(1), data.pixel_height.max(1));

    // Nearest-neighbor resample into a target grid of 6×6×6-cube palette indices.
    let mut idx = vec![0u8; (tw * th) as usize];
    for ty in 0..th {
        let sy = ty * sh / th;
        for tx in 0..tw {
            let sx = tx * sw / tw;
            let p = ((sy * sw + sx) * 4) as usize;
            let q = |c: u8| (c as u32 * 5 + 127) / 255; // 0..=5
            idx[(ty * tw + tx) as usize] =
                (q(data.rgba[p]) * 36 + q(data.rgba[p + 1]) * 6 + q(data.rgba[p + 2])) as u8;
        }
    }

    let mut out = String::new();
    out.push_str("\x1bPq"); // DCS, default params
    out.push_str(&format!("\"1;1;{tw};{th}")); // raster: 1:1 aspect, W×H pixels
    // Define the 216-color cube once (channels scaled to Sixel's 0..=100).
    for i in 0u32..216 {
        let (r, g, b) = (i / 36 % 6, i / 6 % 6, i % 6);
        out.push_str(&format!("#{};2;{};{};{}", i, r * 20, g * 20, b * 20));
    }

    let bands = th.div_ceil(6);
    for band in 0..bands {
        let y0 = band * 6;
        // Which palette colors appear anywhere in this 6-row band.
        let mut present = [false; 216];
        for p in 0..6 {
            let y = y0 + p;
            if y >= th {
                break;
            }
            for tx in 0..tw {
                present[idx[(y * tw + tx) as usize] as usize] = true;
            }
        }
        let colors: Vec<usize> = (0..216).filter(|&c| present[c]).collect();
        for (ci, &c) in colors.iter().enumerate() {
            out.push_str(&format!("#{c}"));
            // One sixel char per column: bit p set when row y0+p is this color.
            let (mut run, mut len) = (0u8, 0u32);
            for tx in 0..tw {
                let mut bits = 0u8;
                for p in 0..6 {
                    let y = y0 + p;
                    if y < th && idx[(y * tw + tx) as usize] as usize == c {
                        bits |= 1 << p;
                    }
                }
                if bits == run {
                    len += 1;
                } else {
                    sixel_run(&mut out, run, len);
                    run = bits;
                    len = 1;
                }
            }
            sixel_run(&mut out, run, len);
            // Overlay the next color on the same band (`$`), else advance a band.
            if ci + 1 < colors.len() {
                out.push('$');
            }
        }
        if band + 1 < bands {
            out.push('-');
        }
    }
    out.push_str("\x1b\\");
    out
}

/// Emit a run of `len` copies of sixel value `bits` (0..=63), run-length-encoded
/// with `!` for runs of three or more.
fn sixel_run(out: &mut String, bits: u8, len: u32) {
    if len == 0 {
        return;
    }
    let ch = (0x3f + bits) as char;
    if len >= 3 {
        out.push_str(&format!("!{len}"));
        out.push(ch);
    } else {
        for _ in 0..len {
            out.push(ch);
        }
    }
}

/// Encode `rgba` (`w × h`, 8-bit RGBA) as a PNG, using stored (uncompressed)
/// DEFLATE blocks. Trivial and exact — and tuika stays dependency-free — at the
/// cost of no compression, which is fine for the small images terminals inline.
/// Used by the iTerm2 protocol, which transmits an image file rather than raw
/// pixels.
fn png_rgba(w: u32, h: u32, rgba: &[u8]) -> Vec<u8> {
    let row = (w * 4) as usize;
    let mut raw = Vec::with_capacity(rgba.len() + h as usize);
    for y in 0..h as usize {
        raw.push(0); // filter type 0 (none) per scanline
        raw.extend_from_slice(&rgba[y * row..(y + 1) * row]);
    }

    let mut png = vec![0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a];
    let mut ihdr = Vec::new();
    ihdr.extend_from_slice(&w.to_be_bytes());
    ihdr.extend_from_slice(&h.to_be_bytes());
    ihdr.extend_from_slice(&[8, 6, 0, 0, 0]); // 8-bit, RGBA, deflate, no filter/interlace
    png_chunk(&mut png, b"IHDR", &ihdr);
    png_chunk(&mut png, b"IDAT", &zlib_stored(&raw));
    png_chunk(&mut png, b"IEND", &[]);
    png
}

/// Append a length-tagged, CRC-checked PNG chunk.
fn png_chunk(out: &mut Vec<u8>, tag: &[u8; 4], data: &[u8]) {
    out.extend_from_slice(&(data.len() as u32).to_be_bytes());
    out.extend_from_slice(tag);
    out.extend_from_slice(data);
    let mut crc_in = Vec::with_capacity(4 + data.len());
    crc_in.extend_from_slice(tag);
    crc_in.extend_from_slice(data);
    out.extend_from_slice(&crc32(&crc_in).to_be_bytes());
}

/// Wrap `data` in a zlib stream of DEFLATE stored blocks (BTYPE 00).
fn zlib_stored(data: &[u8]) -> Vec<u8> {
    let mut out = vec![0x78, 0x01]; // zlib header: deflate, 32K window, no preset dict
    let mut i = 0;
    loop {
        let end = (i + 0xffff).min(data.len());
        let block = &data[i..end];
        let last = end == data.len();
        out.push(u8::from(last)); // BFINAL bit, BTYPE=00
        let len = block.len() as u16;
        out.extend_from_slice(&len.to_le_bytes());
        out.extend_from_slice(&(!len).to_le_bytes());
        out.extend_from_slice(block);
        i = end;
        if last {
            break;
        }
    }
    out.extend_from_slice(&adler32(data).to_be_bytes());
    out
}

/// CRC-32 (IEEE polynomial), computed table-free for the PNG chunk checksum.
fn crc32(data: &[u8]) -> u32 {
    let mut crc = 0xffff_ffffu32;
    for &b in data {
        crc ^= b as u32;
        for _ in 0..8 {
            crc = if crc & 1 != 0 {
                (crc >> 1) ^ 0xedb8_8320
            } else {
                crc >> 1
            };
        }
    }
    !crc
}

/// Adler-32 checksum for the zlib stream trailer.
fn adler32(data: &[u8]) -> u32 {
    let (mut a, mut b) = (1u32, 0u32);
    for &x in data {
        a = (a + x as u32) % 65521;
        b = (b + a) % 65521;
    }
    (b << 16) | a
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::style::Theme;
    use crate::testing::render;
    use crate::view::element;

    /// A tiny solid RGBA image: `w × h` pixels, all the same color.
    fn solid(w: u32, h: u32, rgba: [u8; 4]) -> ImageData {
        let buf: Vec<u8> = std::iter::repeat_n(rgba, (w * h) as usize)
            .flatten()
            .collect();
        ImageData::from_rgba(w, h, buf).expect("valid rgba")
    }

    #[test]
    fn from_rgba_validates_length() {
        assert!(ImageData::from_rgba(2, 2, vec![0u8; 16]).is_some());
        // Wrong length, zero dimensions.
        assert!(ImageData::from_rgba(2, 2, vec![0u8; 15]).is_none());
        assert!(ImageData::from_rgba(0, 2, vec![0u8; 0]).is_none());
    }

    #[test]
    fn base64_matches_known_vectors() {
        assert_eq!(base64_encode(b""), "");
        assert_eq!(base64_encode(b"f"), "Zg==");
        assert_eq!(base64_encode(b"fo"), "Zm8=");
        assert_eq!(base64_encode(b"foo"), "Zm9v");
        assert_eq!(base64_encode(b"foob"), "Zm9vYg==");
        assert_eq!(base64_encode(b"foobar"), "Zm9vYmFy");
    }

    #[test]
    fn encode_kitty_single_chunk_shape() {
        let img = solid(1, 1, [1, 2, 3, 4]);
        let out = encode_kitty(&img, 4, 2);
        // APC open + control keys with pixel + cell dims, response suppression,
        // single-chunk (m=0), then payload and ST.
        assert!(out.starts_with("\x1b_Gf=32,s=1,v=1,a=T,c=4,r=2,q=2,m=0;"));
        assert!(out.ends_with("\x1b\\"));
        // One RGBA pixel [1,2,3,4] base64-encodes to "AQIDBA==".
        assert!(out.contains(";AQIDBA==\x1b\\"));
        // Exactly one APC command.
        assert_eq!(out.matches("\x1b_G").count(), 1);
    }

    #[test]
    fn encode_kitty_chunks_large_payloads() {
        // Enough pixels that the base64 payload exceeds one CHUNK and must split.
        let img = solid(64, 64, [9, 9, 9, 9]);
        let out = encode_kitty(&img, 10, 5);
        let commands = out.matches("\x1b_G").count();
        assert!(commands > 1, "large image should span multiple chunks");
        // First chunk carries the control keys and m=1 (more follows).
        assert!(out.starts_with("\x1b_Gf=32,s=64,v=64,a=T,c=10,r=5,q=2,m=1;"));
        // Continuation chunks carry only the m key.
        assert!(out.contains("\x1b_Gm=1;"));
        // The final chunk closes with m=0.
        assert!(out.contains("\x1b_Gm=0;"));
        // Every command is ST-terminated.
        assert_eq!(out.matches("\x1b\\").count(), commands);
    }

    #[test]
    fn detect_recognizes_kitty_signals() {
        let kitty = ImageSupport::Kitty;
        let none = ImageSupport::None;
        // Positive signals.
        assert_eq!(
            ImageSupport::detect_from(Some("xterm-kitty"), None, None, None),
            kitty
        );
        assert_eq!(
            ImageSupport::detect_from(Some("xterm-256color"), None, Some("1"), None),
            kitty
        );
        assert_eq!(
            ImageSupport::detect_from(None, Some("ghostty"), None, None),
            kitty
        );
        assert_eq!(
            ImageSupport::detect_from(None, Some("WezTerm"), None, None),
            kitty
        );
        assert_eq!(
            ImageSupport::detect_from(None, None, None, Some("/x")),
            kitty
        );
        // Nothing matches, and empty markers don't count.
        assert_eq!(
            ImageSupport::detect_from(Some("xterm-256color"), Some("Apple_Terminal"), None, None),
            none
        );
        assert_eq!(
            ImageSupport::detect_from(None, None, Some(""), Some("")),
            none
        );
    }

    #[test]
    fn image_reserves_its_cell_footprint() {
        let img = Image::new(solid(2, 2, [0, 0, 0, 255]), 6, 3);
        assert_eq!(img.measure(Size::new(80, 24)), Size::new(6, 3));
        // Clamped to the available area.
        assert_eq!(img.measure(Size::new(4, 2)), Size::new(4, 2));
    }

    #[test]
    fn supported_image_records_a_placement_and_leaves_cells_blank() {
        let theme = Theme::default();
        let layer = ImageLayer::new();
        let view = element(
            Image::new(solid(2, 2, [0, 0, 0, 255]), 4, 2)
                .support(ImageSupport::Kitty)
                .in_layer(&layer)
                .alt("cat"),
        );
        let buf = render(&view, 4, 2, &theme);
        // The reserved cells are blank (the image will cover them post-frame),
        // so no alt text leaks into the buffer.
        let text: String = (0..buf.area.width).map(|x| buf[(x, 0)].symbol()).collect();
        assert!(
            !text.contains("cat"),
            "supported image must not paint alt text"
        );
        assert_eq!(layer.len(), 1, "a placement was recorded");
        assert!(!layer.is_empty());
    }

    #[test]
    fn unsupported_image_paints_alt_text_and_records_nothing() {
        let theme = Theme::default();
        let layer = ImageLayer::new();
        // Support::None → fallback, even with a layer attached.
        let view = element(
            Image::new(solid(2, 2, [0, 0, 0, 255]), 20, 3)
                .in_layer(&layer)
                .alt("cat"),
        );
        let buf = render(&view, 20, 3, &theme);
        let mut whole = String::new();
        for y in 0..buf.area.height {
            for x in 0..buf.area.width {
                whole.push_str(buf[(x, y)].symbol());
            }
        }
        assert!(
            whole.contains("[image: cat]"),
            "fallback should show alt text"
        );
        assert!(layer.is_empty(), "fallback records no placement");
    }

    #[test]
    fn emit_positions_each_image_and_brackets_with_cursor_save_restore() {
        let layer = ImageLayer::new();
        let k = ImageSupport::Kitty;
        layer.record(Rect::new(2, 1, 4, 2), solid(1, 1, [1, 2, 3, 4]), k);
        layer.record(Rect::new(0, 5, 3, 3), solid(1, 1, [5, 6, 7, 8]), k);
        let mut out: Vec<u8> = Vec::new();
        layer.emit(&mut out).expect("emit");
        let s = String::from_utf8(out).expect("utf8");
        // Bracketed by a single save / restore.
        assert!(s.starts_with("\x1b7"));
        assert!(s.ends_with("\x1b8"));
        // CUP is 1-based: rect (2,1) → row 2, col 3; rect (0,5) → row 6, col 1.
        assert!(s.contains("\x1b[2;3H\x1b_G"));
        assert!(s.contains("\x1b[6;1H\x1b_G"));
        assert_eq!(s.matches("\x1b_G").count(), 2, "one command per image");
    }

    #[test]
    fn emit_dispatches_the_recorded_protocol() {
        let layer = ImageLayer::new();
        layer.record(
            Rect::new(0, 0, 4, 2),
            solid(1, 1, [1, 2, 3, 4]),
            ImageSupport::Kitty,
        );
        layer.record(
            Rect::new(0, 3, 4, 2),
            solid(1, 1, [5, 6, 7, 8]),
            ImageSupport::ITerm2,
        );
        let mut out: Vec<u8> = Vec::new();
        layer.emit(&mut out).expect("emit");
        let s = String::from_utf8(out).expect("utf8");
        // Each image is emitted with its own protocol's escape.
        assert_eq!(s.matches("\x1b_G").count(), 1, "one Kitty command");
        assert_eq!(
            s.matches("\x1b]1337;File=").count(),
            1,
            "one iTerm2 command"
        );
    }

    #[test]
    fn emit_is_a_noop_when_empty() {
        let layer = ImageLayer::new();
        let mut out: Vec<u8> = Vec::new();
        layer.emit(&mut out).expect("emit");
        assert!(
            out.is_empty(),
            "no images → no bytes, no stray cursor moves"
        );
    }

    #[test]
    fn clear_resets_between_frames() {
        let layer = ImageLayer::new();
        layer.record(
            Rect::new(0, 0, 2, 2),
            solid(1, 1, [0, 0, 0, 0]),
            ImageSupport::Kitty,
        );
        assert_eq!(layer.len(), 1);
        layer.clear();
        assert!(layer.is_empty());
    }

    #[test]
    fn zero_area_placements_are_dropped() {
        let layer = ImageLayer::new();
        let k = ImageSupport::Kitty;
        layer.record(Rect::new(0, 0, 0, 3), solid(1, 1, [0, 0, 0, 0]), k);
        layer.record(Rect::new(0, 0, 3, 0), solid(1, 1, [0, 0, 0, 0]), k);
        assert!(
            layer.is_empty(),
            "clipped-away images have nothing to paint"
        );
    }

    #[test]
    fn encode_iterm2_wraps_a_png_file() {
        let img = solid(2, 2, [10, 20, 30, 255]);
        let out = encode_iterm2(&img, 8, 4);
        // iTerm2 File sequence with cell dims and a byte size, BEL-terminated.
        assert!(
            out.starts_with("\x1b]1337;File=inline=1;width=8;height=4;preserveAspectRatio=0;size=")
        );
        assert!(out.ends_with('\x07'));
        // The payload after the colon base64-decodes to a PNG (signature bytes).
        let payload = out
            .trim_end_matches('\x07')
            .rsplit(':')
            .next()
            .expect("payload");
        let decoded = b64_decode(payload);
        assert_eq!(
            &decoded[..8],
            &[0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a]
        );
        // The declared size matches the actual PNG length.
        let size: usize = out
            .split("size=")
            .nth(1)
            .and_then(|s| s.split(':').next())
            .and_then(|n| n.parse().ok())
            .expect("size field");
        assert_eq!(size, decoded.len());
    }

    #[test]
    fn png_rgba_is_well_formed() {
        let img = solid(3, 2, [1, 2, 3, 4]);
        let png = png_rgba(img.pixel_width, img.pixel_height, &img.rgba);
        assert_eq!(&png[..8], &[0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a]);
        // IHDR carries the dimensions; IDAT and IEND are present.
        let s = String::from_utf8_lossy(&png);
        assert!(s.contains("IHDR") && s.contains("IDAT") && s.contains("IEND"));
    }

    #[test]
    fn encode_sixel_has_dcs_frame_palette_and_data() {
        let img = solid(2, 2, [255, 0, 0, 255]); // pure red
        let out = encode_sixel(&img, 1, 1);
        // DCS intro + `q`, raster attributes sized to cols*10 × rows*20 pixels.
        assert!(
            out.starts_with("\x1bPq\"1;1;10;20"),
            "intro/raster: {:?}",
            &out[..24]
        );
        assert!(out.ends_with("\x1b\\"), "ST terminated");
        // Pure red quantizes to cube index r=5,g=0,b=0 → 180, defined as RGB 100;0;0.
        assert!(out.contains("#180;2;100;0;0"), "red register defined");
        // The band data selects that register and run-length-encodes a full column
        // (all six rows set → value 63 → '~').
        assert!(out.contains("#180"), "red register selected in data");
        assert!(
            out.contains("!"),
            "run-length encoding used for the solid fill"
        );
        assert!(
            out.contains('~'),
            "a fully-set sixel column (0x3f+63) present"
        );
    }

    #[test]
    fn encode_sixel_bytes_stay_in_range() {
        // Every sixel data byte must be printable in the sixel range or a control
        // (#, !, $, -, digits, ;, ", ESC, P, q, backslash). Assert no stray bytes.
        let img = solid(3, 2, [0, 128, 255, 255]);
        let out = encode_sixel(&img, 2, 1);
        for b in out.bytes() {
            let ok = b == 0x1b
                || b == b'P'
                || b == b'q'
                || b == b'\\'
                || b == b'"'
                || b == b'#'
                || b == b'!'
                || b == b'$'
                || b == b'-'
                || b == b';'
                || b.is_ascii_digit()
                || (0x3f..=0x7e).contains(&b);
            assert!(ok, "unexpected sixel byte {b:#x}");
        }
    }

    #[test]
    fn detect_recognizes_sixel_terminals() {
        assert_eq!(
            ImageSupport::detect_from(Some("foot"), None, None, None),
            ImageSupport::Sixel
        );
        assert_eq!(
            ImageSupport::detect_from(Some("xterm-mlterm"), None, None, None),
            ImageSupport::Sixel
        );
    }

    #[test]
    fn emit_dispatches_sixel() {
        let layer = ImageLayer::new();
        layer.record(
            Rect::new(0, 0, 2, 1),
            solid(1, 1, [1, 2, 3, 255]),
            ImageSupport::Sixel,
        );
        let mut out: Vec<u8> = Vec::new();
        layer.emit(&mut out).expect("emit");
        let s = String::from_utf8(out).expect("utf8");
        assert!(s.contains("\x1bPq"), "sixel DCS emitted: {s:?}");
    }

    #[test]
    fn detect_recognizes_iterm2_and_prefers_kitty() {
        // iTerm2 advertises itself via TERM_PROGRAM.
        assert_eq!(
            ImageSupport::detect_from(Some("xterm-256color"), Some("iTerm.app"), None, None),
            ImageSupport::ITerm2
        );
        // WezTerm speaks both; Kitty wins (raw RGBA, no PNG encode).
        assert_eq!(
            ImageSupport::detect_from(None, Some("WezTerm"), None, None),
            ImageSupport::Kitty
        );
    }

    /// Minimal standard-base64 decoder for the iTerm2 round-trip test.
    fn b64_decode(s: &str) -> Vec<u8> {
        fn val(c: u8) -> Option<u32> {
            match c {
                b'A'..=b'Z' => Some((c - b'A') as u32),
                b'a'..=b'z' => Some((c - b'a' + 26) as u32),
                b'0'..=b'9' => Some((c - b'0' + 52) as u32),
                b'+' => Some(62),
                b'/' => Some(63),
                _ => None,
            }
        }
        let mut acc = 0u32;
        let mut bits = 0;
        let mut out = Vec::new();
        for &c in s.as_bytes() {
            let Some(v) = val(c) else { continue }; // skip '=' padding
            acc = (acc << 6) | v;
            bits += 6;
            if bits >= 8 {
                bits -= 8;
                out.push((acc >> bits) as u8);
            }
        }
        out
    }
}