Reduce render allocations and redundant work in core components

This commit is contained in:
2026-11-09 14:35:15 +07:00
parent 73f7dc31d4
commit 122f9b12ae
19 changed files with 174 additions and 139 deletions
+1 -1
View File
@@ -304,7 +304,7 @@ impl RenderOnce for AlertsView {
let theme = cx.theme(); let theme = cx.theme();
let enter_duration = theme.motion.overlay; let enter_duration = theme.motion.overlay;
let entries: Vec<AlertEntry> = self.alerts.read(cx).entries().to_vec(); let entries = self.alerts.read(cx).entries();
deferred( deferred(
div() div()
+4 -4
View File
@@ -604,8 +604,8 @@ where
div() div()
.id(("option", row)) .id(("option", row))
.debug_selector({ .debug_selector({
let name = format!("{id}-option-{row}"); let id = id.clone();
move || name move || format!("{id}-option-{row}")
}) })
.flex() .flex()
.items_center() .items_center()
@@ -681,8 +681,8 @@ where
let panel = v_flex() let panel = v_flex()
.id((id.clone(), "panel")) .id((id.clone(), "panel"))
.debug_selector({ .debug_selector({
let name = format!("{id}-panel"); let id = id.clone();
move || name move || format!("{id}-panel")
}) })
.w(popup_width) .w(popup_width)
.p_1() .p_1()
+4 -4
View File
@@ -335,8 +335,8 @@ impl Render for CommandPaletteState {
h_flex() h_flex()
.id(("command", row)) .id(("command", row))
.debug_selector({ .debug_selector({
let name = format!("{id}-command-{row}"); let id = id.clone();
move || name move || format!("{id}-command-{row}")
}) })
.gap_2() .gap_2()
.px_2() .px_2()
@@ -409,8 +409,8 @@ impl Render for CommandPaletteState {
let panel = v_flex() let panel = v_flex()
.id((id.clone(), "panel")) .id((id.clone(), "panel"))
.debug_selector({ .debug_selector({
let name = format!("{id}-panel"); let id = id.clone();
move || name move || format!("{id}-panel")
}) })
.key_context(COMMAND_PALETTE_CONTEXT) .key_context(COMMAND_PALETTE_CONTEXT)
.role(Role::Dialog) .role(Role::Dialog)
+3 -3
View File
@@ -422,10 +422,10 @@ impl RenderOnce for DropdownMenu {
let items = if self.open { let items = if self.open {
self.items self.items
.map(|build| build(window, cx)) .map(|build| Rc::from(build(window, cx)))
.unwrap_or_default() .unwrap_or_else(|| Rc::from([]))
} else { } else {
Vec::new() Rc::from([])
}; };
if let Some(panel) = anchored_menu_panel( if let Some(panel) = anchored_menu_panel(
+6 -6
View File
@@ -95,8 +95,8 @@ impl RenderOnce for Field {
let title = div() let title = div()
.debug_selector({ .debug_selector({
let name = format!("{id}-label"); let id = id.clone();
move || name move || format!("{id}-label")
}) })
.text_size(metrics.text_size) .text_size(metrics.text_size)
.child(self.label.clone()); .child(self.label.clone());
@@ -105,16 +105,16 @@ impl RenderOnce for Field {
.items_center() .items_center()
.gap_2() .gap_2()
.debug_selector({ .debug_selector({
let name = format!("{id}-control"); let id = id.clone();
move || name move || format!("{id}-control")
}) })
.children(self.control); .children(self.control);
let error = self.error.map(|error| { let error = self.error.map(|error| {
div() div()
.debug_selector({ .debug_selector({
let name = format!("{id}-error"); let id = id.clone();
move || name move || format!("{id}-error")
}) })
.text_size(metrics.caption_size) .text_size(metrics.caption_size)
.text_color(error_color) .text_color(error_color)
+5 -1
View File
@@ -2051,7 +2051,11 @@ impl RenderOnce for Input {
canvas canvas
.with_animation( .with_animation(
animation_id, animation_id,
Animation::new(CARET_BLINK_INTERVAL * 2).repeat(), // The blink needs four repaints per period,
// not the display's refresh rate.
Animation::new(CARET_BLINK_INTERVAL * 2)
.repeat()
.with_max_fps(4.0),
|canvas, _| canvas, |canvas, _| canvas,
) )
.into_any_element() .into_any_element()
+4 -4
View File
@@ -336,11 +336,11 @@ impl RenderOnce for Menu {
let items = if self.open { let items = if self.open {
match self.items { match self.items {
Some(build) => build(window, cx), Some(build) => Rc::from(build(window, cx)),
None => Vec::new(), None => Rc::from([]),
} }
} else { } else {
Vec::new() Rc::from([])
}; };
if let Some(panel) = anchored_menu_panel( if let Some(panel) = anchored_menu_panel(
@@ -372,7 +372,7 @@ pub(crate) fn anchored_menu_panel(
cx: &mut App, cx: &mut App,
id: &ElementId, id: &ElementId,
open: bool, open: bool,
items: Vec<MenuItem>, items: Rc<[MenuItem]>,
initial_selection: Option<usize>, initial_selection: Option<usize>,
preselect: bool, preselect: bool,
on_change: Option<ChangeHandler>, on_change: Option<ChangeHandler>,
+25 -19
View File
@@ -9,7 +9,7 @@ use gpui::{
}; };
use gpui_native_icons::{IconRole, icon}; use gpui_native_icons::{IconRole, icon};
use gpui_native_theme::{ActiveTheme as _, Size}; use gpui_native_theme::{ActiveTheme as _, Size};
use gpui_native_utils::{adjacent_selectable, focus_handle, focus_ring}; use gpui_native_utils::{focus_handle, focus_ring};
use crate::common::{Sizable, StyledExt, h_flex}; use crate::common::{Sizable, StyledExt, h_flex};
@@ -64,7 +64,8 @@ where
T: Clone + PartialEq + 'static, T: Clone + PartialEq + 'static,
{ {
id: ElementId, id: ElementId,
options: Vec<SegmentedOption<T>>, /// Shared with the per-segment and key handlers, so captures are bumps.
options: Rc<[SegmentedOption<T>]>,
selected: T, selected: T,
a11y_label: Option<SharedString>, a11y_label: Option<SharedString>,
size: Size, size: Size,
@@ -82,7 +83,7 @@ where
{ {
Self { Self {
id: id.into(), id: id.into(),
options: Vec::new(), options: Rc::from([]),
selected, selected,
a11y_label: None, a11y_label: None,
size: Size::Small, size: Size::Small,
@@ -163,12 +164,12 @@ where
.options .options
.iter() .iter()
.position(|segment| segment.value == self.selected); .position(|segment| segment.value == self.selected);
let option_count = self.options.len();
let selectable: Vec<usize> = (0..self.options.len()).collect();
let on_change = self.on_change.clone(); let on_change = self.on_change.clone();
let key_on_change = on_change.clone(); let key_on_change = on_change.clone();
let key_options = self.options.clone(); let key_options = self.options.clone();
let key_selectable = selectable.clone(); let options = self.options.clone();
let label = self let label = self
.a11y_label .a11y_label
@@ -176,14 +177,13 @@ where
.unwrap_or_else(|| SharedString::from(self.id.to_string())); .unwrap_or_else(|| SharedString::from(self.id.to_string()));
window.with_element_namespace(self.id.clone(), |window| { window.with_element_namespace(self.id.clone(), |window| {
let focus = focus_handle(&self.id, window, cx);
let geometry: Entity<Vec<Option<Bounds<gpui::Pixels>>>> = let geometry: Entity<Vec<Option<Bounds<gpui::Pixels>>>> =
window.use_keyed_state("segmented-geometry", cx, |_, _| Vec::new()); window.use_keyed_state("segmented-geometry", cx, |_, _| Vec::new());
let track_origin: Entity<Option<Point<gpui::Pixels>>> = let track_origin: Entity<Option<Point<gpui::Pixels>>> =
window.use_keyed_state("segmented-track-origin", cx, |_, _| None); window.use_keyed_state("segmented-track-origin", cx, |_, _| None);
let focus = focus_handle(&self.id, window, cx);
let anim_config = SpringConfig::new(500., 35., 1.); let anim_config = SpringConfig::new(500., 35., 1.);
let track_point = *track_origin.read(cx); let track_point = *track_origin.read(cx);
@@ -197,12 +197,13 @@ where
let segments = self let segments = self
.options .options
.into_iter() .iter()
.enumerate() .enumerate()
.map(move |(index, segment)| { .map(move |(index, segment)| {
let is_selected = Some(index) == selected_index; let is_selected = Some(index) == selected_index;
let on_change = on_change.clone(); let on_change = on_change.clone();
let value = segment.value; let options = options.clone();
let content_color = if is_selected { let content_color = if is_selected {
foreground foreground
} else { } else {
@@ -228,7 +229,7 @@ where
.when_some(segment.icon, |segment, role| { .when_some(segment.icon, |segment, role| {
segment.child(icon(role).size(icon_size).color(content_color)) segment.child(icon(role).size(icon_size).color(content_color))
}) })
.child(segment.label) .child(segment.label.clone())
.child( .child(
canvas( canvas(
{ {
@@ -251,8 +252,9 @@ where
move |_, window, cx| { move |_, window, cx| {
if Some(index) != selected_index if Some(index) != selected_index
&& let Some(on_change) = &on_change && let Some(on_change) = &on_change
&& let Some(option) = options.get(index)
{ {
on_change(value.clone(), window, cx); on_change(option.value.clone(), window, cx);
} }
} }
}) })
@@ -319,22 +321,26 @@ where
.on_key_down({ .on_key_down({
move |event: &KeyDownEvent, window, cx| { move |event: &KeyDownEvent, window, cx| {
let target = match event.keystroke.key.as_str() { let target = match event.keystroke.key.as_str() {
"right" => { "right" => match selected_index {
adjacent_selectable(&key_selectable, selected_index, true) Some(index) => {
index.checked_add(1).filter(|next| *next < option_count)
} }
"left" => { None => (option_count > 0).then_some(0),
adjacent_selectable(&key_selectable, selected_index, false) },
} "left" => selected_index.and_then(|index| index.checked_sub(1)),
"home" => key_selectable.first().copied(), "home" => (option_count > 0).then_some(0),
"end" => key_selectable.last().copied(), "end" => option_count.checked_sub(1),
_ => return, _ => return,
}; };
if let Some(next) = target if let Some(next) = target
&& Some(next) != selected_index && Some(next) != selected_index
&& let Some(on_change) = &key_on_change && let Some(on_change) = &key_on_change
&& let Some(option) = key_options.get(next)
{ {
on_change(key_options[next].value.clone(), window, cx); on_change(option.value.clone(), window, cx);
} }
cx.stop_propagation(); cx.stop_propagation();
} }
}) })
+9 -15
View File
@@ -206,24 +206,18 @@ where
.position(|option| &option.value == value) .position(|option| &option.value == value)
}); });
let trigger_options = self.options.clone(); // The trigger's text is fixed at render time; only it moves into the closure.
let trigger_selected = self.selected.clone(); let trigger_text = selected_index
let trigger_placeholder = self.placeholder.clone(); .and_then(|index| self.options.get(index))
.map(|option| option.label.clone())
.unwrap_or_else(|| self.placeholder.clone());
let trigger_has_value = self.selected.is_some();
let trigger_id = self.id.clone(); let trigger_id = self.id.clone();
let trigger_label = label.clone(); let trigger_label = label.clone();
let trigger_style = self.style; let trigger_style = self.style;
let trigger = move |_window: &mut Window, _cx: &mut App| { let trigger = move |_window: &mut Window, _cx: &mut App| {
let text = trigger_selected
.as_ref()
.and_then(|value| {
trigger_options
.iter()
.find(|option| &option.value == value)
.map(|option| option.label.clone())
})
.unwrap_or_else(|| trigger_placeholder.clone());
h_flex() h_flex()
.id((trigger_id.clone(), "select-trigger")) .id((trigger_id.clone(), "select-trigger"))
.debug_selector(|| "select-trigger".to_string()) .debug_selector(|| "select-trigger".to_string())
@@ -240,7 +234,7 @@ where
.border_color(rest_border) .border_color(rest_border)
.bg(input) .bg(input)
.text_size(metrics.text_size) .text_size(metrics.text_size)
.text_color(if trigger_selected.is_some() { .text_color(if trigger_has_value {
foreground foreground
} else { } else {
muted_foreground muted_foreground
@@ -249,7 +243,7 @@ where
trigger.shadow(focus_ring(ring)) trigger.shadow(focus_ring(ring))
}) })
.hover(|style| style.bg(muted).border_color(hover_border)) .hover(|style| style.bg(muted).border_color(hover_border))
.child(text) .child(trigger_text.clone())
.child( .child(
icon(IconRole::ChevronDown) icon(IconRole::ChevronDown)
.size(icon_size) .size(icon_size)
+1 -4
View File
@@ -133,10 +133,7 @@ impl RenderOnce for Switch {
div() div()
.flex_none() .flex_none()
.relative() .relative()
.debug_selector({ .debug_selector(move || format!("{id}-track"))
let name = format!("{id}-track");
move || name
})
.w(track_width) .w(track_width)
.h(track_height) .h(track_height)
.rounded(theme.radius.full) .rounded(theme.radius.full)
+8 -6
View File
@@ -34,8 +34,8 @@ impl Tooltip {
{ {
let text = text.into(); let text = text.into();
let anchor_id = anchor_id.into(); let anchor_id = anchor_id.into();
move |_window, cx| { move |window, cx| {
let anchor = anchor_bounds(&anchor_id, cx); let anchor = anchor_bounds(window.window_handle().window_id(), &anchor_id, cx);
cx.new(|_| Self { cx.new(|_| Self {
text: text.clone(), text: text.clone(),
anchor, anchor,
@@ -92,11 +92,13 @@ impl Render for Tooltip {
let origin = window.mouse_position() + point(px(1.), px(1.)); let origin = window.mouse_position() + point(px(1.), px(1.));
let viewport_height = window.viewport_size().height; let viewport_height = window.viewport_size().height;
let height = anchor_bounds(&ElementId::from(PANEL_BOUNDS_ID), cx) let height = anchor_bounds(
window.window_handle().window_id(),
&ElementId::from(PANEL_BOUNDS_ID),
cx,
)
.map(|bounds| bounds.size.height) .map(|bounds| bounds.size.height)
.unwrap_or_else(|| { .unwrap_or_else(|| text_size * 1.5 + window.rem_size() * 0.5 + BORDER_WIDTH * 2.0);
text_size * 1.5 + window.rem_size() * 0.5 + BORDER_WIDTH * 2.0
});
let below = viewport_height - spacing_unit - parent.bottom(); let below = viewport_height - spacing_unit - parent.bottom();
let above = parent.top() - spacing_unit; let above = parent.top() - spacing_unit;
+37 -8
View File
@@ -1,3 +1,5 @@
use std::{cell::Cell, rc::Rc, time::Duration};
use gpui::{ use gpui::{
AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render, SharedString, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render, SharedString,
Styled as _, TestAppContext, VisualTestContext, Window, div, Styled as _, TestAppContext, VisualTestContext, Window, div,
@@ -9,10 +11,12 @@ use gpui_native_core::input::{Input, InputState};
struct FieldHost { struct FieldHost {
url: Entity<InputState>, url: Entity<InputState>,
renders: Rc<Cell<usize>>,
} }
impl Render for FieldHost { impl Render for FieldHost {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement { fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
self.renders.set(self.renders.get() + 1);
let url_error = self let url_error = self
.url .url
.read(cx) .read(cx)
@@ -34,15 +38,27 @@ impl Render for FieldHost {
/// A field page in a real window; the url input is focused unless /// A field page in a real window; the url input is focused unless
/// `focus` is false, which leaves the page truly idle. /// `focus` is false, which leaves the page truly idle.
fn field_host(focus: bool) -> (TestAppContext, Entity<InputState>, VisualTestContext) { fn field_host(
focus: bool,
) -> (
TestAppContext,
Entity<InputState>,
VisualTestContext,
Rc<Cell<usize>>,
) {
let cx = TestAppContext::single(); let cx = TestAppContext::single();
cx.update(init); cx.update(init);
let renders = Rc::new(Cell::new(0));
let renders_for_host = renders.clone();
let (url, window) = cx.update(|cx| { let (url, window) = cx.update(|cx| {
let url = InputState::new(cx); let url = InputState::new(cx);
let url_for_host = url.clone(); let url_for_host = url.clone();
let window = cx let window = cx
.open_window(gpui::WindowOptions::default(), |_, cx| { .open_window(gpui::WindowOptions::default(), |_, cx| {
cx.new(|_| FieldHost { url: url_for_host }) cx.new(|_| FieldHost {
url: url_for_host,
renders: renders_for_host.clone(),
})
}) })
.unwrap(); .unwrap();
(url, window) (url, window)
@@ -55,12 +71,12 @@ fn field_host(focus: bool) -> (TestAppContext, Entity<InputState>, VisualTestCon
} }
window.draw(cx).clear(cx); window.draw(cx).clear(cx);
}); });
(cx, url, visual) (cx, url, visual, renders)
} }
#[test] #[test]
fn an_idle_field_page_schedules_no_frames() { fn an_idle_field_page_schedules_no_frames() {
let (_cx, _url, mut visual) = field_host(false); let (_cx, _url, mut visual, _renders) = field_host(false);
let frames = visual.update(|window, cx| window.simulate_next_frame(cx)); let frames = visual.update(|window, cx| window.simulate_next_frame(cx));
assert_eq!( assert_eq!(
frames, 0, frames, 0,
@@ -68,12 +84,25 @@ fn an_idle_field_page_schedules_no_frames() {
); );
} }
/// The caret blink is fps-capped: it must never demand a next frame, and its
/// redraws arrive on the executor timer at the blink cadence.
#[test] #[test]
fn a_focused_field_page_schedules_frames_for_its_blink() { fn a_focused_field_blink_is_fps_capped_and_still_redraws() {
let (_cx, _url, mut visual) = field_host(true); let (cx, _url, mut visual, renders) = field_host(true);
let renders_after_focus = renders.get();
let frames = visual.update(|window, cx| window.simulate_next_frame(cx)); let frames = visual.update(|window, cx| window.simulate_next_frame(cx));
assert_eq!(
frames, 0,
"the blink must be fps-capped, not per-frame scheduled"
);
// The blink redraws through the executor timer (4 fps cap).
cx.executor().advance_clock(Duration::from_millis(251));
cx.run_until_parked();
visual.update(|window, cx| window.draw(cx).clear(cx));
assert!( assert!(
frames > 0, renders.get() > renders_after_focus,
"the focused caret's blink needs frames to redraw at the blink cadence" "the capped blink must still redraw its page"
); );
} }
+3 -3
View File
@@ -195,7 +195,6 @@ impl RenderOnce for Sidebar {
.clone() .clone()
.unwrap_or_else(|| SharedString::from(self.id.to_string())); .unwrap_or_else(|| SharedString::from(self.id.to_string()));
let id_text = self.id.to_string();
let scroll_area_id = (self.id.clone(), "entries"); let scroll_area_id = (self.id.clone(), "entries");
// Entry paint reads the theme through this borrow. // Entry paint reads the theme through this borrow.
@@ -216,9 +215,10 @@ impl RenderOnce for Sidebar {
}) })
.collect(); .collect();
let id = self.id;
div() div()
.id(self.id) .id(id.clone())
.debug_selector(move || format!("sidebar-{id_text}")) .debug_selector(move || format!("sidebar-{id}"))
.size_full() .size_full()
.flex() .flex()
.flex_col() .flex_col()
+6 -4
View File
@@ -307,8 +307,9 @@ fn render_tab(
let mut strip_tab = div() let mut strip_tab = div()
.id((tab.key.clone(), "tab")) .id((tab.key.clone(), "tab"))
.debug_selector({ .debug_selector({
let id = format!("{tabs_id}-tab-{}", tab.label); let tabs_id = tabs_id.clone();
move || id let label = tab.label.clone();
move || format!("{tabs_id}-tab-{}", label)
}) })
.flex() .flex()
.items_center() .items_center()
@@ -411,8 +412,9 @@ fn render_tab_close(
.small() .small()
.tab_stop(false) .tab_stop(false)
.debug_selector({ .debug_selector({
let id = format!("{tabs_id}-close-{}", tab.label); let tabs_id = tabs_id.clone();
move || id.clone() let label = tab.label.clone();
move || format!("{tabs_id}-close-{}", label)
}) })
.tooltip(Tooltip::text("Close")) .tooltip(Tooltip::text("Close"))
.accessibility_label(SharedString::from(format!("Close {}", tab.label))) .accessibility_label(SharedString::from(format!("Close {}", tab.label)))
+4 -7
View File
@@ -462,10 +462,10 @@ fn render_row(
line_height: Pixels, line_height: Pixels,
cx: &App, cx: &App,
) -> gpui::AnyElement { ) -> gpui::AnyElement {
let line = code.code().lines.get(line_ix).cloned().unwrap_or_default(); let line = code.code().lines.get(line_ix);
let mut text = String::new(); let mut text = String::new();
for span in &line.spans { for span in line.map_or(&[][..], |line| line.spans.as_slice()) {
text.push_str(&span.text); text.push_str(&span.text);
} }
@@ -473,7 +473,7 @@ fn render_row(
let mut roles = vec![Role::Text; char_count]; let mut roles = vec![Role::Text; char_count];
let mut offset = 0usize; let mut offset = 0usize;
for span in &line.spans { for span in line.map_or(&[][..], |line| line.spans.as_slice()) {
let chars = span.text.chars().count(); let chars = span.text.chars().count();
for slot in &mut roles[offset..offset + chars] { for slot in &mut roles[offset..offset + chars] {
*slot = span.role; *slot = span.role;
@@ -543,10 +543,7 @@ fn render_row(
}; };
div() div()
.debug_selector({ .debug_selector(move || format!("{id}-row-{line_ix}"))
let name = format!("{id}-row-{line_ix}");
move || name
})
.id(("code-row", line_ix)) .id(("code-row", line_ix))
.w_full() .w_full()
.h(line_height) .h(line_height)
+25 -11
View File
@@ -237,6 +237,8 @@ pub fn diff_rows(old: &str, new: &str, language: Language) -> Vec<DiffRow> {
pub struct DiffViewState { pub struct DiffViewState {
id: ElementId, id: ElementId,
rows: Vec<DiffRow>, rows: Vec<DiffRow>,
/// The row whose width drives horizontal scroll extent, `rows`-derived.
widest_row: Option<usize>,
options: DiffViewOptions, options: DiffViewOptions,
/// Drives both scroll axes of the virtualized row list. /// Drives both scroll axes of the virtualized row list.
handle: UniformListScrollHandle, handle: UniformListScrollHandle,
@@ -251,13 +253,32 @@ impl DiffViewState {
O: AsRef<str>, O: AsRef<str>,
N: AsRef<str>, N: AsRef<str>,
{ {
Self { let mut state = Self {
id: id.into(), id: id.into(),
rows: diff_rows(old.as_ref(), new.as_ref(), language), rows: Vec::new(),
widest_row: None,
options: DiffViewOptions::default(), options: DiffViewOptions::default(),
handle: UniformListScrollHandle::new(), handle: UniformListScrollHandle::new(),
a11y_label: None, a11y_label: None,
};
state.set_rows(old, new, language);
state
} }
/// Replaces the rows, recomputing `widest_row` with them.
fn set_rows<O, N>(&mut self, old: O, new: N, language: Language)
where
O: AsRef<str>,
N: AsRef<str>,
{
self.rows = diff_rows(old.as_ref(), new.as_ref(), language);
self.widest_row = self
.rows
.iter()
.enumerate()
.filter(|(_, row)| row.kind != DiffRowKind::Hunk)
.max_by_key(|(_, row)| row.char_count())
.map(|(ix, _)| ix);
} }
/// Sets how changed rows are marked. /// Sets how changed rows are marked.
@@ -284,7 +305,7 @@ impl DiffViewState {
O: AsRef<str>, O: AsRef<str>,
N: AsRef<str>, N: AsRef<str>,
{ {
self.rows = diff_rows(old.as_ref(), new.as_ref(), language); self.set_rows(old, new, language);
self.handle.scroll_to_item(0, ScrollStrategy::Top); self.handle.scroll_to_item(0, ScrollStrategy::Top);
// The replaced versions rarely share the old width; start at the left. // The replaced versions rarely share the old width; start at the left.
let offset = ScrollbarHandle::offset(&self.handle); let offset = ScrollbarHandle::offset(&self.handle);
@@ -328,14 +349,7 @@ impl Render for DiffViewState {
let state = cx.entity(); let state = cx.entity();
let row_count = self.rows.len(); let row_count = self.rows.len();
let options = self.options; let options = self.options;
let widest_row = self.widest_row;
let widest_row = self
.rows
.iter()
.enumerate()
.filter(|(_, row)| row.kind != DiffRowKind::Hunk)
.max_by_key(|(_, row)| row.char_count())
.map(|(ix, _)| ix);
let mut rows = uniform_list((id.clone(), "rows"), row_count, { let mut rows = uniform_list((id.clone(), "rows"), row_count, {
move |range, _window, cx| { move |range, _window, cx| {
+2 -2
View File
@@ -784,8 +784,8 @@ fn block_frame(
let theme = cx.theme(); let theme = cx.theme();
let content = div() let content = div()
.debug_selector({ .debug_selector({
let name = SharedString::from(format!("{id}")); let id = id.clone();
move || name.to_string() move || id.to_string()
}) })
.w_full() .w_full()
.flex() .flex()
+8 -16
View File
@@ -969,15 +969,10 @@ fn render_pane(
.map(|tab| tab.view.clone()); .map(|tab| tab.view.clone());
// The cache keeps an un-notified panel from re-rendering on dock frames. // The cache keeps an un-notified panel from re-rendering on dock frames.
let content_id = SharedString::from(format!("{dock_id}-content-{}", pane.key));
let content = div() let content = div()
.id(SharedString::from(format!( .id(content_id.clone())
"{dock_id}-content-{}", .debug_selector(move || content_id.to_string())
pane.key
)))
.debug_selector({
let id = SharedString::from(format!("{dock_id}-content-{}", pane.key));
move || id.to_string()
})
.flex_1() .flex_1()
.min_h_0() .min_h_0()
.overflow_hidden() .overflow_hidden()
@@ -999,6 +994,7 @@ fn render_pane(
let pane = pane.clone(); let pane = pane.clone();
let titlebar = *titlebar; let titlebar = *titlebar;
let padding_x = metrics.dense_padding_x; let padding_x = metrics.dense_padding_x;
move |window, cx| { move |window, cx| {
let selected = pane let selected = pane
.active .active
@@ -1065,15 +1061,11 @@ fn render_pane(
} }
}); });
let bar_id = SharedString::from(format!("{dock_id}-pane-{}-bar", pane.key));
h_flex() h_flex()
.id(SharedString::from(format!( .id(bar_id.clone())
"{dock_id}-pane-{}-bar", .debug_selector(move || bar_id.to_string())
pane.key
)))
.debug_selector({
let id = SharedString::from(format!("{dock_id}-pane-{}-bar", pane.key));
move || id.to_string()
})
.flex_none() .flex_none()
.w_full() .w_full()
.h(titlebar.height) .h(titlebar.height)
+16 -18
View File
@@ -1,7 +1,8 @@
use gpui::prelude::FluentBuilder as _; use gpui::prelude::FluentBuilder as _;
use gpui::{ use gpui::{
App, Bounds, BoxShadow, Div, ElementId, FocusHandle, Global, Hsla, IntoElement, Pixels, App, Bounds, BoxShadow, Div, ElementId, FocusHandle, Global, Hsla, IntoElement, Pixels,
Refineable as _, StatefulInteractiveElement, StyleRefinement, Styled, Window, div, px, Refineable as _, StatefulInteractiveElement, StyleRefinement, Styled, Window, WindowId, div,
px,
}; };
use gpui_native_theme::ActiveTheme as _; use gpui_native_theme::ActiveTheme as _;
use std::collections::HashMap; use std::collections::HashMap;
@@ -36,39 +37,36 @@ pub fn focus_handle(id: &ElementId, window: &mut Window, cx: &mut App) -> FocusH
.clone() .clone()
} }
/// The painted bounds of elements that tooltips anchor to, keyed by element id. /// The painted bounds of elements that tooltips anchor to, per window and element id.
#[derive(Clone, Default)] #[derive(Default)]
struct AnchorBoundsRegistry(HashMap<ElementId, Bounds<Pixels>>); struct AnchorBoundsRegistry(HashMap<(WindowId, ElementId), Bounds<Pixels>>);
impl Global for AnchorBoundsRegistry {} impl Global for AnchorBoundsRegistry {}
impl AnchorBoundsRegistry { impl AnchorBoundsRegistry {
fn record(&mut self, id: ElementId, bounds: Bounds<Pixels>) { fn record(&mut self, window: WindowId, id: ElementId, bounds: Bounds<Pixels>) {
self.0.insert(id, bounds); self.0.insert((window, id), bounds);
} }
fn get(&self, id: &ElementId) -> Option<Bounds<Pixels>> { fn get(&self, window: WindowId, id: &ElementId) -> Option<Bounds<Pixels>> {
self.0.get(id).copied() self.0.get(&(window, id.clone())).copied()
} }
} }
/// The last bounds an element painted at. /// The last bounds an element painted at, in the given window.
pub fn anchor_bounds(id: &ElementId, cx: &mut App) -> Option<Bounds<Pixels>> { pub fn anchor_bounds(window: WindowId, id: &ElementId, cx: &App) -> Option<Bounds<Pixels>> {
cx.try_global::<AnchorBoundsRegistry>() cx.try_global::<AnchorBoundsRegistry>()
.and_then(|registry| registry.get(id)) .and_then(|registry| registry.get(window, id))
} }
/// A canvas prepaint closure recording the element's painted bounds. /// A canvas prepaint closure recording the element's painted bounds.
pub fn record_anchor_bounds( pub fn record_anchor_bounds(
id: ElementId, id: ElementId,
) -> impl Fn(Bounds<Pixels>, &mut Window, &mut App) + 'static { ) -> impl Fn(Bounds<Pixels>, &mut Window, &mut App) + 'static {
move |bounds, _window, cx| { move |bounds, window, cx| {
let mut registry = cx let window_id = window.window_handle().window_id();
.try_global::<AnchorBoundsRegistry>() cx.default_global::<AnchorBoundsRegistry>()
.cloned() .record(window_id, id.clone(), bounds);
.unwrap_or_default();
registry.record(id.clone(), bounds);
cx.set_global(registry);
} }
} }