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