-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathtext.rs
More file actions
317 lines (277 loc) · 9.64 KB
/
text.rs
File metadata and controls
317 lines (277 loc) · 9.64 KB
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
use std::ops::ControlFlow;
use anathema_geometry::{LocalPos, Size};
use anathema_value_resolver::{AttributeStorage, ValueKind};
use anathema_widgets::error::Result;
use anathema_widgets::layout::text::{ProcessResult, Segment, Strings};
use anathema_widgets::layout::{Constraints, LayoutCtx, PositionCtx};
use anathema_widgets::paint::{Glyphs, PaintCtx, SizePos};
use anathema_widgets::{LayoutForEach, PaintChildren, PositionChildren, Widget, WidgetId};
use crate::{LEFT, RIGHT};
pub(crate) const WRAP: &str = "wrap";
pub(crate) const TEXT_ALIGN: &str = "text_align";
/// Text alignment aligns the text inside its parent.
///
/// Given a border with a width of nine and text alignment set to [`TextAlignment::Right`]:
/// ```text
/// ┌───────┐
/// │I would│
/// │ like a│
/// │ lovely│
/// │ cup of│
/// │ tea│
/// │ please│
/// └───────┘
/// ```
///
/// The text will only align it self within the parent widget.
#[derive(Debug, PartialEq, Eq, Copy, Clone, Default)]
pub enum TextAlignment {
/// Align the to the left inside the parent
#[default]
Left,
/// Align the text in the centre of the parent
Centre,
/// Align the to the right inside the parent
Right,
}
impl TryFrom<&ValueKind<'_>> for TextAlignment {
type Error = ();
fn try_from(value: &ValueKind<'_>) -> Result<Self, Self::Error> {
let s = value.as_str().ok_or(())?;
match s {
LEFT => Ok(TextAlignment::Left),
RIGHT => Ok(TextAlignment::Right),
"centre" | "center" => Ok(TextAlignment::Centre),
_ => Err(()),
}
}
}
/// Text widget
/// ```ignore
/// Attributes:
/// * background
/// * foreground
/// * text-align
/// * wrap
/// ```
///
/// Note: Spans, unlike other widgets, does not require a widget id
///
/// A `Text` widget will be as wide as its text.
#[derive(Debug, Default)]
pub struct Text {
strings: Strings,
}
impl Widget for Text {
fn layout<'bp>(
&mut self,
mut children: LayoutForEach<'_, 'bp>,
constraints: Constraints,
id: WidgetId,
ctx: &mut LayoutCtx<'_, 'bp>,
) -> Result<Size> {
let attributes = ctx.attributes(id);
let wrap = attributes.get_as(WRAP).unwrap_or_default();
let size = constraints.max_size();
self.strings = Strings::new(size, wrap);
self.strings.set_style(id);
// Layout text
if let Some(text) = attributes.value() {
text.strings(|s| match self.strings.add_str(s) {
ProcessResult::Break => false,
ProcessResult::Continue => true,
});
}
// Layout text of all the sub-nodes
_ = children.each(ctx, |ctx, child, _| {
let Some(_span) = child.try_to_ref::<Span>() else {
return Ok(ControlFlow::Continue(()));
};
self.strings.set_style(child.id());
let attributes = ctx.attributes(child.id());
if let Some(text) = attributes.value() {
text.strings(|s| match self.strings.add_str(s) {
ProcessResult::Break => false,
ProcessResult::Continue => true,
});
Ok(ControlFlow::Continue(()))
} else {
Ok(ControlFlow::Break(()))
}
})?;
Ok(self.strings.finish())
}
fn paint<'bp>(
&mut self,
_: PaintChildren<'_, 'bp>,
id: WidgetId,
attribute_storage: &AttributeStorage<'bp>,
mut ctx: PaintCtx<'_, SizePos>,
) {
let lines = self.strings.lines();
let alignment = attribute_storage.get(id).get_as(TEXT_ALIGN).unwrap_or_default();
let mut pos = LocalPos::ZERO;
let mut style = attribute_storage.get(id);
for line in lines {
let x = match alignment {
TextAlignment::Left => 0,
TextAlignment::Centre => ctx.local_size.width / 2 - line.width / 2,
TextAlignment::Right => ctx.local_size.width - line.width,
};
pos.x = x;
for entry in line.entries {
match entry {
Segment::Str(s) => {
let glyphs = Glyphs::new(s);
if let Some(new_pos) = ctx.place_glyphs(glyphs, pos) {
// TODO:
// In the future there should probably be a way to
// provide both style and glyph at the same time.
for x in pos.x..new_pos.x {
ctx.set_attributes(style, (x, pos.y).into());
}
pos = new_pos;
}
}
Segment::SetStyle(attribute_id) => style = attribute_storage.get(attribute_id),
}
}
pos.y += 1;
pos.x = 0;
}
}
fn position<'bp>(&mut self, _: PositionChildren<'_, 'bp>, _: WidgetId, _: &AttributeStorage<'bp>, _: PositionCtx) {
// NOTE
// No positioning is done in here, it's all done when painting
}
}
#[derive(Default, Copy, Clone)]
pub struct Span;
impl Widget for Span {
fn layout<'bp>(
&mut self,
_: LayoutForEach<'_, 'bp>,
_: Constraints,
_: WidgetId,
_: &mut LayoutCtx<'_, 'bp>,
) -> Result<Size> {
// Everything is handled by the parent text
Ok(Size::ZERO)
}
fn position<'bp>(&mut self, _: PositionChildren<'_, 'bp>, _: WidgetId, _: &AttributeStorage<'bp>, _: PositionCtx) {
// Everything is handled by the parent text
// panic!("this should never be called");
}
}
#[cfg(test)]
mod test {
use crate::testing::TestRunner;
#[test]
fn word_wrap_excessive_space() {
let src = "text 'hello how are you'";
let expected = "
╔════════════════╗
║hello how ║
║are you ║
║ ║
║ ║
║ ║
║ ║
╚════════════════╝";
TestRunner::new(src, (16, 6)).instance().render_assert(expected);
}
#[test]
fn word_wrap() {
let src = "text 'hello how are you'";
let expected = r#"
╔════════════════╗
║hello how are ║
║you ║
║ ║
╚════════════════╝
"#;
TestRunner::new(src, (16, 3)).instance().render_assert(expected);
}
#[test]
fn break_word_wrap() {
let src = "text [wrap: 'break'] 'hello howareyoudoing'";
let expected = r#"
╔════════════════╗
║hello howareyoud║
║oing ║
║ ║
╚════════════════╝
"#;
TestRunner::new(src, (16, 3)).instance().render_assert(expected);
}
#[test]
fn char_wrap_layout_multiple_spans() {
let src = r#"
text 'one'
span 'two'
span ' averylongword'
span ' bunny'
"#;
let expected = r#"
╔═══════════════════╗
║onetwo ║
║averylongword bunny║
║ ║
╚═══════════════════╝
"#;
TestRunner::new(src, (19, 3)).instance().render_assert(expected);
}
#[test]
fn multi_line_with_span() {
let src = r#"
border [width: 5 + 2]
text 'one'
span 'two'
"#;
let expected = r#"
╔═════════╗
║┌─────┐ ║
║│onetw│ ║
║│o │ ║
║└─────┘ ║
╚═════════╝
"#;
TestRunner::new(src, (9, 4)).instance().render_assert(expected);
}
#[test]
fn right_alignment() {
let src = "text [text_align: 'right'] 'a one xxxxxxxxxxxxxxxxxx'";
let expected = r#"
╔══════════════════╗
║ a one ║
║xxxxxxxxxxxxxxxxxx║
║ ║
╚══════════════════╝
"#;
TestRunner::new(src, (18, 3)).instance().render_assert(expected);
}
#[test]
fn centre_alignment() {
let src = "text [text_align: 'centre'] 'a one xxxxxxxxxxxxxxxxxx'";
let expected = r#"
╔══════════════════╗
║ a one ║
║xxxxxxxxxxxxxxxxxx║
║ ║
╚══════════════════╝
"#;
TestRunner::new(src, (18, 3)).instance().render_assert(expected);
}
#[test]
fn line_break() {
let src = "text 'What have you'";
let expected = r#"
╔═════════╗
║What have║
║you ║
║ ║
╚═════════╝
"#;
TestRunner::new(src, (9, 3)).instance().render_assert(expected);
}
}