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;
21const BUTTON_WORDS: f32 = 0.03;
25pub const GLYPH: f32 = 0.86;
27pub const SMALL_GLYPH: f32 = 0.70;
30pub const FIELD_AIR: f32 = 0.0625;
34const GLYPH_LEAD: f32 = 0.15;
37
38#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
39pub struct Rgb(pub u8, pub u8, pub u8);
40
41#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
42pub struct Style {
43 pub fg: Rgb,
44 pub bg: Rgb,
45 pub bold: bool,
46 pub italic: bool,
47 pub underline: bool,
48 pub painted: bool,
50}
51
52fn visible(text: &str) -> std::borrow::Cow<'_, str> {
57 let control = |c: char| c.is_control();
58 if !text.contains(control) {
59 return std::borrow::Cow::Borrowed(text);
60 }
61 let shown = text
62 .chars()
63 .map(|c| match c {
64 '\t' => ' ',
65 '\0'..='\u{1f}' => char::from_u32(0x2400 + c as u32).unwrap_or('\u{fffd}'),
66 '\u{7f}' => '\u{2421}',
67 c if c.is_control() => '\u{fffd}',
68 c => c,
69 })
70 .collect();
71 std::borrow::Cow::Owned(shown)
72}
73
74#[derive(Clone, Debug, PartialEq, Eq, Hash)]
76pub struct Cell {
77 pub symbol: CompactString,
78 pub style: Style,
79}
80
81trait CopyCells {
83 fn copy_within_cells(&mut self, from: std::ops::Range<usize>, to: usize);
84}
85
86impl CopyCells for Vec<Cell> {
87 fn copy_within_cells(&mut self, from: std::ops::Range<usize>, to: usize) {
88 for (n, at) in from.enumerate() {
89 let cell = self[at].clone();
90 self[to + n] = cell;
91 }
92 }
93}
94
95#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
96pub struct Rect {
97 pub x: u16,
98 pub y: u16,
99 pub w: u16,
100 pub h: u16,
101}
102
103impl Rect {
104 pub fn new(x: u16, y: u16, w: u16, h: u16) -> Self {
105 Self { x, y, w, h }
106 }
107
108 pub fn contains(&self, x: u16, y: u16) -> bool {
109 x >= self.x && x < self.x + self.w && y >= self.y && y < self.y + self.h
110 }
111
112 pub fn right(&self) -> u16 {
113 self.x + self.w
114 }
115
116 pub fn bottom(&self) -> u16 {
117 self.y + self.h
118 }
119}
120
121#[derive(Clone, Copy, Debug, PartialEq, Eq)]
123pub struct Run {
124 pub x: u16,
125 pub y: u16,
126 pub len: u16,
127}
128
129#[derive(Clone, Debug, PartialEq, Eq)]
130pub struct Grid {
131 width: u16,
132 height: u16,
133 cells: Vec<Cell>,
134 pub cursor: Option<(u16, u16)>,
135 pub caret: Option<Bounds>,
137 pub paint: Vec<Paint>,
139 pub bands: Vec<u16>,
142 pub edge: Option<Rgb>,
145 pub roomy: bool,
149 pub foot: u16,
154 pub row_bands: Option<(u16, Vec<u16>)>,
158 pub turn: Option<u8>,
161 pub spinning: bool,
164 turning: Vec<(u16, u16)>,
166 kept: Vec<((usize, usize), (u16, u16))>,
170}
171
172impl Grid {
173 pub fn scroll_rows(&mut self, top: u16, bottom: u16, by: i32) {
177 let width = self.width as usize;
178 let (top, bottom) = (
179 top as usize,
180 (bottom as usize).min(self.height as usize - 1),
181 );
182 if top > bottom || by == 0 {
183 return;
184 }
185 let rows = bottom + 1 - top;
186 let n = (by.unsigned_abs() as usize).min(rows);
187 let unknown = Cell {
188 symbol: CompactString::const_new("\u{fffe}"),
189 style: Style::default(),
190 };
191 let row = |y: usize| y * width..(y + 1) * width;
192 if by > 0 {
193 for y in top..bottom + 1 - n {
194 self.cells.copy_within_cells(row(y + n), row(y).start);
195 }
196 for y in bottom + 1 - n..=bottom {
197 self.cells[row(y)].fill(unknown.clone());
198 }
199 } else {
200 for y in (top + n..=bottom).rev() {
201 self.cells.copy_within_cells(row(y - n), row(y).start);
202 }
203 for y in top..top + n {
204 self.cells[row(y)].fill(unknown.clone());
205 }
206 }
207 }
208
209 pub fn new(width: u16, height: u16, style: Style) -> Self {
210 let blank = Cell {
211 symbol: " ".into(),
212 style,
213 };
214 Self {
215 width,
216 height,
217 cells: vec![blank; width as usize * height as usize],
218 cursor: None,
219 caret: None,
220 paint: Vec::new(),
221 bands: Vec::new(),
222 edge: None,
223 roomy: false,
224 foot: 1,
225 row_bands: None,
226 turn: Some(0),
227 spinning: false,
228 turning: Vec::new(),
229 kept: Vec::new(),
230 }
231 }
232
233 pub fn spinner(&mut self, x: f32, y: u16, size: f32, color: Rgb, style: Style) {
239 self.spinner_in((x, x.floor() as u16), y, size, color, style);
240 }
241
242 pub fn spinner_in(
246 &mut self,
247 (x, cell): (f32, u16),
248 y: u16,
249 size: f32,
250 color: Rgb,
251 style: Style,
252 ) {
253 let step = self.turn;
254 self.spinning |= step.is_some();
255 let letter = step.map_or(crate::spinner::STILL, |s| {
256 crate::spinner::FRAMES[s as usize % crate::spinner::FRAMES.len()]
257 });
258 self.mark((x, cell), y, size, color, style, (step, letter));
259 }
260
261 pub fn turn_to(&mut self, step: u8) {
265 if self.turn.is_none() {
266 return;
267 }
268 self.turn = Some(step);
269 for paint in &mut self.paint {
270 if let Paint::Spinner { step: Some(at), .. } = paint {
271 *at = step;
272 }
273 }
274 let letter = crate::spinner::FRAMES[step as usize % crate::spinner::FRAMES.len()];
275 for &(x, y) in &self.turning {
276 let at = y as usize * self.width as usize + x as usize;
277 let cell = self.cells.get_mut(at).filter(|_| x < self.width);
279 if let Some(cell) = cell.filter(|c| crate::spinner::FRAMES.contains(&c.symbol.as_str()))
280 {
281 cell.symbol = letter.into();
282 }
283 }
284 }
285
286 pub fn dot(&mut self, x: f32, y: u16, size: f32, color: Rgb, style: Style) {
289 self.dot_in((x, x.floor() as u16), y, size, color, style);
290 }
291
292 pub fn dot_in(&mut self, (x, cell): (f32, u16), y: u16, size: f32, color: Rgb, style: Style) {
294 let still = (None, crate::spinner::STILL);
295 self.mark((x, cell), y, size, color, style, still);
296 }
297
298 fn mark(
299 &mut self,
300 (x, cell): (f32, u16),
301 y: u16,
302 size: f32,
303 color: Rgb,
304 style: Style,
305 (step, letter): (Option<u8>, &str),
306 ) {
307 if step.is_some() {
308 self.turning.push((cell, y));
309 }
310 if cell < self.width && y < self.height {
311 let shown = Style {
312 fg: color,
313 painted: true,
314 ..style
315 };
316 self.put_str(cell, y, letter, shown, cell + 1);
317 }
318 self.paint.push(Paint::Spinner {
319 bounds: Bounds::cells(x, y as f32 + (1.0 - size) / 2.0, 2.0, size),
320 color,
321 step,
322 });
323 }
324
325 pub fn label(&mut self, x: u16, y: u16, text: &str, style: Style, max_x: u16) -> u16 {
327 self.label_at(x as f32, x, y, text, style, max_x, 100)
328 }
329
330 pub fn clear_paint_in(&mut self, area: Rect) {
333 let (left, right) = (i32::from(area.x) * UNIT, i32::from(area.right()) * UNIT);
334 let (top, bottom) = (i32::from(area.y) * UNIT, i32::from(area.bottom()) * UNIT);
335 self.paint.retain(|paint| {
336 let (from, _) = paint.reach();
337 let start = paint.top();
338 !(start >= top && start < bottom && from >= left && from < right)
339 });
340 }
341
342 pub fn painted_so_far(&self) -> usize {
344 self.paint.len()
345 }
346
347 pub fn keep_to_rows(&mut self, from: usize, top: u16, bottom: u16) {
350 if from < self.paint.len() {
351 self.kept.push(((from, self.paint.len()), (top, bottom)));
352 }
353 }
354
355 pub fn insert_paint(&mut self, index: usize, paint: Paint) {
357 let index = index.min(self.paint.len());
358 self.paint.insert(index, paint);
359 for ((from, to), _) in &mut self.kept {
361 if index < *from {
362 *from += 1;
363 }
364 if index < *to {
365 *to += 1;
366 }
367 }
368 }
369
370 pub fn lift_since(&mut self, from: usize, rows: f32) {
373 let by = units(rows);
374 for paint in self.paint.iter_mut().skip(from) {
375 paint.lift(by);
376 }
377 }
378
379 pub fn nudge_since(&mut self, from: usize, columns: f32) {
382 let by = units(columns);
383 for paint in self.paint.iter_mut().skip(from) {
384 match paint {
385 Paint::Text { x, .. } => *x += by,
386 Paint::Panel { bounds, .. }
387 | Paint::Wash { bounds, .. }
388 | Paint::Hairline { bounds, .. }
389 | Paint::Icon { bounds, .. }
390 | Paint::Spinner { bounds, .. }
391 | Paint::Corners { bounds, .. }
392 | Paint::Strips { bounds, .. } => bounds.x += by,
393 Paint::Image { bounds, clip, .. } => {
394 bounds.x += by;
395 clip.x += by;
396 }
397 }
398 }
399 }
400
401 #[allow(clippy::too_many_arguments)]
403 pub fn label_at(
404 &mut self,
405 x_px: f32,
406 x: u16,
407 y: u16,
408 text: &str,
409 style: Style,
410 max_x: u16,
411 size: u8,
412 ) -> u16 {
413 let end = self.put_str(
414 x,
415 y,
416 text,
417 Style {
418 painted: true,
419 ..style
420 },
421 max_x,
422 );
423 if y < self.height {
424 self.paint.push(Paint::Text {
425 x: units(x_px),
426 y: y as i32 * UNIT,
427 max_width: units(max_x.min(self.width) as f32 - x_px),
428 text: text.to_string(),
429 color: style.fg,
430 font: Font {
431 bold: style.bold,
432 size,
433 ..Font::default()
434 },
435 align_right: false,
436 centred: false,
437 underline: false,
438 });
439 }
440 end
441 }
442
443 pub fn text_run(
445 &mut self,
446 (x, y): (f32, f32),
447 max_x: f32,
448 text: &str,
449 (color, underline): (Rgb, bool),
450 font: Font,
451 ) {
452 self.paint.push(Paint::Text {
453 x: units(x),
454 y: units(y),
455 max_width: units(max_x - x),
456 text: text.to_string(),
457 color,
458 font,
459 align_right: false,
460 centred: false,
461 underline,
462 });
463 }
464
465 pub fn set_caret(&mut self, x: f32, y: u16, height: f32) {
467 self.cursor = Some((x as u16, y));
468 let top = y as f32 + (1.0 - height) / 2.0;
469 self.caret = Some(Bounds::cells(x, top, 0.0, height));
470 }
471
472 pub fn label_right(&mut self, right: u16, y: u16, text: &str, style: Style, size: u8) {
475 let cells = text.chars().count() as u16;
476 let x = right.saturating_sub(cells);
477 self.put_str(
478 x,
479 y,
480 text,
481 Style {
482 painted: true,
483 ..style
484 },
485 right,
486 );
487 self.paint.push(Paint::Text {
488 x: units(right as f32),
489 y: y as i32 * UNIT,
490 max_width: units(right as f32),
491 text: text.to_string(),
492 color: style.fg,
493 font: Font {
494 bold: style.bold,
495 size,
496 ..Font::default()
497 },
498 align_right: true,
499 centred: false,
500 underline: false,
501 });
502 }
503
504 pub fn field(&mut self, rect: Rect, behind: Rgb, fill: Rgb, border: Rgb) {
506 self.panel(Bounds::inset(rect, 0.0, 0.0), 0, Some(behind), None);
507 self.panel(
510 Bounds::inset(rect, 0.15, FIELD_AIR),
511 22,
512 Some(fill),
513 Some(border),
514 );
515 }
516
517 pub fn button(&mut self, x: u16, y: u16, cells: &str, label: &str, fill: Rgb, style: Style) {
520 self.button_of((BUTTON_HEIGHT, 0.0), (x, y), cells, label, fill, style);
521 }
522
523 pub fn row_button(
531 &mut self,
532 (x, y): (u16, u16),
533 cells: &str,
534 label: &str,
535 fill: Rgb,
536 style: Style,
537 ) {
538 self.button(x, y, cells, label, fill, style);
539 if !self.roomy {
540 return;
541 }
542 let chips = self.paint.iter_mut().rev();
545 for paint in chips.take(2) {
546 match paint {
547 Paint::Panel { inset, radius, .. } => {
548 *inset = true;
549 *radius = ROW_BUTTON_RADIUS;
550 }
551 Paint::Text { y, .. } => *y -= units(BUTTON_WORDS),
552 _ => {}
553 }
554 }
555 }
556
557 pub fn exact_fill(&mut self, bounds: Bounds, color: Rgb) {
562 let bitmap = crate::paint::Bitmap {
563 id: EXACT_FILL,
564 width: 1,
565 height: 1,
566 kind: crate::paint::Pixels::Coverage,
567 pixels: std::sync::Arc::new(vec![255]),
568 };
569 self.paint.push(Paint::Image {
570 bounds,
571 clip: bounds,
572 bitmap,
573 color,
574 });
575 }
576
577 pub fn chip(&mut self, x: f32, y: u16, wide: f32, fill: Rgb) {
580 let top = y as f32 + (1.0 - BUTTON_HEIGHT) / 2.0;
581 let bounds = Bounds::cells(x, top, wide, BUTTON_HEIGHT);
582 self.panel(bounds, 22, Some(fill), None);
583 }
584
585 pub fn large_button(
587 &mut self,
588 x: u16,
589 y: u16,
590 cells: &str,
591 label: &str,
592 fill: Rgb,
593 style: Style,
594 ) {
595 self.button_of(
596 (LARGE_BUTTON_HEIGHT, 0.0),
597 (x, y),
598 cells,
599 label,
600 fill,
601 style,
602 );
603 }
604
605 pub fn large_button_between(
607 &mut self,
608 x: u16,
609 y: u16,
610 cells: &str,
611 label: &str,
612 fill: Rgb,
613 style: Style,
614 ) {
615 self.button_of(
616 (LARGE_BUTTON_HEIGHT, 0.5),
617 (x, y),
618 cells,
619 label,
620 fill,
621 style,
622 );
623 }
624
625 fn button_of(
626 &mut self,
627 (height, drop): (f32, f32),
628 (x, y): (u16, u16),
629 cells: &str,
630 label: &str,
631 fill: Rgb,
632 style: Style,
633 ) {
634 let width = cells.chars().count() as u16;
635 let (left, top, right, bottom) = button_span((height, drop), (x, y), width);
636 self.put_str(
637 x,
638 y,
639 cells,
640 Style {
641 painted: true,
642 ..style
643 },
644 self.width,
645 );
646 let bounds = Bounds::cells(left, top, right - left, bottom - top);
647 self.panel(bounds, 22, Some(fill), None);
648 let middle = x as f32 + width as f32 / 2.0;
649 let raised = if self.roomy { 0.0 } else { BUTTON_WORDS };
650 self.centred_text(middle, y as f32 + drop - raised, label, style.fg, 90);
651 }
652
653 pub fn button_words(&mut self, middle: f32, y: u16, label: &str, color: Rgb) {
656 let raised = if self.roomy { 0.0 } else { BUTTON_WORDS };
657 self.centred_text(middle, y as f32 - raised, label, color, 90);
658 }
659
660 pub fn drop_last(&mut self, by: f32) {
662 match self.paint.last_mut() {
663 Some(Paint::Text { y, .. }) => *y += units(by),
664 Some(Paint::Icon { bounds, .. }) => bounds.y += units(by),
665 _ => {}
666 }
667 }
668
669 pub fn centred_text(&mut self, x: f32, y: f32, text: &str, color: Rgb, size: u8) {
671 self.paint.push(Paint::Text {
672 x: units(x),
673 y: units(y),
674 max_width: units(self.width as f32),
675 text: text.to_string(),
676 color,
677 font: Font {
678 size,
679 ..Font::default()
680 },
681 align_right: false,
682 centred: true,
683 underline: false,
684 });
685 }
686
687 pub fn panel(&mut self, bounds: Bounds, radius: u8, fill: Option<Rgb>, border: Option<Rgb>) {
688 self.paint.push(Paint::Panel {
689 bounds,
690 radius,
691 fill,
692 border,
693 shadow: false,
694 dashed: false,
695 inset: false,
696 });
697 }
698
699 pub fn dashed_panel(&mut self, bounds: Bounds, radius: u8, fill: Option<Rgb>, border: Rgb) {
701 self.paint.push(Paint::Panel {
702 bounds,
703 radius,
704 fill,
705 border: Some(border),
706 shadow: false,
707 dashed: true,
708 inset: false,
709 });
710 }
711
712 pub fn popup(&mut self, bounds: Bounds, radius: u8, fill: Rgb, border: Rgb) {
714 self.paint.push(Paint::Panel {
715 bounds,
716 radius,
717 fill: Some(fill),
718 border: Some(border),
719 shadow: true,
720 dashed: false,
721 inset: false,
722 });
723 }
724
725 pub fn wash(
727 &mut self,
728 bounds: Bounds,
729 radius: u8,
730 (color, alpha): (Rgb, u8),
731 border: Option<Rgb>,
732 ) {
733 self.paint.push(Paint::Wash {
734 bounds,
735 radius,
736 color,
737 alpha,
738 border,
739 });
740 }
741
742 pub fn hairline(&mut self, bounds: Bounds, color: Rgb) {
743 self.paint.push(Paint::Hairline { bounds, color });
744 }
745
746 pub fn glyph(&mut self, x: f32, y: u16, icon: Icon, color: Rgb, fallback: &str, style: Style) {
750 self.glyph_in((x, x.floor() as u16), y, (icon, color), fallback, style);
751 }
752
753 pub fn glyph_in(
755 &mut self,
756 (x, cell): (f32, u16),
757 y: u16,
758 (icon, color): (Icon, Rgb),
759 fallback: &str,
760 style: Style,
761 ) {
762 if cell < self.width && y < self.height {
763 self.put_str(
764 cell,
765 y,
766 fallback,
767 Style {
768 painted: true,
769 ..style
770 },
771 self.width,
772 );
773 }
774 self.paint.push(Paint::Icon {
775 bounds: Bounds::cells(x - GLYPH_LEAD, y as f32 + (1.0 - GLYPH) / 2.0, 2.0, GLYPH),
776 icon,
777 color,
778 });
779 }
780
781 #[allow(clippy::too_many_arguments)]
783 pub fn small_glyph(
784 &mut self,
785 x: f32,
786 y: u16,
787 icon: Icon,
788 color: Rgb,
789 fallback: &str,
790 style: Style,
791 ) {
792 self.glyph(x, y, icon, color, fallback, style);
793 if let Some(Paint::Icon { bounds, .. }) = self.paint.last_mut() {
794 let top = y as f32 + (1.0 - SMALL_GLYPH) / 2.0;
795 *bounds = Bounds::cells(x, top, 2.0, SMALL_GLYPH);
796 }
797 }
798
799 pub fn corners(&mut self, bounds: Bounds, radius: u8, color: Rgb, which: u8) {
801 self.paint.push(Paint::Corners {
802 bounds,
803 radius,
804 color,
805 which,
806 });
807 }
808
809 pub fn paint_on_row(&self, y: u16) -> impl Iterator<Item = &Paint> {
810 let (top, bottom) = (y as i32 * UNIT, (y as i32 + 1) * UNIT);
811 let kept_off = move |index: usize| {
812 self.kept.iter().any(|((from, to), (first, end))| {
813 (*from..*to).contains(&index) && !(*first..*end).contains(&y)
814 })
815 };
816 self.paint
817 .iter()
818 .enumerate()
819 .filter(move |(index, p)| {
820 let (from, to) = p.span();
821 from < bottom && to > top && !kept_off(*index)
822 })
823 .map(|(_, paint)| paint)
824 }
825
826 pub fn width(&self) -> u16 {
827 self.width
828 }
829
830 pub fn height(&self) -> u16 {
831 self.height
832 }
833
834 pub fn area(&self) -> Rect {
835 Rect::new(0, 0, self.width, self.height)
836 }
837
838 fn index(&self, x: u16, y: u16) -> usize {
839 y as usize * self.width as usize + x as usize
840 }
841
842 pub fn cell(&self, x: u16, y: u16) -> &Cell {
843 &self.cells[self.index(x, y)]
844 }
845
846 pub fn row(&self, y: u16) -> &[Cell] {
847 let start = self.index(0, y);
848 &self.cells[start..start + self.width as usize]
849 }
850
851 pub fn fill(&mut self, rect: Rect, style: Style) {
852 for y in rect.y..rect.bottom().min(self.height) {
853 for x in rect.x..rect.right().min(self.width) {
854 self.put_cell(x, y, " ", style);
855 }
856 }
857 }
858
859 fn put_cell(&mut self, x: u16, y: u16, symbol: &str, style: Style) {
860 let i = self.index(x, y);
862 if self.cells[i].symbol.is_empty() && x > 0 {
863 self.cells[i - 1].symbol = " ".into();
864 }
865 if x + 1 < self.width && self.cells[i + 1].symbol.is_empty() {
866 self.cells[i + 1].symbol = " ".into();
867 }
868 self.cells[i] = Cell {
869 symbol: symbol.into(),
870 style,
871 };
872 }
873
874 pub fn put_str(&mut self, x: u16, y: u16, text: &str, style: Style, max_x: u16) -> u16 {
877 if y >= self.height {
878 return x;
879 }
880 let max_x = max_x.min(self.width);
881 let mut at = x;
882 let text = visible(text);
883 for g in text.graphemes(true) {
884 if at >= max_x {
885 break;
886 }
887 let width = g.width() as u16;
888 if width == 0 {
889 continue;
890 }
891 if at + width > max_x {
892 self.put_cell(at, y, " ", style);
893 return at + 1;
894 }
895 self.put_cell(at, y, g, style);
896 if width == 2 {
897 self.put_cell(at + 1, y, "", style);
898 }
899 at += width;
900 }
901 at
902 }
903
904 pub fn put_icon(&mut self, x: u16, y: u16, icon: Icon, size: (u8, u8), style: Style) {
906 for row in 0..size.1 {
907 for column in 0..size.0 {
908 let (cx, cy) = (x + u16::from(column), y + u16::from(row));
909 if cx < self.width && cy < self.height {
910 let piece = Piece {
911 icon,
912 width: size.0,
913 height: size.1,
914 column,
915 row,
916 };
917 self.put_cell(cx, cy, piece.symbol().encode_utf8(&mut [0; 4]), style);
918 }
919 }
920 }
921 }
922
923 pub fn set_style(&mut self, rect: Rect, f: impl Fn(Style) -> Style) {
925 for y in rect.y..rect.bottom().min(self.height) {
926 for x in rect.x..rect.right().min(self.width) {
927 let i = self.index(x, y);
928 self.cells[i].style = f(self.cells[i].style);
929 }
930 }
931 }
932
933 pub fn diff(&self, prev: &Grid) -> Vec<Run> {
935 let same_size = self.width == prev.width && self.height == prev.height;
936 let mut runs = Vec::new();
937 for y in 0..self.height {
938 if same_size && self.row(y) == prev.row(y) {
939 continue;
940 }
941 let mut x = 0;
942 while x < self.width {
943 if same_size && self.cell(x, y) == prev.cell(x, y) {
944 x += 1;
945 continue;
946 }
947 let start = x;
948 while x < self.width && !(same_size && self.cell(x, y) == prev.cell(x, y)) {
949 x += 1;
950 }
951 let start = if self.cell(start, y).symbol.is_empty() && start > 0 {
953 start - 1
954 } else {
955 start
956 };
957 runs.push(Run {
958 x: start,
959 y,
960 len: x - start,
961 });
962 }
963 }
964 runs
965 }
966
967 pub fn row_text(&self, y: u16) -> String {
969 self.row(y).iter().map(|c| c.symbol.as_str()).collect()
970 }
971
972 pub fn text(&self) -> String {
974 (0..self.height)
975 .map(|y| self.row_text(y).trim_end().to_string())
976 .collect::<Vec<_>>()
977 .join("\n")
978 }
979}
980
981fn button_span((height, drop): (f32, f32), (x, y): (u16, u16), width: u16) -> (f32, f32, f32, f32) {
983 let top = y as f32 + drop + (1.0 - height) / 2.0;
984 (x as f32, top, (x + width) as f32, top + height)
985}
986
987pub fn air_under_button(row: f32, line: f32) -> f32 {
990 row - button_in_row(row, line).1
991}
992
993pub fn row_button_in_row(row: f32, line: f32) -> (f32, f32) {
997 let (_, top, _, bottom) = button_span((BUTTON_HEIGHT, 0.0), (0, 0), 1);
998 let (top, tall) = crate::raster::inset(units(top), units(bottom - top), row, line);
999 (top, top + tall)
1000}
1001
1002pub fn button_in_row(row: f32, line: f32) -> (f32, f32) {
1005 let (_, top, _, bottom) = button_span((BUTTON_HEIGHT, 0.0), (0, 0), 1);
1006 let bounds = Bounds::cells(0.0, top, 1.0, bottom - top);
1007 let (y, h) = crate::raster::stood(bounds.y, bounds.h, row, line);
1008 (y, y + h)
1009}
1010
1011pub fn on_large_button((x, y): (u16, u16), width: u16, at: (f32, f32)) -> bool {
1016 let (left, top, right, bottom) = button_span((LARGE_BUTTON_HEIGHT, 0.0), (x, y), width);
1017 at.0 >= left && at.0 < right && at.1 >= top && at.1 < bottom
1018}
1019
1020#[cfg(test)]
1021mod tests {
1022 #[test]
1025 fn paint_kept_to_its_rows_is_on_no_other() {
1026 let style = Style::default();
1027 let mut grid = Grid::new(10, 6, style);
1028 let panel = |grid: &mut Grid, y: f32, h: f32| {
1029 grid.panel(Bounds::cells(0.0, y, 10.0, h), 0, Some(Rgb(1, 2, 3)), None);
1030 };
1031 panel(&mut grid, 0.0, 1.0);
1032 let from = grid.painted_so_far();
1033 panel(&mut grid, 1.0, 4.5);
1035 grid.keep_to_rows(from, 2, 4);
1036 panel(&mut grid, 5.0, 1.0);
1037 let on = |grid: &Grid, y: u16| grid.paint_on_row(y).count();
1038 let rows: Vec<usize> = (0..6).map(|y| on(&grid, y)).collect();
1039 assert_eq!(rows, [1, 0, 1, 1, 0, 1]);
1040 grid.insert_paint(
1042 0,
1043 Paint::Hairline {
1044 bounds: Bounds::cells(0.0, 1.0, 10.0, 0.0),
1045 color: Rgb(9, 9, 9),
1046 },
1047 );
1048 let rows: Vec<usize> = (0..6).map(|y| on(&grid, y)).collect();
1049 assert_eq!(rows, [1, 1, 1, 1, 0, 1]);
1050 }
1051
1052 #[test]
1053 fn control_characters_never_reach_a_cell() {
1054 let style = Style::default();
1055 let mut grid = Grid::new(40, 2, style);
1056 let text = "a\x1b]52;c;aGk=\x07b\r\n\x7f\u{9b}2Jc\td";
1057 let end = grid.put_str(0, 0, text, style, 40);
1058 let row: String = (0..end)
1059 .map(|x| grid.cell(x, 0).symbol.to_string())
1060 .collect();
1061 assert_eq!(row, "a␛]52;c;aGk=␇b␍␊␡\u{fffd}2Jc d");
1062 assert!(row.chars().all(|c| !c.is_control()), "{row:?}");
1063 }
1064
1065 use super::*;
1066
1067 fn grid() -> Grid {
1068 Grid::new(10, 3, Style::default())
1069 }
1070
1071 #[test]
1072 fn diff_emits_only_changed_cells() {
1073 let before = grid();
1074 let mut after = grid();
1075 after.put_str(2, 1, "ab", Style::default(), 10);
1076 after.put_str(7, 1, "c", Style::default(), 10);
1077 assert_eq!(
1078 after.diff(&before),
1079 vec![Run { x: 2, y: 1, len: 2 }, Run { x: 7, y: 1, len: 1 }]
1080 );
1081 assert!(before.diff(&before.clone()).is_empty());
1082 }
1083
1084 #[test]
1085 fn resize_redraws_everything() {
1086 let runs = grid().diff(&Grid::new(4, 4, Style::default()));
1087 assert_eq!(runs.len(), 3);
1088 assert!(runs.iter().all(|r| r.len == 10));
1089 }
1090
1091 #[test]
1092 fn wide_characters_take_two_cells() {
1093 let mut g = grid();
1094 let end = g.put_str(0, 0, "日本", Style::default(), 10);
1095 assert_eq!(end, 4);
1096 assert_eq!(g.cell(0, 0).symbol, "日");
1097 assert_eq!(g.cell(1, 0).symbol, "");
1098 assert_eq!(g.row_text(0).trim_end(), "日本");
1099 }
1100
1101 #[test]
1102 fn overwriting_half_a_wide_character_blanks_the_other_half() {
1103 let mut g = grid();
1104 g.put_str(0, 0, "日", Style::default(), 10);
1105 g.put_str(1, 0, "x", Style::default(), 10);
1106 assert_eq!(g.cell(0, 0).symbol, " ");
1107 assert_eq!(g.cell(1, 0).symbol, "x");
1108 }
1109
1110 #[test]
1111 fn wide_character_at_the_edge_becomes_a_space() {
1112 let mut g = grid();
1113 g.put_str(9, 0, "日", Style::default(), 10);
1114 assert_eq!(g.cell(9, 0).symbol, " ");
1115 }
1116
1117 #[test]
1118 fn combining_marks_stay_in_one_cell() {
1119 let mut g = grid();
1120 let end = g.put_str(0, 0, "e\u{301}x", Style::default(), 10);
1121 assert_eq!(end, 2);
1122 assert_eq!(g.cell(0, 0).symbol, "e\u{301}");
1123 }
1124
1125 #[test]
1126 fn diff_never_starts_on_a_continuation_cell() {
1127 let mut before = grid();
1128 before.put_str(0, 0, "日", Style::default(), 10);
1129 let mut after = grid();
1130 after.put_str(
1131 0,
1132 0,
1133 "日",
1134 Style {
1135 bold: true,
1136 ..Style::default()
1137 },
1138 10,
1139 );
1140 let mut only_right = before.clone();
1141 only_right.cells[1].style.bold = true;
1142 assert_eq!(only_right.diff(&before)[0].x, 0);
1143 assert_eq!(after.diff(&before)[0].x, 0);
1144 }
1145
1146 #[test]
1149 fn a_step_on_the_drawn_grid_is_the_grid_drawn_at_that_step() {
1150 let draw = |step: u8| {
1151 let mut grid = Grid::new(30, 4, Style::default());
1152 grid.turn = Some(step);
1153 grid.put_str(0, 1, "working", Style::default(), 30);
1154 grid.spinner(9.0, 1, 0.65, Rgb(1, 2, 3), Style::default());
1155 grid.dot(12.0, 1, 0.65, Rgb(4, 5, 6), Style::default());
1156 grid.spinner(3.0, 3, 0.65, Rgb(1, 2, 3), Style::default());
1157 grid
1158 };
1159 let mut stepped = draw(0);
1160 for step in [1, 7, 0, 9] {
1161 stepped.turn_to(step);
1162 assert_eq!(stepped, draw(step), "step {step}");
1163 }
1164 assert_eq!(
1165 stepped.cell(12, 1).symbol,
1166 crate::spinner::STILL,
1167 "a dot stays"
1168 );
1169 let mut covered = draw(0);
1171 covered.put_str(8, 1, "menu", Style::default(), 30);
1172 covered.turn_to(4);
1173 assert_eq!(covered.row_text(1).trim_end(), "working menu●");
1174 let mut still = Grid::new(30, 4, Style::default());
1176 still.turn = None;
1177 still.spinner(9.0, 1, 0.65, Rgb(1, 2, 3), Style::default());
1178 let before = still.clone();
1179 still.turn_to(3);
1180 assert_eq!(still, before);
1181 }
1182}