1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
use std::{borrow::Cow, convert::TryInto};
use euclid::Size2D;
use unicode_segmentation::UnicodeSegmentation;
use crate::{event::Event, unit::Cell, Printer, View as ViewTrait};
pub struct View<'a> {
inner: &'a str,
}
impl<'a> View<'a> {
pub fn new(s: &'a str) -> Self {
Self {
inner: s,
}
}
fn size_and_lines(
&self,
width_constraint: u16,
) -> (Size2D<u16, Cell>, Vec<Cow<'_, str>>) {
let lines = textwrap::wrap(&self.inner, width_constraint as usize);
let max_width = lines
.iter()
.map(|x| x.graphemes(true).count())
.max()
.unwrap_or(0)
.try_into()
.unwrap_or(0);
let rows = lines.iter().count().try_into().unwrap_or(0);
((max_width, rows).into(), lines)
}
}
pub fn new(s: &str) -> View<'_> {
View::new(s)
}
impl<T, M> ViewTrait<T, M> for View<'_>
where
M: 'static,
{
fn draw(&self, printer: &Printer, _focused: bool) {
let (size, lines) = self.size_and_lines(printer.size().width);
for (line, row) in lines.iter().zip(0..size.height) {
printer.print(&line, (0, row)).unwrap();
}
}
fn width(&self) -> Size2D<u16, Cell> {
let longest_word_len: u16 = self
.inner
.split_whitespace()
.map(|w| w.graphemes(true).count())
.max()
.unwrap_or(0)
.try_into()
.expect("u16 overflow");
self.size_and_lines(longest_word_len).0
}
fn height(&self) -> Size2D<u16, Cell> {
let longest_line_len = self
.inner
.lines()
.map(|l| l.graphemes(true).count())
.max()
.unwrap_or(0)
.try_into()
.expect("u16 overflow");
self.size_and_lines(longest_line_len).0
}
fn layout(&self, constraint: Size2D<u16, Cell>) -> Size2D<u16, Cell> {
self.size_and_lines(constraint.width).0
}
fn event(&mut self, _: &Event<T>, _: bool) -> Box<dyn Iterator<Item = M>> {
Box::new(std::iter::empty())
}
fn interactive(&self) -> bool {
false
}
}