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
83trait CopyCells {
85 fn copy_within_cells(&mut self, from: std::ops::Range<usize>, to: usize);
86}
87
88impl CopyCells for Vec<Cell> {
89 fn copy_within_cells(&mut self, from: std::ops::Range<usize>, to: usize) {
90 for (n, at) in from.enumerate() {
91 let cell = self[at].clone();
92 self[to + n] = cell;
93 }
94 }
95}
96
97#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
98pub struct Rect {
99 pub x: u16,
100 pub y: u16,
101 pub w: u16,
102 pub h: u16,
103}
104
105impl Rect {
106 pub fn new(x: u16, y: u16, w: u16, h: u16) -> Self {
107 Self { x, y, w, h }
108 }
109
110 pub fn contains(&self, x: u16, y: u16) -> bool {
111 x >= self.x && x < self.x + self.w && y >= self.y && y < self.y + self.h
112 }
113
114 pub fn right(&self) -> u16 {
115 self.x + self.w
116 }
117
118 pub fn bottom(&self) -> u16 {
119 self.y + self.h
120 }
121}
122
123#[derive(Clone, Copy, Debug, PartialEq, Eq)]
125pub struct Run {
126 pub x: u16,
127 pub y: u16,
128 pub len: u16,
129}
130
131#[derive(Clone, Debug, PartialEq, Eq)]
132pub struct Grid {
133 width: u16,
134 height: u16,
135 cells: Vec<Cell>,
136 pub cursor: Option<(u16, u16)>,
137 pub caret: Option<Bounds>,
139 pub paint: Vec<Paint>,
141 pub bands: Vec<u16>,
144 pub edge: Option<Rgb>,
147 pub roomy: bool,
151 pub row_air: u16,
155 pub foot: u16,
160 pub row_bands: Option<(u16, Vec<u16>)>,
164 pub turn: Option<u8>,
167 pub spinning: bool,
170 turning: Vec<(u16, u16)>,
172 kept: Vec<((usize, usize), (u16, u16))>,
176}
177
178impl Grid {
179 pub fn scroll_rows(&mut self, top: u16, bottom: u16, by: i32) {
183 let width = self.width as usize;
184 let (top, bottom) = (
185 top as usize,
186 (bottom as usize).min(self.height as usize - 1),
187 );
188 if top > bottom || by == 0 {
189 return;
190 }
191 let rows = bottom + 1 - top;
192 let n = (by.unsigned_abs() as usize).min(rows);
193 let unknown = Cell {
194 symbol: CompactString::const_new("\u{fffe}"),
195 style: Style::default(),
196 };
197 let row = |y: usize| y * width..(y + 1) * width;
198 if by > 0 {
199 for y in top..bottom + 1 - n {
200 self.cells.copy_within_cells(row(y + n), row(y).start);
201 }
202 for y in bottom + 1 - n..=bottom {
203 self.cells[row(y)].fill(unknown.clone());
204 }
205 } else {
206 for y in (top + n..=bottom).rev() {
207 self.cells.copy_within_cells(row(y - n), row(y).start);
208 }
209 for y in top..top + n {
210 self.cells[row(y)].fill(unknown.clone());
211 }
212 }
213 }
214
215 pub fn new(width: u16, height: u16, style: Style) -> Self {
216 let blank = Cell {
217 symbol: " ".into(),
218 style,
219 };
220 Self {
221 width,
222 height,
223 cells: vec![blank; width as usize * height as usize],
224 cursor: None,
225 caret: None,
226 paint: Vec::new(),
227 bands: Vec::new(),
228 edge: None,
229 roomy: false,
230 row_air: 100,
231 foot: 1,
232 row_bands: None,
233 turn: Some(0),
234 spinning: false,
235 turning: Vec::new(),
236 kept: Vec::new(),
237 }
238 }
239
240 pub fn spinner(&mut self, x: f32, y: u16, size: f32, color: Rgb, style: Style) {
246 self.spinner_in((x, x.floor() as u16), y, size, color, style);
247 }
248
249 pub fn spinner_in(
253 &mut self,
254 (x, cell): (f32, u16),
255 y: u16,
256 size: f32,
257 color: Rgb,
258 style: Style,
259 ) {
260 let step = self.turn;
261 self.spinning |= step.is_some();
262 let letter = step.map_or(crate::spinner::STILL, |s| {
263 crate::spinner::FRAMES[s as usize % crate::spinner::FRAMES.len()]
264 });
265 self.mark((x, cell), y, size, color, style, (step, letter));
266 }
267
268 pub fn turn_to(&mut self, step: u8) {
272 if self.turn.is_none() {
273 return;
274 }
275 self.turn = Some(step);
276 for paint in &mut self.paint {
277 if let Paint::Spinner { step: Some(at), .. } = paint {
278 *at = step;
279 }
280 }
281 let letter = crate::spinner::FRAMES[step as usize % crate::spinner::FRAMES.len()];
282 for &(x, y) in &self.turning {
283 let at = y as usize * self.width as usize + x as usize;
284 let cell = self.cells.get_mut(at).filter(|_| x < self.width);
286 if let Some(cell) = cell.filter(|c| crate::spinner::FRAMES.contains(&c.symbol.as_str()))
287 {
288 cell.symbol = letter.into();
289 }
290 }
291 }
292
293 pub fn dot(&mut self, x: f32, y: u16, size: f32, color: Rgb, style: Style) {
296 self.dot_in((x, x.floor() as u16), y, size, color, style);
297 }
298
299 pub fn dot_in(&mut self, (x, cell): (f32, u16), y: u16, size: f32, color: Rgb, style: Style) {
301 let still = (None, crate::spinner::STILL);
302 self.mark((x, cell), y, size, color, style, still);
303 }
304
305 fn mark(
306 &mut self,
307 (x, cell): (f32, u16),
308 y: u16,
309 size: f32,
310 color: Rgb,
311 style: Style,
312 (step, letter): (Option<u8>, &str),
313 ) {
314 if step.is_some() {
315 self.turning.push((cell, y));
316 }
317 if cell < self.width && y < self.height {
318 let shown = Style {
319 fg: color,
320 painted: true,
321 ..style
322 };
323 self.put_str(cell, y, letter, shown, cell + 1);
324 }
325 self.paint.push(Paint::Spinner {
326 bounds: Bounds::cells(x, y as f32 + (1.0 - size) / 2.0, 2.0, size),
327 color,
328 step,
329 });
330 }
331
332 pub fn label(&mut self, x: u16, y: u16, text: &str, style: Style, max_x: u16) -> u16 {
334 self.label_at(x as f32, x, y, text, style, max_x, 100)
335 }
336
337 pub fn clear_paint_in(&mut self, area: Rect) {
340 let (left, right) = (i32::from(area.x) * UNIT, i32::from(area.right()) * UNIT);
341 let (top, bottom) = (i32::from(area.y) * UNIT, i32::from(area.bottom()) * UNIT);
342 self.paint.retain(|paint| {
343 let (from, _) = paint.reach();
344 let start = paint.top();
345 !(start >= top && start < bottom && from >= left && from < right)
346 });
347 }
348
349 pub fn pictures_again_in(&mut self, before: usize, area: Rect) {
357 let clip_to = |clip: Bounds, (left, top, right, bottom): (i32, i32, i32, i32)| {
358 let (x, y) = (clip.x.max(left), clip.y.max(top));
359 let (end_x, end_y) = ((clip.x + clip.w).min(right), (clip.y + clip.h).min(bottom));
360 Bounds {
361 x,
362 y,
363 w: end_x - x,
364 h: end_y - y,
365 }
366 };
367 let (left, right) = (i32::from(area.x) * UNIT, i32::from(area.right()) * UNIT);
368 let (top, bottom) = (i32::from(area.y) * UNIT, i32::from(area.bottom()) * UNIT);
369 let mut again = Vec::new();
370 for (index, paint) in self.paint.iter().enumerate().take(before) {
371 let Paint::Image {
372 bounds,
373 clip,
374 bitmap,
375 color,
376 } = paint
377 else {
378 continue;
379 };
380 if bitmap.id == EXACT_FILL {
381 continue;
382 }
383 let mut clip = clip_to(*clip, (left, top, right, bottom));
384 for ((from, to), (first, end)) in &self.kept {
385 if (*from..*to).contains(&index) {
386 let rows = (i32::from(*first) * UNIT, i32::from(*end) * UNIT);
387 clip = clip_to(clip, (left, rows.0, right, rows.1));
388 }
389 }
390 let shown = clip_to(
391 clip,
392 (bounds.x, bounds.y, bounds.x + bounds.w, bounds.y + bounds.h),
393 );
394 if shown.w > 0 && shown.h > 0 {
395 again.push(Paint::Image {
396 bounds: *bounds,
397 clip,
398 bitmap: bitmap.clone(),
399 color: *color,
400 });
401 }
402 }
403 self.paint.extend(again);
404 }
405
406 pub fn painted_so_far(&self) -> usize {
408 self.paint.len()
409 }
410
411 pub fn keep_to_rows(&mut self, from: usize, top: u16, bottom: u16) {
414 if from < self.paint.len() {
415 self.kept.push(((from, self.paint.len()), (top, bottom)));
416 }
417 }
418
419 pub fn insert_paint(&mut self, index: usize, paint: Paint) {
421 let index = index.min(self.paint.len());
422 self.paint.insert(index, paint);
423 for ((from, to), _) in &mut self.kept {
425 if index < *from {
426 *from += 1;
427 }
428 if index < *to {
429 *to += 1;
430 }
431 }
432 }
433
434 pub fn lift_since(&mut self, from: usize, rows: f32) {
437 let by = units(rows);
438 for paint in self.paint.iter_mut().skip(from) {
439 paint.lift(by);
440 }
441 }
442
443 pub fn nudge_since(&mut self, from: usize, columns: f32) {
446 let by = units(columns);
447 for paint in self.paint.iter_mut().skip(from) {
448 match paint {
449 Paint::Text { x, .. } => *x += by,
450 Paint::Panel { bounds, .. }
451 | Paint::Wash { bounds, .. }
452 | Paint::Hairline { bounds, .. }
453 | Paint::Icon { bounds, .. }
454 | Paint::Spinner { bounds, .. }
455 | Paint::Corners { bounds, .. }
456 | Paint::Strips { bounds, .. } => bounds.x += by,
457 Paint::Image { bounds, clip, .. } => {
458 bounds.x += by;
459 clip.x += by;
460 }
461 }
462 }
463 }
464
465 #[allow(clippy::too_many_arguments)]
467 pub fn label_at(
468 &mut self,
469 x_px: f32,
470 x: u16,
471 y: u16,
472 text: &str,
473 style: Style,
474 max_x: u16,
475 size: u8,
476 ) -> u16 {
477 let end = self.put_str(
478 x,
479 y,
480 text,
481 Style {
482 painted: true,
483 ..style
484 },
485 max_x,
486 );
487 if y < self.height {
488 self.paint.push(Paint::Text {
489 x: units(x_px),
490 y: y as i32 * UNIT,
491 max_width: units(max_x.min(self.width) as f32 - x_px),
492 text: text.to_string(),
493 color: style.fg,
494 font: Font {
495 bold: style.bold,
496 size,
497 ..Font::default()
498 },
499 align_right: false,
500 centred: false,
501 underline: false,
502 span_centred: false,
503 });
504 }
505 end
506 }
507
508 pub fn text_run(
510 &mut self,
511 (x, y): (f32, f32),
512 max_x: f32,
513 text: &str,
514 (color, underline): (Rgb, bool),
515 font: Font,
516 ) {
517 self.paint.push(Paint::Text {
518 x: units(x),
519 y: units(y),
520 max_width: units(max_x - x),
521 text: text.to_string(),
522 color,
523 font,
524 align_right: false,
525 centred: false,
526 underline,
527 span_centred: false,
528 });
529 }
530
531 pub fn set_caret(&mut self, x: f32, y: u16, height: f32) {
533 self.cursor = Some((x as u16, y));
534 let top = y as f32 + (1.0 - height) / 2.0;
535 self.caret = Some(Bounds::cells(x, top, 0.0, height));
536 }
537
538 pub fn label_right(&mut self, right: u16, y: u16, text: &str, style: Style, size: u8) {
541 self.label_right_at(right as f32, right, y, text, style, size);
542 }
543
544 pub fn label_right_at(
547 &mut self,
548 right: f32,
549 cell: u16,
550 y: u16,
551 text: &str,
552 style: Style,
553 size: u8,
554 ) {
555 let cells = text.chars().count() as u16;
556 let x = cell.saturating_sub(cells);
557 self.put_str(
558 x,
559 y,
560 text,
561 Style {
562 painted: true,
563 ..style
564 },
565 cell,
566 );
567 self.paint.push(Paint::Text {
568 x: units(right),
569 y: y as i32 * UNIT,
570 max_width: units(right),
571 text: text.to_string(),
572 color: style.fg,
573 font: Font {
574 bold: style.bold,
575 size,
576 ..Font::default()
577 },
578 align_right: true,
579 centred: false,
580 underline: false,
581 span_centred: false,
582 });
583 }
584
585 pub fn field(&mut self, rect: Rect, behind: Rgb, fill: Rgb, border: Rgb) {
587 self.panel(Bounds::inset(rect, 0.0, 0.0), 0, Some(behind), None);
588 self.panel(
591 Bounds::inset(rect, 0.15, FIELD_AIR),
592 22,
593 Some(fill),
594 Some(border),
595 );
596 }
597
598 pub fn button(&mut self, x: u16, y: u16, cells: &str, label: &str, fill: Rgb, style: Style) {
601 self.button_of((BUTTON_HEIGHT, 0.0), (x, y), cells, label, fill, style);
602 }
603
604 pub fn row_button(
613 &mut self,
614 (x, y): (u16, u16),
615 cells: &str,
616 label: &str,
617 fill: Rgb,
618 style: Style,
619 ) {
620 let from = self.paint.len();
621 self.button(x, y, cells, label, fill, style);
622 if !self.roomy {
623 return;
624 }
625 for paint in &mut self.paint[from..] {
628 if let Paint::Panel { inset, radius, .. } = paint {
629 *inset = true;
630 *radius = ROW_BUTTON_RADIUS;
631 }
632 }
633 self.beside_words(from);
634 }
635
636 pub fn row_chip(&mut self, (left, right): (f32, f32), y: u16, fill: Rgb) {
642 let (_, top, _, bottom) = button_span((BUTTON_HEIGHT, 0.0), (0, y), 1);
643 let (radius, inset) = if self.roomy {
644 (ROW_BUTTON_RADIUS, true)
645 } else {
646 (22, false)
647 };
648 self.paint.push(Paint::Panel {
649 bounds: Bounds::cells(left, top, right - left, bottom - top),
650 radius,
651 fill: Some(fill),
652 border: None,
653 shadow: false,
654 dashed: false,
655 inset,
656 });
657 }
658
659 pub fn beside_words(&mut self, from: usize) {
663 if self.roomy {
664 let line = 100.0 / f32::from(self.row_air.max(1));
665 self.lift_since(from, -WORDS_BASELINE * line);
666 }
667 }
668
669 pub fn exact_fill(&mut self, bounds: Bounds, color: Rgb) {
674 let bitmap = crate::paint::Bitmap {
675 id: EXACT_FILL,
676 width: 1,
677 height: 1,
678 kind: crate::paint::Pixels::Coverage,
679 pixels: std::sync::Arc::new(vec![255]),
680 };
681 self.paint.push(Paint::Image {
682 bounds,
683 clip: bounds,
684 bitmap,
685 color,
686 });
687 }
688
689 pub fn exact_fill_under(&mut self, index: usize, bounds: Bounds, color: Rgb) {
691 self.exact_fill(bounds, color);
692 if let Some(fill) = self.paint.pop() {
693 self.insert_paint(index, fill);
694 }
695 }
696
697 pub fn chip(&mut self, x: f32, y: u16, wide: f32, fill: Rgb) {
700 let top = y as f32 + (1.0 - BUTTON_HEIGHT) / 2.0;
701 let bounds = Bounds::cells(x, top, wide, BUTTON_HEIGHT);
702 self.panel(bounds, 22, Some(fill), None);
703 }
704
705 pub fn large_button(
707 &mut self,
708 x: u16,
709 y: u16,
710 cells: &str,
711 label: &str,
712 fill: Rgb,
713 style: Style,
714 ) {
715 self.button_of(
716 (LARGE_BUTTON_HEIGHT, 0.0),
717 (x, y),
718 cells,
719 label,
720 fill,
721 style,
722 );
723 }
724
725 pub fn large_button_between(
727 &mut self,
728 x: u16,
729 y: u16,
730 cells: &str,
731 label: &str,
732 fill: Rgb,
733 style: Style,
734 ) {
735 self.button_of(
736 (LARGE_BUTTON_HEIGHT, 0.5),
737 (x, y),
738 cells,
739 label,
740 fill,
741 style,
742 );
743 }
744
745 fn button_of(
746 &mut self,
747 (height, drop): (f32, f32),
748 (x, y): (u16, u16),
749 cells: &str,
750 label: &str,
751 fill: Rgb,
752 style: Style,
753 ) {
754 let width = cells.chars().count() as u16;
755 let (left, top, right, bottom) = button_span((height, drop), (x, y), width);
756 self.put_str(
757 x,
758 y,
759 cells,
760 Style {
761 painted: true,
762 ..style
763 },
764 self.width,
765 );
766 let bounds = Bounds::cells(left, top, right - left, bottom - top);
767 self.panel(bounds, 22, Some(fill), None);
768 let middle = x as f32 + width as f32 / 2.0;
769 self.button_label(middle, y as f32 + drop, label, style.fg, 90);
770 }
771
772 pub fn button_words(&mut self, middle: f32, y: u16, label: &str, color: Rgb) {
775 self.button_label(middle, y as f32, label, color, 90);
776 }
777
778 pub fn button_label(&mut self, x: f32, y: f32, text: &str, color: Rgb, size: u8) {
784 self.centred_text(x, y, text, color, size);
785 self.centre_span_since(self.paint.len() - 1);
786 }
787
788 pub fn centre_span_since(&mut self, from: usize) {
791 for paint in self.paint.iter_mut().skip(from) {
792 if let Paint::Text { span_centred, .. } = paint {
793 *span_centred = true;
794 }
795 }
796 }
797
798 pub fn drop_last(&mut self, by: f32) {
800 match self.paint.last_mut() {
801 Some(Paint::Text { y, .. }) => *y += units(by),
802 Some(Paint::Icon { bounds, .. }) => bounds.y += units(by),
803 _ => {}
804 }
805 }
806
807 pub fn centred_text(&mut self, x: f32, y: f32, text: &str, color: Rgb, size: u8) {
809 self.paint.push(Paint::Text {
810 x: units(x),
811 y: units(y),
812 max_width: units(self.width as f32),
813 text: text.to_string(),
814 color,
815 font: Font {
816 size,
817 ..Font::default()
818 },
819 align_right: false,
820 centred: true,
821 underline: false,
822 span_centred: false,
823 });
824 }
825
826 pub fn panel(&mut self, bounds: Bounds, radius: u8, fill: Option<Rgb>, border: Option<Rgb>) {
827 self.paint.push(Paint::Panel {
828 bounds,
829 radius,
830 fill,
831 border,
832 shadow: false,
833 dashed: false,
834 inset: false,
835 });
836 }
837
838 pub fn dashed_panel(&mut self, bounds: Bounds, radius: u8, fill: Option<Rgb>, border: Rgb) {
840 self.paint.push(Paint::Panel {
841 bounds,
842 radius,
843 fill,
844 border: Some(border),
845 shadow: false,
846 dashed: true,
847 inset: false,
848 });
849 }
850
851 pub fn popup(&mut self, bounds: Bounds, radius: u8, fill: Rgb, border: Rgb) {
853 self.paint.push(Paint::Panel {
854 bounds,
855 radius,
856 fill: Some(fill),
857 border: Some(border),
858 shadow: true,
859 dashed: false,
860 inset: false,
861 });
862 }
863
864 pub fn exact_popup(&mut self, bounds: Bounds, radius: u8, fill: Rgb, border: Rgb) {
868 self.paint.push(Paint::Panel {
869 bounds,
870 radius,
871 fill: Some(fill),
872 border: Some(border),
873 shadow: true,
874 dashed: false,
875 inset: true,
876 });
877 }
878
879 pub fn wash(
881 &mut self,
882 bounds: Bounds,
883 radius: u8,
884 (color, alpha): (Rgb, u8),
885 border: Option<Rgb>,
886 ) {
887 self.paint.push(Paint::Wash {
888 bounds,
889 radius,
890 color,
891 alpha,
892 border,
893 });
894 }
895
896 pub fn hairline(&mut self, bounds: Bounds, color: Rgb) {
897 self.paint.push(Paint::Hairline { bounds, color });
898 }
899
900 pub fn glyph(&mut self, x: f32, y: u16, icon: Icon, color: Rgb, fallback: &str, style: Style) {
904 self.glyph_in((x, x.floor() as u16), y, (icon, color), fallback, style);
905 }
906
907 pub fn glyph_in(
909 &mut self,
910 (x, cell): (f32, u16),
911 y: u16,
912 (icon, color): (Icon, Rgb),
913 fallback: &str,
914 style: Style,
915 ) {
916 if cell < self.width && y < self.height {
917 self.put_str(
918 cell,
919 y,
920 fallback,
921 Style {
922 painted: true,
923 ..style
924 },
925 self.width,
926 );
927 }
928 self.paint.push(Paint::Icon {
929 bounds: Bounds::cells(x - GLYPH_LEAD, y as f32 + (1.0 - GLYPH) / 2.0, 2.0, GLYPH),
930 icon,
931 color,
932 });
933 }
934
935 #[allow(clippy::too_many_arguments)]
937 pub fn small_glyph(
938 &mut self,
939 x: f32,
940 y: u16,
941 icon: Icon,
942 color: Rgb,
943 fallback: &str,
944 style: Style,
945 ) {
946 self.glyph(x, y, icon, color, fallback, style);
947 if let Some(Paint::Icon { bounds, .. }) = self.paint.last_mut() {
948 let top = y as f32 + (1.0 - SMALL_GLYPH) / 2.0;
949 *bounds = Bounds::cells(x, top, 2.0, SMALL_GLYPH);
950 }
951 }
952
953 pub fn corners(&mut self, bounds: Bounds, radius: u8, color: Rgb, which: u8) {
955 self.paint.push(Paint::Corners {
956 bounds,
957 radius,
958 color,
959 which,
960 });
961 }
962
963 pub fn paint_on_row(&self, y: u16) -> impl Iterator<Item = &Paint> {
964 let (top, bottom) = (y as i32 * UNIT, (y as i32 + 1) * UNIT);
965 let kept_off = move |index: usize| {
966 self.kept.iter().any(|((from, to), (first, end))| {
967 (*from..*to).contains(&index) && !(*first..*end).contains(&y)
968 })
969 };
970 self.paint
971 .iter()
972 .enumerate()
973 .filter(move |(index, p)| {
974 let (from, to) = p.span();
975 from < bottom && to > top && !kept_off(*index)
976 })
977 .map(|(_, paint)| paint)
978 }
979
980 pub fn spans(&self, y: u16) -> Vec<(u16, u16)> {
984 let width = self.width;
985 let own = self.row_bands.as_ref().filter(|(row, _)| *row == y);
986 let bands = match own {
987 Some((_, bands)) => bands,
988 None if y + 1 == self.height => return vec![(0, width)],
989 None => &self.bands,
990 };
991 let inside = bands.iter().copied().filter(|x| *x > 0 && *x < width);
992 let edges: Vec<u16> = [0].into_iter().chain(inside).chain([width]).collect();
993 edges.windows(2).map(|edge| (edge[0], edge[1])).collect()
994 }
995
996 pub fn width(&self) -> u16 {
997 self.width
998 }
999
1000 pub fn height(&self) -> u16 {
1001 self.height
1002 }
1003
1004 pub fn area(&self) -> Rect {
1005 Rect::new(0, 0, self.width, self.height)
1006 }
1007
1008 fn index(&self, x: u16, y: u16) -> usize {
1009 y as usize * self.width as usize + x as usize
1010 }
1011
1012 pub fn cell(&self, x: u16, y: u16) -> &Cell {
1013 &self.cells[self.index(x, y)]
1014 }
1015
1016 pub fn row(&self, y: u16) -> &[Cell] {
1017 let start = self.index(0, y);
1018 &self.cells[start..start + self.width as usize]
1019 }
1020
1021 pub fn fill(&mut self, rect: Rect, style: Style) {
1022 for y in rect.y..rect.bottom().min(self.height) {
1023 for x in rect.x..rect.right().min(self.width) {
1024 self.put_cell(x, y, " ", style);
1025 }
1026 }
1027 }
1028
1029 fn put_cell(&mut self, x: u16, y: u16, symbol: &str, style: Style) {
1030 let i = self.index(x, y);
1032 if self.cells[i].symbol.is_empty() && x > 0 {
1033 self.cells[i - 1].symbol = " ".into();
1034 }
1035 if x + 1 < self.width && self.cells[i + 1].symbol.is_empty() {
1036 self.cells[i + 1].symbol = " ".into();
1037 }
1038 self.cells[i] = Cell {
1039 symbol: symbol.into(),
1040 style,
1041 };
1042 }
1043
1044 pub fn put_str(&mut self, x: u16, y: u16, text: &str, style: Style, max_x: u16) -> u16 {
1047 if y >= self.height {
1048 return x;
1049 }
1050 let max_x = max_x.min(self.width);
1051 let mut at = x;
1052 let text = visible(text);
1053 for g in text.graphemes(true) {
1054 if at >= max_x {
1055 break;
1056 }
1057 let width = g.width() as u16;
1058 if width == 0 {
1059 continue;
1060 }
1061 if at + width > max_x {
1062 self.put_cell(at, y, " ", style);
1063 return at + 1;
1064 }
1065 self.put_cell(at, y, g, style);
1066 if width == 2 {
1067 self.put_cell(at + 1, y, "", style);
1068 }
1069 at += width;
1070 }
1071 at
1072 }
1073
1074 pub fn put_icon(&mut self, x: u16, y: u16, icon: Icon, size: (u8, u8), style: Style) {
1076 for row in 0..size.1 {
1077 for column in 0..size.0 {
1078 let (cx, cy) = (x + u16::from(column), y + u16::from(row));
1079 if cx < self.width && cy < self.height {
1080 let piece = Piece {
1081 icon,
1082 width: size.0,
1083 height: size.1,
1084 column,
1085 row,
1086 };
1087 self.put_cell(cx, cy, piece.symbol().encode_utf8(&mut [0; 4]), style);
1088 }
1089 }
1090 }
1091 }
1092
1093 pub fn set_style(&mut self, rect: Rect, f: impl Fn(Style) -> Style) {
1095 for y in rect.y..rect.bottom().min(self.height) {
1096 for x in rect.x..rect.right().min(self.width) {
1097 let i = self.index(x, y);
1098 self.cells[i].style = f(self.cells[i].style);
1099 }
1100 }
1101 }
1102
1103 pub fn diff(&self, prev: &Grid) -> Vec<Run> {
1105 let same_size = self.width == prev.width && self.height == prev.height;
1106 let mut runs = Vec::new();
1107 for y in 0..self.height {
1108 if same_size && self.row(y) == prev.row(y) {
1109 continue;
1110 }
1111 let mut x = 0;
1112 while x < self.width {
1113 if same_size && self.cell(x, y) == prev.cell(x, y) {
1114 x += 1;
1115 continue;
1116 }
1117 let start = x;
1118 while x < self.width && !(same_size && self.cell(x, y) == prev.cell(x, y)) {
1119 x += 1;
1120 }
1121 let start = if self.cell(start, y).symbol.is_empty() && start > 0 {
1123 start - 1
1124 } else {
1125 start
1126 };
1127 runs.push(Run {
1128 x: start,
1129 y,
1130 len: x - start,
1131 });
1132 }
1133 }
1134 runs
1135 }
1136
1137 pub fn row_text(&self, y: u16) -> String {
1139 self.row(y).iter().map(|c| c.symbol.as_str()).collect()
1140 }
1141
1142 pub fn text(&self) -> String {
1144 (0..self.height)
1145 .map(|y| self.row_text(y).trim_end().to_string())
1146 .collect::<Vec<_>>()
1147 .join("\n")
1148 }
1149}
1150
1151fn button_span((height, drop): (f32, f32), (x, y): (u16, u16), width: u16) -> (f32, f32, f32, f32) {
1153 let top = y as f32 + drop + (1.0 - height) / 2.0;
1154 (x as f32, top, (x + width) as f32, top + height)
1155}
1156
1157pub fn air_under_button(row: f32, line: f32) -> f32 {
1160 row - button_in_row(row, line).1
1161}
1162
1163pub fn row_button_in_row(row: f32, line: f32) -> (f32, f32) {
1168 let (_, top, _, bottom) = button_span((BUTTON_HEIGHT, 0.0), (0, 0), 1);
1169 let drop = units(WORDS_BASELINE * line / row) as f32 * row / UNIT as f32;
1170 let (top, tall) = crate::raster::inset(units(top), units(bottom - top), row, line);
1171 (top + drop, top + drop + tall)
1172}
1173
1174pub fn button_in_row(row: f32, line: f32) -> (f32, f32) {
1177 let (_, top, _, bottom) = button_span((BUTTON_HEIGHT, 0.0), (0, 0), 1);
1178 let bounds = Bounds::cells(0.0, top, 1.0, bottom - top);
1179 let (y, h) = crate::raster::stood(bounds.y, bounds.h, row, line);
1180 (y, y + h)
1181}
1182
1183pub fn on_large_button((x, y): (u16, u16), width: u16, at: (f32, f32)) -> bool {
1188 let (left, top, right, bottom) = button_span((LARGE_BUTTON_HEIGHT, 0.0), (x, y), width);
1189 at.0 >= left && at.0 < right && at.1 >= top && at.1 < bottom
1190}
1191
1192#[cfg(test)]
1193mod tests {
1194 #[test]
1197 fn paint_kept_to_its_rows_is_on_no_other() {
1198 let style = Style::default();
1199 let mut grid = Grid::new(10, 6, style);
1200 let panel = |grid: &mut Grid, y: f32, h: f32| {
1201 grid.panel(Bounds::cells(0.0, y, 10.0, h), 0, Some(Rgb(1, 2, 3)), None);
1202 };
1203 panel(&mut grid, 0.0, 1.0);
1204 let from = grid.painted_so_far();
1205 panel(&mut grid, 1.0, 4.5);
1207 grid.keep_to_rows(from, 2, 4);
1208 panel(&mut grid, 5.0, 1.0);
1209 let on = |grid: &Grid, y: u16| grid.paint_on_row(y).count();
1210 let rows: Vec<usize> = (0..6).map(|y| on(&grid, y)).collect();
1211 assert_eq!(rows, [1, 0, 1, 1, 0, 1]);
1212 grid.insert_paint(
1214 0,
1215 Paint::Hairline {
1216 bounds: Bounds::cells(0.0, 1.0, 10.0, 0.0),
1217 color: Rgb(9, 9, 9),
1218 },
1219 );
1220 let rows: Vec<usize> = (0..6).map(|y| on(&grid, y)).collect();
1221 assert_eq!(rows, [1, 1, 1, 1, 0, 1]);
1222 }
1223
1224 #[test]
1225 fn control_characters_never_reach_a_cell() {
1226 let style = Style::default();
1227 let mut grid = Grid::new(40, 2, style);
1228 let text = "a\x1b]52;c;aGk=\x07b\r\n\x7f\u{9b}2Jc\td";
1229 let end = grid.put_str(0, 0, text, style, 40);
1230 let row: String = (0..end)
1231 .map(|x| grid.cell(x, 0).symbol.to_string())
1232 .collect();
1233 assert_eq!(row, "a␛]52;c;aGk=␇b␍␊␡\u{fffd}2Jc d");
1234 assert!(row.chars().all(|c| !c.is_control()), "{row:?}");
1235 }
1236
1237 use super::*;
1238
1239 fn grid() -> Grid {
1240 Grid::new(10, 3, Style::default())
1241 }
1242
1243 #[test]
1244 fn diff_emits_only_changed_cells() {
1245 let before = grid();
1246 let mut after = grid();
1247 after.put_str(2, 1, "ab", Style::default(), 10);
1248 after.put_str(7, 1, "c", Style::default(), 10);
1249 assert_eq!(
1250 after.diff(&before),
1251 vec![Run { x: 2, y: 1, len: 2 }, Run { x: 7, y: 1, len: 1 }]
1252 );
1253 assert!(before.diff(&before.clone()).is_empty());
1254 }
1255
1256 #[test]
1257 fn resize_redraws_everything() {
1258 let runs = grid().diff(&Grid::new(4, 4, Style::default()));
1259 assert_eq!(runs.len(), 3);
1260 assert!(runs.iter().all(|r| r.len == 10));
1261 }
1262
1263 #[test]
1264 fn wide_characters_take_two_cells() {
1265 let mut g = grid();
1266 let end = g.put_str(0, 0, "日本", Style::default(), 10);
1267 assert_eq!(end, 4);
1268 assert_eq!(g.cell(0, 0).symbol, "日");
1269 assert_eq!(g.cell(1, 0).symbol, "");
1270 assert_eq!(g.row_text(0).trim_end(), "日本");
1271 }
1272
1273 #[test]
1274 fn overwriting_half_a_wide_character_blanks_the_other_half() {
1275 let mut g = grid();
1276 g.put_str(0, 0, "日", Style::default(), 10);
1277 g.put_str(1, 0, "x", Style::default(), 10);
1278 assert_eq!(g.cell(0, 0).symbol, " ");
1279 assert_eq!(g.cell(1, 0).symbol, "x");
1280 }
1281
1282 #[test]
1283 fn wide_character_at_the_edge_becomes_a_space() {
1284 let mut g = grid();
1285 g.put_str(9, 0, "日", Style::default(), 10);
1286 assert_eq!(g.cell(9, 0).symbol, " ");
1287 }
1288
1289 #[test]
1290 fn combining_marks_stay_in_one_cell() {
1291 let mut g = grid();
1292 let end = g.put_str(0, 0, "e\u{301}x", Style::default(), 10);
1293 assert_eq!(end, 2);
1294 assert_eq!(g.cell(0, 0).symbol, "e\u{301}");
1295 }
1296
1297 #[test]
1298 fn diff_never_starts_on_a_continuation_cell() {
1299 let mut before = grid();
1300 before.put_str(0, 0, "日", Style::default(), 10);
1301 let mut after = grid();
1302 after.put_str(
1303 0,
1304 0,
1305 "日",
1306 Style {
1307 bold: true,
1308 ..Style::default()
1309 },
1310 10,
1311 );
1312 let mut only_right = before.clone();
1313 only_right.cells[1].style.bold = true;
1314 assert_eq!(only_right.diff(&before)[0].x, 0);
1315 assert_eq!(after.diff(&before)[0].x, 0);
1316 }
1317
1318 #[test]
1321 fn a_step_on_the_drawn_grid_is_the_grid_drawn_at_that_step() {
1322 let draw = |step: u8| {
1323 let mut grid = Grid::new(30, 4, Style::default());
1324 grid.turn = Some(step);
1325 grid.put_str(0, 1, "working", Style::default(), 30);
1326 grid.spinner(9.0, 1, 0.65, Rgb(1, 2, 3), Style::default());
1327 grid.dot(12.0, 1, 0.65, Rgb(4, 5, 6), Style::default());
1328 grid.spinner(3.0, 3, 0.65, Rgb(1, 2, 3), Style::default());
1329 grid
1330 };
1331 let mut stepped = draw(0);
1332 for step in [1, 7, 0, 9] {
1333 stepped.turn_to(step);
1334 assert_eq!(stepped, draw(step), "step {step}");
1335 }
1336 assert_eq!(
1337 stepped.cell(12, 1).symbol,
1338 crate::spinner::STILL,
1339 "a dot stays"
1340 );
1341 let mut covered = draw(0);
1343 covered.put_str(8, 1, "menu", Style::default(), 30);
1344 covered.turn_to(4);
1345 assert_eq!(covered.row_text(1).trim_end(), "working menu●");
1346 let mut still = Grid::new(30, 4, Style::default());
1348 still.turn = None;
1349 still.spinner(9.0, 1, 0.65, Rgb(1, 2, 3), Style::default());
1350 let before = still.clone();
1351 still.turn_to(3);
1352 assert_eq!(still, before);
1353 }
1354}