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
15pub const DEFAULT_QUOTA: usize = 64 * 1024 * 1024;
18
19const CHUNK: usize = 4096;
20const PLACEHOLDER: char = '\u{10EEEE}';
21const DIACRITIC_ZERO: char = '\u{305}';
23
24const SCROLL_LAYER: u32 = 1;
26const FIRST_STRIP: usize = 100_000;
28const BAND_PLACEMENTS: usize = 10_000;
30const STRIP_ROWS: i32 = 1 << 20;
32const ARRIVED: f32 = 0.5;
34const KEPT_SCREENS: i32 = 3;
36
37#[derive(Clone, Copy, Debug, PartialEq, Eq)]
39pub struct Smooth {
40 pub frame: Duration,
42 pub ease: Duration,
44}
45
46#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
50pub struct Bleed {
51 pub cols: u16,
53 pub rows: u16,
55 pub padding: usize,
59}
60
61fn 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
74pub struct OwnRows {
75 pub row: usize,
77 pub line: usize,
79}
80
81struct Tile {
82 id: u32,
83 bytes: usize,
84 last_used: u64,
85}
86
87struct Glide {
91 area: Rect,
92 rows: BTreeMap<i32, u32>,
94 target: i32,
96 at: f32,
98 last: Instant,
99 placed: HashSet<i32>,
101}
102
103#[derive(Clone, Copy, Debug, PartialEq, Eq)]
105pub enum Placement {
106 Direct,
108 Placeholder,
111}
112
113pub struct PixelBackend<R> {
116 rasterizer: R,
117 placement: Placement,
118 tiles: HashMap<u64, Tile>,
119 shown: Vec<Vec<Option<u32>>>,
121 bands: Vec<u16>,
123 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 scrolling: bool,
133 bleed: Bleed,
134 glide: Option<Glide>,
135 cell: Option<(i32, i32)>,
137 own: Option<OwnRows>,
138 lines: u16,
140 foot: u16,
142 work: crate::Work,
144 files: Option<TileFiles>,
146}
147
148pub fn row_key(grid: &Grid, y: u16) -> u64 {
150 band_key(grid, y, (0, grid.width()))
151}
152
153fn 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 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 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 for paint in grid.paint_on_row(y).filter(meets) {
180 paint.on_row(top).hash(&mut hasher);
181 }
182 hasher.finish()
183}
184
185fn 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 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 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 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 fn runs_on(&self, rows: u16) -> bool {
264 self.bleed.rows > 0 || self.spare(rows) > 0
265 }
266
267 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 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 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 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 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 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 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 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 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 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 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 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 fn spans(&self, grid: &Grid, y: u16) -> Vec<(u16, u16)> {
477 let width = grid.width();
478 let own = grid.row_bands.as_ref().filter(|(row, _)| *row == y);
479 let bands = match own {
480 Some((_, bands)) => bands,
481 None if y + 1 == grid.height() => return vec![(0, width)],
482 None => &grid.bands,
483 };
484 let inside = bands.iter().copied().filter(|x| *x > 0 && *x < width);
485 let edges: Vec<u16> = [0].into_iter().chain(inside).chain([width]).collect();
486 edges.windows(2).map(|edge| (edge[0], edge[1])).collect()
487 }
488
489 fn band_tiles(&mut self, out: &mut Vec<u8>, grid: &Grid, y: u16) -> Vec<u32> {
491 let spans = self.spans(grid, y);
492 let bottom = y + 1 == grid.height() && self.runs_on(grid.height());
495 let (above, drop) = self.stand(grid.height(), grid.foot, y);
496 let stood = ((above as u64) << 32 | drop as u64).wrapping_mul(0x9e37_79b9_7f4a_7c15);
497 let keys: Vec<u64> = spans
498 .iter()
499 .map(|span| band_key(grid, y, *span).rotate_left(u32::from(bottom)) ^ stood)
500 .collect();
501 if keys.iter().any(|key| !self.tiles.contains_key(key)) {
502 let image = self.rasterizer.row(grid, y);
503 self.work.rows += 1;
504 let cols = grid.width();
505 let cell = image.width / cols.max(1) as usize;
506 self.cell = Some((cell as i32, image.height as i32));
507 let image = self.bled(image, grid, y);
508 for (&(from, to), key) in spans.iter().zip(&keys) {
509 if self.tiles.contains_key(key) {
510 continue;
511 }
512 let right = if to == cols {
513 image.width
514 } else {
515 to as usize * cell
516 };
517 let part = crop(&image, from as usize * cell, right);
518 let id = self.new_id();
519 self.transmit(out, id, &part);
520 self.work.tiles += 1;
521 if self.placement == Placement::Placeholder {
522 let wide = to - from;
523 self.apc(out, &format!("a=p,U=1,i={id},c={wide},r=1,q=2"), b"");
524 }
525 self.used += part.rgb.len();
526 let tile = Tile {
527 id,
528 bytes: part.rgb.len(),
529 last_used: self.frame,
530 };
531 self.tiles.insert(*key, tile);
532 }
533 }
534 let frame = self.frame;
535 let mut use_tile = |key: &u64| {
536 let tile = self.tiles.get_mut(key).expect("made above");
537 tile.last_used = frame;
538 tile.id
539 };
540 keys.iter().map(&mut use_tile).collect()
541 }
542
543 fn start_glide(&self, area: Rect, band: usize) -> Option<Glide> {
545 let shown = (area.y..area.bottom()).enumerate().map(|(index, y)| {
546 let id = (*self.shown.get(y as usize)?.get(band)?)?;
547 Some((index as i32, id))
548 });
549 Some(Glide {
550 area,
551 rows: shown.collect::<Option<_>>()?,
552 target: 0,
553 at: 0.0,
554 last: Instant::now(),
555 placed: HashSet::new(),
556 })
557 }
558
559 fn new_id(&mut self) -> u32 {
560 let id = self.next_id;
561 self.next_id = (self.next_id + 1) & 0xff_ffff;
562 if self.next_id == 0 {
563 self.next_id = 1;
564 }
565 id
566 }
567
568 fn evict(&mut self, out: &mut Vec<u8>, on_screen: &HashSet<u32>) {
570 while self.used > self.quota {
571 let oldest = self
572 .tiles
573 .iter()
574 .filter(|(_, t)| !on_screen.contains(&t.id))
575 .min_by_key(|(_, t)| t.last_used)
576 .map(|(key, _)| *key);
577 let Some(key) = oldest else { return };
578 let tile = self.tiles.remove(&key).expect("key came from the map");
579 self.used -= tile.bytes;
580 self.apc(out, &format!("a=d,d=I,i={},q=2", tile.id), b"");
581 }
582 }
583
584 pub fn tile_count(&self) -> usize {
585 self.tiles.len()
586 }
587
588 pub fn used_bytes(&self) -> usize {
589 self.used
590 }
591}
592
593impl<R: Rasterizer> Backend for PixelBackend<R> {
594 fn present(&mut self, grid: &Grid, out: &mut dyn Write) -> io::Result<()> {
595 let mut bytes = Vec::new();
596 bytes.extend_from_slice(b"\x1b[?2026h\x1b[?25l");
597 let begun = bytes.len();
599 let size = (grid.width(), grid.height());
600 if size != self.size {
601 self.apc(&mut bytes, "a=d,d=A,q=2", b"");
603 bytes.extend_from_slice(b"\x1b[2J");
604 self.tiles.clear();
605 self.glide = None;
606 self.used = 0;
607 self.shown = vec![Vec::new(); grid.height() as usize];
608 self.size = size;
609 }
610 if grid.bands != self.bands {
611 if self.placement == Placement::Direct {
613 self.apc(&mut bytes, "a=d,d=a,q=2", b"");
614 }
615 self.shown = vec![Vec::new(); grid.height() as usize];
616 self.bands.clone_from(&grid.bands);
617 self.glide = None;
618 self.scrolling = false;
619 }
620 if grid.row_bands != self.row_bands {
621 let rows = [&self.row_bands, &grid.row_bands].map(|own| own.as_ref().map(|o| o.0));
623 for y in rows.into_iter().flatten() {
624 let Some(shown) = self.shown.get_mut(y as usize) else {
625 continue;
626 };
627 let old: Vec<(usize, u32)> = std::mem::take(shown)
628 .into_iter()
629 .enumerate()
630 .filter_map(|(band, id)| Some((band, id?)))
631 .collect();
632 if self.placement == Placement::Direct {
633 for (band, id) in old {
634 let number = place_number(y, band);
635 self.apc(&mut bytes, &format!("a=d,d=i,i={id},p={number},q=2"), b"");
636 }
637 }
638 }
639 self.row_bands.clone_from(&grid.row_bands);
640 }
641 self.frame += 1;
642 self.foot = grid.foot;
643 let mut on_screen = HashSet::new();
644 for y in 0..grid.height() {
645 let bottom = y + 1 == grid.height() && self.bleed.rows > 0;
646 let spans = self.spans(grid, y);
647 let ids = self.band_tiles(&mut bytes, grid, y);
648 self.shown[y as usize].resize(ids.len(), None);
649 for (band, (id, span)) in ids.into_iter().zip(spans).enumerate() {
650 on_screen.insert(id);
651 let old = self.shown[y as usize][band];
652 if old == Some(id) {
653 continue;
654 }
655 if let (Placement::Direct, Some(old)) = (self.placement, old) {
658 let number = place_number(y, band);
659 self.apc(&mut bytes, &format!("a=d,d=i,i={old},p={number},q=2"), b"");
660 }
661 let rows = 1 + if bottom { self.bleed.rows } else { 0 };
662 let last = span.1 == grid.width();
663 self.place(&mut bytes, id, (y, band), span, rows, last);
664 self.shown[y as usize][band] = Some(id);
665 }
666 }
667 if std::mem::take(&mut self.scrolling) {
668 self.apc(&mut bytes, &format!("a=d,d=z,z={SCROLL_LAYER},q=2"), b"");
669 }
670 on_screen.extend(self.glide.iter().flat_map(|g| g.rows.values().copied()));
671 self.evict(&mut bytes, &on_screen);
672 if bytes.len() == begun {
673 return Ok(());
674 }
675 bytes.extend_from_slice(b"\x1b[?2026l");
676 out.write_all(&bytes)?;
677 out.flush()
678 }
679
680 fn scroll(
681 &mut self,
682 from: &Grid,
683 to: &Grid,
684 area: Rect,
685 rows: i32,
686 out: &mut dyn Write,
687 ) -> io::Result<()> {
688 let same_size = (from.width(), from.height()) == (to.width(), to.height());
689 let can_glide = self.smooth.is_some()
690 && self.cell.is_some()
691 && same_size
692 && self.size == (to.width(), to.height())
693 && rows != 0
694 && rows.abs() < area.h as i32;
695 let spans = self.spans(to, area.y);
696 let band = spans
697 .iter()
698 .position(|span| *span == (area.x, area.right()));
699 let same_area = self.glide.as_ref().is_none_or(|g| g.area == area);
700 let (true, true, Some(band)) = (can_glide, same_area, band) else {
701 self.settle();
702 return Ok(());
703 };
704 let Some(mut glide) = self.glide.take().or_else(|| self.start_glide(area, band)) else {
705 return Ok(());
706 };
707 let mut bytes = Vec::new();
708 glide.target += rows;
709 for (index, y) in (area.y..area.bottom()).enumerate() {
710 let row = glide.target + index as i32;
711 if let Entry::Vacant(place) = glide.rows.entry(row) {
712 place.insert(self.band_tiles(&mut bytes, to, y)[band]);
713 }
714 }
715 self.glide = Some(glide);
716 out.write_all(&bytes)?;
717 out.flush()
718 }
719
720 fn gliding(&self) -> Option<Duration> {
721 self.glide.as_ref()?;
722 self.smooth.map(|smooth| smooth.frame)
723 }
724
725 fn glide(&mut self, now: Instant, out: &mut dyn Write) -> io::Result<()> {
726 let (Some(mut glide), Some(smooth), Some((cell_w, cell_h))) =
727 (self.glide.take(), self.smooth, self.cell)
728 else {
729 return Ok(());
730 };
731 let target = (glide.target * cell_h) as f32;
732 let window = glide.area.h as i32 * cell_h;
733 glide.at = glide
735 .at
736 .clamp(target - window as f32, target + window as f32);
737 let passed = now.duration_since(glide.last).as_secs_f32();
738 glide.last = now;
739 let left = (-passed / smooth.ease.as_secs_f32()).exp();
740 glide.at = target + (glide.at - target) * left;
741 if (glide.at - target).abs() < ARRIVED {
742 glide.at = target;
743 }
744 let at = glide.at.round() as i32;
745 let wide = i32::from(glide.area.w) * cell_w;
746 let mut bytes = b"\x1b[?2026h".to_vec();
747 for (&row, &id) in &glide.rows {
748 let top = row * cell_h - at;
749 let (clip_top, clip_end) = ((-top).max(0), cell_h.min(window - top));
750 let number = FIRST_STRIP + row.rem_euclid(STRIP_ROWS) as usize;
751 if clip_top >= clip_end {
752 if glide.placed.remove(&row) {
753 self.apc(&mut bytes, &format!("a=d,d=i,i={id},p={number},q=2"), b"");
754 }
755 continue;
756 }
757 let pixel = top.max(0);
758 let y = i32::from(glide.area.y) + pixel / cell_h;
759 let _ = write!(bytes, "\x1b[{};{}H", y + 1, glide.area.x + 1);
760 let control = format!(
761 "a=p,i={id},p={number},x=0,y={clip_top},w={wide},h={},Y={},z={SCROLL_LAYER},C=1,q=2",
762 clip_end - clip_top,
763 pixel % cell_h,
764 );
765 self.apc(&mut bytes, &control, b"");
766 glide.placed.insert(row);
767 }
768 bytes.extend_from_slice(b"\x1b[?2026l");
769 out.write_all(&bytes)?;
770 out.flush()?;
771 let reach = glide.area.h as i32 * KEPT_SCREENS;
773 let view = at / cell_h;
774 glide
775 .rows
776 .retain(|row, _| (row - view).abs() <= reach || glide.placed.contains(row));
777 if glide.at == target {
778 self.scrolling = true;
779 } else {
780 self.glide = Some(glide);
781 }
782 Ok(())
783 }
784
785 fn settle(&mut self) {
786 self.scrolling |= self.glide.take().is_some();
787 }
788
789 fn invalidate(&mut self) {
790 self.size = (0, 0);
791 self.glide = None;
792 }
793
794 fn set_lines(&mut self, lines: u16) {
795 if self.own.is_some() && lines != self.lines {
796 self.size = (0, 0);
798 }
799 self.lines = lines;
800 }
801
802 fn foot_drops(&self, rows: u16, foot: u16) -> Vec<usize> {
803 self.drops(rows, foot)
804 }
805
806 fn take_work(&mut self) -> crate::Work {
807 std::mem::take(&mut self.work)
808 }
809}
810
811#[cfg(test)]
812mod tests {
813 use super::*;
814 use cellix_render::Style;
815
816 #[test]
819 fn a_row_under_a_tall_shape_is_known_wherever_it_stands() {
820 let mut grid = Grid::new(10, 30, Style::default());
821 let sheet = cellix_render::Bounds::cells(1.0, 0.0, 8.0, 30.0);
822 grid.panel(sheet, 40, Some(cellix_render::Rgb(250, 250, 250)), None);
823 assert_eq!(row_key(&grid, 10), row_key(&grid, 15));
824 assert_ne!(
825 row_key(&grid, 0),
826 row_key(&grid, 15),
827 "the rounded top shows in row 0"
828 );
829 }
830
831 struct Flat;
833
834 impl Rasterizer for Flat {
835 fn row(&mut self, grid: &Grid, _y: u16) -> Image {
836 Image {
837 width: grid.width() as usize,
838 height: 1,
839 rgb: vec![9; grid.width() as usize * 3],
840 }
841 }
842 }
843
844 struct Sized;
846
847 impl Rasterizer for Sized {
848 fn row(&mut self, grid: &Grid, y: u16) -> Image {
849 let tone = grid.row(y)[9].symbol.bytes().next().unwrap_or(0);
850 let (width, height) = (grid.width() as usize * 8, 16);
851 Image {
852 width,
853 height,
854 rgb: vec![tone; width * height * 3],
855 }
856 }
857 }
858
859 fn pane(top: usize) -> Grid {
861 let mut grid = Grid::new(20, 8, Style::default());
862 grid.bands = vec![PANE.x];
863 for y in 0..8 {
864 grid.put_str(0, y, &format!("side{y}"), Style::default(), 8);
865 let letter = char::from(b'a' + (top + y as usize) as u8);
866 grid.put_str(9, y, &letter.to_string(), Style::default(), 20);
867 }
868 grid
869 }
870
871 const PANE: Rect = Rect {
872 x: 8,
873 y: 1,
874 w: 12,
875 h: 6,
876 };
877
878 const STEP: Duration = Duration::from_millis(8);
879 const SMOOTH: Smooth = Smooth {
880 frame: STEP,
881 ease: Duration::from_millis(40),
882 };
883
884 fn smooth() -> PixelBackend<Sized> {
885 PixelBackend::new(Sized, Placement::Direct, DEFAULT_QUOTA).with_smooth(SMOOTH)
886 }
887
888 fn scroll(b: &mut PixelBackend<Sized>, from: &Grid, to: &Grid, rows: i32) -> String {
889 let mut out = Vec::new();
890 b.scroll(from, to, PANE, rows, &mut out).unwrap();
891 String::from_utf8(out).unwrap()
892 }
893
894 fn present_sized(b: &mut PixelBackend<Sized>, grid: &Grid) -> String {
895 let mut out = Vec::new();
896 b.present(grid, &mut out).unwrap();
897 String::from_utf8(out).unwrap()
898 }
899
900 #[test]
904 fn a_taller_row_stands_between_the_terminals_lines() {
905 struct Tall;
906 impl Rasterizer for Tall {
907 fn row(&mut self, grid: &Grid, _y: u16) -> Image {
908 let (width, height) = (grid.width() as usize * 8, 22);
909 Image {
910 width,
911 height,
912 rgb: vec![7; width * height * 3],
913 }
914 }
915 }
916 let own = OwnRows { row: 22, line: 16 };
917 let mut b = PixelBackend::new(Tall, Placement::Direct, DEFAULT_QUOTA).with_own_rows(own);
918 b.set_lines(6);
920 let grid = Grid::new(12, 4, Style::default());
921 let mut out = Vec::new();
922 b.present(&grid, &mut out).unwrap();
923 let output = String::from_utf8(out).unwrap();
924 let placed: Vec<(String, String)> = output
925 .split("\x1b[")
926 .filter_map(|part| {
927 let (at, rest) = part.split_once("H\x1b_Ga=p,")?;
928 let into = rest.split(",Y=").nth(1)?.split(',').next()?;
929 Some((at.to_string(), into.to_string()))
930 })
931 .collect();
932 let want = [("1;1", "0"), ("2;1", "6"), ("3;1", "12"), ("5;1", "2")];
933 let want: Vec<(String, String)> = want
934 .iter()
935 .map(|(at, into)| (at.to_string(), into.to_string()))
936 .collect();
937 assert_eq!(
938 placed, want,
939 "the line each row starts in, and how far into it"
940 );
941 assert!(!output.contains(",r="), "a tile isn't stretched over lines");
942 let heights: Vec<&str> = output
943 .split("a=t,")
944 .skip(1)
945 .filter_map(|part| part.split(",v=").nth(1)?.split(',').next())
946 .collect();
947 assert_eq!(
948 heights.last(),
949 Some(&"30"),
950 "the last row covers the 8 pixels left"
951 );
952 assert!(heights[..heights.len() - 1].iter().all(|h| *h == "22"));
953 b.set_lines(7);
955 let mut out = Vec::new();
956 b.present(&grid, &mut out).unwrap();
957 let output = String::from_utf8(out).unwrap();
958 assert!(
959 output.contains(",v=46,"),
960 "8 pixels and a line of 16: {output:?}"
961 );
962 let mut held =
964 PixelBackend::new(Tall, Placement::Placeholder, DEFAULT_QUOTA).with_own_rows(own);
965 let mut out = Vec::new();
966 held.present(&grid, &mut out).unwrap();
967 assert!(!String::from_utf8(out).unwrap().contains(",Y="));
968 }
969
970 #[test]
975 fn the_last_row_stands_in_the_middle_of_what_is_under_the_sheets() {
976 struct Blank;
977 impl Rasterizer for Blank {
978 fn row(&mut self, grid: &Grid, _y: u16) -> Image {
979 let (width, height) = (grid.width() as usize * 8, 22);
980 Image {
981 width,
982 height,
983 rgb: vec![0; width * height * 3],
984 }
985 }
986 }
987 let own = OwnRows { row: 22, line: 16 };
988 let grid = Grid::new(12, 4, Style::default());
989 let lit = |width: usize| Image {
990 width,
991 height: 22,
992 rgb: vec![255; width * 22 * 3],
993 };
994 let starts = |image: &Image| {
995 (0..image.height)
996 .position(|y| image.rgb[y * image.width * 3] == 255)
997 .unwrap()
998 };
999 let mut plain =
1002 PixelBackend::new(Blank, Placement::Direct, DEFAULT_QUOTA).with_own_rows(own);
1003 plain.set_lines(6);
1004 let tile = plain.bled(lit(96), &grid, 3);
1005 assert_eq!((tile.height, starts(&tile)), (30, 4));
1006 let mut padded = PixelBackend::new(Blank, Placement::Direct, DEFAULT_QUOTA)
1008 .with_own_rows(own)
1009 .with_bleed(Bleed {
1010 cols: 0,
1011 rows: 1,
1012 padding: 6,
1013 });
1014 padded.set_lines(6);
1015 let tile = padded.bled(lit(96), &grid, 3);
1016 assert_eq!((tile.height, starts(&tile)), (46, 7));
1017 let tile = padded.bled(lit(96), &grid, 2);
1019 assert_eq!((tile.height, starts(&tile)), (22, 0));
1020 }
1021
1022 #[test]
1027 fn a_foot_of_two_rows_stands_evenly_under_the_sheets() {
1028 struct Blank;
1029 impl Rasterizer for Blank {
1030 fn row(&mut self, grid: &Grid, _y: u16) -> Image {
1031 let (width, height) = (grid.width() as usize * 8, 22);
1032 Image {
1033 width,
1034 height,
1035 rgb: vec![255; width * height * 3],
1036 }
1037 }
1038 }
1039 let own = OwnRows { row: 22, line: 16 };
1040 let mut grid = Grid::new(12, 4, Style::default());
1041 grid.foot = 2;
1042 let lit = || Image {
1043 width: 96,
1044 height: 22,
1045 rgb: vec![255; 96 * 22 * 3],
1046 };
1047 let stands = |image: &Image| {
1049 let lit = |y: &usize| image.rgb[y * image.width * 3] == 255;
1050 let from = (0..image.height).position(|y| lit(&y)).unwrap();
1051 let to = (0..image.height).rposition(|y| lit(&y)).unwrap() + 1;
1052 (image.height, from, to)
1053 };
1054 let mut b = PixelBackend::new(Blank, Placement::Direct, DEFAULT_QUOTA)
1058 .with_own_rows(own)
1059 .with_bleed(Bleed {
1060 cols: 0,
1061 rows: 1,
1062 padding: 6,
1063 });
1064 b.set_lines(7);
1065 assert_eq!(b.foot_drops(4, 2), [10, 20]);
1066 assert_eq!(
1067 stands(&b.bled(lit(), &grid, 2)),
1068 (32, 10, 32),
1069 "the first is 10 px down, in a tile that ends where its picture does"
1070 );
1071 assert_eq!(
1072 stands(&b.bled(lit(), &grid, 3)),
1073 (52, 10, 32),
1074 "the second begins there, 10 px further down, and runs on to the window's end"
1075 );
1076 assert_eq!(
1077 stands(&b.bled(lit(), &grid, 1)),
1078 (22, 0, 22),
1079 "no row of a sheet moves"
1080 );
1081 let placed = |output: &str| -> Vec<(String, String)> {
1082 output
1083 .split("\x1b[")
1084 .filter_map(|part| {
1085 let (at, rest) = part.split_once("H\x1b_Ga=p,")?;
1086 let into = rest.split(",Y=").nth(1)?.split(',').next()?;
1087 Some((at.to_string(), into.to_string()))
1088 })
1089 .collect()
1090 };
1091 let pairs = |want: &[(&str, &str)]| -> Vec<(String, String)> {
1092 want.iter()
1093 .map(|(at, into)| (at.to_string(), into.to_string()))
1094 .collect()
1095 };
1096 let mut out = Vec::new();
1097 b.present(&grid, &mut out).unwrap();
1098 assert_eq!(
1100 placed(&String::from_utf8(out).unwrap()),
1101 pairs(&[("1;1", "0"), ("2;1", "6"), ("3;1", "12"), ("5;1", "12")]),
1102 "the second row of the foot is placed under the first's picture"
1103 );
1104 grid.foot = 1;
1107 assert_eq!(b.foot_drops(4, 1), [15]);
1108 assert_eq!(stands(&b.bled(lit(), &grid, 2)), (22, 0, 22));
1109 assert_eq!(stands(&b.bled(lit(), &grid, 3)), (62, 15, 37));
1110 let mut out = Vec::new();
1111 b.present(&grid, &mut out).unwrap();
1112 assert_eq!(
1113 placed(&String::from_utf8(out).unwrap()),
1114 pairs(&[("3;1", "12"), ("5;1", "2")]),
1115 "both are drawn again, each at its own place"
1116 );
1117 let lines = PixelBackend::new(Blank, Placement::Direct, DEFAULT_QUOTA);
1119 assert!(lines.foot_drops(4, 2).is_empty());
1120 }
1121
1122 #[test]
1123 fn the_window_fills_to_its_edges() {
1124 let mut b = PixelBackend::new(Sized, Placement::Direct, DEFAULT_QUOTA).with_bleed(Bleed {
1125 cols: 2,
1126 rows: 1,
1127 padding: 6,
1128 });
1129 let grid = Grid::new(12, 2, Style::default());
1130 let output = present_sized(&mut b, &grid);
1131 let widths: Vec<String> = output
1132 .split("\x1b_G")
1133 .filter_map(|c| field(c, "s"))
1134 .collect();
1135 let tall: Vec<String> = output
1136 .split("\x1b_G")
1137 .filter_map(|c| field(c, "v"))
1138 .collect();
1139 assert!(
1140 widths.iter().all(|w| w == "112"),
1141 "two more cells: {widths:?}"
1142 );
1143 assert!(
1144 tall.contains(&"32".to_string()),
1145 "the last row takes two: {tall:?}"
1146 );
1147 assert!(tall.contains(&"16".to_string()));
1148 let placed: Vec<&str> = output
1149 .split("\x1b_G")
1150 .filter(|c| c.starts_with("a=p"))
1151 .collect();
1152 assert!(placed.iter().all(|c| c.contains(",c=14,")), "{placed:?}");
1153 assert!(placed[1].contains(",r=2,"), "{placed:?}");
1154 let mut placeholders = PixelBackend::new(Sized, Placement::Placeholder, DEFAULT_QUOTA)
1155 .with_bleed(Bleed {
1156 cols: 2,
1157 rows: 1,
1158 padding: 6,
1159 });
1160 assert_eq!(
1161 placeholders.bleed,
1162 Bleed::default(),
1163 "placeholders are cells"
1164 );
1165 let _ = present_sized(&mut placeholders, &grid);
1166 }
1167
1168 #[test]
1169 fn a_tall_heading_keeps_its_lower_half() {
1170 let mut grid = Grid::new(20, 8, Style::default());
1171 let big = cellix_render::Font {
1172 size: 150,
1173 ..cellix_render::Font::default()
1174 };
1175 grid.text_run((1.0, 3.5), 20.0, "Workflow", (Rgb(9, 9, 9), false), big);
1176 assert_ne!(
1177 row_key(&grid, 2),
1178 row_key(&grid, 4),
1179 "the row above and the row below show different slices"
1180 );
1181 let blank = Grid::new(20, 8, Style::default());
1182 assert_eq!(
1183 row_key(&blank, 2),
1184 row_key(&blank, 4),
1185 "empty rows still share a tile, which scrolling depends on"
1186 );
1187 }
1188
1189 fn frames(b: &mut PixelBackend<Sized>, count: u32) -> String {
1191 let mut out = Vec::new();
1192 for _ in 0..count {
1193 let now = b.glide.as_ref().map_or_else(Instant::now, |g| g.last) + STEP;
1194 b.glide(now, &mut out).unwrap();
1195 }
1196 String::from_utf8(out).unwrap()
1197 }
1198
1199 #[test]
1200 fn regions_scroll_by_pixels() {
1201 let mut b = smooth();
1202 let (from, to) = (pane(0), pane(3));
1203 present_sized(&mut b, &from);
1204 scroll(&mut b, &from, &to, 3);
1205 let moving = frames(&mut b, 4);
1206 assert_eq!(count(&moving, "\x1b[?2026h"), 4, "every frame is atomic");
1207 let offsets: HashSet<String> = moving
1208 .split(",Y=")
1209 .skip(1)
1210 .map(|rest| rest.split(',').next().unwrap().to_string())
1211 .collect();
1212 assert!(
1213 offsets.iter().any(|y| y != "0"),
1214 "it sits between cells: {offsets:?}"
1215 );
1216 assert!(moving.contains(",z=1,"), "above the row tiles");
1217 assert!(
1218 !moving.contains("\x1b[1;9H"),
1219 "nothing lands on the row above the pane"
1220 );
1221 assert!(
1222 !moving.contains(";1H"),
1223 "the sidebar's column is never touched"
1224 );
1225 frames(&mut b, 200);
1226 assert_eq!(b.gliding(), None, "it gets there");
1227 let settled = present_sized(&mut b, &to);
1228 assert_eq!(
1229 count(&settled, "a=d,d=z,z=1"),
1230 1,
1231 "the layer goes with the final page"
1232 );
1233 assert_eq!(count(&present_sized(&mut b, &to), "a=d,d=z"), 0);
1234 }
1235
1236 #[test]
1237 fn a_glide_moves_quickly_at_first_and_settles_gently() {
1238 let mut b = smooth();
1239 let (from, to) = (pane(0), pane(3));
1240 present_sized(&mut b, &from);
1241 scroll(&mut b, &from, &to, 3);
1242 let mut places = vec![0.0];
1243 while b.gliding().is_some() {
1244 frames(&mut b, 1);
1245 places.push(b.glide.as_ref().map_or(48.0, |g| g.at));
1246 assert!(places.len() < 80, "it takes too long: {places:?}");
1247 }
1248 let steps: Vec<f32> = places.windows(2).map(|p| p[1] - p[0]).collect();
1249 assert!(
1250 steps.iter().all(|step| *step >= 0.0),
1251 "never back: {steps:?}"
1252 );
1253 assert!(steps[0] > steps[steps.len() / 2], "it eases: {steps:?}");
1254 }
1255
1256 #[test]
1257 fn a_new_notch_carries_on_from_where_it_is() {
1258 let mut b = smooth();
1259 let (first, second, third) = (pane(0), pane(2), pane(4));
1260 present_sized(&mut b, &first);
1261 scroll(&mut b, &first, &second, 2);
1262 frames(&mut b, 3);
1263 let at = b.glide.as_ref().unwrap().at;
1264 scroll(&mut b, &second, &third, 2);
1265 let glide = b.glide.as_ref().unwrap();
1266 assert_eq!((glide.at, glide.target), (at, 4), "no restart, no jump");
1267 }
1268
1269 #[test]
1270 fn the_wrong_way_turns_round_smoothly() {
1271 let mut b = smooth();
1272 let (first, second) = (pane(0), pane(2));
1273 present_sized(&mut b, &first);
1274 scroll(&mut b, &first, &second, 2);
1275 frames(&mut b, 3);
1276 let at = b.glide.as_ref().unwrap().at;
1277 scroll(&mut b, &second, &first, -2);
1278 frames(&mut b, 1);
1279 let now = b.glide.as_ref().unwrap().at;
1280 assert!(now < at && now > 0.0, "{at} then {now}");
1281 }
1282
1283 #[test]
1284 fn scrolling_only_sends_what_the_terminal_hasnt_seen() {
1285 let mut b = smooth();
1286 let (from, to) = (pane(0), pane(1));
1287 present_sized(&mut b, &from);
1288 let sent = count(&scroll(&mut b, &from, &to, 1), "a=t,");
1289 assert!(sent <= 1, "at most the one new row, not {sent}");
1290 assert_eq!(
1291 count(&frames(&mut b, 5), "a=t,"),
1292 0,
1293 "moving costs no pictures"
1294 );
1295 }
1296
1297 #[test]
1298 fn a_region_clips_at_its_edges() {
1299 let mut b = smooth();
1300 let (from, to) = (pane(0), pane(1));
1301 present_sized(&mut b, &from);
1302 scroll(&mut b, &from, &to, 1);
1303 let moving = frames(&mut b, 3);
1304 assert!(
1305 moving.contains(",x=0,y="),
1306 "the pane's own tiles: {moving:?}"
1307 );
1308 let clipped = moving
1309 .split(",y=")
1310 .skip(1)
1311 .any(|rest| !rest.starts_with("0,"));
1312 assert!(clipped, "the top row loses its top part: {moving:?}");
1313 }
1314
1315 #[test]
1316 fn scrolling_back_needs_nothing_new() {
1317 let mut b = smooth();
1318 let (from, to) = (pane(0), pane(2));
1319 present_sized(&mut b, &from);
1320 scroll(&mut b, &from, &to, 2);
1321 frames(&mut b, 200);
1322 present_sized(&mut b, &to);
1323 let back = scroll(&mut b, &to, &from, -2);
1324 assert_eq!(
1325 count(&back, "a=t,"),
1326 0,
1327 "the tiles are in the terminal already"
1328 );
1329 }
1330
1331 #[test]
1332 fn a_scrolled_page_keeps_its_tiles_whatever_stands_beside_it() {
1333 let mut b = smooth();
1334 let (from, to) = (pane(0), pane(3));
1335 present_sized(&mut b, &from);
1336 scroll(&mut b, &from, &to, 3);
1337 frames(&mut b, 200);
1338 let settled = present_sized(&mut b, &to);
1339 assert!(
1341 count(&settled, "a=t,") <= 2,
1342 "the region sent nothing: {settled:?}"
1343 );
1344 }
1345
1346 #[test]
1347 fn a_change_in_one_band_sends_only_that_band() {
1348 let mut b = smooth();
1349 let mut grid = pane(0);
1350 present_sized(&mut b, &grid);
1351 grid.put_str(10, 3, "x", Style::default(), 20);
1352 let sent = present_sized(&mut b, &grid);
1353 assert_eq!(count(&sent, "a=t,"), 1, "{sent:?}");
1354 }
1355
1356 #[test]
1357 fn typeset_rows_keep_their_tiles_as_they_move() {
1358 let text = |row: u16| Paint::Text {
1359 x: 0,
1360 y: i32::from(row) * UNIT,
1361 max_width: 8 * UNIT,
1362 text: "words".into(),
1363 color: Rgb(1, 2, 3),
1364 font: cellix_render::Font::default(),
1365 align_right: false,
1366 centred: false,
1367 underline: false,
1368 };
1369 let mut grid = Grid::new(20, 8, Style::default());
1370 grid.paint.extend([text(1), text(4)]);
1371 assert_eq!(row_key(&grid, 1), row_key(&grid, 4));
1372 assert_ne!(row_key(&grid, 1), row_key(&grid, 2));
1373 }
1374
1375 #[test]
1376 fn moving_a_panel_recuts_what_is_shown() {
1377 let mut b = smooth();
1378 let mut grid = pane(0);
1379 present_sized(&mut b, &grid);
1380 grid.bands = vec![4];
1381 let sent = present_sized(&mut b, &grid);
1382 assert_eq!(count(&sent, "a=d,d=a,"), 1, "the old cut goes first");
1383 assert!(
1384 sent.contains("\x1b[1;5H"),
1385 "the new one is placed: {sent:?}"
1386 );
1387 }
1388
1389 #[test]
1390 fn typing_ends_a_glide_at_once() {
1391 let mut b = smooth();
1392 let (from, to) = (pane(0), pane(3));
1393 present_sized(&mut b, &from);
1394 scroll(&mut b, &from, &to, 3);
1395 frames(&mut b, 1);
1396 b.settle();
1397 assert_eq!(b.gliding(), None);
1398 assert_eq!(count(&present_sized(&mut b, &to), "a=d,d=z,z=1"), 1);
1399 }
1400
1401 #[test]
1402 fn tiles_a_glide_is_showing_arent_thrown_away() {
1403 let mut b = smooth();
1404 let (from, to) = (pane(0), pane(3));
1405 present_sized(&mut b, &from);
1406 scroll(&mut b, &from, &to, 3);
1407 b.quota = 0;
1408 let held: Vec<u32> = b.glide.as_ref().unwrap().rows.values().copied().collect();
1409 let sent = present_sized(&mut b, &to);
1410 for id in held {
1411 assert!(
1412 !sent.contains(&format!("a=d,d=I,i={id},")),
1413 "{id} is on show"
1414 );
1415 }
1416 }
1417
1418 #[test]
1419 fn a_jump_past_the_region_or_a_tier_without_pixels_doesnt_animate() {
1420 let mut b = smooth();
1421 let (from, to) = (pane(0), pane(9));
1422 present_sized(&mut b, &from);
1423 assert_eq!(scroll(&mut b, &from, &to, 9), "");
1424 assert_eq!(b.gliding(), None);
1425 let tmux =
1426 PixelBackend::new(Sized, Placement::Placeholder, DEFAULT_QUOTA).with_smooth(SMOOTH);
1427 assert_eq!(tmux.smooth, None);
1428 }
1429
1430 fn page(top: usize) -> Grid {
1431 let mut grid = Grid::new(20, 5, Style::default());
1432 for y in 0..5 {
1433 let text = format!("line {}", top + y as usize);
1434 grid.put_str(0, y, &text, Style::default(), 20);
1435 }
1436 grid
1437 }
1438
1439 fn present(backend: &mut PixelBackend<Flat>, grid: &Grid) -> String {
1440 let mut out = Vec::new();
1441 backend.present(grid, &mut out).unwrap();
1442 String::from_utf8(out).unwrap()
1443 }
1444
1445 fn count(haystack: &str, needle: &str) -> usize {
1446 haystack.matches(needle).count()
1447 }
1448
1449 #[derive(Default)]
1452 struct Screen {
1453 placements: HashMap<(u32, u32), u16>,
1454 }
1455
1456 fn field(control: &str, key: &str) -> Option<String> {
1457 control
1458 .split(',')
1459 .find_map(|kv| kv.strip_prefix(&format!("{key}=")).map(str::to_string))
1460 }
1461
1462 impl Screen {
1463 fn apply(&mut self, output: &str) {
1464 let mut rest = output;
1465 let mut row = 0;
1466 while let Some(at) = rest.find('\x1b') {
1467 rest = &rest[at..];
1468 if let Some(after) = rest.strip_prefix("\x1b_G") {
1469 let end = after.find(['\x1b', ';']).unwrap_or(after.len());
1470 let control = &after[..end];
1471 let id = field(control, "i").and_then(|v| v.parse().ok());
1472 let placement = field(control, "p").and_then(|v| v.parse().ok());
1473 match (
1474 field(control, "a").as_deref(),
1475 field(control, "d").as_deref(),
1476 ) {
1477 (Some("p"), _) => {
1478 self.placements
1479 .insert((id.unwrap(), placement.unwrap()), row);
1480 }
1481 (Some("d"), Some("A")) => self.placements.clear(),
1482 (Some("d"), Some("I" | "i")) => self.placements.retain(|k, _| {
1483 k.0 != id.unwrap() || placement.is_some_and(|p| k.1 != p)
1484 }),
1485 _ => {}
1486 }
1487 rest = &rest[3..];
1488 } else {
1489 let body = rest.strip_prefix("\x1b[").unwrap_or("");
1490 if let Some(semi) = body.find(";1H")
1491 && let Ok(y) = body[..semi].parse::<u16>()
1492 {
1493 row = y - 1;
1494 }
1495 rest = &rest[1..];
1496 }
1497 }
1498 }
1499
1500 fn rows(&self) -> Vec<usize> {
1501 let mut counts = vec![0; 5];
1502 for row in self.placements.values() {
1503 counts[*row as usize] += 1;
1504 }
1505 counts
1506 }
1507 }
1508
1509 #[test]
1510 fn scroll_leaves_exactly_one_tile_on_each_row() {
1511 let mut b = PixelBackend::new(Flat, Placement::Direct, DEFAULT_QUOTA);
1512 let mut screen = Screen::default();
1513 for top in [0, 1, 2, 3, 1, 0, 7, 2] {
1514 screen.apply(&present(&mut b, &page(top)));
1515 assert_eq!(screen.rows(), vec![1; 5], "after scrolling to {top}");
1516 }
1517 }
1518
1519 #[test]
1520 fn scroll_reuses_tiles_without_retransmit() {
1521 let mut b = PixelBackend::new(Flat, Placement::Direct, DEFAULT_QUOTA);
1522 assert_eq!(count(&present(&mut b, &page(0)), "a=t,"), 5);
1523 let scrolled = present(&mut b, &page(1));
1524 assert_eq!(count(&scrolled, "a=t,"), 1, "only the new line is sent");
1525 assert_eq!(count(&scrolled, "a=p,"), 5, "every row moves by reference");
1526 let back = present(&mut b, &page(0));
1527 assert_eq!(count(&back, "a=t,"), 0, "scrolling back sends nothing new");
1528 }
1529
1530 #[test]
1531 fn a_change_in_paint_makes_a_new_tile() {
1532 let mut b = PixelBackend::new(Flat, Placement::Direct, DEFAULT_QUOTA);
1533 let mut grid = page(0);
1534 present(&mut b, &grid);
1535 let bounds = cellix_render::Bounds::cells(0.0, 2.0, 4.0, 1.0);
1536 grid.panel(bounds, 0, Some(cellix_render::Rgb(1, 2, 3)), None);
1537 assert_eq!(
1538 count(&present(&mut b, &grid), "a=t,"),
1539 1,
1540 "only row 2 changed"
1541 );
1542 }
1543
1544 #[test]
1545 fn moving_the_caret_sends_only_its_rows() {
1546 let mut b = PixelBackend::new(Flat, Placement::Direct, DEFAULT_QUOTA);
1547 let mut grid = page(0);
1548 grid.set_caret(1.0, 1, 0.6);
1549 present(&mut b, &grid);
1550 let mut moved = page(0);
1551 moved.set_caret(2.0, 1, 0.6);
1552 assert_eq!(count(&present(&mut b, &moved), "a=t,"), 1, "only row 1");
1553 }
1554
1555 #[test]
1558 fn an_unchanged_frame_sends_nothing() {
1559 let mut b = PixelBackend::new(Flat, Placement::Direct, DEFAULT_QUOTA);
1560 present(&mut b, &page(0));
1561 assert_eq!(present(&mut b, &page(0)), "");
1562 let changed = present(&mut b, &page(1));
1563 assert!(changed.starts_with("\x1b[?2026h") && changed.ends_with("\x1b[?2026l"));
1564 }
1565
1566 #[test]
1570 fn a_turning_spinner_sends_only_placements_once_it_has_gone_round() {
1571 use cellix_render::spinner::STEPS;
1572 let mut b = PixelBackend::new(Flat, Placement::Direct, DEFAULT_QUOTA);
1573 let at = |step: u8| {
1574 let mut grid = page(0);
1575 grid.turn = Some(step);
1576 grid.spinner(3.0, 2, 0.65, cellix_render::Rgb(1, 2, 3), Style::default());
1577 assert!(grid.spinning);
1578 grid
1579 };
1580 present(&mut b, &at(0));
1581 let first: Vec<String> = (1..=STEPS)
1582 .map(|n| present(&mut b, &at(n % STEPS)))
1583 .collect();
1584 for (n, frame) in first.iter().enumerate().take(STEPS as usize - 1) {
1585 assert_eq!(
1586 count(frame, "a=t,"),
1587 1,
1588 "step {} is new: its row's tile",
1589 n + 1
1590 );
1591 }
1592 assert_eq!(
1593 count(&first[STEPS as usize - 1], "a=t,"),
1594 0,
1595 "the first step again"
1596 );
1597 for n in 1..=3 * STEPS {
1598 let frame = present(&mut b, &at(n % STEPS));
1599 assert_eq!(count(&frame, "a=t,"), 0, "round again: nothing new to send");
1600 assert_eq!(count(&frame, "a=p,"), 1, "the one row's placement");
1601 assert_eq!(count(&frame, "a=d,"), 1, "and the one it replaces");
1602 assert!(frame.len() < 160, "{} bytes a step", frame.len());
1603 }
1604 let mut still = page(0);
1606 still.turn = None;
1607 still.spinner(3.0, 2, 0.65, cellix_render::Rgb(1, 2, 3), Style::default());
1608 assert!(!still.spinning);
1609 present(&mut b, &still);
1610 assert_eq!(count(&present(&mut b, &still), "\x1b_G"), 0);
1611 }
1612
1613 #[test]
1616 fn a_row_with_bands_of_its_own_sends_only_the_band_that_changed() {
1617 let mut b = PixelBackend::new(Flat, Placement::Direct, DEFAULT_QUOTA);
1618 let bar = |step: u8, said: &str| {
1619 let mut grid = page(0);
1620 grid.row_bands = Some((4, vec![6, 9]));
1621 grid.turn = Some(step);
1622 grid.put_str(0, 4, "main", Style::default(), 6);
1623 grid.spinner(6.5, 4, 0.65, cellix_render::Rgb(1, 2, 3), Style::default());
1624 grid.put_str(10, 4, said, Style::default(), 20);
1625 grid
1626 };
1627 let first = present(&mut b, &bar(0, "Ln 1"));
1628 assert_eq!(count(&first, "a=p,"), 5 + 2, "the bar's three bands");
1629 assert_eq!(
1630 count(&present(&mut b, &bar(1, "Ln 1")), "a=t,"),
1631 1,
1632 "a step: its band"
1633 );
1634 assert_eq!(
1635 count(&present(&mut b, &bar(1, "Ln 2")), "a=t,"),
1636 1,
1637 "the cursor's"
1638 );
1639 let mut whole = bar(1, "Ln 2");
1641 whole.row_bands = None;
1642 let out = present(&mut b, &whole);
1643 assert_eq!(count(&out, "a=d,d=i"), 3, "{out:?}");
1644 assert_eq!(count(&out, "a=p,"), 1);
1645 }
1646
1647 #[test]
1648 fn identical_rows_share_a_tile() {
1649 let mut b = PixelBackend::new(Flat, Placement::Direct, DEFAULT_QUOTA);
1650 let blank = Grid::new(20, 5, Style::default());
1651 let out = present(&mut b, &blank);
1652 assert_eq!(count(&out, "a=t,"), 1);
1653 assert_eq!(count(&out, "a=p,"), 5);
1654 }
1655
1656 #[test]
1657 fn placeholder_cells_are_passthrough_wrapped() {
1658 let mut b = PixelBackend::new(Flat, Placement::Placeholder, DEFAULT_QUOTA);
1659 let out = present(&mut b, &page(0));
1660 assert_eq!(
1661 count(&out, "\x1bPtmux;\x1b\x1b_G"),
1662 count(&out, "\x1b\x1b\\\x1b\\")
1663 );
1664 assert_eq!(count(&out.replace("\x1bPtmux;\x1b\x1b_G", ""), "\x1b_G"), 0);
1665 assert_eq!(count(&out, "a=p,U=1,"), 5);
1666 assert_eq!(count(&out, &PLACEHOLDER.to_string()), 5 * 20);
1667 assert!(out.contains("\u{10EEEE}\u{305}\u{305}"));
1668 }
1669
1670 #[test]
1671 fn placeholder_encodes_the_id_in_the_foreground() {
1672 let mut b = PixelBackend::new(Flat, Placement::Placeholder, DEFAULT_QUOTA);
1673 b.next_id = 0x01_02_03;
1674 let out = present(&mut b, &page(0));
1675 assert!(out.contains("\x1b[38;2;1;2;3m\u{10EEEE}"));
1676 }
1677
1678 #[test]
1679 fn tile_cache_respects_quota() {
1680 let mut b = PixelBackend::new(Flat, Placement::Direct, 60 * 7);
1682 for top in 0..40 {
1683 present(&mut b, &page(top * 5));
1684 }
1685 assert!(b.used_bytes() <= 60 * 7, "used {}", b.used_bytes());
1686 assert!(b.tile_count() >= 5, "the visible page must survive");
1687 }
1688
1689 #[test]
1690 fn eviction_never_removes_a_visible_tile() {
1691 let mut b = PixelBackend::new(Flat, Placement::Direct, 60);
1692 let out = present(&mut b, &page(0));
1693 assert_eq!(count(&out, "a=d,d=I"), 0, "all five tiles are on screen");
1694 assert_eq!(b.tile_count(), 5);
1695 }
1696
1697 #[test]
1698 fn evicted_tiles_are_freed_in_the_terminal() {
1699 let mut b = PixelBackend::new(Flat, Placement::Direct, 60 * 5);
1700 present(&mut b, &page(0));
1701 let out = present(&mut b, &page(5));
1702 assert_eq!(count(&out, "a=d,d=I"), 5);
1703 }
1704
1705 #[cfg(unix)]
1708 fn sent(output: &str) -> BTreeMap<u32, (String, String, Vec<u8>)> {
1709 use std::io::Read;
1710 let mut images = BTreeMap::new();
1711 let mut pending: Option<(u32, String, String, String)> = None;
1712 for command in output.split("\x1b_G").skip(1) {
1713 let command = &command[..command.find("\x1b\\").unwrap()];
1714 let (control, data) = command.split_once(';').unwrap_or((command, ""));
1715 let start = field(control, "a").as_deref() == Some("t");
1716 if start && field(control, "t").as_deref() == Some("t") {
1717 let name = base64::engine::general_purpose::STANDARD
1718 .decode(data)
1719 .unwrap();
1720 let path = std::path::PathBuf::from(String::from_utf8(name).unwrap());
1721 let pixels = std::fs::read(&path).unwrap();
1722 std::fs::remove_file(&path).unwrap();
1723 let size = (field(control, "s").unwrap(), field(control, "v").unwrap());
1724 let id = field(control, "i").unwrap().parse().unwrap();
1725 images.insert(id, (size.0, size.1, pixels));
1726 continue;
1727 }
1728 if start {
1729 let id = field(control, "i").unwrap().parse().unwrap();
1730 let (w, h) = (field(control, "s").unwrap(), field(control, "v").unwrap());
1731 pending = Some((id, w, h, String::new()));
1732 } else if field(control, "a").is_some() {
1733 continue;
1734 }
1735 let (id, w, h, mut b64) = pending.take().unwrap();
1736 b64.push_str(data);
1737 if field(control, "m").as_deref() == Some("1") {
1738 pending = Some((id, w, h, b64));
1739 continue;
1740 }
1741 let packed = base64::engine::general_purpose::STANDARD
1742 .decode(b64)
1743 .unwrap();
1744 let mut pixels = Vec::new();
1745 flate2::read::ZlibDecoder::new(packed.as_slice())
1746 .read_to_end(&mut pixels)
1747 .unwrap();
1748 images.insert(id, (w, h, pixels));
1749 }
1750 images
1751 }
1752
1753 #[cfg(unix)]
1757 #[test]
1758 fn tiles_go_as_files_the_terminal_reads_and_end_up_the_same() {
1759 let root = std::env::temp_dir().join(format!("cellix-pixels-test-{}", std::process::id()));
1760 let _ = std::fs::remove_dir_all(&root);
1761 std::fs::create_dir(&root).unwrap();
1762 let files = TileFiles::for_test(root.clone());
1763 let mut filed =
1764 PixelBackend::new(Sized, Placement::Direct, DEFAULT_QUOTA).with_files(files.clone());
1765 let mut inline = PixelBackend::new(Sized, Placement::Direct, DEFAULT_QUOTA);
1766 for top in [0, 3, 1] {
1767 let (mut a, mut b) = (Vec::new(), Vec::new());
1768 filed.present(&pane(top), &mut a).unwrap();
1769 inline.present(&pane(top), &mut b).unwrap();
1770 let (a, b) = (String::from_utf8(a).unwrap(), String::from_utf8(b).unwrap());
1771 assert_eq!(
1772 count(&a, "t=t,"),
1773 count(&b, "a=t,"),
1774 "every new tile as a file"
1775 );
1776 assert_eq!(count(&a, "o=z"), 0, "nothing inline");
1777 assert_eq!(sent(&a), sent(&b), "the same pictures");
1778 let placed = |out: &str| {
1779 out.split("\x1b_G")
1780 .skip(1)
1781 .filter(|command| !command.starts_with("a=t") && !command.starts_with("m="))
1782 .map(|command| command[..command.find("\x1b\\").unwrap()].to_string())
1783 .collect::<Vec<_>>()
1784 };
1785 assert_eq!(placed(&a), placed(&b), "placed the same way");
1786 }
1787 let tmux = PixelBackend::new(Sized, Placement::Placeholder, DEFAULT_QUOTA)
1788 .with_files(files.clone());
1789 assert!(tmux.files.is_none());
1790 files.clear();
1791 std::fs::remove_dir_all(&root).unwrap();
1792 }
1793
1794 #[test]
1795 fn resize_clears_the_terminal_store() {
1796 let mut b = PixelBackend::new(Flat, Placement::Direct, DEFAULT_QUOTA);
1797 present(&mut b, &page(0));
1798 let wider = Grid::new(30, 5, Style::default());
1799 let out = present(&mut b, &wider);
1800 assert!(out.contains("a=d,d=A"));
1801 assert_eq!(b.tile_count(), 1);
1802 }
1803}