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;
16const ROW_BUTTON_RADIUS: u8 = 17;
19const EXACT_FILL: u64 = u64::MAX - 1;
21pub const WORDS_BASELINE: f32 = 0.026;
27pub const GLYPH: f32 = 0.86;
29pub const SMALL_GLYPH: f32 = 0.70;
32pub const FIELD_AIR: f32 = 0.0625;
36pub const GLYPH_LEAD: f32 = 0.15;
39
40#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
41pub struct Rgb(pub u8, pub u8, pub u8);
42
43#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
44pub struct Style {
45 pub fg: Rgb,
46 pub bg: Rgb,
47 pub bold: bool,
48 pub italic: bool,
49 pub underline: bool,
50 pub painted: bool,
52}
53
54fn visible(text: &str) -> std::borrow::Cow<'_, str> {
59 let control = |c: char| c.is_control();
60 if !text.contains(control) {
61 return std::borrow::Cow::Borrowed(text);
62 }
63 let shown = text
64 .chars()
65 .map(|c| match c {
66 '\t' => ' ',
67 '\0'..='\u{1f}' => char::from_u32(0x2400 + c as u32).unwrap_or('\u{fffd}'),
68 '\u{7f}' => '\u{2421}',
69 c if c.is_control() => '\u{fffd}',
70 c => c,
71 })
72 .collect();
73 std::borrow::Cow::Owned(shown)
74}
75
76#[derive(Clone, Debug, PartialEq, Eq, Hash)]
78pub struct Cell {
79 pub symbol: CompactString,
80 pub style: Style,
81}
82
83#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
87pub enum CursorShape {
88 #[default]
89 Bar,
90 Block,
91 Underline,
92}
93
94#[derive(Clone, Debug, PartialEq, Eq)]
99pub struct TermCursor {
100 pub at: (u16, u16),
101 pub on: Cell,
102 pub off: Cell,
103 pub shape: CursorShape,
104 pub blinks: bool,
105}
106
107#[derive(Clone, Debug, Default, PartialEq, Eq)]
110struct Blinked {
111 caret: Option<Bounds>,
112 cursor: Option<(u16, u16)>,
113 cells: Vec<(u16, u16, Cell)>,
114}
115
116trait CopyCells {
118 fn copy_within_cells(&mut self, from: std::ops::Range<usize>, to: usize);
119}
120
121impl CopyCells for Vec<Cell> {
122 fn copy_within_cells(&mut self, from: std::ops::Range<usize>, to: usize) {
123 for (n, at) in from.enumerate() {
124 let cell = self[at].clone();
125 self[to + n] = cell;
126 }
127 }
128}
129
130#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
131pub struct Rect {
132 pub x: u16,
133 pub y: u16,
134 pub w: u16,
135 pub h: u16,
136}
137
138impl Rect {
139 pub fn new(x: u16, y: u16, w: u16, h: u16) -> Self {
140 Self { x, y, w, h }
141 }
142
143 pub fn contains(&self, x: u16, y: u16) -> bool {
144 x >= self.x && x < self.x + self.w && y >= self.y && y < self.y + self.h
145 }
146
147 pub fn right(&self) -> u16 {
148 self.x + self.w
149 }
150
151 pub fn bottom(&self) -> u16 {
152 self.y + self.h
153 }
154}
155
156#[derive(Clone, Copy, Debug, PartialEq, Eq)]
158pub struct Run {
159 pub x: u16,
160 pub y: u16,
161 pub len: u16,
162}
163
164#[derive(Clone, Debug, PartialEq, Eq)]
165pub struct Grid {
166 width: u16,
167 height: u16,
168 cells: Vec<Cell>,
169 pub cursor: Option<(u16, u16)>,
170 pub caret: Option<Bounds>,
172 pub paint: Vec<Paint>,
174 pub bands: Vec<u16>,
177 pub edge: Option<Rgb>,
180 pub roomy: bool,
184 pub row_air: u16,
188 pub foot: u16,
193 pub row_bands: Option<(u16, Vec<u16>)>,
197 pub turn: Option<u8>,
200 pub spinning: bool,
203 turning: Vec<(u16, u16)>,
205 kept: Vec<((usize, usize), (u16, u16))>,
209 pub cursor_shape: CursorShape,
211 pub cursor_blinks: bool,
215 pub term_cursors: Vec<TermCursor>,
217 blinking: Vec<(u16, u16, Cell, Cell)>,
220 blinked: Option<Blinked>,
222}
223
224impl Grid {
225 pub fn scroll_rows(&mut self, top: u16, bottom: u16, by: i32) {
229 let width = self.width as usize;
230 let (top, bottom) = (
231 top as usize,
232 (bottom as usize).min(self.height as usize - 1),
233 );
234 if top > bottom || by == 0 {
235 return;
236 }
237 let rows = bottom + 1 - top;
238 let n = (by.unsigned_abs() as usize).min(rows);
239 let unknown = Cell {
240 symbol: CompactString::const_new("\u{fffe}"),
241 style: Style::default(),
242 };
243 let row = |y: usize| y * width..(y + 1) * width;
244 if by > 0 {
245 for y in top..bottom + 1 - n {
246 self.cells.copy_within_cells(row(y + n), row(y).start);
247 }
248 for y in bottom + 1 - n..=bottom {
249 self.cells[row(y)].fill(unknown.clone());
250 }
251 } else {
252 for y in (top + n..=bottom).rev() {
253 self.cells.copy_within_cells(row(y - n), row(y).start);
254 }
255 for y in top..top + n {
256 self.cells[row(y)].fill(unknown.clone());
257 }
258 }
259 }
260
261 pub fn new(width: u16, height: u16, style: Style) -> Self {
262 let blank = Cell {
263 symbol: " ".into(),
264 style,
265 };
266 Self {
267 width,
268 height,
269 cells: vec![blank; width as usize * height as usize],
270 cursor: None,
271 caret: None,
272 paint: Vec::new(),
273 bands: Vec::new(),
274 edge: None,
275 roomy: false,
276 row_air: 100,
277 foot: 1,
278 row_bands: None,
279 turn: Some(0),
280 spinning: false,
281 turning: Vec::new(),
282 kept: Vec::new(),
283 cursor_shape: CursorShape::Bar,
284 cursor_blinks: false,
285 term_cursors: Vec::new(),
286 blinking: Vec::new(),
287 blinked: None,
288 }
289 }
290
291 pub fn blink_cell(&mut self, x: u16, y: u16, off: Cell) {
294 if x < self.width && y < self.height {
295 let on = self.cell(x, y).clone();
296 self.blinking.push((x, y, off, on));
297 }
298 }
299
300 pub fn blinks(&self) -> bool {
303 self.cursor_blinks
304 && (self.caret.is_some()
305 || self.cursor.is_some()
306 || self.blinked.is_some()
307 || !self.blinking.is_empty())
308 }
309
310 pub fn caret_shown(&self) -> bool {
312 self.blinked.is_none()
313 }
314
315 pub fn blink_to(&mut self, shown: bool) {
321 if shown == self.caret_shown() || (!shown && !self.blinks()) {
322 return;
323 }
324 if shown {
325 let blinked = self.blinked.take().unwrap_or_default();
326 self.caret = blinked.caret;
327 self.cursor = blinked.cursor;
328 for (x, y, on) in blinked.cells {
329 let at = self.index(x, y);
330 self.cells[at] = on;
331 }
332 return;
333 }
334 let mut cells = Vec::new();
335 for (x, y, off, on) in &self.blinking {
336 let at = self.index(*x, *y);
337 if self.cells[at] == *on {
338 self.cells[at] = off.clone();
339 cells.push((*x, *y, on.clone()));
340 }
341 }
342 self.blinked = Some(Blinked {
343 caret: self.caret.take(),
344 cursor: self.cursor.take(),
345 cells,
346 });
347 }
348
349 pub fn spinner(&mut self, x: f32, y: u16, size: f32, color: Rgb, style: Style) {
355 self.spinner_in((x, x.floor() as u16), y, size, color, style);
356 }
357
358 pub fn spinner_in(
362 &mut self,
363 (x, cell): (f32, u16),
364 y: u16,
365 size: f32,
366 color: Rgb,
367 style: Style,
368 ) {
369 let step = self.turn;
370 self.spinning |= step.is_some();
371 let letter = step.map_or(crate::spinner::STILL, |s| {
372 crate::spinner::FRAMES[s as usize % crate::spinner::FRAMES.len()]
373 });
374 self.mark((x, cell), y, size, color, style, (step, letter));
375 }
376
377 pub fn turn_to(&mut self, step: u8) {
381 if self.turn.is_none() {
382 return;
383 }
384 self.turn = Some(step);
385 for paint in &mut self.paint {
386 if let Paint::Spinner { step: Some(at), .. } = paint {
387 *at = step;
388 }
389 }
390 let letter = crate::spinner::FRAMES[step as usize % crate::spinner::FRAMES.len()];
391 for &(x, y) in &self.turning {
392 let at = y as usize * self.width as usize + x as usize;
393 let cell = self.cells.get_mut(at).filter(|_| x < self.width);
395 if let Some(cell) = cell.filter(|c| crate::spinner::FRAMES.contains(&c.symbol.as_str()))
396 {
397 cell.symbol = letter.into();
398 }
399 }
400 }
401
402 pub fn dot(&mut self, x: f32, y: u16, size: f32, color: Rgb, style: Style) {
405 self.dot_in((x, x.floor() as u16), y, size, color, style);
406 }
407
408 pub fn dot_in(&mut self, (x, cell): (f32, u16), y: u16, size: f32, color: Rgb, style: Style) {
410 let still = (None, crate::spinner::STILL);
411 self.mark((x, cell), y, size, color, style, still);
412 }
413
414 fn mark(
415 &mut self,
416 (x, cell): (f32, u16),
417 y: u16,
418 size: f32,
419 color: Rgb,
420 style: Style,
421 (step, letter): (Option<u8>, &str),
422 ) {
423 if step.is_some() {
424 self.turning.push((cell, y));
425 }
426 if cell < self.width && y < self.height {
427 let shown = Style {
428 fg: color,
429 painted: true,
430 ..style
431 };
432 self.put_str(cell, y, letter, shown, cell + 1);
433 }
434 self.paint.push(Paint::Spinner {
435 bounds: Bounds::cells(x, y as f32 + (1.0 - size) / 2.0, 2.0, size),
436 color,
437 step,
438 });
439 }
440
441 pub fn label(&mut self, x: u16, y: u16, text: &str, style: Style, max_x: u16) -> u16 {
443 self.label_at(x as f32, x, y, text, style, max_x, 100)
444 }
445
446 pub fn clear_paint_in(&mut self, area: Rect) {
449 let (left, right) = (i32::from(area.x) * UNIT, i32::from(area.right()) * UNIT);
450 let (top, bottom) = (i32::from(area.y) * UNIT, i32::from(area.bottom()) * UNIT);
451 self.paint.retain(|paint| {
452 let (from, _) = paint.reach();
453 let start = paint.top();
454 !(start >= top && start < bottom && from >= left && from < right)
455 });
456 }
457
458 pub fn pictures_again_in(&mut self, before: usize, area: Rect) {
466 let clip_to = |clip: Bounds, (left, top, right, bottom): (i32, i32, i32, i32)| {
467 let (x, y) = (clip.x.max(left), clip.y.max(top));
468 let (end_x, end_y) = ((clip.x + clip.w).min(right), (clip.y + clip.h).min(bottom));
469 Bounds {
470 x,
471 y,
472 w: end_x - x,
473 h: end_y - y,
474 }
475 };
476 let (left, right) = (i32::from(area.x) * UNIT, i32::from(area.right()) * UNIT);
477 let (top, bottom) = (i32::from(area.y) * UNIT, i32::from(area.bottom()) * UNIT);
478 let mut again = Vec::new();
479 for (index, paint) in self.paint.iter().enumerate().take(before) {
480 let Paint::Image {
481 bounds,
482 clip,
483 bitmap,
484 color,
485 } = paint
486 else {
487 continue;
488 };
489 if bitmap.id == EXACT_FILL {
490 continue;
491 }
492 let mut clip = clip_to(*clip, (left, top, right, bottom));
493 for ((from, to), (first, end)) in &self.kept {
494 if (*from..*to).contains(&index) {
495 let rows = (i32::from(*first) * UNIT, i32::from(*end) * UNIT);
496 clip = clip_to(clip, (left, rows.0, right, rows.1));
497 }
498 }
499 let shown = clip_to(
500 clip,
501 (bounds.x, bounds.y, bounds.x + bounds.w, bounds.y + bounds.h),
502 );
503 if shown.w > 0 && shown.h > 0 {
504 again.push(Paint::Image {
505 bounds: *bounds,
506 clip,
507 bitmap: bitmap.clone(),
508 color: *color,
509 });
510 }
511 }
512 self.paint.extend(again);
513 }
514
515 pub fn painted_so_far(&self) -> usize {
517 self.paint.len()
518 }
519
520 pub fn keep_to_rows(&mut self, from: usize, top: u16, bottom: u16) {
523 if from < self.paint.len() {
524 self.kept.push(((from, self.paint.len()), (top, bottom)));
525 }
526 }
527
528 pub fn insert_paint(&mut self, index: usize, paint: Paint) {
530 let index = index.min(self.paint.len());
531 self.paint.insert(index, paint);
532 for ((from, to), _) in &mut self.kept {
534 if index < *from {
535 *from += 1;
536 }
537 if index < *to {
538 *to += 1;
539 }
540 }
541 }
542
543 pub fn lift_since(&mut self, from: usize, rows: f32) {
546 let by = units(rows);
547 for paint in self.paint.iter_mut().skip(from) {
548 paint.lift(by);
549 }
550 }
551
552 pub fn nudge_since(&mut self, from: usize, columns: f32) {
555 let by = units(columns);
556 for paint in self.paint.iter_mut().skip(from) {
557 match paint {
558 Paint::Text { x, .. } => *x += by,
559 Paint::Panel { bounds, .. }
560 | Paint::Wash { bounds, .. }
561 | Paint::Hairline { bounds, .. }
562 | Paint::Icon { bounds, .. }
563 | Paint::Monogram { bounds, .. }
564 | Paint::Spinner { bounds, .. }
565 | Paint::Corners { bounds, .. }
566 | Paint::Strips { bounds, .. } => bounds.x += by,
567 Paint::Image { bounds, clip, .. } => {
568 bounds.x += by;
569 clip.x += by;
570 }
571 }
572 }
573 }
574
575 #[allow(clippy::too_many_arguments)]
577 pub fn label_at(
578 &mut self,
579 x_px: f32,
580 x: u16,
581 y: u16,
582 text: &str,
583 style: Style,
584 max_x: u16,
585 size: u8,
586 ) -> u16 {
587 let end = self.put_str(
588 x,
589 y,
590 text,
591 Style {
592 painted: true,
593 ..style
594 },
595 max_x,
596 );
597 if y < self.height {
598 self.paint.push(Paint::Text {
599 x: units(x_px),
600 y: y as i32 * UNIT,
601 max_width: units(max_x.min(self.width) as f32 - x_px),
602 text: text.to_string(),
603 color: style.fg,
604 font: Font {
605 bold: style.bold,
606 size,
607 ..Font::default()
608 },
609 align_right: false,
610 centred: false,
611 underline: false,
612 span_centred: false,
613 });
614 }
615 end
616 }
617
618 pub fn text_run(
620 &mut self,
621 (x, y): (f32, f32),
622 max_x: f32,
623 text: &str,
624 (color, underline): (Rgb, bool),
625 font: Font,
626 ) {
627 self.paint.push(Paint::Text {
628 x: units(x),
629 y: units(y),
630 max_width: units(max_x - x),
631 text: text.to_string(),
632 color,
633 font,
634 align_right: false,
635 centred: false,
636 underline,
637 span_centred: false,
638 });
639 }
640
641 pub fn set_caret(&mut self, x: f32, y: u16, height: f32) {
643 self.cursor = Some((x as u16, y));
644 let top = y as f32 + (1.0 - height) / 2.0;
645 self.caret = Some(Bounds::cells(x, top, 0.0, height));
646 }
647
648 pub fn label_right(&mut self, right: u16, y: u16, text: &str, style: Style, size: u8) {
651 self.label_right_at(right as f32, right, y, text, style, size);
652 }
653
654 pub fn label_right_at(
657 &mut self,
658 right: f32,
659 cell: u16,
660 y: u16,
661 text: &str,
662 style: Style,
663 size: u8,
664 ) {
665 let cells = text.chars().count() as u16;
666 let x = cell.saturating_sub(cells);
667 self.put_str(
668 x,
669 y,
670 text,
671 Style {
672 painted: true,
673 ..style
674 },
675 cell,
676 );
677 self.paint.push(Paint::Text {
678 x: units(right),
679 y: y as i32 * UNIT,
680 max_width: units(right),
681 text: text.to_string(),
682 color: style.fg,
683 font: Font {
684 bold: style.bold,
685 size,
686 ..Font::default()
687 },
688 align_right: true,
689 centred: false,
690 underline: false,
691 span_centred: false,
692 });
693 }
694
695 pub fn field(&mut self, rect: Rect, behind: Rgb, fill: Rgb, border: Rgb) {
697 self.panel(Bounds::inset(rect, 0.0, 0.0), 0, Some(behind), None);
698 self.panel(
701 Bounds::inset(rect, 0.15, FIELD_AIR),
702 22,
703 Some(fill),
704 Some(border),
705 );
706 }
707
708 pub fn button(&mut self, x: u16, y: u16, cells: &str, label: &str, fill: Rgb, style: Style) {
711 self.button_of((BUTTON_HEIGHT, 0.0), (x, y), cells, label, fill, style);
712 }
713
714 pub fn row_button(
723 &mut self,
724 (x, y): (u16, u16),
725 cells: &str,
726 label: &str,
727 fill: Rgb,
728 style: Style,
729 ) {
730 let from = self.paint.len();
731 self.button(x, y, cells, label, fill, style);
732 if !self.roomy {
733 return;
734 }
735 for paint in &mut self.paint[from..] {
738 if let Paint::Panel { inset, radius, .. } = paint {
739 *inset = true;
740 *radius = ROW_BUTTON_RADIUS;
741 }
742 }
743 self.beside_words(from);
744 }
745
746 pub fn row_chip(&mut self, (left, right): (f32, f32), y: u16, fill: Rgb) {
752 let (_, top, _, bottom) = button_span((BUTTON_HEIGHT, 0.0), (0, y), 1);
753 let (radius, inset) = if self.roomy {
754 (ROW_BUTTON_RADIUS, true)
755 } else {
756 (22, false)
757 };
758 self.paint.push(Paint::Panel {
759 bounds: Bounds::cells(left, top, right - left, bottom - top),
760 radius,
761 fill: Some(fill),
762 border: None,
763 shadow: false,
764 dashed: false,
765 inset,
766 });
767 }
768
769 pub fn beside_words(&mut self, from: usize) {
773 if self.roomy {
774 let line = 100.0 / f32::from(self.row_air.max(1));
775 self.lift_since(from, -WORDS_BASELINE * line);
776 }
777 }
778
779 pub fn exact_fill(&mut self, bounds: Bounds, color: Rgb) {
784 let bitmap = crate::paint::Bitmap {
785 id: EXACT_FILL,
786 width: 1,
787 height: 1,
788 kind: crate::paint::Pixels::Coverage,
789 pixels: std::sync::Arc::new(vec![255]),
790 };
791 self.paint.push(Paint::Image {
792 bounds,
793 clip: bounds,
794 bitmap,
795 color,
796 });
797 }
798
799 pub fn exact_fill_under(&mut self, index: usize, bounds: Bounds, color: Rgb) {
801 self.exact_fill(bounds, color);
802 if let Some(fill) = self.paint.pop() {
803 self.insert_paint(index, fill);
804 }
805 }
806
807 pub fn chip(&mut self, x: f32, y: u16, wide: f32, fill: Rgb) {
810 let top = y as f32 + (1.0 - BUTTON_HEIGHT) / 2.0;
811 let bounds = Bounds::cells(x, top, wide, BUTTON_HEIGHT);
812 self.panel(bounds, 22, Some(fill), None);
813 }
814
815 pub fn large_button(
817 &mut self,
818 x: u16,
819 y: u16,
820 cells: &str,
821 label: &str,
822 fill: Rgb,
823 style: Style,
824 ) {
825 self.button_of(
826 (LARGE_BUTTON_HEIGHT, 0.0),
827 (x, y),
828 cells,
829 label,
830 fill,
831 style,
832 );
833 }
834
835 pub fn large_button_between(
837 &mut self,
838 x: u16,
839 y: u16,
840 cells: &str,
841 label: &str,
842 fill: Rgb,
843 style: Style,
844 ) {
845 self.button_of(
846 (LARGE_BUTTON_HEIGHT, 0.5),
847 (x, y),
848 cells,
849 label,
850 fill,
851 style,
852 );
853 }
854
855 fn button_of(
856 &mut self,
857 (height, drop): (f32, f32),
858 (x, y): (u16, u16),
859 cells: &str,
860 label: &str,
861 fill: Rgb,
862 style: Style,
863 ) {
864 let width = cells.chars().count() as u16;
865 let (left, top, right, bottom) = button_span((height, drop), (x, y), width);
866 self.put_str(
867 x,
868 y,
869 cells,
870 Style {
871 painted: true,
872 ..style
873 },
874 self.width,
875 );
876 let bounds = Bounds::cells(left, top, right - left, bottom - top);
877 self.panel(bounds, 22, Some(fill), None);
878 let middle = x as f32 + width as f32 / 2.0;
879 self.button_label(middle, y as f32 + drop, label, style.fg, 90);
880 }
881
882 pub fn button_words(&mut self, middle: f32, y: u16, label: &str, color: Rgb) {
885 self.button_label(middle, y as f32, label, color, 90);
886 }
887
888 pub fn button_label(&mut self, x: f32, y: f32, text: &str, color: Rgb, size: u8) {
894 self.centred_text(x, y, text, color, size);
895 self.centre_span_since(self.paint.len() - 1);
896 }
897
898 pub fn centre_span_since(&mut self, from: usize) {
901 for paint in self.paint.iter_mut().skip(from) {
902 if let Paint::Text { span_centred, .. } = paint {
903 *span_centred = true;
904 }
905 }
906 }
907
908 pub fn drop_last(&mut self, by: f32) {
910 match self.paint.last_mut() {
911 Some(Paint::Text { y, .. }) => *y += units(by),
912 Some(Paint::Icon { bounds, .. }) => bounds.y += units(by),
913 _ => {}
914 }
915 }
916
917 pub fn centred_text(&mut self, x: f32, y: f32, text: &str, color: Rgb, size: u8) {
919 self.paint.push(Paint::Text {
920 x: units(x),
921 y: units(y),
922 max_width: units(self.width as f32),
923 text: text.to_string(),
924 color,
925 font: Font {
926 size,
927 ..Font::default()
928 },
929 align_right: false,
930 centred: true,
931 underline: false,
932 span_centred: false,
933 });
934 }
935
936 pub fn panel(&mut self, bounds: Bounds, radius: u8, fill: Option<Rgb>, border: Option<Rgb>) {
937 self.paint.push(Paint::Panel {
938 bounds,
939 radius,
940 fill,
941 border,
942 shadow: false,
943 dashed: false,
944 inset: false,
945 });
946 }
947
948 pub fn dashed_panel(&mut self, bounds: Bounds, radius: u8, fill: Option<Rgb>, border: Rgb) {
950 self.paint.push(Paint::Panel {
951 bounds,
952 radius,
953 fill,
954 border: Some(border),
955 shadow: false,
956 dashed: true,
957 inset: false,
958 });
959 }
960
961 pub fn popup(&mut self, bounds: Bounds, radius: u8, fill: Rgb, border: Rgb) {
963 self.paint.push(Paint::Panel {
964 bounds,
965 radius,
966 fill: Some(fill),
967 border: Some(border),
968 shadow: true,
969 dashed: false,
970 inset: false,
971 });
972 }
973
974 pub fn exact_popup(&mut self, bounds: Bounds, radius: u8, fill: Rgb, border: Rgb) {
978 self.paint.push(Paint::Panel {
979 bounds,
980 radius,
981 fill: Some(fill),
982 border: Some(border),
983 shadow: true,
984 dashed: false,
985 inset: true,
986 });
987 }
988
989 pub fn wash(
991 &mut self,
992 bounds: Bounds,
993 radius: u8,
994 (color, alpha): (Rgb, u8),
995 border: Option<Rgb>,
996 ) {
997 self.paint.push(Paint::Wash {
998 bounds,
999 radius,
1000 color,
1001 alpha,
1002 border,
1003 });
1004 }
1005
1006 pub fn hairline(&mut self, bounds: Bounds, color: Rgb) {
1007 self.paint.push(Paint::Hairline { bounds, color });
1008 }
1009
1010 pub fn glyph(&mut self, x: f32, y: u16, icon: Icon, color: Rgb, fallback: &str, style: Style) {
1014 self.glyph_in((x, x.floor() as u16), y, (icon, color), fallback, style);
1015 }
1016
1017 pub fn glyph_in(
1019 &mut self,
1020 (x, cell): (f32, u16),
1021 y: u16,
1022 (icon, color): (Icon, Rgb),
1023 fallback: &str,
1024 style: Style,
1025 ) {
1026 if cell < self.width && y < self.height {
1027 self.put_str(
1028 cell,
1029 y,
1030 fallback,
1031 Style {
1032 painted: true,
1033 ..style
1034 },
1035 self.width,
1036 );
1037 }
1038 self.paint.push(Paint::Icon {
1039 bounds: Bounds::cells(x - GLYPH_LEAD, y as f32 + (1.0 - GLYPH) / 2.0, 2.0, GLYPH),
1040 icon,
1041 color,
1042 });
1043 }
1044
1045 #[allow(clippy::too_many_arguments)]
1047 pub fn small_glyph(
1048 &mut self,
1049 x: f32,
1050 y: u16,
1051 icon: Icon,
1052 color: Rgb,
1053 fallback: &str,
1054 style: Style,
1055 ) {
1056 self.glyph(x, y, icon, color, fallback, style);
1057 if let Some(Paint::Icon { bounds, .. }) = self.paint.last_mut() {
1058 let top = y as f32 + (1.0 - SMALL_GLYPH) / 2.0;
1059 *bounds = Bounds::cells(x, top, 2.0, SMALL_GLYPH);
1060 }
1061 }
1062
1063 pub fn corners(&mut self, bounds: Bounds, radius: u8, color: Rgb, which: u8) {
1065 self.paint.push(Paint::Corners {
1066 bounds,
1067 radius,
1068 color,
1069 which,
1070 });
1071 }
1072
1073 pub fn paint_on_row(&self, y: u16) -> impl Iterator<Item = &Paint> {
1074 let (top, bottom) = (y as i32 * UNIT, (y as i32 + 1) * UNIT);
1075 let kept_off = move |index: usize| {
1076 self.kept.iter().any(|((from, to), (first, end))| {
1077 (*from..*to).contains(&index) && !(*first..*end).contains(&y)
1078 })
1079 };
1080 self.paint
1081 .iter()
1082 .enumerate()
1083 .filter(move |(index, p)| {
1084 let (from, to) = p.span();
1085 from < bottom && to > top && !kept_off(*index)
1086 })
1087 .map(|(_, paint)| paint)
1088 }
1089
1090 pub fn spans(&self, y: u16) -> Vec<(u16, u16)> {
1094 let width = self.width;
1095 let own = self.row_bands.as_ref().filter(|(row, _)| *row == y);
1096 let bands = match own {
1097 Some((_, bands)) => bands,
1098 None if y + 1 == self.height => return vec![(0, width)],
1099 None => &self.bands,
1100 };
1101 let inside = bands.iter().copied().filter(|x| *x > 0 && *x < width);
1102 let edges: Vec<u16> = [0].into_iter().chain(inside).chain([width]).collect();
1103 edges.windows(2).map(|edge| (edge[0], edge[1])).collect()
1104 }
1105
1106 pub fn width(&self) -> u16 {
1107 self.width
1108 }
1109
1110 pub fn height(&self) -> u16 {
1111 self.height
1112 }
1113
1114 pub fn area(&self) -> Rect {
1115 Rect::new(0, 0, self.width, self.height)
1116 }
1117
1118 fn index(&self, x: u16, y: u16) -> usize {
1119 y as usize * self.width as usize + x as usize
1120 }
1121
1122 pub fn cell(&self, x: u16, y: u16) -> &Cell {
1123 &self.cells[self.index(x, y)]
1124 }
1125
1126 pub fn row(&self, y: u16) -> &[Cell] {
1127 let start = self.index(0, y);
1128 &self.cells[start..start + self.width as usize]
1129 }
1130
1131 pub fn fill(&mut self, rect: Rect, style: Style) {
1132 for y in rect.y..rect.bottom().min(self.height) {
1133 for x in rect.x..rect.right().min(self.width) {
1134 self.put_cell(x, y, " ", style);
1135 }
1136 }
1137 }
1138
1139 fn put_cell(&mut self, x: u16, y: u16, symbol: &str, style: Style) {
1140 let i = self.index(x, y);
1142 if self.cells[i].symbol.is_empty() && x > 0 {
1143 self.cells[i - 1].symbol = " ".into();
1144 }
1145 if x + 1 < self.width && self.cells[i + 1].symbol.is_empty() {
1146 self.cells[i + 1].symbol = " ".into();
1147 }
1148 self.cells[i] = Cell {
1149 symbol: symbol.into(),
1150 style,
1151 };
1152 }
1153
1154 pub fn put_str(&mut self, x: u16, y: u16, text: &str, style: Style, max_x: u16) -> u16 {
1157 if y >= self.height {
1158 return x;
1159 }
1160 let max_x = max_x.min(self.width);
1161 let mut at = x;
1162 let text = visible(text);
1163 for g in text.graphemes(true) {
1164 if at >= max_x {
1165 break;
1166 }
1167 let width = g.width() as u16;
1168 if width == 0 {
1169 continue;
1170 }
1171 if at + width > max_x {
1172 self.put_cell(at, y, " ", style);
1173 return at + 1;
1174 }
1175 self.put_cell(at, y, g, style);
1176 if width == 2 {
1177 self.put_cell(at + 1, y, "", style);
1178 }
1179 at += width;
1180 }
1181 at
1182 }
1183
1184 pub fn put_icon(&mut self, x: u16, y: u16, icon: Icon, size: (u8, u8), style: Style) {
1186 for row in 0..size.1 {
1187 for column in 0..size.0 {
1188 let (cx, cy) = (x + u16::from(column), y + u16::from(row));
1189 if cx < self.width && cy < self.height {
1190 let piece = Piece {
1191 icon,
1192 width: size.0,
1193 height: size.1,
1194 column,
1195 row,
1196 };
1197 self.put_cell(cx, cy, piece.symbol().encode_utf8(&mut [0; 4]), style);
1198 }
1199 }
1200 }
1201 }
1202
1203 pub fn set_style(&mut self, rect: Rect, f: impl Fn(Style) -> Style) {
1205 for y in rect.y..rect.bottom().min(self.height) {
1206 for x in rect.x..rect.right().min(self.width) {
1207 let i = self.index(x, y);
1208 self.cells[i].style = f(self.cells[i].style);
1209 }
1210 }
1211 }
1212
1213 pub fn diff(&self, prev: &Grid) -> Vec<Run> {
1215 let same_size = self.width == prev.width && self.height == prev.height;
1216 let mut runs = Vec::new();
1217 for y in 0..self.height {
1218 if same_size && self.row(y) == prev.row(y) {
1219 continue;
1220 }
1221 let mut x = 0;
1222 while x < self.width {
1223 if same_size && self.cell(x, y) == prev.cell(x, y) {
1224 x += 1;
1225 continue;
1226 }
1227 let start = x;
1228 while x < self.width && !(same_size && self.cell(x, y) == prev.cell(x, y)) {
1229 x += 1;
1230 }
1231 let start = if self.cell(start, y).symbol.is_empty() && start > 0 {
1233 start - 1
1234 } else {
1235 start
1236 };
1237 runs.push(Run {
1238 x: start,
1239 y,
1240 len: x - start,
1241 });
1242 }
1243 }
1244 runs
1245 }
1246
1247 pub fn row_text(&self, y: u16) -> String {
1249 self.row(y).iter().map(|c| c.symbol.as_str()).collect()
1250 }
1251
1252 pub fn text(&self) -> String {
1254 (0..self.height)
1255 .map(|y| self.row_text(y).trim_end().to_string())
1256 .collect::<Vec<_>>()
1257 .join("\n")
1258 }
1259}
1260
1261fn button_span((height, drop): (f32, f32), (x, y): (u16, u16), width: u16) -> (f32, f32, f32, f32) {
1263 let top = y as f32 + drop + (1.0 - height) / 2.0;
1264 (x as f32, top, (x + width) as f32, top + height)
1265}
1266
1267pub fn air_under_button(row: f32, line: f32) -> f32 {
1270 row - button_in_row(row, line).1
1271}
1272
1273pub fn row_button_in_row(row: f32, line: f32) -> (f32, f32) {
1278 let (_, top, _, bottom) = button_span((BUTTON_HEIGHT, 0.0), (0, 0), 1);
1279 let drop = units(WORDS_BASELINE * line / row) as f32 * row / UNIT as f32;
1280 let (top, tall) = crate::raster::inset(units(top), units(bottom - top), row, line);
1281 (top + drop, top + drop + tall)
1282}
1283
1284pub fn button_in_row(row: f32, line: f32) -> (f32, f32) {
1287 let (_, top, _, bottom) = button_span((BUTTON_HEIGHT, 0.0), (0, 0), 1);
1288 let bounds = Bounds::cells(0.0, top, 1.0, bottom - top);
1289 let (y, h) = crate::raster::stood(bounds.y, bounds.h, row, line);
1290 (y, y + h)
1291}
1292
1293pub fn on_large_button((x, y): (u16, u16), width: u16, at: (f32, f32)) -> bool {
1298 let (left, top, right, bottom) = button_span((LARGE_BUTTON_HEIGHT, 0.0), (x, y), width);
1299 at.0 >= left && at.0 < right && at.1 >= top && at.1 < bottom
1300}
1301
1302#[cfg(test)]
1303mod tests {
1304 #[test]
1307 fn paint_kept_to_its_rows_is_on_no_other() {
1308 let style = Style::default();
1309 let mut grid = Grid::new(10, 6, style);
1310 let panel = |grid: &mut Grid, y: f32, h: f32| {
1311 grid.panel(Bounds::cells(0.0, y, 10.0, h), 0, Some(Rgb(1, 2, 3)), None);
1312 };
1313 panel(&mut grid, 0.0, 1.0);
1314 let from = grid.painted_so_far();
1315 panel(&mut grid, 1.0, 4.5);
1317 grid.keep_to_rows(from, 2, 4);
1318 panel(&mut grid, 5.0, 1.0);
1319 let on = |grid: &Grid, y: u16| grid.paint_on_row(y).count();
1320 let rows: Vec<usize> = (0..6).map(|y| on(&grid, y)).collect();
1321 assert_eq!(rows, [1, 0, 1, 1, 0, 1]);
1322 grid.insert_paint(
1324 0,
1325 Paint::Hairline {
1326 bounds: Bounds::cells(0.0, 1.0, 10.0, 0.0),
1327 color: Rgb(9, 9, 9),
1328 },
1329 );
1330 let rows: Vec<usize> = (0..6).map(|y| on(&grid, y)).collect();
1331 assert_eq!(rows, [1, 1, 1, 1, 0, 1]);
1332 }
1333
1334 #[test]
1335 fn control_characters_never_reach_a_cell() {
1336 let style = Style::default();
1337 let mut grid = Grid::new(40, 2, style);
1338 let text = "a\x1b]52;c;aGk=\x07b\r\n\x7f\u{9b}2Jc\td";
1339 let end = grid.put_str(0, 0, text, style, 40);
1340 let row: String = (0..end)
1341 .map(|x| grid.cell(x, 0).symbol.to_string())
1342 .collect();
1343 assert_eq!(row, "a␛]52;c;aGk=␇b␍␊␡\u{fffd}2Jc d");
1344 assert!(row.chars().all(|c| !c.is_control()), "{row:?}");
1345 }
1346
1347 use super::*;
1348
1349 fn grid() -> Grid {
1350 Grid::new(10, 3, Style::default())
1351 }
1352
1353 #[test]
1354 fn diff_emits_only_changed_cells() {
1355 let before = grid();
1356 let mut after = grid();
1357 after.put_str(2, 1, "ab", Style::default(), 10);
1358 after.put_str(7, 1, "c", Style::default(), 10);
1359 assert_eq!(
1360 after.diff(&before),
1361 vec![Run { x: 2, y: 1, len: 2 }, Run { x: 7, y: 1, len: 1 }]
1362 );
1363 assert!(before.diff(&before.clone()).is_empty());
1364 }
1365
1366 #[test]
1367 fn resize_redraws_everything() {
1368 let runs = grid().diff(&Grid::new(4, 4, Style::default()));
1369 assert_eq!(runs.len(), 3);
1370 assert!(runs.iter().all(|r| r.len == 10));
1371 }
1372
1373 #[test]
1374 fn wide_characters_take_two_cells() {
1375 let mut g = grid();
1376 let end = g.put_str(0, 0, "日本", Style::default(), 10);
1377 assert_eq!(end, 4);
1378 assert_eq!(g.cell(0, 0).symbol, "日");
1379 assert_eq!(g.cell(1, 0).symbol, "");
1380 assert_eq!(g.row_text(0).trim_end(), "日本");
1381 }
1382
1383 #[test]
1384 fn overwriting_half_a_wide_character_blanks_the_other_half() {
1385 let mut g = grid();
1386 g.put_str(0, 0, "日", Style::default(), 10);
1387 g.put_str(1, 0, "x", Style::default(), 10);
1388 assert_eq!(g.cell(0, 0).symbol, " ");
1389 assert_eq!(g.cell(1, 0).symbol, "x");
1390 }
1391
1392 #[test]
1393 fn wide_character_at_the_edge_becomes_a_space() {
1394 let mut g = grid();
1395 g.put_str(9, 0, "日", Style::default(), 10);
1396 assert_eq!(g.cell(9, 0).symbol, " ");
1397 }
1398
1399 #[test]
1400 fn combining_marks_stay_in_one_cell() {
1401 let mut g = grid();
1402 let end = g.put_str(0, 0, "e\u{301}x", Style::default(), 10);
1403 assert_eq!(end, 2);
1404 assert_eq!(g.cell(0, 0).symbol, "e\u{301}");
1405 }
1406
1407 #[test]
1408 fn diff_never_starts_on_a_continuation_cell() {
1409 let mut before = grid();
1410 before.put_str(0, 0, "日", Style::default(), 10);
1411 let mut after = grid();
1412 after.put_str(
1413 0,
1414 0,
1415 "日",
1416 Style {
1417 bold: true,
1418 ..Style::default()
1419 },
1420 10,
1421 );
1422 let mut only_right = before.clone();
1423 only_right.cells[1].style.bold = true;
1424 assert_eq!(only_right.diff(&before)[0].x, 0);
1425 assert_eq!(after.diff(&before)[0].x, 0);
1426 }
1427
1428 #[test]
1431 fn a_step_on_the_drawn_grid_is_the_grid_drawn_at_that_step() {
1432 let draw = |step: u8| {
1433 let mut grid = Grid::new(30, 4, Style::default());
1434 grid.turn = Some(step);
1435 grid.put_str(0, 1, "working", Style::default(), 30);
1436 grid.spinner(9.0, 1, 0.65, Rgb(1, 2, 3), Style::default());
1437 grid.dot(12.0, 1, 0.65, Rgb(4, 5, 6), Style::default());
1438 grid.spinner(3.0, 3, 0.65, Rgb(1, 2, 3), Style::default());
1439 grid
1440 };
1441 let mut stepped = draw(0);
1442 for step in [1, 7, 0, 9] {
1443 stepped.turn_to(step);
1444 assert_eq!(stepped, draw(step), "step {step}");
1445 }
1446 assert_eq!(
1447 stepped.cell(12, 1).symbol,
1448 crate::spinner::STILL,
1449 "a dot stays"
1450 );
1451 let mut covered = draw(0);
1453 covered.put_str(8, 1, "menu", Style::default(), 30);
1454 covered.turn_to(4);
1455 assert_eq!(covered.row_text(1).trim_end(), "working menu●");
1456 let mut still = Grid::new(30, 4, Style::default());
1458 still.turn = None;
1459 still.spinner(9.0, 1, 0.65, Rgb(1, 2, 3), Style::default());
1460 let before = still.clone();
1461 still.turn_to(3);
1462 assert_eq!(still, before);
1463 }
1464}