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(
677        &mut previous.wrapped_lines_by_hash,
678        &mut current.wrapped_lines_by_hash,
679    );
680    carry_over(&mut previous.lines, &mut current.lines);
681    carry_over(&mut previous.lines_by_hash, &mut current.lines_by_hash);
682
683    // The used lists index what this frame laid out, which is what a view
684    // reused next frame looks its lines up by.
685    mem::swap(&mut previous.used_lines, &mut current.used_lines);
686    mem::swap(
687        &mut previous.used_wrapped_lines,
688        &mut current.used_wrapped_lines,
689    );
690    mem::swap(
691        &mut previous.used_lines_by_hash,
692        &mut current.used_lines_by_hash,
693    );
694    mem::swap(
695        &mut previous.used_wrapped_lines_by_hash,
696        &mut current.used_wrapped_lines_by_hash,
697    );
698    current.used_lines.clear();
699    current.used_wrapped_lines.clear();
700    current.used_lines_by_hash.clear();
701    current.used_wrapped_lines_by_hash.clear();
702}
703
704impl LineLayoutIndex {
705    /// This index, taken from a range that started at `from`, as it falls in
706    /// a copy of that range starting at `to`.
707    pub(crate) fn shifted(&self, from: &Self, to: &Self) -> Self {
708        LineLayoutIndex {
709            font_generation: to.font_generation,
710            lines_index: self.lines_index - from.lines_index + to.lines_index,
711            wrapped_lines_index: self.wrapped_lines_index - from.wrapped_lines_index
712                + to.wrapped_lines_index,
713            lines_by_hash_index: self.lines_by_hash_index - from.lines_by_hash_index
714                + to.lines_by_hash_index,
715            wrapped_lines_by_hash_index: self.wrapped_lines_by_hash_index
716                - from.wrapped_lines_by_hash_index
717                + to.wrapped_lines_by_hash_index,
718        }
719    }
720}
721
722/// Counts the lines the line layout cache hands to the platform to be shaped,
723/// because neither this frame nor the last one had them, and times them.
724///
725/// The line layout cache only remembers the lines of this frame and the last
726/// one. Numbers that change every frame, like prices, keep coming back to
727/// values they had a few frames ago, and a row scrolled out comes back with
728/// the same text. So the lines shaped recently are kept here too, in
729/// [`RecentShapes`], and a line found there is copied instead of shaped again.
730#[derive(Default)]
731pub(crate) struct LineShaping {
732    /// Lines shaped lately, answered without asking the platform again.
733    recent: Mutex<RecentShapes>,
734    /// Numbers put together from their glyphs rather than shaped by the
735    /// platform.
736    numbers: Mutex<crate::fast::number_shaping::NumberShaping>,
737    /// Lines handed to the platform to be shaped. See [`LineShaping::stats`].
738    lines_shaped: AtomicU64,
739    /// Time spent in those calls, in nanoseconds.
740    shape_nanos: AtomicU64,
741    /// Whether to time shaping, which it does once the stats have been reset.
742    shape_timed: AtomicBool,
743}
744
745impl LineShaping {
746    /// How many lines have been shaped, and how long that took, since the last
747    /// [`LineShaping::reset`]. A line answered from the cache is not counted,
748    /// so this is the text work the cache failed to save.
749    #[cfg(any(test, feature = "test-support"))]
750    pub(crate) fn stats(&self) -> (u64, std::time::Duration) {
751        (
752            self.lines_shaped.load(Ordering::Relaxed),
753            std::time::Duration::from_nanos(self.shape_nanos.load(Ordering::Relaxed)),
754        )
755    }
756
757    /// Zeroes the counters reported by [`LineShaping::stats`], and from then
758    /// on times shaping too.
759    #[cfg(any(test, feature = "test-support"))]
760    pub(crate) fn reset(&self) {
761        self.lines_shaped.store(0, Ordering::Relaxed);
762        self.shape_nanos.store(0, Ordering::Relaxed);
763        self.shape_timed.store(true, Ordering::Relaxed);
764    }
765
766    /// Shapes a line the cache does not have, counting it, unless it was
767    /// shaped lately and can be copied from [`RecentShapes`].
768    pub(crate) fn shape_line(
769        &self,
770        platform_text_system: &dyn PlatformTextSystem,
771        text: &str,
772        font_size: Pixels,
773        runs: &[FontRun],
774    ) -> LineLayout {
775        let hash = RecentShapes::hash(text, font_size, runs);
776        if let Some(layout) = self.recent.lock().get(hash, text, font_size, runs) {
777            return layout;
778        }
779        let layout = self.shape_line_uncached(platform_text_system, text, font_size, runs);
780        self.recent
781            .lock()
782            .insert(hash, text, font_size, runs, copy_layout(&layout));
783        layout
784    }
785
786    fn shape_line_uncached(
787        &self,
788        platform_text_system: &dyn PlatformTextSystem,
789        text: &str,
790        font_size: Pixels,
791        runs: &[FontRun],
792    ) -> LineLayout {
793        let started_at = self.shape_timed.load(Ordering::Relaxed).then(Instant::now);
794        let layout = self
795            .numbers
796            .lock()
797            .shape(platform_text_system, text, font_size, runs)
798            .unwrap_or_else(|| platform_text_system.layout_line(text, font_size, runs));
799        self.lines_shaped.fetch_add(1, Ordering::Relaxed);
800        if let Some(started_at) = started_at {
801            self.shape_nanos
802                .fetch_add(started_at.elapsed().as_nanos() as u64, Ordering::Relaxed);
803        }
804        layout
805    }
806}
807
808/// Bumped whenever fonts are added to a text system, which can change how a
809/// line already shaped would shape now (a fallback font it lacked).
810static FONTS_GENERATION: AtomicU64 = AtomicU64::new(0);
811
812/// How many times fonts have been added to a text system.
813pub(crate) fn fonts_generation() -> u64 {
814    FONTS_GENERATION.load(Ordering::Relaxed)
815}
816
817/// Called when fonts are added to a text system, so no line shaped before is
818/// taken from [`RecentShapes`] again.
819#[inline(always)]
820pub(crate) fn fonts_changed() {
821    FONTS_GENERATION.fetch_add(1, Ordering::Relaxed);
822}
823
824/// How many glyphs the lines of one generation of [`RecentShapes`] may hold
825/// before it becomes the old one, which bounds what it keeps to about a
826/// megabyte. Between one and two generations' worth of the most recently used
827/// lines are remembered: some two thousand short numbers, or a few hundred
828/// lines of prose.
829pub(crate) const RECENT_GLYPHS_PER_GENERATION: usize = 16 * 1024;
830
831/// A line shaped lately: what it was shaped from, and what that gave.
832struct RecentShape {
833    text: Box<str>,
834    font_size: Pixels,
835    runs: SmallVec<[FontRun; 1]>,
836    layout: LineLayout,
837}
838
839/// The lines shaped lately, in two generations: lines are added to the
840/// current one, and a line found in the old one moves to the current one.
841/// When the current generation is full, the old one is dropped and the
842/// current one takes its place, so the lines not used for the longest go.
843#[derive(Default)]
844pub(crate) struct RecentShapes {
845    current: FxHashMap<u64, SmallVec<[RecentShape; 1]>>,
846    /// The glyphs in `current`, counting each line at least as one.
847    current_glyphs: usize,
848    old: FxHashMap<u64, SmallVec<[RecentShape; 1]>>,
849    fonts_generation: u64,
850}
851
852impl crate::Window {
853    /// Forgets the lines this window's text system shaped lately, so that a
854    /// test sees what the line layout cache alone keeps.
855    #[cfg(test)]
856    pub(crate) fn forget_recent_shapes(&self) {
857        let shaping = &self.text_system().line_layout_cache.shaping;
858        *shaping.recent.lock() = RecentShapes::default();
859    }
860}
861
862impl RecentShapes {
863    pub(crate) fn hash(text: &str, font_size: Pixels, runs: &[FontRun]) -> u64 {
864        let mut hasher = FxHasher::default();
865        text.hash(&mut hasher);
866        font_size.0.to_bits().hash(&mut hasher);
867        runs.hash(&mut hasher);
868        hasher.finish()
869    }
870
871    pub(crate) fn get(
872        &mut self,
873        hash: u64,
874        text: &str,
875        font_size: Pixels,
876        runs: &[FontRun],
877    ) -> Option<LineLayout> {
878        let fonts_generation = FONTS_GENERATION.load(Ordering::Relaxed);
879        if fonts_generation != self.fonts_generation {
880            self.current.clear();
881            self.current_glyphs = 0;
882            self.old.clear();
883            self.fonts_generation = fonts_generation;
884            return None;
885        }
886        let matches = |shape: &RecentShape| {
887            &*shape.text == text
888                && shape.font_size.0.to_bits() == font_size.0.to_bits()
889                && shape.runs.as_slice() == runs
890        };
891        if let Some(shape) = self
892            .current
893            .get(&hash)
894            .and_then(|shapes| shapes.iter().find(|shape| matches(shape)))
895        {
896            return Some(copy_layout(&shape.layout));
897        }
898        let shapes = self.old.get_mut(&hash)?;
899        let ix = shapes.iter().position(matches)?;
900        let shape = shapes.swap_remove(ix);
901        if shapes.is_empty() {
902            self.old.remove(&hash);
903        }
904        let layout = copy_layout(&shape.layout);
905        self.push(hash, shape);
906        Some(layout)
907    }
908
909    pub(crate) fn insert(
910        &mut self,
911        hash: u64,
912        text: &str,
913        font_size: Pixels,
914        runs: &[FontRun],
915        layout: LineLayout,
916    ) {
917        if self.fonts_generation != FONTS_GENERATION.load(Ordering::Relaxed) {
918            return;
919        }
920        self.push(
921            hash,
922            RecentShape {
923                text: text.into(),
924                font_size,
925                runs: SmallVec::from(runs),
926                layout,
927            },
928        );
929    }
930
931    fn push(&mut self, hash: u64, shape: RecentShape) {
932        if self.current_glyphs >= RECENT_GLYPHS_PER_GENERATION {
933            self.old = mem::take(&mut self.current);
934            self.current_glyphs = 0;
935        }
936        self.current_glyphs += shape
937            .layout
938            .runs
939            .iter()
940            .map(|run| run.glyphs.len())
941            .sum::<usize>()
942            .max(1);
943        self.current.entry(hash).or_default().push(shape);
944    }
945}
946
947/// A copy of a shaped line. (`LineLayout` is public, and cloning it isn't
948/// part of upstream's API.)
949fn copy_layout(layout: &LineLayout) -> LineLayout {
950    // Destructured, so that a field upstream adds can't be missed here.
951    let LineLayout {
952        font_size,
953        width,
954        ascent,
955        descent,
956        runs,
957        len,
958    } = layout;
959    LineLayout {
960        font_size: *font_size,
961        width: *width,
962        ascent: *ascent,
963        descent: *descent,
964        runs: runs.clone(),
965        len: *len,
966    }
967}
968
969/// Shapes a line `cache` does not have, counting it. See [`LineShaping`].
970#[inline(always)]
971pub(crate) fn shape_line(
972    cache: &LineLayoutCache,
973    text: &str,
974    font_size: Pixels,
975    runs: &[FontRun],
976) -> LineLayout {
977    cache
978        .shaping
979        .shape_line(&*cache.platform_text_system, text, font_size, runs)
980}
981
982/// The decoration runs of a line about to be measured. Most lines carry one
983/// decoration run, and highlighted ones a handful; reserving for the worst
984/// case, as upstream does, allocated two kilobytes on every measurement, which
985/// is much of what a short line costs.
986#[inline(always)]
987pub(crate) fn decoration_runs() -> Vec<DecorationRun> {
988    Vec::with_capacity(4)
989}
990
991/// Whether two decoration runs decorate alike, so a line measured with one
992/// can be reused for the other.
993impl PartialEq for DecorationRun {
994    fn eq(&self, other: &Self) -> bool {
995        // Destructured, so that a field upstream adds can't be missed here.
996        let DecorationRun {
997            len,
998            color,
999            background_color,
1000            underline,
1001            strikethrough,
1002        } = self;
1003        *len == other.len
1004            && *color == other.color
1005            && *background_color == other.background_color
1006            && *underline == other.underline
1007            && *strikethrough == other.strikethrough
1008    }
1009}
1010
1011/// Where each of the line layout cache's lists stood, compared to tell
1012/// whether a reused range of lines is the one recorded.
1013impl PartialEq for LineLayoutIndex {
1014    fn eq(&self, other: &Self) -> bool {
1015        let LineLayoutIndex {
1016            font_generation,
1017            lines_index,
1018            wrapped_lines_index,
1019            lines_by_hash_index,
1020            wrapped_lines_by_hash_index,
1021        } = self;
1022        *font_generation == other.font_generation
1023            && *lines_index == other.lines_index
1024            && *wrapped_lines_index == other.wrapped_lines_index
1025            && *lines_by_hash_index == other.lines_by_hash_index
1026            && *wrapped_lines_by_hash_index == other.wrapped_lines_by_hash_index
1027    }
1028}
1029
1030impl std::fmt::Debug for LineLayoutIndex {
1031    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1032        let LineLayoutIndex {
1033            font_generation,
1034            lines_index,
1035            wrapped_lines_index,
1036            lines_by_hash_index,
1037            wrapped_lines_by_hash_index,
1038        } = self;
1039        f.debug_struct("LineLayoutIndex")
1040            .field("font_generation", font_generation)
1041            .field("lines_index", lines_index)
1042            .field("wrapped_lines_index", wrapped_lines_index)
1043            .field("lines_by_hash_index", lines_by_hash_index)
1044            .field("wrapped_lines_by_hash_index", wrapped_lines_by_hash_index)
1045            .finish()
1046    }
1047}
1048
1049impl WindowTextSystem {
1050    /// Lines shaped by the platform, and the time that took, since the last
1051    /// [`Self::reset_shaping_stats`]. Lines answered from the cache do not count.
1052    #[cfg(any(test, feature = "test-support"))]
1053    pub(crate) fn shaping_stats(&self) -> (u64, std::time::Duration) {
1054        self.line_layout_cache.shaping.stats()
1055    }
1056
1057    /// Zeroes the counters reported by [`Self::shaping_stats`].
1058    #[cfg(any(test, feature = "test-support"))]
1059    pub(crate) fn reset_shaping_stats(&self) {
1060        self.line_layout_cache.shaping.reset()
1061    }
1062}
1063
1064/// How many fonts [`resolve_font`] remembers, most recently resolved last.
1065const RESOLVED_FONTS: usize = 16;
1066
1067/// A font resolved lately: the text system that resolved it, the fonts
1068/// generation it was resolved in, the font asked for and what it resolved to.
1069struct ResolvedFont {
1070    text_system: std::sync::Weak<dyn PlatformTextSystem>,
1071    generation: u64,
1072    font: crate::Font,
1073    font_id: crate::FontId,
1074}
1075
1076thread_local! {
1077    static RESOLVED: std::cell::RefCell<SmallVec<[ResolvedFont; RESOLVED_FONTS]>> =
1078        const { std::cell::RefCell::new(SmallVec::new_const()) };
1079}
1080
1081/// Resolves `font` as [`TextSystem::resolve_font`] does, remembering the few
1082/// fonts resolved lately: every run of every line shaped asks for its font,
1083/// and looking it up hashes the font and takes a lock each time, where a
1084/// frame's text uses a handful of fonts.
1085#[inline]
1086pub(crate) fn resolve_font(text_system: &crate::TextSystem, font: &crate::Font) -> crate::FontId {
1087    let generation = FONTS_GENERATION.load(Ordering::Relaxed);
1088    let platform = &text_system.platform_text_system;
1089    let remembered = RESOLVED.with_borrow(|resolved| {
1090        resolved.iter().rev().find_map(|entry| {
1091            (entry.generation == generation
1092                && entry.text_system.strong_count() > 0
1093                && std::ptr::addr_eq(entry.text_system.as_ptr(), Arc::as_ptr(platform))
1094                && entry.font == *font)
1095                .then_some(entry.font_id)
1096        })
1097    });
1098    if let Some(font_id) = remembered {
1099        return font_id;
1100    }
1101    let font_id = resolve_font_uncached(text_system, font);
1102    RESOLVED.with_borrow_mut(|resolved| {
1103        if resolved.len() == RESOLVED_FONTS {
1104            resolved.remove(0);
1105        }
1106        resolved.push(ResolvedFont {
1107            text_system: Arc::downgrade(platform),
1108            generation,
1109            font: font.clone(),
1110            font_id,
1111        });
1112    });
1113    font_id
1114}
1115
1116/// [`TextSystem::resolve_font`]: the font, or else the first of the
1117/// fallbacks that resolves with the features asked for, or else upstream's
1118/// plain fallback.
1119///
1120/// Upstream resolves a fallback as the fallback stack names it, plain: its
1121/// features — tabular numerals, say — dropped, so digits of a family that
1122/// isn't installed took their proportional widths, and a ticking price
1123/// changed width, and laid out its row again, every time it changed. The
1124/// fallback's weight and style stay upstream's.
1125fn resolve_font_uncached(text_system: &crate::TextSystem, font: &crate::Font) -> crate::FontId {
1126    if let Some(
1127        crate::text_system::CachedFont::Direct(font_id)
1128        | crate::text_system::CachedFont::Fallback(font_id),
1129    ) = text_system.font_ids_by_font.read().get(font)
1130    {
1131        return *font_id;
1132    }
1133    let mut font_error = None;
1134    if let Some(font_id) = cached_font_id(text_system, font, font, &mut font_error) {
1135        return font_id;
1136    }
1137    for fallback in &text_system.fallback_font_stack {
1138        let as_asked = crate::Font {
1139            features: font.features.clone(),
1140            ..fallback.clone()
1141        };
1142        if let Some(font_id) = cached_font_id(text_system, &as_asked, font, &mut font_error) {
1143            if let Some(error) = font_error {
1144                log::warn!("failed to load font {font:?}: {error:#}");
1145            }
1146            text_system.font_ids_by_font.write().insert(
1147                font.clone(),
1148                crate::text_system::CachedFont::Fallback(font_id),
1149            );
1150            return font_id;
1151        }
1152    }
1153    // No fallback has the font as asked: upstream's resolution takes the
1154    // first fallback as the stack names it, or panics.
1155    text_system.resolve_font_uncached(font)
1156}
1157
1158/// `candidate`'s own font id, looked up once per text system and remembered
1159/// in upstream's cache, misses included. Only a miss for the font `asked`
1160/// for is reported, as upstream reports only explicitly requested fonts.
1161fn cached_font_id(
1162    text_system: &crate::TextSystem,
1163    candidate: &crate::Font,
1164    asked: &crate::Font,
1165    font_error: &mut Option<Arc<anyhow::Error>>,
1166) -> Option<crate::FontId> {
1167    use crate::text_system::CachedFont;
1168    let cached = text_system.font_ids_by_font.read().get(candidate).cloned();
1169    let cached = cached.unwrap_or_else(|| {
1170        let cached = match text_system.platform_text_system.font_id(candidate) {
1171            Ok(font_id) => CachedFont::Direct(font_id),
1172            Err(error) => CachedFont::Missing(Arc::new(error)),
1173        };
1174        text_system
1175            .font_ids_by_font
1176            .write()
1177            .insert(candidate.clone(), cached.clone());
1178        cached
1179    });
1180    match cached {
1181        CachedFont::Direct(font_id) => Some(font_id),
1182        CachedFont::Fallback(_) => None,
1183        CachedFont::Missing(error) => {
1184            if candidate == asked {
1185                *font_error = Some(error);
1186            }
1187            None
1188        }
1189    }
1190}
1191
1192#[cfg(test)]
1193mod tests {
1194    use super::{TextMeasureInputs, measure_text};
1195    use crate::{AppContext as _, AvailableSpace, Size, TestAppContext, TextLayout, px};
1196    use std::cell::RefCell;
1197
1198    /// Taffy can measure a retained leaf under other constraints after it has
1199    /// been laid out: at width zero, say, when a node above it is sized to its
1200    /// content again. Text it wrapped there must not answer a later probe for
1201    /// its unwrapped width with the width it wrapped to: a box as wide as its
1202    /// content would take that width, the text would wrap in it, and the box
1203    /// would stay that narrow with room for the text on one line.
1204    #[test]
1205    fn text_wrapped_narrow_does_not_answer_for_its_unwrapped_width() {
1206        let mut cx = TestAppContext::single();
1207        let window = cx.add_window(|_, _| crate::Empty);
1208        cx.update_window(window.into(), |_, window, cx| {
1209            let text_style = crate::fast::text_style::text_style(window);
1210            let font_size = text_style.font_size.to_pixels(window.rem_size());
1211            let line_height = text_style
1212                .line_height
1213                .to_pixels(font_size.into(), window.rem_size());
1214            let inputs = TextMeasureInputs {
1215                text: "the quick brown fox jumps over the lazy dog".into(),
1216                runs: Vec::new(),
1217                text_style,
1218                font_size,
1219                line_height,
1220                layout: RefCell::new(TextLayout::default()),
1221            };
1222            let probe = |width| Size {
1223                width,
1224                height: AvailableSpace::MaxContent,
1225            };
1226            let unwrapped = measure_text(
1227                &inputs,
1228                Size::default(),
1229                probe(AvailableSpace::MaxContent),
1230                window,
1231                cx,
1232            );
1233
1234            let narrow = px(40.);
1235            let wrapped = measure_text(
1236                &inputs,
1237                Size {
1238                    width: Some(narrow),
1239                    height: None,
1240                },
1241                probe(AvailableSpace::Definite(narrow)),
1242                window,
1243                cx,
1244            );
1245            assert!(
1246                wrapped.width < unwrapped.width,
1247                "the text should wrap at {narrow:?}: {wrapped:?}, unwrapped {unwrapped:?}"
1248            );
1249
1250            for width in [AvailableSpace::MaxContent, AvailableSpace::MinContent] {
1251                assert_eq!(
1252                    measure_text(&inputs, Size::default(), probe(width), window, cx),
1253                    unwrapped,
1254                    "probed under {width:?} after wrapping at {narrow:?}"
1255                );
1256            }
1257        })
1258        .unwrap();
1259    }
1260}