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 grid.spans(y)
478 }
479
480 fn band_tiles(&mut self, out: &mut Vec<u8>, grid: &Grid, y: u16) -> Vec<u32> {
482 let spans = self.spans(grid, y);
483 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 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 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 let begun = bytes.len();
590 let size = (grid.width(), grid.height());
591 if size != self.size {
592 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 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 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 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 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 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 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 #[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 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 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 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 #[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 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 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 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 #[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 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 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 let tile = padded.bled(lit(96), &grid, 2);
1010 assert_eq!((tile.height, starts(&tile)), (22, 0));
1011 }
1012
1013 #[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 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 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 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 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 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 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 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 #[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 #[test]
1550 fn an_unchanged_frame_sends_nothing() {
1551 let mut b = PixelBackend::new(Flat, Placement::Direct, DEFAULT_QUOTA);
1552 present(&mut b, &page(0));
1553 assert_eq!(present(&mut b, &page(0)), "");
1554 let changed = present(&mut b, &page(1));
1555 assert!(changed.starts_with("\x1b[?2026h") && changed.ends_with("\x1b[?2026l"));
1556 }
1557
1558 #[test]
1562 fn a_turning_spinner_sends_only_placements_once_it_has_gone_round() {
1563 use cellix_render::spinner::STEPS;
1564 let mut b = PixelBackend::new(Flat, Placement::Direct, DEFAULT_QUOTA);
1565 let at = |step: u8| {
1566 let mut grid = page(0);
1567 grid.turn = Some(step);
1568 grid.spinner(3.0, 2, 0.65, cellix_render::Rgb(1, 2, 3), Style::default());
1569 assert!(grid.spinning);
1570 grid
1571 };
1572 present(&mut b, &at(0));
1573 let first: Vec<String> = (1..=STEPS)
1574 .map(|n| present(&mut b, &at(n % STEPS)))
1575 .collect();
1576 for (n, frame) in first.iter().enumerate().take(STEPS as usize - 1) {
1577 assert_eq!(
1578 count(frame, "a=t,"),
1579 1,
1580 "step {} is new: its row's tile",
1581 n + 1
1582 );
1583 }
1584 assert_eq!(
1585 count(&first[STEPS as usize - 1], "a=t,"),
1586 0,
1587 "the first step again"
1588 );
1589 for n in 1..=3 * STEPS {
1590 let frame = present(&mut b, &at(n % STEPS));
1591 assert_eq!(count(&frame, "a=t,"), 0, "round again: nothing new to send");
1592 assert_eq!(count(&frame, "a=p,"), 1, "the one row's placement");
1593 assert_eq!(count(&frame, "a=d,"), 1, "and the one it replaces");
1594 assert!(frame.len() < 160, "{} bytes a step", frame.len());
1595 }
1596 let mut still = page(0);
1598 still.turn = None;
1599 still.spinner(3.0, 2, 0.65, cellix_render::Rgb(1, 2, 3), Style::default());
1600 assert!(!still.spinning);
1601 present(&mut b, &still);
1602 assert_eq!(count(&present(&mut b, &still), "\x1b_G"), 0);
1603 }
1604
1605 #[test]
1608 fn a_row_with_bands_of_its_own_sends_only_the_band_that_changed() {
1609 let mut b = PixelBackend::new(Flat, Placement::Direct, DEFAULT_QUOTA);
1610 let bar = |step: u8, said: &str| {
1611 let mut grid = page(0);
1612 grid.row_bands = Some((4, vec![6, 9]));
1613 grid.turn = Some(step);
1614 grid.put_str(0, 4, "main", Style::default(), 6);
1615 grid.spinner(6.5, 4, 0.65, cellix_render::Rgb(1, 2, 3), Style::default());
1616 grid.put_str(10, 4, said, Style::default(), 20);
1617 grid
1618 };
1619 let first = present(&mut b, &bar(0, "Ln 1"));
1620 assert_eq!(count(&first, "a=p,"), 5 + 2, "the bar's three bands");
1621 assert_eq!(
1622 count(&present(&mut b, &bar(1, "Ln 1")), "a=t,"),
1623 1,
1624 "a step: its band"
1625 );
1626 assert_eq!(
1627 count(&present(&mut b, &bar(1, "Ln 2")), "a=t,"),
1628 1,
1629 "the cursor's"
1630 );
1631 let mut whole = bar(1, "Ln 2");
1633 whole.row_bands = None;
1634 let out = present(&mut b, &whole);
1635 assert_eq!(count(&out, "a=d,d=i"), 3, "{out:?}");
1636 assert_eq!(count(&out, "a=p,"), 1);
1637 }
1638
1639 #[test]
1640 fn identical_rows_share_a_tile() {
1641 let mut b = PixelBackend::new(Flat, Placement::Direct, DEFAULT_QUOTA);
1642 let blank = Grid::new(20, 5, Style::default());
1643 let out = present(&mut b, &blank);
1644 assert_eq!(count(&out, "a=t,"), 1);
1645 assert_eq!(count(&out, "a=p,"), 5);
1646 }
1647
1648 #[test]
1649 fn placeholder_cells_are_passthrough_wrapped() {
1650 let mut b = PixelBackend::new(Flat, Placement::Placeholder, DEFAULT_QUOTA);
1651 let out = present(&mut b, &page(0));
1652 assert_eq!(
1653 count(&out, "\x1bPtmux;\x1b\x1b_G"),
1654 count(&out, "\x1b\x1b\\\x1b\\")
1655 );
1656 assert_eq!(count(&out.replace("\x1bPtmux;\x1b\x1b_G", ""), "\x1b_G"), 0);
1657 assert_eq!(count(&out, "a=p,U=1,"), 5);
1658 assert_eq!(count(&out, &PLACEHOLDER.to_string()), 5 * 20);
1659 assert!(out.contains("\u{10EEEE}\u{305}\u{305}"));
1660 }
1661
1662 #[test]
1663 fn placeholder_encodes_the_id_in_the_foreground() {
1664 let mut b = PixelBackend::new(Flat, Placement::Placeholder, DEFAULT_QUOTA);
1665 b.next_id = 0x01_02_03;
1666 let out = present(&mut b, &page(0));
1667 assert!(out.contains("\x1b[38;2;1;2;3m\u{10EEEE}"));
1668 }
1669
1670 #[test]
1671 fn tile_cache_respects_quota() {
1672 let mut b = PixelBackend::new(Flat, Placement::Direct, 60 * 7);
1674 for top in 0..40 {
1675 present(&mut b, &page(top * 5));
1676 }
1677 assert!(b.used_bytes() <= 60 * 7, "used {}", b.used_bytes());
1678 assert!(b.tile_count() >= 5, "the visible page must survive");
1679 }
1680
1681 #[test]
1682 fn eviction_never_removes_a_visible_tile() {
1683 let mut b = PixelBackend::new(Flat, Placement::Direct, 60);
1684 let out = present(&mut b, &page(0));
1685 assert_eq!(count(&out, "a=d,d=I"), 0, "all five tiles are on screen");
1686 assert_eq!(b.tile_count(), 5);
1687 }
1688
1689 #[test]
1690 fn evicted_tiles_are_freed_in_the_terminal() {
1691 let mut b = PixelBackend::new(Flat, Placement::Direct, 60 * 5);
1692 present(&mut b, &page(0));
1693 let out = present(&mut b, &page(5));
1694 assert_eq!(count(&out, "a=d,d=I"), 5);
1695 }
1696
1697 #[cfg(unix)]
1700 fn sent(output: &str) -> BTreeMap<u32, (String, String, Vec<u8>)> {
1701 use std::io::Read;
1702 let mut images = BTreeMap::new();
1703 let mut pending: Option<(u32, String, String, String)> = None;
1704 for command in output.split("\x1b_G").skip(1) {
1705 let command = &command[..command.find("\x1b\\").unwrap()];
1706 let (control, data) = command.split_once(';').unwrap_or((command, ""));
1707 let start = field(control, "a").as_deref() == Some("t");
1708 if start && field(control, "t").as_deref() == Some("t") {
1709 let name = base64::engine::general_purpose::STANDARD
1710 .decode(data)
1711 .unwrap();
1712 let path = std::path::PathBuf::from(String::from_utf8(name).unwrap());
1713 let pixels = std::fs::read(&path).unwrap();
1714 std::fs::remove_file(&path).unwrap();
1715 let size = (field(control, "s").unwrap(), field(control, "v").unwrap());
1716 let id = field(control, "i").unwrap().parse().unwrap();
1717 images.insert(id, (size.0, size.1, pixels));
1718 continue;
1719 }
1720 if start {
1721 let id = field(control, "i").unwrap().parse().unwrap();
1722 let (w, h) = (field(control, "s").unwrap(), field(control, "v").unwrap());
1723 pending = Some((id, w, h, String::new()));
1724 } else if field(control, "a").is_some() {
1725 continue;
1726 }
1727 let (id, w, h, mut b64) = pending.take().unwrap();
1728 b64.push_str(data);
1729 if field(control, "m").as_deref() == Some("1") {
1730 pending = Some((id, w, h, b64));
1731 continue;
1732 }
1733 let packed = base64::engine::general_purpose::STANDARD
1734 .decode(b64)
1735 .unwrap();
1736 let mut pixels = Vec::new();
1737 flate2::read::ZlibDecoder::new(packed.as_slice())
1738 .read_to_end(&mut pixels)
1739 .unwrap();
1740 images.insert(id, (w, h, pixels));
1741 }
1742 images
1743 }
1744
1745 #[cfg(unix)]
1749 #[test]
1750 fn tiles_go_as_files_the_terminal_reads_and_end_up_the_same() {
1751 let root = std::env::temp_dir().join(format!("cellix-pixels-test-{}", std::process::id()));
1752 let _ = std::fs::remove_dir_all(&root);
1753 std::fs::create_dir(&root).unwrap();
1754 let files = TileFiles::for_test(root.clone());
1755 let mut filed =
1756 PixelBackend::new(Sized, Placement::Direct, DEFAULT_QUOTA).with_files(files.clone());
1757 let mut inline = PixelBackend::new(Sized, Placement::Direct, DEFAULT_QUOTA);
1758 for top in [0, 3, 1] {
1759 let (mut a, mut b) = (Vec::new(), Vec::new());
1760 filed.present(&pane(top), &mut a).unwrap();
1761 inline.present(&pane(top), &mut b).unwrap();
1762 let (a, b) = (String::from_utf8(a).unwrap(), String::from_utf8(b).unwrap());
1763 assert_eq!(
1764 count(&a, "t=t,"),
1765 count(&b, "a=t,"),
1766 "every new tile as a file"
1767 );
1768 assert_eq!(count(&a, "o=z"), 0, "nothing inline");
1769 assert_eq!(sent(&a), sent(&b), "the same pictures");
1770 let placed = |out: &str| {
1771 out.split("\x1b_G")
1772 .skip(1)
1773 .filter(|command| !command.starts_with("a=t") && !command.starts_with("m="))
1774 .map(|command| command[..command.find("\x1b\\").unwrap()].to_string())
1775 .collect::<Vec<_>>()
1776 };
1777 assert_eq!(placed(&a), placed(&b), "placed the same way");
1778 }
1779 let tmux = PixelBackend::new(Sized, Placement::Placeholder, DEFAULT_QUOTA)
1780 .with_files(files.clone());
1781 assert!(tmux.files.is_none());
1782 files.clear();
1783 std::fs::remove_dir_all(&root).unwrap();
1784 }
1785
1786 #[test]
1787 fn resize_clears_the_terminal_store() {
1788 let mut b = PixelBackend::new(Flat, Placement::Direct, DEFAULT_QUOTA);
1789 present(&mut b, &page(0));
1790 let wider = Grid::new(30, 5, Style::default());
1791 let out = present(&mut b, &wider);
1792 assert!(out.contains("a=d,d=A"));
1793 assert_eq!(b.tile_count(), 1);
1794 }
1795}