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::Spinner { bounds, .. }
564 | Paint::Corners { bounds, .. }
565 | Paint::Strips { bounds, .. } => bounds.x += by,
566 Paint::Image { bounds, clip, .. } => {
567 bounds.x += by;
568 clip.x += by;
569 }
570 }
571 }
572 }
573
574 #[allow(clippy::too_many_arguments)]
576 pub fn label_at(
577 &mut self,
578 x_px: f32,
579 x: u16,
580 y: u16,
581 text: &str,
582 style: Style,
583 max_x: u16,
584 size: u8,
585 ) -> u16 {
586 let end = self.put_str(
587 x,
588 y,
589 text,
590 Style {
591 painted: true,
592 ..style
593 },
594 max_x,
595 );
596 if y < self.height {
597 self.paint.push(Paint::Text {
598 x: units(x_px),
599 y: y as i32 * UNIT,
600 max_width: units(max_x.min(self.width) as f32 - x_px),
601 text: text.to_string(),
602 color: style.fg,
603 font: Font {
604 bold: style.bold,
605 size,
606 ..Font::default()
607 },
608 align_right: false,
609 centred: false,
610 underline: false,
611 span_centred: false,
612 });
613 }
614 end
615 }
616
617 pub fn text_run(
619 &mut self,
620 (x, y): (f32, f32),
621 max_x: f32,
622 text: &str,
623 (color, underline): (Rgb, bool),
624 font: Font,
625 ) {
626 self.paint.push(Paint::Text {
627 x: units(x),
628 y: units(y),
629 max_width: units(max_x - x),
630 text: text.to_string(),
631 color,
632 font,
633 align_right: false,
634 centred: false,
635 underline,
636 span_centred: false,
637 });
638 }
639
640 pub fn set_caret(&mut self, x: f32, y: u16, height: f32) {
642 self.cursor = Some((x as u16, y));
643 let top = y as f32 + (1.0 - height) / 2.0;
644 self.caret = Some(Bounds::cells(x, top, 0.0, height));
645 }
646
647 pub fn label_right(&mut self, right: u16, y: u16, text: &str, style: Style, size: u8) {
650 self.label_right_at(right as f32, right, y, text, style, size);
651 }
652
653 pub fn label_right_at(
656 &mut self,
657 right: f32,
658 cell: u16,
659 y: u16,
660 text: &str,
661 style: Style,
662 size: u8,
663 ) {
664 let cells = text.chars().count() as u16;
665 let x = cell.saturating_sub(cells);
666 self.put_str(
667 x,
668 y,
669 text,
670 Style {
671 painted: true,
672 ..style
673 },
674 cell,
675 );
676 self.paint.push(Paint::Text {
677 x: units(right),
678 y: y as i32 * UNIT,
679 max_width: units(right),
680 text: text.to_string(),
681 color: style.fg,
682 font: Font {
683 bold: style.bold,
684 size,
685 ..Font::default()
686 },
687 align_right: true,
688 centred: false,
689 underline: false,
690 span_centred: false,
691 });
692 }
693
694 pub fn field(&mut self, rect: Rect, behind: Rgb, fill: Rgb, border: Rgb) {
696 self.panel(Bounds::inset(rect, 0.0, 0.0), 0, Some(behind), None);
697 self.panel(
700 Bounds::inset(rect, 0.15, FIELD_AIR),
701 22,
702 Some(fill),
703 Some(border),
704 );
705 }
706
707 pub fn button(&mut self, x: u16, y: u16, cells: &str, label: &str, fill: Rgb, style: Style) {
710 self.button_of((BUTTON_HEIGHT, 0.0), (x, y), cells, label, fill, style);
711 }
712
713 pub fn row_button(
722 &mut self,
723 (x, y): (u16, u16),
724 cells: &str,
725 label: &str,
726 fill: Rgb,
727 style: Style,
728 ) {
729 let from = self.paint.len();
730 self.button(x, y, cells, label, fill, style);
731 if !self.roomy {
732 return;
733 }
734 for paint in &mut self.paint[from..] {
737 if let Paint::Panel { inset, radius, .. } = paint {
738 *inset = true;
739 *radius = ROW_BUTTON_RADIUS;
740 }
741 }
742 self.beside_words(from);
743 }
744
745 pub fn row_chip(&mut self, (left, right): (f32, f32), y: u16, fill: Rgb) {
751 let (_, top, _, bottom) = button_span((BUTTON_HEIGHT, 0.0), (0, y), 1);
752 let (radius, inset) = if self.roomy {
753 (ROW_BUTTON_RADIUS, true)
754 } else {
755 (22, false)
756 };
757 self.paint.push(Paint::Panel {
758 bounds: Bounds::cells(left, top, right - left, bottom - top),
759 radius,
760 fill: Some(fill),
761 border: None,
762 shadow: false,
763 dashed: false,
764 inset,
765 });
766 }
767
768 pub fn beside_words(&mut self, from: usize) {
772 if self.roomy {
773 let line = 100.0 / f32::from(self.row_air.max(1));
774 self.lift_since(from, -WORDS_BASELINE * line);
775 }
776 }
777
778 pub fn exact_fill(&mut self, bounds: Bounds, color: Rgb) {
783 let bitmap = crate::paint::Bitmap {
784 id: EXACT_FILL,
785 width: 1,
786 height: 1,
787 kind: crate::paint::Pixels::Coverage,
788 pixels: std::sync::Arc::new(vec![255]),
789 };
790 self.paint.push(Paint::Image {
791 bounds,
792 clip: bounds,
793 bitmap,
794 color,
795 });
796 }
797
798 pub fn exact_fill_under(&mut self, index: usize, bounds: Bounds, color: Rgb) {
800 self.exact_fill(bounds, color);
801 if let Some(fill) = self.paint.pop() {
802 self.insert_paint(index, fill);
803 }
804 }
805
806 pub fn chip(&mut self, x: f32, y: u16, wide: f32, fill: Rgb) {
809 let top = y as f32 + (1.0 - BUTTON_HEIGHT) / 2.0;
810 let bounds = Bounds::cells(x, top, wide, BUTTON_HEIGHT);
811 self.panel(bounds, 22, Some(fill), None);
812 }
813
814 pub fn large_button(
816 &mut self,
817 x: u16,
818 y: u16,
819 cells: &str,
820 label: &str,
821 fill: Rgb,
822 style: Style,
823 ) {
824 self.button_of(
825 (LARGE_BUTTON_HEIGHT, 0.0),
826 (x, y),
827 cells,
828 label,
829 fill,
830 style,
831 );
832 }
833
834 pub fn large_button_between(
836 &mut self,
837 x: u16,
838 y: u16,
839 cells: &str,
840 label: &str,
841 fill: Rgb,
842 style: Style,
843 ) {
844 self.button_of(
845 (LARGE_BUTTON_HEIGHT, 0.5),
846 (x, y),
847 cells,
848 label,
849 fill,
850 style,
851 );
852 }
853
854 fn button_of(
855 &mut self,
856 (height, drop): (f32, f32),
857 (x, y): (u16, u16),
858 cells: &str,
859 label: &str,
860 fill: Rgb,
861 style: Style,
862 ) {
863 let width = cells.chars().count() as u16;
864 let (left, top, right, bottom) = button_span((height, drop), (x, y), width);
865 self.put_str(
866 x,
867 y,
868 cells,
869 Style {
870 painted: true,
871 ..style
872 },
873 self.width,
874 );
875 let bounds = Bounds::cells(left, top, right - left, bottom - top);
876 self.panel(bounds, 22, Some(fill), None);
877 let middle = x as f32 + width as f32 / 2.0;
878 self.button_label(middle, y as f32 + drop, label, style.fg, 90);
879 }
880
881 pub fn button_words(&mut self, middle: f32, y: u16, label: &str, color: Rgb) {
884 self.button_label(middle, y as f32, label, color, 90);
885 }
886
887 pub fn button_label(&mut self, x: f32, y: f32, text: &str, color: Rgb, size: u8) {
893 self.centred_text(x, y, text, color, size);
894 self.centre_span_since(self.paint.len() - 1);
895 }
896
897 pub fn centre_span_since(&mut self, from: usize) {
900 for paint in self.paint.iter_mut().skip(from) {
901 if let Paint::Text { span_centred, .. } = paint {
902 *span_centred = true;
903 }
904 }
905 }
906
907 pub fn drop_last(&mut self, by: f32) {
909 match self.paint.last_mut() {
910 Some(Paint::Text { y, .. }) => *y += units(by),
911 Some(Paint::Icon { bounds, .. }) => bounds.y += units(by),
912 _ => {}
913 }
914 }
915
916 pub fn centred_text(&mut self, x: f32, y: f32, text: &str, color: Rgb, size: u8) {
918 self.paint.push(Paint::Text {
919 x: units(x),
920 y: units(y),
921 max_width: units(self.width as f32),
922 text: text.to_string(),
923 color,
924 font: Font {
925 size,
926 ..Font::default()
927 },
928 align_right: false,
929 centred: true,
930 underline: false,
931 span_centred: false,
932 });
933 }
934
935 pub fn panel(&mut self, bounds: Bounds, radius: u8, fill: Option<Rgb>, border: Option<Rgb>) {
936 self.paint.push(Paint::Panel {
937 bounds,
938 radius,
939 fill,
940 border,
941 shadow: false,
942 dashed: false,
943 inset: false,
944 });
945 }
946
947 pub fn dashed_panel(&mut self, bounds: Bounds, radius: u8, fill: Option<Rgb>, border: Rgb) {
949 self.paint.push(Paint::Panel {
950 bounds,
951 radius,
952 fill,
953 border: Some(border),
954 shadow: false,
955 dashed: true,
956 inset: false,
957 });
958 }
959
960 pub fn popup(&mut self, bounds: Bounds, radius: u8, fill: Rgb, border: Rgb) {
962 self.paint.push(Paint::Panel {
963 bounds,
964 radius,
965 fill: Some(fill),
966 border: Some(border),
967 shadow: true,
968 dashed: false,
969 inset: false,
970 });
971 }
972
973 pub fn exact_popup(&mut self, bounds: Bounds, radius: u8, fill: Rgb, border: Rgb) {
977 self.paint.push(Paint::Panel {
978 bounds,
979 radius,
980 fill: Some(fill),
981 border: Some(border),
982 shadow: true,
983 dashed: false,
984 inset: true,
985 });
986 }
987
988 pub fn wash(
990 &mut self,
991 bounds: Bounds,
992 radius: u8,
993 (color, alpha): (Rgb, u8),
994 border: Option<Rgb>,
995 ) {
996 self.paint.push(Paint::Wash {
997 bounds,
998 radius,
999 color,
1000 alpha,
1001 border,
1002 });
1003 }
1004
1005 pub fn hairline(&mut self, bounds: Bounds, color: Rgb) {
1006 self.paint.push(Paint::Hairline { bounds, color });
1007 }
1008
1009 pub fn glyph(&mut self, x: f32, y: u16, icon: Icon, color: Rgb, fallback: &str, style: Style) {
1013 self.glyph_in((x, x.floor() as u16), y, (icon, color), fallback, style);
1014 }
1015
1016 pub fn glyph_in(
1018 &mut self,
1019 (x, cell): (f32, u16),
1020 y: u16,
1021 (icon, color): (Icon, Rgb),
1022 fallback: &str,
1023 style: Style,
1024 ) {
1025 if cell < self.width && y < self.height {
1026 self.put_str(
1027 cell,
1028 y,
1029 fallback,
1030 Style {
1031 painted: true,
1032 ..style
1033 },
1034 self.width,
1035 );
1036 }
1037 self.paint.push(Paint::Icon {
1038 bounds: Bounds::cells(x - GLYPH_LEAD, y as f32 + (1.0 - GLYPH) / 2.0, 2.0, GLYPH),
1039 icon,
1040 color,
1041 });
1042 }
1043
1044 #[allow(clippy::too_many_arguments)]
1046 pub fn small_glyph(
1047 &mut self,
1048 x: f32,
1049 y: u16,
1050 icon: Icon,
1051 color: Rgb,
1052 fallback: &str,
1053 style: Style,
1054 ) {
1055 self.glyph(x, y, icon, color, fallback, style);
1056 if let Some(Paint::Icon { bounds, .. }) = self.paint.last_mut() {
1057 let top = y as f32 + (1.0 - SMALL_GLYPH) / 2.0;
1058 *bounds = Bounds::cells(x, top, 2.0, SMALL_GLYPH);
1059 }
1060 }
1061
1062 pub fn corners(&mut self, bounds: Bounds, radius: u8, color: Rgb, which: u8) {
1064 self.paint.push(Paint::Corners {
1065 bounds,
1066 radius,
1067 color,
1068 which,
1069 });
1070 }
1071
1072 pub fn paint_on_row(&self, y: u16) -> impl Iterator<Item = &Paint> {
1073 let (top, bottom) = (y as i32 * UNIT, (y as i32 + 1) * UNIT);
1074 let kept_off = move |index: usize| {
1075 self.kept.iter().any(|((from, to), (first, end))| {
1076 (*from..*to).contains(&index) && !(*first..*end).contains(&y)
1077 })
1078 };
1079 self.paint
1080 .iter()
1081 .enumerate()
1082 .filter(move |(index, p)| {
1083 let (from, to) = p.span();
1084 from < bottom && to > top && !kept_off(*index)
1085 })
1086 .map(|(_, paint)| paint)
1087 }
1088
1089 pub fn spans(&self, y: u16) -> Vec<(u16, u16)> {
1093 let width = self.width;
1094 let own = self.row_bands.as_ref().filter(|(row, _)| *row == y);
1095 let bands = match own {
1096 Some((_, bands)) => bands,
1097 None if y + 1 == self.height => return vec![(0, width)],
1098 None => &self.bands,
1099 };
1100 let inside = bands.iter().copied().filter(|x| *x > 0 && *x < width);
1101 let edges: Vec<u16> = [0].into_iter().chain(inside).chain([width]).collect();
1102 edges.windows(2).map(|edge| (edge[0], edge[1])).collect()
1103 }
1104
1105 pub fn width(&self) -> u16 {
1106 self.width
1107 }
1108
1109 pub fn height(&self) -> u16 {
1110 self.height
1111 }
1112
1113 pub fn area(&self) -> Rect {
1114 Rect::new(0, 0, self.width, self.height)
1115 }
1116
1117 fn index(&self, x: u16, y: u16) -> usize {
1118 y as usize * self.width as usize + x as usize
1119 }
1120
1121 pub fn cell(&self, x: u16, y: u16) -> &Cell {
1122 &self.cells[self.index(x, y)]
1123 }
1124
1125 pub fn row(&self, y: u16) -> &[Cell] {
1126 let start = self.index(0, y);
1127 &self.cells[start..start + self.width as usize]
1128 }
1129
1130 pub fn fill(&mut self, rect: Rect, style: Style) {
1131 for y in rect.y..rect.bottom().min(self.height) {
1132 for x in rect.x..rect.right().min(self.width) {
1133 self.put_cell(x, y, " ", style);
1134 }
1135 }
1136 }
1137
1138 fn put_cell(&mut self, x: u16, y: u16, symbol: &str, style: Style) {
1139 let i = self.index(x, y);
1141 if self.cells[i].symbol.is_empty() && x > 0 {
1142 self.cells[i - 1].symbol = " ".into();
1143 }
1144 if x + 1 < self.width && self.cells[i + 1].symbol.is_empty() {
1145 self.cells[i + 1].symbol = " ".into();
1146 }
1147 self.cells[i] = Cell {
1148 symbol: symbol.into(),
1149 style,
1150 };
1151 }
1152
1153 pub fn put_str(&mut self, x: u16, y: u16, text: &str, style: Style, max_x: u16) -> u16 {
1156 if y >= self.height {
1157 return x;
1158 }
1159 let max_x = max_x.min(self.width);
1160 let mut at = x;
1161 let text = visible(text);
1162 for g in text.graphemes(true) {
1163 if at >= max_x {
1164 break;
1165 }
1166 let width = g.width() as u16;
1167 if width == 0 {
1168 continue;
1169 }
1170 if at + width > max_x {
1171 self.put_cell(at, y, " ", style);
1172 return at + 1;
1173 }
1174 self.put_cell(at, y, g, style);
1175 if width == 2 {
1176 self.put_cell(at + 1, y, "", style);
1177 }
1178 at += width;
1179 }
1180 at
1181 }
1182
1183 pub fn put_icon(&mut self, x: u16, y: u16, icon: Icon, size: (u8, u8), style: Style) {
1185 for row in 0..size.1 {
1186 for column in 0..size.0 {
1187 let (cx, cy) = (x + u16::from(column), y + u16::from(row));
1188 if cx < self.width && cy < self.height {
1189 let piece = Piece {
1190 icon,
1191 width: size.0,
1192 height: size.1,
1193 column,
1194 row,
1195 };
1196 self.put_cell(cx, cy, piece.symbol().encode_utf8(&mut [0; 4]), style);
1197 }
1198 }
1199 }
1200 }
1201
1202 pub fn set_style(&mut self, rect: Rect, f: impl Fn(Style) -> Style) {
1204 for y in rect.y..rect.bottom().min(self.height) {
1205 for x in rect.x..rect.right().min(self.width) {
1206 let i = self.index(x, y);
1207 self.cells[i].style = f(self.cells[i].style);
1208 }
1209 }
1210 }
1211
1212 pub fn diff(&self, prev: &Grid) -> Vec<Run> {
1214 let same_size = self.width == prev.width && self.height == prev.height;
1215 let mut runs = Vec::new();
1216 for y in 0..self.height {
1217 if same_size && self.row(y) == prev.row(y) {
1218 continue;
1219 }
1220 let mut x = 0;
1221 while x < self.width {
1222 if same_size && self.cell(x, y) == prev.cell(x, y) {
1223 x += 1;
1224 continue;
1225 }
1226 let start = x;
1227 while x < self.width && !(same_size && self.cell(x, y) == prev.cell(x, y)) {
1228 x += 1;
1229 }
1230 let start = if self.cell(start, y).symbol.is_empty() && start > 0 {
1232 start - 1
1233 } else {
1234 start
1235 };
1236 runs.push(Run {
1237 x: start,
1238 y,
1239 len: x - start,
1240 });
1241 }
1242 }
1243 runs
1244 }
1245
1246 pub fn row_text(&self, y: u16) -> String {
1248 self.row(y).iter().map(|c| c.symbol.as_str()).collect()
1249 }
1250
1251 pub fn text(&self) -> String {
1253 (0..self.height)
1254 .map(|y| self.row_text(y).trim_end().to_string())
1255 .collect::<Vec<_>>()
1256 .join("\n")
1257 }
1258}
1259
1260fn button_span((height, drop): (f32, f32), (x, y): (u16, u16), width: u16) -> (f32, f32, f32, f32) {
1262 let top = y as f32 + drop + (1.0 - height) / 2.0;
1263 (x as f32, top, (x + width) as f32, top + height)
1264}
1265
1266pub fn air_under_button(row: f32, line: f32) -> f32 {
1269 row - button_in_row(row, line).1
1270}
1271
1272pub fn row_button_in_row(row: f32, line: f32) -> (f32, f32) {
1277 let (_, top, _, bottom) = button_span((BUTTON_HEIGHT, 0.0), (0, 0), 1);
1278 let drop = units(WORDS_BASELINE * line / row) as f32 * row / UNIT as f32;
1279 let (top, tall) = crate::raster::inset(units(top), units(bottom - top), row, line);
1280 (top + drop, top + drop + tall)
1281}
1282
1283pub fn button_in_row(row: f32, line: f32) -> (f32, f32) {
1286 let (_, top, _, bottom) = button_span((BUTTON_HEIGHT, 0.0), (0, 0), 1);
1287 let bounds = Bounds::cells(0.0, top, 1.0, bottom - top);
1288 let (y, h) = crate::raster::stood(bounds.y, bounds.h, row, line);
1289 (y, y + h)
1290}
1291
1292pub fn on_large_button((x, y): (u16, u16), width: u16, at: (f32, f32)) -> bool {
1297 let (left, top, right, bottom) = button_span((LARGE_BUTTON_HEIGHT, 0.0), (x, y), width);
1298 at.0 >= left && at.0 < right && at.1 >= top && at.1 < bottom
1299}
1300
1301#[cfg(test)]
1302mod tests {
1303 #[test]
1306 fn paint_kept_to_its_rows_is_on_no_other() {
1307 let style = Style::default();
1308 let mut grid = Grid::new(10, 6, style);
1309 let panel = |grid: &mut Grid, y: f32, h: f32| {
1310 grid.panel(Bounds::cells(0.0, y, 10.0, h), 0, Some(Rgb(1, 2, 3)), None);
1311 };
1312 panel(&mut grid, 0.0, 1.0);
1313 let from = grid.painted_so_far();
1314 panel(&mut grid, 1.0, 4.5);
1316 grid.keep_to_rows(from, 2, 4);
1317 panel(&mut grid, 5.0, 1.0);
1318 let on = |grid: &Grid, y: u16| grid.paint_on_row(y).count();
1319 let rows: Vec<usize> = (0..6).map(|y| on(&grid, y)).collect();
1320 assert_eq!(rows, [1, 0, 1, 1, 0, 1]);
1321 grid.insert_paint(
1323 0,
1324 Paint::Hairline {
1325 bounds: Bounds::cells(0.0, 1.0, 10.0, 0.0),
1326 color: Rgb(9, 9, 9),
1327 },
1328 );
1329 let rows: Vec<usize> = (0..6).map(|y| on(&grid, y)).collect();
1330 assert_eq!(rows, [1, 1, 1, 1, 0, 1]);
1331 }
1332
1333 #[test]
1334 fn control_characters_never_reach_a_cell() {
1335 let style = Style::default();
1336 let mut grid = Grid::new(40, 2, style);
1337 let text = "a\x1b]52;c;aGk=\x07b\r\n\x7f\u{9b}2Jc\td";
1338 let end = grid.put_str(0, 0, text, style, 40);
1339 let row: String = (0..end)
1340 .map(|x| grid.cell(x, 0).symbol.to_string())
1341 .collect();
1342 assert_eq!(row, "a␛]52;c;aGk=␇b␍␊␡\u{fffd}2Jc d");
1343 assert!(row.chars().all(|c| !c.is_control()), "{row:?}");
1344 }
1345
1346 use super::*;
1347
1348 fn grid() -> Grid {
1349 Grid::new(10, 3, Style::default())
1350 }
1351
1352 #[test]
1353 fn diff_emits_only_changed_cells() {
1354 let before = grid();
1355 let mut after = grid();
1356 after.put_str(2, 1, "ab", Style::default(), 10);
1357 after.put_str(7, 1, "c", Style::default(), 10);
1358 assert_eq!(
1359 after.diff(&before),
1360 vec![Run { x: 2, y: 1, len: 2 }, Run { x: 7, y: 1, len: 1 }]
1361 );
1362 assert!(before.diff(&before.clone()).is_empty());
1363 }
1364
1365 #[test]
1366 fn resize_redraws_everything() {
1367 let runs = grid().diff(&Grid::new(4, 4, Style::default()));
1368 assert_eq!(runs.len(), 3);
1369 assert!(runs.iter().all(|r| r.len == 10));
1370 }
1371
1372 #[test]
1373 fn wide_characters_take_two_cells() {
1374 let mut g = grid();
1375 let end = g.put_str(0, 0, "日本", Style::default(), 10);
1376 assert_eq!(end, 4);
1377 assert_eq!(g.cell(0, 0).symbol, "日");
1378 assert_eq!(g.cell(1, 0).symbol, "");
1379 assert_eq!(g.row_text(0).trim_end(), "日本");
1380 }
1381
1382 #[test]
1383 fn overwriting_half_a_wide_character_blanks_the_other_half() {
1384 let mut g = grid();
1385 g.put_str(0, 0, "日", Style::default(), 10);
1386 g.put_str(1, 0, "x", Style::default(), 10);
1387 assert_eq!(g.cell(0, 0).symbol, " ");
1388 assert_eq!(g.cell(1, 0).symbol, "x");
1389 }
1390
1391 #[test]
1392 fn wide_character_at_the_edge_becomes_a_space() {
1393 let mut g = grid();
1394 g.put_str(9, 0, "日", Style::default(), 10);
1395 assert_eq!(g.cell(9, 0).symbol, " ");
1396 }
1397
1398 #[test]
1399 fn combining_marks_stay_in_one_cell() {
1400 let mut g = grid();
1401 let end = g.put_str(0, 0, "e\u{301}x", Style::default(), 10);
1402 assert_eq!(end, 2);
1403 assert_eq!(g.cell(0, 0).symbol, "e\u{301}");
1404 }
1405
1406 #[test]
1407 fn diff_never_starts_on_a_continuation_cell() {
1408 let mut before = grid();
1409 before.put_str(0, 0, "日", Style::default(), 10);
1410 let mut after = grid();
1411 after.put_str(
1412 0,
1413 0,
1414 "日",
1415 Style {
1416 bold: true,
1417 ..Style::default()
1418 },
1419 10,
1420 );
1421 let mut only_right = before.clone();
1422 only_right.cells[1].style.bold = true;
1423 assert_eq!(only_right.diff(&before)[0].x, 0);
1424 assert_eq!(after.diff(&before)[0].x, 0);
1425 }
1426
1427 #[test]
1430 fn a_step_on_the_drawn_grid_is_the_grid_drawn_at_that_step() {
1431 let draw = |step: u8| {
1432 let mut grid = Grid::new(30, 4, Style::default());
1433 grid.turn = Some(step);
1434 grid.put_str(0, 1, "working", Style::default(), 30);
1435 grid.spinner(9.0, 1, 0.65, Rgb(1, 2, 3), Style::default());
1436 grid.dot(12.0, 1, 0.65, Rgb(4, 5, 6), Style::default());
1437 grid.spinner(3.0, 3, 0.65, Rgb(1, 2, 3), Style::default());
1438 grid
1439 };
1440 let mut stepped = draw(0);
1441 for step in [1, 7, 0, 9] {
1442 stepped.turn_to(step);
1443 assert_eq!(stepped, draw(step), "step {step}");
1444 }
1445 assert_eq!(
1446 stepped.cell(12, 1).symbol,
1447 crate::spinner::STILL,
1448 "a dot stays"
1449 );
1450 let mut covered = draw(0);
1452 covered.put_str(8, 1, "menu", Style::default(), 30);
1453 covered.turn_to(4);
1454 assert_eq!(covered.row_text(1).trim_end(), "working menu●");
1455 let mut still = Grid::new(30, 4, Style::default());
1457 still.turn = None;
1458 still.spinner(9.0, 1, 0.65, Rgb(1, 2, 3), Style::default());
1459 let before = still.clone();
1460 still.turn_to(3);
1461 assert_eq!(still, before);
1462 }
1463}