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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
//! Line rendering
use crate::{
    parser::{Parser, Token},
    rendering::{
        character::StyledCharacterIterator, cursor::Cursor, whitespace::EmptySpaceIterator,
    },
    utils::font_ext::FontExt,
};
use core::str::Chars;
use embedded_graphics::{prelude::*, style::TextStyle};

/// Internal state used to render a line
#[derive(Debug)]
pub enum LineState<'a, C, F>
where
    C: PixelColor,
    F: Font + Copy,
{
    /// Fetch next token
    FetchNext,

    /// Decide what to do next
    ProcessToken(Token<'a>),

    /// Render a word
    Word(Chars<'a>, StyledCharacterIterator<C, F>),

    /// Render whitespace
    Whitespace(u32, EmptySpaceIterator<C, F>),

    /// Signal that the renderer has finished, store the token that was consumed but not rendered
    Done(Option<Token<'a>>),
}

/// Retrieves size of space characters
pub trait SpaceConfig: Copy {
    /// Render spaces at the start of a line
    fn starting_spaces(&self) -> bool;

    /// Render spaces at the end of a line
    fn ending_spaces(&self) -> bool;

    /// Look at the size of next n spaces, without advancing
    fn peek_next_width(&self, n: u32) -> u32;

    /// Get the width of the next space and advance
    fn next_space_width(&mut self) -> u32;
}

/// Contains the fixed width of a space character
#[derive(Copy, Clone, Debug)]
pub struct UniformSpaceConfig {
    /// Space width
    pub space_width: u32,

    /// Render spaces at the start of a line
    pub starting_spaces: bool,

    /// Render spaces at the end of a line
    pub ending_spaces: bool,
}

impl SpaceConfig for UniformSpaceConfig {
    #[inline]
    fn starting_spaces(&self) -> bool {
        self.starting_spaces
    }

    #[inline]
    fn ending_spaces(&self) -> bool {
        self.ending_spaces
    }

    #[inline]
    fn peek_next_width(&self, n: u32) -> u32 {
        n * self.space_width
    }

    #[inline]
    fn next_space_width(&mut self) -> u32 {
        self.space_width
    }
}

/// Pixel iterator to render a styled character
#[derive(Debug)]
pub struct StyledLineIterator<'a, C, F, SP: SpaceConfig>
where
    C: PixelColor,
    F: Font + Copy,
{
    /// Position information
    pub cursor: Cursor<F>,
    /// The text to draw.
    pub parser: Parser<'a>,
    current_token: LineState<'a, C, F>,
    config: SP,
    style: TextStyle<C, F>,
    first_word: bool,
}

impl<'a, C, F, SP> StyledLineIterator<'a, C, F, SP>
where
    C: PixelColor,
    F: Font + Copy,
    SP: SpaceConfig,
{
    /// Creates a new pixel iterator to draw the given character.
    #[inline]
    #[must_use]
    pub fn new(
        parser: Parser<'a>,
        cursor: Cursor<F>,
        config: SP,
        style: TextStyle<C, F>,
        carried_token: Option<Token<'a>>,
    ) -> Self {
        Self {
            parser,
            current_token: carried_token
                .map(LineState::ProcessToken)
                .unwrap_or(LineState::FetchNext),
            config,
            cursor,
            style,
            first_word: true,
        }
    }

    /// When finished, this method returns the last partially processed token, or
    /// None if everything was rendered.
    #[must_use]
    #[inline]
    pub fn remaining_token(&self) -> Option<Token<'a>> {
        match self.current_token {
            LineState::Done(ref t) => t.clone(),
            _ => None,
        }
    }

    fn fits_in_line(&self, width: u32) -> bool {
        self.cursor.fits_in_line(width)
    }
}

impl<C, F, SP> Iterator for StyledLineIterator<'_, C, F, SP>
where
    C: PixelColor,
    F: Font + Copy,
    SP: SpaceConfig,
{
    type Item = Pixel<C>;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        loop {
            match self.current_token {
                LineState::FetchNext => {
                    self.current_token = if let Some(token) = self.parser.next() {
                        LineState::ProcessToken(token)
                    } else {
                        // we're done
                        LineState::Done(None)
                    }
                }

                LineState::ProcessToken(ref token) => {
                    // No token being processed, get next one
                    match token.clone() {
                        Token::Whitespace(n) => {
                            let render_whitespace = if self.first_word {
                                self.config.starting_spaces()
                            } else if self.config.ending_spaces() {
                                true
                            } else if let Some(Token::Word(w)) = self.parser.peek() {
                                // Check if space + w fits in line, otherwise it's up to config
                                let space_width = self.config.peek_next_width(n);
                                let word_width = F::str_width(w);

                                self.fits_in_line(space_width + word_width)
                            } else {
                                false
                            };

                            if render_whitespace {
                                // take as many spaces as possible and save the rest in state

                                let mut space_width = 0;
                                let mut spaces = n;

                                while spaces > 0
                                    && self
                                        .fits_in_line(space_width + self.config.peek_next_width(1))
                                {
                                    spaces -= 1;
                                    space_width += self.config.next_space_width();
                                }

                                self.current_token = if space_width > 0 {
                                    let pos = self.cursor.position;
                                    self.cursor.advance(space_width);
                                    LineState::Whitespace(
                                        spaces,
                                        EmptySpaceIterator::new(space_width, pos, self.style),
                                    )
                                } else if spaces > 1 {
                                    // there are spaces to render but none fit the line
                                    // eat one as a newline and stop
                                    LineState::Done(Some(Token::Whitespace(
                                        spaces.saturating_sub(1),
                                    )))
                                } else {
                                    LineState::Done(None)
                                }
                            } else {
                                // nothing, process next token
                                self.current_token = LineState::FetchNext;
                            }
                        }

                        Token::Word(w) => {
                            if self.first_word {
                                self.first_word = false;
                            } else if !self.fits_in_line(F::str_width(w)) {
                                self.current_token = LineState::Done(Some(Token::Word(w)));
                                break None;
                            }

                            // - always draw first word, Word state should handle wrapping
                            let mut chars = w.chars();

                            // unwrap is safe here, parser doesn't emit empty words
                            let c = chars.next().unwrap();

                            let pos = self.cursor.position;
                            self.cursor.advance(F::total_char_width(c));

                            self.current_token = LineState::Word(
                                chars,
                                StyledCharacterIterator::new(c, pos, self.style),
                            );
                        }

                        Token::NewLine => {
                            // we're done
                            self.current_token = LineState::Done(None);
                        }
                    }
                }

                LineState::Whitespace(ref n, ref mut iter) => {
                    if let pixel @ Some(_) = iter.next() {
                        break pixel;
                    }

                    self.current_token = if *n == 0 {
                        LineState::FetchNext
                    } else {
                        // n > 0 only if not every space was rendered
                        LineState::Done(Some(Token::Whitespace(*n)))
                    }
                }

                LineState::Word(ref chars, ref mut iter) => {
                    if let pixel @ Some(_) = iter.next() {
                        break pixel;
                    }

                    let mut lookahead = chars.clone();
                    self.current_token = if let Some(c) = lookahead.next() {
                        // character done, move to the next one
                        let char_width = F::total_char_width(c);

                        if self.fits_in_line(char_width) {
                            let pos = self.cursor.position;
                            self.cursor.advance(char_width);
                            LineState::Word(
                                lookahead,
                                StyledCharacterIterator::new(c, pos, self.style),
                            )
                        } else {
                            // word wrapping, this line is done
                            LineState::Done(Some(Token::Word(chars.as_str())))
                        }
                    } else {
                        // process token
                        LineState::FetchNext
                    }
                }

                LineState::Done(_) => {
                    break None;
                }
            }
        }
    }
}

#[cfg(test)]
mod test {

    use crate::parser::{Parser, Token};
    use crate::rendering::{
        cursor::Cursor,
        line::{StyledLineIterator, UniformSpaceConfig},
    };
    use embedded_graphics::{
        fonts::Font6x8, mock_display::MockDisplay, pixelcolor::BinaryColor, prelude::*,
        primitives::Rectangle, style::TextStyleBuilder,
    };

    #[test]
    fn simple_render() {
        let parser = Parser::parse(" Some sample text");
        let config = UniformSpaceConfig {
            starting_spaces: true,
            ending_spaces: true,
            space_width: 6,
        };
        let style = TextStyleBuilder::new(Font6x8)
            .text_color(BinaryColor::On)
            .background_color(BinaryColor::Off)
            .build();

        let cursor = Cursor::new(Rectangle::new(Point::zero(), Point::new(6 * 7 - 1, 8)));
        let mut iter = StyledLineIterator::new(parser, cursor, config, style, None);
        let mut display = MockDisplay::new();

        iter.draw(&mut display).unwrap();

        assert_eq!(
            display,
            MockDisplay::from_pattern(&[
                ".......###..........................",
                "......#...#.........................",
                "......#......###..##.#...###........",
                ".......###..#...#.#.#.#.#...#.......",
                "..........#.#...#.#...#.#####.......",
                "......#...#.#...#.#...#.#...........",
                ".......###...###..#...#..###........",
                "....................................",
            ])
        );
        assert_eq!(Some(Token::Word("sample")), iter.remaining_token());
    }

    #[test]
    fn simple_render_first_word_not_wrapped() {
        let parser = Parser::parse(" Some sample text");
        let config = UniformSpaceConfig {
            starting_spaces: true,
            ending_spaces: true,
            space_width: 6,
        };
        let style = TextStyleBuilder::new(Font6x8)
            .text_color(BinaryColor::On)
            .background_color(BinaryColor::Off)
            .build();

        let cursor = Cursor::new(Rectangle::new(Point::zero(), Point::new(6 * 3 - 1, 8)));
        let mut iter = StyledLineIterator::new(parser, cursor, config, style, None);
        let mut display = MockDisplay::new();

        iter.draw(&mut display).unwrap();

        assert_eq!(
            display,
            MockDisplay::from_pattern(&[
                ".......###........",
                "......#...#.......",
                "......#......###..",
                ".......###..#...#.",
                "..........#.#...#.",
                "......#...#.#...#.",
                ".......###...###..",
                "..................",
            ])
        );
        assert_eq!(Some(Token::Word("me")), iter.remaining_token());
    }

    #[test]
    fn newline_stops_render() {
        let parser = Parser::parse("Some \nsample text");
        let config = UniformSpaceConfig {
            starting_spaces: true,
            ending_spaces: true,
            space_width: 6,
        };
        let style = TextStyleBuilder::new(Font6x8)
            .text_color(BinaryColor::On)
            .background_color(BinaryColor::Off)
            .build();

        let cursor = Cursor::new(Rectangle::new(Point::zero(), Point::new(6 * 7 - 1, 8)));
        let mut iter = StyledLineIterator::new(parser, cursor, config, style, None);
        let mut display = MockDisplay::new();

        iter.draw(&mut display).unwrap();

        assert_eq!(
            display,
            MockDisplay::from_pattern(&[
                ".###..........................",
                "#...#.........................",
                "#......###..##.#...###........",
                ".###..#...#.#.#.#.#...#.......",
                "....#.#...#.#...#.#####.......",
                "#...#.#...#.#...#.#...........",
                ".###...###..#...#..###........",
                "..............................",
            ])
        );
    }

    #[test]
    fn first_spaces_not_rendered() {
        let parser = Parser::parse("  Some sample text");
        let config = UniformSpaceConfig {
            starting_spaces: true,
            ending_spaces: true,
            space_width: 6,
        };
        let style = TextStyleBuilder::new(Font6x8)
            .text_color(BinaryColor::On)
            .background_color(BinaryColor::Off)
            .build();

        let cursor = Cursor::new(Rectangle::new(Point::zero(), Point::new(6 * 3 - 1, 8)));
        let mut iter = StyledLineIterator::new(parser, cursor, config, style, None);
        let mut display = MockDisplay::new();

        iter.draw(&mut display).unwrap();

        assert_eq!(
            display,
            MockDisplay::from_pattern(&[
                ".###..............",
                "#...#.............",
                "#......###..##.#..",
                ".###..#...#.#.#.#.",
                "....#.#...#.#...#.",
                "#...#.#...#.#...#.",
                ".###...###..#...#.",
                "..................",
            ])
        );
    }

    #[test]
    fn last_spaces() {
        let style = TextStyleBuilder::new(Font6x8)
            .text_color(BinaryColor::On)
            .background_color(BinaryColor::Off)
            .build();

        let parser = Parser::parse("Some  sample text");
        let config = UniformSpaceConfig {
            starting_spaces: true,
            ending_spaces: true,
            space_width: 6,
        };

        let cursor = Cursor::new(Rectangle::new(Point::zero(), Point::new(6 * 7 - 1, 8)));
        let mut iter = StyledLineIterator::new(parser, cursor, config, style, None);
        let mut display = MockDisplay::new();

        iter.draw(&mut display).unwrap();

        assert_eq!(
            display,
            MockDisplay::from_pattern(&[
                ".###....................",
                "#...#...................",
                "#......###..##.#...###..",
                ".###..#...#.#.#.#.#...#.",
                "....#.#...#.#...#.#####.",
                "#...#.#...#.#...#.#.....",
                ".###...###..#...#..###..",
                "........................",
            ])
        );

        let parser = Parser::parse("Some  sample text");
        let config = UniformSpaceConfig {
            starting_spaces: true,
            ending_spaces: true,
            space_width: 6,
        };

        let cursor = Cursor::new(Rectangle::new(Point::zero(), Point::new(6 * 7 - 1, 8)));
        let mut iter = StyledLineIterator::new(parser, cursor, config, style, None);
        let mut display = MockDisplay::new();

        iter.draw(&mut display).unwrap();

        assert_eq!(
            display,
            MockDisplay::from_pattern(&[
                ".###................................",
                "#...#...............................",
                "#......###..##.#...###..............",
                ".###..#...#.#.#.#.#...#.............",
                "....#.#...#.#...#.#####.............",
                "#...#.#...#.#...#.#.................",
                ".###...###..#...#..###..............",
                "....................................",
            ])
        );
    }

    #[test]
    fn carried_over_spaces() {
        let style = TextStyleBuilder::new(Font6x8)
            .text_color(BinaryColor::On)
            .background_color(BinaryColor::Off)
            .build();

        let parser = Parser::parse("Some  sample text");
        let config = UniformSpaceConfig {
            starting_spaces: true,
            ending_spaces: true,
            space_width: 6,
        };

        let cursor = Cursor::new(Rectangle::new(Point::zero(), Point::new(6 * 5 - 1, 8)));
        let mut iter = StyledLineIterator::new(parser, cursor, config, style, None);
        let mut display = MockDisplay::new();

        iter.draw(&mut display).unwrap();

        assert_eq!(Some(Token::Whitespace(1)), iter.remaining_token());

        let mut iter = StyledLineIterator::new(
            iter.parser.clone(),
            cursor,
            config,
            style,
            iter.remaining_token(),
        );
        let mut display = MockDisplay::new();

        iter.draw(&mut display).unwrap();

        assert_eq!(
            display,
            MockDisplay::from_pattern(&[
                "..............................",
                "..............................",
                ".......####..###..##.#..####..",
                "......#.........#.#.#.#.#...#.",
                ".......###...####.#...#.#...#.",
                "..........#.#...#.#...#.####..",
                "......####...####.#...#.#.....",
                "........................#.....",
            ])
        );
    }
}