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 large_button(
347 &mut self,
348 x: u16,
349 y: u16,
350 cells: &str,
351 label: &str,
352 fill: Rgb,
353 style: Style,
354 ) {
355 self.button_of(
356 (LARGE_BUTTON_HEIGHT, 0.0),
357 (x, y),
358 cells,
359 label,
360 fill,
361 style,
362 );
363 }
364
365 pub fn large_button_between(
367 &mut self,
368 x: u16,
369 y: u16,
370 cells: &str,
371 label: &str,
372 fill: Rgb,
373 style: Style,
374 ) {
375 self.button_of(
376 (LARGE_BUTTON_HEIGHT, 0.5),
377 (x, y),
378 cells,
379 label,
380 fill,
381 style,
382 );
383 }
384
385 fn button_of(
386 &mut self,
387 (height, drop): (f32, f32),
388 (x, y): (u16, u16),
389 cells: &str,
390 label: &str,
391 fill: Rgb,
392 style: Style,
393 ) {
394 let width = cells.chars().count() as u16;
395 let (left, top, right, bottom) = button_span((height, drop), (x, y), width);
396 self.put_str(
397 x,
398 y,
399 cells,
400 Style {
401 painted: true,
402 ..style
403 },
404 self.width,
405 );
406 let bounds = Bounds::cells(left, top, right - left, bottom - top);
407 self.panel(bounds, 22, Some(fill), None);
408 let middle = x as f32 + width as f32 / 2.0;
409 self.centred_text(middle, y as f32 + drop, label, style.fg, 90);
410 }
411
412 pub fn drop_last(&mut self, by: f32) {
414 match self.paint.last_mut() {
415 Some(Paint::Text { y, .. }) => *y += units(by),
416 Some(Paint::Icon { bounds, .. }) => bounds.y += units(by),
417 _ => {}
418 }
419 }
420
421 pub fn centred_text(&mut self, x: f32, y: f32, text: &str, color: Rgb, size: u8) {
423 self.paint.push(Paint::Text {
424 x: units(x),
425 y: units(y),
426 max_width: units(self.width as f32),
427 text: text.to_string(),
428 color,
429 font: Font {
430 size,
431 ..Font::default()
432 },
433 align_right: false,
434 centred: true,
435 underline: false,
436 });
437 }
438
439 pub fn panel(&mut self, bounds: Bounds, radius: u8, fill: Option<Rgb>, border: Option<Rgb>) {
440 self.paint.push(Paint::Panel {
441 bounds,
442 radius,
443 fill,
444 border,
445 shadow: false,
446 dashed: false,
447 });
448 }
449
450 pub fn dashed_panel(&mut self, bounds: Bounds, radius: u8, fill: Option<Rgb>, border: Rgb) {
452 self.paint.push(Paint::Panel {
453 bounds,
454 radius,
455 fill,
456 border: Some(border),
457 shadow: false,
458 dashed: true,
459 });
460 }
461
462 pub fn popup(&mut self, bounds: Bounds, radius: u8, fill: Rgb, border: Rgb) {
464 self.paint.push(Paint::Panel {
465 bounds,
466 radius,
467 fill: Some(fill),
468 border: Some(border),
469 shadow: true,
470 dashed: false,
471 });
472 }
473
474 pub fn wash(
476 &mut self,
477 bounds: Bounds,
478 radius: u8,
479 (color, alpha): (Rgb, u8),
480 border: Option<Rgb>,
481 ) {
482 self.paint.push(Paint::Wash {
483 bounds,
484 radius,
485 color,
486 alpha,
487 border,
488 });
489 }
490
491 pub fn hairline(&mut self, bounds: Bounds, color: Rgb) {
492 self.paint.push(Paint::Hairline { bounds, color });
493 }
494
495 pub fn glyph(&mut self, x: f32, y: u16, icon: Icon, color: Rgb, fallback: &str, style: Style) {
498 let cell = x.floor() as u16;
499 if cell < self.width && y < self.height {
500 self.put_str(
501 cell,
502 y,
503 fallback,
504 Style {
505 painted: true,
506 ..style
507 },
508 self.width,
509 );
510 }
511 self.paint.push(Paint::Icon {
512 bounds: Bounds::cells(x, y as f32 + 0.14, 2.0, 0.72),
513 icon,
514 color,
515 });
516 }
517
518 pub fn corners(&mut self, bounds: Bounds, radius: u8, color: Rgb, which: u8) {
520 self.paint.push(Paint::Corners {
521 bounds,
522 radius,
523 color,
524 which,
525 });
526 }
527
528 pub fn paint_on_row(&self, y: u16) -> impl Iterator<Item = &Paint> {
529 let (top, bottom) = (y as i32 * UNIT, (y as i32 + 1) * UNIT);
530 let kept_off = move |index: usize| {
531 self.kept.iter().any(|((from, to), (first, end))| {
532 (*from..*to).contains(&index) && !(*first..*end).contains(&y)
533 })
534 };
535 self.paint
536 .iter()
537 .enumerate()
538 .filter(move |(index, p)| {
539 let (from, to) = p.span();
540 from < bottom && to > top && !kept_off(*index)
541 })
542 .map(|(_, paint)| paint)
543 }
544
545 pub fn width(&self) -> u16 {
546 self.width
547 }
548
549 pub fn height(&self) -> u16 {
550 self.height
551 }
552
553 pub fn area(&self) -> Rect {
554 Rect::new(0, 0, self.width, self.height)
555 }
556
557 fn index(&self, x: u16, y: u16) -> usize {
558 y as usize * self.width as usize + x as usize
559 }
560
561 pub fn cell(&self, x: u16, y: u16) -> &Cell {
562 &self.cells[self.index(x, y)]
563 }
564
565 pub fn row(&self, y: u16) -> &[Cell] {
566 let start = self.index(0, y);
567 &self.cells[start..start + self.width as usize]
568 }
569
570 pub fn fill(&mut self, rect: Rect, style: Style) {
571 for y in rect.y..rect.bottom().min(self.height) {
572 for x in rect.x..rect.right().min(self.width) {
573 self.put_cell(x, y, " ", style);
574 }
575 }
576 }
577
578 fn put_cell(&mut self, x: u16, y: u16, symbol: &str, style: Style) {
579 let i = self.index(x, y);
581 if self.cells[i].symbol.is_empty() && x > 0 {
582 self.cells[i - 1].symbol = " ".into();
583 }
584 if x + 1 < self.width && self.cells[i + 1].symbol.is_empty() {
585 self.cells[i + 1].symbol = " ".into();
586 }
587 self.cells[i] = Cell {
588 symbol: symbol.into(),
589 style,
590 };
591 }
592
593 pub fn put_str(&mut self, x: u16, y: u16, text: &str, style: Style, max_x: u16) -> u16 {
596 if y >= self.height {
597 return x;
598 }
599 let max_x = max_x.min(self.width);
600 let mut at = x;
601 let text = visible(text);
602 for g in text.graphemes(true) {
603 if at >= max_x {
604 break;
605 }
606 let width = g.width() as u16;
607 if width == 0 {
608 continue;
609 }
610 if at + width > max_x {
611 self.put_cell(at, y, " ", style);
612 return at + 1;
613 }
614 self.put_cell(at, y, g, style);
615 if width == 2 {
616 self.put_cell(at + 1, y, "", style);
617 }
618 at += width;
619 }
620 at
621 }
622
623 pub fn put_icon(&mut self, x: u16, y: u16, icon: Icon, size: (u8, u8), style: Style) {
625 for row in 0..size.1 {
626 for column in 0..size.0 {
627 let (cx, cy) = (x + u16::from(column), y + u16::from(row));
628 if cx < self.width && cy < self.height {
629 let piece = Piece {
630 icon,
631 width: size.0,
632 height: size.1,
633 column,
634 row,
635 };
636 self.put_cell(cx, cy, piece.symbol().encode_utf8(&mut [0; 4]), style);
637 }
638 }
639 }
640 }
641
642 pub fn set_style(&mut self, rect: Rect, f: impl Fn(Style) -> Style) {
644 for y in rect.y..rect.bottom().min(self.height) {
645 for x in rect.x..rect.right().min(self.width) {
646 let i = self.index(x, y);
647 self.cells[i].style = f(self.cells[i].style);
648 }
649 }
650 }
651
652 pub fn diff(&self, prev: &Grid) -> Vec<Run> {
654 let same_size = self.width == prev.width && self.height == prev.height;
655 let mut runs = Vec::new();
656 for y in 0..self.height {
657 if same_size && self.row(y) == prev.row(y) {
658 continue;
659 }
660 let mut x = 0;
661 while x < self.width {
662 if same_size && self.cell(x, y) == prev.cell(x, y) {
663 x += 1;
664 continue;
665 }
666 let start = x;
667 while x < self.width && !(same_size && self.cell(x, y) == prev.cell(x, y)) {
668 x += 1;
669 }
670 let start = if self.cell(start, y).symbol.is_empty() && start > 0 {
672 start - 1
673 } else {
674 start
675 };
676 runs.push(Run {
677 x: start,
678 y,
679 len: x - start,
680 });
681 }
682 }
683 runs
684 }
685
686 pub fn row_text(&self, y: u16) -> String {
688 self.row(y).iter().map(|c| c.symbol.as_str()).collect()
689 }
690
691 pub fn text(&self) -> String {
693 (0..self.height)
694 .map(|y| self.row_text(y).trim_end().to_string())
695 .collect::<Vec<_>>()
696 .join("\n")
697 }
698}
699
700fn button_span((height, drop): (f32, f32), (x, y): (u16, u16), width: u16) -> (f32, f32, f32, f32) {
702 let top = y as f32 + drop + (1.0 - height) / 2.0;
703 (x as f32, top, (x + width) as f32, top + height)
704}
705
706pub fn on_large_button((x, y): (u16, u16), width: u16, at: (f32, f32)) -> bool {
711 let (left, top, right, bottom) = button_span((LARGE_BUTTON_HEIGHT, 0.0), (x, y), width);
712 at.0 >= left && at.0 < right && at.1 >= top && at.1 < bottom
713}
714
715#[cfg(test)]
716mod tests {
717 #[test]
720 fn paint_kept_to_its_rows_is_on_no_other() {
721 let style = Style::default();
722 let mut grid = Grid::new(10, 6, style);
723 let panel = |grid: &mut Grid, y: f32, h: f32| {
724 grid.panel(Bounds::cells(0.0, y, 10.0, h), 0, Some(Rgb(1, 2, 3)), None);
725 };
726 panel(&mut grid, 0.0, 1.0);
727 let from = grid.painted_so_far();
728 panel(&mut grid, 1.0, 4.5);
730 grid.keep_to_rows(from, 2, 4);
731 panel(&mut grid, 5.0, 1.0);
732 let on = |grid: &Grid, y: u16| grid.paint_on_row(y).count();
733 let rows: Vec<usize> = (0..6).map(|y| on(&grid, y)).collect();
734 assert_eq!(rows, [1, 0, 1, 1, 0, 1]);
735 grid.insert_paint(
737 0,
738 Paint::Hairline {
739 bounds: Bounds::cells(0.0, 1.0, 10.0, 0.0),
740 color: Rgb(9, 9, 9),
741 },
742 );
743 let rows: Vec<usize> = (0..6).map(|y| on(&grid, y)).collect();
744 assert_eq!(rows, [1, 1, 1, 1, 0, 1]);
745 }
746
747 #[test]
748 fn control_characters_never_reach_a_cell() {
749 let style = Style::default();
750 let mut grid = Grid::new(40, 2, style);
751 let text = "a\x1b]52;c;aGk=\x07b\r\n\x7f\u{9b}2Jc\td";
752 let end = grid.put_str(0, 0, text, style, 40);
753 let row: String = (0..end)
754 .map(|x| grid.cell(x, 0).symbol.to_string())
755 .collect();
756 assert_eq!(row, "a␛]52;c;aGk=␇b␍␊␡\u{fffd}2Jc d");
757 assert!(row.chars().all(|c| !c.is_control()), "{row:?}");
758 }
759
760 use super::*;
761
762 fn grid() -> Grid {
763 Grid::new(10, 3, Style::default())
764 }
765
766 #[test]
767 fn diff_emits_only_changed_cells() {
768 let before = grid();
769 let mut after = grid();
770 after.put_str(2, 1, "ab", Style::default(), 10);
771 after.put_str(7, 1, "c", Style::default(), 10);
772 assert_eq!(
773 after.diff(&before),
774 vec![Run { x: 2, y: 1, len: 2 }, Run { x: 7, y: 1, len: 1 }]
775 );
776 assert!(before.diff(&before.clone()).is_empty());
777 }
778
779 #[test]
780 fn resize_redraws_everything() {
781 let runs = grid().diff(&Grid::new(4, 4, Style::default()));
782 assert_eq!(runs.len(), 3);
783 assert!(runs.iter().all(|r| r.len == 10));
784 }
785
786 #[test]
787 fn wide_characters_take_two_cells() {
788 let mut g = grid();
789 let end = g.put_str(0, 0, "日本", Style::default(), 10);
790 assert_eq!(end, 4);
791 assert_eq!(g.cell(0, 0).symbol, "日");
792 assert_eq!(g.cell(1, 0).symbol, "");
793 assert_eq!(g.row_text(0).trim_end(), "日本");
794 }
795
796 #[test]
797 fn overwriting_half_a_wide_character_blanks_the_other_half() {
798 let mut g = grid();
799 g.put_str(0, 0, "日", Style::default(), 10);
800 g.put_str(1, 0, "x", Style::default(), 10);
801 assert_eq!(g.cell(0, 0).symbol, " ");
802 assert_eq!(g.cell(1, 0).symbol, "x");
803 }
804
805 #[test]
806 fn wide_character_at_the_edge_becomes_a_space() {
807 let mut g = grid();
808 g.put_str(9, 0, "日", Style::default(), 10);
809 assert_eq!(g.cell(9, 0).symbol, " ");
810 }
811
812 #[test]
813 fn combining_marks_stay_in_one_cell() {
814 let mut g = grid();
815 let end = g.put_str(0, 0, "e\u{301}x", Style::default(), 10);
816 assert_eq!(end, 2);
817 assert_eq!(g.cell(0, 0).symbol, "e\u{301}");
818 }
819
820 #[test]
821 fn diff_never_starts_on_a_continuation_cell() {
822 let mut before = grid();
823 before.put_str(0, 0, "日", Style::default(), 10);
824 let mut after = grid();
825 after.put_str(
826 0,
827 0,
828 "日",
829 Style {
830 bold: true,
831 ..Style::default()
832 },
833 10,
834 );
835 let mut only_right = before.clone();
836 only_right.cells[1].style.bold = true;
837 assert_eq!(only_right.diff(&before)[0].x, 0);
838 assert_eq!(after.diff(&before)[0].x, 0);
839 }
840}