Skip to main content

gpui/fast/
text.rs

1// Modified by Longbridge for gpui-fast.
2//! Where a reused range of shaped lines falls in a new frame, text measurements
3//! carried from one frame to the next, and shaping statistics.
4
5use crate::fast::layout::Adopted;
6use crate::{
7    App, AvailableSpace, Bounds, DecorationRun, FontRun, FrameCache, Hsla, LayoutId, LineLayout,
8    LineLayoutCache, LineLayoutIndex, Pixels, PlatformTextSystem, SharedString, Size,
9    StrikethroughStyle, TextLayout, TextLayoutInner, TextOverflow, TextRun, TextStyle,
10    TruncateFrom, UnderlineStyle, WhiteSpace, Window, WindowTextSystem, WrappedLine,
11};
12use collections::{FxHashMap, FxHasher};
13use gpui_util::ResultExt as _;
14use parking_lot::Mutex;
15use scheduler::Instant;
16use smallvec::SmallVec;
17use std::{
18    any::Any,
19    borrow::Cow,
20    cell::RefCell,
21    cmp,
22    hash::{Hash, Hasher},
23    mem,
24    rc::Rc,
25    sync::Arc,
26    sync::atomic::{AtomicBool, AtomicU64, Ordering},
27};
28
29/// Everything a text element's measurement is taken from, and the layout it
30/// keeps the measurement in.
31///
32/// The element hands its text, runs and style over rather than copying them:
33/// its measurement closure reads them from here, and the next frame's element
34/// at the same place compares its own against them.
35pub(crate) struct TextMeasureInputs {
36    text: SharedString,
37    /// The runs the element was given, or none for plain text, which is one
38    /// run in the text style: that run is only made when the text has to be
39    /// shaped, rather than copying the style's font into every element.
40    runs: Vec<TextRun>,
41    /// The text style in effect, shared with the window's text style stack
42    /// and every other element under the same refinements.
43    text_style: Rc<TextStyle>,
44    font_size: Pixels,
45    line_height: Pixels,
46    /// The layout of the element whose inputs these are, or of a later one
47    /// that took the measurement over while leaving the node with these.
48    layout: RefCell<TextLayout>,
49}
50
51/// The decorations of a run: what it is painted with, and what shaping splits
52/// font runs on.
53fn decoration_of(
54    run: &TextRun,
55) -> (
56    Hsla,
57    Option<Hsla>,
58    Option<UnderlineStyle>,
59    Option<StrikethroughStyle>,
60) {
61    (
62        run.color,
63        run.background_color,
64        run.underline,
65        run.strikethrough,
66    )
67}
68
69/// The decorations of plain text in `style`, as [`decoration_of`] its run.
70fn style_decoration(
71    style: &TextStyle,
72) -> (
73    Hsla,
74    Option<Hsla>,
75    Option<UnderlineStyle>,
76    Option<StrikethroughStyle>,
77) {
78    (
79        style.color,
80        style.background_color,
81        style.underline,
82        style.strikethrough,
83    )
84}
85
86/// Whether two text styles have the same font: `style.font() ==
87/// other.font()`, without making either font.
88fn same_font(style: &TextStyle, other: &TextStyle) -> bool {
89    style.font_family == other.font_family
90        && style.font_features == other.font_features
91        && style.font_fallbacks == other.font_fallbacks
92        && style.font_weight == other.font_weight
93        && style.font_style == other.font_style
94}
95
96impl TextMeasureInputs {
97    /// Whether text truncates, in which case it is shaped from a rewritten
98    /// string whose runs no longer line up with these.
99    fn truncates(&self) -> bool {
100        self.text_style.text_overflow.is_some()
101    }
102
103    /// Whether this is plain text: one run in the text style.
104    fn plain(&self) -> bool {
105        self.runs.is_empty()
106    }
107
108    /// The runs the text is shaped and painted with.
109    fn runs(&self) -> Cow<'_, [TextRun]> {
110        if self.plain() {
111            Cow::Owned(vec![self.text_style.to_run(self.text.len())])
112        } else {
113            Cow::Borrowed(&self.runs)
114        }
115    }
116
117    /// Whether `self` is shaped as `other` is: the same text, sizes, fonts and
118    /// wrapping, and decoration changing in the same places, since shaping
119    /// splits font runs wherever it changes. What it is painted with may
120    /// differ; see [`Self::decorated_as`].
121    fn shapes_as(&self, other: &Self) -> bool {
122        fn runs(runs: &[TextRun]) -> impl Iterator<Item = &TextRun> {
123            runs.iter().filter(|run| run.len > 0)
124        }
125        fn joins_previous<'a>(
126            runs: impl Iterator<Item = &'a TextRun>,
127        ) -> impl Iterator<Item = bool> {
128            let mut previous = None;
129            runs.map(move |run| {
130                previous
131                    .replace(decoration_of(run))
132                    .is_some_and(|previous| previous == decoration_of(run))
133            })
134        }
135        let (style, other_style) = (&*self.text_style, &*other.text_style);
136        if !(self.text == other.text
137            && self.font_size == other.font_size
138            && self.line_height == other.line_height
139            && style.white_space == other_style.white_space
140            && style.line_clamp == other_style.line_clamp
141            && style.text_overflow == other_style.text_overflow
142            // Only truncation reads the style's own font.
143            && (!self.truncates() || same_font(style, other_style)))
144        {
145            return false;
146        }
147        if self.plain() && other.plain() {
148            // One run each, as long as the text, unless there is no text.
149            return self.text.is_empty() || same_font(style, other_style);
150        }
151        let (self_runs, other_runs) = (self.runs(), other.runs());
152        runs(&self_runs).count() == runs(&other_runs).count()
153            && runs(&self_runs)
154                .zip(runs(&other_runs))
155                .all(|(run, other)| run.len == other.len && run.font == other.font)
156            && joins_previous(runs(&self_runs)).eq(joins_previous(runs(&other_runs)))
157    }
158
159    /// Whether `self` is painted with what `other` is.
160    fn decorated_as(&self, other: &Self) -> bool {
161        if self.plain() && other.plain() {
162            return self.text.is_empty()
163                || style_decoration(&self.text_style) == style_decoration(&other.text_style);
164        }
165        let (self_runs, other_runs) = (self.runs(), other.runs());
166        self_runs
167            .iter()
168            .filter(|run| run.len > 0)
169            .map(decoration_of)
170            .eq(other_runs
171                .iter()
172                .filter(|run| run.len > 0)
173                .map(decoration_of))
174    }
175}
176
177/// Requests the layout of a text element, whose measurement it keeps in
178/// `layout`: what [`TextLayout`]'s layout does upstream.
179///
180/// A measured node is given a new closure every frame, and would be dirtied
181/// for it, with every node above it: a view built again would have all of its
182/// text measured and laid out again, though none of it changed. When last
183/// frame's element at this place measured text shaped the same way, its
184/// measurement is carried into this one's layout instead, repainted with this
185/// one's decorations if only they changed, and the node is left clean,
186/// keeping what Taffy cached for it.
187///
188/// If only the decorations changed, the node is given this element's inputs
189/// to measure from when Taffy measures it again under other constraints.
190/// Otherwise it keeps last frame's, which measure it the same way, only
191/// keeping the measurement in this element's layout from now on: rebuilding
192/// the closure and the inputs of every unchanged text element, and dropping
193/// last frame's, was most of what it cost.
194#[inline]
195pub(crate) fn layout_text(
196    layout: &TextLayout,
197    text: SharedString,
198    runs: Option<Vec<TextRun>>,
199    window: &mut Window,
200    cx: &mut App,
201) -> LayoutId {
202    let inputs = measure_inputs(layout, text, runs.unwrap_or_default(), window);
203    window.request_carried_measured_layout(
204        inputs,
205        adopt_measurement,
206        forget_measurement,
207        measure_text,
208        cx,
209    )
210}
211
212/// The inputs of text laid out in the text style in effect, keeping its
213/// measurement in `layout`.
214fn measure_inputs(
215    layout: &TextLayout,
216    text: SharedString,
217    runs: Vec<TextRun>,
218    window: &Window,
219) -> TextMeasureInputs {
220    let text_style = crate::fast::text_style::text_style(window);
221    let font_size = text_style.font_size.to_pixels(window.rem_size());
222    let line_height = window.pixel_snap(
223        text_style
224            .line_height
225            .to_pixels(font_size.into(), window.rem_size()),
226    );
227    TextMeasureInputs {
228        text,
229        runs,
230        text_style,
231        font_size,
232        line_height,
233        layout: RefCell::new(layout.clone()),
234    }
235}
236
237/// [`TextLayout`]'s prepaint: notes the bounds the text is painted in.
238///
239/// Text should be measured by the time it is prepainted: carried over from
240/// last frame as its layout is requested, or by Taffy as it lays the text's
241/// node out. Should a gap in retention let text reach prepaint without a
242/// measurement (a node no layout computed this frame reaches, say), upstream
243/// panics here. It is measured here instead, as plain text in the text style
244/// in effect at the size it is prepainted at, so that the frame degrades
245/// (the text loses its runs' colors and fonts for a frame) rather than the
246/// app aborting.
247pub(crate) fn prepaint_text(
248    layout: &TextLayout,
249    bounds: Bounds<Pixels>,
250    text: &str,
251    window: &mut Window,
252    cx: &mut App,
253) {
254    if layout.0.borrow().is_none() {
255        report_unmeasured(
256            "text reached prepaint unmeasured; measured there as plain text",
257            text,
258        );
259        let inputs = measure_inputs(
260            layout,
261            SharedString::from(text.to_owned()),
262            Vec::new(),
263            window,
264        );
265        // A node no layout reached has no size: lay the text out unwrapped
266        // rather than a glyph to a line.
267        let (known, available) = if bounds.size.width > Pixels::ZERO {
268            (
269                bounds.size.map(Some),
270                bounds.size.map(AvailableSpace::Definite),
271            )
272        } else {
273            (
274                Size::default(),
275                Size::new(AvailableSpace::MaxContent, AvailableSpace::MaxContent),
276            )
277        };
278        measure_text(&inputs, known, available, window, cx);
279    }
280    if let Some(inner) = layout.0.borrow_mut().as_mut() {
281        inner.bounds = Some(bounds);
282    }
283}
284
285/// Whether [`TextLayout`]'s paint can paint the text: it was measured and
286/// prepainted. Upstream panics when it was not; it is left unpainted instead.
287/// See [`prepaint_text`].
288pub(crate) fn paintable(layout: &TextLayout, text: &str) -> bool {
289    let paintable = layout
290        .0
291        .borrow()
292        .as_ref()
293        .is_some_and(|inner| inner.bounds.is_some());
294    if !paintable {
295        report_unmeasured(
296            "text painted before it was measured and prepainted; not painted",
297            text,
298        );
299    }
300    paintable
301}
302
303/// Whether [`report_unmeasured`] has reported anything in this process.
304static REPORTED_UNMEASURED: AtomicBool = AtomicBool::new(false);
305
306/// Logs text found unmeasured where it should not be: as an error the first
307/// time, and at debug level after that, since a frame that finds it is likely
308/// to be followed by many that find it again.
309fn report_unmeasured(what: &str, text: &str) {
310    const SHOWN_CHARS: usize = 32;
311    let mut shown: String = text.chars().take(SHOWN_CHARS).collect();
312    if text.chars().nth(SHOWN_CHARS).is_some() {
313        shown.push('…');
314    }
315    if REPORTED_UNMEASURED.swap(true, Ordering::Relaxed) {
316        log::debug!("{what}: {shown:?}");
317    } else {
318        log::error!("{what}: {shown:?}");
319    }
320}
321
322/// Takes over the measurement `previous` left, if it stands for `inputs`. See
323/// [`layout_text`].
324fn adopt_measurement(inputs: &TextMeasureInputs, previous: &dyn Any) -> Adopted {
325    let Some(previous) = previous.downcast_ref::<TextMeasureInputs>() else {
326        return Adopted::No;
327    };
328    if !previous.shapes_as(inputs) {
329        return Adopted::No;
330    }
331    let recolored = !previous.decorated_as(inputs);
332    if recolored && inputs.truncates() {
333        return Adopted::No;
334    }
335    let Some(mut inner) = carry_measurement(&previous.layout.borrow()) else {
336        return Adopted::No;
337    };
338    let layout = inputs.layout.borrow();
339    if recolored {
340        update_decoration_runs(&mut inner.lines, &inputs.runs());
341        *layout.0.borrow_mut() = Some(inner);
342        Adopted::Measurement
343    } else {
344        *layout.0.borrow_mut() = Some(inner);
345        // The node keeps `previous`, which now keeps its measurement where
346        // this element looks for it.
347        *previous.layout.borrow_mut() = layout.clone();
348        Adopted::Node
349    }
350}
351
352/// Drops the measurement `inputs` were left with, for text laid out afresh:
353/// [`measure_text`] answers from a measurement it holds, and one taken under
354/// another text's constraints would answer for those.
355fn forget_measurement(inputs: &TextMeasureInputs) {
356    inputs.layout.borrow().0.borrow_mut().take();
357}
358
359/// Measures text under the constraints Taffy offers, keeping the result in
360/// its layout: upstream's measurement, doing less of its work.
361///
362/// - Taffy asks a node for its intrinsic size before it lays the node out, so
363///   a wrapping leaf is measured unconstrained and then again at the width it
364///   ends up with. Text that came out narrower than the width now on offer
365///   wraps nowhere, and the lines shaped without a wrap width are the same
366///   lines, so that is answered from what is already there. The other way
367///   round holds only for text that wrapped nowhere at its width.
368/// - Which affix to truncate with, and the line wrapper truncation needs, are
369///   worked out only when the text truncates and has to be shaped: resolving
370///   the font and borrowing a wrapper from the pool on every measurement was
371///   for nothing on text that does not truncate.
372fn measure_text(
373    inputs: &TextMeasureInputs,
374    known_dimensions: Size<Option<Pixels>>,
375    available_space: Size<AvailableSpace>,
376    window: &mut Window,
377    cx: &mut App,
378) -> Size<Pixels> {
379    let TextMeasureInputs {
380        text,
381        runs: _,
382        text_style,
383        font_size,
384        line_height,
385        layout,
386    } = inputs;
387    let layout = &*layout.borrow();
388    let (font_size, line_height) = (*font_size, *line_height);
389    let wrap_width = if text_style.white_space == WhiteSpace::Normal {
390        known_dimensions.width.or(match available_space.width {
391            AvailableSpace::Definite(x) => Some(x),
392            _ => None,
393        })
394    } else {
395        None
396    };
397    let truncate_width = text_style.text_overflow.as_ref().and_then(|_| {
398        known_dimensions.width.or(match available_space.width {
399            AvailableSpace::Definite(x) => match text_style.line_clamp {
400                Some(max_lines) => Some(x * max_lines),
401                None => Some(x),
402            },
403            _ => None,
404        })
405    });
406
407    // A kept measurement answers when the wrap width is one it was taken at,
408    // an unconstrained probe when it wrapped nowhere, or a wrap width it fits
409    // within unwrapped, unless truncation is involved either way: a truncated
410    // layout would answer an unconstrained probe with the truncated size.
411    // Text wrapped at a width is only as wide as that width, and Taffy can
412    // measure a retained leaf narrow after laying it out (see
413    // `text_laid_out_from_the_cache_paints_the_lines_of_its_box`): answering
414    // an unconstrained probe with that would size a box as wide as its
415    // content to the narrow width, for good.
416    if let Some(text_layout) = layout.0.borrow().as_ref()
417        && let Some(size) = text_layout.size
418        && (wrap_width == text_layout.wrap_width
419            || (wrap_width.is_none()
420                && text_layout
421                    .lines
422                    .iter()
423                    .all(|line| line.wrap_boundaries.is_empty()))
424            || (text_layout.wrap_width.is_none()
425                && wrap_width.is_some_and(|wrap_width| size.width <= wrap_width)))
426        && truncate_width.is_none()
427        && text_layout.truncate_width.is_none()
428    {
429        return size;
430    }
431
432    let runs = inputs.runs();
433    let runs = &*runs;
434    let (text, runs) = if let Some(truncate_width) = truncate_width {
435        let (truncation_affix, truncate_from) = match text_style.text_overflow.clone() {
436            Some(TextOverflow::Truncate(affix)) => (affix, TruncateFrom::End),
437            Some(TextOverflow::TruncateStart(affix)) => (affix, TruncateFrom::Start),
438            Some(TextOverflow::TruncateMiddle(affix)) => (affix, TruncateFrom::Middle),
439            None => (SharedString::default(), TruncateFrom::End),
440        };
441        let mut line_wrapper = cx.text_system().line_wrapper(text_style.font(), font_size);
442        if let Some(max_lines) = text_style.line_clamp
443            && let Some(wrap_width) = wrap_width
444        {
445            line_wrapper.truncate_wrapped_line(
446                text.clone(),
447                wrap_width,
448                max_lines,
449                &truncation_affix,
450                runs,
451                truncate_from,
452            )
453        } else if let Some(unclipped) = window
454            .text_system()
455            .shape_text(text.clone(), font_size, runs, None, None)
456            .log_err()
457            && unclipped
458                .iter()
459                .all(|line| line.size(line_height).width <= truncate_width)
460        {
461            // Truncation sums per-character advances, which overestimates the
462            // shaped width, so text that fits once shaped is not truncated.
463            (text.clone(), Cow::Borrowed(runs))
464        } else {
465            line_wrapper.truncate_line(
466                text.clone(),
467                truncate_width,
468                &truncation_affix,
469                runs,
470                truncate_from,
471            )
472        }
473    } else {
474        (text.clone(), Cow::Borrowed(runs))
475    };
476    let len = text.len();
477
478    let Some(lines) = window
479        .text_system()
480        .shape_text(text, font_size, &runs, wrap_width, text_style.line_clamp)
481        .log_err()
482    else {
483        layout.0.borrow_mut().replace(TextLayoutInner {
484            lines: Default::default(),
485            len: 0,
486            line_height,
487            wrap_width,
488            truncate_width,
489            size: Some(Size::default()),
490            bounds: None,
491        });
492        return Size::default();
493    };
494
495    let mut size: Size<Pixels> = Size::default();
496    for line in &lines {
497        let line_size = line.size(line_height);
498        size.height += line_size.height;
499        size.width = size.width.max(line_size.width).ceil();
500    }
501    layout.0.borrow_mut().replace(TextLayoutInner {
502        lines,
503        len,
504        line_height,
505        wrap_width,
506        truncate_width,
507        size: Some(size),
508        bounds: None,
509    });
510    size
511}
512
513/// Rewrites the decorations of lines already shaped, leaving the shaping
514/// alone: recoloring text is a matter of replacing what is painted over it.
515///
516/// `runs` must split the lines as the runs they were shaped with did: the same
517/// lengths, the same fonts, and decoration changing in the same places; see
518/// [`TextMeasureInputs::shapes_as`].
519pub(crate) fn update_decoration_runs(lines: &mut [WrappedLine], runs: &[TextRun]) {
520    let mut runs = runs.iter().filter(|run| run.len > 0).cloned().peekable();
521    for line in lines.iter_mut() {
522        let line_len = line.text.len();
523        line.decoration_runs.clear();
524        let mut offset = 0;
525        while offset < line_len {
526            let Some(run) = runs.peek_mut() else {
527                log::warn!("`TextRun`s do not cover the entire shaped text");
528                break;
529            };
530            let len_within_line = cmp::min(line_len - offset, run.len);
531            if let Some(last_run) = line.decoration_runs.last_mut()
532                && last_run.color == run.color
533                && last_run.underline == run.underline
534                && last_run.strikethrough == run.strikethrough
535                && last_run.background_color == run.background_color
536            {
537                last_run.len += len_within_line as u32;
538            } else {
539                line.decoration_runs.push(DecorationRun {
540                    len: len_within_line as u32,
541                    color: run.color,
542                    background_color: run.background_color,
543                    underline: run.underline,
544                    strikethrough: run.strikethrough,
545                });
546            }
547            run.len -= len_within_line;
548            if run.len == 0 {
549                runs.next();
550            }
551            offset += len_within_line;
552        }
553        // Skip the `\n` that separated this line from the next.
554        if let Some(run) = runs.peek_mut() {
555            run.len -= 1;
556            if run.len == 0 {
557                runs.next();
558            }
559        }
560    }
561}
562
563/// What the measurement kept in `layout` left, without where it was last
564/// painted, for another element's layout to take over.
565///
566/// Last frame's element is usually gone by now, and its layout only held by
567/// what it left for this frame's, in which case the measurement is moved out
568/// of it rather than copied line by line. Something may still hold it (an
569/// element kept by a view reused as it was, say, or a caller's clone of a
570/// `StyledText`'s layout), and then it is copied, so it still answers.
571fn carry_measurement(layout: &TextLayout) -> Option<TextLayoutInner> {
572    if Rc::strong_count(&layout.0) == 1 {
573        let mut inner = layout.0.borrow_mut().take()?;
574        inner.bounds = None;
575        Some(inner)
576    } else {
577        layout.0.borrow().as_ref().map(copy_measurement)
578    }
579}
580
581/// A copy of what a measurement left, without where it was last painted.
582fn copy_measurement(inner: &TextLayoutInner) -> TextLayoutInner {
583    TextLayoutInner {
584        len: inner.len,
585        lines: inner
586            .lines
587            .iter()
588            .map(|line| WrappedLine {
589                layout: line.layout.clone(),
590                text: line.text.clone(),
591                decoration_runs: line.decoration_runs.clone(),
592            })
593            .collect(),
594        line_height: inner.line_height,
595        wrap_width: inner.wrap_width,
596        truncate_width: inner.truncate_width,
597        size: inner.size,
598        bounds: None,
599    }
600}
601
602impl Window {
603    /// Requests a self-measuring leaf, as [`Window::request_measured_layout`]
604    /// does, whose measurement can be carried over from the element at the
605    /// same place last frame. `adopt` is given `state` and what that element
606    /// measured from, and takes its measurement over if it still stands.
607    /// Otherwise `measure` may be run here, to tell whether it measures what
608    /// the node was measured at before. See
609    /// `TaffyLayoutEngine::request_retained_carried_measured_layout`.
610    pub(crate) fn request_carried_measured_layout<S: 'static>(
611        &mut self,
612        state: S,
613        adopt: impl FnOnce(&S, &dyn Any) -> Adopted,
614        forget: impl FnOnce(&S),
615        measure: impl Fn(
616            &S,
617            Size<Option<Pixels>>,
618            Size<AvailableSpace>,
619            &mut Window,
620            &mut App,
621        ) -> Size<Pixels>
622        + 'static,
623        cx: &mut App,
624    ) -> LayoutId {
625        self.invalidator.debug_assert_prepaint();
626        let rem_size = self.rem_size();
627        let scale_factor = self.scale_factor();
628        let key = crate::fast::layout_key::layout_key(self);
629        let mut layout_engine = self.layout_engine.take().unwrap();
630        let id = layout_engine.request_retained_carried_measured_layout(
631            key,
632            rem_size,
633            scale_factor,
634            state,
635            adopt,
636            forget,
637            measure,
638            self,
639            cx,
640        );
641        self.layout_engine = Some(layout_engine);
642        id
643    }
644}
645
646/// Leaves in `previous` everything the next frame may ask for: what this
647/// frame asked for, which is in `current`, and what it did not but something
648/// still holds. `current` is left empty.
649///
650/// Whichever of the two is larger is kept and the other moved into it, so a
651/// frame that asked for little costs little, and so does one that asked for
652/// everything.
653fn carry_over<K: Eq + Hash, V>(
654    previous: &mut FxHashMap<Arc<K>, Arc<V>>,
655    current: &mut FxHashMap<Arc<K>, Arc<V>>,
656) {
657    previous.retain(|_, layout| Arc::strong_count(layout) > 1);
658    if previous.len() < current.len() {
659        mem::swap(previous, current);
660    }
661    previous.extend(current.drain());
662}
663
664/// Ends a frame of the line layout cache: what it laid out, in `current`,
665/// becomes what the next frame can reuse, in `previous`.
666///
667/// Upstream drops every line the frame did not ask for. A text node that
668/// takes over last frame's measurement answers from the lines it holds
669/// without asking the cache for them, so its lines would be dropped, and its
670/// text, sliding onto another node with the rows around it, shaped again
671/// there. A line something still holds is kept.
672pub(crate) fn carry_over_line_layouts(previous: &mut FrameCache, current: &mut FrameCache) {
673    // Wrapped lines hold the lines they were wrapped from, so they are swept
674    // first, letting a line they were the last to hold go with them.
675    carry_over(&mut previous.wrapped_lines, &mut current.wrapped_lines);
676    carry_over(&mut previous.lines, &mut current.lines);
677
678    // The used lists index what this frame laid out, which is what a view
679    // reused next frame looks its lines up by.
680    mem::swap(&mut previous.used_lines, &mut current.used_lines);
681    mem::swap(
682        &mut previous.used_wrapped_lines,
683        &mut current.used_wrapped_lines,
684    );
685    current.used_lines.clear();
686    current.used_wrapped_lines.clear();
687}
688
689impl LineLayoutIndex {
690    /// This index, taken from a range that started at `from`, as it falls in
691    /// a copy of that range starting at `to`.
692    pub(crate) fn shifted(&self, from: &Self, to: &Self) -> Self {
693        LineLayoutIndex {
694            font_generation: to.font_generation,
695            lines_index: self.lines_index - from.lines_index + to.lines_index,
696            wrapped_lines_index: self.wrapped_lines_index - from.wrapped_lines_index
697                + to.wrapped_lines_index,
698        }
699    }
700}
701
702/// Counts the lines the line layout cache hands to the platform to be shaped,
703/// because neither this frame nor the last one had them, and times them.
704///
705/// The line layout cache only remembers the lines of this frame and the last
706/// one. Numbers that change every frame, like prices, keep coming back to
707/// values they had a few frames ago, and a row scrolled out comes back with
708/// the same text. So the lines shaped recently are kept here too, in
709/// [`RecentShapes`], and a line found there is copied instead of shaped again.
710#[derive(Default)]
711pub(crate) struct LineShaping {
712    /// Lines shaped lately, answered without asking the platform again.
713    recent: Mutex<RecentShapes>,
714    /// Numbers put together from their glyphs rather than shaped by the
715    /// platform.
716    numbers: Mutex<crate::fast::number_shaping::NumberShaping>,
717    /// Lines handed to the platform to be shaped. See [`LineShaping::stats`].
718    lines_shaped: AtomicU64,
719    /// Time spent in those calls, in nanoseconds.
720    shape_nanos: AtomicU64,
721    /// Whether to time shaping, which it does once the stats have been reset.
722    shape_timed: AtomicBool,
723}
724
725impl LineShaping {
726    /// How many lines have been shaped, and how long that took, since the last
727    /// [`LineShaping::reset`]. A line answered from the cache is not counted,
728    /// so this is the text work the cache failed to save.
729    #[cfg(any(test, feature = "test-support"))]
730    pub(crate) fn stats(&self) -> (u64, std::time::Duration) {
731        (
732            self.lines_shaped.load(Ordering::Relaxed),
733            std::time::Duration::from_nanos(self.shape_nanos.load(Ordering::Relaxed)),
734        )
735    }
736
737    /// Zeroes the counters reported by [`LineShaping::stats`], and from then
738    /// on times shaping too.
739    #[cfg(any(test, feature = "test-support"))]
740    pub(crate) fn reset(&self) {
741        self.lines_shaped.store(0, Ordering::Relaxed);
742        self.shape_nanos.store(0, Ordering::Relaxed);
743        self.shape_timed.store(true, Ordering::Relaxed);
744    }
745
746    /// Shapes a line the cache does not have, counting it, unless it was
747    /// shaped lately and can be copied from [`RecentShapes`].
748    pub(crate) fn shape_line(
749        &self,
750        platform_text_system: &dyn PlatformTextSystem,
751        text: &str,
752        font_size: Pixels,
753        runs: &[FontRun],
754    ) -> LineLayout {
755        let hash = RecentShapes::hash(text, font_size, runs);
756        if let Some(layout) = self.recent.lock().get(hash, text, font_size, runs) {
757            return layout;
758        }
759        let layout = self.shape_line_uncached(platform_text_system, text, font_size, runs);
760        self.recent
761            .lock()
762            .insert(hash, text, font_size, runs, copy_layout(&layout));
763        layout
764    }
765
766    fn shape_line_uncached(
767        &self,
768        platform_text_system: &dyn PlatformTextSystem,
769        text: &str,
770        font_size: Pixels,
771        runs: &[FontRun],
772    ) -> LineLayout {
773        let started_at = self.shape_timed.load(Ordering::Relaxed).then(Instant::now);
774        let layout = self
775            .numbers
776            .lock()
777            .shape(platform_text_system, text, font_size, runs)
778            .unwrap_or_else(|| platform_text_system.layout_line(text, font_size, runs));
779        self.lines_shaped.fetch_add(1, Ordering::Relaxed);
780        if let Some(started_at) = started_at {
781            self.shape_nanos
782                .fetch_add(started_at.elapsed().as_nanos() as u64, Ordering::Relaxed);
783        }
784        layout
785    }
786}
787
788/// Bumped whenever fonts are added to a text system, which can change how a
789/// line already shaped would shape now (a fallback font it lacked).
790static FONTS_GENERATION: AtomicU64 = AtomicU64::new(0);
791
792/// How many times fonts have been added to a text system.
793pub(crate) fn fonts_generation() -> u64 {
794    FONTS_GENERATION.load(Ordering::Relaxed)
795}
796
797/// Called when fonts are added to a text system, so no line shaped before is
798/// taken from [`RecentShapes`] again.
799#[inline(always)]
800pub(crate) fn fonts_changed() {
801    FONTS_GENERATION.fetch_add(1, Ordering::Relaxed);
802}
803
804/// How many glyphs the lines of one generation of [`RecentShapes`] may hold
805/// before it becomes the old one, which bounds what it keeps to about a
806/// megabyte. Between one and two generations' worth of the most recently used
807/// lines are remembered: some two thousand short numbers, or a few hundred
808/// lines of prose.
809pub(crate) const RECENT_GLYPHS_PER_GENERATION: usize = 16 * 1024;
810
811/// A line shaped lately: what it was shaped from, and what that gave.
812struct RecentShape {
813    text: Box<str>,
814    font_size: Pixels,
815    runs: SmallVec<[FontRun; 1]>,
816    layout: LineLayout,
817}
818
819/// The lines shaped lately, in two generations: lines are added to the
820/// current one, and a line found in the old one moves to the current one.
821/// When the current generation is full, the old one is dropped and the
822/// current one takes its place, so the lines not used for the longest go.
823#[derive(Default)]
824pub(crate) struct RecentShapes {
825    current: FxHashMap<u64, SmallVec<[RecentShape; 1]>>,
826    /// The glyphs in `current`, counting each line at least as one.
827    current_glyphs: usize,
828    old: FxHashMap<u64, SmallVec<[RecentShape; 1]>>,
829    fonts_generation: u64,
830}
831
832impl crate::Window {
833    /// Forgets the lines this window's text system shaped lately, so that a
834    /// test sees what the line layout cache alone keeps.
835    #[cfg(test)]
836    pub(crate) fn forget_recent_shapes(&self) {
837        let shaping = &self.text_system().line_layout_cache.shaping;
838        *shaping.recent.lock() = RecentShapes::default();
839    }
840}
841
842impl RecentShapes {
843    pub(crate) fn hash(text: &str, font_size: Pixels, runs: &[FontRun]) -> u64 {
844        let mut hasher = FxHasher::default();
845        text.hash(&mut hasher);
846        font_size.0.to_bits().hash(&mut hasher);
847        runs.hash(&mut hasher);
848        hasher.finish()
849    }
850
851    pub(crate) fn get(
852        &mut self,
853        hash: u64,
854        text: &str,
855        font_size: Pixels,
856        runs: &[FontRun],
857    ) -> Option<LineLayout> {
858        let fonts_generation = FONTS_GENERATION.load(Ordering::Relaxed);
859        if fonts_generation != self.fonts_generation {
860            self.current.clear();
861            self.current_glyphs = 0;
862            self.old.clear();
863            self.fonts_generation = fonts_generation;
864            return None;
865        }
866        let matches = |shape: &RecentShape| {
867            &*shape.text == text
868                && shape.font_size.0.to_bits() == font_size.0.to_bits()
869                && shape.runs.as_slice() == runs
870        };
871        if let Some(shape) = self
872            .current
873            .get(&hash)
874            .and_then(|shapes| shapes.iter().find(|shape| matches(shape)))
875        {
876            return Some(copy_layout(&shape.layout));
877        }
878        let shapes = self.old.get_mut(&hash)?;
879        let ix = shapes.iter().position(matches)?;
880        let shape = shapes.swap_remove(ix);
881        if shapes.is_empty() {
882            self.old.remove(&hash);
883        }
884        let layout = copy_layout(&shape.layout);
885        self.push(hash, shape);
886        Some(layout)
887    }
888
889    pub(crate) fn insert(
890        &mut self,
891        hash: u64,
892        text: &str,
893        font_size: Pixels,
894        runs: &[FontRun],
895        layout: LineLayout,
896    ) {
897        if self.fonts_generation != FONTS_GENERATION.load(Ordering::Relaxed) {
898            return;
899        }
900        self.push(
901            hash,
902            RecentShape {
903                text: text.into(),
904                font_size,
905                runs: SmallVec::from(runs),
906                layout,
907            },
908        );
909    }
910
911    fn push(&mut self, hash: u64, shape: RecentShape) {
912        if self.current_glyphs >= RECENT_GLYPHS_PER_GENERATION {
913            self.old = mem::take(&mut self.current);
914            self.current_glyphs = 0;
915        }
916        self.current_glyphs += shape
917            .layout
918            .runs
919            .iter()
920            .map(|run| run.glyphs.len())
921            .sum::<usize>()
922            .max(1);
923        self.current.entry(hash).or_default().push(shape);
924    }
925}
926
927/// A copy of a shaped line. (`LineLayout` is public, and cloning it isn't
928/// part of upstream's API.)
929fn copy_layout(layout: &LineLayout) -> LineLayout {
930    // Destructured, so that a field upstream adds can't be missed here.
931    let LineLayout {
932        font_size,
933        width,
934        ascent,
935        descent,
936        runs,
937        len,
938    } = layout;
939    LineLayout {
940        font_size: *font_size,
941        width: *width,
942        ascent: *ascent,
943        descent: *descent,
944        runs: runs.clone(),
945        len: *len,
946    }
947}
948
949/// Shapes a line `cache` does not have, counting it. See [`LineShaping`].
950#[inline(always)]
951pub(crate) fn shape_line(
952    cache: &LineLayoutCache,
953    text: &str,
954    font_size: Pixels,
955    runs: &[FontRun],
956) -> LineLayout {
957    cache
958        .shaping
959        .shape_line(&*cache.platform_text_system, text, font_size, runs)
960}
961
962/// The decoration runs of a line about to be measured. Most lines carry one
963/// decoration run, and highlighted ones a handful; reserving for the worst
964/// case, as upstream does, allocated two kilobytes on every measurement, which
965/// is much of what a short line costs.
966#[inline(always)]
967pub(crate) fn decoration_runs() -> Vec<DecorationRun> {
968    Vec::with_capacity(4)
969}
970
971/// Whether two decoration runs decorate alike, so a line measured with one
972/// can be reused for the other.
973impl PartialEq for DecorationRun {
974    fn eq(&self, other: &Self) -> bool {
975        // Destructured, so that a field upstream adds can't be missed here.
976        let DecorationRun {
977            len,
978            color,
979            background_color,
980            underline,
981            strikethrough,
982        } = self;
983        *len == other.len
984            && *color == other.color
985            && *background_color == other.background_color
986            && *underline == other.underline
987            && *strikethrough == other.strikethrough
988    }
989}
990
991/// Where each of the line layout cache's lists stood, compared to tell
992/// whether a reused range of lines is the one recorded.
993impl PartialEq for LineLayoutIndex {
994    fn eq(&self, other: &Self) -> bool {
995        let LineLayoutIndex {
996            font_generation,
997            lines_index,
998            wrapped_lines_index,
999        } = self;
1000        *font_generation == other.font_generation
1001            && *lines_index == other.lines_index
1002            && *wrapped_lines_index == other.wrapped_lines_index
1003    }
1004}
1005
1006impl std::fmt::Debug for LineLayoutIndex {
1007    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1008        let LineLayoutIndex {
1009            font_generation,
1010            lines_index,
1011            wrapped_lines_index,
1012        } = self;
1013        f.debug_struct("LineLayoutIndex")
1014            .field("font_generation", font_generation)
1015            .field("lines_index", lines_index)
1016            .field("wrapped_lines_index", wrapped_lines_index)
1017            .finish()
1018    }
1019}
1020
1021impl WindowTextSystem {
1022    /// Lines shaped by the platform, and the time that took, since the last
1023    /// [`Self::reset_shaping_stats`]. Lines answered from the cache do not count.
1024    #[cfg(any(test, feature = "test-support"))]
1025    pub(crate) fn shaping_stats(&self) -> (u64, std::time::Duration) {
1026        self.line_layout_cache.shaping.stats()
1027    }
1028
1029    /// Zeroes the counters reported by [`Self::shaping_stats`].
1030    #[cfg(any(test, feature = "test-support"))]
1031    pub(crate) fn reset_shaping_stats(&self) {
1032        self.line_layout_cache.shaping.reset()
1033    }
1034}
1035
1036/// How many fonts [`resolve_font`] remembers, most recently resolved last.
1037const RESOLVED_FONTS: usize = 16;
1038
1039/// A font resolved lately: the text system that resolved it, the fonts
1040/// generation it was resolved in, the font asked for and what it resolved to.
1041struct ResolvedFont {
1042    text_system: std::sync::Weak<dyn PlatformTextSystem>,
1043    generation: u64,
1044    font: crate::Font,
1045    font_id: crate::FontId,
1046}
1047
1048thread_local! {
1049    static RESOLVED: std::cell::RefCell<SmallVec<[ResolvedFont; RESOLVED_FONTS]>> =
1050        const { std::cell::RefCell::new(SmallVec::new_const()) };
1051}
1052
1053/// Resolves `font` as [`TextSystem::resolve_font`] does, remembering the few
1054/// fonts resolved lately: every run of every line shaped asks for its font,
1055/// and looking it up hashes the font and takes a lock each time, where a
1056/// frame's text uses a handful of fonts.
1057#[inline]
1058pub(crate) fn resolve_font(text_system: &crate::TextSystem, font: &crate::Font) -> crate::FontId {
1059    let generation = FONTS_GENERATION.load(Ordering::Relaxed);
1060    let platform = &text_system.platform_text_system;
1061    let remembered = RESOLVED.with_borrow(|resolved| {
1062        resolved.iter().rev().find_map(|entry| {
1063            (entry.generation == generation
1064                && entry.text_system.strong_count() > 0
1065                && std::ptr::addr_eq(entry.text_system.as_ptr(), Arc::as_ptr(platform))
1066                && entry.font == *font)
1067                .then_some(entry.font_id)
1068        })
1069    });
1070    if let Some(font_id) = remembered {
1071        return font_id;
1072    }
1073    let font_id = resolve_font_uncached(text_system, font);
1074    RESOLVED.with_borrow_mut(|resolved| {
1075        if resolved.len() == RESOLVED_FONTS {
1076            resolved.remove(0);
1077        }
1078        resolved.push(ResolvedFont {
1079            text_system: Arc::downgrade(platform),
1080            generation,
1081            font: font.clone(),
1082            font_id,
1083        });
1084    });
1085    font_id
1086}
1087
1088/// [`TextSystem::resolve_font`]: the font, or else the first of the
1089/// fallbacks that resolves with the features asked for, or else upstream's
1090/// plain fallback.
1091///
1092/// Upstream resolves a fallback as the fallback stack names it, plain: its
1093/// features — tabular numerals, say — dropped, so digits of a family that
1094/// isn't installed took their proportional widths, and a ticking price
1095/// changed width, and laid out its row again, every time it changed. The
1096/// fallback's weight and style stay upstream's.
1097fn resolve_font_uncached(text_system: &crate::TextSystem, font: &crate::Font) -> crate::FontId {
1098    if let Some(
1099        crate::text_system::CachedFont::Direct(font_id)
1100        | crate::text_system::CachedFont::Fallback(font_id),
1101    ) = text_system.font_ids_by_font.read().get(font)
1102    {
1103        return *font_id;
1104    }
1105    let mut font_error = None;
1106    if let Some(font_id) = cached_font_id(text_system, font, font, &mut font_error) {
1107        return font_id;
1108    }
1109    for fallback in &text_system.fallback_font_stack {
1110        let as_asked = crate::Font {
1111            features: font.features.clone(),
1112            ..fallback.clone()
1113        };
1114        if let Some(font_id) = cached_font_id(text_system, &as_asked, font, &mut font_error) {
1115            if let Some(error) = font_error {
1116                log::warn!("failed to load font {font:?}: {error:#}");
1117            }
1118            text_system.font_ids_by_font.write().insert(
1119                font.clone(),
1120                crate::text_system::CachedFont::Fallback(font_id),
1121            );
1122            return font_id;
1123        }
1124    }
1125    // No fallback has the font as asked: upstream's resolution takes the
1126    // first fallback as the stack names it, or panics.
1127    text_system.resolve_font_uncached(font)
1128}
1129
1130/// `candidate`'s own font id, looked up once per text system and remembered
1131/// in upstream's cache, misses included. Only a miss for the font `asked`
1132/// for is reported, as upstream reports only explicitly requested fonts.
1133fn cached_font_id(
1134    text_system: &crate::TextSystem,
1135    candidate: &crate::Font,
1136    asked: &crate::Font,
1137    font_error: &mut Option<Arc<anyhow::Error>>,
1138) -> Option<crate::FontId> {
1139    use crate::text_system::CachedFont;
1140    let cached = text_system.font_ids_by_font.read().get(candidate).cloned();
1141    let cached = cached.unwrap_or_else(|| {
1142        let cached = match text_system.platform_text_system.font_id(candidate) {
1143            Ok(font_id) => CachedFont::Direct(font_id),
1144            Err(error) => CachedFont::Missing(Arc::new(error)),
1145        };
1146        text_system
1147            .font_ids_by_font
1148            .write()
1149            .insert(candidate.clone(), cached.clone());
1150        cached
1151    });
1152    match cached {
1153        CachedFont::Direct(font_id) => Some(font_id),
1154        CachedFont::Fallback(_) => None,
1155        CachedFont::Missing(error) => {
1156            if candidate == asked {
1157                *font_error = Some(error);
1158            }
1159            None
1160        }
1161    }
1162}
1163
1164#[cfg(test)]
1165mod tests {
1166    use super::{TextMeasureInputs, measure_text};
1167    use crate::{AppContext as _, AvailableSpace, Size, TestAppContext, TextLayout, px};
1168    use std::cell::RefCell;
1169
1170    /// Taffy can measure a retained leaf under other constraints after it has
1171    /// been laid out: at width zero, say, when a node above it is sized to its
1172    /// content again. Text it wrapped there must not answer a later probe for
1173    /// its unwrapped width with the width it wrapped to: a box as wide as its
1174    /// content would take that width, the text would wrap in it, and the box
1175    /// would stay that narrow with room for the text on one line.
1176    #[test]
1177    fn text_wrapped_narrow_does_not_answer_for_its_unwrapped_width() {
1178        let mut cx = TestAppContext::single();
1179        let window = cx.add_window(|_, _| crate::Empty);
1180        cx.update_window(window.into(), |_, window, cx| {
1181            let text_style = crate::fast::text_style::text_style(window);
1182            let font_size = text_style.font_size.to_pixels(window.rem_size());
1183            let line_height = text_style
1184                .line_height
1185                .to_pixels(font_size.into(), window.rem_size());
1186            let inputs = TextMeasureInputs {
1187                text: "the quick brown fox jumps over the lazy dog".into(),
1188                runs: Vec::new(),
1189                text_style,
1190                font_size,
1191                line_height,
1192                layout: RefCell::new(TextLayout::default()),
1193            };
1194            let probe = |width| Size {
1195                width,
1196                height: AvailableSpace::MaxContent,
1197            };
1198            let unwrapped = measure_text(
1199                &inputs,
1200                Size::default(),
1201                probe(AvailableSpace::MaxContent),
1202                window,
1203                cx,
1204            );
1205
1206            let narrow = px(40.);
1207            let wrapped = measure_text(
1208                &inputs,
1209                Size {
1210                    width: Some(narrow),
1211                    height: None,
1212                },
1213                probe(AvailableSpace::Definite(narrow)),
1214                window,
1215                cx,
1216            );
1217            assert!(
1218                wrapped.width < unwrapped.width,
1219                "the text should wrap at {narrow:?}: {wrapped:?}, unwrapped {unwrapped:?}"
1220            );
1221
1222            for width in [AvailableSpace::MaxContent, AvailableSpace::MinContent] {
1223                assert_eq!(
1224                    measure_text(&inputs, Size::default(), probe(width), window, cx),
1225                    unwrapped,
1226                    "probed under {width:?} after wrapping at {narrow:?}"
1227                );
1228            }
1229        })
1230        .unwrap();
1231    }
1232}