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