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