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