cranpose-ui 0.19.0

Composable widgets, text, layouts and input for Cranpose apps
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
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
use std::{
    cell::{Cell, OnceCell, RefCell},
    ops::Range,
    rc::Rc,
    sync::Arc,
};

use cranpose_core::{
    PackedU64,
    collections::pass_aged::{IDLE_PASSES, PassAgedCache},
};
use cranpose_text::{
    CaretDirection, FontExtent, FontFamily, FontFamilyResolver, FontRequest, FontStyle, FontWeight,
    LayoutInput, ParagraphIntrinsics, TextLayout, TextLayouter, paragraph_line_box,
};
use cranpose_ui_graphics::{MemoryHeadroom, Size, TextLayoutHandle};

use super::{
    AnnotatedString, LineBox, RenderString, SpanStyle, TextAlign, TextDrawStyle, TextUnit,
    layout_cache::{CacheAdmission, Cached, LayoutCache},
    layout_input::{DEFAULT_FONT_SIZE_SP, ParagraphSpans, TextUnits},
    layout_options::{TextLayoutOptions, TextOverflow},
    style::TextStyle,
    text_key::TextKey,
};
use crate::{density::Density, font_scale::FontScaleCurve, text_layout_result::TextLayoutResult};

const TEXT_INTRINSICS_CACHE_CAPACITY: usize = 1024;
const SCALE_DOWN_SEARCH_STEPS: usize = 14;

/// Size of a laid-out text. Distances are in logical pixels.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct TextMetrics {
    /// The paragraph's width, within the widths it was laid out between.
    pub width: f32,
    /// Height of all lines together.
    pub height: f32,
    /// The distance from the first line's baseline down to the next line's.
    pub line_height: f32,
    /// Number of lines, at least the minimum the options ask for.
    pub line_count: usize,
}

/// A text laid out between two widths: its glyphs and lines, which every
/// query, measurement and renderer reads, and the size it measures.
#[derive(Clone, Debug)]
pub struct PreparedTextLayout {
    /// The text that was laid out.
    pub text: Rc<AnnotatedString>,
    /// The style the text draws in, shared with every render node drawn
    /// from this layout.
    pub visual_style: Arc<TextStyle>,
    /// The lines and glyphs.
    pub layout: TextLayout,
    // The widest the text could be, and the fewest lines its height covers,
    // which its metrics follow from with its layout.
    max_width: f32,
    min_lines: u32,
    /// `text` as a renderer draws it, and its
    /// [`RenderString::render_hash`](crate::text::RenderString::render_hash),
    /// converted on first use: see [`PreparedTextLayout::render_text`].
    pub render_text: OnceCell<(Arc<RenderString>, PackedU64)>,
    pub(crate) visual_style_hash: OnceCell<PackedU64>,
    // The layout as a draw scope carries it, made on first use.
    layout_handle: OnceCell<TextLayoutHandle>,
}

impl PreparedTextLayout {
    // The prepared layout of `text` in `style` laid out as `layout`, `max_width`
    // the widest it could be.
    fn new(
        text: Rc<AnnotatedString>,
        style: Arc<TextStyle>,
        layout: TextLayout,
        (max_width, min_lines): (f32, usize),
    ) -> Self {
        Self {
            max_width,
            min_lines: u32::try_from(min_lines).unwrap_or(u32::MAX),
            text,
            visual_style: style,
            layout,
            render_text: OnceCell::new(),
            visual_style_hash: OnceCell::new(),
            layout_handle: OnceCell::new(),
        }
    }

    /// The paragraph's width, within the widths it was laid out between, and
    /// the height of all its lines together.
    pub fn size(&self) -> Size {
        Size::new(
            self.layout.width().min(self.max_width),
            self.layout.height(),
        )
    }

    // The max widths at which the text laid out from `min_width` gives this
    // layout again: its lines, its width and its size the same.
    pub(crate) fn max_widths_kept(&self, min_width: f32) -> cranpose_ui_layout::BoundRange {
        let width = self.layout.width();
        // A paragraph wider than its max measures as the max, which moves
        // with it.
        if self.max_width < width {
            return cranpose_ui_layout::BoundRange::exactly(self.max_width);
        }
        let (low, high) = self.layout.max_widths_kept(min_width);
        cranpose_ui_layout::BoundRange {
            low: low.max(width),
            high,
        }
    }

    /// Size and line count.
    pub fn metrics(&self) -> TextMetrics {
        let layout = &self.layout;
        let size = self.size();
        TextMetrics {
            width: size.width,
            height: size.height,
            line_height: layout.line_advance(),
            line_count: layout
                .line_count()
                .max(usize::try_from(self.min_lines).unwrap_or(usize::MAX)),
        }
    }

    /// The first and last baselines.
    pub fn alignment_lines(&self) -> cranpose_ui_layout::AlignmentLines {
        let layout = &self.layout;
        cranpose_ui_layout::AlignmentLines::new(
            Some(layout.line_baseline(0)),
            Some(layout.line_baseline(layout.line_count() - 1)),
        )
    }

    /// True when the text did not fit: it had more lines than the line limit,
    /// or was wider than the widest it could be.
    pub fn did_overflow(&self) -> bool {
        self.layout.did_overflow_height() || self.layout.did_overflow_width()
    }

    // The layout as a draw scope carries it to a renderer, made once for
    // every frame that draws the same text.
    pub(crate) fn layout_handle(&self) -> TextLayoutHandle {
        self.layout_handle
            .get_or_init(|| TextLayoutHandle::from(Arc::new(self.layout.clone())))
            .clone()
    }

    // This layout at `widths`, at which it breaks into the same lines: itself when its width there is its own, else a copy whose
    // lines `align` places across that width. The copy keeps the text as a
    // renderer draws it and the style's hash, and takes the allocation of
    // `spare` when nothing else holds it.
    pub(crate) fn at_widths(
        self: &Rc<Self>,
        widths: (f32, f32),
        align: TextAlign,
        spare: Option<Rc<Self>>,
    ) -> Rc<Self> {
        let width = self.layout.width_between(widths.0, widths.1);
        if width.to_bits() == self.layout.width().to_bits() {
            return Rc::clone(self);
        }
        self.aligned_at(widths, align, spare)
    }

    // The copy `at_widths` makes. Out of line: the copy costs more than the
    // call, and a layout held at its own width takes none.
    #[inline(never)]
    fn aligned_at(
        self: &Rc<Self>,
        widths: (f32, f32),
        align: TextAlign,
        spare: Option<Rc<Self>>,
    ) -> Rc<Self> {
        let mut aligned = Self {
            min_lines: self.min_lines,
            render_text: self.render_text.clone(),
            visual_style_hash: self.visual_style_hash.clone(),
            ..Self::new(
                Rc::clone(&self.text),
                Arc::clone(&self.visual_style),
                self.layout.clone(),
                (self.max_width, 0),
            )
        };
        aligned.realign(widths, align);
        if let Some(mut spare) = spare
            && let Some(slot) = Rc::get_mut(&mut spare)
        {
            *slot = aligned;
            return spare;
        }
        Rc::new(aligned)
    }

    // Places the lines across `(min_width, max_width)`, at which the layout
    // breaks into the same lines, as `align` says.
    pub(crate) fn realign(&mut self, (min_width, max_width): (f32, f32), align: TextAlign) {
        self.layout.align(min_width, max_width, align);
        self.max_width = max_width;
        self.layout_handle = OnceCell::new();
    }

    // `realign` when the layout breaks into the same lines between
    // `(min_width, max_width)`; `false`, leaving it as it was, when not.
    pub(crate) fn try_realign(
        &mut self,
        (min_width, max_width): (f32, f32),
        align: TextAlign,
    ) -> bool {
        let held = self.layout.try_align(min_width, max_width, align);
        if held {
            self.max_width = max_width;
            self.layout_handle = OnceCell::new();
        }
        held
    }

    /// The display text as a renderer draws it. Converted once for the layout
    /// and shared after, so every frame and scene rebuild drawing this layout
    /// hands over the same allocation.
    pub fn render_text(&self) -> Arc<RenderString> {
        if let Some((converted, _)) = self.render_text.get() {
            return Arc::clone(converted);
        }
        self.convert_render_text().0
    }

    /// [`RenderString::render_hash`](crate::text::RenderString::render_hash)
    /// of [`PreparedTextLayout::render_text`], kept beside it so that reading
    /// it never loads the string.
    pub fn render_text_hash(&self) -> u64 {
        if let Some((_, hash)) = self.render_text.get() {
            return hash.get();
        }
        self.convert_render_text().1
    }

    fn convert_render_text(&self) -> (Arc<RenderString>, u64) {
        let converted = Arc::new(self.text.render_string());
        let hash = converted.render_hash();
        let _ = self
            .render_text
            .set((Arc::clone(&converted), PackedU64::new(hash)));
        (converted, hash)
    }

    /// [`TextStyle::render_hash`] of `visual_style`, hashed once for the
    /// layout, or handed over by the node that knows its style's hash.
    pub fn visual_style_hash(&self) -> u64 {
        if let Some(hash) = self.visual_style_hash.get() {
            return hash.get();
        }
        let hash = self.visual_style.render_hash();
        let _ = self.visual_style_hash.set(PackedU64::new(hash));
        hash
    }

    /// The layout's queries, as Compose's `TextLayoutResult` gives them.
    pub fn result(&self) -> TextLayoutResult {
        TextLayoutResult::new(self.layout.clone())
    }
}

impl PartialEq for PreparedTextLayout {
    fn eq(&self, other: &Self) -> bool {
        self.text == other.text
            && self.visual_style == other.visual_style
            && self.metrics() == other.metrics()
            && self.alignment_lines() == other.alignment_lines()
            && self.did_overflow() == other.did_overflow()
    }
}

/// The text and style a layout is prepared from: borrowed, which the layout
/// copies, or shared with the node that holds them.
#[derive(Clone, Copy)]
enum LayoutSource<'a> {
    Borrowed {
        text: &'a AnnotatedString,
        style: &'a TextStyle,
    },
    Shared {
        text: &'a SharedText<'a>,
        // A layout of the text in the style at other widths, whose glyphs a
        // new layout takes in place of shaping the text again.
        shaped: Option<&'a TextLayout>,
    },
}

// A text and style a node holds, and the style's render hash.
pub(crate) struct SharedText<'a> {
    pub(crate) text: &'a Rc<AnnotatedString>,
    pub(crate) style: &'a Arc<TextStyle>,
    pub(crate) style_hash: u64,
}

impl LayoutSource<'_> {
    fn text(&self) -> &AnnotatedString {
        match self {
            Self::Borrowed { text, .. } => text,
            Self::Shared { text, .. } => text.text,
        }
    }

    fn style(&self) -> &TextStyle {
        match self {
            Self::Borrowed { style, .. } => style,
            Self::Shared { text, .. } => text.style,
        }
    }

    fn shared(&self) -> (Rc<AnnotatedString>, Arc<TextStyle>) {
        match self {
            Self::Borrowed { text, style } => {
                (Rc::new((*text).clone()), Arc::new((*style).clone()))
            }
            Self::Shared { text, .. } => (Rc::clone(text.text), Arc::clone(text.style)),
        }
    }

    fn style_hash(&self) -> u64 {
        match self {
            Self::Borrowed { style, .. } => style.render_hash(),
            Self::Shared { text, .. } => text.style_hash,
        }
    }

    fn shaped(&self) -> Option<&TextLayout> {
        match self {
            Self::Borrowed { .. } => None,
            Self::Shared { shaped, .. } => *shaped,
        }
    }
}

/// The widths a text lays out between, and its options.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct TextFrame {
    pub(crate) min_width: f32,
    pub(crate) max_width: f32,
    pub(crate) options: TextLayoutOptions,
}

impl TextFrame {
    // No width limit, lines ending only at line breaks.
    fn unbounded(options: TextLayoutOptions) -> Self {
        Self {
            min_width: 0.0,
            max_width: f32::INFINITY,
            options,
        }
    }

    // From zero up to `max_width`; `None`, and a width that is not positive
    // and finite, is no limit.
    pub(crate) fn up_to(max_width: Option<f32>, options: TextLayoutOptions) -> Self {
        Self {
            max_width: max_width
                .filter(|width| width.is_finite() && *width > 0.0)
                .unwrap_or(f32::INFINITY),
            ..Self::unbounded(options)
        }
    }
}

/// The app's fonts and the text engine its text lays out with, and the
/// layouts and intrinsic widths recent passes used.
pub(crate) struct TextService {
    generation: Cell<u64>,
    /// Whether a frame started since the last pass began: the first use of
    /// the service outside a layout pass then begins one.
    pass_owed: Cell<bool>,
    fonts: RefCell<FontFamilyResolver>,
    layouter: RefCell<TextLayouter>,
    layouts: RefCell<LayoutCache>,
    intrinsics: RefCell<PassAgedCache<TextKey, ParagraphIntrinsics>>,
}

impl TextService {
    pub(crate) fn new() -> Self {
        Self {
            generation: Cell::new(1),
            pass_owed: Cell::new(false),
            fonts: RefCell::new(default_fonts()),
            layouter: RefCell::new(TextLayouter::default()),
            layouts: RefCell::new(LayoutCache::new()),
            intrinsics: RefCell::new(PassAgedCache::with_capacity_at_least_one(
                TEXT_INTRINSICS_CACHE_CAPACITY,
            )),
        }
    }

    /// Lays text out with `fonts` from now on.
    pub(crate) fn set_fonts(&self, fonts: FontFamilyResolver) {
        *self.fonts.borrow_mut() = fonts;
        self.generation
            .set(self.generation.get().wrapping_add(1).max(1));
        self.layouts.borrow_mut().clear();
        self.intrinsics.borrow_mut().clear();
    }

    pub(crate) fn generation(&self) -> u64 {
        self.generation.get()
    }

    // The layout of `source` in `frame` with sizes in `units`: a cached one
    // that breaks into the same lines, aligned to the frame's widths, or a
    // new one.
    fn prepare(
        &self,
        source: LayoutSource<'_>,
        frame: TextFrame,
        (units, admission): (TextUnits, CacheAdmission),
    ) -> Rc<PreparedTextLayout> {
        let (text, style) = (source.text(), source.style());
        let key = TextKey::of(text, source.style_hash(), frame.options, units);
        let cached = key.map(|key| {
            let cached = self
                .layouts
                .borrow_mut()
                .cached(key, frame, (style, admission));
            (key, cached)
        });
        let missed = match cached {
            Some((_, Cached::Held(prepared))) => return prepared,
            Some((key, Cached::Missed(miss))) => Some((key, miss)),
            None => None,
        };
        let (text, style) = source.shared();
        let prepared = Rc::new(self.lay_out(text, style, frame, (units, source.shaped())));
        if let Some((key, miss)) = missed {
            self.layouts
                .borrow_mut()
                .keep(key, &prepared, (miss, admission));
        }
        prepared
    }

    // Lays `text` out in `style`, auto-sizing it when its options ask, with
    // the glyphs of `shaped` when given.
    fn lay_out(
        &self,
        text: Rc<AnnotatedString>,
        style: Arc<TextStyle>,
        frame: TextFrame,
        (units, shaped): (TextUnits, Option<&TextLayout>),
    ) -> PreparedTextLayout {
        let options = frame.options.normalized();
        let min_lines = options.min_lines;
        let Some(min_font_size_sp) = options.overflow.scale_down_min_font_size_sp() else {
            let layout = self.layout(&text, &style, frame, (units, shaped));
            return PreparedTextLayout::new(text, style, layout, (frame.max_width, min_lines));
        };
        self.lay_out_scaled_down(text, style, frame, (units, shaped), min_font_size_sp)
    }

    // Lays `text` out in `style` at the largest size from `min_font_size_sp`
    // up that fits `frame`. Out of line: its layouts stay off the stack of
    // the common layout, which shaping runs at the bottom of.
    #[inline(never)]
    fn lay_out_scaled_down(
        &self,
        text: Rc<AnnotatedString>,
        style: Arc<TextStyle>,
        frame: TextFrame,
        (units, shaped): (TextUnits, Option<&TextLayout>),
        min_font_size_sp: f32,
    ) -> PreparedTextLayout {
        let options = frame.options.normalized();
        let min_lines = options.min_lines;
        let frame = TextFrame {
            options: TextLayoutOptions {
                overflow: TextOverflow::Clip,
                ..options
            },
            ..frame
        };
        let fits =
            |layout: &TextLayout| !layout.did_overflow_height() && !layout.did_overflow_width();
        let full = self.layout(&text, &style, frame, (units, shaped));
        let base = style.resolve_font_size(DEFAULT_FONT_SIZE_SP);
        let min_factor = (min_font_size_sp.min(base) / base).clamp(0.0, 1.0);
        if fits(&full) || !frame.max_width.is_finite() || min_factor >= 1.0 {
            return PreparedTextLayout::new(text, style, full, (frame.max_width, min_lines));
        }
        // Each size takes the glyphs of the first: shaping is the same at
        // every size.
        let at = |factor: f32| {
            let units = TextUnits {
                factor: units.factor * factor,
                ..units
            };
            self.layout(&text, &style, frame, (units, Some(&full)))
        };
        let (mut best, mut factor) = (at(min_factor), min_factor);
        if fits(&best) {
            let (mut low, mut high) = (min_factor, 1.0);
            for _ in 0..SCALE_DOWN_SEARCH_STEPS {
                let mid = (low + high) * 0.5;
                let candidate = at(mid);
                if fits(&candidate) {
                    low = mid;
                    (best, factor) = (candidate, mid);
                } else {
                    high = mid;
                }
            }
        }
        let (text, style) = scaled_drawing(&text, &style, factor);
        PreparedTextLayout::new(text, style, best, (frame.max_width, min_lines))
    }

    // One layout of `text` in `style` in `frame`, with sizes in `units`, with
    // the glyphs of `shaped` when given.
    fn layout(
        &self,
        text: &AnnotatedString,
        style: &TextStyle,
        frame: TextFrame,
        (units, shaped): (TextUnits, Option<&TextLayout>),
    ) -> TextLayout {
        let paragraph = ParagraphSpans::new(text, style, units);
        let fonts = self.fonts.borrow();
        let spans = paragraph.spans(&fonts);
        let input = LayoutInput {
            text: &text.text,
            spans: &spans,
            paragraph: &style.paragraph_style,
            lengths: paragraph.lengths,
            min_width: frame.min_width,
            max_width: frame.max_width,
            options: frame.options,
        };
        let mut layouter = self.layouter.borrow_mut();
        match shaped {
            Some(shaped) => layouter.relayout(&input, &fonts, shaped),
            None => layouter.layout(&input, &fonts),
        }
    }

    // The intrinsic widths of `text` in `style`, with sizes in `units`.
    fn intrinsics(
        &self,
        text: &AnnotatedString,
        style: &TextStyle,
        units: TextUnits,
    ) -> ParagraphIntrinsics {
        let key = TextKey::of(
            text,
            style.measurement_hash(),
            TextLayoutOptions::default(),
            units,
        );
        if let Some(key) = key
            && let Some(found) = self.intrinsics.borrow_mut().get(&key).copied()
        {
            return found;
        }
        let paragraph = ParagraphSpans::new(text, style, units);
        let fonts = self.fonts.borrow();
        let spans = paragraph.spans(&fonts);
        let input = LayoutInput {
            text: &text.text,
            spans: &spans,
            paragraph: &style.paragraph_style,
            lengths: paragraph.lengths,
            min_width: 0.0,
            max_width: f32::INFINITY,
            options: TextLayoutOptions::default(),
        };
        let found = self.layouter.borrow_mut().intrinsics(&input, &fonts);
        if let Some(key) = key {
            self.intrinsics.borrow_mut().push(key, found);
        }
        found
    }

    // The extent of `style`'s own font with sizes in `units`: its ascent,
    // descent and line gap in pixels. `None` with no font.
    fn extent(&self, style: &TextStyle, units: TextUnits) -> Option<FontExtent> {
        let span = &style.span_style;
        let size = units
            .density
            .font_scale_curve()
            .sp_to_dp(style.resolve_font_size(DEFAULT_FONT_SIZE_SP))
            * units.factor;
        let fonts = self.fonts.borrow();
        let typeface = fonts.resolve(FontRequest {
            family: span.font_family.as_ref().unwrap_or(&FontFamily::Default),
            weight: span.font_weight.unwrap_or(FontWeight::NORMAL),
            style: span.font_style.unwrap_or(FontStyle::Normal),
        })?;
        let scale = size / f32::from(typeface.units_per_em());
        let metrics = typeface.line_metrics();
        Some(FontExtent::new(
            metrics.ascent * scale,
            -metrics.descent * scale,
            metrics.line_gap * scale,
        ))
    }

    // The box of a line of `style`'s own font with sizes in `units`, before
    // any text: its advance, baseline and edges. `None` with no font.
    fn line_box(&self, style: &TextStyle, units: TextUnits) -> Option<LineBox> {
        let extent = self.extent(style, units)?;
        let empty = AnnotatedString::from("");
        let paragraph = ParagraphSpans::new(&empty, style, units);
        let asked = paragraph.lengths.line_height.unwrap_or(f32::NAN);
        Some(paragraph_line_box(
            &style.paragraph_style,
            extent,
            asked,
            units.density.density(),
        ))
    }

    /// Starts a layout pass: the caches drop what recent passes did not use.
    pub(crate) fn begin_layout_pass(&self) {
        self.pass_owed.set(false);
        let headroom = crate::current_memory_headroom();
        // A tight heap keeps only what the last pass asked for.
        let idle_passes = match headroom {
            MemoryHeadroom::Ample => IDLE_PASSES,
            MemoryHeadroom::Tight => 1,
        };
        self.layouts.borrow_mut().begin_pass(idle_passes, headroom);
        self.intrinsics.borrow_mut().begin_pass(idle_passes, drop);
        self.layouter.borrow_mut().set_memory_headroom(headroom);
    }

    /// A frame starts: the first use of the service in it outside a layout
    /// pass begins a pass.
    pub(crate) fn owe_pass(&self) {
        self.pass_owed.set(true);
    }

    /// Begins the pass a frame owes, if no layout pass began one: what a
    /// frame that only draws measures then ages out as a layout pass's does.
    pub(crate) fn pay_owed_pass(&self) {
        if self.pass_owed.get() {
            self.begin_layout_pass();
        }
    }
}

// The fonts text lays out with before a renderer hands the app its own:
// none, and Cranpose Test Mono in tests.
fn default_fonts() -> FontFamilyResolver {
    #[cfg(any(test, feature = "test-helpers"))]
    {
        super::test_fonts()
    }
    #[cfg(not(any(test, feature = "test-helpers")))]
    {
        FontFamilyResolver::new([])
    }
}

// `text` and `style` as a text scaled down by `factor` draws them: sizes,
// shadows and strokes `factor` of what they say, as its glyphs are. A text
// whose spans scale nothing keeps its own string.
fn scaled_drawing(
    text: &Rc<AnnotatedString>,
    style: &TextStyle,
    factor: f32,
) -> (Rc<AnnotatedString>, Arc<TextStyle>) {
    let mut scaled_style = style.clone();
    scaled_style.span_style.font_size =
        TextUnit::Sp(style.resolve_font_size(DEFAULT_FONT_SIZE_SP) * factor);
    scale_span_drawing(&mut scaled_style.span_style, factor);
    let text = if text.span_styles.is_empty() {
        Rc::clone(text)
    } else {
        let mut scaled = AnnotatedString::clone(text);
        for span in &mut scaled.span_styles {
            if let TextUnit::Sp(size) = span.item.font_size {
                span.item.font_size = TextUnit::Sp(size * factor);
            }
            scale_span_drawing(&mut span.item, factor);
        }
        Rc::new(scaled)
    };
    (text, Arc::new(scaled_style))
}

// Scales the letter spacing, shadow and stroke of `span` by `factor`.
fn scale_span_drawing(span: &mut SpanStyle, factor: f32) {
    if let TextUnit::Sp(spacing) = span.letter_spacing {
        span.letter_spacing = TextUnit::Sp(spacing * factor);
    }
    if let Some(shadow) = &mut span.shadow {
        shadow.offset.x *= factor;
        shadow.offset.y *= factor;
        shadow.blur_radius *= factor;
    }
    if let Some(TextDrawStyle::Stroke { width }) = &mut span.draw_style {
        *width *= factor;
    }
}

// Text sizes at the host's density and font scale.
fn host_units() -> TextUnits {
    TextUnits {
        density: Density::from_host(),
        factor: 1.0,
    }
}

// Text sizes taken as stated, on the host's pixel grid: a draw scope's text
// style has its sizes resolved already.
fn resolved_units() -> TextUnits {
    TextUnits {
        density: Density::with_curve(Density::from_host().density(), FontScaleCurve::linear(1.0)),
        factor: 1.0,
    }
}

fn prepare_borrowed(
    text: &AnnotatedString,
    style: &TextStyle,
    frame: TextFrame,
    units: TextUnits,
) -> Rc<PreparedTextLayout> {
    crate::render_state::with_text_service(|service| {
        service.prepare(
            LayoutSource::Borrowed { text, style },
            frame,
            (units, CacheAdmission::First),
        )
    })
}

/// Lays text out with `fonts` in the active app context from now on. Panics
/// when no app context is active.
pub fn set_text_fonts(fonts: FontFamilyResolver) {
    let Some(context) = crate::render_state::current_app_context() else {
        panic!("set_text_fonts requires an active AppContext");
    };
    context.set_text_fonts(fonts);
}

/// Measures `text` in `style` with line breaks only at its line breaks, at
/// the system font scale.
pub fn measure_text(text: &AnnotatedString, style: &TextStyle) -> TextMetrics {
    prepare_borrowed(
        text,
        style,
        TextFrame::unbounded(TextLayoutOptions::default()),
        host_units(),
    )
    .metrics()
}

// `text` laid out in its style with lines ending only at its line breaks,
// the style's sizes taken as stated, not scaled by the system font scale, as
// a draw scope draws it: the cache keeps it while the last pass drew it,
// and longer once it comes back, so a number drawn anew each frame takes
// little room in it.
pub(crate) fn prepare_resolved(text: &SharedText<'_>) -> Rc<PreparedTextLayout> {
    crate::render_state::with_text_service(|service| {
        service.prepare(
            LayoutSource::Shared { text, shaped: None },
            TextFrame::unbounded(TextLayoutOptions::default()),
            (resolved_units(), CacheAdmission::Drawn),
        )
    })
}

/// Measures `text` wrapped to `max_width` under `options`. `None` and widths
/// that are not positive and finite mean no width limit.
pub fn measure_text_with_options(
    text: &AnnotatedString,
    style: &TextStyle,
    options: TextLayoutOptions,
    max_width: Option<f32>,
) -> TextMetrics {
    prepare_borrowed(
        text,
        style,
        TextFrame::up_to(max_width, options),
        host_units(),
    )
    .metrics()
}

/// Lays `text` out in `style` wrapped to `max_width` under `options`.
pub fn prepare_text_layout(
    text: &AnnotatedString,
    style: &TextStyle,
    options: TextLayoutOptions,
    max_width: Option<f32>,
) -> Rc<PreparedTextLayout> {
    prepare_borrowed(
        text,
        style,
        TextFrame::up_to(max_width, options),
        host_units(),
    )
}

// Lays out `text` in `style` between the widths of `frame`, sharing them,
// kept by the shared cache as `admission` says.
pub(crate) fn prepare_shared(
    text: &SharedText<'_>,
    frame: TextFrame,
    admission: CacheAdmission,
    shaped: Option<&TextLayout>,
) -> Rc<PreparedTextLayout> {
    crate::render_state::with_text_service(|service| {
        service.prepare(
            LayoutSource::Shared { text, shaped },
            frame,
            (host_units(), admission),
        )
    })
}

/// The byte offset of the caret nearest to the point (`x`, `y`) of `text`
/// laid out in `style` with lines ending only at its line breaks, in logical
/// pixels from its top left corner.
pub fn get_offset_for_position(text: &AnnotatedString, style: &TextStyle, x: f32, y: f32) -> usize {
    prepare_borrowed(
        text,
        style,
        TextFrame::unbounded(TextLayoutOptions::default()),
        host_units(),
    )
    .layout
    .offset_for_position(x, y)
}

/// The byte offset of the caret nearest to the point (`x`, `y`) of `text`
/// laid out in `style` and wrapped to `wrap_width`: the hit test of every
/// editable text's pointer path. `x` and `y` are in text space, padding and
/// scrolling taken off.
pub fn offset_for_position_wrapped(
    text: &str,
    style: &TextStyle,
    wrap_width: Option<f32>,
    x: f32,
    y: f32,
) -> usize {
    prepare_borrowed(
        &AnnotatedString::from(text),
        style,
        TextFrame::up_to(wrap_width, TextLayoutOptions::default()),
        host_units(),
    )
    .layout
    .offset_for_position(x, y)
}

/// The x of the caret at byte `offset` of `text` laid out in `style` with
/// lines ending only at its line breaks.
pub fn get_cursor_x_for_offset(text: &AnnotatedString, style: &TextStyle, offset: usize) -> f32 {
    prepare_borrowed(
        text,
        style,
        TextFrame::unbounded(TextLayoutOptions::default()),
        host_units(),
    )
    .layout
    .horizontal_position(offset, CaretDirection::Primary)
}

/// Lays `text` out in `style` with lines ending only at its line breaks.
pub fn layout_text(text: &AnnotatedString, style: &TextStyle) -> TextLayoutResult {
    prepare_borrowed(
        text,
        style,
        TextFrame::unbounded(TextLayoutOptions::default()),
        host_units(),
    )
    .result()
}

/// The byte range of each line of `text` laid out at `max_width` with
/// `options`, without its line break.
pub fn wrapped_line_ranges(
    text: &AnnotatedString,
    style: &TextStyle,
    options: TextLayoutOptions,
    max_width: Option<f32>,
) -> Vec<Range<usize>> {
    let prepared = prepare_borrowed(
        text,
        style,
        TextFrame::up_to(max_width, options),
        host_units(),
    );
    let layout = &prepared.layout;
    (0..layout.line_count())
        .map(|line| {
            let (start, end) = (layout.line_start(line), layout.line_end(line));
            let line_text = text.text.get(start..end).unwrap_or_default();
            let without_break = line_text.trim_end_matches(['\n', '\r', '\u{2028}', '\u{2029}']);
            start..start + without_break.len()
        })
        .collect()
}

/// The widest word of `text` in `style`: Compose's
/// `ParagraphIntrinsics.minIntrinsicWidth`.
pub(crate) fn min_intrinsic_text_width(text: &AnnotatedString, style: &TextStyle) -> f32 {
    crate::render_state::with_text_service(|service| service.intrinsics(text, style, host_units()))
        .min_intrinsic_width
}

/// The line box of `style`'s own font: its advance, its baseline and what a
/// paragraph gives back at its edges. `None` with no font.
pub fn text_line_box(style: &TextStyle) -> Option<LineBox> {
    crate::render_state::with_text_service(|service| service.line_box(style, host_units()))
}

/// Like [`text_line_box`] with `style`'s sizes taken as stated.
pub(crate) fn resolved_line_box(style: &TextStyle) -> Option<LineBox> {
    crate::render_state::current_app_context()?;
    crate::render_state::with_text_service(|service| service.line_box(style, resolved_units()))
}

/// Distance from the top of a `style` paragraph down to its first baseline.
/// `None` with no font.
pub fn first_baseline(style: &TextStyle) -> Option<f32> {
    text_line_box(style).map(LineBox::first_baseline)
}

/// The glyph box `(top_offset, height)` of a `style` line inside a line
/// `line_height` tall, where lines stack from the paragraph's top one advance
/// apart: the font's ascent and descent under the first line's baseline. The
/// whole line with no font.
pub fn glyph_line_box(style: &TextStyle, line_height: f32) -> (f32, f32) {
    let units = host_units();
    crate::render_state::with_text_service(|service| {
        let extent = service.extent(style, units)?;
        let line_box = service.line_box(style, units)?;
        Some((
            line_box.first_baseline() - extent.ascent,
            extent.ascent + extent.descent,
        ))
    })
    .map_or((0.0, line_height), |(top, height)| {
        (top.clamp(0.0, line_height), height.min(line_height))
    })
}

#[cfg(test)]
#[path = "tests/measure_tests.rs"]
mod tests;