Skip to main content

cellix_term/
pixels.rs

1use std::collections::btree_map::Entry;
2use std::collections::hash_map::DefaultHasher;
3use std::collections::{BTreeMap, HashMap, HashSet};
4use std::hash::{Hash, Hasher};
5use std::io::{self, Write};
6use std::time::{Duration, Instant};
7
8use base64::Engine;
9use cellix_render::{Grid, Image, Paint, Rasterizer, Rect, Rgb, UNIT};
10use flate2::{Compression, write::ZlibEncoder};
11
12use crate::Backend;
13
14/// Decoded image memory Cellix keeps in the terminal. Kitty's default limit is 320 MB and
15/// other terminals' are lower, so this stays well inside them.
16pub const DEFAULT_QUOTA: usize = 64 * 1024 * 1024;
17
18const CHUNK: usize = 4096;
19const PLACEHOLDER: char = '\u{10EEEE}';
20/// Row and column zero in the placeholder encoding.
21const DIACRITIC_ZERO: char = '\u{305}';
22
23/// Above the row tiles, so a scrolling region covers them and nothing else has to change.
24const SCROLL_LAYER: u32 = 1;
25/// Placement ids for a scrolling region, clear of the row placements.
26const FIRST_STRIP: usize = 100_000;
27/// Placement numbers a band adds, so each band of a row has its own.
28const BAND_PLACEMENTS: usize = 10_000;
29/// Rows of the page a glide can tell apart, which wrap round far out of sight.
30const STRIP_ROWS: i32 = 1 << 20;
31/// Pixels from the end at which a glide counts as there.
32const ARRIVED: f32 = 0.5;
33/// Screens of rows kept around the view, so turning round needs nothing sent.
34const KEPT_SCREENS: i32 = 3;
35
36/// How a region animates. Direct placement only, since only that can sit between cells.
37#[derive(Clone, Copy, Debug, PartialEq, Eq)]
38pub struct Smooth {
39    /// How often it moves.
40    pub frame: Duration,
41    /// How quickly it closes on where it's going: about two thirds of the way in this time.
42    pub ease: Duration,
43}
44
45/// How far tiles reach past the text area. Ghostty doesn't clip images, so a tile can cover
46/// its right and bottom padding, which no cell can. Left and top stay out of reach, and the
47/// frame there is the terminal's own colour.
48#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
49pub struct Bleed {
50    /// Columns past the right edge.
51    pub cols: u16,
52    /// Rows past the bottom edge.
53    pub rows: u16,
54    /// Pixels the last row's content moves down, to centre it in the band it now fills.
55    pub drop: usize,
56}
57
58/// Rows of Cellix's own, taller than the terminal's lines. Direct placement only: a tile
59/// stands wherever its row begins, which is between two of the terminal's lines as often as
60/// on one, and the terminal has to say where the mouse is in pixels for a press to find it.
61#[derive(Clone, Copy, Debug, PartialEq, Eq)]
62pub struct OwnRows {
63    /// A row's height in pixels.
64    pub row: usize,
65    /// The height of a line of the terminal's, in pixels.
66    pub line: usize,
67}
68
69struct Tile {
70    id: u32,
71    bytes: usize,
72    last_used: u64,
73}
74
75/// A scroll under way. Its rows are tiles the terminal already has, shown through a crop and
76/// a pixel offset, so moving costs a line of text per row and nothing has to be drawn. The
77/// screen underneath is already at the end, and this stands over it until it gets there.
78struct Glide {
79    area: Rect,
80    /// The rows of the page it's seen, counted from the top of the view when it started.
81    rows: BTreeMap<i32, u32>,
82    /// Where the view's heading, in rows from the start.
83    target: i32,
84    /// Where it is, in pixels from the start.
85    at: f32,
86    last: Instant,
87    /// The rows with a placement to take away.
88    placed: HashSet<i32>,
89}
90
91/// How tiles reach the screen. See the tier table in `docs/DESIGN.md`.
92#[derive(Clone, Copy, Debug, PartialEq, Eq)]
93pub enum Placement {
94    /// `a=p` at the cursor. Fails under tmux, which can't track it.
95    Direct,
96    /// Unicode placeholder cells, which tmux stores like text. Every graphics command
97    /// goes through tmux's DCS passthrough.
98    Placeholder,
99}
100
101/// Renders each row once as a tile, keeps it in the terminal's image store, and moves it
102/// by reference, so only new content crosses the wire.
103pub struct PixelBackend<R> {
104    rasterizer: R,
105    placement: Placement,
106    tiles: HashMap<u64, Tile>,
107    /// What's showing in each row, band by band.
108    shown: Vec<Vec<Option<u32>>>,
109    /// The bands those are.
110    bands: Vec<u16>,
111    size: (u16, u16),
112    next_id: u32,
113    used: usize,
114    quota: usize,
115    frame: u64,
116    smooth: Option<Smooth>,
117    /// Whether region placements are waiting to be removed by the next present.
118    scrolling: bool,
119    bleed: Bleed,
120    glide: Option<Glide>,
121    /// A cell's size in pixels, from the tiles.
122    cell: Option<(i32, i32)>,
123    own: Option<OwnRows>,
124    /// The terminal's lines, to know what's left under the last of Cellix's own rows.
125    lines: u16,
126}
127
128/// What a row looks like, as a key: rows with the same key draw the same pixels.
129pub fn row_key(grid: &Grid, y: u16) -> u64 {
130    band_key(grid, y, (0, grid.width()))
131}
132
133/// What one band of a row looks like, as a key. It says nothing of where the row stands, so
134/// a row keeps its tile as it scrolls.
135fn band_key(grid: &Grid, y: u16, (from, to): (u16, u16)) -> u64 {
136    let mut hasher = DefaultHasher::new();
137    (from, to).hash(&mut hasher);
138    grid.row(y)[from as usize..to as usize].hash(&mut hasher);
139    // The band at the row's end runs on past it in this colour.
140    if to == grid.width() {
141        grid.edge.hash(&mut hasher);
142    }
143    let inside = |x: u16| x >= from && x < to;
144    let cursor = grid.cursor.filter(|c| c.1 == y && inside(c.0));
145    cursor.map(|c| c.0).hash(&mut hasher);
146    // Only on its own row: hashed everywhere, moving the caret resent the whole screen.
147    let (top, bottom) = (y as i32 * UNIT, (y as i32 + 1) * UNIT);
148    let (left, right) = (from as i32 * UNIT, to as i32 * UNIT);
149    let caret = grid
150        .caret
151        .filter(|c| c.y < bottom && c.y + c.h > top && c.x >= left && c.x < right);
152    caret.map(|c| (c.x, c.y - top, c.w, c.h)).hash(&mut hasher);
153    let meets = |paint: &&Paint| {
154        let (start, end) = paint.reach();
155        start < right && end > left
156    };
157    // Paint can stand in several rows, and each shows its own slice, which `on_row` keeps
158    // apart: the rows above and below a tall heading aren't the same tile.
159    for paint in grid.paint_on_row(y).filter(meets) {
160        paint.on_row(top).hash(&mut hasher);
161    }
162    hasher.finish()
163}
164
165/// Part of a row's image, between two pixel columns.
166fn crop(image: &Image, left: usize, right: usize) -> Image {
167    let mut rgb = Vec::with_capacity((right - left) * image.height * 3);
168    for line in image.rgb.chunks_exact(image.width * 3) {
169        rgb.extend_from_slice(&line[left * 3..right * 3]);
170    }
171    Image {
172        width: right - left,
173        height: image.height,
174        rgb,
175    }
176}
177
178fn place_number(y: u16, band: usize) -> usize {
179    y as usize + 1 + band * BAND_PLACEMENTS
180}
181
182fn zlib(data: &[u8]) -> Vec<u8> {
183    let mut z = ZlibEncoder::new(Vec::with_capacity(data.len() / 8), Compression::fast());
184    z.write_all(data).expect("writing to a Vec");
185    z.finish().expect("writing to a Vec")
186}
187
188impl<R: Rasterizer> PixelBackend<R> {
189    pub fn new(rasterizer: R, placement: Placement, quota: usize) -> Self {
190        Self {
191            rasterizer,
192            placement,
193            tiles: HashMap::new(),
194            shown: Vec::new(),
195            bands: Vec::new(),
196            size: (0, 0),
197            next_id: 1,
198            used: 0,
199            quota,
200            frame: 0,
201            smooth: None,
202            scrolling: false,
203            bleed: Bleed::default(),
204            glide: None,
205            cell: None,
206            own: None,
207            lines: 0,
208        }
209    }
210
211    /// Lays rows out at a height of Cellix's own. Nothing glides: a glide counts in lines.
212    pub fn with_own_rows(mut self, own: OwnRows) -> Self {
213        if self.placement == Placement::Direct && own.row > own.line && own.line > 0 {
214            self.own = Some(own);
215            self.smooth = None;
216        }
217        self
218    }
219
220    /// Pixels under the last row of `rows`, down to the end of what a tile can cover: what
221    /// the terminal's lines leave over, and the padding below them.
222    fn spare(&self, rows: u16) -> usize {
223        self.own.map_or(0, |own| {
224            let lines = (self.lines as usize + self.bleed.rows as usize) * own.line;
225            lines.saturating_sub(rows as usize * own.row)
226        })
227    }
228
229    /// Whether the last row's tile is taller than the same row anywhere else.
230    fn runs_on(&self, rows: u16) -> bool {
231        self.bleed.rows > 0 || self.spare(rows) > 0
232    }
233
234    /// Only direct placement can leave the text area: placeholders are cells.
235    pub fn with_bleed(mut self, bleed: Bleed) -> Self {
236        if self.placement == Placement::Direct {
237            self.bleed = bleed;
238        }
239        self
240    }
241
242    pub fn with_smooth(mut self, smooth: Smooth) -> Self {
243        let can = self.placement == Placement::Direct && self.own.is_none();
244        self.smooth = can.then_some(smooth);
245        self
246    }
247
248    /// Writes one graphics command, wrapped for tmux in placeholder mode.
249    fn apc(&self, out: &mut Vec<u8>, control: &str, payload: &[u8]) {
250        let wrap = self.placement == Placement::Placeholder;
251        out.extend_from_slice(if wrap {
252            b"\x1bPtmux;\x1b\x1b_G"
253        } else {
254            b"\x1b_G"
255        });
256        out.extend_from_slice(control.as_bytes());
257        if !payload.is_empty() {
258            out.push(b';');
259            out.extend_from_slice(payload);
260        }
261        out.extend_from_slice(if wrap { b"\x1b\x1b\\\x1b\\" } else { b"\x1b\\" });
262    }
263
264    fn transmit(&self, out: &mut Vec<u8>, id: u32, image: &Image) {
265        let b64 = base64::engine::general_purpose::STANDARD.encode(zlib(&image.rgb));
266        let chunks: Vec<&[u8]> = b64.as_bytes().chunks(CHUNK).collect();
267        for (i, chunk) in chunks.iter().enumerate() {
268            let more = u8::from(i + 1 < chunks.len());
269            let control = if i == 0 {
270                format!(
271                    "a=t,f=24,o=z,t=d,q=2,i={id},s={},v={},m={more}",
272                    image.width, image.height
273                )
274            } else {
275                format!("m={more},q=2")
276            };
277            self.apc(out, &control, chunk);
278        }
279    }
280
281    /// Where a band of a row goes, and how many rows high.
282    fn place(
283        &self,
284        out: &mut Vec<u8>,
285        id: u32,
286        (y, band): (u16, usize),
287        (from, to): (u16, u16),
288        rows: u16,
289        last: bool,
290    ) {
291        let cols = to - from;
292        // A row of Cellix's own starts so many pixels down, which is on one of the
293        // terminal's lines and some way into it.
294        let (line, into) = match self.own {
295            Some(own) => {
296                let top = y as usize * own.row;
297                (top / own.line, top % own.line)
298            }
299            None => (y as usize, 0),
300        };
301        let _ = write!(out, "\x1b[{};{}H", line + 1, from + 1);
302        match self.placement {
303            Placement::Direct => {
304                let cols = cols + if last { self.bleed.cols } else { 0 };
305                let number = place_number(y, band);
306                let control = match self.own {
307                    // At its own size: the tile is a row tall, which no count of lines is.
308                    Some(_) => format!("a=p,i={id},p={number},Y={into},C=1,q=2"),
309                    None => format!("a=p,i={id},p={number},c={cols},r={rows},C=1,q=2"),
310                };
311                self.apc(out, &control, b"");
312            }
313            Placement::Placeholder => {
314                // The foreground colour carries the image id.
315                let (r, g, b) = ((id >> 16) & 255, (id >> 8) & 255, id & 255);
316                let _ = write!(out, "\x1b[38;2;{r};{g};{b}m");
317                let _ = write!(out, "{PLACEHOLDER}{DIACRITIC_ZERO}{DIACRITIC_ZERO}");
318                for _ in 1..cols {
319                    let _ = write!(out, "{PLACEHOLDER}");
320                }
321                out.extend_from_slice(b"\x1b[39m");
322            }
323        }
324    }
325
326    /// A row's image, grown to cover the padding beyond it in the colours at the edge.
327    fn bled(&self, image: Image, grid: &Grid, y: u16) -> Image {
328        let Bleed { cols, rows, drop } = self.bleed;
329        let cells = grid.row(y);
330        let spare = if y + 1 == grid.height() {
331            self.spare(grid.height())
332        } else {
333            0
334        };
335        let (Some(last), true) = (cells.last(), cols > 0 || rows > 0 || spare > 0) else {
336            return image;
337        };
338        let cell = image.width / cells.len();
339        let width = image.width + cols as usize * cell;
340        let paint = |line: &mut Vec<u8>, from: usize, to: usize, color: Rgb| {
341            for _ in from..to {
342                line.extend_from_slice(&[color.0, color.1, color.2]);
343            }
344        };
345        let mut rgb = Vec::new();
346        // Past the row's end: the frame's colour where the grid says what that is, so a sheet
347        // that ends at the grid's edge ends there and the window's padding stays the frame's.
348        let beyond = grid.edge.unwrap_or(last.style.bg);
349        if y + 1 != grid.height() {
350            for line in image.rgb.chunks_exact(image.width * 3) {
351                rgb.extend_from_slice(line);
352                paint(&mut rgb, image.width, width, beyond);
353            }
354            return Image {
355                width,
356                rgb,
357                ..image
358            };
359        }
360        // The bar's own colours run on below it, column by column.
361        let height = match self.own {
362            Some(_) => image.height + spare,
363            None => image.height * (1 + rows as usize),
364        };
365        let drop = drop.min(height - image.height);
366        let mut plain = Vec::with_capacity(width * 3);
367        for c in cells {
368            paint(&mut plain, 0, cell, c.style.bg);
369        }
370        paint(&mut plain, image.width, width, last.style.bg);
371        for _ in 0..drop {
372            rgb.extend_from_slice(&plain);
373        }
374        for line in image.rgb.chunks_exact(image.width * 3) {
375            rgb.extend_from_slice(line);
376            paint(&mut rgb, image.width, width, last.style.bg);
377        }
378        for _ in drop + image.height..height {
379            rgb.extend_from_slice(&plain);
380        }
381        Image { width, height, rgb }
382    }
383
384    /// The bands of a row, as (first column, column past the last). The last row is the
385    /// status bar, which nothing scrolls in, and its tile can reach below the text area.
386    fn spans(&self, grid: &Grid, y: u16) -> Vec<(u16, u16)> {
387        let width = grid.width();
388        if y + 1 == grid.height() {
389            return vec![(0, width)];
390        }
391        let inside = grid.bands.iter().copied().filter(|x| *x > 0 && *x < width);
392        let edges: Vec<u16> = [0].into_iter().chain(inside).chain([width]).collect();
393        edges.windows(2).map(|edge| (edge[0], edge[1])).collect()
394    }
395
396    /// The tile for each band of a row, rasterizing the row once if any of them is new.
397    fn band_tiles(&mut self, out: &mut Vec<u8>, grid: &Grid, y: u16) -> Vec<u32> {
398        let spans = self.spans(grid, y);
399        // The last row's tile is taller than the same row anywhere else.
400        let bottom = y + 1 == grid.height() && self.runs_on(grid.height());
401        let keys: Vec<u64> = spans
402            .iter()
403            .map(|span| band_key(grid, y, *span).rotate_left(u32::from(bottom)))
404            .collect();
405        if keys.iter().any(|key| !self.tiles.contains_key(key)) {
406            let image = self.rasterizer.row(grid, y);
407            let cols = grid.width();
408            let cell = image.width / cols.max(1) as usize;
409            self.cell = Some((cell as i32, image.height as i32));
410            let image = self.bled(image, grid, y);
411            for (&(from, to), key) in spans.iter().zip(&keys) {
412                if self.tiles.contains_key(key) {
413                    continue;
414                }
415                let right = if to == cols {
416                    image.width
417                } else {
418                    to as usize * cell
419                };
420                let part = crop(&image, from as usize * cell, right);
421                let id = self.new_id();
422                self.transmit(out, id, &part);
423                if self.placement == Placement::Placeholder {
424                    let wide = to - from;
425                    self.apc(out, &format!("a=p,U=1,i={id},c={wide},r=1,q=2"), b"");
426                }
427                self.used += part.rgb.len();
428                let tile = Tile {
429                    id,
430                    bytes: part.rgb.len(),
431                    last_used: self.frame,
432                };
433                self.tiles.insert(*key, tile);
434            }
435        }
436        let frame = self.frame;
437        let mut use_tile = |key: &u64| {
438            let tile = self.tiles.get_mut(key).expect("made above");
439            tile.last_used = frame;
440            tile.id
441        };
442        keys.iter().map(&mut use_tile).collect()
443    }
444
445    /// A glide from what's on screen now, whose rows are in the terminal already.
446    fn start_glide(&self, area: Rect, band: usize) -> Option<Glide> {
447        let shown = (area.y..area.bottom()).enumerate().map(|(index, y)| {
448            let id = (*self.shown.get(y as usize)?.get(band)?)?;
449            Some((index as i32, id))
450        });
451        Some(Glide {
452            area,
453            rows: shown.collect::<Option<_>>()?,
454            target: 0,
455            at: 0.0,
456            last: Instant::now(),
457            placed: HashSet::new(),
458        })
459    }
460
461    fn new_id(&mut self) -> u32 {
462        let id = self.next_id;
463        self.next_id = (self.next_id + 1) & 0xff_ffff;
464        if self.next_id == 0 {
465            self.next_id = 1;
466        }
467        id
468    }
469
470    /// Frees the least recently used tiles that aren't on screen.
471    fn evict(&mut self, out: &mut Vec<u8>, on_screen: &HashSet<u32>) {
472        while self.used > self.quota {
473            let oldest = self
474                .tiles
475                .iter()
476                .filter(|(_, t)| !on_screen.contains(&t.id))
477                .min_by_key(|(_, t)| t.last_used)
478                .map(|(key, _)| *key);
479            let Some(key) = oldest else { return };
480            let tile = self.tiles.remove(&key).expect("key came from the map");
481            self.used -= tile.bytes;
482            self.apc(out, &format!("a=d,d=I,i={},q=2", tile.id), b"");
483        }
484    }
485
486    pub fn tile_count(&self) -> usize {
487        self.tiles.len()
488    }
489
490    pub fn used_bytes(&self) -> usize {
491        self.used
492    }
493}
494
495impl<R: Rasterizer> Backend for PixelBackend<R> {
496    fn present(&mut self, grid: &Grid, out: &mut dyn Write) -> io::Result<()> {
497        let mut bytes = Vec::new();
498        bytes.extend_from_slice(b"\x1b[?2026h\x1b[?25l");
499        let size = (grid.width(), grid.height());
500        if size != self.size {
501            // Tiles are as wide as the grid, so a new width makes all of them useless.
502            self.apc(&mut bytes, "a=d,d=A,q=2", b"");
503            bytes.extend_from_slice(b"\x1b[2J");
504            self.tiles.clear();
505            self.glide = None;
506            self.used = 0;
507            self.shown = vec![Vec::new(); grid.height() as usize];
508            self.size = size;
509        }
510        if grid.bands != self.bands {
511            // The panels moved, so what's shown is cut in the wrong places. Tiles stay.
512            if self.placement == Placement::Direct {
513                self.apc(&mut bytes, "a=d,d=a,q=2", b"");
514            }
515            self.shown = vec![Vec::new(); grid.height() as usize];
516            self.bands.clone_from(&grid.bands);
517            self.glide = None;
518            self.scrolling = false;
519        }
520        self.frame += 1;
521        let mut on_screen = HashSet::new();
522        for y in 0..grid.height() {
523            let bottom = y + 1 == grid.height() && self.bleed.rows > 0;
524            let spans = self.spans(grid, y);
525            let ids = self.band_tiles(&mut bytes, grid, y);
526            self.shown[y as usize].resize(ids.len(), None);
527            for (band, (id, span)) in ids.into_iter().zip(spans).enumerate() {
528                on_screen.insert(id);
529                let old = self.shown[y as usize][band];
530                if old == Some(id) {
531                    continue;
532                }
533                // A placement belongs to its image, so a new image at this row doesn't
534                // replace the old one. Left alone, stale rows pile up as you scroll.
535                if let (Placement::Direct, Some(old)) = (self.placement, old) {
536                    let number = place_number(y, band);
537                    self.apc(&mut bytes, &format!("a=d,d=i,i={old},p={number},q=2"), b"");
538                }
539                let rows = 1 + if bottom { self.bleed.rows } else { 0 };
540                let last = span.1 == grid.width();
541                self.place(&mut bytes, id, (y, band), span, rows, last);
542                self.shown[y as usize][band] = Some(id);
543            }
544        }
545        if std::mem::take(&mut self.scrolling) {
546            self.apc(&mut bytes, &format!("a=d,d=z,z={SCROLL_LAYER},q=2"), b"");
547        }
548        on_screen.extend(self.glide.iter().flat_map(|g| g.rows.values().copied()));
549        self.evict(&mut bytes, &on_screen);
550        bytes.extend_from_slice(b"\x1b[?2026l");
551        out.write_all(&bytes)?;
552        out.flush()
553    }
554
555    fn scroll(
556        &mut self,
557        from: &Grid,
558        to: &Grid,
559        area: Rect,
560        rows: i32,
561        out: &mut dyn Write,
562    ) -> io::Result<()> {
563        let same_size = (from.width(), from.height()) == (to.width(), to.height());
564        let can_glide = self.smooth.is_some()
565            && self.cell.is_some()
566            && same_size
567            && self.size == (to.width(), to.height())
568            && rows != 0
569            && rows.abs() < area.h as i32;
570        let spans = self.spans(to, area.y);
571        let band = spans
572            .iter()
573            .position(|span| *span == (area.x, area.right()));
574        let same_area = self.glide.as_ref().is_none_or(|g| g.area == area);
575        let (true, true, Some(band)) = (can_glide, same_area, band) else {
576            self.settle();
577            return Ok(());
578        };
579        let Some(mut glide) = self.glide.take().or_else(|| self.start_glide(area, band)) else {
580            return Ok(());
581        };
582        let mut bytes = Vec::new();
583        glide.target += rows;
584        for (index, y) in (area.y..area.bottom()).enumerate() {
585            let row = glide.target + index as i32;
586            if let Entry::Vacant(place) = glide.rows.entry(row) {
587                place.insert(self.band_tiles(&mut bytes, to, y)[band]);
588            }
589        }
590        self.glide = Some(glide);
591        out.write_all(&bytes)?;
592        out.flush()
593    }
594
595    fn gliding(&self) -> Option<Duration> {
596        self.glide.as_ref()?;
597        self.smooth.map(|smooth| smooth.frame)
598    }
599
600    fn glide(&mut self, now: Instant, out: &mut dyn Write) -> io::Result<()> {
601        let (Some(mut glide), Some(smooth), Some((cell_w, cell_h))) =
602            (self.glide.take(), self.smooth, self.cell)
603        else {
604            return Ok(());
605        };
606        let target = (glide.target * cell_h) as f32;
607        let window = glide.area.h as i32 * cell_h;
608        // A long way behind, as after a hard flick, it would only look like lag.
609        glide.at = glide
610            .at
611            .clamp(target - window as f32, target + window as f32);
612        let passed = now.duration_since(glide.last).as_secs_f32();
613        glide.last = now;
614        let left = (-passed / smooth.ease.as_secs_f32()).exp();
615        glide.at = target + (glide.at - target) * left;
616        if (glide.at - target).abs() < ARRIVED {
617            glide.at = target;
618        }
619        let at = glide.at.round() as i32;
620        let wide = i32::from(glide.area.w) * cell_w;
621        let mut bytes = b"\x1b[?2026h".to_vec();
622        for (&row, &id) in &glide.rows {
623            let top = row * cell_h - at;
624            let (clip_top, clip_end) = ((-top).max(0), cell_h.min(window - top));
625            let number = FIRST_STRIP + row.rem_euclid(STRIP_ROWS) as usize;
626            if clip_top >= clip_end {
627                if glide.placed.remove(&row) {
628                    self.apc(&mut bytes, &format!("a=d,d=i,i={id},p={number},q=2"), b"");
629                }
630                continue;
631            }
632            let pixel = top.max(0);
633            let y = i32::from(glide.area.y) + pixel / cell_h;
634            let _ = write!(bytes, "\x1b[{};{}H", y + 1, glide.area.x + 1);
635            let control = format!(
636                "a=p,i={id},p={number},x=0,y={clip_top},w={wide},h={},Y={},z={SCROLL_LAYER},C=1,q=2",
637                clip_end - clip_top,
638                pixel % cell_h,
639            );
640            self.apc(&mut bytes, &control, b"");
641            glide.placed.insert(row);
642        }
643        bytes.extend_from_slice(b"\x1b[?2026l");
644        out.write_all(&bytes)?;
645        out.flush()?;
646        // What's far behind has no way back into view before it's drawn again.
647        let reach = glide.area.h as i32 * KEPT_SCREENS;
648        let view = at / cell_h;
649        glide
650            .rows
651            .retain(|row, _| (row - view).abs() <= reach || glide.placed.contains(row));
652        if glide.at == target {
653            self.scrolling = true;
654        } else {
655            self.glide = Some(glide);
656        }
657        Ok(())
658    }
659
660    fn settle(&mut self) {
661        self.scrolling |= self.glide.take().is_some();
662    }
663
664    fn invalidate(&mut self) {
665        self.size = (0, 0);
666        self.glide = None;
667    }
668
669    fn set_lines(&mut self, lines: u16) {
670        if self.own.is_some() && lines != self.lines {
671            // The last row's tile is as tall as what's left under it, which just changed.
672            self.size = (0, 0);
673        }
674        self.lines = lines;
675    }
676}
677
678#[cfg(test)]
679mod tests {
680    use super::*;
681    use cellix_render::Style;
682
683    /// A row under a tall shape, like a page's sheet, is the same row wherever it stands, so it
684    /// keeps its picture as the page scrolls. Near the shape's rounded ends it isn't.
685    #[test]
686    fn a_row_under_a_tall_shape_is_known_wherever_it_stands() {
687        let mut grid = Grid::new(10, 30, Style::default());
688        let sheet = cellix_render::Bounds::cells(1.0, 0.0, 8.0, 30.0);
689        grid.panel(sheet, 40, Some(cellix_render::Rgb(250, 250, 250)), None);
690        assert_eq!(row_key(&grid, 10), row_key(&grid, 15));
691        assert_ne!(
692            row_key(&grid, 0),
693            row_key(&grid, 15),
694            "the rounded top shows in row 0"
695        );
696    }
697
698    /// Solid tiles, so these tests measure the protocol and not fonts.
699    struct Flat;
700
701    impl Rasterizer for Flat {
702        fn row(&mut self, grid: &Grid, _y: u16) -> Image {
703            Image {
704                width: grid.width() as usize,
705                height: 1,
706                rgb: vec![9; grid.width() as usize * 3],
707            }
708        }
709    }
710
711    /// Eight by sixteen, with a colour taken from the row's first letter.
712    struct Sized;
713
714    impl Rasterizer for Sized {
715        fn row(&mut self, grid: &Grid, y: u16) -> Image {
716            let tone = grid.row(y)[9].symbol.bytes().next().unwrap_or(0);
717            let (width, height) = (grid.width() as usize * 8, 16);
718            Image {
719                width,
720                height,
721                rgb: vec![tone; width * height * 3],
722            }
723        }
724    }
725
726    /// A sidebar in the first eight columns that stays still, and a pane that moves.
727    fn pane(top: usize) -> Grid {
728        let mut grid = Grid::new(20, 8, Style::default());
729        grid.bands = vec![PANE.x];
730        for y in 0..8 {
731            grid.put_str(0, y, &format!("side{y}"), Style::default(), 8);
732            let letter = char::from(b'a' + (top + y as usize) as u8);
733            grid.put_str(9, y, &letter.to_string(), Style::default(), 20);
734        }
735        grid
736    }
737
738    const PANE: Rect = Rect {
739        x: 8,
740        y: 1,
741        w: 12,
742        h: 6,
743    };
744
745    const STEP: Duration = Duration::from_millis(8);
746    const SMOOTH: Smooth = Smooth {
747        frame: STEP,
748        ease: Duration::from_millis(40),
749    };
750
751    fn smooth() -> PixelBackend<Sized> {
752        PixelBackend::new(Sized, Placement::Direct, DEFAULT_QUOTA).with_smooth(SMOOTH)
753    }
754
755    fn scroll(b: &mut PixelBackend<Sized>, from: &Grid, to: &Grid, rows: i32) -> String {
756        let mut out = Vec::new();
757        b.scroll(from, to, PANE, rows, &mut out).unwrap();
758        String::from_utf8(out).unwrap()
759    }
760
761    fn present_sized(b: &mut PixelBackend<Sized>, grid: &Grid) -> String {
762        let mut out = Vec::new();
763        b.present(grid, &mut out).unwrap();
764        String::from_utf8(out).unwrap()
765    }
766
767    /// Rows of Cellix's own, 22 pixels on lines of 16: each tile is placed at its own size
768    /// on the line its row starts in, so many pixels into it, and the last one runs on over
769    /// what the lines leave under it. Nothing is stretched to a count of lines.
770    #[test]
771    fn a_taller_row_stands_between_the_terminals_lines() {
772        struct Tall;
773        impl Rasterizer for Tall {
774            fn row(&mut self, grid: &Grid, _y: u16) -> Image {
775                let (width, height) = (grid.width() as usize * 8, 22);
776                Image {
777                    width,
778                    height,
779                    rgb: vec![7; width * height * 3],
780                }
781            }
782        }
783        let own = OwnRows { row: 22, line: 16 };
784        let mut b = PixelBackend::new(Tall, Placement::Direct, DEFAULT_QUOTA).with_own_rows(own);
785        // Six lines are 96 pixels: four rows of 22, and 8 pixels over.
786        b.set_lines(6);
787        let grid = Grid::new(12, 4, Style::default());
788        let mut out = Vec::new();
789        b.present(&grid, &mut out).unwrap();
790        let output = String::from_utf8(out).unwrap();
791        let placed: Vec<(String, String)> = output
792            .split("\x1b[")
793            .filter_map(|part| {
794                let (at, rest) = part.split_once("H\x1b_Ga=p,")?;
795                let into = rest.split(",Y=").nth(1)?.split(',').next()?;
796                Some((at.to_string(), into.to_string()))
797            })
798            .collect();
799        let want = [("1;1", "0"), ("2;1", "6"), ("3;1", "12"), ("5;1", "2")];
800        let want: Vec<(String, String)> = want
801            .iter()
802            .map(|(at, into)| (at.to_string(), into.to_string()))
803            .collect();
804        assert_eq!(
805            placed, want,
806            "the line each row starts in, and how far into it"
807        );
808        assert!(!output.contains(",r="), "a tile isn't stretched over lines");
809        let heights: Vec<&str> = output
810            .split("a=t,")
811            .skip(1)
812            .filter_map(|part| part.split(",v=").nth(1)?.split(',').next())
813            .collect();
814        assert_eq!(
815            heights.last(),
816            Some(&"30"),
817            "the last row covers the 8 pixels left"
818        );
819        assert!(heights[..heights.len() - 1].iter().all(|h| *h == "22"));
820        // With another line under it there's more to cover, so the last row is drawn again.
821        b.set_lines(7);
822        let mut out = Vec::new();
823        b.present(&grid, &mut out).unwrap();
824        let output = String::from_utf8(out).unwrap();
825        assert!(
826            output.contains(",v=46,"),
827            "8 pixels and a line of 16: {output:?}"
828        );
829        // Under tmux a tile is cells, which only a line can be.
830        let mut held =
831            PixelBackend::new(Tall, Placement::Placeholder, DEFAULT_QUOTA).with_own_rows(own);
832        let mut out = Vec::new();
833        held.present(&grid, &mut out).unwrap();
834        assert!(!String::from_utf8(out).unwrap().contains(",Y="));
835    }
836
837    #[test]
838    fn the_window_fills_to_its_edges() {
839        let mut b = PixelBackend::new(Sized, Placement::Direct, DEFAULT_QUOTA).with_bleed(Bleed {
840            cols: 2,
841            rows: 1,
842            drop: 3,
843        });
844        let grid = Grid::new(12, 2, Style::default());
845        let output = present_sized(&mut b, &grid);
846        let widths: Vec<String> = output
847            .split("\x1b_G")
848            .filter_map(|c| field(c, "s"))
849            .collect();
850        let tall: Vec<String> = output
851            .split("\x1b_G")
852            .filter_map(|c| field(c, "v"))
853            .collect();
854        assert!(
855            widths.iter().all(|w| w == "112"),
856            "two more cells: {widths:?}"
857        );
858        assert!(
859            tall.contains(&"32".to_string()),
860            "the last row takes two: {tall:?}"
861        );
862        assert!(tall.contains(&"16".to_string()));
863        let placed: Vec<&str> = output
864            .split("\x1b_G")
865            .filter(|c| c.starts_with("a=p"))
866            .collect();
867        assert!(placed.iter().all(|c| c.contains(",c=14,")), "{placed:?}");
868        assert!(placed[1].contains(",r=2,"), "{placed:?}");
869        let mut placeholders = PixelBackend::new(Sized, Placement::Placeholder, DEFAULT_QUOTA)
870            .with_bleed(Bleed {
871                cols: 2,
872                rows: 1,
873                drop: 3,
874            });
875        assert_eq!(
876            placeholders.bleed,
877            Bleed::default(),
878            "placeholders are cells"
879        );
880        let _ = present_sized(&mut placeholders, &grid);
881    }
882
883    #[test]
884    fn a_tall_heading_keeps_its_lower_half() {
885        let mut grid = Grid::new(20, 8, Style::default());
886        let big = cellix_render::Font {
887            size: 150,
888            ..cellix_render::Font::default()
889        };
890        grid.text_run((1.0, 3.5), 20.0, "Workflow", (Rgb(9, 9, 9), false), big);
891        assert_ne!(
892            row_key(&grid, 2),
893            row_key(&grid, 4),
894            "the row above and the row below show different slices"
895        );
896        let blank = Grid::new(20, 8, Style::default());
897        assert_eq!(
898            row_key(&blank, 2),
899            row_key(&blank, 4),
900            "empty rows still share a tile, which scrolling depends on"
901        );
902    }
903
904    /// Runs `count` frames of a glide, and gives back what they sent.
905    fn frames(b: &mut PixelBackend<Sized>, count: u32) -> String {
906        let mut out = Vec::new();
907        for _ in 0..count {
908            let now = b.glide.as_ref().map_or_else(Instant::now, |g| g.last) + STEP;
909            b.glide(now, &mut out).unwrap();
910        }
911        String::from_utf8(out).unwrap()
912    }
913
914    #[test]
915    fn regions_scroll_by_pixels() {
916        let mut b = smooth();
917        let (from, to) = (pane(0), pane(3));
918        present_sized(&mut b, &from);
919        scroll(&mut b, &from, &to, 3);
920        let moving = frames(&mut b, 4);
921        assert_eq!(count(&moving, "\x1b[?2026h"), 4, "every frame is atomic");
922        let offsets: HashSet<String> = moving
923            .split(",Y=")
924            .skip(1)
925            .map(|rest| rest.split(',').next().unwrap().to_string())
926            .collect();
927        assert!(
928            offsets.iter().any(|y| y != "0"),
929            "it sits between cells: {offsets:?}"
930        );
931        assert!(moving.contains(",z=1,"), "above the row tiles");
932        assert!(
933            !moving.contains("\x1b[1;9H"),
934            "nothing lands on the row above the pane"
935        );
936        assert!(
937            !moving.contains(";1H"),
938            "the sidebar's column is never touched"
939        );
940        frames(&mut b, 200);
941        assert_eq!(b.gliding(), None, "it gets there");
942        let settled = present_sized(&mut b, &to);
943        assert_eq!(
944            count(&settled, "a=d,d=z,z=1"),
945            1,
946            "the layer goes with the final page"
947        );
948        assert_eq!(count(&present_sized(&mut b, &to), "a=d,d=z"), 0);
949    }
950
951    #[test]
952    fn a_glide_moves_quickly_at_first_and_settles_gently() {
953        let mut b = smooth();
954        let (from, to) = (pane(0), pane(3));
955        present_sized(&mut b, &from);
956        scroll(&mut b, &from, &to, 3);
957        let mut places = vec![0.0];
958        while b.gliding().is_some() {
959            frames(&mut b, 1);
960            places.push(b.glide.as_ref().map_or(48.0, |g| g.at));
961            assert!(places.len() < 80, "it takes too long: {places:?}");
962        }
963        let steps: Vec<f32> = places.windows(2).map(|p| p[1] - p[0]).collect();
964        assert!(
965            steps.iter().all(|step| *step >= 0.0),
966            "never back: {steps:?}"
967        );
968        assert!(steps[0] > steps[steps.len() / 2], "it eases: {steps:?}");
969    }
970
971    #[test]
972    fn a_new_notch_carries_on_from_where_it_is() {
973        let mut b = smooth();
974        let (first, second, third) = (pane(0), pane(2), pane(4));
975        present_sized(&mut b, &first);
976        scroll(&mut b, &first, &second, 2);
977        frames(&mut b, 3);
978        let at = b.glide.as_ref().unwrap().at;
979        scroll(&mut b, &second, &third, 2);
980        let glide = b.glide.as_ref().unwrap();
981        assert_eq!((glide.at, glide.target), (at, 4), "no restart, no jump");
982    }
983
984    #[test]
985    fn the_wrong_way_turns_round_smoothly() {
986        let mut b = smooth();
987        let (first, second) = (pane(0), pane(2));
988        present_sized(&mut b, &first);
989        scroll(&mut b, &first, &second, 2);
990        frames(&mut b, 3);
991        let at = b.glide.as_ref().unwrap().at;
992        scroll(&mut b, &second, &first, -2);
993        frames(&mut b, 1);
994        let now = b.glide.as_ref().unwrap().at;
995        assert!(now < at && now > 0.0, "{at} then {now}");
996    }
997
998    #[test]
999    fn scrolling_only_sends_what_the_terminal_hasnt_seen() {
1000        let mut b = smooth();
1001        let (from, to) = (pane(0), pane(1));
1002        present_sized(&mut b, &from);
1003        let sent = count(&scroll(&mut b, &from, &to, 1), "a=t,");
1004        assert!(sent <= 1, "at most the one new row, not {sent}");
1005        assert_eq!(
1006            count(&frames(&mut b, 5), "a=t,"),
1007            0,
1008            "moving costs no pictures"
1009        );
1010    }
1011
1012    #[test]
1013    fn a_region_clips_at_its_edges() {
1014        let mut b = smooth();
1015        let (from, to) = (pane(0), pane(1));
1016        present_sized(&mut b, &from);
1017        scroll(&mut b, &from, &to, 1);
1018        let moving = frames(&mut b, 3);
1019        assert!(
1020            moving.contains(",x=0,y="),
1021            "the pane's own tiles: {moving:?}"
1022        );
1023        let clipped = moving
1024            .split(",y=")
1025            .skip(1)
1026            .any(|rest| !rest.starts_with("0,"));
1027        assert!(clipped, "the top row loses its top part: {moving:?}");
1028    }
1029
1030    #[test]
1031    fn scrolling_back_needs_nothing_new() {
1032        let mut b = smooth();
1033        let (from, to) = (pane(0), pane(2));
1034        present_sized(&mut b, &from);
1035        scroll(&mut b, &from, &to, 2);
1036        frames(&mut b, 200);
1037        present_sized(&mut b, &to);
1038        let back = scroll(&mut b, &to, &from, -2);
1039        assert_eq!(
1040            count(&back, "a=t,"),
1041            0,
1042            "the tiles are in the terminal already"
1043        );
1044    }
1045
1046    #[test]
1047    fn a_scrolled_page_keeps_its_tiles_whatever_stands_beside_it() {
1048        let mut b = smooth();
1049        let (from, to) = (pane(0), pane(3));
1050        present_sized(&mut b, &from);
1051        scroll(&mut b, &from, &to, 3);
1052        frames(&mut b, 200);
1053        let settled = present_sized(&mut b, &to);
1054        // A row outside the region can change too, as this page has no bars there.
1055        assert!(
1056            count(&settled, "a=t,") <= 2,
1057            "the region sent nothing: {settled:?}"
1058        );
1059    }
1060
1061    #[test]
1062    fn a_change_in_one_band_sends_only_that_band() {
1063        let mut b = smooth();
1064        let mut grid = pane(0);
1065        present_sized(&mut b, &grid);
1066        grid.put_str(10, 3, "x", Style::default(), 20);
1067        let sent = present_sized(&mut b, &grid);
1068        assert_eq!(count(&sent, "a=t,"), 1, "{sent:?}");
1069    }
1070
1071    #[test]
1072    fn typeset_rows_keep_their_tiles_as_they_move() {
1073        let text = |row: u16| Paint::Text {
1074            x: 0,
1075            y: i32::from(row) * UNIT,
1076            max_width: 8 * UNIT,
1077            text: "words".into(),
1078            color: Rgb(1, 2, 3),
1079            font: cellix_render::Font::default(),
1080            align_right: false,
1081            centred: false,
1082            underline: false,
1083        };
1084        let mut grid = Grid::new(20, 8, Style::default());
1085        grid.paint.extend([text(1), text(4)]);
1086        assert_eq!(row_key(&grid, 1), row_key(&grid, 4));
1087        assert_ne!(row_key(&grid, 1), row_key(&grid, 2));
1088    }
1089
1090    #[test]
1091    fn moving_a_panel_recuts_what_is_shown() {
1092        let mut b = smooth();
1093        let mut grid = pane(0);
1094        present_sized(&mut b, &grid);
1095        grid.bands = vec![4];
1096        let sent = present_sized(&mut b, &grid);
1097        assert_eq!(count(&sent, "a=d,d=a,"), 1, "the old cut goes first");
1098        assert!(
1099            sent.contains("\x1b[1;5H"),
1100            "the new one is placed: {sent:?}"
1101        );
1102    }
1103
1104    #[test]
1105    fn typing_ends_a_glide_at_once() {
1106        let mut b = smooth();
1107        let (from, to) = (pane(0), pane(3));
1108        present_sized(&mut b, &from);
1109        scroll(&mut b, &from, &to, 3);
1110        frames(&mut b, 1);
1111        b.settle();
1112        assert_eq!(b.gliding(), None);
1113        assert_eq!(count(&present_sized(&mut b, &to), "a=d,d=z,z=1"), 1);
1114    }
1115
1116    #[test]
1117    fn tiles_a_glide_is_showing_arent_thrown_away() {
1118        let mut b = smooth();
1119        let (from, to) = (pane(0), pane(3));
1120        present_sized(&mut b, &from);
1121        scroll(&mut b, &from, &to, 3);
1122        b.quota = 0;
1123        let held: Vec<u32> = b.glide.as_ref().unwrap().rows.values().copied().collect();
1124        let sent = present_sized(&mut b, &to);
1125        for id in held {
1126            assert!(
1127                !sent.contains(&format!("a=d,d=I,i={id},")),
1128                "{id} is on show"
1129            );
1130        }
1131    }
1132
1133    #[test]
1134    fn a_jump_past_the_region_or_a_tier_without_pixels_doesnt_animate() {
1135        let mut b = smooth();
1136        let (from, to) = (pane(0), pane(9));
1137        present_sized(&mut b, &from);
1138        assert_eq!(scroll(&mut b, &from, &to, 9), "");
1139        assert_eq!(b.gliding(), None);
1140        let tmux =
1141            PixelBackend::new(Sized, Placement::Placeholder, DEFAULT_QUOTA).with_smooth(SMOOTH);
1142        assert_eq!(tmux.smooth, None);
1143    }
1144
1145    fn page(top: usize) -> Grid {
1146        let mut grid = Grid::new(20, 5, Style::default());
1147        for y in 0..5 {
1148            let text = format!("line {}", top + y as usize);
1149            grid.put_str(0, y, &text, Style::default(), 20);
1150        }
1151        grid
1152    }
1153
1154    fn present(backend: &mut PixelBackend<Flat>, grid: &Grid) -> String {
1155        let mut out = Vec::new();
1156        backend.present(grid, &mut out).unwrap();
1157        String::from_utf8(out).unwrap()
1158    }
1159
1160    fn count(haystack: &str, needle: &str) -> usize {
1161        haystack.matches(needle).count()
1162    }
1163
1164    /// What a Kitty-protocol terminal keeps on screen: placements are keyed by image and
1165    /// placement id together, so a new image at a row doesn't replace the old one.
1166    #[derive(Default)]
1167    struct Screen {
1168        placements: HashMap<(u32, u32), u16>,
1169    }
1170
1171    fn field(control: &str, key: &str) -> Option<String> {
1172        control
1173            .split(',')
1174            .find_map(|kv| kv.strip_prefix(&format!("{key}=")).map(str::to_string))
1175    }
1176
1177    impl Screen {
1178        fn apply(&mut self, output: &str) {
1179            let mut rest = output;
1180            let mut row = 0;
1181            while let Some(at) = rest.find('\x1b') {
1182                rest = &rest[at..];
1183                if let Some(after) = rest.strip_prefix("\x1b_G") {
1184                    let end = after.find(['\x1b', ';']).unwrap_or(after.len());
1185                    let control = &after[..end];
1186                    let id = field(control, "i").and_then(|v| v.parse().ok());
1187                    let placement = field(control, "p").and_then(|v| v.parse().ok());
1188                    match (
1189                        field(control, "a").as_deref(),
1190                        field(control, "d").as_deref(),
1191                    ) {
1192                        (Some("p"), _) => {
1193                            self.placements
1194                                .insert((id.unwrap(), placement.unwrap()), row);
1195                        }
1196                        (Some("d"), Some("A")) => self.placements.clear(),
1197                        (Some("d"), Some("I" | "i")) => self.placements.retain(|k, _| {
1198                            k.0 != id.unwrap() || placement.is_some_and(|p| k.1 != p)
1199                        }),
1200                        _ => {}
1201                    }
1202                    rest = &rest[3..];
1203                } else {
1204                    let body = rest.strip_prefix("\x1b[").unwrap_or("");
1205                    if let Some(semi) = body.find(";1H")
1206                        && let Ok(y) = body[..semi].parse::<u16>()
1207                    {
1208                        row = y - 1;
1209                    }
1210                    rest = &rest[1..];
1211                }
1212            }
1213        }
1214
1215        fn rows(&self) -> Vec<usize> {
1216            let mut counts = vec![0; 5];
1217            for row in self.placements.values() {
1218                counts[*row as usize] += 1;
1219            }
1220            counts
1221        }
1222    }
1223
1224    #[test]
1225    fn scroll_leaves_exactly_one_tile_on_each_row() {
1226        let mut b = PixelBackend::new(Flat, Placement::Direct, DEFAULT_QUOTA);
1227        let mut screen = Screen::default();
1228        for top in [0, 1, 2, 3, 1, 0, 7, 2] {
1229            screen.apply(&present(&mut b, &page(top)));
1230            assert_eq!(screen.rows(), vec![1; 5], "after scrolling to {top}");
1231        }
1232    }
1233
1234    #[test]
1235    fn scroll_reuses_tiles_without_retransmit() {
1236        let mut b = PixelBackend::new(Flat, Placement::Direct, DEFAULT_QUOTA);
1237        assert_eq!(count(&present(&mut b, &page(0)), "a=t,"), 5);
1238        let scrolled = present(&mut b, &page(1));
1239        assert_eq!(count(&scrolled, "a=t,"), 1, "only the new line is sent");
1240        assert_eq!(count(&scrolled, "a=p,"), 5, "every row moves by reference");
1241        let back = present(&mut b, &page(0));
1242        assert_eq!(count(&back, "a=t,"), 0, "scrolling back sends nothing new");
1243    }
1244
1245    #[test]
1246    fn a_change_in_paint_makes_a_new_tile() {
1247        let mut b = PixelBackend::new(Flat, Placement::Direct, DEFAULT_QUOTA);
1248        let mut grid = page(0);
1249        present(&mut b, &grid);
1250        let bounds = cellix_render::Bounds::cells(0.0, 2.0, 4.0, 1.0);
1251        grid.panel(bounds, 0, Some(cellix_render::Rgb(1, 2, 3)), None);
1252        assert_eq!(
1253            count(&present(&mut b, &grid), "a=t,"),
1254            1,
1255            "only row 2 changed"
1256        );
1257    }
1258
1259    #[test]
1260    fn moving_the_caret_sends_only_its_rows() {
1261        let mut b = PixelBackend::new(Flat, Placement::Direct, DEFAULT_QUOTA);
1262        let mut grid = page(0);
1263        grid.set_caret(1.0, 1, 0.6);
1264        present(&mut b, &grid);
1265        let mut moved = page(0);
1266        moved.set_caret(2.0, 1, 0.6);
1267        assert_eq!(count(&present(&mut b, &moved), "a=t,"), 1, "only row 1");
1268    }
1269
1270    #[test]
1271    fn an_unchanged_frame_sends_no_graphics() {
1272        let mut b = PixelBackend::new(Flat, Placement::Direct, DEFAULT_QUOTA);
1273        present(&mut b, &page(0));
1274        let again = present(&mut b, &page(0));
1275        assert_eq!(count(&again, "\x1b_G"), 0);
1276    }
1277
1278    #[test]
1279    fn identical_rows_share_a_tile() {
1280        let mut b = PixelBackend::new(Flat, Placement::Direct, DEFAULT_QUOTA);
1281        let blank = Grid::new(20, 5, Style::default());
1282        let out = present(&mut b, &blank);
1283        assert_eq!(count(&out, "a=t,"), 1);
1284        assert_eq!(count(&out, "a=p,"), 5);
1285    }
1286
1287    #[test]
1288    fn placeholder_cells_are_passthrough_wrapped() {
1289        let mut b = PixelBackend::new(Flat, Placement::Placeholder, DEFAULT_QUOTA);
1290        let out = present(&mut b, &page(0));
1291        assert_eq!(
1292            count(&out, "\x1bPtmux;\x1b\x1b_G"),
1293            count(&out, "\x1b\x1b\\\x1b\\")
1294        );
1295        assert_eq!(count(&out.replace("\x1bPtmux;\x1b\x1b_G", ""), "\x1b_G"), 0);
1296        assert_eq!(count(&out, "a=p,U=1,"), 5);
1297        assert_eq!(count(&out, &PLACEHOLDER.to_string()), 5 * 20);
1298        assert!(out.contains("\u{10EEEE}\u{305}\u{305}"));
1299    }
1300
1301    #[test]
1302    fn placeholder_encodes_the_id_in_the_foreground() {
1303        let mut b = PixelBackend::new(Flat, Placement::Placeholder, DEFAULT_QUOTA);
1304        b.next_id = 0x01_02_03;
1305        let out = present(&mut b, &page(0));
1306        assert!(out.contains("\x1b[38;2;1;2;3m\u{10EEEE}"));
1307    }
1308
1309    #[test]
1310    fn tile_cache_respects_quota() {
1311        // Each tile is 60 bytes and a page is five tiles.
1312        let mut b = PixelBackend::new(Flat, Placement::Direct, 60 * 7);
1313        for top in 0..40 {
1314            present(&mut b, &page(top * 5));
1315        }
1316        assert!(b.used_bytes() <= 60 * 7, "used {}", b.used_bytes());
1317        assert!(b.tile_count() >= 5, "the visible page must survive");
1318    }
1319
1320    #[test]
1321    fn eviction_never_removes_a_visible_tile() {
1322        let mut b = PixelBackend::new(Flat, Placement::Direct, 60);
1323        let out = present(&mut b, &page(0));
1324        assert_eq!(count(&out, "a=d,d=I"), 0, "all five tiles are on screen");
1325        assert_eq!(b.tile_count(), 5);
1326    }
1327
1328    #[test]
1329    fn evicted_tiles_are_freed_in_the_terminal() {
1330        let mut b = PixelBackend::new(Flat, Placement::Direct, 60 * 5);
1331        present(&mut b, &page(0));
1332        let out = present(&mut b, &page(5));
1333        assert_eq!(count(&out, "a=d,d=I"), 5);
1334    }
1335
1336    #[test]
1337    fn resize_clears_the_terminal_store() {
1338        let mut b = PixelBackend::new(Flat, Placement::Direct, DEFAULT_QUOTA);
1339        present(&mut b, &page(0));
1340        let wider = Grid::new(30, 5, Style::default());
1341        let out = present(&mut b, &wider);
1342        assert!(out.contains("a=d,d=A"));
1343        assert_eq!(b.tile_count(), 1);
1344    }
1345}