From 79af38b26c7571fbbdf84b8dd1f19d4426e58df7 Mon Sep 17 00:00:00 2001 From: Anthony Eid <56899983+Anthony-Eid@users.noreply.github.com> Date: Tue, 24 Nov 2026 09:49:03 +0000 Subject: [PATCH] gpui: Keep measured layouts while their inputs are unchanged (#67223) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit With layout nodes kept between frames, a node sized by a measure function still can't stay cached: the function is a new closure every frame, so there is no way to tell whether it would measure the same sizes. That covers every text element, and invalidating one invalidates its ancestors too. This adds `Window::request_keyed_measured_layout`, which takes a key describing everything the measured size depends on. While the key equals the one the node was last measured with, Taffy's cached sizes are kept and the measure function isn't called. `request_measured_layout` is unchanged and still measures every frame. On steady-state frames, same-type measure contexts are updated in place to avoid allocating and freeing a `Box` per measured node per frame. Text elements use it. Their key is the text, runs, text style, font size, line height, scale factor, and the text system's font generation. Unchanged text takes over the lines it shaped last frame and paints from those, so it is neither measured nor shaped again. - Text is measured from its own inputs alone, and only `PerformLayout` (not sizing probes) replaces the lines kept for painting. - The line layout cache keeps layouts that an element still holds even in frames that don't shape them, and now includes `max_lines` (`line_clamp`) in its cache key. - `TaffyLayoutEngine` clears its layout cache when a window's `scale_factor` changes so device-pixel cached measurements (such as `list` and `uniform_list`) never go stale across displays. - `list` and `uniform_list` key their `ListSizingBehavior::Infer` measurements. Testing: - Targeted tests verify that keyed leaves and text elements are measured again only when their inputs change (including `TextSystem::add_fonts`), that keyed leaves update on `scale_factor` changes, and that `LineLayoutCache` distinguishes `max_lines`. - Expanded `RandomizedElementTree` and `layout_cache_matches_rebuilding_every_frame` to cover flex, grid, absolute positioning, `Display::None`, `with_rem_size`, single-field mutations, root inherited text styles and scope changes, deferred anchored popups, `StyledText`/`InteractiveText` with mouse moves, keyed/unkeyed measured leaves, and scrolling `list`/`uniform_list` (128 seeds / 6,144 frames verified locally). Performance: instructions per frame against `main` in the GPUI benchmarks (`script/gpui-bench-compare`), including the previous PR. These are synthetic trees, not Zed scenarios. | Benchmark | Previous PR | With this PR | |---|---:|---:| | Full refresh, trees with paths | −2.2% to −8.2% | −3.0% to −32% | | Full refresh, trees without paths | −8.3% to −19.6% | −22% to −34% | | ID churn (no node can be matched) | −1.3% / −3.9% | −1.1% / −2.8% | | Warm text, 32 panels | −7.3% | −38.6% | | First populated text frame | −4.3% | −4.1% | | Scrolling a pane of text rows | −7.9% | −57.2% | | `uniform_list` scrolling | −5.7% | −27.5% | | Inspector panel, 500 rows | −7.2% | −52.4% | Release Notes: - [GPUI] Added `Window::request_keyed_measured_layout`, which keeps a measured element's size while its key is unchanged - Improved layout performance in Zed's renderer --- crates/gpui/src/elements/list.rs | 3 +- crates/gpui/src/elements/text.rs | 442 ++++-- crates/gpui/src/elements/uniform_list.rs | 3 +- crates/gpui/src/randomized_element_tree.rs | 1433 +++++++++++++++++++- crates/gpui/src/taffy.rs | 436 +++++- crates/gpui/src/text_system.rs | 10 + crates/gpui/src/text_system/line_layout.rs | 77 +- crates/gpui/src/window.rs | 99 +- 8 files changed, 2254 insertions(+), 249 deletions(-) diff --git a/crates/gpui/src/elements/list.rs b/crates/gpui/src/elements/list.rs index eaa72361687..eecfd76dc88 100644 --- a/crates/gpui/src/elements/list.rs +++ b/crates/gpui/src/elements/list.rs @@ -1505,8 +1505,9 @@ impl Element for List { let summary = state.items.summary(); let total_height = summary.height; - window.request_measured_layout( + window.request_keyed_measured_layout( style, + (max_element_width, total_height), move |known_dimensions, available_space, _window, _cx| { let width = known_dimensions diff --git a/crates/gpui/src/elements/text.rs b/crates/gpui/src/elements/text.rs index 1c9f660dceb..096e3040f22 100644 --- a/crates/gpui/src/elements/text.rs +++ b/crates/gpui/src/elements/text.rs @@ -598,6 +598,216 @@ struct TextLayoutInner { bounds: Option>, } +/// What a text element's size depends on, and where its measurement is stored for +/// painting. +pub(crate) struct TextMeasure { + text: SharedString, + runs: Vec, + text_style: TextStyle, + font_size: Pixels, + line_height: Pixels, + scale_factor: f32, + font_generation: usize, + element_state: TextLayout, +} + +impl TextMeasure { + /// Takes over the lines `previous` measured, so a text element that hasn't changed + /// since the last frame can paint without being measured again. + fn reuse_measurement(&mut self, previous: &mut TextMeasure) -> bool { + if self.text != previous.text + || self.font_size != previous.font_size + || self.line_height != previous.line_height + || self.scale_factor != previous.scale_factor + || self.font_generation != previous.font_generation + || self.runs != previous.runs + || self.text_style != previous.text_style + { + return false; + } + // Whoever holds the previous frame's layout, such as an element reading it in an + // event handler, keeps it; otherwise it is moved rather than copied. + let measured = if Rc::strong_count(&previous.element_state.0) == 1 { + previous.element_state.0.borrow_mut().take() + } else { + previous + .element_state + .0 + .borrow() + .as_ref() + .map(TextLayoutInner::clone_measurement) + }; + let Some(mut measured) = measured else { + return false; + }; + measured.bounds = None; + *self.element_state.0.borrow_mut() = Some(measured); + true + } + + /// Measures the text. The size only depends on the measure's inputs and the space + /// given, never on what was measured before. + /// + /// The final measurement's lines (`final_layout`, made after any sizing probes) are + /// kept for painting, since Taffy may serve that measurement from its cache instead + /// of measuring again, and a probe's lines would be painted in bounds that weren't + /// computed from them. + fn measure( + &self, + known_dimensions: Size>, + available_space: Size, + final_layout: bool, + window: &mut Window, + cx: &mut App, + ) -> Size { + let Self { + text, + runs, + text_style, + font_size, + line_height, + element_state, + .. + } = self; + let font_size = *font_size; + let line_height = *line_height; + let wrap_width = if text_style.white_space == WhiteSpace::Normal { + known_dimensions.width.or(match available_space.width { + crate::AvailableSpace::Definite(x) => Some(x), + _ => None, + }) + } else { + None + }; + + let (truncate_width, truncation_affix, truncate_from) = + if let Some(text_overflow) = text_style.text_overflow.clone() { + let width = known_dimensions.width.or(match available_space.width { + crate::AvailableSpace::Definite(x) => match text_style.line_clamp { + Some(max_lines) => Some(x * max_lines), + None => Some(x), + }, + _ => None, + }); + + match text_overflow { + TextOverflow::Truncate(s) => (width, s, TruncateFrom::End), + TextOverflow::TruncateStart(s) => (width, s, TruncateFrom::Start), + TextOverflow::TruncateMiddle(s) => (width, s, TruncateFrom::Middle), + } + } else { + (None, "".into(), TruncateFrom::End) + }; + + if let Some(text_layout) = element_state.0.borrow().as_ref() + && let Some(size) = text_layout.size + && wrap_width == text_layout.wrap_width + && truncate_width == text_layout.truncate_width + { + return size; + } + + let (text, runs) = if let Some(truncate_width) = truncate_width { + // Taking a wrapper from the pool locks it twice and moves its + // character width cache around, so only do it when truncating. + let mut line_wrapper = cx.text_system().line_wrapper(text_style.font(), font_size); + if let Some(max_lines) = text_style.line_clamp + && let Some(wrap_width) = wrap_width + { + line_wrapper.truncate_wrapped_line( + text.clone(), + wrap_width, + max_lines, + &truncation_affix, + &runs, + truncate_from, + ) + } else if let Some(unclipped) = window + .text_system() + .shape_text(text.clone(), font_size, &runs, None, None) + .log_err() + && unclipped + .iter() + .all(|line| line.size(line_height).width <= truncate_width) + { + // The truncation decision below sums per-character advances, + // which overestimates the shaped width (no kerning), truncating + // text that fits exactly in its measured width. Skip truncation + // whenever the honestly-shaped text fits; the shaping result + // comes from the line layout cache when the same text was + // already measured untruncated this frame. + (text.clone(), Cow::Borrowed(runs.as_slice())) + } else { + line_wrapper.truncate_line( + text.clone(), + truncate_width, + &truncation_affix, + &runs, + truncate_from, + ) + } + } else { + (text.clone(), Cow::Borrowed(runs.as_slice())) + }; + let len = text.len(); + + // Text that fails to shape is measured as empty. + let (lines, len) = window + .text_system() + .shape_text( + text, + font_size, + &runs, + wrap_width, // Wrap if we know the width. + text_style.line_clamp, // Limit the number of lines if line_clamp is set. + ) + .log_err() + .map(|lines| (lines, len)) + .unwrap_or_default(); + + let mut size: Size = Size::default(); + for line in &lines { + let line_size = line.size(line_height); + size.height += line_size.height; + size.width = size.width.max(line_size.width).ceil(); + } + if final_layout || element_state.0.borrow().is_none() { + element_state.0.borrow_mut().replace(TextLayoutInner { + lines, + len, + line_height, + wrap_width, + truncate_width, + size: Some(size), + bounds: None, + }); + } + size + } +} + +impl TextLayoutInner { + fn clone_measurement(&self) -> Self { + Self { + len: self.len, + lines: self + .lines + .iter() + .map(|line| WrappedLine { + layout: line.layout.clone(), + text: line.text.clone(), + decoration_runs: line.decoration_runs.clone(), + }) + .collect(), + line_height: self.line_height, + wrap_width: self.wrap_width, + truncate_width: self.truncate_width, + size: self.size, + bounds: None, + } + } +} + impl TextLayout { fn layout( &self, @@ -606,6 +816,20 @@ impl TextLayout { window: &mut Window, _: &mut App, ) -> LayoutId { + window.request_keyed_measure( + &crate::Style::default(), + self.measurement(text, runs, window), + TextMeasure::reuse_measurement, + TextMeasure::measure, + ) + } + + fn measurement( + &self, + text: SharedString, + runs: Option>, + window: &Window, + ) -> TextMeasure { let text_style = window.text_style(); let font_size = text_style.font_size.to_pixels(window.rem_size()); let line_height = window.pixel_snap( @@ -619,143 +843,16 @@ impl TextLayout { } else { vec![text_style.to_run(text.len())] }; - window.request_measured_layout(Default::default(), { - let element_state = self.clone(); - - move |known_dimensions, available_space, window, cx| { - let wrap_width = if text_style.white_space == WhiteSpace::Normal { - known_dimensions.width.or(match available_space.width { - crate::AvailableSpace::Definite(x) => Some(x), - _ => None, - }) - } else { - None - }; - - let (truncate_width, truncation_affix, truncate_from) = - if let Some(text_overflow) = text_style.text_overflow.clone() { - let width = known_dimensions.width.or(match available_space.width { - crate::AvailableSpace::Definite(x) => match text_style.line_clamp { - Some(max_lines) => Some(x * max_lines), - None => Some(x), - }, - _ => None, - }); - - match text_overflow { - TextOverflow::Truncate(s) => (width, s, TruncateFrom::End), - TextOverflow::TruncateStart(s) => (width, s, TruncateFrom::Start), - TextOverflow::TruncateMiddle(s) => (width, s, TruncateFrom::Middle), - } - } else { - (None, "".into(), TruncateFrom::End) - }; - - // Only use cached layout if: - // 1. We have a cached size - // 2. wrap_width matches (or both are None) - // 3. truncate_width is None (if truncate_width is Some, we need to re-layout - // because the previous layout may have been computed without truncation) - // 4. the cached layout was not truncated (a truncated layout answers an - // unconstrained probe with the truncated size, which poisons intrinsic - // sizing with whatever width some earlier measure pass happened to use) - if let Some(text_layout) = element_state.0.borrow().as_ref() - && let Some(size) = text_layout.size - && (wrap_width.is_none() || wrap_width == text_layout.wrap_width) - && truncate_width.is_none() - && text_layout.truncate_width.is_none() - { - return size; - } - - let (text, runs) = if let Some(truncate_width) = truncate_width { - // Taking a wrapper from the pool locks it twice and moves its - // character width cache around, so only do it when truncating. - let mut line_wrapper = - cx.text_system().line_wrapper(text_style.font(), font_size); - if let Some(max_lines) = text_style.line_clamp - && let Some(wrap_width) = wrap_width - { - line_wrapper.truncate_wrapped_line( - text.clone(), - wrap_width, - max_lines, - &truncation_affix, - &runs, - truncate_from, - ) - } else if let Some(unclipped) = window - .text_system() - .shape_text(text.clone(), font_size, &runs, None, None) - .log_err() - && unclipped - .iter() - .all(|line| line.size(line_height).width <= truncate_width) - { - // The truncation decision below sums per-character advances, - // which overestimates the shaped width (no kerning), truncating - // text that fits exactly in its measured width. Skip truncation - // whenever the honestly-shaped text fits; the shaping result - // comes from the line layout cache when the same text was - // already measured untruncated this frame. - (text.clone(), Cow::Borrowed(&*runs)) - } else { - line_wrapper.truncate_line( - text.clone(), - truncate_width, - &truncation_affix, - &runs, - truncate_from, - ) - } - } else { - (text.clone(), Cow::Borrowed(&*runs)) - }; - let len = text.len(); - - let Some(lines) = window - .text_system() - .shape_text( - text, - font_size, - &runs, - wrap_width, // Wrap if we know the width. - text_style.line_clamp, // Limit the number of lines if line_clamp is set. - ) - .log_err() - else { - element_state.0.borrow_mut().replace(TextLayoutInner { - lines: Default::default(), - len: 0, - line_height, - wrap_width, - truncate_width, - size: Some(Size::default()), - bounds: None, - }); - return Size::default(); - }; - - let mut size: Size = Size::default(); - for line in &lines { - let line_size = line.size(line_height); - size.height += line_size.height; - size.width = size.width.max(line_size.width).ceil(); - } - - element_state.0.borrow_mut().replace(TextLayoutInner { - lines, - len, - line_height, - wrap_width, - truncate_width, - size: Some(size), - bounds: None, - }); - - size - } - }) + TextMeasure { + text, + runs, + text_style, + font_size, + line_height, + scale_factor: window.scale_factor(), + font_generation: window.text_system().font_generation(), + element_state: self.clone(), + } } fn prepaint(&self, bounds: Bounds, text: &str) { @@ -1280,6 +1377,77 @@ impl Element for InteractiveText { mod tests { use super::*; + #[crate::test] + fn text_measurement_depends_only_on_its_inputs(cx: &mut crate::TestAppContext) { + let cx = cx.add_empty_window(); + cx.update(|window, cx| { + let text = SharedString::from("Several words that wrap in a narrow parent"); + let narrow = Size { + width: crate::AvailableSpace::Definite(crate::px(60.)), + height: crate::AvailableSpace::MaxContent, + }; + let wide = Size { + width: crate::AvailableSpace::Definite(crate::px(2000.)), + ..narrow + }; + let unconstrained = Size { + width: crate::AvailableSpace::MaxContent, + ..narrow + }; + // The height of the lines a layout would paint. + let painted_height = |layout: &TextLayout| { + layout.0.borrow().as_ref().map(|measured| { + measured + .lines + .iter() + .map(|line| line.size(measured.line_height).height) + .sum::() + }) + }; + let fresh_size = + |space: Size, window: &mut Window, cx: &mut App| { + TextLayout::default() + .measurement(text.clone(), None, window) + .measure(Size::default(), space, false, window, cx) + }; + + let layout = TextLayout::default(); + let mut measure = layout.measurement(text.clone(), None, window); + let narrow_size = measure.measure(Size::default(), narrow, true, window, cx); + // An unconstrained probe measures the unwrapped text, rather than answering + // with the size of whatever was measured before it. + let unconstrained_size = + measure.measure(Size::default(), unconstrained, false, window, cx); + assert_eq!(unconstrained_size, fresh_size(unconstrained, window, cx)); + assert!(unconstrained_size.width > narrow_size.width); + assert!(unconstrained_size.height < narrow_size.height); + + // Probes don't replace the lines kept for painting; the final measurement does. + assert_eq!(painted_height(&layout), Some(narrow_size.height)); + let wide_size = measure.measure(Size::default(), wide, false, window, cx); + assert!(wide_size.height < narrow_size.height); + assert_eq!(painted_height(&layout), Some(narrow_size.height)); + measure.measure(Size::default(), wide, true, window, cx); + assert_eq!(painted_height(&layout), Some(wide_size.height)); + + // A measure with the same inputs takes over the lines, and measures the same + // as one measuring from scratch. + let next_layout = TextLayout::default(); + let mut next = next_layout.measurement(text.clone(), None, window); + assert!(next.reuse_measurement(&mut measure)); + assert_eq!(painted_height(&next_layout), Some(wide_size.height)); + for space in [narrow, wide, unconstrained] { + assert_eq!( + next.measure(Size::default(), space, false, window, cx), + fresh_size(space, window, cx) + ); + } + + let mut changed = TextLayout::default().measurement("Other text".into(), None, window); + assert!(!changed.reuse_measurement(&mut next)); + }); + } + #[test] fn test_into_element_for() { use crate::{ParentElement as _, SharedString, div}; diff --git a/crates/gpui/src/elements/uniform_list.rs b/crates/gpui/src/elements/uniform_list.rs index ad31cda493d..e1967b07604 100644 --- a/crates/gpui/src/elements/uniform_list.rs +++ b/crates/gpui/src/elements/uniform_list.rs @@ -289,8 +289,9 @@ impl Element for UniformList { |style, window, cx| match self.sizing_behavior { ListSizingBehavior::Infer => { window.with_text_style(style.text_style().cloned(), |window| { - window.request_measured_layout( + window.request_keyed_measured_layout( style, + (item_size, max_items), move |known_dimensions, available_space, _window, _cx| { let desired_height = item_size.height * max_items; let width = known_dimensions.width.unwrap_or(match available_space diff --git a/crates/gpui/src/randomized_element_tree.rs b/crates/gpui/src/randomized_element_tree.rs index dabe0e24525..6fa7efa94e9 100644 --- a/crates/gpui/src/randomized_element_tree.rs +++ b/crates/gpui/src/randomized_element_tree.rs @@ -1,8 +1,12 @@ //! A seeded, mutable element tree for benchmarks and tests of GPUI rendering. use crate::{ - AnimationExt as _, AnyElement, AppContext as _, Context, ElementId, Entity, Hsla, - InteractiveElement, IntoElement, ParentElement, Render, StatefulInteractiveElement, Styled, - Window, div, px, util::FluentBuilder, + AlignContent, AlignItems, AlignSelf, AnimationExt as _, AnyElement, App, AppContext as _, + AvailableSpace, Bounds, Context, Element, ElementId, Entity, GlobalElementId, HighlightStyle, + Hsla, InspectorElementId, InteractiveElement, InteractiveText, IntoElement, JustifyContent, + LayoutId, ListAlignment, ListOffset, ListSizingBehavior, ListState, ParentElement, Pixels, + Render, Size, StatefulInteractiveElement, StrikethroughStyle, Style, Styled, StyledText, + TextAlign, TextOverflow, UnderlineStyle, UniformListScrollHandle, WhiteSpace, Window, anchored, + deferred, div, fill, list, point, px, relative, rems, size, uniform_list, util::FluentBuilder, }; use collections::{HashMap, HashSet}; use rand::{Rng as _, SeedableRng as _, rngs::StdRng}; @@ -385,6 +389,21 @@ impl RandomizedElementTreeSnapshot { fn node(&self, element_id: u64) -> Option<&RandomizedElementNode> { node_at_path(&self.children, self.paths_by_element_id.get(&element_id)?) } + + /// Returns element IDs for keyed nodes, matching the `"randomized-element"` entries + /// whose element state is recorded during `request_layout`. + #[cfg(test)] + fn keyed_element_ids(&self) -> Vec { + let mut ids = Vec::new(); + let mut stack = self.children.iter().collect::>(); + while let Some(node) = stack.pop() { + if node.is_keyed() { + ids.push(node.id); + } + stack.extend(node.children.iter()); + } + ids + } } /// A requested class of deterministic randomized-tree mutation. @@ -402,6 +421,10 @@ pub enum RandomizedElementTreeMutationKind { RootClipping, /// Toggle root visibility. RootVisibility, + /// Change one field of the root's inherited default text style. + RootTextStyle, + /// Cycle the root's optional scope wrapper element ID. + RootScope, /// Change a seeded random descendant's colors. ChildColor, /// Change a seeded random descendant's opacity. @@ -417,6 +440,18 @@ pub enum RandomizedElementTreeMutationKind { /// Change a seeded random descendant's text, adding text to one that had none or /// removing it from one that didn't always have it. ChildText, + /// Toggle `Display::None` on a seeded random descendant. + ChildDisplay, + /// Mutate layout properties (`auto` sizing, `rems`, margin, flex grow/shrink, + /// direction, wrap, alignment, aspect ratio, unkeyed ID) on a seeded random descendant. + ChildLayout, + /// Mutate text styling (`color`, `font_size`, `line_height`, `white_space`, + /// `text_overflow`, `line_clamp`, `text_align`, runs/interactive text) on a descendant. + ChildTextStyle, + /// Mutate a descendant's measured leaf or inferred-size list content. + ChildMeasuredContent, + /// Mutate a descendant's deferred anchored popup. + ChildPopup, /// Reorder a seeded random descendant among its siblings. Reorder, /// Insert a generated descendant below a seeded random parent. @@ -431,13 +466,15 @@ pub enum RandomizedElementTreeMutationKind { impl RandomizedElementTreeMutationKind { /// Every supported mutation kind, suitable for parameterized tests and benchmarks. - pub const ALL: [Self; 17] = [ + pub const ALL: [Self; 24] = [ Self::RootColor, Self::RootOpacity, Self::RootBorder, Self::RootBounds, Self::RootClipping, Self::RootVisibility, + Self::RootTextStyle, + Self::RootScope, Self::ChildColor, Self::ChildOpacity, Self::ChildBorder, @@ -445,6 +482,11 @@ impl RandomizedElementTreeMutationKind { Self::ChildClipping, Self::ChildVisibility, Self::ChildText, + Self::ChildDisplay, + Self::ChildLayout, + Self::ChildTextStyle, + Self::ChildMeasuredContent, + Self::ChildPopup, Self::Reorder, Self::Insert, Self::Remove, @@ -467,6 +509,10 @@ pub enum RandomizedElementTreeMutation { RootClipping, /// Toggled root visibility. RootVisibility, + /// Changed the root's inherited default text style. + RootTextStyle, + /// Changed the root's scope wrapper element ID. + RootScope, /// Changed a descendant's colors. ChildColor { /// The stable ID of the mutated element. @@ -502,6 +548,31 @@ pub enum RandomizedElementTreeMutation { /// The stable ID of the mutated element. element_id: u64, }, + /// Toggled `Display::None` on a descendant. + ChildDisplay { + /// The stable ID of the mutated element. + element_id: u64, + }, + /// Changed a descendant's layout properties. + ChildLayout { + /// The stable ID of the mutated element. + element_id: u64, + }, + /// Changed a descendant's text styling. + ChildTextStyle { + /// The stable ID of the mutated element. + element_id: u64, + }, + /// Changed a descendant's measured leaf or list content. + ChildMeasuredContent { + /// The stable ID of the mutated element. + element_id: u64, + }, + /// Changed a descendant's deferred anchored popup. + ChildPopup { + /// The stable ID of the mutated element. + element_id: u64, + }, /// Moved an element to a different position among its siblings. Reordered { /// The stable ID of the moved element. @@ -561,6 +632,8 @@ pub struct RandomizedElementTree { snapshot: Rc>, entities: Rc>, scroll_handles: Rc>>, + list_states: Rc>>, + uniform_list_scroll_handles: Rc>>, work_counters: Rc>, config: RandomizedElementTreeConfig, rng: StdRng, @@ -613,6 +686,7 @@ impl RandomizedElementTree { hover_styles: config.hover_styles, paths: config.paths, id_generation: 0, + root_scope: 0, }, paths_by_element_id: HashMap::default(), }; @@ -622,6 +696,8 @@ impl RandomizedElementTree { snapshot: Rc::new(RefCell::new(snapshot)), entities: Rc::new(RefCell::new(HashMap::default())), scroll_handles: Rc::default(), + list_states: Rc::default(), + uniform_list_scroll_handles: Rc::default(), work_counters: Rc::new(RefCell::new(RandomizedElementTreeWorkCounters::default())), config, rng, @@ -635,6 +711,8 @@ impl RandomizedElementTree { snapshot: Rc::new(RefCell::new(snapshot)), entities: Rc::new(RefCell::new(HashMap::default())), scroll_handles: Rc::default(), + list_states: Rc::default(), + uniform_list_scroll_handles: Rc::default(), work_counters: Rc::new(RefCell::new(RandomizedElementTreeWorkCounters::default())), rng: StdRng::seed_from_u64(0), } @@ -807,6 +885,22 @@ impl RandomizedElementTree { RandomizedElementTreeMutation::RootVisibility, ) } + RandomizedElementTreeMutationKind::RootTextStyle => { + self.snapshot + .borrow_mut() + .root + .rich + .text + .mutate(&mut self.rng); + AppliedRandomizedElementTreeMutation::root( + RandomizedElementTreeMutation::RootTextStyle, + ) + } + RandomizedElementTreeMutationKind::RootScope => { + let mut snapshot = self.snapshot.borrow_mut(); + snapshot.render_options.root_scope = (snapshot.render_options.root_scope + 1) % 3; + AppliedRandomizedElementTreeMutation::root(RandomizedElementTreeMutation::RootScope) + } RandomizedElementTreeMutationKind::ChildColor => { self.mutate_random_child(RandomizedChildMutation::Color) } @@ -828,6 +922,21 @@ impl RandomizedElementTree { RandomizedElementTreeMutationKind::ChildText => { self.mutate_random_child(RandomizedChildMutation::Text) } + RandomizedElementTreeMutationKind::ChildDisplay => { + self.mutate_random_child(RandomizedChildMutation::Display) + } + RandomizedElementTreeMutationKind::ChildLayout => { + self.mutate_random_child(RandomizedChildMutation::Layout) + } + RandomizedElementTreeMutationKind::ChildTextStyle => { + self.mutate_random_child(RandomizedChildMutation::TextStyle) + } + RandomizedElementTreeMutationKind::ChildMeasuredContent => { + self.mutate_random_child(RandomizedChildMutation::MeasuredContent) + } + RandomizedElementTreeMutationKind::ChildPopup => { + self.mutate_random_child(RandomizedChildMutation::Popup) + } RandomizedElementTreeMutationKind::Reorder => self.reorder_child(), RandomizedElementTreeMutationKind::Insert => self.insert_child_internal(), RandomizedElementTreeMutationKind::Remove => self @@ -1028,6 +1137,27 @@ impl RandomizedElementTree { (node.style.label + self.rng.random_range(1..LABELS.len())) % LABELS.len(); RandomizedElementTreeMutation::ChildText { element_id } } + RandomizedChildMutation::Display => { + node.style.rich.display_none = !node.style.rich.display_none; + RandomizedElementTreeMutation::ChildDisplay { element_id } + } + RandomizedChildMutation::Layout => { + node.style.mutate_layout(&mut self.rng); + RandomizedElementTreeMutation::ChildLayout { element_id } + } + RandomizedChildMutation::TextStyle => { + node.style.rich.text_override = true; + node.style.rich.text.mutate(&mut self.rng); + RandomizedElementTreeMutation::ChildTextStyle { element_id } + } + RandomizedChildMutation::MeasuredContent => { + node.style.rich.mutate_measured(&mut self.rng); + RandomizedElementTreeMutation::ChildMeasuredContent { element_id } + } + RandomizedChildMutation::Popup => { + node.style.rich.mutate_popup(&mut self.rng); + RandomizedElementTreeMutation::ChildPopup { element_id } + } }; AppliedRandomizedElementTreeMutation { mutation, @@ -1122,6 +1252,8 @@ impl RandomizedElementTree { snapshot: self.snapshot.clone(), entities: weak_entities.clone(), scroll_handles: self.scroll_handles.clone(), + list_states: self.list_states.clone(), + uniform_list_scroll_handles: self.uniform_list_scroll_handles.clone(), work_counters: self.work_counters.clone(), }); self.entities.borrow_mut().insert(element_id, entity); @@ -1147,14 +1279,48 @@ impl Render for RandomizedElementTree { let mut work_counters = self.work_counters.borrow_mut(); work_counters.record_root_render(); - div() + let children = snapshot.children.iter().map(|node| { + render_node( + node, + &entities, + &self.scroll_handles, + &self.list_states, + &self.uniform_list_scroll_handles, + &mut work_counters, + snapshot.render_options, + ) + }); + let content: AnyElement = match snapshot.render_options.root_scope { + 1 => div() + .id("randomized-root-scope-a") + .flex() + .when(root.vertical, |element| element.flex_col()) + .when(root.wrap, |element| element.flex_wrap()) + .gap(px(root.gap)) + .children(children) + .into_any_element(), + 2 => div() + .id("randomized-root-scope-b") + .flex() + .when(root.vertical, |element| element.flex_col()) + .when(root.wrap, |element| element.flex_wrap()) + .gap(px(root.gap)) + .children(children) + .into_any_element(), + _ => div() + .flex() + .when(root.vertical, |element| element.flex_col()) + .when(root.wrap, |element| element.flex_wrap()) + .gap(px(root.gap)) + .children(children) + .into_any_element(), + }; + + let mut root_div = div() .flex() .when(snapshot.render_options.hover_styles, |element| { element.group("randomized-tree-root") }) - .when(root.vertical, |element| element.flex_col()) - .when(root.wrap, |element| element.flex_wrap()) - .gap(px(root.gap)) .p(px(root.padding)) .w(px(root.width)) .h(px(root.height)) @@ -1167,16 +1333,9 @@ impl Render for RandomizedElementTree { .rounded(px(root.corner_radius)) .opacity(root.opacity) .when(root.clipped, |element| element.overflow_hidden()) - .when(!root.visible, |element| element.invisible()) - .children(snapshot.children.iter().map(|node| { - render_node( - node, - &entities, - &self.scroll_handles, - &mut work_counters, - snapshot.render_options, - ) - })) + .when(!root.visible, |element| element.invisible()); + apply_text_style(&mut root_div, &root.rich.text); + root_div.child(content) } } @@ -1192,6 +1351,7 @@ struct RenderOptions { hover_styles: bool, paths: bool, id_generation: u64, + root_scope: u8, } struct RandomizedElementEntity { @@ -1199,6 +1359,8 @@ struct RandomizedElementEntity { snapshot: Rc>, entities: Weak>, scroll_handles: Rc>>, + list_states: Rc>>, + uniform_list_scroll_handles: Rc>>, work_counters: Rc>, } @@ -1217,6 +1379,8 @@ impl Render for RandomizedElementEntity { node, entities.as_deref(), &self.scroll_handles, + &self.list_states, + &self.uniform_list_scroll_handles, &mut work_counters, snapshot.render_options, ) @@ -1252,13 +1416,16 @@ struct RandomizedElementNode { impl RandomizedElementNode { fn random(id: u64, config: &RandomizedElementTreeConfig, rng: &mut StdRng) -> Self { - let style = RandomizedElementStyle::random_child(rng); + let mut style = RandomizedElementStyle::random_child(rng); let is_entity = rng.random_bool(config.entity_density); let mut features = RandomizedElementFeatures::random(config.handler_density, rng); // Drawn only when enabled, so trees without animations keep the same RNG stream. features.animated = is_entity && config.animation_density > 0.0 && rng.random_bool(config.animation_density); + if rng.random_bool(0.35) { + style.rich = RandomizedRichLayout::random(rng); + } Self { id, style, @@ -1277,6 +1444,10 @@ impl RandomizedElementNode { } count } + + fn is_keyed(&self) -> bool { + !self.style.rich.unkeyed || self.id.is_multiple_of(3) || self.is_entity + } } #[derive(Clone, Debug, PartialEq)] @@ -1320,13 +1491,772 @@ struct RandomizedElementStyle { /// Index into [`LABELS`] of the element's text. Not drawn when generating a tree, so /// adding it left every seed's tree as it was. label: usize, + /// Additional layout and measured-content state used when `rich_layout` is enabled. + rich: RandomizedRichLayout, +} + +#[derive(Clone, Debug, PartialEq)] +struct RandomizedRichLayout { + display_none: bool, + grid: Option<(u16, u16)>, + grid_span: Option<(u16, u16)>, + absolute_inset: Option<(f32, f32)>, + auto_width: bool, + auto_height: bool, + min_width: Option, + max_width: Option, + min_height: Option, + max_height: Option, + rem_sized: bool, + rem_size_override: Option, + margin: f32, + flex_basis: Option, + flex_grow: f32, + flex_shrink: f32, + scrollbar_width: Option, + align_items: Option, + align_self: Option, + align_content: Option, + justify_content: Option, + aspect_ratio: Option, + unkeyed: bool, + text_override: bool, + text: RandomizedTextStyle, + measured: RandomizedMeasuredContent, + popup: Option, + list_version: u64, +} + +impl Default for RandomizedRichLayout { + fn default() -> Self { + Self { + display_none: false, + grid: None, + grid_span: None, + absolute_inset: None, + auto_width: false, + auto_height: false, + min_width: None, + max_width: None, + min_height: None, + max_height: None, + rem_sized: false, + rem_size_override: None, + margin: 0.0, + flex_basis: None, + flex_grow: 0.0, + flex_shrink: 0.0, + scrollbar_width: None, + align_items: None, + align_self: None, + align_content: None, + justify_content: None, + aspect_ratio: None, + unkeyed: false, + text_override: false, + text: RandomizedTextStyle::default(), + measured: RandomizedMeasuredContent::None, + popup: None, + list_version: 0, + } + } +} + +#[derive(Clone, Debug, PartialEq)] +struct RandomizedPopup { + priority: usize, + offset_x: f32, + offset_y: f32, + width: f32, + height: f32, + label: usize, + color: Hsla, +} + +impl RandomizedPopup { + fn random(rng: &mut StdRng) -> Self { + Self { + priority: rng.random_range(0..3), + offset_x: rng.random_range(0.0..400.0), + offset_y: rng.random_range(0.0..300.0), + width: rng.random_range(40.0..180.0), + height: rng.random_range(20.0..90.0), + label: rng.random_range(0..LABELS.len()), + color: random_color(rng), + } + } + + fn mutate(&mut self, rng: &mut StdRng) { + match rng.random_range(0..6) { + 0 => self.priority = rng.random_range(0..3), + 1 => { + self.offset_x = rng.random_range(0.0..400.0); + self.offset_y = rng.random_range(0.0..300.0); + } + 2 => self.width = rng.random_range(40.0..180.0), + 3 => self.height = rng.random_range(20.0..90.0), + 4 => self.label = (self.label + rng.random_range(1..LABELS.len())) % LABELS.len(), + _ => self.color = random_color(rng), + } + } +} + +impl RandomizedRichLayout { + fn random(rng: &mut StdRng) -> Self { + let mut rich = Self { + display_none: rng.random_bool(0.06), + ..Self::default() + }; + rich.randomize_layout(rng); + if rng.random_bool(0.5) { + rich.text_override = true; + rich.text.randomize(rng); + } + if rng.random_bool(0.6) { + rich.randomize_measured(rng); + } + if rng.random_bool(0.2) { + rich.popup = Some(RandomizedPopup::random(rng)); + } + rich + } + + fn randomize_layout(&mut self, rng: &mut StdRng) { + self.grid = rng + .random_bool(0.18) + .then(|| (rng.random_range(1..=3), rng.random_range(1..=3))); + self.grid_span = rng + .random_bool(0.15) + .then(|| (rng.random_range(1..=2), rng.random_range(1..=2))); + self.absolute_inset = rng + .random_bool(0.12) + .then(|| (rng.random_range(0.0..24.0), rng.random_range(0.0..24.0))); + self.auto_width = rng.random_bool(0.45); + self.auto_height = rng.random_bool(0.45); + self.min_width = rng.random_bool(0.2).then(|| rng.random_range(0.0..60.0)); + self.max_width = rng.random_bool(0.2).then(|| rng.random_range(60.0..240.0)); + self.min_height = rng.random_bool(0.2).then(|| rng.random_range(0.0..50.0)); + self.max_height = rng.random_bool(0.2).then(|| rng.random_range(50.0..200.0)); + self.rem_sized = rng.random_bool(0.35); + self.rem_size_override = rng.random_bool(0.15).then(|| rng.random_range(10.0..22.0)); + self.margin = if rng.random_bool(0.4) { + rng.random_range(0.0..8.0) + } else { + 0.0 + }; + self.flex_basis = rng.random_bool(0.2).then(|| rng.random_range(16.0..120.0)); + self.flex_grow = if rng.random_bool(0.25) { 1.0 } else { 0.0 }; + self.flex_shrink = if rng.random_bool(0.5) { 1.0 } else { 0.0 }; + self.scrollbar_width = rng.random_bool(0.15).then(|| rng.random_range(0.0..12.0)); + self.align_items = random_align_items(rng); + self.align_self = random_align_self(rng); + self.align_content = random_align_content(rng); + self.justify_content = random_justify_content(rng); + self.aspect_ratio = rng.random_bool(0.15).then(|| rng.random_range(0.5..2.5)); + self.unkeyed = rng.random_bool(0.3); + } + + fn mutate_one_layout_field(&mut self, rng: &mut StdRng) { + match rng.random_range(0..22) { + 0 => self.auto_width = !self.auto_width, + 1 => self.auto_height = !self.auto_height, + 2 => self.rem_sized = !self.rem_sized, + 3 => { + self.margin = if self.margin == 0.0 || rng.random_bool(0.7) { + rng.random_range(0.0..8.0) + } else { + 0.0 + }; + } + 4 => self.flex_grow = if self.flex_grow == 0.0 { 1.0 } else { 0.0 }, + 5 => self.flex_shrink = if self.flex_shrink == 0.0 { 1.0 } else { 0.0 }, + 6 => self.align_items = random_align_items(rng), + 7 => self.justify_content = random_justify_content(rng), + 8 => { + self.aspect_ratio = if self.aspect_ratio.is_some() && rng.random_bool(0.5) { + None + } else { + Some(rng.random_range(0.5..2.5)) + }; + } + 9 => self.unkeyed = !self.unkeyed, + 10 => { + self.grid = if self.grid.is_some() && rng.random_bool(0.5) { + None + } else { + Some((rng.random_range(1..=3), rng.random_range(1..=3))) + }; + } + 11 => { + self.grid_span = if self.grid_span.is_some() && rng.random_bool(0.5) { + None + } else { + Some((rng.random_range(1..=2), rng.random_range(1..=2))) + }; + } + 12 => { + self.absolute_inset = if self.absolute_inset.is_some() && rng.random_bool(0.5) { + None + } else { + Some((rng.random_range(0.0..24.0), rng.random_range(0.0..24.0))) + }; + } + 13 => { + self.min_width = if self.min_width.is_some() && rng.random_bool(0.5) { + None + } else { + Some(rng.random_range(0.0..60.0)) + }; + } + 14 => { + self.max_width = if self.max_width.is_some() && rng.random_bool(0.5) { + None + } else { + Some(rng.random_range(60.0..240.0)) + }; + } + 15 => { + self.min_height = if self.min_height.is_some() && rng.random_bool(0.5) { + None + } else { + Some(rng.random_range(0.0..50.0)) + }; + } + 16 => { + self.max_height = if self.max_height.is_some() && rng.random_bool(0.5) { + None + } else { + Some(rng.random_range(50.0..200.0)) + }; + } + 17 => { + self.rem_size_override = if self.rem_size_override.is_some() && rng.random_bool(0.5) + { + None + } else { + Some(rng.random_range(10.0..22.0)) + }; + } + 18 => { + self.flex_basis = if self.flex_basis.is_some() && rng.random_bool(0.5) { + None + } else { + Some(rng.random_range(16.0..120.0)) + }; + } + 19 => { + self.scrollbar_width = if self.scrollbar_width.is_some() && rng.random_bool(0.5) { + None + } else { + Some(rng.random_range(0.0..12.0)) + }; + } + 20 => self.align_self = random_align_self(rng), + _ => self.align_content = random_align_content(rng), + } + } + + fn randomize_measured(&mut self, rng: &mut StdRng) { + self.list_version += 1; + let color = random_color(rng); + self.measured = match rng.random_range(0..6) { + 0 => RandomizedMeasuredContent::KeyedLeaf { + width: rng.random_range(12.0..96.0), + height: rng.random_range(10.0..48.0), + color, + }, + 1 => RandomizedMeasuredContent::UnkeyedLeaf { + width: rng.random_range(12.0..96.0), + height: rng.random_range(10.0..48.0), + color, + }, + 2 => RandomizedMeasuredContent::UniformList { + item_count: rng.random_range(0..=6), + item_width: rng.random_range(24.0..80.0), + item_height: rng.random_range(10.0..24.0), + scroll_offset: if rng.random_bool(0.5) { + rng.random_range(0.0..48.0) + } else { + 0.0 + }, + color, + }, + 3 => { + let item_count = rng.random_range(0..=6); + let scroll_index = if item_count > 0 && rng.random_bool(0.5) { + rng.random_range(0..item_count) + } else { + 0 + }; + RandomizedMeasuredContent::List { + item_count, + item_width: rng.random_range(24.0..80.0), + item_height: rng.random_range(10.0..24.0), + scroll_index, + color, + } + } + _ => RandomizedMeasuredContent::None, + }; + } + + fn mutate_measured(&mut self, rng: &mut StdRng) { + // Usually tweak a single field so minimal-change invalidation edge cases get tested. + if rng.random_bool(0.25) || matches!(self.measured, RandomizedMeasuredContent::None) { + self.randomize_measured(rng); + return; + } + match &mut self.measured { + RandomizedMeasuredContent::None => {} + RandomizedMeasuredContent::KeyedLeaf { + width, + height, + color, + } + | RandomizedMeasuredContent::UnkeyedLeaf { + width, + height, + color, + } => match rng.random_range(0..3) { + 0 => *width = rng.random_range(12.0..96.0), + 1 => *height = rng.random_range(10.0..48.0), + _ => *color = random_color(rng), + }, + RandomizedMeasuredContent::UniformList { + item_count, + item_width, + item_height, + scroll_offset, + color, + } => match rng.random_range(0..5) { + 0 => *item_count = rng.random_range(0..=6), + 1 => *item_width = rng.random_range(24.0..80.0), + 2 => *item_height = rng.random_range(10.0..24.0), + 3 => { + *scroll_offset = rng.random_range(0.0..48.0); + self.list_version += 1; + } + _ => *color = random_color(rng), + }, + RandomizedMeasuredContent::List { + item_count, + item_width, + item_height, + scroll_index, + color, + } => match rng.random_range(0..5) { + 0 => { + *item_count = rng.random_range(0..=6); + *scroll_index = (*scroll_index).min(item_count.saturating_sub(1)); + self.list_version += 1; + } + 1 => { + *item_width = rng.random_range(24.0..80.0); + self.list_version += 1; + } + 2 => { + *item_height = rng.random_range(10.0..24.0); + self.list_version += 1; + } + 3 => { + *scroll_index = if *item_count > 0 { + rng.random_range(0..*item_count) + } else { + 0 + }; + self.list_version += 1; + } + _ => *color = random_color(rng), + }, + } + } + + fn mutate_popup(&mut self, rng: &mut StdRng) { + match &mut self.popup { + Some(popup) if rng.random_bool(0.75) => popup.mutate(rng), + Some(_) => self.popup = None, + None => self.popup = Some(RandomizedPopup::random(rng)), + } + } +} + +fn random_align_items(rng: &mut StdRng) -> Option { + match rng.random_range(0..5) { + 0 => Some(AlignItems::FlexStart), + 1 => Some(AlignItems::Center), + 2 => Some(AlignItems::FlexEnd), + 3 => Some(AlignItems::Stretch), + _ => None, + } +} + +fn random_justify_content(rng: &mut StdRng) -> Option { + match rng.random_range(0..5) { + 0 => Some(JustifyContent::FlexStart), + 1 => Some(JustifyContent::Center), + 2 => Some(JustifyContent::SpaceBetween), + 3 => Some(JustifyContent::FlexEnd), + _ => None, + } +} + +fn random_align_self(rng: &mut StdRng) -> Option { + match rng.random_range(0..5) { + 0 => Some(AlignSelf::FlexStart), + 1 => Some(AlignSelf::Center), + 2 => Some(AlignSelf::FlexEnd), + 3 => Some(AlignSelf::Stretch), + _ => None, + } +} + +fn random_align_content(rng: &mut StdRng) -> Option { + match rng.random_range(0..5) { + 0 => Some(AlignContent::FlexStart), + 1 => Some(AlignContent::Center), + 2 => Some(AlignContent::SpaceBetween), + 3 => Some(AlignContent::FlexEnd), + _ => None, + } +} + +#[derive(Clone, Debug, PartialEq)] +struct RandomizedTextStyle { + color: Hsla, + highlight_color: Hsla, + highlight_bg: Hsla, + size_in_rems: bool, + font_size: f32, + line_height_relative: bool, + line_height: f32, + white_space: WhiteSpace, + text_overflow: Option, + line_clamp: Option, + text_align: TextAlign, + kind: RandomizedTextKind, +} + +impl Default for RandomizedTextStyle { + fn default() -> Self { + Self { + color: crate::black(), + highlight_color: crate::black(), + highlight_bg: crate::transparent_black(), + size_in_rems: false, + font_size: 14.0, + line_height_relative: true, + line_height: 1.3, + white_space: WhiteSpace::Normal, + text_overflow: None, + line_clamp: None, + text_align: TextAlign::Left, + kind: RandomizedTextKind::Plain, + } + } +} + +impl RandomizedTextStyle { + fn randomize(&mut self, rng: &mut StdRng) { + self.color = random_color(rng); + self.highlight_color = random_color(rng); + self.highlight_bg = random_color(rng); + self.size_in_rems = rng.random_bool(0.5); + self.font_size = if self.size_in_rems { + rng.random_range(0.75..1.5) + } else { + rng.random_range(10.0..22.0) + }; + self.line_height_relative = rng.random_bool(0.5); + self.line_height = if self.line_height_relative { + rng.random_range(1.1..1.8) + } else { + rng.random_range(0.9..2.0) + }; + self.white_space = if rng.random_bool(0.35) { + WhiteSpace::Nowrap + } else { + WhiteSpace::Normal + }; + self.text_overflow = random_text_overflow(rng); + self.line_clamp = random_line_clamp(rng); + self.text_align = random_text_align(rng); + self.kind = random_text_kind(rng); + } + + fn mutate(&mut self, rng: &mut StdRng) { + if rng.random_bool(0.2) { + self.randomize(rng); + return; + } + match rng.random_range(0..9) { + 0 => self.color = random_color(rng), + 1 => { + self.highlight_color = random_color(rng); + self.highlight_bg = random_color(rng); + } + 2 => { + self.size_in_rems = rng.random_bool(0.5); + self.font_size = if self.size_in_rems { + rng.random_range(0.75..1.5) + } else { + rng.random_range(10.0..22.0) + }; + } + 3 => { + self.line_height_relative = rng.random_bool(0.5); + self.line_height = if self.line_height_relative { + rng.random_range(1.1..1.8) + } else { + rng.random_range(0.9..2.0) + }; + } + 4 => { + self.white_space = match self.white_space { + WhiteSpace::Normal => WhiteSpace::Nowrap, + WhiteSpace::Nowrap => WhiteSpace::Normal, + }; + } + 5 => self.text_overflow = random_text_overflow(rng), + 6 => self.line_clamp = random_line_clamp(rng), + 7 => self.text_align = random_text_align(rng), + _ => self.kind = random_text_kind(rng), + } + } +} + +fn random_text_overflow(rng: &mut StdRng) -> Option { + match rng.random_range(0..5) { + 0 => Some(TextOverflow::Truncate("...".into())), + 1 => Some(TextOverflow::TruncateStart("...".into())), + 2 => Some(TextOverflow::TruncateMiddle("...".into())), + _ => None, + } +} + +fn random_line_clamp(rng: &mut StdRng) -> Option { + match rng.random_range(0..4) { + 0 => Some(1), + 1 => Some(2), + _ => None, + } +} + +fn random_text_align(rng: &mut StdRng) -> TextAlign { + match rng.random_range(0..3) { + 0 => TextAlign::Left, + 1 => TextAlign::Center, + _ => TextAlign::Right, + } +} + +fn random_text_kind(rng: &mut StdRng) -> RandomizedTextKind { + match rng.random_range(0..3) { + 0 => RandomizedTextKind::Plain, + 1 => RandomizedTextKind::StyledRuns, + _ => RandomizedTextKind::Interactive, + } +} + +fn apply_text_style(element: &mut crate::Div, text: &RandomizedTextStyle) { + let text_refinement = element.text_style(); + text_refinement.color = Some(text.color); + text_refinement.font_size = Some(if text.size_in_rems { + rems(text.font_size).into() + } else { + px(text.font_size).into() + }); + text_refinement.line_height = Some(if text.line_height_relative { + relative(text.line_height) + } else { + rems(text.line_height).into() + }); + text_refinement.white_space = Some(text.white_space); + text_refinement.text_overflow = text.text_overflow.clone(); + text_refinement.line_clamp = text.line_clamp; + text_refinement.text_align = Some(text.text_align); +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum RandomizedTextKind { + Plain, + StyledRuns, + Interactive, +} + +#[derive(Clone, Debug, PartialEq)] +enum RandomizedMeasuredContent { + None, + KeyedLeaf { + width: f32, + height: f32, + color: Hsla, + }, + UnkeyedLeaf { + width: f32, + height: f32, + color: Hsla, + }, + UniformList { + item_count: usize, + item_width: f32, + item_height: f32, + scroll_offset: f32, + color: Hsla, + }, + List { + item_count: usize, + item_width: f32, + item_height: f32, + scroll_index: usize, + color: Hsla, + }, +} + +struct RemSizeScope { + rem_size: Pixels, + child: AnyElement, +} + +impl Element for RemSizeScope { + type RequestLayoutState = (); + type PrepaintState = (); + + fn id(&self) -> Option { + None + } + + fn source_location(&self) -> Option<&'static std::panic::Location<'static>> { + None + } + + fn request_layout( + &mut self, + _: Option<&GlobalElementId>, + _: Option<&InspectorElementId>, + window: &mut Window, + cx: &mut App, + ) -> (LayoutId, ()) { + let layout_id = window.with_rem_size(Some(self.rem_size), |window| { + self.child.request_layout(window, cx) + }); + (layout_id, ()) + } + + fn prepaint( + &mut self, + _: Option<&GlobalElementId>, + _: Option<&InspectorElementId>, + _: Bounds, + _: &mut (), + window: &mut Window, + cx: &mut App, + ) { + window.with_rem_size(Some(self.rem_size), |window| { + self.child.prepaint(window, cx); + }); + } + + fn paint( + &mut self, + _: Option<&GlobalElementId>, + _: Option<&InspectorElementId>, + _: Bounds, + _: &mut (), + _: &mut (), + window: &mut Window, + cx: &mut App, + ) { + window.with_rem_size(Some(self.rem_size), |window| { + self.child.paint(window, cx); + }); + } +} + +struct RandomizedMeasuredLeaf { + width: f32, + height: f32, + color: Hsla, + keyed: bool, +} + +impl Element for RandomizedMeasuredLeaf { + type RequestLayoutState = (); + type PrepaintState = (); + + fn id(&self) -> Option { + None + } + + fn source_location(&self) -> Option<&'static std::panic::Location<'static>> { + None + } + + fn request_layout( + &mut self, + _: Option<&GlobalElementId>, + _: Option<&InspectorElementId>, + window: &mut Window, + _: &mut App, + ) -> (LayoutId, ()) { + let intrinsic = size(px(self.width), px(self.height)); + let measure = move |known_dimensions: Size>, + available_space: Size, + _: &mut Window, + _: &mut App| { + let width = known_dimensions + .width + .unwrap_or(match available_space.width { + AvailableSpace::Definite(available) => intrinsic.width.min(available), + AvailableSpace::MinContent => intrinsic.width * 0.5, + AvailableSpace::MaxContent => intrinsic.width, + }); + let height = known_dimensions + .height + .unwrap_or(match available_space.height { + AvailableSpace::Definite(available) => intrinsic.height.min(available), + AvailableSpace::MinContent | AvailableSpace::MaxContent => intrinsic.height, + }); + size(width, height) + }; + let layout_id = if self.keyed { + window.request_keyed_measured_layout(Style::default(), intrinsic, measure) + } else { + window.request_measured_layout(Style::default(), measure) + }; + (layout_id, ()) + } + + fn prepaint( + &mut self, + _: Option<&GlobalElementId>, + _: Option<&InspectorElementId>, + _: Bounds, + _: &mut (), + _: &mut Window, + _: &mut App, + ) { + } + + fn paint( + &mut self, + _: Option<&GlobalElementId>, + _: Option<&InspectorElementId>, + bounds: Bounds, + _: &mut (), + _: &mut (), + window: &mut Window, + _: &mut App, + ) { + window.paint_quad(fill(bounds, self.color)); + } } /// The texts an element can show. Elements whose number is 1 more than a multiple of 4 /// show the first; others show text only once a mutation changes their label. -const LABELS: [&str; 4] = [ +const LABELS: [&str; 5] = [ "Retained glyphs: abc Ω", "Retained glyphs: abc Ω, now with enough words that narrow parents wrap them", + "Line one: abc Ω\nLine two wraps when narrow enough", "Ω", "", ]; @@ -1348,6 +2278,7 @@ impl RandomizedElementStyle { vertical: rng.random_bool(0.5), wrap: rng.random_bool(0.7), label: 0, + rich: RandomizedRichLayout::default(), } } @@ -1367,6 +2298,7 @@ impl RandomizedElementStyle { vertical: rng.random_bool(0.5), wrap: rng.random_bool(0.4), label: 0, + rich: RandomizedRichLayout::default(), } } @@ -1375,6 +2307,24 @@ impl RandomizedElementStyle { self.border_width = rng.random_range(0.0..5.0); self.corner_radius = rng.random_range(0.0..18.0); } + + fn mutate_layout(&mut self, rng: &mut StdRng) { + if rng.random_bool(0.2) { + self.vertical = rng.random_bool(0.5); + self.wrap = rng.random_bool(0.4); + self.padding = rng.random_range(0.0..12.0); + self.gap = rng.random_range(0.0..10.0); + self.rich.randomize_layout(rng); + return; + } + match rng.random_range(0..14) { + 0 => self.vertical = !self.vertical, + 1 => self.wrap = !self.wrap, + 2 => self.padding = rng.random_range(0.0..12.0), + 3 => self.gap = rng.random_range(0.0..10.0), + _ => self.rich.mutate_one_layout_field(rng), + } + } } #[derive(Clone, Copy)] @@ -1386,6 +2336,11 @@ enum RandomizedChildMutation { Clipping, Visibility, Text, + Display, + Layout, + TextStyle, + MeasuredContent, + Popup, } #[cfg_attr(feature = "stacker", stacksafe::stacksafe)] @@ -1393,6 +2348,8 @@ fn render_node( node: &RandomizedElementNode, entities: &RandomizedElementEntities, scroll_handles: &RefCell>, + list_states: &RefCell>, + uniform_list_scroll_handles: &RefCell>, work_counters: &mut RandomizedElementTreeWorkCounters, options: RenderOptions, ) -> AnyElement { @@ -1409,7 +2366,60 @@ fn render_node( return entity.clone().into_any_element(); } - render_node_body(node, Some(entities), scroll_handles, work_counters, options) + render_node_body( + node, + Some(entities), + scroll_handles, + list_states, + uniform_list_scroll_handles, + work_counters, + options, + ) +} + +fn render_rich_text( + node_id: u64, + label: &'static str, + text_style: &RandomizedTextStyle, + id_generation: u64, +) -> AnyElement { + let styled_with_highlights = || { + let mut highlights = Vec::new(); + if let Some(first_end) = label.chars().next().map(char::len_utf8) { + highlights.push(( + 0..first_end, + HighlightStyle { + color: Some(text_style.highlight_color), + background_color: Some(text_style.highlight_bg), + underline: Some(UnderlineStyle { + thickness: px(1.0), + color: Some(text_style.highlight_color), + wavy: false, + }), + strikethrough: Some(StrikethroughStyle { + thickness: px(1.0), + color: Some(text_style.color), + }), + ..Default::default() + }, + )); + } + StyledText::new(label).with_highlights(highlights) + }; + + match text_style.kind { + RandomizedTextKind::Plain => label.into_any_element(), + RandomizedTextKind::StyledRuns => styled_with_highlights().into_any_element(), + RandomizedTextKind::Interactive => InteractiveText::new( + ElementId::NamedInteger( + "randomized-interactive-text".into(), + node_id | id_generation << ID_GENERATION_SHIFT, + ), + styled_with_highlights(), + ) + .on_hover(|_, _, _, _| {}) + .into_any_element(), + } } #[cfg_attr(feature = "stacker", stacksafe::stacksafe)] @@ -1417,24 +2427,126 @@ fn render_node_body( node: &RandomizedElementNode, entities: Option<&RandomizedElementEntities>, scroll_handles: &RefCell>, + list_states: &RefCell>, + uniform_list_scroll_handles: &RefCell>, work_counters: &mut RandomizedElementTreeWorkCounters, options: RenderOptions, ) -> AnyElement { work_counters.record_element_render(node.features.handler_count()); let style = &node.style; - div() - .id(ElementId::NamedInteger( - "randomized-element".into(), - node.id | options.id_generation << ID_GENERATION_SHIFT, - )) - .flex() - .flex_shrink_0() + let rich = &style.rich; + let is_scroll = node.id.is_multiple_of(3); + let keyed = node.is_keyed(); + + let mut base = div(); + base = if rich.display_none { + base.hidden() + } else if let Some((cols, rows)) = rich.grid { + base.grid().grid_cols(cols).grid_rows(rows) + } else { + base.flex() + }; + if let Some((col_span, row_span)) = rich.grid_span { + base = base.col_span(col_span).row_span(row_span); + } + if let Some((top, left)) = rich.absolute_inset { + base = base.absolute(); + if rich.rem_sized { + base = base.top(rems(top / 16.0)).left(rems(left / 16.0)); + } else { + base = base.top(px(top)).left(px(left)); + } + } + base.style().flex_grow = Some(rich.flex_grow); + base.style().flex_shrink = Some(rich.flex_shrink); + if let Some(flex_basis) = rich.flex_basis { + if rich.rem_sized { + base = base.flex_basis(rems(flex_basis / 16.0)); + } else { + base = base.flex_basis(px(flex_basis)); + } + } + if let Some(scrollbar_width) = rich.scrollbar_width { + base = base.scrollbar_width(px(scrollbar_width)); + } + if let Some(align_items) = rich.align_items { + base.style().align_items = Some(align_items); + } + if let Some(align_self) = rich.align_self { + base.style().align_self = Some(align_self); + } + if let Some(align_content) = rich.align_content { + base.style().align_content = Some(align_content); + } + if let Some(justify_content) = rich.justify_content { + base.style().justify_content = Some(justify_content); + } + if let Some(aspect_ratio) = rich.aspect_ratio { + base.style().aspect_ratio = Some(aspect_ratio); + } + if let Some(min_width) = rich.min_width { + if rich.rem_sized { + base = base.min_w(rems(min_width / 16.0)); + } else { + base = base.min_w(px(min_width)); + } + } + if let Some(max_width) = rich.max_width { + if rich.rem_sized { + base = base.max_w(rems(max_width / 16.0)); + } else { + base = base.max_w(px(max_width)); + } + } + if let Some(min_height) = rich.min_height { + if rich.rem_sized { + base = base.min_h(rems(min_height / 16.0)); + } else { + base = base.min_h(px(min_height)); + } + } + if let Some(max_height) = rich.max_height { + if rich.rem_sized { + base = base.max_h(rems(max_height / 16.0)); + } else { + base = base.max_h(px(max_height)); + } + } + if rich.margin > 0.0 { + if rich.rem_sized { + base = base.m(rems(rich.margin / 16.0)); + } else { + base = base.m(px(rich.margin)); + } + } + if rich.rem_sized { + base = base + .gap(rems(style.gap / 16.0)) + .p(rems(style.padding / 16.0)); + } else { + base = base.gap(px(style.gap)).p(px(style.padding)); + } + if !rich.auto_width { + if rich.rem_sized { + base = base.w(rems(style.width / 16.0)); + } else { + base = base.w(px(style.width)); + } + } + if !rich.auto_height { + if rich.rem_sized { + base = base.h(rems(style.height / 16.0)); + } else { + base = base.h(px(style.height)); + } + } + if rich.text_override { + apply_text_style(&mut base, &rich.text); + } + + let base = base .when(style.vertical, |element| element.flex_col()) .when(style.wrap, |element| element.flex_wrap()) - .gap(px(style.gap)) - .p(px(style.padding)) - .w(px(style.width)) - .h(px(style.height)) .bg(style.background) .when(options.hover_styles, |element| { element @@ -1456,20 +2568,10 @@ fn render_node_body( }) .opacity(style.opacity) .when(style.clipped, |element| element.overflow_hidden()) - .when(node.id.is_multiple_of(3), |element| { - let mut handles = scroll_handles.borrow_mut(); - let handle = handles - .entry(node.id) - .or_insert_with(crate::ScrollHandle::new); - element.overflow_scroll().track_scroll(handle) - }) .when(!style.visible, |element| element.invisible()) .when(node.features.action_handler, |element| { element.on_action(|_: &RandomizedElementTreeAction, _window, _cx| {}) }) - .when(node.features.click_handler, |element| { - element.cursor_pointer().on_click(|_event, _window, _cx| {}) - }) .when(node.features.key_context, |element| { element .key_context("RandomizedElementTree") @@ -1492,9 +2594,143 @@ fn render_node_body( ) }) .when(node.id % 4 == 1 || style.label != 0, |element| { - element - .underline() - .child(LABELS[style.label % LABELS.len()]) + let label = LABELS[style.label % LABELS.len()]; + element.underline().child(render_rich_text( + node.id, + label, + &rich.text, + options.id_generation, + )) + }) + .map(|element| match rich.measured { + RandomizedMeasuredContent::None => element, + RandomizedMeasuredContent::KeyedLeaf { + width, + height, + color, + } => element.child(RandomizedMeasuredLeaf { + width, + height, + color, + keyed: true, + }), + RandomizedMeasuredContent::UnkeyedLeaf { + width, + height, + color, + } => element.child(RandomizedMeasuredLeaf { + width, + height, + color, + keyed: false, + }), + RandomizedMeasuredContent::UniformList { + item_count, + item_width, + item_height, + scroll_offset, + color, + } => { + let scroll_handle = { + let mut handles = uniform_list_scroll_handles.borrow_mut(); + let entry = handles.entry(node.id).or_insert_with(|| { + let handle = UniformListScrollHandle::new(); + handle + .0 + .borrow() + .base_handle + .set_offset(point(px(0.0), px(-scroll_offset))); + (handle, rich.list_version) + }); + if entry.1 != rich.list_version { + entry + .0 + .0 + .borrow() + .base_handle + .set_offset(point(px(0.0), px(-scroll_offset))); + entry.1 = rich.list_version; + } + entry.0.clone() + }; + element.child( + uniform_list( + ElementId::NamedInteger( + "randomized-uniform-list".into(), + node.id | options.id_generation << ID_GENERATION_SHIFT, + ), + item_count, + move |range, _, _| { + range + .map(|_| div().w(px(item_width)).h(px(item_height)).bg(color)) + .collect() + }, + ) + .with_sizing_behavior(ListSizingBehavior::Infer) + .track_scroll(&scroll_handle) + .when(scroll_offset > 0.0, |list| list.max_h(px(32.0))), + ) + } + RandomizedMeasuredContent::List { + item_count, + item_width, + item_height, + scroll_index, + color, + } => { + let list_state = { + let mut states = list_states.borrow_mut(); + let entry = states.entry(node.id).or_insert_with(|| { + let state = ListState::new(item_count, ListAlignment::Top, px(500.0)); + if scroll_index > 0 && item_count > 0 { + state.scroll_to(ListOffset { + item_ix: scroll_index.min(item_count - 1), + offset_in_item: px(0.0), + }); + } + (state, rich.list_version) + }); + if entry.1 != rich.list_version { + entry.0.reset(item_count); + if scroll_index > 0 && item_count > 0 { + entry.0.scroll_to(ListOffset { + item_ix: scroll_index.min(item_count - 1), + offset_in_item: px(0.0), + }); + } + entry.1 = rich.list_version; + } + entry.0.clone() + }; + element.child( + list(list_state, move |_, _, _| { + div() + .w(px(item_width)) + .h(px(item_height)) + .bg(color) + .into_any_element() + }) + .with_sizing_behavior(ListSizingBehavior::Infer) + .when(scroll_index > 0, |list| list.max_h(px(32.0))), + ) + } + }) + .when_some(rich.popup.as_ref(), |element, popup| { + element.child( + deferred( + anchored() + .position(point(px(popup.offset_x), px(popup.offset_y))) + .snap_to_window() + .child( + div() + .w(px(popup.width)) + .h(px(popup.height)) + .bg(popup.color) + .child(LABELS[popup.label % LABELS.len()]), + ), + ) + .with_priority(popup.priority), + ) }) .child({ let color = style.border_color; @@ -1533,12 +2769,57 @@ fn render_node_body( }) .children(node.children.iter().map(|child| { if let Some(entities) = entities { - render_node(child, entities, scroll_handles, work_counters, options) + render_node( + child, + entities, + scroll_handles, + list_states, + uniform_list_scroll_handles, + work_counters, + options, + ) } else { - render_node_body(child, None, scroll_handles, work_counters, options) + render_node_body( + child, + None, + scroll_handles, + list_states, + uniform_list_scroll_handles, + work_counters, + options, + ) } - })) + })); + + let element = if keyed { + base.id(ElementId::NamedInteger( + "randomized-element".into(), + node.id | options.id_generation << ID_GENERATION_SHIFT, + )) + .when(is_scroll, |element| { + let mut handles = scroll_handles.borrow_mut(); + let handle = handles + .entry(node.id) + .or_insert_with(crate::ScrollHandle::new); + element.overflow_scroll().track_scroll(handle) + }) + .when(node.features.click_handler, |element| { + element.cursor_pointer().on_click(|_event, _window, _cx| {}) + }) .into_any_element() + } else { + base.into_any_element() + }; + + if let Some(rem_size) = rich.rem_size_override { + RemSizeScope { + rem_size: px(rem_size), + child: element, + } + .into_any_element() + } else { + element + } } fn insert_node( @@ -2032,7 +3313,10 @@ mod tests { mutation: Option<(usize, RandomizedElementTreeMutation)>, ) { let snapshot = persistent_root.read_with(cx, |tree, _| tree.snapshot()); - let expected_element_ids = snapshot.element_ids().into_iter().collect::>(); + let expected_element_ids = snapshot + .keyed_element_ids() + .into_iter() + .collect::>(); let persistent_scene = draw_window(persistent_window, cx); assert_eq!( persistent_scene.element_ids, expected_element_ids, @@ -2104,6 +3388,10 @@ mod tests { ); let rem_size = px(rng.random_range(8.0..24.0)); let scale_factor = [1.0, 1.25, 1.5, 2.0, 2.5][rng.random_range(0..5)]; + let mouse_position = point( + px(rng.random_range(0.0..WINDOW_SIZE.width.0)), + px(rng.random_range(0.0..WINDOW_SIZE.height.0)), + ); for (window, root) in [&cached, &uncached] { match change { 0..60 => { @@ -2119,6 +3407,19 @@ mod tests { window.set_scale_factor(scale_factor) }) .expect("window should remain open"), + 88..94 => { + cx.update_window(*window, |_, window, cx| { + window.dispatch_event( + crate::PlatformInput::MouseMove(crate::MouseMoveEvent { + position: mouse_position, + pressed_button: None, + modifiers: crate::Modifiers::default(), + }), + cx, + ); + }) + .expect("window should remain open"); + } _ => root.update(cx, |_, cx| cx.notify()), } } @@ -2126,10 +3427,36 @@ mod tests { .expect("window should remain open"); let [cached_frame, uncached_frame] = [&cached, &uncached].map(|(window, _)| draw_window_with_hitboxes(*window, cx)); - assert_eq!( - cached_frame, uncached_frame, - "cached layout diverged at step {step} (change {change}) for {config:?}" - ); + if cached_frame != uncached_frame { + let first_quad_diff = cached_frame + .0 + .quads + .iter() + .zip(&uncached_frame.0.quads) + .enumerate() + .find(|(_, (a, b))| a != b); + let first_hitbox_diff = cached_frame + .1 + .iter() + .zip(&uncached_frame.1) + .enumerate() + .find(|(_, (a, b))| a != b); + panic!( + "cached layout diverged at step {step} (change {change}, mutation {mutation:?}, \ + scale_factor {scale_factor}, rem_size {rem_size:?}) for {config:?}\n\ + quad counts: cached={} uncached={}\n\ + other_primitives counts: cached={} uncached={}\n\ + hitbox counts: cached={} uncached={}\n\ + first_quad_diff: {first_quad_diff:?}\n\ + first_hitbox_diff: {first_hitbox_diff:?}", + cached_frame.0.quads.len(), + uncached_frame.0.quads.len(), + cached_frame.0.other_primitives.len(), + uncached_frame.0.other_primitives.len(), + cached_frame.1.len(), + uncached_frame.1.len(), + ); + } } for (window, _) in [cached, uncached] { diff --git a/crates/gpui/src/taffy.rs b/crates/gpui/src/taffy.rs index bc84bb8859c..db3202a3b92 100644 --- a/crates/gpui/src/taffy.rs +++ b/crates/gpui/src/taffy.rs @@ -9,7 +9,7 @@ use crate::{ use collections::{FxHashMap, FxHashSet}; use slotmap::{DefaultKey, KeyData, SecondaryMap}; use smallvec::SmallVec; -use std::{fmt::Debug, ops::Range}; +use std::{any::Any, fmt::Debug, ops::Range}; use taffy::{ TaffyTree, TraversePartialTree as _, geometry::{Point as TaffyPoint, Rect as TaffyRect, Size as TaffySize}, @@ -23,9 +23,113 @@ type StackSafe = stacksafe::StackSafe; #[cfg(not(feature = "stacker"))] type StackSafe = T; -type MeasureFn = - dyn FnMut(Size>, Size, &mut Window, &mut App) -> Size; -type NodeContext = StackSafe>; +type NodeContext = StackSafe>; + +/// Lets a node hold any [`KeyedMeasure`] in a single allocation. +trait Measure: Any { + /// `final_layout` is false when Taffy is only probing the node's size. + fn measure( + &mut self, + known_dimensions: Size>, + available_space: Size, + final_layout: bool, + window: &mut Window, + cx: &mut App, + ) -> Size; +} + +/// Replaces `previous` in place when it already holds a `KeyedMeasure`, returning +/// whether `reuse` said its cached sizes still apply. Returns `Err((key, measure))` when +/// the node held a measure of a different type and needs a fresh allocation. +/// +/// Unlike the rest of a layout request, this reads the node's context, which with the +/// `stacker` feature may only be done from a stack-safe function. +#[cfg_attr(feature = "stacker", stacksafe::stacksafe)] +fn replace_measure_in_place( + previous: &mut NodeContext, + mut key: K, + reuse: fn(&mut K, &mut K) -> bool, + measure: F, +) -> Result +where + K: 'static, + F: FnMut( + &K, + Size>, + Size, + bool, + &mut Window, + &mut App, + ) -> Size + + 'static, +{ + let previous: &mut Box = previous; + let Some(previous) = (&mut **previous as &mut dyn Any).downcast_mut::>() + else { + return Err((key, measure)); + }; + let reused = reuse(&mut key, &mut previous.key); + previous.key = key; + previous.measure = measure; + Ok(reused) +} + +fn box_measure(key: K, measure: F) -> NodeContext +where + K: 'static, + F: FnMut( + &K, + Size>, + Size, + bool, + &mut Window, + &mut App, + ) -> Size + + 'static, +{ + let measure: Box = Box::new(KeyedMeasure { key, measure }); + #[cfg(feature = "stacker")] + let measure = StackSafe::new(measure); + measure +} + +/// A measure function and the key describing what its measured size depends on. +struct KeyedMeasure { + key: K, + measure: F, +} + +impl Measure for KeyedMeasure +where + K: 'static, + F: FnMut( + &K, + Size>, + Size, + bool, + &mut Window, + &mut App, + ) -> Size + + 'static, +{ + fn measure( + &mut self, + known_dimensions: Size>, + available_space: Size, + final_layout: bool, + window: &mut Window, + cx: &mut App, + ) -> Size { + (self.measure)( + &self.key, + known_dimensions, + available_space, + final_layout, + window, + cx, + ) + } +} pub struct TaffyLayoutEngine { taffy: TaffyTree, @@ -72,6 +176,8 @@ struct LayoutCache { /// frame are removed. free_nodes: Vec, frame: u64, + /// Scale factor Taffy's cached device-pixel styles and measurements were computed at. + scale_factor: Option, } fn node_key(id: NodeId) -> DefaultKey { @@ -97,11 +203,27 @@ impl TaffyLayoutEngine { /// Drops every layout node kept from earlier frames, so the next frame builds its /// tree from scratch. - #[cfg(test)] pub(crate) fn clear_layout_cache(&mut self) { self.taffy.clear(); self.contexts.clear(); self.cache = LayoutCache::default(); + self.absolute_layout_bounds.clear(); + self.absolute_outer_origins.clear(); + self.computed_layouts.clear(); + } + + /// Clears the layout cache when the window's scale factor changes. Taffy stores styles + /// and measured leaf sizes in device pixels, so none of the cached layouts apply at a + /// different scale factor. + pub(crate) fn clear_if_scale_factor_changed(&mut self, scale_factor: f32) { + if self + .cache + .scale_factor + .is_some_and(|previous| previous != scale_factor) + { + self.clear_layout_cache(); + } + self.cache.scale_factor = Some(scale_factor); } #[cfg(test)] @@ -126,42 +248,70 @@ impl TaffyLayoutEngine { scale_factor: f32, children: &[LayoutId], ) -> LayoutId { - self.request_node(scope, style, rem_size, scale_factor, children, None) + let id = self.acquire_node(scope, style, rem_size, scale_factor, children); + if self.contexts.remove(node_key(id)).is_some() { + self.taffy.mark_dirty(id).expect(EXPECT_MESSAGE); + } + id.into() } - pub fn request_measured_layout( + /// See [`Window::request_keyed_measure`]. + pub(crate) fn request_keyed_measure( &mut self, scope: PathHash, style: &Style, rem_size: Pixels, scale_factor: f32, - measure: impl FnMut( - Size>, - Size, - &mut Window, - &mut App, - ) -> Size - + 'static, - ) -> LayoutId { - let measure = Box::new(measure) as Box; - #[cfg(feature = "stacker")] - let measure = StackSafe::new(measure); - self.request_node(scope, style, rem_size, scale_factor, &[], Some(measure)) + key: K, + reuse: fn(&mut K, &mut K) -> bool, + measure: F, + ) -> LayoutId + where + K: 'static, + F: FnMut( + &K, + Size>, + Size, + bool, + &mut Window, + &mut App, + ) -> Size + + 'static, + { + let id = self.acquire_node(scope, style, rem_size, scale_factor, &[]); + let key_id = node_key(id); + // A measure that measures the same as the node's previous one keeps the sizes + // Taffy cached from it; any other must invalidate them. Updating a same-type + // context in place avoids allocating and freeing a Box on steady-state frames. + let reused = if let Some(previous) = self.contexts.get_mut(key_id) { + match replace_measure_in_place(previous, key, reuse, measure) { + Ok(reused) => reused, + Err((key, measure)) => { + *previous = box_measure(key, measure); + false + } + } + } else { + self.contexts.insert(key_id, box_measure(key, measure)); + false + }; + if !reused { + self.taffy.mark_dirty(id).expect(EXPECT_MESSAGE); + } + id.into() } - fn request_node( + fn acquire_node( &mut self, scope: PathHash, style: &Style, rem_size: Pixels, scale_factor: f32, children: &[LayoutId], - context: Option, - ) -> LayoutId { + ) -> NodeId { // This is safe because LayoutId is repr(transparent) to taffy::tree::NodeId. let children = LayoutId::to_taffy_slice(children); let taffy = &mut self.taffy; - let contexts = &mut self.contexts; let cache = &mut self.cache; let frame = cache.frame; @@ -214,19 +364,7 @@ impl TaffyLayoutEngine { }; cache.nodes[node_key(id)].frame = frame; - // A measure function can measure anything, so the sizes Taffy cached from the - // node's previous one can't be kept. - let measure_changed = match context { - Some(context) => { - contexts.insert(node_key(id), context); - true - } - None => contexts.remove(node_key(id)).is_some(), - }; - if measure_changed { - taffy.mark_dirty(id).expect(EXPECT_MESSAGE); - } - id.into() + id } /// Treats any `auto` dimension of the given node's style as filling `size`. @@ -407,8 +545,14 @@ impl TaffyLayoutEngine { untransform(available_space.height), ); - let measured_size = - node_context(known_dimensions, available_space, window, cx); + let final_layout = input.run_mode == taffy::RunMode::PerformLayout; + let measured_size = node_context.measure( + known_dimensions, + available_space, + final_layout, + window, + cx, + ); snap_measured_size_to_device_pixels(measured_size, scale_factor).into() }, ) @@ -1017,6 +1161,17 @@ mod tests { /// them, checking that every element with a debug selector has the same bounds in /// both. fn assert_frames_match_uncached(cx: &mut TestAppContext, frames: Vec) { + assert_frames_match_uncached_with(cx, frames, |_| {}, |_| ()); + } + + /// Like [`assert_frames_match_uncached`], running `before_cached` before and + /// `after_cached` after each cached frame draw and returning the observations. + fn assert_frames_match_uncached_with( + cx: &mut TestAppContext, + frames: Vec, + mut before_cached: impl FnMut(&Window), + mut after_cached: impl FnMut(&Window) -> T, + ) -> Vec { let frames = Rc::new(frames); let frame = Rc::new(Cell::new(0)); let windows = [false, true].map(|rebuild| { @@ -1028,15 +1183,19 @@ mod tests { }); (AnyWindowHandle::from(window), rebuild) }); + let mut observations = Vec::new(); for index in 0..frames.len() { frame.set(index); let [cached, uncached] = windows.map(|(window, rebuild)| { cx.update_window(window, |_, window, cx| { if rebuild { window.clear_layout_cache(); + } else { + before_cached(window); } window.refresh(); window.draw(cx).clear(cx); + let observation = (!rebuild).then(|| after_cached(window)); let mut bounds = window .rendered_frame .debug_bounds @@ -1044,21 +1203,46 @@ mod tests { .map(|(selector, bounds)| (selector.clone(), *bounds)) .collect::>(); bounds.sort_by(|a, b| a.0.cmp(&b.0)); - bounds + (bounds, observation) }) .expect("window should remain open") }); - assert!(!uncached.is_empty(), "frame {index} has no debug selectors"); - assert_eq!(cached, uncached, "frame {index}"); + assert!( + !uncached.0.is_empty(), + "frame {index} has no debug selectors" + ); + assert_eq!(cached.0, uncached.0, "frame {index}"); + observations.push(cached.1.expect("cached window observation")); } + observations } fn frame(render: impl Fn(&mut Window) -> AnyElement + 'static) -> Frame { Box::new(render) } - /// A leaf whose size comes from its measure function, which captures it. - struct MeasuredLeaf(Size); + /// A leaf whose size comes from its measure function, which captures it and is keyed + /// by it. + struct MeasuredLeaf { + size: Size, + measurements: Option>>, + } + + impl MeasuredLeaf { + fn new(size: Size) -> Self { + Self { + size, + measurements: None, + } + } + + fn with_counter(size: Size, measurements: Rc>) -> Self { + Self { + size, + measurements: Some(measurements), + } + } + } impl Element for MeasuredLeaf { type RequestLayoutState = (); @@ -1079,9 +1263,18 @@ mod tests { window: &mut Window, _: &mut App, ) -> (LayoutId, ()) { - let measured = self.0; - let layout_id = - window.request_measured_layout(Style::default(), move |_, _, _, _| measured); + let measured = self.size; + let measurements = self.measurements.clone(); + let layout_id = window.request_keyed_measured_layout( + Style::default(), + measured, + move |_, _, _, _| { + if let Some(measurements) = &measurements { + measurements.set(measurements.get() + 1); + } + measured + }, + ); (layout_id, ()) } @@ -1180,6 +1373,44 @@ mod tests { ); } + #[crate::test] + fn measured_leaf_is_measured_again_only_when_its_key_changes(cx: &mut TestAppContext) { + let counter = Rc::new(Cell::new(0)); + let measured = |width: f32, height: f32| { + let counter = counter.clone(); + frame(move |_| { + div() + .flex() + .child(div().debug_selector(|| "wrapper".into()).child( + MeasuredLeaf::with_counter(size(px(width), px(height)), counter.clone()), + )) + .into_any_element() + }) + }; + let measurements = assert_frames_match_uncached_with( + cx, + vec![ + measured(10., 10.), + measured(10., 10.), + measured(30., 20.), + measured(30., 20.), + measured(5., 40.), + ], + |_| counter.set(0), + |_| counter.get(), + ); + // Opening the window draws the first frame, so drawing it again measures nothing. + let measured = measurements + .iter() + .map(|count| *count > 0) + .collect::>(); + assert_eq!( + measured, + [false, false, true, false, true], + "measurements per frame: {measurements:?}" + ); + } + #[crate::test] fn rem_size_changes_resolve_lengths_again(cx: &mut TestAppContext) { let with_rem_size = |rem_size: f32| { @@ -1214,7 +1445,7 @@ mod tests { div() .id("reused") .debug_selector(|| "reused".into()) - .child(MeasuredLeaf(size(px(12.), px(9.)))), + .child(MeasuredLeaf::new(size(px(12.), px(9.)))), ) .into_any_element() }) @@ -1248,6 +1479,117 @@ mod tests { ); } + #[crate::test] + fn text_is_measured_again_only_when_it_changes(cx: &mut TestAppContext) { + let text = |width: f32, text: &'static str, font_size: f32| { + frame(move |_| { + div() + .flex() + .child( + div() + .w(px(width)) + .text_size(px(font_size)) + .debug_selector(|| "wrapper".into()) + .child(text), + ) + .child(div().size(px(10.)).debug_selector(|| "sibling".into())) + .into_any_element() + }) + }; + let short = "Some text"; + let same_length = "Same text"; + let long = "Some longer text that wraps in narrow parents"; + // Opening the window draws the first frame, so drawing it again measures nothing. + let frames = [ + (text(200., short, 14.), false), + (text(200., short, 14.), false), + (text(200., same_length, 14.), true), + (text(200., long, 14.), true), + (text(200., long, 14.), false), + (text(60., long, 14.), true), + (text(60., long, 18.), true), + (text(60., long, 18.), false), + (text(200., long, 14.), true), + ]; + let expected = frames + .iter() + .map(|(_, measured)| *measured) + .collect::>(); + let measurements = assert_frames_match_uncached_with( + cx, + frames.into_iter().map(|(frame, _)| frame).collect(), + |_| {}, + |window| window.text_system().last_frame_wrapped_line_count(), + ); + let measured = measurements + .iter() + .map(|count| *count > 0) + .collect::>(); + assert_eq!( + measured, expected, + "text measurements per frame: {measurements:?}" + ); + } + + #[crate::test] + fn measured_leaf_updates_when_scale_factor_changes(cx: &mut TestAppContext) { + let at_scale = |scale_factor: f32| { + frame(move |window| { + window.set_scale_factor(scale_factor); + div() + .flex() + .child( + div() + .debug_selector(|| "wrapper".into()) + .child(MeasuredLeaf::new(size(px(100.), px(40.)))), + ) + .into_any_element() + }) + }; + assert_frames_match_uncached(cx, vec![at_scale(1.0), at_scale(2.0), at_scale(1.0)]); + } + + #[crate::test] + fn text_is_measured_again_when_fonts_are_added(cx: &mut TestAppContext) { + let with_text = || { + frame(|_| { + div() + .flex() + .child( + div() + .w(px(200.)) + .debug_selector(|| "wrapper".into()) + .child("Some text"), + ) + .into_any_element() + }) + }; + let mut frame_index = 0; + let measurements = assert_frames_match_uncached_with( + cx, + vec![with_text(), with_text(), with_text()], + |window| { + if frame_index == 1 { + window + .text_system() + .add_fonts(Vec::new()) + .expect("noop text system accepts empty font list"); + } + frame_index += 1; + }, + |window| window.text_system().last_frame_wrapped_line_count(), + ); + let measured = measurements + .iter() + .map(|count| *count > 0) + .collect::>(); + assert_eq!( + measured, + [false, true, false], + "text measurements per frame: {measurements:?}" + ); + } + #[crate::test] fn evicted_nodes_do_not_accumulate_when_ids_change_every_frame(cx: &mut TestAppContext) { let window = cx.open_window(size(px(800.), px(600.)), |_, cx| { diff --git a/crates/gpui/src/text_system.rs b/crates/gpui/src/text_system.rs index e4ff3ec8f53..2db72fe060d 100644 --- a/crates/gpui/src/text_system.rs +++ b/crates/gpui/src/text_system.rs @@ -652,6 +652,11 @@ impl WindowTextSystem { } } + /// Changes whenever fonts are added, which can change how any text is shaped. + pub(crate) fn font_generation(&self) -> usize { + self.text_system.font_generation.load(Ordering::Acquire) + } + pub(crate) fn layout_index(&self) -> LineLayoutIndex { self.line_layout_cache.layout_index() } @@ -664,6 +669,11 @@ impl WindowTextSystem { self.line_layout_cache.truncate_layouts(index) } + #[cfg(test)] + pub(crate) fn last_frame_wrapped_line_count(&self) -> usize { + self.line_layout_cache.last_frame_wrapped_line_count() + } + /// Shape the given line, at the given font_size, for painting to the screen. /// Subsets of the line can be styled independently with the `runs` parameter. /// diff --git a/crates/gpui/src/text_system/line_layout.rs b/crates/gpui/src/text_system/line_layout.rs index 4c002187c4a..1b9ccc4d89f 100644 --- a/crates/gpui/src/text_system/line_layout.rs +++ b/crates/gpui/src/text_system/line_layout.rs @@ -474,6 +474,19 @@ impl WrappedLineLayout { } } +/// Moves the layouts in `unused` that are held outside the cache into `cache`, and drops +/// the rest. The two never share a key, so only the smaller map's entries are moved. +fn keep_held_layouts( + cache: &mut FxHashMap, Arc>, + unused: &mut FxHashMap, Arc>, +) { + unused.retain(|_, layout| Arc::strong_count(layout) > 1); + if unused.len() > cache.len() { + std::mem::swap(cache, unused); + } + cache.extend(unused.drain()); +} + pub(crate) struct LineLayoutCache { state: RefCell, wrap_scratch: RefCell, @@ -587,12 +600,22 @@ impl LineLayoutCache { current_frame, } = &mut *self.state.borrow_mut(); std::mem::swap(previous_frame, current_frame); - current_frame.lines.clear(); - current_frame.wrapped_lines.clear(); + // Text that kept its measurement isn't shaped again, so the layouts it holds must + // stay cached. Wrapped lines go first, since they hold their unwrapped lines. + keep_held_layouts( + &mut previous_frame.wrapped_lines, + &mut current_frame.wrapped_lines, + ); + keep_held_layouts(&mut previous_frame.lines, &mut current_frame.lines); current_frame.used_lines.clear(); current_frame.used_wrapped_lines.clear(); } + #[cfg(test)] + pub(crate) fn last_frame_wrapped_line_count(&self) -> usize { + self.state.borrow().previous_frame.used_wrapped_lines.len() + } + pub fn layout_wrapped_line( &self, text: Text, @@ -611,6 +634,7 @@ impl LineLayoutCache { font_size, runs, wrap_width, + max_lines, force_width: None, } as &dyn AsCacheKeyRef; @@ -653,6 +677,7 @@ impl LineLayoutCache { font_size, runs: SmallVec::from(runs), wrap_width, + max_lines, force_width: None, }); @@ -684,6 +709,7 @@ impl LineLayoutCache { font_size, runs, wrap_width: None, + max_lines: None, force_width, } as &dyn AsCacheKeyRef; @@ -717,6 +743,7 @@ impl LineLayoutCache { font_size, runs: SmallVec::from(runs), wrap_width: None, + max_lines: None, force_width, }); let layout = Arc::new(layout); @@ -792,6 +819,7 @@ struct CacheKey { font_size: Pixels, runs: SmallVec<[FontRun; 1]>, wrap_width: Option, + max_lines: Option, force_width: Option, } @@ -801,6 +829,7 @@ struct CacheKeyRef<'a> { font_size: Pixels, runs: &'a [FontRun], wrap_width: Option, + max_lines: Option, force_width: Option, } @@ -825,6 +854,7 @@ impl AsCacheKeyRef for CacheKey { font_size: self.font_size, runs: self.runs.as_slice(), wrap_width: self.wrap_width, + max_lines: self.max_lines, force_width: self.force_width, } } @@ -877,6 +907,33 @@ mod tests { assert_eq!(key.text.as_ptr(), text.as_ptr()); } + #[test] + fn layouts_held_outside_the_cache_outlive_frames_that_dont_use_them() { + let text_system = + WindowTextSystem::new(Arc::new(TextSystem::new(Arc::new(NoopTextSystem::new())))); + let shape = |text: &'static str| { + let runs = [TextRun { + len: text.len(), + font: font(".ZedMono"), + ..Default::default() + }]; + text_system + .shape_text(text.into(), px(14.), &runs, Some(px(100.)), None) + .unwrap() + .remove(0) + .layout + }; + + let held = shape("held"); + let dropped = Arc::downgrade(&shape("dropped").unwrapped_layout); + for _ in 0..3 { + text_system.finish_frame(); + } + + assert!(Arc::ptr_eq(&shape("held"), &held)); + assert!(dropped.upgrade().is_none()); + } + fn glyph_at(x: f32, index: usize) -> ShapedGlyph { ShapedGlyph { id: GlyphId(0), @@ -1088,4 +1145,20 @@ mod tests { assert_eq!(warm.wrap_boundaries, cold.wrap_boundaries); } + + #[test] + fn test_wrap_cache_distinguishes_max_lines() { + let text = "one two three four five six"; + let runs = [FontRun { + len: text.len(), + font_id: FontId(1), + }]; + let cache = LineLayoutCache::new(Arc::new(NoopTextSystem::new()), Arc::default()); + + let unclamped = cache.layout_wrapped_line(text, px(14.), &runs, Some(px(50.)), None); + assert!(unclamped.wrap_boundaries.len() > 1); + + let clamped = cache.layout_wrapped_line(text, px(14.), &runs, Some(px(50.)), Some(1)); + assert!(clamped.wrap_boundaries.is_empty()); + } } diff --git a/crates/gpui/src/window.rs b/crates/gpui/src/window.rs index 844eef408b2..fbf4b2e3fc9 100644 --- a/crates/gpui/src/window.rs +++ b/crates/gpui/src/window.rs @@ -3158,7 +3158,13 @@ impl Window { /// the platform window, then notifies observers. Normally called automatically /// by the platform's resize callback, but exposed publicly for test infrastructure. pub fn bounds_changed(&mut self, cx: &mut App) { - self.scale_factor = self.platform_window.scale_factor(); + let scale_factor = self.platform_window.scale_factor(); + if self.scale_factor != scale_factor { + self.scale_factor = scale_factor; + if let Some(layout_engine) = self.layout_engine.as_mut() { + layout_engine.clear_layout_cache(); + } + } self.viewport_size = self.platform_window.content_size(); self.last_window_bounds = self.platform_window.window_bounds(); cx.sync_window_update_entry(self); @@ -3496,7 +3502,12 @@ impl Window { /// Overrides the display scale factor for tests. #[cfg(any(test, feature = "test-support"))] pub fn set_scale_factor(&mut self, scale_factor: f32) { - self.scale_factor = scale_factor; + if self.scale_factor != scale_factor { + self.scale_factor = scale_factor; + if let Some(layout_engine) = self.layout_engine.as_mut() { + layout_engine.clear_layout_cache(); + } + } self.refresh(); } @@ -3871,6 +3882,10 @@ impl Window { } } if !cx.mode.skip_drawing() { + self.layout_engine + .as_mut() + .unwrap() + .clear_if_scale_factor_changed(self.scale_factor); self.draw_roots(cx); #[cfg(feature = "profiler")] { @@ -5727,26 +5742,94 @@ impl Window { /// Add a node to the layout tree for the current frame. Instead of taking a `Style` and children, /// this variant takes a function that is invoked during layout so you can use arbitrary logic to - /// determine the element's size. One place this is used internally is when measuring text. + /// determine the element's size. /// /// The given closure is invoked at layout time with the known dimensions and available space and - /// returns a `Size`. + /// returns a `Size`. It is invoked every frame; see [`Self::request_keyed_measured_layout`] to + /// keep the measured sizes while what they depend on is unchanged. /// /// This method should only be called as part of the request_layout or prepaint phase of element drawing. pub fn request_measured_layout(&mut self, style: Style, measure: F) -> LayoutId where F: Fn(Size>, Size, &mut Window, &mut App) -> Size + 'static, + { + self.request_keyed_measure( + &style, + (), + |_, _| false, + move |_, known_dimensions, available_space, _, window, cx| { + measure(known_dimensions, available_space, window, cx) + }, + ) + } + + /// Like [`Self::request_measured_layout`], but `key` must describe everything the size depends + /// on besides the known dimensions and available space: while it equals the key the element's + /// node was last measured with, the sizes measured then can be used without calling `measure` + /// again, and the node doesn't need to be laid out again. + /// + /// Do not pass a constant key such as `()` unless the measure function's result truly never + /// changes for a given available space; use [`Self::request_measured_layout`] instead. + /// + /// This method should only be called as part of the request_layout or prepaint phase of element drawing. + pub fn request_keyed_measured_layout( + &mut self, + style: Style, + key: K, + measure: F, + ) -> LayoutId + where + K: PartialEq + 'static, + F: Fn(Size>, Size, &mut Window, &mut App) -> Size + + 'static, + { + self.request_keyed_measure( + &style, + key, + |key, previous| key == previous, + move |_, known_dimensions, available_space, _, window, cx| { + measure(known_dimensions, available_space, window, cx) + }, + ) + } + + /// Like [`Self::request_keyed_measured_layout`], but `reuse` decides whether a key measures + /// the same as the previous one, and `measure` is given the key and whether this is + /// the node's final measurement rather than a sizing probe. + pub(crate) fn request_keyed_measure( + &mut self, + style: &Style, + key: K, + reuse: fn(&mut K, &mut K) -> bool, + measure: F, + ) -> LayoutId + where + K: 'static, + F: FnMut( + &K, + Size>, + Size, + bool, + &mut Window, + &mut App, + ) -> Size + + 'static, { self.invalidator.debug_assert_prepaint(); let rem_size = self.rem_size(); let scale_factor = self.scale_factor(); let scope = self.element_id_stack.hash(); - self.layout_engine - .as_mut() - .unwrap() - .request_measured_layout(scope, &style, rem_size, scale_factor, measure) + self.layout_engine.as_mut().unwrap().request_keyed_measure( + scope, + style, + rem_size, + scale_factor, + key, + reuse, + measure, + ) } /// Drops the layout nodes kept from earlier frames, so the next frame builds its