diff --git a/crates/gpui/src/elements/div.rs b/crates/gpui/src/elements/div.rs index 9b34aa23469..f28f091739d 100644 --- a/crates/gpui/src/elements/div.rs +++ b/crates/gpui/src/elements/div.rs @@ -1842,8 +1842,14 @@ pub(crate) type ActionListener = /// Construct a new [`Div`] element #[track_caller] pub fn div() -> Div { + #[allow(unused_mut)] + let mut interactivity = InteractivityBox::new(); + #[cfg(any(feature = "inspector", debug_assertions))] + { + interactivity.source_location = Some(core::panic::Location::caller()); + } Div { - interactivity: Interactivity::new(), + interactivity, children: SmallVec::default(), prepaint_listener: None, image_cache: None, @@ -1851,9 +1857,55 @@ pub fn div() -> Div { } } +/// Where a [`Div`]'s [`Interactivity`] lives. Divs built while a frame is drawn, which is +/// nearly all of them, use the element arena so they don't each cost a heap allocation; +/// the arena outlives every element built during the frame. +enum InteractivityBox { + Arena(crate::ArenaBox), + Heap(Box), +} + +impl InteractivityBox { + /// Builds the `Interactivity` in place, since moving one in would copy over a kilobyte. + #[inline] + fn new() -> Self { + if crate::window::draw_in_progress() { + Self::Arena(crate::window::with_element_arena(|arena| { + arena.alloc(Interactivity::default) + })) + } else { + Self::Heap(Box::default()) + } + } +} + +impl std::ops::Deref for InteractivityBox { + type Target = Interactivity; + + #[inline] + fn deref(&self) -> &Interactivity { + match self { + Self::Arena(interactivity) => interactivity, + Self::Heap(interactivity) => interactivity, + } + } +} + +impl std::ops::DerefMut for InteractivityBox { + #[inline] + fn deref_mut(&mut self) -> &mut Interactivity { + match self { + Self::Arena(interactivity) => interactivity, + Self::Heap(interactivity) => interactivity, + } + } +} + /// A [`Div`] element, the all-in-one element for building complex UIs in GPUI pub struct Div { - interactivity: Interactivity, + // Kept out of line because builder methods move the `Div` by value on every call, + // and `Interactivity` is over a kilobyte. + interactivity: InteractivityBox, children: SmallVec<[StackSafe; 2]>, prepaint_listener: Option>, &mut Window, &mut App) + 'static>>, image_cache: Option>, diff --git a/crates/gpui/src/randomized_element_tree.rs b/crates/gpui/src/randomized_element_tree.rs index 01b9f204abf..6b2ad69c8be 100644 --- a/crates/gpui/src/randomized_element_tree.rs +++ b/crates/gpui/src/randomized_element_tree.rs @@ -65,6 +65,7 @@ pub struct RandomizedElementTreeConfig { animation_density: f64, cached_views: bool, hover_styles: bool, + paths: bool, } impl RandomizedElementTreeConfig { @@ -79,6 +80,7 @@ impl RandomizedElementTreeConfig { animation_density: 0.0, cached_views: false, hover_styles: false, + paths: true, } } @@ -102,6 +104,14 @@ impl RandomizedElementTreeConfig { self } + /// Whether elements paint vector paths. Path tessellation dominates the cost of + /// frames that draw them, so turning them off isolates layout and the rest of the + /// frame; elements keep the canvas that would have painted them, so layout is the same. + pub fn with_paths(mut self, paths: bool) -> Self { + self.paths = paths; + self + } + /// Selects the initial tree topology independently of the RNG seed. pub fn with_topology(mut self, topology: RandomizedElementTreeTopology) -> Self { self.topology = topology; @@ -302,8 +312,7 @@ pub struct RandomizedElementTreeSnapshot { root: RandomizedElementStyle, children: Vec, next_element_id: u64, - cached_views: bool, - hover_styles: bool, + render_options: RenderOptions, paths_by_element_id: HashMap>, } @@ -405,6 +414,9 @@ pub enum RandomizedElementTreeMutationKind { ChildClipping, /// Toggle visibility on a seeded random descendant. ChildVisibility, + /// 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, /// Reorder a seeded random descendant among its siblings. Reorder, /// Insert a generated descendant below a seeded random parent. @@ -419,7 +431,7 @@ pub enum RandomizedElementTreeMutationKind { impl RandomizedElementTreeMutationKind { /// Every supported mutation kind, suitable for parameterized tests and benchmarks. - pub const ALL: [Self; 16] = [ + pub const ALL: [Self; 17] = [ Self::RootColor, Self::RootOpacity, Self::RootBorder, @@ -432,6 +444,7 @@ impl RandomizedElementTreeMutationKind { Self::ChildBounds, Self::ChildClipping, Self::ChildVisibility, + Self::ChildText, Self::Reorder, Self::Insert, Self::Remove, @@ -484,6 +497,11 @@ pub enum RandomizedElementTreeMutation { /// The stable ID of the mutated element. element_id: u64, }, + /// Changed a descendant's text. + ChildText { + /// 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. @@ -590,8 +608,11 @@ impl RandomizedElementTree { root: RandomizedElementStyle::random_root(&mut rng), children, next_element_id: config.element_count as u64, - cached_views: config.cached_views, - hover_styles: config.hover_styles, + render_options: RenderOptions { + cached_views: config.cached_views, + hover_styles: config.hover_styles, + paths: config.paths, + }, paths_by_element_id: HashMap::default(), }; snapshot.rebuild_element_paths(); @@ -795,6 +816,9 @@ impl RandomizedElementTree { RandomizedElementTreeMutationKind::ChildVisibility => { self.mutate_random_child(RandomizedChildMutation::Visibility) } + RandomizedElementTreeMutationKind::ChildText => { + self.mutate_random_child(RandomizedChildMutation::Text) + } RandomizedElementTreeMutationKind::Reorder => self.reorder_child(), RandomizedElementTreeMutationKind::Insert => self.insert_child_internal(), RandomizedElementTreeMutationKind::Remove => self @@ -990,6 +1014,11 @@ impl RandomizedElementTree { node.style.visible = !node.style.visible; RandomizedElementTreeMutation::ChildVisibility { element_id } } + RandomizedChildMutation::Text => { + node.style.label = + (node.style.label + self.rng.random_range(1..LABELS.len())) % LABELS.len(); + RandomizedElementTreeMutation::ChildText { element_id } + } }; AppliedRandomizedElementTreeMutation { mutation, @@ -1111,7 +1140,7 @@ impl Render for RandomizedElementTree { div() .flex() - .when(snapshot.hover_styles, |element| { + .when(snapshot.render_options.hover_styles, |element| { element.group("randomized-tree-root") }) .when(root.vertical, |element| element.flex_col()) @@ -1136,8 +1165,7 @@ impl Render for RandomizedElementTree { &entities, &self.scroll_handles, &mut work_counters, - snapshot.cached_views, - snapshot.hover_styles, + snapshot.render_options, ) })) } @@ -1145,6 +1173,13 @@ impl Render for RandomizedElementTree { type RandomizedElementEntities = HashMap>; +#[derive(Clone, Copy, Debug, PartialEq)] +struct RenderOptions { + cached_views: bool, + hover_styles: bool, + paths: bool, +} + struct RandomizedElementEntity { element_id: u64, snapshot: Rc>, @@ -1169,8 +1204,7 @@ impl Render for RandomizedElementEntity { entities.as_deref(), &self.scroll_handles, &mut work_counters, - snapshot.cached_views, - snapshot.hover_styles, + snapshot.render_options, ) }) .unwrap_or_else(|| div().into_any_element()) @@ -1269,8 +1303,20 @@ struct RandomizedElementStyle { visible: bool, vertical: bool, wrap: bool, + /// 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, } +/// 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] = [ + "Retained glyphs: abc Ω", + "Retained glyphs: abc Ω, now with enough words that narrow parents wrap them", + "Ω", + "", +]; + impl RandomizedElementStyle { fn random_root(rng: &mut StdRng) -> Self { Self { @@ -1287,6 +1333,7 @@ impl RandomizedElementStyle { visible: true, vertical: rng.random_bool(0.5), wrap: rng.random_bool(0.7), + label: 0, } } @@ -1305,6 +1352,7 @@ impl RandomizedElementStyle { visible: rng.random_bool(0.9), vertical: rng.random_bool(0.5), wrap: rng.random_bool(0.4), + label: 0, } } @@ -1323,6 +1371,7 @@ enum RandomizedChildMutation { Bounds, Clipping, Visibility, + Text, } #[cfg_attr(feature = "stacker", stacksafe::stacksafe)] @@ -1331,13 +1380,12 @@ fn render_node( entities: &RandomizedElementEntities, scroll_handles: &RefCell>, work_counters: &mut RandomizedElementTreeWorkCounters, - cached_views: bool, - hover_styles: bool, + options: RenderOptions, ) -> AnyElement { if node.is_entity && let Some(entity) = entities.get(&node.id) { - if cached_views { + if options.cached_views { let mut style = crate::StyleRefinement::default(); style.size.width = Some(px(node.style.width).into()); style.size.height = Some(px(node.style.height).into()); @@ -1347,14 +1395,7 @@ fn render_node( return entity.clone().into_any_element(); } - render_node_body( - node, - Some(entities), - scroll_handles, - work_counters, - cached_views, - hover_styles, - ) + render_node_body(node, Some(entities), scroll_handles, work_counters, options) } #[cfg_attr(feature = "stacker", stacksafe::stacksafe)] @@ -1363,8 +1404,7 @@ fn render_node_body( entities: Option<&RandomizedElementEntities>, scroll_handles: &RefCell>, work_counters: &mut RandomizedElementTreeWorkCounters, - cached_views: bool, - hover_styles: bool, + options: RenderOptions, ) -> AnyElement { work_counters.record_element_render(node.features.handler_count()); let style = &node.style; @@ -1382,7 +1422,7 @@ fn render_node_body( .w(px(style.width)) .h(px(style.height)) .bg(style.background) - .when(hover_styles, |element| { + .when(options.hover_styles, |element| { element .hover(|element| { element @@ -1437,8 +1477,10 @@ fn render_node_body( ), ) }) - .when(node.id % 4 == 1, |element| { - element.underline().child("Retained glyphs: abc Ω") + .when(node.id % 4 == 1 || style.label != 0, |element| { + element + .underline() + .child(LABELS[style.label % LABELS.len()]) }) .child({ let color = style.border_color; @@ -1447,6 +1489,9 @@ fn render_node_body( crate::canvas( |_, _, _| (), move |bounds, (), window, _| { + if !options.paths { + return; + } for index in 0..6 { let mut path = if index % 2 == 0 { crate::PathBuilder::fill() @@ -1474,23 +1519,9 @@ fn render_node_body( }) .children(node.children.iter().map(|child| { if let Some(entities) = entities { - render_node( - child, - entities, - scroll_handles, - work_counters, - cached_views, - hover_styles, - ) + render_node(child, entities, scroll_handles, work_counters, options) } else { - render_node_body( - child, - None, - scroll_handles, - work_counters, - cached_views, - hover_styles, - ) + render_node_body(child, None, scroll_handles, work_counters, options) } })) .into_any_element() @@ -1857,6 +1888,7 @@ mod tests { RandomizedChildMutation::Bounds, RandomizedChildMutation::Clipping, RandomizedChildMutation::Visibility, + RandomizedChildMutation::Text, ] { tree.mutate_random_child(mutation); assert_eq!(tree.snapshot().element_ids(), initial_ids); diff --git a/crates/gpui/src/window.rs b/crates/gpui/src/window.rs index 4e2e1a798c4..836afe9e0d3 100644 --- a/crates/gpui/src/window.rs +++ b/crates/gpui/src/window.rs @@ -353,7 +353,7 @@ thread_local! { /// arrive re-entrantly while a draw is already on the stack (e.g. via nested /// message pumping in the Windows window procedure), instead of running a /// nested draw or panicking on the already-borrowed App. -fn draw_in_progress() -> bool { +pub(crate) fn draw_in_progress() -> bool { CURRENT_ELEMENT_ARENA.with(|current| current.get().is_some()) } diff --git a/crates/gpui_platform/benches/randomized_element_tree.rs b/crates/gpui_platform/benches/randomized_element_tree.rs index 551d010b433..db0651c6546 100644 --- a/crates/gpui_platform/benches/randomized_element_tree.rs +++ b/crates/gpui_platform/benches/randomized_element_tree.rs @@ -395,6 +395,31 @@ fn full_refresh(family: &TreeFamily, mut rng: StdRng, cx: &mut BenchAppContext) measure_in_window("full refresh", input, cx, |_, window, _| window.refresh()); } +/// The same tree as `family` draws, with elements painting no vector paths. Tessellating +/// paths dominates the frames of trees that paint them, hiding everything else; without +/// them the rest of the frame, layout especially, is most of what is measured. +fn sample_without_paths(family: &TreeFamily, rng: &mut StdRng) -> TreeInput { + let mut input = family.sample(rng); + input.config = input.config.with_paths(false); + input +} + +/// [`full_refresh`] on trees that paint no paths. +#[gpui::bench(inputs = families(), input_name = "tree", iterations = 2, group = "PathlessTree/full refresh", fps = 120)] +fn pathless_full_refresh(family: &TreeFamily, mut rng: StdRng, cx: &mut BenchAppContext) { + let input = &sample_without_paths(family, &mut rng); + measure_in_window("pathless full refresh", input, cx, |_, window, _| { + window.refresh() + }); +} + +/// [`element_style`] on trees that paint no paths. +#[gpui::bench(inputs = families(), input_name = "tree", iterations = 2, group = "PathlessTree/element style", fps = 120)] +fn pathless_element_style(family: &TreeFamily, mut rng: StdRng, cx: &mut BenchAppContext) { + let input = &sample_without_paths(family, &mut rng); + measure_element_style("pathless element style", input, cx); +} + /// A frame in which the root is notified but nothing in the tree changed. On a renderer /// that rebuilds every frame this is the whole tree's cost; on one that retains output /// it is the floor for a frame that has to do nothing. @@ -1565,6 +1590,8 @@ gpui::bench_group!( reorder, hover, mixed, + pathless_full_refresh, + pathless_element_style, changing_share, text_panel_updates, installed_font_panel_updates, diff --git a/script/gpui-bench-compare b/script/gpui-bench-compare index 15d2d1ca581..eadd0f04ac7 100755 --- a/script/gpui-bench-compare +++ b/script/gpui-bench-compare @@ -11,12 +11,13 @@ samples and summary.json persist under target/gpui-bench-compare. Nothing switches the invoking checkout or publishes a branch. The default core suite keeps the mixed workload (plain and with cached views), -five full-refresh tree shapes, element style, cached element style, pointer -hover, warm installed-font text, text first frame, three scrolling workloads, -random and patterned primitive painting, and two inspector workloads. --full -selects every variant; --slow restores the benchmarks' own Criterion settings -(including inspector's five-second measurement). --repetitions controls -independent runs, not random seeds. Use --seed to compare another fixed tree. +five full-refresh tree shapes with and without paths, element style, cached +element style, pointer hover, warm installed-font text, text first frame, three +scrolling workloads, random and patterned primitive painting, and two inspector +workloads. --full selects every variant; --slow restores the benchmarks' own +Criterion settings (including inspector's five-second measurement). +--repetitions controls independent runs, not random seeds. Use --seed to +compare another fixed tree. Foreground retired instructions are primary. Linux needs perf access (CAP_PERFMON or perf_event_paranoid <= 2); macOS needs Apple Silicon. Frames run @@ -57,6 +58,7 @@ CORE = { "randomized_element_tree": ( r"^((Randomized|Cached)Tree/mixed/tree/mixed/|" r"RandomizedTree/full refresh/tree/|" + r"PathlessTree/full refresh/tree/|" r"RandomizedTree/element style/tree/mixed/|" r"CachedTree/element style/tree/mixed/|" r"RandomizedTree/hover/tree/mixed/|"