cranpose-text 0.20.0

Text styles, fonts, shaping and paragraph layout for Cranpose
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
use std::{
    ops::Range,
    sync::{
        Arc,
        atomic::{AtomicU32, Ordering},
    },
};

use cranpose_ui_graphics::Rect;

use crate::{
    bidi_level::BidiLevel,
    glyph_id::GlyphId,
    glyph_ink::{InkReach, find_ink_past_lines, may_ink_past_lines},
    index_range::{IndexRange, widen},
    laid_glyphs::RunGlyphs,
    layout_body::LayoutBody,
    paragraph::TextAlign,
    shaped_glyphs::GlyphOffset,
    synthesized_style::SynthesizedStyle,
    typeface::Typeface,
};

/// A paragraph laid out in lines: glyph runs placed for drawing, and the
/// queries of Compose's `TextLayoutResult`. Distances are in pixels from the
/// layout's top left corner; offsets are byte offsets in the text. The
/// default is empty, ready for [`TextLayouter::layout_into`].
///
/// [`TextLayouter::layout_into`]: crate::TextLayouter::layout_into
#[derive(Clone, Debug, Default)]
pub struct TextLayout {
    // The lines and glyphs, shared by the copies aligned at other widths
    // while their lines keep their places.
    body: Arc<LayoutBody>,
    width: f32,
    // The width the lines wrap at.
    wrap: f32,
    did_overflow_width: bool,
    // Whether a glyph asks a bold or an italic of a face that lacks it.
    // Kept beside the body, so the paint of a text that asks none does not
    // load the body.
    synthesizes: bool,
    id: u32,
    // How far the glyphs reach, as `glyph_reach` gives it. Kept beside the
    // body, so a renderer reads it in the layout it holds.
    glyph_reach: Rect,
}

impl PartialEq for TextLayout {
    fn eq(&self, other: &Self) -> bool {
        // Copies that share a body hold the same lines and glyphs. A text
        // laid out again into the same lines draws the same, though it
        // takes a new id.
        (Arc::ptr_eq(&self.body, &other.body) || self.body == other.body)
            && self.width == other.width
            && self.did_overflow_width == other.did_overflow_width
    }
}

// The id the next layout made or aligned takes.
static NEXT_ID: AtomicU32 = AtomicU32::new(1);

// A new id for a layout whose glyphs or positions changed.
fn next_id() -> u32 {
    NEXT_ID.fetch_add(1, Ordering::Relaxed).max(1)
}

// How far the visible text of the lines of `body` reaches across, from the
// left edge of the leftmost to the right edge of the rightmost.
fn lines_reach(body: &LayoutBody) -> (f32, f32) {
    body.lines
        .iter()
        .map(|line| (line.left, line.right()))
        .reduce(|(left, right), (line_left, line_right)| {
            (left.min(line_left), right.max(line_right))
        })
        .unwrap_or_default()
}

// How far the glyphs of `body`, in the places its lines now take, reach, as
// `TextLayout::glyph_reach` gives it; `reach` tells whether a glyph may put
// ink past its advance or its typeface's lines. Inline: each layout takes
// its lines.
#[inline]
fn glyph_reach(body: &LayoutBody, reach: InkReach) -> Rect {
    let (left, right) = lines_reach(body);
    let lines = Rect {
        x: left,
        y: 0.0,
        width: right - left,
        height: 0.0,
    };
    if !may_ink_past_lines(body, reach) {
        return lines;
    }
    find_ink_past_lines(body, (left, right), reach).map_or(lines, |past| lines.union(past))
}

// Widths from `min` up to but not including `max`.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct WidthRange {
    pub(crate) min: f32,
    pub(crate) max: f32,
}

impl WidthRange {
    pub(crate) const ALL: Self = Self {
        min: f32::NEG_INFINITY,
        max: f32::INFINITY,
    };

    // Narrows the range to the widths from `min` up to `max`.
    pub(crate) fn narrow(&mut self, min: f32, max: f32) {
        self.min = self.min.max(min);
        self.max = self.max.min(max);
    }
}

// A run of one typeface, size and bidi level inside a line, in visual order.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct LineRun {
    pub(crate) text: IndexRange,
    pub(crate) glyphs: IndexRange,
    pub(crate) face: u32,
    pub(crate) size: f32,
    // Extra width of each cluster, half on each side.
    pub(crate) spacing: f32,
    // In a justified line, how many of the run's glyphs are spaces before
    // the line's trailing whitespace and the extra width each of them takes.
    pub(crate) spaces: u16,
    pub(crate) word_spacing: f32,
    // How far the run's baseline sits above the line's.
    pub(crate) baseline_shift: f32,
    pub(crate) level: BidiLevel,
    // The left edge from the line's left edge and the width, before
    // justification, and how far justification moves the run right.
    pub(crate) x: f32,
    pub(crate) width: f32,
    pub(crate) shift: f32,
}

// One cluster of a run, left to right: the offset its text starts at, its
// glyphs within the run and its width with the run's spacing.
struct Cluster {
    offset: usize,
    glyphs: Range<usize>,
    width: f32,
}

impl LineRun {
    // The left edge from the line's left edge.
    pub(crate) fn left(&self) -> f32 {
        self.x + self.shift
    }

    // The right edge from the line's left edge.
    fn right(&self) -> f32 {
        self.left() + self.width + self.word_spacing * f32::from(self.spaces)
    }

    // Pixels per design unit of `face`, the run's typeface.
    fn scale(&self, face: &Typeface) -> f32 {
        self.size / f32::from(face.units_per_em())
    }

    // The run's clusters left to right, of its `glyphs` in its typeface
    // `face`.
    fn clusters<'a>(
        &'a self,
        glyphs: RunGlyphs<'a>,
        face: &Typeface,
    ) -> impl Iterator<Item = Cluster> + 'a {
        let scale = self.scale(face);
        let space = face.space();
        let mut at = 0;
        std::iter::from_fn(move || {
            let first = glyphs.get(at)?;
            let start = at;
            let mut width = self.spacing;
            while let Some(glyph) = glyphs
                .get(at)
                .filter(|glyph| glyph.cluster == first.cluster)
            {
                width += font_units(glyph.advance) * scale;
                if space == Some(glyph.id()) {
                    width += self.word_spacing;
                }
                at += 1;
            }
            Some(Cluster {
                offset: first.text_offset(),
                glyphs: start..at,
                width,
            })
        })
    }

    // The run's clusters left to right, each with its left edge from the
    // run's left edge and the offset where its text ends: where the next
    // cluster in text order starts.
    fn cluster_spans<'a>(
        &'a self,
        (glyphs, face): (RunGlyphs<'a>, &Typeface),
    ) -> impl Iterator<Item = (f32, Cluster, usize)> + 'a {
        let mut clusters = self.clusters(glyphs, face).peekable();
        let mut left = 0.0;
        let mut previous = None;
        std::iter::from_fn(move || {
            let cluster = clusters.next()?;
            let end = if self.level.is_rtl() {
                previous.unwrap_or_else(|| self.text.end())
            } else {
                clusters
                    .peek()
                    .map_or_else(|| self.text.end(), |next| next.offset)
            };
            previous = Some(cluster.offset);
            let at = left;
            left += cluster.width;
            Some((at, cluster, end))
        })
    }
}

#[derive(Clone, Debug, PartialEq)]
pub(crate) struct LayoutLine {
    pub(crate) text: IndexRange,
    // The end of the text before the line's trailing whitespace.
    pub(crate) visible_end: u32,
    pub(crate) runs: IndexRange,
    pub(crate) top: f32,
    pub(crate) baseline: f32,
    pub(crate) bottom: f32,
    // The left edge of the line's visible text, its indent, its width
    // before justification and what justification adds to it.
    pub(crate) left: f32,
    pub(crate) indent: f32,
    pub(crate) width: f32,
    pub(crate) stretch: f32,
    // The level of the paragraph the line is in.
    pub(crate) level: BidiLevel,
    pub(crate) ellipsized: bool,
    pub(crate) ends_paragraph: bool,
}

impl LayoutLine {
    // The right edge of the visible text.
    pub(crate) fn right(&self) -> f32 {
        self.left + self.width + self.stretch
    }
}

/// Which of its two places a caret takes where the text before and after it
/// runs in different directions.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CaretDirection {
    /// The place of the paragraph's direction: Compose's
    /// `usePrimaryDirection = true`.
    Primary,
    /// The other place.
    Secondary,
}

/// The glyphs of one run of a line, ready to draw.
pub struct GlyphRun<'a> {
    /// The typeface the glyphs come from.
    pub typeface: &'a Typeface,
    /// The font size in pixels.
    pub size: f32,
    pub(crate) glyphs: RunGlyphs<'a>,
    pub(crate) offsets: Option<&'a [GlyphOffset]>,
    pub(crate) run: &'a LineRun,
    pub(crate) pen: f32,
    pub(crate) baseline: f32,
}

/// A glyph placed in a layout.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct PositionedGlyph {
    /// The glyph.
    pub id: GlyphId,
    /// Where its origin sits, from the layout's left edge.
    pub x: f32,
    /// Where its origin sits, from the layout's top edge.
    pub y: f32,
    /// The offset in the text of the character it draws, the first of its
    /// cluster.
    pub offset: usize,
}

impl GlyphRun<'_> {
    /// Each glyph with the position of its origin in the layout, left to
    /// right.
    pub fn positions(&self) -> impl Iterator<Item = PositionedGlyph> + '_ {
        let run = self.run;
        let baseline = self.baseline - run.baseline_shift;
        let scale = run.scale(self.typeface);
        let mut pen = self.pen;
        run.clusters(self.glyphs, self.typeface)
            .flat_map(move |cluster| {
                let mut x = pen + run.spacing / 2.0;
                pen += cluster.width;
                cluster.glyphs.filter_map(move |index| {
                    let glyph = self.glyphs.get(index)?;
                    let drawn = self
                        .offsets
                        .and_then(|offsets| offsets.get(index))
                        .copied()
                        .unwrap_or_default();
                    let at = x + font_units(drawn.x) * scale;
                    x += font_units(glyph.advance) * scale;
                    Some(PositionedGlyph {
                        id: glyph.id(),
                        x: at,
                        y: baseline - font_units(drawn.y) * scale,
                        offset: cluster.offset,
                    })
                })
            })
    }

    /// The text the run draws.
    pub fn text(&self) -> Range<usize> {
        self.run.text.range()
    }

    /// Where the run's baseline sits, from the layout's top edge.
    pub fn baseline(&self) -> f32 {
        self.baseline - self.run.baseline_shift
    }

    /// The run's left and right edges, from the layout's left edge.
    pub fn edges(&self) -> (f32, f32) {
        (self.pen, self.pen + self.run.right() - self.run.left())
    }
}

impl TextLayout {
    // The layout of `body`, whose lines wrap at `wrap`, laid out between
    // `widths`, the narrowest and the widest it may be, of glyphs whose ink
    // reaches as `reach` says that ask `synthesized` of their faces.
    pub(crate) fn new(
        mut body: LayoutBody,
        wrap: f32,
        widths: (f32, f32),
        (reach, synthesized): (InkReach, SynthesizedStyle),
    ) -> Self {
        let width = body.width_between(widths.0, widths.1);
        (body.ink_reach, body.synthesized) = (reach, synthesized);
        let glyph_reach = glyph_reach(&body, reach);
        Self {
            did_overflow_width: body.widest > width || width > widths.1,
            synthesizes: synthesized != SynthesizedStyle::default(),
            body: Arc::new(body),
            width,
            wrap,
            id: next_id(),
            glyph_reach,
        }
    }

    // Lays the layout out again between `widths`: `fill` fills its body, in
    // the body's own storage when no copy shares it, and gives the width its
    // lines wrap at, how the ink of its glyphs reaches and what they ask of
    // their faces.
    pub(crate) fn refill(
        &mut self,
        widths: (f32, f32),
        fill: impl FnOnce(&mut LayoutBody) -> (f32, (InkReach, SynthesizedStyle)),
    ) {
        if Arc::get_mut(&mut self.body).is_none() {
            self.body = Arc::default();
        }
        let body = Arc::make_mut(&mut self.body);
        (self.wrap, (body.ink_reach, body.synthesized)) = fill(body);
        self.synthesizes = body.synthesized != SynthesizedStyle::default();
        self.width = body.width_between(widths.0, widths.1);
        self.did_overflow_width = body.widest > self.width || self.width > widths.1;
        self.glyph_reach = glyph_reach(body, body.ink_reach);
        self.id = next_id();
    }

    // The body, which the layouter reads glyphs shaped before from.
    pub(crate) fn body(&self) -> &LayoutBody {
        &self.body
    }

    /// A number this layout's glyphs and positions go by: a layout laid out
    /// or aligned again takes a new one, so a renderer keys what it drew of
    /// a layout by it; a clone keeps it.
    pub fn id(&self) -> u32 {
        self.id
    }

    /// Whether the text laid out again between `min_width` and `max_width`,
    /// with the rest of its input the same, breaks into the same lines:
    /// [`TextLayout::align`] then gives that layout without laying the text
    /// out again.
    pub fn holds(&self, min_width: f32, max_width: f32) -> bool {
        self.holds_wrap(self.body.wrap_width(min_width, max_width))
    }

    // Whether lines that wrap at `wrap` are this layout's: a hold ends where
    // the comparisons of a fresh layout change, and a layout without one
    // stands only for the width it wraps at.
    fn holds_wrap(&self, wrap: f32) -> bool {
        match self.body.hold {
            Some(hold) => hold.min <= wrap && wrap < hold.max,
            None => wrap.to_bits() == self.wrap.to_bits(),
        }
    }

    /// The width the paragraph takes laid out between `min_width` and
    /// `max_width`: its max intrinsic width rounded up to whole device
    /// pixels within them, the max when they are equal, and its widest line
    /// rounded up to whole device pixels within them when its lines wrap.
    pub fn width_between(&self, min_width: f32, max_width: f32) -> f32 {
        self.body.width_between(min_width, max_width)
    }

    /// The max widths, from `.0` up to and with `.1`, at which the paragraph
    /// laid out from `min_width` keeps its width and its lines: every width
    /// when its width follows no max, every width from its own when its text
    /// fits, else the widths its lines wrap the same at below the width it
    /// fits at, or only the one it wraps at when those are not known or its
    /// widest line is wider than that one: its width is then the one it
    /// wraps at, and moves with it.
    pub fn max_widths_kept(&self, min_width: f32) -> (f32, f32) {
        let body = &self.body;
        if !body.follows_max {
            (f32::NEG_INFINITY, f32::INFINITY)
        } else if self.width >= body.content_width.max(min_width) {
            (self.width, f32::INFINITY)
        } else if let Some(hold) = body
            .hold
            .filter(|_| body.line_width.max(min_width) <= self.wrap)
        {
            let low = hold.min.max(self.width);
            let high = hold.max.min(body.content_width).next_down();
            if low <= high {
                (low, high)
            } else {
                (self.wrap, self.wrap)
            }
        } else {
            (self.wrap, self.wrap)
        }
    }

    /// Places the lines across the width the paragraph takes between
    /// `min_width` and `max_width` as `align` says, for widths the layout
    /// [holds](TextLayout::holds).
    pub fn align(&mut self, min_width: f32, max_width: f32, align: TextAlign) {
        self.place(
            self.body.wrap_width(min_width, max_width),
            (min_width, max_width),
            align,
        );
    }

    /// [Aligns](TextLayout::align) the lines between `min_width` and
    /// `max_width` when the layout [holds](TextLayout::holds) there; `false`,
    /// leaving the layout as it was, when it does not.
    pub fn try_align(&mut self, min_width: f32, max_width: f32, align: TextAlign) -> bool {
        let wrap = self.body.wrap_width(min_width, max_width);
        let held = self.holds_wrap(wrap);
        if held {
            self.place(wrap, (min_width, max_width), align);
        }
        held
    }

    // Places the lines, which wrap at `wrap`, across the width the
    // paragraph takes between `(min_width, max_width)` as `align` says.
    fn place(&mut self, wrap: f32, (min_width, max_width): (f32, f32), align: TextAlign) {
        self.wrap = wrap;
        self.width = self.body.width_at(wrap, min_width);
        self.did_overflow_width = self.body.widest > self.width || self.width > max_width;
        // Lines that keep their places keep the body the copies share, and
        // the id what a renderer drew of the layout goes by.
        if self.body.lines_move(self.width, align) {
            self.move_lines(align);
        }
    }

    // Places the lines across the layout's width as `align` says. Out of
    // line: as a width animates, most lines keep their places, and a call
    // that moves none then saves no registers.
    #[inline(never)]
    fn move_lines(&mut self, align: TextAlign) {
        let body = Arc::make_mut(&mut self.body);
        if body.align_lines(self.width, align) {
            // Moved across, the glyphs and the lines' heights stay.
            self.glyph_reach = glyph_reach(body, body.ink_reach);
            self.id = next_id();
        }
    }

    /// The paragraph's width: its max intrinsic width rounded up to whole
    /// device pixels, within the widths it was laid out between.
    pub fn width(&self) -> f32 {
        self.width
    }

    /// The height of all lines.
    pub fn height(&self) -> f32 {
        self.body.height
    }

    /// The distance from the first line's baseline down to the next line's:
    /// the first line's height before the paragraph's edges trim it.
    pub fn line_advance(&self) -> f32 {
        self.body.advance
    }

    /// The number of lines, at least one.
    pub fn line_count(&self) -> usize {
        self.body.lines.len()
    }

    /// How far the visible text of the lines reaches across: the left edge
    /// of the leftmost line's and the right edge of the rightmost line's,
    /// both zero for the empty default.
    pub fn lines_reach(&self) -> (f32, f32) {
        lines_reach(&self.body)
    }

    /// The typefaces the glyphs come from.
    pub fn typefaces(&self) -> &[Typeface] {
        &self.body.faces
    }

    /// The bold and the italic the glyphs ask of faces that lack them, which
    /// a renderer synthesizes and which spread their ink.
    pub fn synthesized_style(&self) -> SynthesizedStyle {
        if self.synthesizes {
            self.body.synthesized
        } else {
            SynthesizedStyle::default()
        }
    }

    /// How far the glyphs reach, in pixels from the layout's top left
    /// corner: across, the visible text of the lines and the ink a glyph puts
    /// past it, as the overhang of an `f` that ends a line does; down, from
    /// the top, or the ink above it, to the lowest ink, at the top when the
    /// glyphs ink no lower than the box. A renderer joins it with the box it
    /// draws the text in.
    pub fn glyph_reach(&self) -> Rect {
        self.glyph_reach
    }

    /// Whether the text had more lines than the line limit: Compose's
    /// `didOverflowHeight` of a layout the line limit cut.
    pub fn did_overflow_height(&self) -> bool {
        self.body.did_overflow_height
    }

    /// Whether the paragraph is wider than the widest it was laid out at, or
    /// a line wider than the paragraph: Compose's `didOverflowWidth`.
    pub fn did_overflow_width(&self) -> bool {
        self.did_overflow_width
    }

    /// Whether `line` shows an ellipsis in place of text.
    pub fn is_line_ellipsized(&self, line: usize) -> bool {
        self.body.lines[line].ellipsized
    }

    /// The offset where `line` starts. Panics when `line` is out of range, as
    /// Compose throws.
    pub fn line_start(&self, line: usize) -> usize {
        self.body.lines[line].text.start()
    }

    /// The offset where `line` ends, after its line break and trailing
    /// whitespace.
    pub fn line_end(&self, line: usize) -> usize {
        self.body.lines[line].text.end()
    }

    /// The offset where the visible text of `line` ends, before its line
    /// break and trailing whitespace: Compose's `getLineEnd(line, true)`.
    pub fn line_visible_end(&self, line: usize) -> usize {
        widen(self.body.lines[line].visible_end)
    }

    /// The top of `line`.
    pub fn line_top(&self, line: usize) -> f32 {
        self.body.lines[line].top
    }

    /// The bottom of `line`.
    pub fn line_bottom(&self, line: usize) -> f32 {
        self.body.lines[line].bottom
    }

    /// The baseline of `line`.
    pub fn line_baseline(&self, line: usize) -> f32 {
        self.body.lines[line].baseline
    }

    /// The left edge of the visible text of `line`.
    pub fn line_left(&self, line: usize) -> f32 {
        self.body.lines[line].left
    }

    /// The right edge of the visible text of `line`.
    pub fn line_right(&self, line: usize) -> f32 {
        self.body.lines[line].right()
    }

    /// The line that holds `offset`; the last line for the end of the text.
    pub fn line_for_offset(&self, offset: usize) -> usize {
        self.body
            .lines
            .partition_point(|line| line.text.end() <= offset)
            .min(self.body.lines.len() - 1)
    }

    /// The line at height `y`, the first above the text and the last below it.
    pub fn line_for_vertical_position(&self, y: f32) -> usize {
        self.body
            .lines
            .partition_point(|line| line.bottom <= y)
            .min(self.body.lines.len() - 1)
    }

    /// The x of a caret at `offset`. Where the text before and after `offset`
    /// runs in different directions the caret has two places, and `direction`
    /// picks one.
    pub fn horizontal_position(&self, offset: usize, direction: CaretDirection) -> f32 {
        let line = &self.body.lines[self.line_for_offset(offset)];
        let runs = &self.body.runs[line.runs.range()];
        let after = runs
            .iter()
            .find(|run| run.text.start() <= offset && offset < run.text.end());
        let before = runs
            .iter()
            .find(|run| run.text.start() < offset && offset <= run.text.end());
        let run = match (before, after) {
            (Some(before), Some(after)) if before.level != after.level => {
                if (before.level == line.level) == (direction == CaretDirection::Primary) {
                    before
                } else {
                    after
                }
            }
            (_, Some(run)) | (Some(run), None) => run,
            (None, None) => {
                return if line.level.is_rtl() {
                    line.right()
                } else {
                    line.left
                };
            }
        };
        line.left + self.caret_in_run(run, offset)
    }

    /// The offset of the caret nearest to the point `x`, `y`.
    pub fn offset_for_position(&self, x: f32, y: f32) -> usize {
        let line = &self.body.lines[self.line_for_vertical_position(y)];
        let runs = &self.body.runs[line.runs.range()];
        let local = x - line.left;
        let Some(run) = runs
            .iter()
            .find(|run| local < run.right())
            .or_else(|| runs.last())
        else {
            return line.text.start();
        };
        self.offset_in_run(run, local - run.left())
    }

    /// The glyph runs of `line`, left to right.
    pub fn glyph_runs(&self, line: usize) -> impl Iterator<Item = GlyphRun<'_>> + '_ {
        self.body.glyph_runs(line)
    }

    /// The box of the character at `offset`, across its line: Compose's
    /// `getBoundingBox`. A zero-width box at the caret for an offset with no
    /// character, such as the end of the text.
    pub fn bounding_box(&self, offset: usize) -> Rect {
        let line = &self.body.lines[self.line_for_offset(offset)];
        let found = self.body.runs[line.runs.range()].iter().find_map(|run| {
            run.cluster_spans(self.body.run_glyphs(run))
                .find(|(_, cluster, end)| (cluster.offset..*end).contains(&offset))
                .map(|(left, cluster, _)| (run.left() + left, cluster.width))
        });
        let (x, width) = found.unwrap_or_else(|| {
            (
                self.horizontal_position(offset, CaretDirection::Primary) - line.left,
                0.0,
            )
        });
        Rect {
            x: line.left + x,
            y: line.top,
            width,
            height: line.bottom - line.top,
        }
    }

    /// The caret at `offset` as a zero-width rectangle across its line:
    /// Compose's `getCursorRect`.
    pub fn cursor_rect(&self, offset: usize) -> Rect {
        let line = &self.body.lines[self.line_for_offset(offset)];
        Rect {
            x: self.horizontal_position(offset, CaretDirection::Primary),
            y: line.top,
            width: 0.0,
            height: line.bottom - line.top,
        }
    }

    /// Pushes onto `rects` the rectangles that cover the text from `start`
    /// to `end` line by line, one for each stretch of it that runs in one
    /// direction, within the paragraph's width or its visible text: Compose's
    /// `getPathForRange` as rectangles. The spaces a wrapped line ends with
    /// hang past the widest line, which they do not widen, and cover nothing
    /// there.
    pub fn selection_rects(&self, start: usize, end: usize, rects: &mut Vec<Rect>) {
        let width = self.width;
        for line in &self.body.lines {
            if line.text.end() <= start || line.text.start() >= end {
                continue;
            }
            let mut open: Option<(f32, f32)> = None;
            for run in &self.body.runs[line.runs.range()] {
                for (left, cluster, cluster_end) in run.cluster_spans(self.body.run_glyphs(run)) {
                    let x = run.left() + left;
                    let covered = cluster.offset < end && cluster_end > start;
                    match (covered, open) {
                        (true, Some((from, _))) => open = Some((from, x + cluster.width)),
                        (true, None) => open = Some((x, x + cluster.width)),
                        (false, Some(span)) => {
                            push_span(rects, (line, width), span);
                            open = None;
                        }
                        (false, None) => {}
                    }
                }
            }
            if let Some(span) = open {
                push_span(rects, (line, width), span);
            }
        }
    }

    // The caret x of `offset` inside `run`, from the line's left edge.
    fn caret_in_run(&self, run: &LineRun, offset: usize) -> f32 {
        let (glyphs, face) = self.body.run_glyphs(run);
        let before: f32 = run
            .clusters(glyphs, face)
            .filter(|cluster| cluster.offset < offset)
            .map(|cluster| cluster.width)
            .sum();
        if run.level.is_rtl() {
            run.right() - before
        } else {
            run.left() + before
        }
    }

    // The offset nearest to `x` pixels from the left edge of `run`: each
    // cluster's left half gives the offset on its left.
    fn offset_in_run(&self, run: &LineRun, x: f32) -> usize {
        for (left, cluster, end) in run.cluster_spans(self.body.run_glyphs(run)) {
            if x < left + cluster.width / 2.0 {
                return if run.level.is_rtl() {
                    end
                } else {
                    cluster.offset
                };
            }
        }
        if run.level.is_rtl() {
            run.text.start()
        } else {
            run.text.end()
        }
    }
}

// Adds the rectangle of `line` from `left` to `right`, from the line's left
// edge.
// Pushes the rectangle of `line` from `left` to `right` within the
// paragraph's `width`, or past it as far as the line's visible text reaches.
fn push_span(rects: &mut Vec<Rect>, (line, width): (&LayoutLine, f32), (left, right): (f32, f32)) {
    let (low, high) = (line.left.min(0.0), width.max(line.left + line.width));
    let (left, right) = (
        (line.left + left).clamp(low, high),
        (line.left + right).clamp(low, high),
    );
    if left < right {
        rects.push(Rect {
            x: left,
            y: line.top,
            width: right - left,
            height: line.bottom - line.top,
        });
    }
}

// A distance in font design units as a float, exact for every value under
// 2^24: shaped values lie far inside it for any font, whose em is at most
// 16,384 units.
pub(crate) fn font_units(value: i32) -> f32 {
    value as f32
}