Skip to main content

katui_present/surface/
patched.rs

1//! The patched kitty strategy: one whole transmit, then per-frame
2//! retransmits of only the tiles whose pixels changed, each under a
3//! stable tile image id whose placement it replaces.
4
5use crate::Sink;
6use std::collections::HashMap;
7use std::io::{self, Write as _};
8
9use katui_proto::kitty::{
10    Delete, IdSpace, ImageId as KittyImage, Place, PlacementId as KittyPlacement,
11};
12use katui_proto::placeholder::placeholder_row;
13use katui_proto::probe::CellPixels;
14use katui_scene::cell::Position;
15use katui_scene::placement::CellRect;
16use katui_scene::surface::{PixelRect, Surface, diff_tiles};
17
18use crate::anchor::Anchor;
19
20use super::{Stash, damage_is_dense, transmit_pixels, write_whole_image};
21use crate::cells::move_cursor;
22use crate::kitty::crop_rect;
23
24/// The patched kitty surface presenter: transmits the whole surface once,
25/// then per frame retransmits only the tiles whose pixels changed, each
26/// as its own small image under a stable tile id, placed over the base.
27/// The kitty protocol has no in-place pixel update (retransmitting an id
28/// replaces the image and its placements), so a tile id is simply
29/// retransmitted and its placement replaced without flicker. A frame
30/// with more damaged tiles than the patch budget, a resize, or anything
31/// that loses the base image falls back to one whole retransmit.
32/// An unchanged frame writes nothing.
33///
34/// The default tile side is `cell.width * cell.height` pixels, a
35/// multiple of both cell axes, so every tile maps to whole cells and
36/// patch edges never tear.
37#[derive(Debug)]
38pub struct PatchedKitty {
39    base: u32,
40    tile_side: u32,
41    budget: usize,
42    prev: Option<Surface>,
43    base_shown: Option<KittyImage>,
44    tile_generations: HashMap<u32, bool>,
45    grid: Grid,
46    cell: CellPixels,
47    stash: Option<Box<dyn Stash>>,
48    repaint: bool,
49}
50
51/// Where tiles go under a multiplexer: nowhere special outside one, on a
52/// placeholder anchor in kitty, or each under its own placeholder text.
53#[derive(Debug)]
54enum Grid {
55    Plain,
56    Anchored(Anchor),
57    Placeholders,
58}
59
60impl PatchedKitty {
61    /// A presenter for surfaces drawn at `cell` pixel resolution, handing
62    /// out image ids from `base` upward, tiling at the cell-derived side
63    /// with the sprite-friendly budget of 64 tiles.
64    #[must_use]
65    pub fn new(base: u32, cell: CellPixels) -> Self {
66        Self::with_tiles(
67            base,
68            cell,
69            u32::from(cell.width) * u32::from(cell.height),
70            64,
71        )
72    }
73
74    /// A presenter with an explicit `tile_side` in surface pixels and
75    /// `budget`, the damaged-tile count past which one whole retransmit
76    /// wins. Fine-grained surfaces want small tiles and a high budget;
77    /// the tile's cell span always follows the surface-to-area scale.
78    #[must_use]
79    pub fn with_tiles(base: u32, cell: CellPixels, tile_side: u32, budget: usize) -> Self {
80        Self {
81            base,
82            tile_side: tile_side.max(1),
83            budget,
84            prev: None,
85            base_shown: None,
86            tile_generations: HashMap::new(),
87            grid: Grid::Plain,
88            cell,
89            stash: None,
90            repaint: false,
91        }
92    }
93
94    /// Send pixels through `stash`, for a terminal on this machine that
95    /// reads them from there.
96    #[must_use]
97    pub fn with_stash(mut self, stash: Box<dyn Stash>) -> Self {
98        self.stash = Some(stash);
99        self
100    }
101
102    /// Draw placeholder tiles for cells of `cell` pixels from now on, after
103    /// a font zoom changed them.
104    pub fn set_cell(&mut self, cell: CellPixels) {
105        self.cell = cell;
106    }
107
108    /// Send every pixel again on the next frame, for when the terminal
109    /// may have lost what it was showing.
110    pub fn repaint(&mut self) {
111        self.repaint = true;
112    }
113
114    /// Free every image this presenter sent and repaint on the next frame.
115    pub fn free<W: Sink>(&mut self, out: &mut W) -> io::Result<()> {
116        let mut bytes = Vec::new();
117        self.free_tiles(&mut bytes)?;
118        for image in [self.base, self.base + 1] {
119            bytes.write_all(&Delete::Free(KittyImage(image)).encode())?;
120        }
121        self.base_shown = None;
122        self.repaint = true;
123        out.write_all(&bytes)
124    }
125
126    /// Send every frame as small tiles for a multiplexer, which drops
127    /// uploads bigger than it buffers and hides placeholder text with its
128    /// pane. With `relative_placements` every tile sits on one placeholder
129    /// anchor and stretches to its cells; without, each tile shows through
130    /// placeholder text of its own, which keeps its aspect and so needs
131    /// the true cell size.
132    #[must_use]
133    pub fn for_multiplexer(mut self, space: IdSpace, relative_placements: bool) -> Self {
134        self.base = space.image(self.base).0;
135        self.grid = if relative_placements {
136            Grid::Anchored(Anchor::new(space))
137        } else {
138            Grid::Placeholders
139        };
140        self
141    }
142
143    /// Write one frame into `area` cells and return the bytes written.
144    pub fn render_frame<W: Sink>(
145        &mut self,
146        out: &mut W,
147        surface: &Surface,
148        area: CellRect,
149    ) -> io::Result<usize> {
150        let resized = self.prev.as_ref().is_none_or(|prev| {
151            prev.width() != surface.width() || prev.height() != surface.height()
152        });
153        let repaint = std::mem::take(&mut self.repaint);
154        if !matches!(self.grid, Grid::Plain) {
155            if resized && matches!(self.grid, Grid::Placeholders) {
156                self.fit_tiles_to_cells(surface, area);
157            }
158            return self.render_tiles(out, surface, area, resized, repaint);
159        }
160        let fresh_start = resized || repaint;
161        let damage = match self.prev.as_ref() {
162            Some(prev) if !fresh_start => diff_tiles(prev, surface, self.tile_side),
163            _ => Vec::new(),
164        };
165        let dense = damage_is_dense(surface, self.tile_side, damage.len());
166        let patching = !fresh_start && !dense && damage.len() <= self.budget;
167
168        let mut bytes = Vec::new();
169        if !patching {
170            self.full_frame(&mut bytes, surface, area)?;
171        } else if damage.is_empty() {
172            self.prev = Some(surface.clone());
173            return Ok(0);
174        } else {
175            self.patch_all(&mut bytes, surface, &damage, area)?;
176        }
177        self.prev = Some(surface.clone());
178        let written = bytes.len();
179        out.write_all(&bytes)?;
180        Ok(written)
181    }
182
183    /// Make the tile side a whole number of cells again when a resize or a
184    /// font zoom changed the cell. A placeholder tile covers whole cells,
185    /// so a tile that cut a cell in two would leave cells uncovered.
186    fn fit_tiles_to_cells(&mut self, surface: &Surface, area: CellRect) {
187        let width = surface.width().checked_div(u32::from(area.columns));
188        let height = surface.height().checked_div(u32::from(area.rows));
189        if let (Some(width), Some(height)) = (width, height)
190            && width > 0
191            && height > 0
192            && width * u32::from(area.columns) == surface.width()
193            && height * u32::from(area.rows) == surface.height()
194            && (!self.tile_side.is_multiple_of(width) || !self.tile_side.is_multiple_of(height))
195        {
196            let whole = least_common_multiple(width, height);
197            self.tile_side = whole * SMALLEST_TILE.div_ceil(whole);
198        }
199    }
200
201    /// Every damaged rectangle as one synchronized update.
202    fn patch_all(
203        &mut self,
204        bytes: &mut Vec<u8>,
205        surface: &Surface,
206        damage: &[PixelRect],
207        area: CellRect,
208    ) -> io::Result<()> {
209        bytes.write_all(b"\x1b[?2026h")?;
210        let mut shows = Vec::new();
211        for rect in damage {
212            self.patch(bytes, &mut shows, surface, *rect, area)?;
213        }
214        bytes.append(&mut shows);
215        bytes.write_all(b"\x1b[?2026l")
216    }
217
218    /// A repaint keeps the old tiles up until each one is replaced. Every
219    /// upload goes out before any tile shows, because a multiplexer gives
220    /// us no synchronized update: the new frame then appears at once
221    /// instead of in strips while the uploads trickle through.
222    fn render_tiles<W: Sink>(
223        &mut self,
224        out: &mut W,
225        surface: &Surface,
226        area: CellRect,
227        resized: bool,
228        repaint: bool,
229    ) -> io::Result<usize> {
230        let blank = Surface::new(surface.width(), surface.height());
231        let before = self
232            .prev
233            .as_ref()
234            .filter(|_| !resized && !repaint)
235            .unwrap_or(&blank);
236        let damage = diff_tiles(before, surface, self.tile_side);
237        let mut bytes = Vec::new();
238        if resized {
239            self.free_tiles(&mut bytes)?;
240        }
241        if !damage.is_empty()
242            && let Grid::Anchored(anchor) = &mut self.grid
243        {
244            anchor.write(&mut bytes)?;
245        }
246        let mut shows = Vec::new();
247        for rect in &damage {
248            self.patch(&mut bytes, &mut shows, surface, *rect, area)?;
249        }
250        bytes.append(&mut shows);
251        self.prev = Some(surface.clone());
252        out.write_all(&bytes)?;
253        Ok(bytes.len())
254    }
255
256    /// Ghostty's range delete frees every image, the base included, so we
257    /// free the shown tiles one by one.
258    fn free_tiles(&mut self, bytes: &mut Vec<u8>) -> io::Result<()> {
259        for (index, generation) in std::mem::take(&mut self.tile_generations) {
260            bytes.write_all(&Delete::Free(self.tile_image(index, generation)).encode())?;
261        }
262        Ok(())
263    }
264
265    /// The whole surface under the base id not on screen, so the old
266    /// image stays visible until the new one is placed: multiplexers
267    /// drop synchronized updates, and retransmitting a visible id
268    /// removes its placement for a moment.
269    fn full_frame(
270        &mut self,
271        bytes: &mut Vec<u8>,
272        surface: &Surface,
273        area: CellRect,
274    ) -> io::Result<()> {
275        let image = if self.base_shown == Some(KittyImage(self.base)) {
276            KittyImage(self.base + 1)
277        } else {
278            KittyImage(self.base)
279        };
280        bytes.write_all(b"\x1b[?2026h")?;
281        write_whole_image(bytes, image, surface, area, self.stash.as_deref_mut())?;
282        // old tiles sit above the base and would hide the new pixels
283        self.free_tiles(bytes)?;
284        if let Some(shown) = self.base_shown.replace(image) {
285            bytes.write_all(&Delete::Free(shown).encode())?;
286        }
287        bytes.write_all(b"\x1b[?2026l")?;
288        Ok(())
289    }
290
291    fn tile_index(&self, x: u32, y: u32) -> u32 {
292        x / self.tile_side + (y / self.tile_side) * 4096
293    }
294
295    fn tile_image(&self, index: u32, second_generation: bool) -> KittyImage {
296        KittyImage(self.base + 2 + index * 2 + u32::from(second_generation))
297    }
298
299    /// One damaged tile as its own small image at the tile's cell
300    /// rectangle: its upload into `uploads`, and into `reveal` what puts
301    /// it on screen and frees the image it replaces. Each tile alternates
302    /// between two ids so its previous pixels stay visible until the new
303    /// ones are placed.
304    fn patch(
305        &mut self,
306        uploads: &mut Vec<u8>,
307        reveal: &mut Vec<u8>,
308        surface: &Surface,
309        rect: PixelRect,
310        area: CellRect,
311    ) -> io::Result<()> {
312        // the tile's cell span comes from the surface-to-area scale, not
313        // the terminal's cell pixels: the caller's surface may run at any
314        // resolution and the base image already proved the scale
315        let columns = u16::try_from(rect.width * u32::from(area.columns) / surface.width())
316            .unwrap_or(u16::MAX);
317        let rows = u16::try_from(rect.height * u32::from(area.rows) / surface.height())
318            .unwrap_or(u16::MAX);
319        let origin_x = area.x.saturating_add(
320            u16::try_from(rect.x * u32::from(area.columns) / surface.width()).unwrap_or(u16::MAX),
321        );
322        let origin_y = area.y.saturating_add(
323            u16::try_from(rect.y * u32::from(area.rows) / surface.height()).unwrap_or(u16::MAX),
324        );
325        let index = self.tile_index(rect.x, rect.y);
326        let shown = self.tile_generations.get(&index).copied();
327        let generation = shown.is_some_and(|generation| !generation);
328        let image = self.tile_image(index, generation);
329        let origin = Position {
330            x: origin_x,
331            y: origin_y,
332        };
333        let cells = (columns, rows);
334        if matches!(self.grid, Grid::Placeholders) {
335            upload_placeholder_tile(uploads, image, surface, rect, cells, self.cell)?;
336            show_placeholder_tile(reveal, image, origin, cells)?;
337        } else {
338            let padded = with_apron(rect, surface);
339            transmit_pixels(
340                uploads,
341                image,
342                &tile_pixels(surface, padded),
343                (padded.width, padded.height),
344                self.stash.as_deref_mut(),
345            )?;
346            self.place_tile(reveal, image, rect, padded, origin, cells)?;
347        }
348        if let Some(previous) = shown {
349            reveal.write_all(&Delete::Free(self.tile_image(index, previous)).encode())?;
350        }
351        self.tile_generations.insert(index, generation);
352        Ok(())
353    }
354
355    /// A tile placed over the base at its cell rectangle, cropped out of
356    /// the `padded` copy with an apron around it.
357    fn place_tile(
358        &self,
359        bytes: &mut Vec<u8>,
360        image: KittyImage,
361        rect: PixelRect,
362        padded: PixelRect,
363        origin: Position,
364        cells: (u16, u16),
365    ) -> io::Result<()> {
366        let (columns, rows) = cells;
367        let index = self.tile_index(rect.x, rect.y);
368        let mut place = Place::new(image);
369        place.columns = u32::from(columns);
370        place.rows = u32::from(rows);
371        place.placement = KittyPlacement(2 + index);
372        place.crop = Some(crop_rect(PixelRect {
373            x: rect.x - padded.x,
374            y: rect.y - padded.y,
375            width: rect.width,
376            height: rect.height,
377        }));
378        if let Grid::Anchored(anchor) = &self.grid {
379            place.parent = Some(anchor.offset_to(origin));
380        } else {
381            move_cursor(bytes, origin)?;
382        }
383        bytes.write_all(&place.encode())
384    }
385}
386
387/// The smallest tile side in pixels we refit to, so a whole frame stays a
388/// few hundred tiles.
389const SMALLEST_TILE: u32 = 64;
390
391fn least_common_multiple(first: u32, second: u32) -> u32 {
392    let (mut a, mut b) = (first, second);
393    while b != 0 {
394        (a, b) = (b, a % b);
395    }
396    first / a.max(1) * second
397}
398
399/// A terminal fits a placeholder image into its cells keeping its aspect,
400/// so we stretch the tile's height to the aspect of its cells and keep its
401/// width, which keeps a game's reduced resolution.
402fn upload_placeholder_tile(
403    bytes: &mut Vec<u8>,
404    image: KittyImage,
405    surface: &Surface,
406    rect: PixelRect,
407    (columns, rows): (u16, u16),
408    cell: CellPixels,
409) -> io::Result<()> {
410    let cells_wide = (u32::from(columns) * u32::from(cell.width)).max(1);
411    let cells_high = u32::from(rows) * u32::from(cell.height);
412    let width = rect.width.max(1);
413    let height = (u64::from(width) * u64::from(cells_high) / u64::from(cells_wide)).max(1);
414    let height = u32::try_from(height).unwrap_or(rect.height);
415    let pixels = resample(
416        &tile_pixels(surface, rect),
417        (rect.width, rect.height),
418        (width, height),
419    );
420    transmit_pixels(bytes, image, &pixels, (width, height), None)
421}
422
423/// A virtual placement of the tile's cell size, and the placeholder text
424/// that shows it written over its cells.
425fn show_placeholder_tile(
426    bytes: &mut Vec<u8>,
427    image: KittyImage,
428    origin: Position,
429    (columns, rows): (u16, u16),
430) -> io::Result<()> {
431    let mut place = Place::new(image);
432    place.columns = u32::from(columns);
433    place.rows = u32::from(rows);
434    place.virtual_placement = true;
435    bytes.write_all(&place.encode())?;
436    for row in 0..rows {
437        if let Some(text) = placeholder_row(image, u32::from(row), u32::from(columns)) {
438            move_cursor(
439                bytes,
440                Position {
441                    x: origin.x,
442                    y: origin.y.saturating_add(row),
443                },
444            )?;
445            bytes.write_all(text.as_bytes())?;
446        }
447    }
448    Ok(())
449}
450
451/// `pixels` of `from` size scaled to `to` by nearest neighbour, or as they
452/// are when the sizes match.
453fn resample(pixels: &[u8], from: (u32, u32), to: (u32, u32)) -> Vec<u8> {
454    if from == to || from.0 == 0 || from.1 == 0 {
455        return pixels.to_vec();
456    }
457    let mut scaled = Vec::with_capacity((to.0 * to.1 * 4) as usize);
458    for y in 0..to.1 {
459        let source_row = (y * from.1 / to.1) * from.0;
460        for x in 0..to.0 {
461            let start = ((source_row + x * from.0 / to.0) * 4) as usize;
462            scaled.extend_from_slice(pixels.get(start..start + 4).unwrap_or(&[0; 4]));
463        }
464    }
465    scaled
466}
467
468/// `rect` grown by one pixel on every side the surface has room for. A
469/// terminal filters each image on its own, so we send a tile with its
470/// neighbours' edge pixels and crop them away, which blends tile edges the
471/// way one whole image would.
472fn with_apron(rect: PixelRect, surface: &Surface) -> PixelRect {
473    let left = rect.x.saturating_sub(1);
474    let top = rect.y.saturating_sub(1);
475    let right = (rect.x + rect.width + 1).min(surface.width());
476    let bottom = (rect.y + rect.height + 1).min(surface.height());
477    PixelRect {
478        x: left,
479        y: top,
480        width: right - left,
481        height: bottom - top,
482    }
483}
484
485/// The tile's RGBA rows out of the surface, row-major, tile width per
486/// row: exactly the payload a tile transmit declares.
487pub(super) fn tile_pixels(surface: &Surface, rect: PixelRect) -> Vec<u8> {
488    let row_bytes = (surface.width() * 4) as usize;
489    let mut tile = Vec::with_capacity((rect.width * rect.height * 4) as usize);
490    for (row_index, row) in surface.pixels().chunks(row_bytes).enumerate() {
491        if (row_index as u32) < rect.y || (row_index as u32) >= rect.y + rect.height {
492            continue;
493        }
494        let start = (rect.x * 4) as usize;
495        let end = start + (rect.width * 4) as usize;
496        if let Some(slice) = row.get(start..end) {
497            tile.extend_from_slice(slice);
498        }
499    }
500    tile
501}
502
503#[cfg(test)]
504mod tests {
505    use super::PatchedKitty;
506
507    fn plain_surface(width: u32, height: u32) -> Surface {
508        crate::surface::test_support::solid(width, height, Rgba::solid(10, 10, 30))
509    }
510    use katui_proto::probe::CellPixels;
511    use katui_scene::placement::CellRect;
512    use katui_scene::surface::{Rgba, Surface};
513
514    // 8x8 px tiles with a 2x4 cell: 2*4=8, a multiple of both axes
515    fn cell() -> CellPixels {
516        CellPixels {
517            width: 2,
518            height: 4,
519        }
520    }
521
522    #[test]
523    fn the_first_frame_transmits_the_whole_surface() {
524        let mut presenter = PatchedKitty::new(90, cell());
525        let mut out = Vec::new();
526        presenter
527            .render_frame(
528                &mut out,
529                &plain_surface(64, 64),
530                crate::surface::test_support::area(),
531            )
532            .expect("writing to a Vec cannot fail");
533        let text = String::from_utf8_lossy(&out);
534        assert!(text.contains("a=t"), "the whole image travels");
535        assert!(text.contains("o=z"), "compressed");
536        assert!(text.contains("a=p,i=90"), "and is placed");
537    }
538
539    #[test]
540    fn an_identical_frame_writes_nothing() {
541        let mut presenter = PatchedKitty::new(90, cell());
542        let surface = plain_surface(64, 64);
543        let mut first = Vec::new();
544        presenter
545            .render_frame(&mut first, &surface, crate::surface::test_support::area())
546            .expect("writing to a Vec cannot fail");
547        let mut second = Vec::new();
548        let written = presenter
549            .render_frame(&mut second, &surface, crate::surface::test_support::area())
550            .expect("writing to a Vec cannot fail");
551        assert_eq!(written, 0, "no damage means no bytes");
552        assert!(second.is_empty());
553    }
554
555    #[test]
556    fn a_small_change_retransmits_only_its_tile() {
557        let mut presenter = PatchedKitty::new(90, cell());
558        let mut surface = plain_surface(64, 64);
559        let mut warmup = Vec::new();
560        presenter
561            .render_frame(&mut warmup, &surface, crate::surface::test_support::area())
562            .expect("writing to a Vec cannot fail");
563        surface.set(
564            katui_scene::surface::PixelPos::new(40, 40),
565            Rgba::solid(255, 255, 255),
566        );
567        let mut out = Vec::new();
568        presenter
569            .render_frame(&mut out, &surface, crate::surface::test_support::area())
570            .expect("writing to a Vec cannot fail");
571        let text = String::from_utf8_lossy(&out);
572        assert!(
573            !text.contains("s=64"),
574            "the whole surface does not travel again"
575        );
576        assert!(
577            text.contains("s=10,v=10"),
578            "the damaged 8x8 tile travels with a pixel of apron on each side"
579        );
580        assert!(
581            text.contains("x=1,y=1,w=8,h=8"),
582            "the placement crops the apron away"
583        );
584        assert!(
585            text.contains("a=p,i=41062") && text.contains("c=2,r=2"),
586            "the tile covers its 2x2 cells at the surface's scale"
587        );
588    }
589
590    #[test]
591    fn a_whole_frame_frees_the_tiles_that_would_cover_it() {
592        let mut presenter = PatchedKitty::new(90, cell());
593        let mut surface = plain_surface(64, 64);
594        let mut wire = Vec::new();
595        presenter
596            .render_frame(&mut wire, &surface, crate::surface::test_support::area())
597            .expect("writing to a Vec cannot fail");
598        assert!(
599            !String::from_utf8_lossy(&wire).contains("d=R"),
600            "no tiles exist yet"
601        );
602        surface.set(
603            katui_scene::surface::PixelPos::new(40, 40),
604            Rgba::solid(255, 255, 255),
605        );
606        presenter
607            .render_frame(&mut wire, &surface, crate::surface::test_support::area())
608            .expect("writing to a Vec cannot fail");
609        wire.clear();
610        for y in (0..64).step_by(8) {
611            for x in (0..64).step_by(8) {
612                surface.set(
613                    katui_scene::surface::PixelPos::new(x, y),
614                    Rgba::solid(1, 2, 3),
615                );
616            }
617        }
618        presenter
619            .render_frame(&mut wire, &surface, crate::surface::test_support::area())
620            .expect("writing to a Vec cannot fail");
621        let text = String::from_utf8_lossy(&wire);
622        let placed = text.find("a=p,i=").expect("the new base is placed");
623        let freed = text.find("d=I").expect("the stale tiles are freed");
624        assert!(
625            !text.contains("d=R"),
626            "Ghostty frees every image on a range delete"
627        );
628        assert!(placed < freed, "the new base appears before the tiles go");
629    }
630
631    fn space() -> katui_proto::kitty::IdSpace {
632        katui_proto::kitty::IdSpace::of_process(4242)
633    }
634
635    const VIRTUAL: &str = ",U=1";
636
637    #[test]
638    fn a_multiplexer_grid_shows_every_tile_through_placeholders_and_never_a_whole_image() {
639        let mut presenter = PatchedKitty::new(90, cell()).for_multiplexer(space(), false);
640        let surface = plain_surface(64, 64);
641        let mut wire = Vec::new();
642        presenter
643            .render_frame(&mut wire, &surface, crate::surface::test_support::area())
644            .expect("writing to a Vec cannot fail");
645        let text = String::from_utf8_lossy(&wire);
646        assert!(!text.contains("s=64"), "no whole image travels");
647        assert_eq!(
648            text.matches(VIRTUAL).count(),
649            64,
650            "every tile has a virtual placement"
651        );
652        assert_eq!(
653            text.matches('\u{10eeee}').count(),
654            16 * 16,
655            "placeholder text covers every cell once"
656        );
657        assert!(!text.contains(",P="), "no tile needs a parent placement");
658    }
659
660    #[test]
661    fn a_multiplexer_frame_uploads_every_tile_before_showing_any() {
662        let mut presenter = PatchedKitty::new(90, cell()).for_multiplexer(space(), false);
663        let mut wire = Vec::new();
664        presenter
665            .render_frame(
666                &mut wire,
667                &plain_surface(64, 64),
668                crate::surface::test_support::area(),
669            )
670            .expect("writing to a Vec cannot fail");
671        let text = String::from_utf8_lossy(&wire);
672        let last_upload = text.rfind("a=t,").expect("tiles travel");
673        let first_show = text.find(VIRTUAL).expect("tiles show");
674        assert!(last_upload < first_show, "the frame appears at once");
675    }
676
677    #[test]
678    fn a_repainted_grid_resends_every_tile() {
679        let mut presenter = PatchedKitty::new(90, cell()).for_multiplexer(space(), false);
680        let surface = plain_surface(64, 64);
681        let mut wire = Vec::new();
682        presenter
683            .render_frame(&mut wire, &surface, crate::surface::test_support::area())
684            .expect("writing to a Vec cannot fail");
685        presenter.repaint();
686        wire.clear();
687        presenter
688            .render_frame(&mut wire, &surface, crate::surface::test_support::area())
689            .expect("writing to a Vec cannot fail");
690        let text = String::from_utf8_lossy(&wire);
691        assert_eq!(text.matches(VIRTUAL).count(), 64, "every tile returns");
692        assert_eq!(text.matches("a=t,").count(), 64, "only the tiles travel");
693        assert!(!text.contains("d=R"), "old tiles stay until replaced");
694        wire.clear();
695        presenter
696            .render_frame(&mut wire, &surface, crate::surface::test_support::area())
697            .expect("writing to a Vec cannot fail");
698        assert!(wire.is_empty(), "one repaint request repaints once");
699    }
700
701    #[test]
702    fn a_multiplexer_grid_frees_the_old_tiles_on_a_resize() {
703        let mut presenter = PatchedKitty::new(90, cell()).for_multiplexer(space(), false);
704        let mut wire = Vec::new();
705        presenter
706            .render_frame(
707                &mut wire,
708                &plain_surface(64, 64),
709                crate::surface::test_support::area(),
710            )
711            .expect("writing to a Vec cannot fail");
712        wire.clear();
713        presenter
714            .render_frame(
715                &mut wire,
716                &plain_surface(32, 32),
717                crate::surface::test_support::area(),
718            )
719            .expect("writing to a Vec cannot fail");
720        let text = String::from_utf8_lossy(&wire);
721        let freed = text.find("d=I").expect("the old grid is freed");
722        let placed = text.find("a=p,").expect("the new grid is placed");
723        assert!(freed < placed);
724    }
725
726    #[test]
727    fn a_base_retransmit_never_reuses_the_visible_id() {
728        let mut presenter = PatchedKitty::with_tiles(90, cell(), 8, 0);
729        let mut surface = plain_surface(16, 16);
730        let mut first = Vec::new();
731        presenter
732            .render_frame(&mut first, &surface, crate::surface::test_support::area())
733            .expect("writing to a Vec cannot fail");
734        surface.set(
735            katui_scene::surface::PixelPos::new(1, 1),
736            Rgba::solid(9, 9, 9),
737        );
738        let mut second = Vec::new();
739        presenter
740            .render_frame(&mut second, &surface, crate::surface::test_support::area())
741            .expect("writing to a Vec cannot fail");
742        let text = String::from_utf8_lossy(&second);
743        let placed = text.find("a=p,i=91").expect("the alternate id is placed");
744        let freed = text.find("d=I,i=90").expect("the old base is freed");
745        assert!(placed < freed, "something is always on screen");
746    }
747
748    #[test]
749    fn a_tile_alternates_ids_and_frees_the_previous_one_after_placing() {
750        let mut presenter = PatchedKitty::new(90, cell());
751        let mut surface = plain_surface(64, 64);
752        let mut wire = Vec::new();
753        presenter
754            .render_frame(&mut wire, &surface, crate::surface::test_support::area())
755            .expect("writing to a Vec cannot fail");
756        for shade in [10, 20] {
757            surface.set(
758                katui_scene::surface::PixelPos::new(40, 40),
759                Rgba::solid(shade, shade, shade),
760            );
761            wire.clear();
762            presenter
763                .render_frame(&mut wire, &surface, crate::surface::test_support::area())
764                .expect("writing to a Vec cannot fail");
765        }
766        let text = String::from_utf8_lossy(&wire);
767        let placed = text.find("a=p,i=41063").expect("the second generation");
768        let freed = text.find("d=I,i=41062").expect("the first is freed");
769        assert!(placed < freed, "the old tile stays until the new one shows");
770    }
771
772    #[test]
773    fn a_whole_surface_change_falls_back_to_one_retransmit() {
774        // 128x128 at 8px tiles is 256 tiles: everything dirty blows
775        // the patch budget
776        let mut presenter = PatchedKitty::new(90, cell());
777        let mut surface = plain_surface(128, 128);
778        let big_area = CellRect {
779            x: 0,
780            y: 0,
781            columns: 32,
782            rows: 32,
783        };
784        let mut warmup = Vec::new();
785        presenter
786            .render_frame(&mut warmup, &surface, big_area)
787            .expect("writing to a Vec cannot fail");
788        for y in 0..128u32 {
789            for x in 0..128u32 {
790                surface.set(
791                    katui_scene::surface::PixelPos::new(x, y),
792                    Rgba::solid(200, 40, 40),
793                );
794            }
795        }
796        let mut out = Vec::new();
797        presenter
798            .render_frame(&mut out, &surface, big_area)
799            .expect("writing to a Vec cannot fail");
800        let text = String::from_utf8_lossy(&out);
801        assert!(
802            text.contains("a=t"),
803            "everything dirty means one full frame"
804        );
805    }
806
807    #[test]
808    fn a_size_change_falls_back_to_one_retransmit() {
809        let mut presenter = PatchedKitty::new(90, cell());
810        let mut out = Vec::new();
811        presenter
812            .render_frame(
813                &mut out,
814                &plain_surface(64, 64),
815                crate::surface::test_support::area(),
816            )
817            .expect("writing to a Vec cannot fail");
818        let mut resized = Vec::new();
819        presenter
820            .render_frame(
821                &mut resized,
822                &plain_surface(32, 32),
823                crate::surface::test_support::area(),
824            )
825            .expect("writing to a Vec cannot fail");
826        let text = String::from_utf8_lossy(&resized);
827        assert!(text.contains("a=t"), "a resize retransmits whole");
828    }
829}