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