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