plotive-text 0.4.0

Text shaping and rendering library for plotive
Documentation
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
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
use plotive_base::{Color, ColorU8, color, geom};
use ttf_parser as ttf;

use crate::{Error, font, fontdb, line};

mod boundaries;
mod builder;
mod parse;
mod render;

use boundaries::Boundaries;
pub use parse::{
    ParseRichTextError, ParsedRichText, parse_rich_text, parse_rich_text_with_classes,
};
pub use render::{RichPrimitive, render_rich_text, render_rich_text_with};

/// Typographic alignment, possibly depending on the script direction.
#[derive(Debug, Clone, Copy, Default)]
pub enum Align {
    /// The start of the text is aligned with the reference point.
    #[default]
    Start,
    /// Text is centered around the reference point.
    Center,
    /// The end of the text is aligned with the reference point.
    End,
    /// Text is left aligned.
    /// For vertical layout, this is the same as [`Start`](Align::Start).
    Left,
    /// Text is right aligned.
    /// For vertical layout, this is the same as [`End`](Align::End).
    Right,
    /// The text is justified on both ends.
    /// The parameter is the total width of the text (or height for vertical text)
    Justify(f32),
}

/// Vertical alignment for a whole horizontal text, possibly considering multiple lines
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum VerAlign {
    /// Align at the specified line
    Line(usize, line::VerAlign),
    /// Align at the top (ascender) of the first line
    Top,
    /// Align at the center, that is (top + bottom) / 2
    Center,
    /// Align at the bottom (descender) of the last line
    Bottom,
}

impl Default for VerAlign {
    fn default() -> Self {
        VerAlign::Line(0, Default::default())
    }
}

impl From<line::VerAlign> for VerAlign {
    fn from(value: line::VerAlign) -> Self {
        Self::Line(0, value)
    }
}

/// Horizontal alignement of vertical text
/// This will not affect the placement of glyphs relative to each other,
/// but will dictate how they are aligned relative to the reference X coordinate.
/// The default is center.
#[derive(Debug, Clone, Copy, Default)]
pub enum HorAlign {
    Left,
    #[default]
    Center,
    Right,
}

/// A direction for horizontal text layout.
/// Direction refers to left to right, or right to left text.
/// The mixed directions take into account bidirectional text and refer to
/// the main direction of the text.
/// (see <https://www.w3.org/International/articles/inline-bidi-markup/uba-basics#context>)
#[derive(Debug, Clone, Copy, Default)]

pub enum Direction {
    /// The main direction is the one of the first encountered script.
    /// This is the default.
    #[default]
    Mixed,
    /// The main direction of the script is Left to Right.
    /// Right to Left script will still be rendered right to left,
    /// but in case of mixed script, the main direction is left to right.
    MixedLTR,
    /// The main direction of the script is Right to Left.
    /// Left to Right script will still be rendered left to right,
    /// but in case of mixed script, the main direction is right to left.
    MixedRTL,
    /// Left to right text. (no bidirectional algorithm applied)
    LTR,
    /// Right to left text. (no bidirectional algorithm applied)
    RTL,
}

/// Direction for vertical text layout
#[derive(Debug, Clone, Copy, Default)]
pub enum VerDirection {
    /// Top to bottom
    #[default]
    TTB,
    /// Bottom to top
    BTT,
}

/// Direction of progression of successive columns for vertical text.
/// While horizontal text lines always progress from top to bottom,
/// vertical text columns can progress either left to right or right to left.
#[derive(Debug, Clone, Copy, Default)]
pub enum VerProgression {
    /// Progression is determined by the main direction of the script.
    /// That is, Hebrew and Arabic progress right to left, while others progress left to right.
    #[default]
    PerScript,
    /// Progression is left to right
    LTR,
    /// Progression is right to left
    RTL,
}

/// Space between two columns of vertical space.
/// This value is a factor of the font em-box side size
/// E.g. if the em-box after scaling is 40px wide, a value of 0.5 will yield
/// to an inter-space of 20px. (0.5 is the default value)
#[derive(Debug, Clone, Copy)]
pub struct InterColumn(pub f32);

impl Default for InterColumn {
    fn default() -> Self {
        InterColumn(0.5)
    }
}

/// Layout options for rich text
#[derive(Debug, Clone, Copy)]
pub enum Layout {
    /// Horizontal text layout options
    Horizontal(Align, VerAlign, Direction),
    /// Vertical text layout options
    Vertical(Align, HorAlign, VerDirection, VerProgression, InterColumn),
}

impl Default for Layout {
    fn default() -> Self {
        Layout::Horizontal(Default::default(), Default::default(), Default::default())
    }
}

/// A builder struct for rich text
#[derive(Debug, Clone)]
pub struct RichTextBuilder<C>
where
    C: Clone + PartialEq,
{
    text: String,
    root_props: TextProps<C>,
    layout: Layout,
    spans: Vec<TextSpan<C>>,
}

impl<C> RichTextBuilder<C>
where
    C: Clone + PartialEq,
{
    /// Create a new RichTextBuilder
    pub fn new(text: String, root_props: TextProps<C>) -> RichTextBuilder<C> {
        RichTextBuilder {
            text,
            root_props,
            layout: Layout::default(),
            spans: vec![],
        }
    }

    pub fn with_layout(mut self, layout: Layout) -> Self {
        self.layout = layout;
        self
    }

    /// Add a new text span
    pub fn add_span(&mut self, start: usize, end: usize, props: TextOptProps<C>) {
        assert!(start <= end);
        assert!(
            self.text.is_char_boundary(start) && self.text.is_char_boundary(end),
            "start and end must be on char boundaries"
        );
        self.spans.push(TextSpan { start, end, props });
    }

    /// Create a RichText from this builder
    pub fn done(self, fontdb: &fontdb::Database) -> Result<RichText<C>, Error> {
        self.done_impl(fontdb)
    }
}

#[derive(Debug, Clone)]
pub struct RichText<C = ColorU8>
where
    C: Clone,
{
    text: String,
    layout: Layout,
    lines: Vec<LineSpan<C>>,
    bbox: Option<geom::Rect>,
}

impl<C> RichText<C>
where
    C: Clone,
{
    pub fn text(&self) -> &str {
        &self.text
    }

    pub fn layout(&self) -> Layout {
        self.layout
    }

    pub fn lines(&self) -> &[LineSpan<C>] {
        &self.lines
    }

    pub fn bbox(&self) -> Option<&geom::Rect> {
        self.bbox.as_ref()
    }

    #[inline]
    pub fn width(&self) -> f32 {
        self.bbox.map_or(0.0, |bbox| bbox.width())
    }

    #[inline]
    pub fn height(&self) -> f32 {
        self.bbox.map_or(0.0, |bbox| bbox.height())
    }

    pub fn visual_bbox(&self) -> Option<geom::Rect> {
        if self.lines.is_empty() {
            return None;
        }
        let mut bbox = None;
        for l in &self.lines {
            bbox = geom::Rect::unite_opt(bbox.as_ref(), l.visual_bbox().as_ref());
        }
        bbox
    }

    /// Convert this RichText to another color type using the provided mapping function
    pub fn to_other_color<D, M>(&self, color_map: M) -> RichText<D>
    where
        D: Clone,
        M: Fn(&C) -> D,
    {
        RichText {
            text: self.text.clone(),
            layout: self.layout,
            lines: self
                .lines
                .iter()
                .map(|l| l.to_other_color(&color_map))
                .collect(),
            bbox: self.bbox,
        }
    }

    fn empty() -> Self {
        Self {
            text: String::new(),
            layout: Layout::default(),
            lines: Vec::new(),
            bbox: None,
        }
    }

    #[cfg(debug_assertions)]
    pub fn assert_flat_coverage(&self) {
        let len = self.text.len();
        let mut cursor = 0;
        for l in self.lines.iter() {
            assert_eq!(l.start, cursor);
            cursor = l.end;
            if cursor == len {
                // last line might not end with a newline
                break;
            }
            if self.text.as_bytes()[cursor] == b'\r' {
                cursor += 1;
            }
            assert_eq!(
                self.text.as_bytes()[cursor],
                b'\n',
                "expected end of line, found {}",
                self.text[cursor..].chars().next().unwrap()
            );
            cursor += 1;
            l.assert_flat_coverage();
        }
        assert_eq!(cursor, len);
    }
}

/// A set of properties to be applied to a text span.
/// If a property is `None`, value is inherited from the parent span.
#[derive(Debug, Clone, PartialEq)]
pub struct TextOptProps<C> {
    pub font_family: Option<Vec<font::Family>>,
    pub font_weight: Option<font::Weight>,
    pub font_width: Option<font::Width>,
    pub font_style: Option<font::Style>,
    pub font_size: Option<f32>,
    pub fill: Option<C>,
    pub stroke: Option<(C, f32)>,
    pub underline: Option<bool>,
    pub strikeout: Option<bool>,
}

impl<C> Default for TextOptProps<C> {
    fn default() -> Self {
        TextOptProps {
            font_family: None,
            font_weight: None,
            font_width: None,
            font_style: None,
            font_size: None,
            fill: None,
            stroke: None,
            underline: None,
            strikeout: None,
        }
    }
}

impl<C> TextOptProps<C> {
    fn affect_shape(&self) -> bool {
        self.font_family.is_some()
            || self.font_weight.is_some()
            || self.font_width.is_some()
            || self.font_style.is_some()
            || self.font_size.is_some()
    }
}

/// A set of resolved properties for a text span
#[derive(Debug, Clone)]
pub struct TextProps<C>
where
    C: Clone,
{
    font_size: f32,
    font: font::Font,
    fill: Option<C>,
    outline: Option<(C, f32)>,
    underline: bool,
    strikeout: bool,
}

impl<C> TextProps<C>
where
    C: Clone,
{
    /// Convert this TextProps to another color type using the provided mapping function
    pub fn to_other_color<D, M>(&self, color_map: M) -> TextProps<D>
    where
        D: Clone,
        M: Fn(&C) -> D,
    {
        TextProps {
            font_size: self.font_size,
            font: self.font.clone(),
            fill: self.fill.as_ref().map(|c| color_map(c)),
            outline: self.outline.as_ref().map(|(c, w)| (color_map(c), *w)),
            underline: self.underline,
            strikeout: self.strikeout,
        }
    }
}

/// A color that has meaning for the foreground
/// (e.g. a font color)
pub trait Foreground {
    fn foreground() -> Self;
}

impl Foreground for ColorU8 {
    fn foreground() -> Self {
        color::BLACK
    }
}

impl<C> TextProps<C>
where
    C: Color + Foreground,
{
    pub fn new(font_size: f32) -> TextProps<C> {
        TextProps {
            font_size,
            font: font::Font::default(),
            fill: Some(C::foreground()),
            outline: None,
            underline: false,
            strikeout: false,
        }
    }
}

impl<C> TextProps<C>
where
    C: Clone,
{
    pub fn with_font(mut self, font: font::Font) -> Self {
        self.font = font;
        self
    }

    pub fn with_fill(mut self, fill: Option<C>) -> Self {
        self.fill = fill;
        self
    }

    pub fn with_outline(mut self, stroke: (C, f32)) -> Self {
        self.outline = Some(stroke);
        self
    }

    pub fn with_underline(mut self) -> Self {
        self.underline = true;
        self
    }

    pub fn with_strikeout(mut self) -> Self {
        self.strikeout = true;
        self
    }

    pub fn font_size(&self) -> f32 {
        self.font_size
    }

    pub fn font(&self) -> &font::Font {
        &self.font
    }

    pub fn fill(&self) -> Option<C> {
        self.fill.clone()
    }

    pub fn outline(&self) -> Option<(C, f32)> {
        self.outline.clone()
    }

    pub fn underline(&self) -> bool {
        self.underline
    }

    pub fn strikeout(&self) -> bool {
        self.strikeout
    }

    fn apply_opts(&mut self, opts: &TextOptProps<C>) {
        if let Some(font_family) = &opts.font_family {
            self.font = self.font.clone().with_families(font_family.clone());
        }
        if let Some(font_weight) = opts.font_weight {
            self.font = self.font.clone().with_weight(font_weight);
        }
        if let Some(font_width) = opts.font_width {
            self.font = self.font.clone().with_width(font_width);
        }
        if let Some(font_style) = opts.font_style {
            self.font = self.font.clone().with_style(font_style);
        }
        if let Some(font_size) = opts.font_size {
            self.font_size = font_size;
        }
        if let Some(fill) = opts.fill.as_ref() {
            self.fill = Some(fill.clone());
        }
        if let Some(stroke) = opts.stroke.as_ref() {
            self.outline = Some(stroke.clone());
        }
        if let Some(underline) = opts.underline {
            self.underline = underline;
        }
        if let Some(strikeout) = opts.strikeout {
            self.strikeout = strikeout;
        }
    }
}

/// A text span
#[derive(Debug, Clone)]
struct TextSpan<C> {
    start: usize,
    end: usize,
    props: TextOptProps<C>,
}

/// A line of rich text
#[derive(Debug, Clone)]
pub struct LineSpan<C>
where
    C: Clone,
{
    start: usize,
    end: usize,
    shapes: Vec<ShapeSpan<C>>,
    main_dir: rustybuzz::Direction,
    bbox: Option<geom::Rect>,
}

impl<C> LineSpan<C>
where
    C: Clone,
{
    /// Convert this LineSpan to another color type using the provided mapping function
    pub fn to_other_color<D, M>(&self, color_map: M) -> LineSpan<D>
    where
        D: Clone,
        M: Fn(&C) -> D,
    {
        LineSpan {
            start: self.start,
            end: self.end,
            shapes: self
                .shapes
                .iter()
                .map(|s| s.to_other_color(&color_map))
                .collect(),
            main_dir: self.main_dir,
            bbox: self.bbox,
        }
    }

    /// Byte index where the line starts in the text
    pub fn start(&self) -> usize {
        self.start
    }

    /// Byte index where the line ends in the text
    pub fn end(&self) -> usize {
        self.end
    }

    /// The text shapes in this line
    pub fn shapes(&self) -> &[ShapeSpan<C>] {
        &self.shapes
    }

    /// The main text direction of this line
    pub fn main_dir(&self) -> rustybuzz::Direction {
        self.main_dir
    }

    /// Bounding box of the line
    pub fn bbox(&self) -> Option<geom::Rect> {
        self.bbox
    }

    /// The total height of this line including the gap to the next one
    pub fn total_height(&self) -> f32 {
        self.height() + self.gap()
    }

    /// The vertical gap from this line to the next.
    /// Can be zero if the font includes this in the height
    pub fn gap(&self) -> f32 {
        self.shapes
            .iter()
            .map(|s| s.metrics.line_gap)
            .max_by(|a, b| a.partial_cmp(b).unwrap())
            .unwrap_or(0.0)
    }

    pub fn height(&self) -> f32 {
        self.shapes
            .iter()
            .map(|s| s.metrics.height())
            .max_by(|a, b| a.partial_cmp(b).unwrap())
            .unwrap_or(0.0)
    }

    pub fn ascent(&self) -> f32 {
        self.shapes
            .iter()
            .map(|s| s.metrics.ascent)
            .max_by(|a, b| a.partial_cmp(b).unwrap())
            .unwrap_or(0.0)
    }

    pub fn descent(&self) -> f32 {
        self.shapes
            .iter()
            .map(|s| s.metrics.descent)
            .max_by(|a, b| a.partial_cmp(b).unwrap())
            .unwrap_or(0.0)
    }

    /// The maximum capital height of this line.
    /// If there are multiple shape sizes, the average is returned
    pub fn cap_height(&self) -> f32 {
        self.shapes
            .iter()
            .map(|s| s.metrics.cap_height)
            .max_by(|a, b| a.partial_cmp(b).unwrap())
            .unwrap_or(0.0)
    }

    /// The x-height of this line.
    /// If there are multiple shape sizes, the average is returned
    pub fn x_height(&self) -> f32 {
        if self.shapes.is_empty() {
            return 0.0;
        }
        let sum: f32 = self.shapes.iter().map(|s| s.metrics.x_height).sum();
        sum / (self.shapes.len() as f32)
    }

    /// Visual bounding box of the line
    pub fn visual_bbox(&self) -> Option<geom::Rect> {
        if self.shapes.is_empty() {
            return None;
        }
        let mut bbox = None;
        for s in &self.shapes {
            bbox = geom::Rect::unite_opt(bbox.as_ref(), Some(&s.visual_bbox()));
        }
        bbox
    }

    #[cfg(debug_assertions)]
    fn assert_flat_coverage(&self) {
        let mut cursor = self.start;
        for s in self.shapes.iter() {
            assert_eq!(s.start, cursor);
            cursor = s.end;
            s.assert_flat_coverage();
        }
        assert_eq!(cursor, self.end);
    }
}

/// A shape of text in a line
/// A shape is a sequence of glyphs that share the same properties:
///   - font
///   - font size
///   - script direction
#[derive(Debug, Clone)]
pub struct ShapeSpan<C>
where
    C: Clone,
{
    start: usize,
    end: usize,
    spans: Vec<PropsSpan<C>>,
    face_id: fontdb::ID,
    glyphs: Vec<Glyph>,
    metrics: font::ScaledMetrics,
    y_baseline: f32,
    bbox: Option<geom::Rect>,
}

impl<C> ShapeSpan<C>
where
    C: Clone,
{
    /// Convert this ShapeSpan to another color type using the provided mapping function
    pub fn to_other_color<D, M>(&self, color_map: M) -> ShapeSpan<D>
    where
        D: Clone,
        M: Fn(&C) -> D,
    {
        ShapeSpan {
            start: self.start,
            end: self.end,
            spans: self
                .spans
                .iter()
                .map(|s| s.to_other_color(&color_map))
                .collect(),
            face_id: self.face_id,
            glyphs: self.glyphs.clone(),
            metrics: self.metrics,
            y_baseline: self.y_baseline,
            bbox: self.bbox,
        }
    }

    /// Byte index where the shape starts in the text
    pub fn start(&self) -> usize {
        self.start
    }

    /// Byte index where the shape ends in the text
    pub fn end(&self) -> usize {
        self.end
    }

    /// The font of this shape
    pub fn font(&self) -> &font::Font {
        &self.spans[0].props.font
    }

    /// The font of this shape
    pub fn font_size(&self) -> f32 {
        self.spans[0].props.font_size
    }

    /// The text spans in this shape
    pub fn spans(&self) -> &[PropsSpan<C>] {
        &self.spans
    }

    /// The metrics of this shape
    pub fn metrics(&self) -> font::ScaledMetrics {
        self.metrics
    }

    /// The bounding box of this shape
    pub fn bbox(&self) -> geom::Rect {
        // no empty shapes are built
        self.bbox.unwrap()
    }

    /// The visual bounding box of this shape
    pub fn visual_bbox(&self) -> geom::Rect {
        // no empty shapes are built
        assert!(!self.glyphs.is_empty());

        let mut bbox = None;
        for g in &self.glyphs {
            match bbox {
                Some(ref mut b) => {
                    *b = geom::Rect::unite(b, &g.visual_bbox());
                }
                None => {
                    bbox = Some(g.visual_bbox());
                }
            }
        }
        bbox.unwrap()
    }

    #[cfg(debug_assertions)]
    fn assert_flat_coverage(&self) {
        let mut cursor = self.start;
        for s in self.spans.iter() {
            assert_eq!(s.start, cursor);
            cursor = s.end;
        }
        assert_eq!(cursor, self.end);
    }
}

/// A span of text with the same properties
#[derive(Debug, Clone)]
pub struct PropsSpan<C>
where
    C: Clone,
{
    start: usize,
    end: usize,
    props: TextProps<C>,
    bbox: Option<geom::Rect>,
}

impl<C> PropsSpan<C>
where
    C: Clone,
{
    /// Convert this PropSpan to another color type using the provided mapping function
    pub fn to_other_color<D, M>(&self, color_map: M) -> PropsSpan<D>
    where
        D: Clone,
        M: Fn(&C) -> D,
    {
        PropsSpan {
            start: self.start,
            end: self.end,
            props: self.props.to_other_color(color_map),
            bbox: self.bbox,
        }
    }

    /// Byte index where the span starts in the text
    pub fn start(&self) -> usize {
        self.start
    }

    /// Byte index where the span ends in the text
    pub fn end(&self) -> usize {
        self.end
    }

    /// The properties of this span
    pub fn props(&self) -> &TextProps<C> {
        &self.props
    }

    /// Bounding box of the span
    pub fn bbox(&self) -> geom::Rect {
        // no empty spans are built
        self.bbox.unwrap()
    }
}

#[derive(Debug, Clone, Copy)]
struct Glyph {
    id: ttf::GlyphId,
    cluster: usize,
    x_advance: f32,
    y_advance: f32,
    x_offset: f32,
    y_offset: f32,
    ts: tiny_skia::Transform,
    rect: ttf::Rect,
}

impl Glyph {
    fn visual_bbox(&self) -> geom::Rect {
        let mut tl_br = [
            geom::Point {
                x: self.rect.x_min as f32,
                y: self.rect.y_max as f32,
            },
            geom::Point {
                x: self.rect.x_max as f32,
                y: self.rect.y_min as f32,
            },
        ];
        self.ts.map_points(&mut tl_br);
        geom::Rect::from_trbl(tl_br[0].y, tl_br[1].x, tl_br[1].y, tl_br[0].x)
    }
}