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