1use compact_str::CompactString;
2use unicode_segmentation::UnicodeSegmentation;
3use unicode_width::UnicodeWidthStr;
4
5use crate::icon::{Icon, Piece};
6use crate::measure::Font;
7use crate::paint::{Bounds, Paint, UNIT, units};
8
9const BUTTON_HEIGHT: f32 = 0.88;
15const LARGE_BUTTON_HEIGHT: f32 = BUTTON_HEIGHT;
16
17#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
18pub struct Rgb(pub u8, pub u8, pub u8);
19
20#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
21pub struct Style {
22 pub fg: Rgb,
23 pub bg: Rgb,
24 pub bold: bool,
25 pub italic: bool,
26 pub underline: bool,
27 pub painted: bool,
29}
30
31fn visible(text: &str) -> std::borrow::Cow<'_, str> {
36 let control = |c: char| c.is_control();
37 if !text.contains(control) {
38 return std::borrow::Cow::Borrowed(text);
39 }
40 let shown = text
41 .chars()
42 .map(|c| match c {
43 '\t' => ' ',
44 '\0'..='\u{1f}' => char::from_u32(0x2400 + c as u32).unwrap_or('\u{fffd}'),
45 '\u{7f}' => '\u{2421}',
46 c if c.is_control() => '\u{fffd}',
47 c => c,
48 })
49 .collect();
50 std::borrow::Cow::Owned(shown)
51}
52
53#[derive(Clone, Debug, PartialEq, Eq, Hash)]
55pub struct Cell {
56 pub symbol: CompactString,
57 pub style: Style,
58}
59
60trait CopyCells {
62 fn copy_within_cells(&mut self, from: std::ops::Range<usize>, to: usize);
63}
64
65impl CopyCells for Vec<Cell> {
66 fn copy_within_cells(&mut self, from: std::ops::Range<usize>, to: usize) {
67 for (n, at) in from.enumerate() {
68 let cell = self[at].clone();
69 self[to + n] = cell;
70 }
71 }
72}
73
74#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
75pub struct Rect {
76 pub x: u16,
77 pub y: u16,
78 pub w: u16,
79 pub h: u16,
80}
81
82impl Rect {
83 pub fn new(x: u16, y: u16, w: u16, h: u16) -> Self {
84 Self { x, y, w, h }
85 }
86
87 pub fn contains(&self, x: u16, y: u16) -> bool {
88 x >= self.x && x < self.x + self.w && y >= self.y && y < self.y + self.h
89 }
90
91 pub fn right(&self) -> u16 {
92 self.x + self.w
93 }
94
95 pub fn bottom(&self) -> u16 {
96 self.y + self.h
97 }
98}
99
100#[derive(Clone, Copy, Debug, PartialEq, Eq)]
102pub struct Run {
103 pub x: u16,
104 pub y: u16,
105 pub len: u16,
106}
107
108#[derive(Clone, Debug, PartialEq, Eq)]
109pub struct Grid {
110 width: u16,
111 height: u16,
112 cells: Vec<Cell>,
113 pub cursor: Option<(u16, u16)>,
114 pub caret: Option<Bounds>,
116 pub paint: Vec<Paint>,
118 pub bands: Vec<u16>,
121 kept: Vec<((usize, usize), (u16, u16))>,
125}
126
127impl Grid {
128 pub fn scroll_rows(&mut self, top: u16, bottom: u16, by: i32) {
132 let width = self.width as usize;
133 let (top, bottom) = (
134 top as usize,
135 (bottom as usize).min(self.height as usize - 1),
136 );
137 if top > bottom || by == 0 {
138 return;
139 }
140 let rows = bottom + 1 - top;
141 let n = (by.unsigned_abs() as usize).min(rows);
142 let unknown = Cell {
143 symbol: CompactString::const_new("\u{fffe}"),
144 style: Style::default(),
145 };
146 let row = |y: usize| y * width..(y + 1) * width;
147 if by > 0 {
148 for y in top..bottom + 1 - n {
149 self.cells.copy_within_cells(row(y + n), row(y).start);
150 }
151 for y in bottom + 1 - n..=bottom {
152 self.cells[row(y)].fill(unknown.clone());
153 }
154 } else {
155 for y in (top + n..=bottom).rev() {
156 self.cells.copy_within_cells(row(y - n), row(y).start);
157 }
158 for y in top..top + n {
159 self.cells[row(y)].fill(unknown.clone());
160 }
161 }
162 }
163
164 pub fn new(width: u16, height: u16, style: Style) -> Self {
165 let blank = Cell {
166 symbol: " ".into(),
167 style,
168 };
169 Self {
170 width,
171 height,
172 cells: vec![blank; width as usize * height as usize],
173 cursor: None,
174 caret: None,
175 paint: Vec::new(),
176 bands: Vec::new(),
177 kept: Vec::new(),
178 }
179 }
180
181 pub fn label(&mut self, x: u16, y: u16, text: &str, style: Style, max_x: u16) -> u16 {
183 self.label_at(x as f32, x, y, text, style, max_x, 100)
184 }
185
186 pub fn painted_so_far(&self) -> usize {
188 self.paint.len()
189 }
190
191 pub fn keep_to_rows(&mut self, from: usize, top: u16, bottom: u16) {
194 if from < self.paint.len() {
195 self.kept.push(((from, self.paint.len()), (top, bottom)));
196 }
197 }
198
199 pub fn insert_paint(&mut self, index: usize, paint: Paint) {
201 let index = index.min(self.paint.len());
202 self.paint.insert(index, paint);
203 for ((from, to), _) in &mut self.kept {
205 if index < *from {
206 *from += 1;
207 }
208 if index < *to {
209 *to += 1;
210 }
211 }
212 }
213
214 pub fn lift_since(&mut self, from: usize, rows: f32) {
217 let by = units(rows);
218 for paint in self.paint.iter_mut().skip(from) {
219 paint.lift(by);
220 }
221 }
222
223 #[allow(clippy::too_many_arguments)]
225 pub fn label_at(
226 &mut self,
227 x_px: f32,
228 x: u16,
229 y: u16,
230 text: &str,
231 style: Style,
232 max_x: u16,
233 size: u8,
234 ) -> u16 {
235 let end = self.put_str(
236 x,
237 y,
238 text,
239 Style {
240 painted: true,
241 ..style
242 },
243 max_x,
244 );
245 if y < self.height {
246 self.paint.push(Paint::Text {
247 x: units(x_px),
248 y: y as i32 * UNIT,
249 max_width: units(max_x.min(self.width) as f32 - x_px),
250 text: text.to_string(),
251 color: style.fg,
252 font: Font {
253 bold: style.bold,
254 size,
255 ..Font::default()
256 },
257 align_right: false,
258 centred: false,
259 underline: false,
260 });
261 }
262 end
263 }
264
265 pub fn text_run(
267 &mut self,
268 (x, y): (f32, f32),
269 max_x: f32,
270 text: &str,
271 (color, underline): (Rgb, bool),
272 font: Font,
273 ) {
274 self.paint.push(Paint::Text {
275 x: units(x),
276 y: units(y),
277 max_width: units(max_x - x),
278 text: text.to_string(),
279 color,
280 font,
281 align_right: false,
282 centred: false,
283 underline,
284 });
285 }
286
287 pub fn set_caret(&mut self, x: f32, y: u16, height: f32) {
289 self.cursor = Some((x as u16, y));
290 let top = y as f32 + (1.0 - height) / 2.0;
291 self.caret = Some(Bounds::cells(x, top, 0.0, height));
292 }
293
294 pub fn label_right(&mut self, right: u16, y: u16, text: &str, style: Style, size: u8) {
297 let cells = text.chars().count() as u16;
298 let x = right.saturating_sub(cells);
299 self.put_str(
300 x,
301 y,
302 text,
303 Style {
304 painted: true,
305 ..style
306 },
307 right,
308 );
309 self.paint.push(Paint::Text {
310 x: units(right as f32),
311 y: y as i32 * UNIT,
312 max_width: units(right as f32),
313 text: text.to_string(),
314 color: style.fg,
315 font: Font {
316 bold: style.bold,
317 size,
318 ..Font::default()
319 },
320 align_right: true,
321 centred: false,
322 underline: false,
323 });
324 }
325
326 pub fn field(&mut self, rect: Rect, behind: Rgb, fill: Rgb, border: Rgb) {
328 self.panel(Bounds::inset(rect, 0.0, 0.0), 0, Some(behind), None);
329 self.panel(
332 Bounds::inset(rect, 0.15, 0.11),
333 22,
334 Some(fill),
335 Some(border),
336 );
337 }
338
339 pub fn button(&mut self, x: u16, y: u16, cells: &str, label: &str, fill: Rgb, style: Style) {
342 self.button_of((BUTTON_HEIGHT, 0.0), (x, y), cells, label, fill, style);
343 }
344
345 pub fn chip(&mut self, x: f32, y: u16, wide: f32, fill: Rgb) {
348 let top = y as f32 + (1.0 - BUTTON_HEIGHT) / 2.0;
349 let bounds = Bounds::cells(x, top, wide, BUTTON_HEIGHT);
350 self.panel(bounds, 22, Some(fill), None);
351 }
352
353 pub fn large_button(
355 &mut self,
356 x: u16,
357 y: u16,
358 cells: &str,
359 label: &str,
360 fill: Rgb,
361 style: Style,
362 ) {
363 self.button_of(
364 (LARGE_BUTTON_HEIGHT, 0.0),
365 (x, y),
366 cells,
367 label,
368 fill,
369 style,
370 );
371 }
372
373 pub fn large_button_between(
375 &mut self,
376 x: u16,
377 y: u16,
378 cells: &str,
379 label: &str,
380 fill: Rgb,
381 style: Style,
382 ) {
383 self.button_of(
384 (LARGE_BUTTON_HEIGHT, 0.5),
385 (x, y),
386 cells,
387 label,
388 fill,
389 style,
390 );
391 }
392
393 fn button_of(
394 &mut self,
395 (height, drop): (f32, f32),
396 (x, y): (u16, u16),
397 cells: &str,
398 label: &str,
399 fill: Rgb,
400 style: Style,
401 ) {
402 let width = cells.chars().count() as u16;
403 let (left, top, right, bottom) = button_span((height, drop), (x, y), width);
404 self.put_str(
405 x,
406 y,
407 cells,
408 Style {
409 painted: true,
410 ..style
411 },
412 self.width,
413 );
414 let bounds = Bounds::cells(left, top, right - left, bottom - top);
415 self.panel(bounds, 22, Some(fill), None);
416 let middle = x as f32 + width as f32 / 2.0;
417 self.centred_text(middle, y as f32 + drop, label, style.fg, 90);
418 }
419
420 pub fn drop_last(&mut self, by: f32) {
422 match self.paint.last_mut() {
423 Some(Paint::Text { y, .. }) => *y += units(by),
424 Some(Paint::Icon { bounds, .. }) => bounds.y += units(by),
425 _ => {}
426 }
427 }
428
429 pub fn centred_text(&mut self, x: f32, y: f32, text: &str, color: Rgb, size: u8) {
431 self.paint.push(Paint::Text {
432 x: units(x),
433 y: units(y),
434 max_width: units(self.width as f32),
435 text: text.to_string(),
436 color,
437 font: Font {
438 size,
439 ..Font::default()
440 },
441 align_right: false,
442 centred: true,
443 underline: false,
444 });
445 }
446
447 pub fn panel(&mut self, bounds: Bounds, radius: u8, fill: Option<Rgb>, border: Option<Rgb>) {
448 self.paint.push(Paint::Panel {
449 bounds,
450 radius,
451 fill,
452 border,
453 shadow: false,
454 dashed: false,
455 });
456 }
457
458 pub fn dashed_panel(&mut self, bounds: Bounds, radius: u8, fill: Option<Rgb>, border: Rgb) {
460 self.paint.push(Paint::Panel {
461 bounds,
462 radius,
463 fill,
464 border: Some(border),
465 shadow: false,
466 dashed: true,
467 });
468 }
469
470 pub fn popup(&mut self, bounds: Bounds, radius: u8, fill: Rgb, border: Rgb) {
472 self.paint.push(Paint::Panel {
473 bounds,
474 radius,
475 fill: Some(fill),
476 border: Some(border),
477 shadow: true,
478 dashed: false,
479 });
480 }
481
482 pub fn wash(
484 &mut self,
485 bounds: Bounds,
486 radius: u8,
487 (color, alpha): (Rgb, u8),
488 border: Option<Rgb>,
489 ) {
490 self.paint.push(Paint::Wash {
491 bounds,
492 radius,
493 color,
494 alpha,
495 border,
496 });
497 }
498
499 pub fn hairline(&mut self, bounds: Bounds, color: Rgb) {
500 self.paint.push(Paint::Hairline { bounds, color });
501 }
502
503 pub fn glyph(&mut self, x: f32, y: u16, icon: Icon, color: Rgb, fallback: &str, style: Style) {
506 let cell = x.floor() as u16;
507 if cell < self.width && y < self.height {
508 self.put_str(
509 cell,
510 y,
511 fallback,
512 Style {
513 painted: true,
514 ..style
515 },
516 self.width,
517 );
518 }
519 self.paint.push(Paint::Icon {
520 bounds: Bounds::cells(x, y as f32 + 0.14, 2.0, 0.72),
521 icon,
522 color,
523 });
524 }
525
526 pub fn corners(&mut self, bounds: Bounds, radius: u8, color: Rgb, which: u8) {
528 self.paint.push(Paint::Corners {
529 bounds,
530 radius,
531 color,
532 which,
533 });
534 }
535
536 pub fn paint_on_row(&self, y: u16) -> impl Iterator<Item = &Paint> {
537 let (top, bottom) = (y as i32 * UNIT, (y as i32 + 1) * UNIT);
538 let kept_off = move |index: usize| {
539 self.kept.iter().any(|((from, to), (first, end))| {
540 (*from..*to).contains(&index) && !(*first..*end).contains(&y)
541 })
542 };
543 self.paint
544 .iter()
545 .enumerate()
546 .filter(move |(index, p)| {
547 let (from, to) = p.span();
548 from < bottom && to > top && !kept_off(*index)
549 })
550 .map(|(_, paint)| paint)
551 }
552
553 pub fn width(&self) -> u16 {
554 self.width
555 }
556
557 pub fn height(&self) -> u16 {
558 self.height
559 }
560
561 pub fn area(&self) -> Rect {
562 Rect::new(0, 0, self.width, self.height)
563 }
564
565 fn index(&self, x: u16, y: u16) -> usize {
566 y as usize * self.width as usize + x as usize
567 }
568
569 pub fn cell(&self, x: u16, y: u16) -> &Cell {
570 &self.cells[self.index(x, y)]
571 }
572
573 pub fn row(&self, y: u16) -> &[Cell] {
574 let start = self.index(0, y);
575 &self.cells[start..start + self.width as usize]
576 }
577
578 pub fn fill(&mut self, rect: Rect, style: Style) {
579 for y in rect.y..rect.bottom().min(self.height) {
580 for x in rect.x..rect.right().min(self.width) {
581 self.put_cell(x, y, " ", style);
582 }
583 }
584 }
585
586 fn put_cell(&mut self, x: u16, y: u16, symbol: &str, style: Style) {
587 let i = self.index(x, y);
589 if self.cells[i].symbol.is_empty() && x > 0 {
590 self.cells[i - 1].symbol = " ".into();
591 }
592 if x + 1 < self.width && self.cells[i + 1].symbol.is_empty() {
593 self.cells[i + 1].symbol = " ".into();
594 }
595 self.cells[i] = Cell {
596 symbol: symbol.into(),
597 style,
598 };
599 }
600
601 pub fn put_str(&mut self, x: u16, y: u16, text: &str, style: Style, max_x: u16) -> u16 {
604 if y >= self.height {
605 return x;
606 }
607 let max_x = max_x.min(self.width);
608 let mut at = x;
609 let text = visible(text);
610 for g in text.graphemes(true) {
611 if at >= max_x {
612 break;
613 }
614 let width = g.width() as u16;
615 if width == 0 {
616 continue;
617 }
618 if at + width > max_x {
619 self.put_cell(at, y, " ", style);
620 return at + 1;
621 }
622 self.put_cell(at, y, g, style);
623 if width == 2 {
624 self.put_cell(at + 1, y, "", style);
625 }
626 at += width;
627 }
628 at
629 }
630
631 pub fn put_icon(&mut self, x: u16, y: u16, icon: Icon, size: (u8, u8), style: Style) {
633 for row in 0..size.1 {
634 for column in 0..size.0 {
635 let (cx, cy) = (x + u16::from(column), y + u16::from(row));
636 if cx < self.width && cy < self.height {
637 let piece = Piece {
638 icon,
639 width: size.0,
640 height: size.1,
641 column,
642 row,
643 };
644 self.put_cell(cx, cy, piece.symbol().encode_utf8(&mut [0; 4]), style);
645 }
646 }
647 }
648 }
649
650 pub fn set_style(&mut self, rect: Rect, f: impl Fn(Style) -> Style) {
652 for y in rect.y..rect.bottom().min(self.height) {
653 for x in rect.x..rect.right().min(self.width) {
654 let i = self.index(x, y);
655 self.cells[i].style = f(self.cells[i].style);
656 }
657 }
658 }
659
660 pub fn diff(&self, prev: &Grid) -> Vec<Run> {
662 let same_size = self.width == prev.width && self.height == prev.height;
663 let mut runs = Vec::new();
664 for y in 0..self.height {
665 if same_size && self.row(y) == prev.row(y) {
666 continue;
667 }
668 let mut x = 0;
669 while x < self.width {
670 if same_size && self.cell(x, y) == prev.cell(x, y) {
671 x += 1;
672 continue;
673 }
674 let start = x;
675 while x < self.width && !(same_size && self.cell(x, y) == prev.cell(x, y)) {
676 x += 1;
677 }
678 let start = if self.cell(start, y).symbol.is_empty() && start > 0 {
680 start - 1
681 } else {
682 start
683 };
684 runs.push(Run {
685 x: start,
686 y,
687 len: x - start,
688 });
689 }
690 }
691 runs
692 }
693
694 pub fn row_text(&self, y: u16) -> String {
696 self.row(y).iter().map(|c| c.symbol.as_str()).collect()
697 }
698
699 pub fn text(&self) -> String {
701 (0..self.height)
702 .map(|y| self.row_text(y).trim_end().to_string())
703 .collect::<Vec<_>>()
704 .join("\n")
705 }
706}
707
708fn button_span((height, drop): (f32, f32), (x, y): (u16, u16), width: u16) -> (f32, f32, f32, f32) {
710 let top = y as f32 + drop + (1.0 - height) / 2.0;
711 (x as f32, top, (x + width) as f32, top + height)
712}
713
714pub fn on_large_button((x, y): (u16, u16), width: u16, at: (f32, f32)) -> bool {
719 let (left, top, right, bottom) = button_span((LARGE_BUTTON_HEIGHT, 0.0), (x, y), width);
720 at.0 >= left && at.0 < right && at.1 >= top && at.1 < bottom
721}
722
723#[cfg(test)]
724mod tests {
725 #[test]
728 fn paint_kept_to_its_rows_is_on_no_other() {
729 let style = Style::default();
730 let mut grid = Grid::new(10, 6, style);
731 let panel = |grid: &mut Grid, y: f32, h: f32| {
732 grid.panel(Bounds::cells(0.0, y, 10.0, h), 0, Some(Rgb(1, 2, 3)), None);
733 };
734 panel(&mut grid, 0.0, 1.0);
735 let from = grid.painted_so_far();
736 panel(&mut grid, 1.0, 4.5);
738 grid.keep_to_rows(from, 2, 4);
739 panel(&mut grid, 5.0, 1.0);
740 let on = |grid: &Grid, y: u16| grid.paint_on_row(y).count();
741 let rows: Vec<usize> = (0..6).map(|y| on(&grid, y)).collect();
742 assert_eq!(rows, [1, 0, 1, 1, 0, 1]);
743 grid.insert_paint(
745 0,
746 Paint::Hairline {
747 bounds: Bounds::cells(0.0, 1.0, 10.0, 0.0),
748 color: Rgb(9, 9, 9),
749 },
750 );
751 let rows: Vec<usize> = (0..6).map(|y| on(&grid, y)).collect();
752 assert_eq!(rows, [1, 1, 1, 1, 0, 1]);
753 }
754
755 #[test]
756 fn control_characters_never_reach_a_cell() {
757 let style = Style::default();
758 let mut grid = Grid::new(40, 2, style);
759 let text = "a\x1b]52;c;aGk=\x07b\r\n\x7f\u{9b}2Jc\td";
760 let end = grid.put_str(0, 0, text, style, 40);
761 let row: String = (0..end)
762 .map(|x| grid.cell(x, 0).symbol.to_string())
763 .collect();
764 assert_eq!(row, "a␛]52;c;aGk=␇b␍␊␡\u{fffd}2Jc d");
765 assert!(row.chars().all(|c| !c.is_control()), "{row:?}");
766 }
767
768 use super::*;
769
770 fn grid() -> Grid {
771 Grid::new(10, 3, Style::default())
772 }
773
774 #[test]
775 fn diff_emits_only_changed_cells() {
776 let before = grid();
777 let mut after = grid();
778 after.put_str(2, 1, "ab", Style::default(), 10);
779 after.put_str(7, 1, "c", Style::default(), 10);
780 assert_eq!(
781 after.diff(&before),
782 vec![Run { x: 2, y: 1, len: 2 }, Run { x: 7, y: 1, len: 1 }]
783 );
784 assert!(before.diff(&before.clone()).is_empty());
785 }
786
787 #[test]
788 fn resize_redraws_everything() {
789 let runs = grid().diff(&Grid::new(4, 4, Style::default()));
790 assert_eq!(runs.len(), 3);
791 assert!(runs.iter().all(|r| r.len == 10));
792 }
793
794 #[test]
795 fn wide_characters_take_two_cells() {
796 let mut g = grid();
797 let end = g.put_str(0, 0, "日本", Style::default(), 10);
798 assert_eq!(end, 4);
799 assert_eq!(g.cell(0, 0).symbol, "日");
800 assert_eq!(g.cell(1, 0).symbol, "");
801 assert_eq!(g.row_text(0).trim_end(), "日本");
802 }
803
804 #[test]
805 fn overwriting_half_a_wide_character_blanks_the_other_half() {
806 let mut g = grid();
807 g.put_str(0, 0, "日", Style::default(), 10);
808 g.put_str(1, 0, "x", Style::default(), 10);
809 assert_eq!(g.cell(0, 0).symbol, " ");
810 assert_eq!(g.cell(1, 0).symbol, "x");
811 }
812
813 #[test]
814 fn wide_character_at_the_edge_becomes_a_space() {
815 let mut g = grid();
816 g.put_str(9, 0, "日", Style::default(), 10);
817 assert_eq!(g.cell(9, 0).symbol, " ");
818 }
819
820 #[test]
821 fn combining_marks_stay_in_one_cell() {
822 let mut g = grid();
823 let end = g.put_str(0, 0, "e\u{301}x", Style::default(), 10);
824 assert_eq!(end, 2);
825 assert_eq!(g.cell(0, 0).symbol, "e\u{301}");
826 }
827
828 #[test]
829 fn diff_never_starts_on_a_continuation_cell() {
830 let mut before = grid();
831 before.put_str(0, 0, "日", Style::default(), 10);
832 let mut after = grid();
833 after.put_str(
834 0,
835 0,
836 "日",
837 Style {
838 bold: true,
839 ..Style::default()
840 },
841 10,
842 );
843 let mut only_right = before.clone();
844 only_right.cells[1].style.bold = true;
845 assert_eq!(only_right.diff(&before)[0].x, 0);
846 assert_eq!(after.diff(&before)[0].x, 0);
847 }
848}