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