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}
122
123impl Grid {
124 pub fn scroll_rows(&mut self, top: u16, bottom: u16, by: i32) {
128 let width = self.width as usize;
129 let (top, bottom) = (
130 top as usize,
131 (bottom as usize).min(self.height as usize - 1),
132 );
133 if top > bottom || by == 0 {
134 return;
135 }
136 let rows = bottom + 1 - top;
137 let n = (by.unsigned_abs() as usize).min(rows);
138 let unknown = Cell {
139 symbol: CompactString::const_new("\u{fffe}"),
140 style: Style::default(),
141 };
142 let row = |y: usize| y * width..(y + 1) * width;
143 if by > 0 {
144 for y in top..bottom + 1 - n {
145 self.cells.copy_within_cells(row(y + n), row(y).start);
146 }
147 for y in bottom + 1 - n..=bottom {
148 self.cells[row(y)].fill(unknown.clone());
149 }
150 } else {
151 for y in (top + n..=bottom).rev() {
152 self.cells.copy_within_cells(row(y - n), row(y).start);
153 }
154 for y in top..top + n {
155 self.cells[row(y)].fill(unknown.clone());
156 }
157 }
158 }
159
160 pub fn new(width: u16, height: u16, style: Style) -> Self {
161 let blank = Cell {
162 symbol: " ".into(),
163 style,
164 };
165 Self {
166 width,
167 height,
168 cells: vec![blank; width as usize * height as usize],
169 cursor: None,
170 caret: None,
171 paint: Vec::new(),
172 bands: Vec::new(),
173 }
174 }
175
176 pub fn label(&mut self, x: u16, y: u16, text: &str, style: Style, max_x: u16) -> u16 {
178 self.label_at(x as f32, x, y, text, style, max_x, 100)
179 }
180
181 pub fn painted_so_far(&self) -> usize {
183 self.paint.len()
184 }
185
186 pub fn lift_since(&mut self, from: usize, rows: f32) {
189 let by = units(rows);
190 for paint in self.paint.iter_mut().skip(from) {
191 paint.lift(by);
192 }
193 }
194
195 #[allow(clippy::too_many_arguments)]
197 pub fn label_at(
198 &mut self,
199 x_px: f32,
200 x: u16,
201 y: u16,
202 text: &str,
203 style: Style,
204 max_x: u16,
205 size: u8,
206 ) -> u16 {
207 let end = self.put_str(
208 x,
209 y,
210 text,
211 Style {
212 painted: true,
213 ..style
214 },
215 max_x,
216 );
217 if y < self.height {
218 self.paint.push(Paint::Text {
219 x: units(x_px),
220 y: y as i32 * UNIT,
221 max_width: units(max_x.min(self.width) as f32 - x_px),
222 text: text.to_string(),
223 color: style.fg,
224 font: Font {
225 bold: style.bold,
226 size,
227 ..Font::default()
228 },
229 align_right: false,
230 centred: false,
231 underline: false,
232 });
233 }
234 end
235 }
236
237 pub fn text_run(
239 &mut self,
240 (x, y): (f32, f32),
241 max_x: f32,
242 text: &str,
243 (color, underline): (Rgb, bool),
244 font: Font,
245 ) {
246 self.paint.push(Paint::Text {
247 x: units(x),
248 y: units(y),
249 max_width: units(max_x - x),
250 text: text.to_string(),
251 color,
252 font,
253 align_right: false,
254 centred: false,
255 underline,
256 });
257 }
258
259 pub fn set_caret(&mut self, x: f32, y: u16, height: f32) {
261 self.cursor = Some((x as u16, y));
262 let top = y as f32 + (1.0 - height) / 2.0;
263 self.caret = Some(Bounds::cells(x, top, 0.0, height));
264 }
265
266 pub fn label_right(&mut self, right: u16, y: u16, text: &str, style: Style, size: u8) {
269 let cells = text.chars().count() as u16;
270 let x = right.saturating_sub(cells);
271 self.put_str(
272 x,
273 y,
274 text,
275 Style {
276 painted: true,
277 ..style
278 },
279 right,
280 );
281 self.paint.push(Paint::Text {
282 x: units(right as f32),
283 y: y as i32 * UNIT,
284 max_width: units(right as f32),
285 text: text.to_string(),
286 color: style.fg,
287 font: Font {
288 bold: style.bold,
289 size,
290 ..Font::default()
291 },
292 align_right: true,
293 centred: false,
294 underline: false,
295 });
296 }
297
298 pub fn field(&mut self, rect: Rect, behind: Rgb, fill: Rgb, border: Rgb) {
300 self.panel(Bounds::inset(rect, 0.0, 0.0), 0, Some(behind), None);
301 self.panel(
304 Bounds::inset(rect, 0.15, 0.11),
305 22,
306 Some(fill),
307 Some(border),
308 );
309 }
310
311 pub fn button(&mut self, x: u16, y: u16, cells: &str, label: &str, fill: Rgb, style: Style) {
314 self.button_of((BUTTON_HEIGHT, 0.0), (x, y), cells, label, fill, style);
315 }
316
317 pub fn large_button(
319 &mut self,
320 x: u16,
321 y: u16,
322 cells: &str,
323 label: &str,
324 fill: Rgb,
325 style: Style,
326 ) {
327 self.button_of(
328 (LARGE_BUTTON_HEIGHT, 0.0),
329 (x, y),
330 cells,
331 label,
332 fill,
333 style,
334 );
335 }
336
337 pub fn large_button_between(
339 &mut self,
340 x: u16,
341 y: u16,
342 cells: &str,
343 label: &str,
344 fill: Rgb,
345 style: Style,
346 ) {
347 self.button_of(
348 (LARGE_BUTTON_HEIGHT, 0.5),
349 (x, y),
350 cells,
351 label,
352 fill,
353 style,
354 );
355 }
356
357 fn button_of(
358 &mut self,
359 (height, drop): (f32, f32),
360 (x, y): (u16, u16),
361 cells: &str,
362 label: &str,
363 fill: Rgb,
364 style: Style,
365 ) {
366 let width = cells.chars().count() as u16;
367 let (left, top, right, bottom) = button_span((height, drop), (x, y), width);
368 self.put_str(
369 x,
370 y,
371 cells,
372 Style {
373 painted: true,
374 ..style
375 },
376 self.width,
377 );
378 let bounds = Bounds::cells(left, top, right - left, bottom - top);
379 self.panel(bounds, 22, Some(fill), None);
380 let middle = x as f32 + width as f32 / 2.0;
381 self.centred_text(middle, y as f32 + drop, label, style.fg, 90);
382 }
383
384 pub fn drop_last(&mut self, by: f32) {
386 match self.paint.last_mut() {
387 Some(Paint::Text { y, .. }) => *y += units(by),
388 Some(Paint::Icon { bounds, .. }) => bounds.y += units(by),
389 _ => {}
390 }
391 }
392
393 pub fn centred_text(&mut self, x: f32, y: f32, text: &str, color: Rgb, size: u8) {
395 self.paint.push(Paint::Text {
396 x: units(x),
397 y: units(y),
398 max_width: units(self.width as f32),
399 text: text.to_string(),
400 color,
401 font: Font {
402 size,
403 ..Font::default()
404 },
405 align_right: false,
406 centred: true,
407 underline: false,
408 });
409 }
410
411 pub fn panel(&mut self, bounds: Bounds, radius: u8, fill: Option<Rgb>, border: Option<Rgb>) {
412 self.paint.push(Paint::Panel {
413 bounds,
414 radius,
415 fill,
416 border,
417 shadow: false,
418 dashed: false,
419 });
420 }
421
422 pub fn dashed_panel(&mut self, bounds: Bounds, radius: u8, fill: Option<Rgb>, border: Rgb) {
424 self.paint.push(Paint::Panel {
425 bounds,
426 radius,
427 fill,
428 border: Some(border),
429 shadow: false,
430 dashed: true,
431 });
432 }
433
434 pub fn popup(&mut self, bounds: Bounds, radius: u8, fill: Rgb, border: Rgb) {
436 self.paint.push(Paint::Panel {
437 bounds,
438 radius,
439 fill: Some(fill),
440 border: Some(border),
441 shadow: true,
442 dashed: false,
443 });
444 }
445
446 pub fn wash(
448 &mut self,
449 bounds: Bounds,
450 radius: u8,
451 (color, alpha): (Rgb, u8),
452 border: Option<Rgb>,
453 ) {
454 self.paint.push(Paint::Wash {
455 bounds,
456 radius,
457 color,
458 alpha,
459 border,
460 });
461 }
462
463 pub fn hairline(&mut self, bounds: Bounds, color: Rgb) {
464 self.paint.push(Paint::Hairline { bounds, color });
465 }
466
467 pub fn glyph(&mut self, x: f32, y: u16, icon: Icon, color: Rgb, fallback: &str, style: Style) {
470 let cell = x.floor() as u16;
471 if cell < self.width && y < self.height {
472 self.put_str(
473 cell,
474 y,
475 fallback,
476 Style {
477 painted: true,
478 ..style
479 },
480 self.width,
481 );
482 }
483 self.paint.push(Paint::Icon {
484 bounds: Bounds::cells(x, y as f32 + 0.14, 2.0, 0.72),
485 icon,
486 color,
487 });
488 }
489
490 pub fn corners(&mut self, bounds: Bounds, radius: u8, color: Rgb, which: u8) {
492 self.paint.push(Paint::Corners {
493 bounds,
494 radius,
495 color,
496 which,
497 });
498 }
499
500 pub fn paint_on_row(&self, y: u16) -> impl Iterator<Item = &Paint> {
501 let (top, bottom) = (y as i32 * UNIT, (y as i32 + 1) * UNIT);
502 self.paint.iter().filter(move |p| {
503 let (from, to) = p.span();
504 from < bottom && to > top
505 })
506 }
507
508 pub fn width(&self) -> u16 {
509 self.width
510 }
511
512 pub fn height(&self) -> u16 {
513 self.height
514 }
515
516 pub fn area(&self) -> Rect {
517 Rect::new(0, 0, self.width, self.height)
518 }
519
520 fn index(&self, x: u16, y: u16) -> usize {
521 y as usize * self.width as usize + x as usize
522 }
523
524 pub fn cell(&self, x: u16, y: u16) -> &Cell {
525 &self.cells[self.index(x, y)]
526 }
527
528 pub fn row(&self, y: u16) -> &[Cell] {
529 let start = self.index(0, y);
530 &self.cells[start..start + self.width as usize]
531 }
532
533 pub fn fill(&mut self, rect: Rect, style: Style) {
534 for y in rect.y..rect.bottom().min(self.height) {
535 for x in rect.x..rect.right().min(self.width) {
536 self.put_cell(x, y, " ", style);
537 }
538 }
539 }
540
541 fn put_cell(&mut self, x: u16, y: u16, symbol: &str, style: Style) {
542 let i = self.index(x, y);
544 if self.cells[i].symbol.is_empty() && x > 0 {
545 self.cells[i - 1].symbol = " ".into();
546 }
547 if x + 1 < self.width && self.cells[i + 1].symbol.is_empty() {
548 self.cells[i + 1].symbol = " ".into();
549 }
550 self.cells[i] = Cell {
551 symbol: symbol.into(),
552 style,
553 };
554 }
555
556 pub fn put_str(&mut self, x: u16, y: u16, text: &str, style: Style, max_x: u16) -> u16 {
559 if y >= self.height {
560 return x;
561 }
562 let max_x = max_x.min(self.width);
563 let mut at = x;
564 let text = visible(text);
565 for g in text.graphemes(true) {
566 if at >= max_x {
567 break;
568 }
569 let width = g.width() as u16;
570 if width == 0 {
571 continue;
572 }
573 if at + width > max_x {
574 self.put_cell(at, y, " ", style);
575 return at + 1;
576 }
577 self.put_cell(at, y, g, style);
578 if width == 2 {
579 self.put_cell(at + 1, y, "", style);
580 }
581 at += width;
582 }
583 at
584 }
585
586 pub fn put_icon(&mut self, x: u16, y: u16, icon: Icon, size: (u8, u8), style: Style) {
588 for row in 0..size.1 {
589 for column in 0..size.0 {
590 let (cx, cy) = (x + u16::from(column), y + u16::from(row));
591 if cx < self.width && cy < self.height {
592 let piece = Piece {
593 icon,
594 width: size.0,
595 height: size.1,
596 column,
597 row,
598 };
599 self.put_cell(cx, cy, piece.symbol().encode_utf8(&mut [0; 4]), style);
600 }
601 }
602 }
603 }
604
605 pub fn set_style(&mut self, rect: Rect, f: impl Fn(Style) -> Style) {
607 for y in rect.y..rect.bottom().min(self.height) {
608 for x in rect.x..rect.right().min(self.width) {
609 let i = self.index(x, y);
610 self.cells[i].style = f(self.cells[i].style);
611 }
612 }
613 }
614
615 pub fn diff(&self, prev: &Grid) -> Vec<Run> {
617 let same_size = self.width == prev.width && self.height == prev.height;
618 let mut runs = Vec::new();
619 for y in 0..self.height {
620 if same_size && self.row(y) == prev.row(y) {
621 continue;
622 }
623 let mut x = 0;
624 while x < self.width {
625 if same_size && self.cell(x, y) == prev.cell(x, y) {
626 x += 1;
627 continue;
628 }
629 let start = x;
630 while x < self.width && !(same_size && self.cell(x, y) == prev.cell(x, y)) {
631 x += 1;
632 }
633 let start = if self.cell(start, y).symbol.is_empty() && start > 0 {
635 start - 1
636 } else {
637 start
638 };
639 runs.push(Run {
640 x: start,
641 y,
642 len: x - start,
643 });
644 }
645 }
646 runs
647 }
648
649 pub fn row_text(&self, y: u16) -> String {
651 self.row(y).iter().map(|c| c.symbol.as_str()).collect()
652 }
653
654 pub fn text(&self) -> String {
656 (0..self.height)
657 .map(|y| self.row_text(y).trim_end().to_string())
658 .collect::<Vec<_>>()
659 .join("\n")
660 }
661}
662
663fn button_span((height, drop): (f32, f32), (x, y): (u16, u16), width: u16) -> (f32, f32, f32, f32) {
665 let top = y as f32 + drop + (1.0 - height) / 2.0;
666 (x as f32, top, (x + width) as f32, top + height)
667}
668
669pub fn on_large_button((x, y): (u16, u16), width: u16, at: (f32, f32)) -> bool {
674 let (left, top, right, bottom) = button_span((LARGE_BUTTON_HEIGHT, 0.0), (x, y), width);
675 at.0 >= left && at.0 < right && at.1 >= top && at.1 < bottom
676}
677
678#[cfg(test)]
679mod tests {
680
681 #[test]
682 fn control_characters_never_reach_a_cell() {
683 let style = Style::default();
684 let mut grid = Grid::new(40, 2, style);
685 let text = "a\x1b]52;c;aGk=\x07b\r\n\x7f\u{9b}2Jc\td";
686 let end = grid.put_str(0, 0, text, style, 40);
687 let row: String = (0..end)
688 .map(|x| grid.cell(x, 0).symbol.to_string())
689 .collect();
690 assert_eq!(row, "a␛]52;c;aGk=␇b␍␊␡\u{fffd}2Jc d");
691 assert!(row.chars().all(|c| !c.is_control()), "{row:?}");
692 }
693
694 use super::*;
695
696 fn grid() -> Grid {
697 Grid::new(10, 3, Style::default())
698 }
699
700 #[test]
701 fn diff_emits_only_changed_cells() {
702 let before = grid();
703 let mut after = grid();
704 after.put_str(2, 1, "ab", Style::default(), 10);
705 after.put_str(7, 1, "c", Style::default(), 10);
706 assert_eq!(
707 after.diff(&before),
708 vec![Run { x: 2, y: 1, len: 2 }, Run { x: 7, y: 1, len: 1 }]
709 );
710 assert!(before.diff(&before.clone()).is_empty());
711 }
712
713 #[test]
714 fn resize_redraws_everything() {
715 let runs = grid().diff(&Grid::new(4, 4, Style::default()));
716 assert_eq!(runs.len(), 3);
717 assert!(runs.iter().all(|r| r.len == 10));
718 }
719
720 #[test]
721 fn wide_characters_take_two_cells() {
722 let mut g = grid();
723 let end = g.put_str(0, 0, "日本", Style::default(), 10);
724 assert_eq!(end, 4);
725 assert_eq!(g.cell(0, 0).symbol, "日");
726 assert_eq!(g.cell(1, 0).symbol, "");
727 assert_eq!(g.row_text(0).trim_end(), "日本");
728 }
729
730 #[test]
731 fn overwriting_half_a_wide_character_blanks_the_other_half() {
732 let mut g = grid();
733 g.put_str(0, 0, "日", Style::default(), 10);
734 g.put_str(1, 0, "x", Style::default(), 10);
735 assert_eq!(g.cell(0, 0).symbol, " ");
736 assert_eq!(g.cell(1, 0).symbol, "x");
737 }
738
739 #[test]
740 fn wide_character_at_the_edge_becomes_a_space() {
741 let mut g = grid();
742 g.put_str(9, 0, "日", Style::default(), 10);
743 assert_eq!(g.cell(9, 0).symbol, " ");
744 }
745
746 #[test]
747 fn combining_marks_stay_in_one_cell() {
748 let mut g = grid();
749 let end = g.put_str(0, 0, "e\u{301}x", Style::default(), 10);
750 assert_eq!(end, 2);
751 assert_eq!(g.cell(0, 0).symbol, "e\u{301}");
752 }
753
754 #[test]
755 fn diff_never_starts_on_a_continuation_cell() {
756 let mut before = grid();
757 before.put_str(0, 0, "日", Style::default(), 10);
758 let mut after = grid();
759 after.put_str(
760 0,
761 0,
762 "日",
763 Style {
764 bold: true,
765 ..Style::default()
766 },
767 10,
768 );
769 let mut only_right = before.clone();
770 only_right.cells[1].style.bold = true;
771 assert_eq!(only_right.diff(&before)[0].x, 0);
772 assert_eq!(after.diff(&before)[0].x, 0);
773 }
774}