logo
  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
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
use crate::{
    draw_target::DrawTarget,
    geometry::{Dimensions, Point, Size},
    primitives::Rectangle,
    text::{
        renderer::{TextMetrics, TextRenderer},
        Alignment, Baseline, TextStyle,
    },
    transform::Transform,
    Drawable,
};
use az::SaturatingAs;

use super::TextStyleBuilder;
/// Text drawable.
///
/// A text drawable can be used to draw text to a draw target.
///
/// See the [module-level documentation] for more information about text drawables and examples.
///
/// [module-level documentation]: index.html
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
pub struct Text<'a, S> {
    /// The string.
    pub text: &'a str,

    /// The position.
    pub position: Point,

    /// The character style.
    pub character_style: S,

    /// The text style.
    pub text_style: TextStyle,
}

impl<'a, S> Text<'a, S> {
    /// Creates a text drawable with the default text style.
    pub const fn new(text: &'a str, position: Point, character_style: S) -> Self {
        Self {
            text,
            position,
            character_style,
            text_style: TextStyleBuilder::new().build(),
        }
    }

    /// Creates a text drawable with the given text style.
    pub const fn with_text_style(
        text: &'a str,
        position: Point,
        character_style: S,
        text_style: TextStyle,
    ) -> Self {
        Self {
            text,
            position,
            character_style,
            text_style,
        }
    }

    /// Creates a text drawable with the given baseline.
    pub const fn with_baseline(
        text: &'a str,
        position: Point,
        character_style: S,
        baseline: Baseline,
    ) -> Self {
        Self {
            text,
            position,
            character_style,
            text_style: TextStyle::with_baseline(baseline),
        }
    }

    /// Creates a text drawable with the given alignment.
    pub const fn with_alignment(
        text: &'a str,
        position: Point,
        character_style: S,
        alignment: Alignment,
    ) -> Self {
        Self {
            text,
            position,
            character_style,
            text_style: TextStyle::with_alignment(alignment),
        }
    }
}

impl<S: Clone> Transform for Text<'_, S> {
    fn translate(&self, by: Point) -> Self {
        Self {
            position: self.position + by,
            ..self.clone()
        }
    }

    fn translate_mut(&mut self, by: Point) -> &mut Self {
        self.position += by;

        self
    }
}

impl<S: TextRenderer> Text<'_, S> {
    fn lines(&self) -> impl Iterator<Item = (&str, Point)> {
        let mut position = self.position;

        self.text.lines().map(move |line| {
            let p = match self.text_style.alignment {
                Alignment::Left => position,
                Alignment::Right => {
                    let metrics = self.character_style.measure_string(
                        line,
                        Point::zero(),
                        self.text_style.baseline,
                    );
                    position - (metrics.next_position - Point::new(1, 0))
                }
                Alignment::Center => {
                    let metrics = self.character_style.measure_string(
                        line,
                        Point::zero(),
                        self.text_style.baseline,
                    );
                    position - (metrics.next_position - Point::new(1, 0)) / 2
                }
            };

            position.y += self
                .text_style
                .line_height
                .to_absolute(self.character_style.line_height())
                .saturating_as::<i32>();

            (line, p)
        })
    }
}

impl<S: TextRenderer> Drawable for Text<'_, S> {
    type Color = S::Color;
    type Output = Point;

    fn draw<D>(&self, target: &mut D) -> Result<Point, D::Error>
    where
        D: DrawTarget<Color = Self::Color>,
    {
        let mut next_position = self.position;

        for (line, position) in self.lines() {
            next_position = self.character_style.draw_string(
                line,
                position,
                self.text_style.baseline,
                target,
            )?;
        }

        Ok(next_position)
    }
}

fn update_min_max(min_max: &mut Option<(Point, Point)>, metrics: &TextMetrics) {
    if let Some(bottom_right) = metrics.bounding_box.bottom_right() {
        if let Some((min, max)) = min_max {
            min.x = min.x.min(metrics.bounding_box.top_left.x);
            min.y = min.y.min(metrics.bounding_box.top_left.y);
            max.x = max.x.max(bottom_right.x);
            max.y = max.y.max(bottom_right.y);
        } else {
            *min_max = Some((metrics.bounding_box.top_left, bottom_right));
        }
    }
}

impl<S: TextRenderer> Dimensions for Text<'_, S> {
    fn bounding_box(&self) -> Rectangle {
        let mut min_max: Option<(Point, Point)> = None;

        for (line, position) in self.lines() {
            let metrics =
                self.character_style
                    .measure_string(line, position, self.text_style.baseline);
            update_min_max(&mut min_max, &metrics);
        }

        if let Some((min, max)) = min_max {
            Rectangle::with_corners(min, max)
        } else {
            Rectangle::new(self.position, Size::zero())
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        geometry::Size,
        mock_display::MockDisplay,
        mono_font::{
            ascii::{FONT_6X13, FONT_6X9},
            tests::assert_text_from_pattern,
            MonoTextStyle, MonoTextStyleBuilder,
        },
        pixelcolor::BinaryColor,
        primitives::{Primitive, PrimitiveStyle},
        text::{Alignment, Baseline, LineHeight, TextStyleBuilder},
    };

    const HELLO_WORLD: &'static str = "Hello World!";

    #[test]
    fn constructor() {
        let character_style = MonoTextStyle::new(&FONT_6X9, BinaryColor::On);

        let text = Text::new("Hello e-g", Point::new(10, 11), character_style);

        assert_eq!(
            text,
            Text {
                text: "Hello e-g",
                position: Point::new(10, 11),
                character_style,
                text_style: TextStyle::default(),
            }
        );
    }

    #[test]
    fn multiline() {
        assert_text_from_pattern(
            "AB\nC",
            &FONT_6X9,
            &[
                "            ",
                "  #   ####  ",
                " # #  #   # ",
                "#   # ####  ",
                "##### #   # ",
                "#   # #   # ",
                "#   # ####  ",
                "            ",
                "            ",
                "            ",
                "  ##        ",
                " #  #       ",
                " #          ",
                " #          ",
                " #  #       ",
                "  ##        ",
            ],
        );
    }

    #[test]
    fn multiline_empty_line() {
        assert_text_from_pattern(
            "A\n\nBC",
            &FONT_6X9,
            &[
                "            ",
                "  #         ",
                " # #        ",
                "#   #       ",
                "#####       ",
                "#   #       ",
                "#   #       ",
                "            ",
                "            ",
                "            ",
                "            ",
                "            ",
                "            ",
                "            ",
                "            ",
                "            ",
                "            ",
                "            ",
                "            ",
                "####    ##  ",
                "#   #  #  # ",
                "####   #    ",
                "#   #  #    ",
                "#   #  #  # ",
                "####    ##  ",
                "            ",
            ],
        );
    }

    #[test]
    fn multiline_dimensions() {
        let character_style = MonoTextStyleBuilder::new()
            .font(&FONT_6X9)
            .text_color(BinaryColor::On)
            .build();

        let text = Text::with_baseline("AB\nC", Point::zero(), character_style, Baseline::Top);

        assert_eq!(
            text.bounding_box(),
            Rectangle::new(Point::zero(), Size::new(2 * 6, 2 * 9))
        );
    }

    #[test]
    fn position_and_translate() {
        let style = MonoTextStyle::new(&FONT_6X9, BinaryColor::On);

        let hello = Text::new(HELLO_WORLD, Point::zero(), style);

        let hello_translated = hello.translate(Point::new(5, -20));
        assert_eq!(
            hello.bounding_box().size,
            hello_translated.bounding_box().size
        );

        let mut hello_with_point = Text::new(HELLO_WORLD, Point::new(5, -20), style);
        assert_eq!(hello_translated, hello_with_point);

        hello_with_point.translate_mut(Point::new(-5, 20));
        assert_eq!(hello, hello_with_point);
    }

    #[test]
    fn inverted_text() {
        let mut display_inverse = MockDisplay::new();
        let style_inverse = MonoTextStyleBuilder::new()
            .font(&FONT_6X9)
            .text_color(BinaryColor::Off)
            .background_color(BinaryColor::On)
            .build();
        Text::new("Mm", Point::new(0, 7), style_inverse)
            .draw(&mut display_inverse)
            .unwrap();

        let mut display_normal = MockDisplay::new();
        let style_normal = MonoTextStyleBuilder::new()
            .font(&FONT_6X9)
            .text_color(BinaryColor::On)
            .background_color(BinaryColor::Off)
            .build();
        Text::new("Mm", Point::new(0, 7), style_normal)
            .draw(&mut display_normal)
            .unwrap();

        display_inverse.assert_eq(&display_normal.map(|c| c.invert()));
    }

    #[test]
    fn no_fill_does_not_hang() {
        let mut display = MockDisplay::new();
        Text::new(
            " ",
            Point::zero(),
            MonoTextStyle::new(&FONT_6X9, BinaryColor::On),
        )
        .draw(&mut display)
        .unwrap();

        display.assert_eq(&MockDisplay::new());
    }

    #[test]
    fn transparent_text_color_does_not_overwrite_background() {
        let character_style = MonoTextStyleBuilder::new()
            .font(&FONT_6X9)
            .background_color(BinaryColor::On)
            .build();

        let mut display = MockDisplay::new();
        display.set_allow_overdraw(true);

        // Draw a background for the first character
        Rectangle::new(Point::zero(), Size::new(6, 8))
            .into_styled(PrimitiveStyle::with_fill(BinaryColor::Off))
            .draw(&mut display)
            .unwrap();

        Text::with_baseline("AA", Point::zero(), character_style, Baseline::Top)
            .draw(&mut display)
            .unwrap();

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

    #[test]
    #[ignore]
    fn transparent_text_has_zero_size_but_retains_position() {
        let style = MonoTextStyleBuilder::<BinaryColor>::new()
            .font(&FONT_6X9)
            .build();

        let styled = Text::new(" A", Point::new(7, 11), style);

        assert_eq!(
            styled.bounding_box(),
            Rectangle::new(Point::new(7, 11), Size::zero()),
            "Transparent text is expected to have a zero sized bounding box with the top left corner at the text position",
        );
    }

    #[test]
    fn alignment_left() {
        let character_style = MonoTextStyleBuilder::new()
            .font(&FONT_6X9)
            .text_color(BinaryColor::On)
            .build();

        let text_style = TextStyleBuilder::new()
            .alignment(Alignment::Left)
            .baseline(Baseline::Top)
            .build();

        let mut display = MockDisplay::new();
        Text::with_text_style("A\nBC", Point::new(0, 0), character_style, text_style)
            .draw(&mut display)
            .unwrap();

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

    #[test]
    fn alignment_center() {
        let character_style = MonoTextStyleBuilder::new()
            .font(&FONT_6X9)
            .text_color(BinaryColor::On)
            .build();

        let text_style = TextStyleBuilder::new()
            .alignment(Alignment::Center)
            .baseline(Baseline::Top)
            .build();

        let mut display = MockDisplay::new();
        Text::with_text_style("A\nBC", Point::new(5, 0), character_style, text_style)
            .draw(&mut display)
            .unwrap();

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

    #[test]
    fn horizontal_alignment_right() {
        let character_style = MonoTextStyleBuilder::new()
            .font(&FONT_6X9)
            .text_color(BinaryColor::On)
            .build();

        let text_style = TextStyleBuilder::new()
            .alignment(Alignment::Right)
            .baseline(Baseline::Top)
            .build();

        let mut display = MockDisplay::new();
        Text::with_text_style("A\nBC", Point::new(11, 0), character_style, text_style)
            .draw(&mut display)
            .unwrap();

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

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

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

        Text::with_baseline("t", Point::new(0, 8), character_style, Baseline::Top)
            .draw(&mut display)
            .unwrap();
        Text::with_baseline("m", Point::new(6, 8), character_style, Baseline::Middle)
            .draw(&mut display)
            .unwrap();
        Text::with_baseline("b", Point::new(12, 8), character_style, Baseline::Bottom)
            .draw(&mut display)
            .unwrap();
        Text::with_baseline(
            "B",
            Point::new(18, 8),
            character_style,
            Baseline::Alphabetic,
        )
        .draw(&mut display)
        .unwrap();

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

    #[test]
    fn bounding_box() {
        for &baseline in &[
            Baseline::Top,
            Baseline::Middle,
            Baseline::Bottom,
            Baseline::Alphabetic,
        ] {
            for &alignment in &[Alignment::Left, Alignment::Center, Alignment::Right] {
                let character_style = MonoTextStyleBuilder::new()
                    .font(&FONT_6X9)
                    .text_color(BinaryColor::On)
                    .background_color(BinaryColor::Off)
                    .build();

                let text_style = TextStyleBuilder::new()
                    .alignment(alignment)
                    .baseline(baseline)
                    .build();

                let text = Text::with_text_style(
                    "1\n23",
                    Point::new_equal(20),
                    character_style,
                    text_style,
                );

                let mut display = MockDisplay::new();
                text.draw(&mut display).unwrap();

                assert_eq!(
                    display.affected_area(),
                    text.bounding_box(),
                    "alignment: {:?}, baseline: {:?}",
                    alignment,
                    baseline
                );
            }
        }
    }

    #[test]
    fn chained_text_drawing() {
        let character_style1 = MonoTextStyleBuilder::new()
            .font(&FONT_6X9)
            .text_color(BinaryColor::On)
            .build();

        let character_style2 = MonoTextStyleBuilder::new()
            .font(&FONT_6X13)
            .text_color(BinaryColor::Off)
            .build();

        let mut display = MockDisplay::new();
        let next = Text::new("AB", Point::new(0, 8), character_style1)
            .draw(&mut display)
            .unwrap();
        Text::new("C", next, character_style2)
            .draw(&mut display)
            .unwrap();

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

    #[test]
    fn line_height_pixels() {
        let character_style = MonoTextStyleBuilder::new()
            .font(&FONT_6X9)
            .text_color(BinaryColor::On)
            .build();

        let text_style = TextStyleBuilder::new()
            .line_height(LineHeight::Pixels(7))
            .build();

        let mut display = MockDisplay::new();
        Text::with_text_style("A\nB", Point::new(0, 5), character_style, text_style)
            .draw(&mut display)
            .unwrap();

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

    #[test]
    fn line_height_percent() {
        let character_style = MonoTextStyleBuilder::new()
            .font(&FONT_6X9)
            .text_color(BinaryColor::On)
            .build();

        let text_style = TextStyleBuilder::new()
            .baseline(Baseline::Top)
            .line_height(LineHeight::Percent(200))
            .build();

        let mut display = MockDisplay::new();
        Text::with_text_style("A\nBC", Point::zero(), character_style, text_style)
            .draw(&mut display)
            .unwrap();

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