cranpose-ui 0.28.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
use std::{
    cell::{Cell, RefCell},
    ops::Range,
    rc::Rc,
    sync::Arc,
};

use cranpose_core::collections::pass_aged::{IDLE_PASSES, PassAgedCache};
use cranpose_text::{
    CaretDirection, FontExtent, FontFamily, FontFamilyResolver, FontRequest, FontStyle, FontWeight,
    LayoutInput, ParagraphIntrinsics, RenderString, Retired, TextLayout, TextLayouter,
    paragraph_line_box,
};
use cranpose_ui_graphics::{DEFAULT_FONT_SIZE, MemoryHeadroom, Point};

pub use super::prepared_text_layout::PreparedTextLayout;
use super::{
    AnnotatedString, LineBox, SpanStyle, TextDrawStyle, TextUnit,
    layout_cache::{CacheAdmission, Cached, LayoutCache, Miss},
    layout_input::{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;
// The most retired layouts and strings kept. A layout a text gave up stays
// in the scene until the next frame is drawn, so the next frame's texts take
// the layouts retired the frame before: the pool holds two frames of
// changed texts, the gauntlet's 480 a frame among them.
const RETIRED_LAYOUTS: usize = 4096;
const RETIRED_STRINGS: usize = 4096;
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,
}

/// 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 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_style(&self) -> Arc<TextStyle> {
        match self {
            Self::Borrowed { style, .. } => Arc::new((*style).clone()),
            Self::Shared { 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)
        }
    }

    // Exactly `width`, the width of a node's content, which the renderer
    // draws its text at. A node not laid out yet has no width, and no limit.
    pub(crate) fn drawn(width: f32, options: TextLayoutOptions) -> Self {
        if width.is_finite() && width > 0.0 {
            Self {
                min_width: width,
                max_width: width,
                options,
            }
        } else {
            Self::up_to(None, 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>>,
    // The prepared layouts of texts that changed: a layout whose lines no
    // scene or packet holds any more takes a new text in its allocation and
    // in its lines' storage.
    retired: RefCell<Retired<Rc<PreparedTextLayout>>>,
    retired_strings: RefCell<Retired<Arc<RenderString>>>,
}

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,
            )),
            retired: RefCell::new(Retired::new(RETIRED_LAYOUTS)),
            retired_strings: RefCell::new(Retired::new(RETIRED_STRINGS)),
        }
    }

    /// 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,
        };
        self.prepare_missed(source, frame, (units, admission), missed)
    }

    // Lays out `source` the cache did not hold and keeps it as `missed`
    // says. Out of line: a text that shows what it showed before stops
    // before it, and inlined it takes room in the cache's lookup.
    #[inline(never)]
    fn prepare_missed(
        &self,
        source: LayoutSource<'_>,
        frame: TextFrame,
        (units, admission): (TextUnits, CacheAdmission),
        missed: Option<(TextKey, Miss)>,
    ) -> Rc<PreparedTextLayout> {
        let prepared = self
            .lay_out_retired(&source, frame, units)
            .unwrap_or_else(|| {
                let style = source.shared_style();
                Rc::new(self.lay_out(source.text(), style, frame, (units, source.shaped())))
            });
        if let Some((key, miss)) = missed {
            let let_go = self
                .layouts
                .borrow_mut()
                .keep(key, &prepared, (miss, admission));
            if let Some(layout) = let_go {
                self.retire_evicted(layout);
            }
        }
        prepared
    }

    // Keeps `text` and `layouts`, what a text that changed gave up, for the
    // next changed texts.
    pub(crate) fn retire(
        &self,
        text: AnnotatedString,
        layouts: impl IntoIterator<Item = Rc<PreparedTextLayout>>,
    ) {
        // A layout something else holds, as the shared cache does, stays
        // with it and with the string it was laid out from: no changed text
        // could take that string while it does. A layout the text alone held
        // lets go of its string, which the text gives up below.
        let mut kept_string = false;
        {
            let mut retired = self.retired.borrow_mut();
            for mut layout in layouts {
                match Rc::get_mut(&mut layout) {
                    Some(free) => {
                        free.take_text();
                        retired.retire(layout);
                    }
                    None => kept_string |= Arc::ptr_eq(&layout.text, text.render_string()),
                }
            }
        }
        if !kept_string {
            self.retired_strings.borrow_mut().retire_text(text);
        }
    }

    // Keeps `layout`, which the shared cache let go, for the next changed
    // texts when nothing else holds it, and its string when nothing else
    // holds that. Out of line: few misses make the cache let go a layout
    // that nothing else holds.
    #[inline(never)]
    fn retire_evicted(&self, mut layout: Rc<PreparedTextLayout>) {
        let Some(free) = Rc::get_mut(&mut layout) else {
            return;
        };
        let mut text = free.take_text();
        if Arc::get_mut(&mut text).is_some() {
            self.retired_strings
                .borrow_mut()
                .retire_text(AnnotatedString::from(text));
        }
        self.retired.borrow_mut().retire(layout);
    }

    // A plain string of `text`, in the room of a retired one nothing holds.
    pub(crate) fn plain_text(&self, text: &str) -> AnnotatedString {
        self.retired_strings.borrow_mut().plain(text)
    }

    // `plain_text` of a string the caller gives up, which keeps its own room
    // when no retired one is free.
    pub(crate) fn plain_string(&self, text: String) -> AnnotatedString {
        self.retired_strings.borrow_mut().plain_owned(text)
    }

    // `source` laid out in the allocation of a retired layout nothing holds
    // and in its lines' storage; `None` when no retired layout is free, or
    // `source` takes glyphs shaped before or sizes itself down.
    fn lay_out_retired(
        &self,
        source: &LayoutSource<'_>,
        frame: TextFrame,
        units: TextUnits,
    ) -> Option<Rc<PreparedTextLayout>> {
        let scales = frame.options.overflow.scale_down_min_font_size_sp();
        if source.shaped().is_some() || scales.is_some() {
            return None;
        }
        let mut spare = self
            .retired
            .borrow_mut()
            .take(|layout| Rc::get_mut(layout).is_some_and(|free| !free.layout.shares_lines()))?;
        let slot = Rc::get_mut(&mut spare)?;
        let (text, style) = (source.text(), source.shared_style());
        self.with_input(text, &style, frame, units, |layouter, input, fonts| {
            layouter.layout_into(input, fonts, &mut slot.layout);
        });
        slot.retext(text, style, frame);
        Some(spare)
    }

    // Lays `text` out in `style`, auto-sizing it when its options ask, with
    // the glyphs of `shaped` when given.
    fn lay_out(
        &self,
        text: &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: &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);
        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 {
        self.with_input(
            text,
            style,
            frame,
            units,
            |layouter, input, fonts| match shaped {
                Some(shaped) => layouter.relayout(input, fonts, shaped),
                None => layouter.layout(input, fonts),
            },
        )
    }

    // Runs `lay_out` on the layouter with the input of `text` in `style` in
    // `frame`, with sizes in `units`.
    fn with_input<R>(
        &self,
        text: &AnnotatedString,
        style: &TextStyle,
        frame: TextFrame,
        units: TextUnits,
        lay_out: impl FnOnce(&mut TextLayouter, &LayoutInput<'_>, &FontFamilyResolver) -> R,
    ) -> R {
        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,
        };
        lay_out(&mut self.layouter.borrow_mut(), &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 frame = TextFrame::unbounded(TextLayoutOptions::default());
        let found = self.with_input(text, style, frame, units, |layouter, input, fonts| {
            layouter.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))
            * 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,
        };
        let mut aged = self.layouts.borrow_mut().begin_pass(idle_passes, headroom);
        for layout in aged.drain(..) {
            self.retire_evicted(layout);
        }
        self.layouts.borrow_mut().give_back(aged);
        self.intrinsics.borrow_mut().begin_pass(idle_passes, drop);
        self.retired.borrow_mut().begin_pass(idle_passes);
        self.retired_strings.borrow_mut().begin_pass(idle_passes);
        self.layouter.borrow_mut().begin_pass(headroom);
    }

    // Drops the retired layouts and strings, the texts the cache waits to
    // see return and the layouter's glyph room a long text took: the texts
    // rest.
    pub(crate) fn trim(&self) {
        self.retired.borrow_mut().clear();
        self.retired_strings.borrow_mut().clear();
        self.layouts.borrow_mut().rest();
        self.layouter.borrow_mut().rest();
    }

    /// 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: &AnnotatedString,
    style: &TextStyle,
    factor: f32,
) -> (AnnotatedString, Arc<TextStyle>) {
    let mut scaled_style = style.clone();
    scaled_style.span_style.font_size =
        TextUnit::Sp(style.resolve_font_size(DEFAULT_FONT_SIZE) * factor);
    scale_span_drawing(&mut scaled_style.span_style, factor);
    let text = if text.span_styles().is_empty() {
        text.clone()
    } else {
        text.map_span_styles(|span| {
            if let TextUnit::Sp(size) = span.font_size {
                span.font_size = TextUnit::Sp(size * factor);
            }
            scale_span_drawing(span, factor);
        })
    };
    (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 nearest `point` of `text` as a node's content `width`
// wide draws it, in the content's coordinates.
pub(crate) fn offset_in_drawn_text(
    text: &AnnotatedString,
    style: &TextStyle,
    options: TextLayoutOptions,
    width: f32,
    point: Point,
) -> usize {
    prepare_borrowed(text, style, TextFrame::drawn(width, options), host_units())
        .layout
        .offset_for_position(point.x, point.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;