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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
//! Pixel iterators used for text rendering.

pub(crate) mod cursor;
pub(crate) mod line;
pub(crate) mod line_iter;
pub(crate) mod space_config;

use crate::{
    parser::Parser,
    plugin::{PluginMarker as Plugin, ProcessingState},
    rendering::{
        cursor::Cursor,
        line::{LineRenderState, StyledLineRenderer},
    },
    style::TextBoxStyle,
    TextBox,
};
use az::SaturatingAs;
use embedded_graphics::{
    draw_target::{DrawTarget, DrawTargetExt},
    prelude::{Dimensions, Point, Size},
    primitives::Rectangle,
    text::renderer::{CharacterStyle, TextRenderer},
    Drawable,
};
use line_iter::LineEndType;

/// Text box properties.
///
/// This struct holds information about the text box.
#[derive(Clone)]
pub struct TextBoxProperties<'a, S> {
    /// The used text box style.
    pub box_style: &'a TextBoxStyle,

    /// The character style.
    pub char_style: &'a S,

    /// The height of the text.
    pub text_height: i32,

    /// The bounds of the text box.
    pub bounding_box: Rectangle,
}

impl<'a, F, M> Drawable for TextBox<'a, F, M>
where
    F: TextRenderer<Color = <F as CharacterStyle>::Color> + CharacterStyle,
    M: Plugin<'a, <F as TextRenderer>::Color> + Plugin<'a, <F as CharacterStyle>::Color>,
    <F as CharacterStyle>::Color: Default,
{
    type Color = <F as CharacterStyle>::Color;
    type Output = &'a str;

    #[inline]
    fn draw<D: DrawTarget<Color = Self::Color>>(
        &self,
        display: &mut D,
    ) -> Result<&'a str, D::Error> {
        let mut cursor = Cursor::new(
            self.bounds,
            self.character_style.line_height(),
            self.style.line_height,
            self.style.tab_size.into_pixels(&self.character_style),
        );

        let text_height = self
            .style
            .measure_text_height_impl(
                self.plugin.clone(),
                &self.character_style,
                self.text,
                cursor.line_width(),
            )
            .saturating_as::<i32>();

        let box_height = self.bounding_box().size.height.saturating_as::<i32>();

        self.style.vertical_alignment.apply_vertical_alignment(
            &mut cursor,
            text_height,
            box_height,
        );

        cursor.y += self.vertical_offset;

        let props = TextBoxProperties {
            box_style: &self.style,
            char_style: &self.character_style,
            text_height,
            bounding_box: self.bounding_box(),
        };

        self.plugin.on_start_render(&mut cursor, props);

        let mut state = LineRenderState {
            text_renderer: self.character_style.clone(),
            parser: Parser::parse(self.text),
            end_type: LineEndType::EndOfText,
            plugin: &self.plugin,
        };

        state.plugin.set_state(ProcessingState::Render);

        let mut anything_drawn = false;
        loop {
            state.plugin.new_line();

            let display_range = self
                .style
                .height_mode
                .calculate_displayed_row_range(&cursor);
            let display_range_start = display_range.start.saturating_as::<i32>();
            let display_range_count = display_range.count() as u32;
            let display_size = Size::new(cursor.line_width(), display_range_count);

            let line_start = cursor.line_start();

            // FIXME: cropping isn't necessary for whole lines, but make sure not to blow up the
            // binary size as well. We could also use a different way to consume invisible text.
            let mut display = display.clipped(&Rectangle::new(
                line_start + Point::new(0, display_range_start),
                display_size,
            ));
            if display_range_count == 0 {
                // Display range can be empty if we are above, or below the visible text section
                if anything_drawn {
                    // We are below, so we won't be drawing anything else
                    let remaining_bytes = state.parser.as_str().len();
                    let consumed_bytes = self.text.len() - remaining_bytes;

                    state.plugin.post_render(
                        &mut display,
                        &self.character_style,
                        None,
                        Rectangle::new(line_start, Size::new(0, cursor.line_height())),
                    )?;
                    state.plugin.on_rendering_finished();
                    return Ok(self.text.get(consumed_bytes..).unwrap());
                }
            } else {
                anything_drawn = true;
            }

            StyledLineRenderer {
                cursor: cursor.line(),
                state: &mut state,
                style: &self.style,
            }
            .draw(&mut display)?;

            match state.end_type {
                LineEndType::EndOfText => {
                    state.plugin.on_rendering_finished();
                    break;
                }
                LineEndType::CarriageReturn => {}
                _ => {
                    cursor.new_line();

                    if state.end_type == LineEndType::NewLine {
                        cursor.y += self.style.paragraph_spacing.saturating_as::<i32>();
                    }
                }
            }
        }

        Ok("")
    }
}

#[cfg(test)]
pub mod test {
    use embedded_graphics::{
        mock_display::MockDisplay,
        mono_font::{
            ascii::{FONT_6X10, FONT_6X9},
            MonoTextStyleBuilder,
        },
        pixelcolor::BinaryColor,
        prelude::*,
        primitives::Rectangle,
    };

    use crate::{
        alignment::HorizontalAlignment,
        style::{HeightMode, TextBoxStyle, TextBoxStyleBuilder, VerticalOverdraw},
        utils::test::size_for,
        TextBox,
    };

    #[track_caller]
    pub fn assert_rendered(
        alignment: HorizontalAlignment,
        text: &str,
        size: Size,
        pattern: &[&str],
    ) {
        assert_styled_rendered(
            TextBoxStyleBuilder::new().alignment(alignment).build(),
            text,
            size,
            pattern,
        );
    }

    #[track_caller]
    pub fn assert_styled_rendered(style: TextBoxStyle, text: &str, size: Size, pattern: &[&str]) {
        let mut display = MockDisplay::new();

        let character_style = MonoTextStyleBuilder::new()
            .font(&FONT_6X9)
            .text_color(BinaryColor::On)
            .background_color(BinaryColor::Off)
            .build();

        TextBox::with_textbox_style(
            text,
            Rectangle::new(Point::zero(), size),
            character_style,
            style,
        )
        .draw(&mut display)
        .unwrap();

        display.assert_pattern(pattern);
    }

    #[test]
    fn nbsp_doesnt_break() {
        assert_rendered(
            HorizontalAlignment::Left,
            "a b c\u{a0}d e f",
            size_for(&FONT_6X9, 5, 3),
            &[
                "..................            ",
                ".............#....            ",
                ".............#....            ",
                "..###........###..            ",
                ".#..#........#..#.            ",
                ".#..#........#..#.            ",
                "..###........###..            ",
                "..................            ",
                "..................            ",
                "..............................",
                "................#.............",
                "................#.............",
                "..###.........###.........##..",
                ".#...........#..#........#.##.",
                ".#...........#..#........##...",
                "..###.........###.........###.",
                "..............................",
                "..............................",
                "......                        ",
                "...#..                        ",
                "..#.#.                        ",
                "..#...                        ",
                ".###..                        ",
                "..#...                        ",
                "..#...                        ",
                "......                        ",
                "......                        ",
            ],
        );
    }

    #[test]
    fn vertical_offset() {
        let mut display = MockDisplay::new();

        let character_style = MonoTextStyleBuilder::new()
            .font(&FONT_6X9)
            .text_color(BinaryColor::On)
            .background_color(BinaryColor::Off)
            .build();

        TextBox::new(
            "hello",
            Rectangle::new(Point::zero(), size_for(&FONT_6X9, 5, 3)),
            character_style,
        )
        .set_vertical_offset(6)
        .draw(&mut display)
        .unwrap();

        display.assert_pattern(&[
            "                              ",
            "                              ",
            "                              ",
            "                              ",
            "                              ",
            "                              ",
            "..............................",
            ".#...........##....##.........",
            ".#............#.....#.........",
            ".###....##....#.....#.....##..",
            ".#..#..#.##...#.....#....#..#.",
            ".#..#..##.....#.....#....#..#.",
            ".#..#...###..###...###....##..",
            "..............................",
            "..............................",
        ]);
    }

    #[test]
    fn vertical_offset_negative() {
        let mut display = MockDisplay::new();

        let character_style = MonoTextStyleBuilder::new()
            .font(&FONT_6X9)
            .text_color(BinaryColor::On)
            .background_color(BinaryColor::Off)
            .build();

        TextBox::with_textbox_style(
            "hello",
            Rectangle::new(Point::zero(), size_for(&FONT_6X9, 5, 3)),
            character_style,
            TextBoxStyleBuilder::new()
                .height_mode(HeightMode::Exact(VerticalOverdraw::Hidden))
                .build(),
        )
        .set_vertical_offset(-4)
        .draw(&mut display)
        .unwrap();

        display.assert_pattern(&[
            ".#..#..#.##...#.....#....#..#.",
            ".#..#..##.....#.....#....#..#.",
            ".#..#...###..###...###....##..",
            "..............................",
            "..............................",
        ]);
    }

    #[test]
    fn rendering_not_stopped_prematurely() {
        let mut display = MockDisplay::new();

        let character_style = MonoTextStyleBuilder::new()
            .font(&FONT_6X10)
            .text_color(BinaryColor::On)
            .background_color(BinaryColor::Off)
            .build();

        TextBox::with_textbox_style(
            "hello\nbuggy\nworld",
            Rectangle::new(Point::zero(), size_for(&FONT_6X10, 5, 3)),
            character_style,
            TextBoxStyleBuilder::new()
                .height_mode(HeightMode::Exact(VerticalOverdraw::Hidden))
                .build(),
        )
        .set_vertical_offset(-20)
        .draw(&mut display)
        .unwrap();

        display.assert_pattern(&[
            "..............................",
            "...................##.......#.",
            "....................#.......#.",
            "#...#..###..#.##....#....##.#.",
            "#...#.#...#.##..#...#...#..##.",
            "#.#.#.#...#.#.......#...#...#.",
            "#.#.#.#...#.#.......#...#..##.",
            ".#.#...###..#......###...##.#.",
            "..............................",
            "..............................",
        ]);
    }

    #[test]
    fn space_wrapping_issue() {
        let mut display = MockDisplay::new();

        let character_style = MonoTextStyleBuilder::new()
            .font(&FONT_6X10)
            .text_color(BinaryColor::On)
            .background_color(BinaryColor::Off)
            .build();

        TextBox::with_textbox_style(
            "Hello,      s",
            Rectangle::new(Point::zero(), size_for(&FONT_6X10, 10, 2)),
            character_style,
            TextBoxStyleBuilder::new()
                .height_mode(HeightMode::Exact(VerticalOverdraw::Hidden))
                .trailing_spaces(true)
                .build(),
        )
        .draw(&mut display)
        .unwrap();

        display.assert_pattern(&[
            "............................................................",
            "#...#........##....##.......................................",
            "#...#.........#.....#.......................................",
            "#...#..###....#.....#....###................................",
            "#####.#...#...#.....#...#...#...............................",
            "#...#.#####...#.....#...#...#...............................",
            "#...#.#.......#.....#...#...#...##..........................",
            "#...#..###...###...###...###....#...........................",
            "...............................#............................",
            "............................................................",
            "............                                                ",
            "............                                                ",
            "............                                                ",
            ".......###..                                                ",
            "......#.....                                                ",
            ".......###..                                                ",
            "..........#.                                                ",
            "......####..                                                ",
            "............                                                ",
            "............                                                ",
        ]);
    }
}