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, 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 text_style = crate::fast::text_style::text_style(window);
203    let font_size = text_style.font_size.to_pixels(window.rem_size());
204    let line_height = window.pixel_snap(
205        text_style
206            .line_height
207            .to_pixels(font_size.into(), window.rem_size()),
208    );
209    let inputs = TextMeasureInputs {
210        text,
211        runs: runs.unwrap_or_default(),
212        text_style,
213        font_size,
214        line_height,
215        layout: RefCell::new(layout.clone()),
216    };
217    window.request_carried_measured_layout(
218        inputs,
219        adopt_measurement,
220        forget_measurement,
221        measure_text,
222        cx,
223    )
224}
225
226/// Takes over the measurement `previous` left, if it stands for `inputs`. See
227/// [`layout_text`].
228fn adopt_measurement(inputs: &TextMeasureInputs, previous: &dyn Any) -> Adopted {
229    let Some(previous) = previous.downcast_ref::<TextMeasureInputs>() else {
230        return Adopted::No;
231    };
232    if !previous.shapes_as(inputs) {
233        return Adopted::No;
234    }
235    let recolored = !previous.decorated_as(inputs);
236    if recolored && inputs.truncates() {
237        return Adopted::No;
238    }
239    let Some(mut inner) = carry_measurement(&previous.layout.borrow()) else {
240        return Adopted::No;
241    };
242    let layout = inputs.layout.borrow();
243    if recolored {
244        update_decoration_runs(&mut inner.lines, &inputs.runs());
245        *layout.0.borrow_mut() = Some(inner);
246        Adopted::Measurement
247    } else {
248        *layout.0.borrow_mut() = Some(inner);
249        // The node keeps `previous`, which now keeps its measurement where
250        // this element looks for it.
251        *previous.layout.borrow_mut() = layout.clone();
252        Adopted::Node
253    }
254}
255
256/// Drops the measurement `inputs` were left with, for text laid out afresh:
257/// [`measure_text`] answers from a measurement it holds, and one taken under
258/// another text's constraints would answer for those.
259fn forget_measurement(inputs: &TextMeasureInputs) {
260    inputs.layout.borrow().0.borrow_mut().take();
261}
262
263/// Measures text under the constraints Taffy offers, keeping the result in
264/// its layout: upstream's measurement, doing less of its work.
265///
266/// - Taffy asks a node for its intrinsic size before it lays the node out, so
267///   a wrapping leaf is measured unconstrained and then again at the width it
268///   ends up with. Text that came out narrower than the width now on offer
269///   wraps nowhere, and the lines shaped without a wrap width are the same
270///   lines, so that is answered from what is already there. The other way
271///   round holds only for text that wrapped nowhere at its width.
272/// - Which affix to truncate with, and the line wrapper truncation needs, are
273///   worked out only when the text truncates and has to be shaped: resolving
274///   the font and borrowing a wrapper from the pool on every measurement was
275///   for nothing on text that does not truncate.
276fn measure_text(
277    inputs: &TextMeasureInputs,
278    known_dimensions: Size<Option<Pixels>>,
279    available_space: Size<AvailableSpace>,
280    window: &mut Window,
281    cx: &mut App,
282) -> Size<Pixels> {
283    let TextMeasureInputs {
284        text,
285        runs: _,
286        text_style,
287        font_size,
288        line_height,
289        layout,
290    } = inputs;
291    let layout = &*layout.borrow();
292    let (font_size, line_height) = (*font_size, *line_height);
293    let wrap_width = if text_style.white_space == WhiteSpace::Normal {
294        known_dimensions.width.or(match available_space.width {
295            AvailableSpace::Definite(x) => Some(x),
296            _ => None,
297        })
298    } else {
299        None
300    };
301    let truncate_width = text_style.text_overflow.as_ref().and_then(|_| {
302        known_dimensions.width.or(match available_space.width {
303            AvailableSpace::Definite(x) => match text_style.line_clamp {
304                Some(max_lines) => Some(x * max_lines),
305                None => Some(x),
306            },
307            _ => None,
308        })
309    });
310
311    // A kept measurement answers when the wrap width is one it was taken at,
312    // an unconstrained probe when it wrapped nowhere, or a wrap width it fits
313    // within unwrapped, unless truncation is involved either way: a truncated
314    // layout would answer an unconstrained probe with the truncated size.
315    // Text wrapped at a width is only as wide as that width, and Taffy can
316    // measure a retained leaf narrow after laying it out (see
317    // `text_laid_out_from_the_cache_paints_the_lines_of_its_box`): answering
318    // an unconstrained probe with that would size a box as wide as its
319    // content to the narrow width, for good.
320    if let Some(text_layout) = layout.0.borrow().as_ref()
321        && let Some(size) = text_layout.size
322        && (wrap_width == text_layout.wrap_width
323            || (wrap_width.is_none()
324                && text_layout
325                    .lines
326                    .iter()
327                    .all(|line| line.wrap_boundaries.is_empty()))
328            || (text_layout.wrap_width.is_none()
329                && wrap_width.is_some_and(|wrap_width| size.width <= wrap_width)))
330        && truncate_width.is_none()
331        && text_layout.truncate_width.is_none()
332    {
333        return size;
334    }
335
336    let runs = inputs.runs();
337    let runs = &*runs;
338    let (text, runs) = if let Some(truncate_width) = truncate_width {
339        let (truncation_affix, truncate_from) = match text_style.text_overflow.clone() {
340            Some(TextOverflow::Truncate(affix)) => (affix, TruncateFrom::End),
341            Some(TextOverflow::TruncateStart(affix)) => (affix, TruncateFrom::Start),
342            Some(TextOverflow::TruncateMiddle(affix)) => (affix, TruncateFrom::Middle),
343            None => (SharedString::default(), TruncateFrom::End),
344        };
345        let mut line_wrapper = cx.text_system().line_wrapper(text_style.font(), font_size);
346        if let Some(max_lines) = text_style.line_clamp
347            && let Some(wrap_width) = wrap_width
348        {
349            line_wrapper.truncate_wrapped_line(
350                text.clone(),
351                wrap_width,
352                max_lines,
353                &truncation_affix,
354                runs,
355                truncate_from,
356            )
357        } else if let Some(unclipped) = window
358            .text_system()
359            .shape_text(text.clone(), font_size, runs, None, None)
360            .log_err()
361            && unclipped
362                .iter()
363                .all(|line| line.size(line_height).width <= truncate_width)
364        {
365            // Truncation sums per-character advances, which overestimates the
366            // shaped width, so text that fits once shaped is not truncated.
367            (text.clone(), Cow::Borrowed(runs))
368        } else {
369            line_wrapper.truncate_line(
370                text.clone(),
371                truncate_width,
372                &truncation_affix,
373                runs,
374                truncate_from,
375            )
376        }
377    } else {
378        (text.clone(), Cow::Borrowed(runs))
379    };
380    let len = text.len();
381
382    let Some(lines) = window
383        .text_system()
384        .shape_text(text, font_size, &runs, wrap_width, text_style.line_clamp)
385        .log_err()
386    else {
387        layout.0.borrow_mut().replace(TextLayoutInner {
388            lines: Default::default(),
389            len: 0,
390            line_height,
391            wrap_width,
392            truncate_width,
393            size: Some(Size::default()),
394            bounds: None,
395        });
396        return Size::default();
397    };
398
399    let mut size: Size<Pixels> = Size::default();
400    for line in &lines {
401        let line_size = line.size(line_height);
402        size.height += line_size.height;
403        size.width = size.width.max(line_size.width).ceil();
404    }
405    layout.0.borrow_mut().replace(TextLayoutInner {
406        lines,
407        len,
408        line_height,
409        wrap_width,
410        truncate_width,
411        size: Some(size),
412        bounds: None,
413    });
414    size
415}
416
417/// Rewrites the decorations of lines already shaped, leaving the shaping
418/// alone: recoloring text is a matter of replacing what is painted over it.
419///
420/// `runs` must split the lines as the runs they were shaped with did: the same
421/// lengths, the same fonts, and decoration changing in the same places; see
422/// [`TextMeasureInputs::shapes_as`].
423pub(crate) fn update_decoration_runs(lines: &mut [WrappedLine], runs: &[TextRun]) {
424    let mut runs = runs.iter().filter(|run| run.len > 0).cloned().peekable();
425    for line in lines.iter_mut() {
426        let line_len = line.text.len();
427        line.decoration_runs.clear();
428        let mut offset = 0;
429        while offset < line_len {
430            let Some(run) = runs.peek_mut() else {
431                log::warn!("`TextRun`s do not cover the entire shaped text");
432                break;
433            };
434            let len_within_line = cmp::min(line_len - offset, run.len);
435            if let Some(last_run) = line.decoration_runs.last_mut()
436                && last_run.color == run.color
437                && last_run.underline == run.underline
438                && last_run.strikethrough == run.strikethrough
439                && last_run.background_color == run.background_color
440            {
441                last_run.len += len_within_line as u32;
442            } else {
443                line.decoration_runs.push(DecorationRun {
444                    len: len_within_line as u32,
445                    color: run.color,
446                    background_color: run.background_color,
447                    underline: run.underline,
448                    strikethrough: run.strikethrough,
449                });
450            }
451            run.len -= len_within_line;
452            if run.len == 0 {
453                runs.next();
454            }
455            offset += len_within_line;
456        }
457        // Skip the `\n` that separated this line from the next.
458        if let Some(run) = runs.peek_mut() {
459            run.len -= 1;
460            if run.len == 0 {
461                runs.next();
462            }
463        }
464    }
465}
466
467/// What the measurement kept in `layout` left, without where it was last
468/// painted, for another element's layout to take over.
469///
470/// Last frame's element is usually gone by now, and its layout only held by
471/// what it left for this frame's, in which case the measurement is moved out
472/// of it rather than copied line by line. Something may still hold it (an
473/// element kept by a view reused as it was, say, or a caller's clone of a
474/// `StyledText`'s layout), and then it is copied, so it still answers.
475fn carry_measurement(layout: &TextLayout) -> Option<TextLayoutInner> {
476    if Rc::strong_count(&layout.0) == 1 {
477        let mut inner = layout.0.borrow_mut().take()?;
478        inner.bounds = None;
479        Some(inner)
480    } else {
481        layout.0.borrow().as_ref().map(copy_measurement)
482    }
483}
484
485/// A copy of what a measurement left, without where it was last painted.
486fn copy_measurement(inner: &TextLayoutInner) -> TextLayoutInner {
487    TextLayoutInner {
488        len: inner.len,
489        lines: inner
490            .lines
491            .iter()
492            .map(|line| WrappedLine {
493                layout: line.layout.clone(),
494                text: line.text.clone(),
495                decoration_runs: line.decoration_runs.clone(),
496            })
497            .collect(),
498        line_height: inner.line_height,
499        wrap_width: inner.wrap_width,
500        truncate_width: inner.truncate_width,
501        size: inner.size,
502        bounds: None,
503    }
504}
505
506impl Window {
507    /// Requests a self-measuring leaf, as [`Window::request_measured_layout`]
508    /// does, whose measurement can be carried over from the element at the
509    /// same place last frame. `adopt` is given `state` and what that element
510    /// measured from, and takes its measurement over if it still stands.
511    /// Otherwise `measure` may be run here, to tell whether it measures what
512    /// the node was measured at before. See
513    /// `TaffyLayoutEngine::request_retained_carried_measured_layout`.
514    pub(crate) fn request_carried_measured_layout<S: 'static>(
515        &mut self,
516        state: S,
517        adopt: impl FnOnce(&S, &dyn Any) -> Adopted,
518        forget: impl FnOnce(&S),
519        measure: impl Fn(
520            &S,
521            Size<Option<Pixels>>,
522            Size<AvailableSpace>,
523            &mut Window,
524            &mut App,
525        ) -> Size<Pixels>
526        + 'static,
527        cx: &mut App,
528    ) -> LayoutId {
529        self.invalidator.debug_assert_prepaint();
530        let rem_size = self.rem_size();
531        let scale_factor = self.scale_factor();
532        let key = crate::fast::layout_key::layout_key(self);
533        let mut layout_engine = self.layout_engine.take().unwrap();
534        let id = layout_engine.request_retained_carried_measured_layout(
535            key,
536            rem_size,
537            scale_factor,
538            state,
539            adopt,
540            forget,
541            measure,
542            self,
543            cx,
544        );
545        self.layout_engine = Some(layout_engine);
546        id
547    }
548}
549
550/// Leaves in `previous` everything the next frame may ask for: what this
551/// frame asked for, which is in `current`, and what it did not but something
552/// still holds. `current` is left empty.
553///
554/// Whichever of the two is larger is kept and the other moved into it, so a
555/// frame that asked for little costs little, and so does one that asked for
556/// everything.
557fn carry_over<K: Eq + Hash, V>(
558    previous: &mut FxHashMap<Arc<K>, Arc<V>>,
559    current: &mut FxHashMap<Arc<K>, Arc<V>>,
560) {
561    previous.retain(|_, layout| Arc::strong_count(layout) > 1);
562    if previous.len() < current.len() {
563        mem::swap(previous, current);
564    }
565    previous.extend(current.drain());
566}
567
568/// Ends a frame of the line layout cache: what it laid out, in `current`,
569/// becomes what the next frame can reuse, in `previous`.
570///
571/// Upstream drops every line the frame did not ask for. A text node that
572/// takes over last frame's measurement answers from the lines it holds
573/// without asking the cache for them, so its lines would be dropped, and its
574/// text, sliding onto another node with the rows around it, shaped again
575/// there. A line something still holds is kept.
576pub(crate) fn carry_over_line_layouts(previous: &mut FrameCache, current: &mut FrameCache) {
577    // Wrapped lines hold the lines they were wrapped from, so they are swept
578    // first, letting a line they were the last to hold go with them.
579    carry_over(&mut previous.wrapped_lines, &mut current.wrapped_lines);
580    carry_over(
581        &mut previous.wrapped_lines_by_hash,
582        &mut current.wrapped_lines_by_hash,
583    );
584    carry_over(&mut previous.lines, &mut current.lines);
585    carry_over(&mut previous.lines_by_hash, &mut current.lines_by_hash);
586
587    // The used lists index what this frame laid out, which is what a view
588    // reused next frame looks its lines up by.
589    mem::swap(&mut previous.used_lines, &mut current.used_lines);
590    mem::swap(
591        &mut previous.used_wrapped_lines,
592        &mut current.used_wrapped_lines,
593    );
594    mem::swap(
595        &mut previous.used_lines_by_hash,
596        &mut current.used_lines_by_hash,
597    );
598    mem::swap(
599        &mut previous.used_wrapped_lines_by_hash,
600        &mut current.used_wrapped_lines_by_hash,
601    );
602    current.used_lines.clear();
603    current.used_wrapped_lines.clear();
604    current.used_lines_by_hash.clear();
605    current.used_wrapped_lines_by_hash.clear();
606}
607
608impl LineLayoutIndex {
609    /// This index, taken from a range that started at `from`, as it falls in
610    /// a copy of that range starting at `to`.
611    pub(crate) fn shifted(&self, from: &Self, to: &Self) -> Self {
612        LineLayoutIndex {
613            font_generation: to.font_generation,
614            lines_index: self.lines_index - from.lines_index + to.lines_index,
615            wrapped_lines_index: self.wrapped_lines_index - from.wrapped_lines_index
616                + to.wrapped_lines_index,
617            lines_by_hash_index: self.lines_by_hash_index - from.lines_by_hash_index
618                + to.lines_by_hash_index,
619            wrapped_lines_by_hash_index: self.wrapped_lines_by_hash_index
620                - from.wrapped_lines_by_hash_index
621                + to.wrapped_lines_by_hash_index,
622        }
623    }
624}
625
626/// Counts the lines the line layout cache hands to the platform to be shaped,
627/// because neither this frame nor the last one had them, and times them.
628///
629/// The line layout cache only remembers the lines of this frame and the last
630/// one. Numbers that change every frame, like prices, keep coming back to
631/// values they had a few frames ago, and a row scrolled out comes back with
632/// the same text. So the lines shaped recently are kept here too, in
633/// [`RecentShapes`], and a line found there is copied instead of shaped again.
634#[derive(Default)]
635pub(crate) struct LineShaping {
636    /// Lines shaped lately, answered without asking the platform again.
637    recent: Mutex<RecentShapes>,
638    /// Numbers put together from their glyphs rather than shaped by the
639    /// platform.
640    numbers: Mutex<crate::fast::number_shaping::NumberShaping>,
641    /// Lines handed to the platform to be shaped. See [`LineShaping::stats`].
642    lines_shaped: AtomicU64,
643    /// Time spent in those calls, in nanoseconds.
644    shape_nanos: AtomicU64,
645    /// Whether to time shaping, which it does once the stats have been reset.
646    shape_timed: AtomicBool,
647}
648
649impl LineShaping {
650    /// How many lines have been shaped, and how long that took, since the last
651    /// [`LineShaping::reset`]. A line answered from the cache is not counted,
652    /// so this is the text work the cache failed to save.
653    #[cfg(any(test, feature = "test-support"))]
654    pub(crate) fn stats(&self) -> (u64, std::time::Duration) {
655        (
656            self.lines_shaped.load(Ordering::Relaxed),
657            std::time::Duration::from_nanos(self.shape_nanos.load(Ordering::Relaxed)),
658        )
659    }
660
661    /// Zeroes the counters reported by [`LineShaping::stats`], and from then
662    /// on times shaping too.
663    #[cfg(any(test, feature = "test-support"))]
664    pub(crate) fn reset(&self) {
665        self.lines_shaped.store(0, Ordering::Relaxed);
666        self.shape_nanos.store(0, Ordering::Relaxed);
667        self.shape_timed.store(true, Ordering::Relaxed);
668    }
669
670    /// Shapes a line the cache does not have, counting it, unless it was
671    /// shaped lately and can be copied from [`RecentShapes`].
672    pub(crate) fn shape_line(
673        &self,
674        platform_text_system: &dyn PlatformTextSystem,
675        text: &str,
676        font_size: Pixels,
677        runs: &[FontRun],
678    ) -> LineLayout {
679        let hash = RecentShapes::hash(text, font_size, runs);
680        if let Some(layout) = self.recent.lock().get(hash, text, font_size, runs) {
681            return layout;
682        }
683        let layout = self.shape_line_uncached(platform_text_system, text, font_size, runs);
684        self.recent
685            .lock()
686            .insert(hash, text, font_size, runs, copy_layout(&layout));
687        layout
688    }
689
690    fn shape_line_uncached(
691        &self,
692        platform_text_system: &dyn PlatformTextSystem,
693        text: &str,
694        font_size: Pixels,
695        runs: &[FontRun],
696    ) -> LineLayout {
697        let started_at = self.shape_timed.load(Ordering::Relaxed).then(Instant::now);
698        let layout = self
699            .numbers
700            .lock()
701            .shape(platform_text_system, text, font_size, runs)
702            .unwrap_or_else(|| platform_text_system.layout_line(text, font_size, runs));
703        self.lines_shaped.fetch_add(1, Ordering::Relaxed);
704        if let Some(started_at) = started_at {
705            self.shape_nanos
706                .fetch_add(started_at.elapsed().as_nanos() as u64, Ordering::Relaxed);
707        }
708        layout
709    }
710}
711
712/// Bumped whenever fonts are added to a text system, which can change how a
713/// line already shaped would shape now (a fallback font it lacked).
714static FONTS_GENERATION: AtomicU64 = AtomicU64::new(0);
715
716/// How many times fonts have been added to a text system.
717pub(crate) fn fonts_generation() -> u64 {
718    FONTS_GENERATION.load(Ordering::Relaxed)
719}
720
721/// Called when fonts are added to a text system, so no line shaped before is
722/// taken from [`RecentShapes`] again.
723#[inline(always)]
724pub(crate) fn fonts_changed() {
725    FONTS_GENERATION.fetch_add(1, Ordering::Relaxed);
726}
727
728/// How many glyphs the lines of one generation of [`RecentShapes`] may hold
729/// before it becomes the old one, which bounds what it keeps to about a
730/// megabyte. Between one and two generations' worth of the most recently used
731/// lines are remembered: some two thousand short numbers, or a few hundred
732/// lines of prose.
733pub(crate) const RECENT_GLYPHS_PER_GENERATION: usize = 16 * 1024;
734
735/// A line shaped lately: what it was shaped from, and what that gave.
736struct RecentShape {
737    text: Box<str>,
738    font_size: Pixels,
739    runs: SmallVec<[FontRun; 1]>,
740    layout: LineLayout,
741}
742
743/// The lines shaped lately, in two generations: lines are added to the
744/// current one, and a line found in the old one moves to the current one.
745/// When the current generation is full, the old one is dropped and the
746/// current one takes its place, so the lines not used for the longest go.
747#[derive(Default)]
748pub(crate) struct RecentShapes {
749    current: FxHashMap<u64, SmallVec<[RecentShape; 1]>>,
750    /// The glyphs in `current`, counting each line at least as one.
751    current_glyphs: usize,
752    old: FxHashMap<u64, SmallVec<[RecentShape; 1]>>,
753    fonts_generation: u64,
754}
755
756impl crate::Window {
757    /// Forgets the lines this window's text system shaped lately, so that a
758    /// test sees what the line layout cache alone keeps.
759    #[cfg(test)]
760    pub(crate) fn forget_recent_shapes(&self) {
761        let shaping = &self.text_system().line_layout_cache.shaping;
762        *shaping.recent.lock() = RecentShapes::default();
763    }
764}
765
766impl RecentShapes {
767    pub(crate) fn hash(text: &str, font_size: Pixels, runs: &[FontRun]) -> u64 {
768        let mut hasher = FxHasher::default();
769        text.hash(&mut hasher);
770        font_size.0.to_bits().hash(&mut hasher);
771        runs.hash(&mut hasher);
772        hasher.finish()
773    }
774
775    pub(crate) fn get(
776        &mut self,
777        hash: u64,
778        text: &str,
779        font_size: Pixels,
780        runs: &[FontRun],
781    ) -> Option<LineLayout> {
782        let fonts_generation = FONTS_GENERATION.load(Ordering::Relaxed);
783        if fonts_generation != self.fonts_generation {
784            self.current.clear();
785            self.current_glyphs = 0;
786            self.old.clear();
787            self.fonts_generation = fonts_generation;
788            return None;
789        }
790        let matches = |shape: &RecentShape| {
791            &*shape.text == text
792                && shape.font_size.0.to_bits() == font_size.0.to_bits()
793                && shape.runs.as_slice() == runs
794        };
795        if let Some(shape) = self
796            .current
797            .get(&hash)
798            .and_then(|shapes| shapes.iter().find(|shape| matches(shape)))
799        {
800            return Some(copy_layout(&shape.layout));
801        }
802        let shapes = self.old.get_mut(&hash)?;
803        let ix = shapes.iter().position(matches)?;
804        let shape = shapes.swap_remove(ix);
805        if shapes.is_empty() {
806            self.old.remove(&hash);
807        }
808        let layout = copy_layout(&shape.layout);
809        self.push(hash, shape);
810        Some(layout)
811    }
812
813    pub(crate) fn insert(
814        &mut self,
815        hash: u64,
816        text: &str,
817        font_size: Pixels,
818        runs: &[FontRun],
819        layout: LineLayout,
820    ) {
821        if self.fonts_generation != FONTS_GENERATION.load(Ordering::Relaxed) {
822            return;
823        }
824        self.push(
825            hash,
826            RecentShape {
827                text: text.into(),
828                font_size,
829                runs: SmallVec::from(runs),
830                layout,
831            },
832        );
833    }
834
835    fn push(&mut self, hash: u64, shape: RecentShape) {
836        if self.current_glyphs >= RECENT_GLYPHS_PER_GENERATION {
837            self.old = mem::take(&mut self.current);
838            self.current_glyphs = 0;
839        }
840        self.current_glyphs += shape
841            .layout
842            .runs
843            .iter()
844            .map(|run| run.glyphs.len())
845            .sum::<usize>()
846            .max(1);
847        self.current.entry(hash).or_default().push(shape);
848    }
849}
850
851/// A copy of a shaped line. (`LineLayout` is public, and cloning it isn't
852/// part of upstream's API.)
853fn copy_layout(layout: &LineLayout) -> LineLayout {
854    // Destructured, so that a field upstream adds can't be missed here.
855    let LineLayout {
856        font_size,
857        width,
858        ascent,
859        descent,
860        runs,
861        len,
862    } = layout;
863    LineLayout {
864        font_size: *font_size,
865        width: *width,
866        ascent: *ascent,
867        descent: *descent,
868        runs: runs.clone(),
869        len: *len,
870    }
871}
872
873/// Shapes a line `cache` does not have, counting it. See [`LineShaping`].
874#[inline(always)]
875pub(crate) fn shape_line(
876    cache: &LineLayoutCache,
877    text: &str,
878    font_size: Pixels,
879    runs: &[FontRun],
880) -> LineLayout {
881    cache
882        .shaping
883        .shape_line(&*cache.platform_text_system, text, font_size, runs)
884}
885
886/// The decoration runs of a line about to be measured. Most lines carry one
887/// decoration run, and highlighted ones a handful; reserving for the worst
888/// case, as upstream does, allocated two kilobytes on every measurement, which
889/// is much of what a short line costs.
890#[inline(always)]
891pub(crate) fn decoration_runs() -> Vec<DecorationRun> {
892    Vec::with_capacity(4)
893}
894
895/// Whether two decoration runs decorate alike, so a line measured with one
896/// can be reused for the other.
897impl PartialEq for DecorationRun {
898    fn eq(&self, other: &Self) -> bool {
899        // Destructured, so that a field upstream adds can't be missed here.
900        let DecorationRun {
901            len,
902            color,
903            background_color,
904            underline,
905            strikethrough,
906        } = self;
907        *len == other.len
908            && *color == other.color
909            && *background_color == other.background_color
910            && *underline == other.underline
911            && *strikethrough == other.strikethrough
912    }
913}
914
915/// Where each of the line layout cache's lists stood, compared to tell
916/// whether a reused range of lines is the one recorded.
917impl PartialEq for LineLayoutIndex {
918    fn eq(&self, other: &Self) -> bool {
919        let LineLayoutIndex {
920            font_generation,
921            lines_index,
922            wrapped_lines_index,
923            lines_by_hash_index,
924            wrapped_lines_by_hash_index,
925        } = self;
926        *font_generation == other.font_generation
927            && *lines_index == other.lines_index
928            && *wrapped_lines_index == other.wrapped_lines_index
929            && *lines_by_hash_index == other.lines_by_hash_index
930            && *wrapped_lines_by_hash_index == other.wrapped_lines_by_hash_index
931    }
932}
933
934impl std::fmt::Debug for LineLayoutIndex {
935    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
936        let LineLayoutIndex {
937            font_generation,
938            lines_index,
939            wrapped_lines_index,
940            lines_by_hash_index,
941            wrapped_lines_by_hash_index,
942        } = self;
943        f.debug_struct("LineLayoutIndex")
944            .field("font_generation", font_generation)
945            .field("lines_index", lines_index)
946            .field("wrapped_lines_index", wrapped_lines_index)
947            .field("lines_by_hash_index", lines_by_hash_index)
948            .field("wrapped_lines_by_hash_index", wrapped_lines_by_hash_index)
949            .finish()
950    }
951}
952
953impl WindowTextSystem {
954    /// Lines shaped by the platform, and the time that took, since the last
955    /// [`Self::reset_shaping_stats`]. Lines answered from the cache do not count.
956    #[cfg(any(test, feature = "test-support"))]
957    pub(crate) fn shaping_stats(&self) -> (u64, std::time::Duration) {
958        self.line_layout_cache.shaping.stats()
959    }
960
961    /// Zeroes the counters reported by [`Self::shaping_stats`].
962    #[cfg(any(test, feature = "test-support"))]
963    pub(crate) fn reset_shaping_stats(&self) {
964        self.line_layout_cache.shaping.reset()
965    }
966}
967
968/// How many fonts [`resolve_font`] remembers, most recently resolved last.
969const RESOLVED_FONTS: usize = 16;
970
971/// A font resolved lately: the text system that resolved it, the fonts
972/// generation it was resolved in, the font asked for and what it resolved to.
973struct ResolvedFont {
974    text_system: std::sync::Weak<dyn PlatformTextSystem>,
975    generation: u64,
976    font: crate::Font,
977    font_id: crate::FontId,
978}
979
980thread_local! {
981    static RESOLVED: std::cell::RefCell<SmallVec<[ResolvedFont; RESOLVED_FONTS]>> =
982        const { std::cell::RefCell::new(SmallVec::new_const()) };
983}
984
985/// Resolves `font` as [`TextSystem::resolve_font`] does, remembering the few
986/// fonts resolved lately: every run of every line shaped asks for its font,
987/// and looking it up hashes the font and takes a lock each time, where a
988/// frame's text uses a handful of fonts.
989#[inline]
990pub(crate) fn resolve_font(text_system: &crate::TextSystem, font: &crate::Font) -> crate::FontId {
991    let generation = FONTS_GENERATION.load(Ordering::Relaxed);
992    let platform = &text_system.platform_text_system;
993    let remembered = RESOLVED.with_borrow(|resolved| {
994        resolved.iter().rev().find_map(|entry| {
995            (entry.generation == generation
996                && entry.text_system.strong_count() > 0
997                && std::ptr::addr_eq(entry.text_system.as_ptr(), Arc::as_ptr(platform))
998                && entry.font == *font)
999                .then_some(entry.font_id)
1000        })
1001    });
1002    if let Some(font_id) = remembered {
1003        return font_id;
1004    }
1005    let font_id = resolve_font_uncached(text_system, font);
1006    RESOLVED.with_borrow_mut(|resolved| {
1007        if resolved.len() == RESOLVED_FONTS {
1008            resolved.remove(0);
1009        }
1010        resolved.push(ResolvedFont {
1011            text_system: Arc::downgrade(platform),
1012            generation,
1013            font: font.clone(),
1014            font_id,
1015        });
1016    });
1017    font_id
1018}
1019
1020/// [`TextSystem::resolve_font`]: the font, or else the first of the
1021/// fallbacks that resolves — in the weight and style asked for, with the
1022/// features asked for, where the fallback family has them.
1023///
1024/// Upstream resolves a fallback as the fallback stack names it, plain: text
1025/// asked for in bold came out regular, and with its features — tabular
1026/// numerals, say — dropped, so digits of a family that isn't installed took
1027/// their proportional widths, and a ticking price changed width, and laid
1028/// out its row again, every time it changed.
1029fn resolve_font_uncached(text_system: &crate::TextSystem, font: &crate::Font) -> crate::FontId {
1030    if let Ok(font_id) = text_system.font_id(font) {
1031        return font_id;
1032    }
1033    for fallback in &text_system.fallback_font_stack {
1034        let as_asked = crate::Font {
1035            family: fallback.family.clone(),
1036            features: font.features.clone(),
1037            fallbacks: font.fallbacks.clone(),
1038            weight: font.weight,
1039            style: font.style,
1040        };
1041        if let Ok(font_id) = text_system.font_id(&as_asked) {
1042            return font_id;
1043        }
1044        if let Ok(font_id) = text_system.font_id(fallback) {
1045            return font_id;
1046        }
1047    }
1048    panic!(
1049        "failed to resolve font '{}' or any of the fallbacks: {}",
1050        font.family,
1051        text_system
1052            .fallback_font_stack
1053            .iter()
1054            .map(|fallback| fallback.family.to_string())
1055            .collect::<Vec<_>>()
1056            .join(", ")
1057    );
1058}
1059
1060#[cfg(test)]
1061mod tests {
1062    use super::{TextMeasureInputs, measure_text};
1063    use crate::{AppContext as _, AvailableSpace, Size, TestAppContext, TextLayout, px};
1064    use std::cell::RefCell;
1065
1066    /// Taffy can measure a retained leaf under other constraints after it has
1067    /// been laid out: at width zero, say, when a node above it is sized to its
1068    /// content again. Text it wrapped there must not answer a later probe for
1069    /// its unwrapped width with the width it wrapped to: a box as wide as its
1070    /// content would take that width, the text would wrap in it, and the box
1071    /// would stay that narrow with room for the text on one line.
1072    #[test]
1073    fn text_wrapped_narrow_does_not_answer_for_its_unwrapped_width() {
1074        let mut cx = TestAppContext::single();
1075        let window = cx.add_window(|_, _| crate::Empty);
1076        cx.update_window(window.into(), |_, window, cx| {
1077            let text_style = crate::fast::text_style::text_style(window);
1078            let font_size = text_style.font_size.to_pixels(window.rem_size());
1079            let line_height = text_style
1080                .line_height
1081                .to_pixels(font_size.into(), window.rem_size());
1082            let inputs = TextMeasureInputs {
1083                text: "the quick brown fox jumps over the lazy dog".into(),
1084                runs: Vec::new(),
1085                text_style,
1086                font_size,
1087                line_height,
1088                layout: RefCell::new(TextLayout::default()),
1089            };
1090            let probe = |width| Size {
1091                width,
1092                height: AvailableSpace::MaxContent,
1093            };
1094            let unwrapped = measure_text(
1095                &inputs,
1096                Size::default(),
1097                probe(AvailableSpace::MaxContent),
1098                window,
1099                cx,
1100            );
1101
1102            let narrow = px(40.);
1103            let wrapped = measure_text(
1104                &inputs,
1105                Size {
1106                    width: Some(narrow),
1107                    height: None,
1108                },
1109                probe(AvailableSpace::Definite(narrow)),
1110                window,
1111                cx,
1112            );
1113            assert!(
1114                wrapped.width < unwrapped.width,
1115                "the text should wrap at {narrow:?}: {wrapped:?}, unwrapped {unwrapped:?}"
1116            );
1117
1118            for width in [AvailableSpace::MaxContent, AvailableSpace::MinContent] {
1119                assert_eq!(
1120                    measure_text(&inputs, Size::default(), probe(width), window, cx),
1121                    unwrapped,
1122                    "probed under {width:?} after wrapping at {narrow:?}"
1123                );
1124            }
1125        })
1126        .unwrap();
1127    }
1128}