perf: reuse rendered elements across repaints
Rust / build (macos-latest, stable) (push) Canceled after 0s
Rust / build (ubuntu-latest, stable) (push) Canceled after 0s
Rust / build (windows-latest, stable) (push) Canceled after 0s

This commit is contained in:
2026-11-25 05:00:06 +07:00
parent 3f64b36ff4
commit bf06d29c2e
21 changed files with 603 additions and 316 deletions
+7 -1
View File
@@ -312,6 +312,9 @@ impl RenderOnce for Dialog {
.read(cx)
.clone();
// The panel takes focus when it first paints, and again whenever nothing else holds it.
let painted = window.use_keyed_state((self.id.clone(), "dialog-painted"), cx, |_, _| false);
deferred(
root.flex()
.items_center()
@@ -442,8 +445,11 @@ impl RenderOnce for Dialog {
})
.child(
canvas(|_, _, _| {}, {
let painted = painted.clone();
move |_, _, window, cx| {
if !focus.contains_focused(window, cx) {
let first_paint = painted
.update(cx, |painted, _| !std::mem::replace(painted, true));
if first_paint || window.focused(cx).is_none() {
window.focus(&focus, cx);
}
}
+24 -43
View File
@@ -1005,11 +1005,6 @@ impl InputState {
/// with the paint-time text style. Reuses the previous result while the
/// text, wrap width, and text style are unchanged.
fn shape_current_text(&self, wrap_width: Option<Pixels>, window: &Window) -> ShapedText {
let (text, mask_map) = if self.masked() {
masked_display(&self.text)
} else {
(self.text.clone(), None)
};
let text_style = window.text_style();
let font = Font {
@@ -1022,6 +1017,23 @@ impl InputState {
let font_size = text_style.font_size.to_pixels(window.rem_size());
if !self.masked()
&& let Some((cached_key, shaped)) = self.shaped_cache.borrow().as_ref()
&& cached_key.text == self.text
&& cached_key.wrap_width == wrap_width
&& cached_key.font_size == font_size
&& cached_key.font == font
&& cached_key.color == text_style.color
{
return shaped.clone();
}
let (text, mask_map) = if self.masked() {
masked_display(&self.text)
} else {
(self.text.clone(), None)
};
let key = ShapeCacheKey {
text: text.clone(),
wrap_width,
@@ -1030,12 +1042,6 @@ impl InputState {
color: text_style.color,
};
if let Some((cached_key, shaped)) = self.shaped_cache.borrow().as_ref()
&& *cached_key == key
{
return shaped.clone();
}
let runs = [TextRun {
len: text.len(),
font,
@@ -2022,6 +2028,13 @@ impl RenderOnce for Input {
let padding_x = self.size.padding_x_rems().to_pixels(rem);
let dense_padding_x = self.size.dense_padding_x_rems().to_pixels(rem);
let focus_handle = self.state.read(cx).focus_handle.clone();
let owner = window.current_view();
let state = self.state.clone();
window.use_keyed_state((self.id.clone(), "input-owner"), cx, |_, cx| {
// Edits must repaint the view that renders the field, even below a cached view.
App::observe(cx, &state, move |_, cx| cx.notify(owner))
});
let focused = focus_handle.is_focused(window);
let is_empty = self.state.read(cx).text.is_empty();
@@ -2634,35 +2647,3 @@ fn floor_to_char_boundary(text: &str, index: usize) -> usize {
}
index
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[allow(clippy::reversed_empty_ranges)] // The fixture is intentionally reversed.
fn utf16_range_to_utf8_orders_reversed_endpoints() {
// "héllo": h 0, é 1, l 2, l 3, o 4 in UTF-16 units.
let text = "héllo";
assert_eq!(utf16_range_to_utf8(text, 4..2), 3..5);
assert_eq!(utf16_range_to_utf8(text, 2..4), 3..5);
}
#[test]
#[allow(clippy::reversed_empty_ranges)] // The fixture is intentionally reversed.
fn utf8_range_to_utf16_floors_off_boundary_offsets() {
let text = "héllo";
// Byte 2 sits inside `é`; a reversed, off-boundary range must not panic.
let range = utf8_range_to_utf16(text, 4..2);
assert!(range.start <= range.end);
assert_eq!(range, 1..3);
}
#[test]
fn char_boundary_floor_clamps_to_len() {
// "héllo" is six bytes.
assert_eq!(floor_to_char_boundary("héllo", 7), 6);
assert_eq!(floor_to_char_boundary("héllo", 2), 1);
assert_eq!(floor_to_char_boundary("héllo", 0), 0);
}
}
+11 -4
View File
@@ -460,7 +460,14 @@ impl Tab {
.group_hover(group.clone(), |style| style.visible()),
)
})
.when(!titlebar, |label| label.child(self.label.clone()));
.when(!titlebar, |label| {
label
.min_w_0()
.whitespace_nowrap()
.overflow_hidden()
.text_ellipsis()
.child(self.label.clone())
});
let strip_tab = div()
.id((self.key.clone(), "tab"))
@@ -485,9 +492,9 @@ impl Tab {
})
})
.map(|strip_tab| {
apply_tab_chrome(strip_tab, ctx.variant, active, cx).when(titlebar, |strip_tab| {
strip_tab.min_w(TAB_MIN_WIDTH).max_w(TAB_MAX_WIDTH)
})
apply_tab_chrome(strip_tab, ctx.variant, active, cx)
.max_w(TAB_MAX_WIDTH)
.when(titlebar, |strip_tab| strip_tab.min_w(TAB_MIN_WIDTH))
})
.when_some(self.lead.take(), |strip_tab, lead| strip_tab.child(lead))
.child(label)
+12 -5
View File
@@ -3,14 +3,16 @@
//! # Examples
//!
//! ```no_run
//! use std::sync::Arc;
//!
//! use ui::tree::{Tree, TreeItem};
//!
//! let project = Tree::new("project")
//! .items(|_, _| {
//! vec![
//! Arc::new(vec![
//! TreeItem::new("src", "src").expandable(true).expanded(true),
//! TreeItem::new("main", "main.rs").depth(1),
//! ]
//! ])
//! })
//! .on_change(|_selected, _window, _cx| println!("selection changed"));
//! ```
@@ -18,6 +20,7 @@
use std::collections::{HashMap, HashSet};
use std::path::PathBuf;
use std::rc::Rc;
use std::sync::Arc;
use gpui::prelude::FluentBuilder;
use gpui::{
@@ -37,7 +40,7 @@ type ChangeHandler = Rc<dyn Fn(Option<usize>, &mut Window, &mut App)>;
/// The disclosure reporter, fired with the toggled row's index.
type DisclosureHandler = Rc<dyn Fn(usize, &mut Window, &mut App)>;
/// The visible row builder, run during render.
type ItemsFn = Box<dyn Fn(&mut Window, &mut App) -> Vec<TreeItem>>;
type ItemsFn = Box<dyn Fn(&mut Window, &mut App) -> Arc<Vec<TreeItem>>>;
/// The deepest indent the tree paints, bounding misbuilt item trees.
const TREE_MAX_DEPTH: usize = 16;
@@ -192,6 +195,10 @@ impl TreeItem {
.child(
div()
.flex_1()
.min_w_0()
.whitespace_nowrap()
.overflow_hidden()
.text_ellipsis()
.text_color(label_color)
.child(self.label.clone()),
)
@@ -465,7 +472,7 @@ impl Tree {
/// Sets the visible rows; the closure runs during render and must not mutate entities or notify.
pub fn items<F>(mut self, items: F) -> Self
where
F: Fn(&mut Window, &mut App) -> Vec<TreeItem> + 'static,
F: Fn(&mut Window, &mut App) -> Arc<Vec<TreeItem>> + 'static,
{
self.items = Some(Box::new(items));
self
@@ -546,7 +553,7 @@ impl RenderOnce for Tree {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let items = match self.items {
Some(build) => build(window, cx),
None => Vec::new(),
None => Arc::default(),
};
let selectable: Vec<usize> = items
+29 -20
View File
@@ -401,19 +401,16 @@ impl PanelStack {
/// The main stack's tab strip for the titlebar; `None` while the stack is empty.
pub fn main_tabs(stack: Entity<Self>, cx: &App) -> Option<Tabs> {
let (id, panels, selected) = {
let (id, selected) = {
let this = stack.read(cx);
if this.main.is_empty() {
return None;
}
(
this.id.clone(),
this.main.panels.clone(),
this.main.selected().unwrap_or(usize::MAX),
)
(this.id.clone(), this.main.selected().unwrap_or(usize::MAX))
};
let change = stack.downgrade();
let close = change.clone();
let tabs = change.clone();
Some(
Tabs::new((id, "main-tabs"))
@@ -421,10 +418,15 @@ impl PanelStack {
.overflow_scroll(true)
.selected(selected)
.tabs(move |_, cx| {
panels
.iter()
.map(|(id, panel)| panel.tab(id.clone().into(), cx).closeable(true))
.collect()
tabs.read_with(cx, |stack, cx| {
stack
.main
.panels
.iter()
.map(|(id, panel)| panel.tab(id.clone().into(), cx).closeable(true))
.collect()
})
.unwrap_or_default()
})
.on_change(move |index, _, cx| {
change
@@ -539,10 +541,10 @@ impl PanelStack {
/// The split pane's content: the split stack's tabs over its shown panel.
fn split_pane(&self, cx: &mut Context<Self>) -> AnyElement {
let panels: Vec<(SharedString, Arc<dyn PanelView>)> = self.split.panels.clone();
let selected = self.split.selected().unwrap_or(usize::MAX);
let change = cx.weak_entity();
let close = change.clone();
let tabs = change.clone();
v_flex()
.size_full()
@@ -554,10 +556,17 @@ impl PanelStack {
.overflow_scroll(true)
.selected(selected)
.tabs(move |_, cx| {
panels
.iter()
.map(|(id, panel)| panel.tab(id.clone().into(), cx).closeable(true))
.collect()
tabs.read_with(cx, |stack, cx| {
stack
.split
.panels
.iter()
.map(|(id, panel)| {
panel.tab(id.clone().into(), cx).closeable(true)
})
.collect()
})
.unwrap_or_default()
})
.on_change(move |index, _, cx| {
change
@@ -574,11 +583,11 @@ impl PanelStack {
)
})
.child(
div()
.flex_1()
.min_h_0()
.w_full()
.children(self.split.active().map(|panel| panel.view())),
div().flex_1().min_h_0().w_full().children(
self.split
.active()
.map(|panel| panel.view().cached(content_style()).into_any_element()),
),
)
.into_any_element()
}
+6 -2
View File
@@ -504,8 +504,12 @@ pub(crate) fn reapply(cx: &mut App) {
let resolved = resolve::resolve(&system, preset.as_ref(), mode_override, custom);
cx.set_reduce_motion(resolved.accessibility.reduce_motion);
cx.set_global(Theme::from_resolved(resolved));
cx.refresh_windows();
let theme = Theme::from_resolved(resolved);
let theme_changed = cx.try_global::<Theme>() != Some(&theme);
cx.set_global(theme);
if theme_changed {
cx.refresh_windows();
}
}
/// Forces a variant, independent of the OS. `None` follows the system.
+71
View File
@@ -1,6 +1,8 @@
//! The panel stack: the main island fills the window; splitting makes two
//! half-width islands with a drag divider that resizes them.
use std::cell::Cell;
use std::rc::Rc;
use std::sync::Arc;
use gpui::{
@@ -10,6 +12,7 @@ use gpui::{
size,
};
use ui::common::v_flex;
use ui::input::{Input, InputState};
use ui::layout::panel::{Panel, PanelSlot, PanelStack, PanelView, SplitSide};
use ui::tabs::Tabs;
use ui::theme::Theme;
@@ -69,6 +72,28 @@ impl Render for PanelHarness {
}
}
/// A split panel that counts its renders around a field.
struct FieldView {
input: Entity<InputState>,
renders: Rc<Cell<usize>>,
}
impl Render for FieldView {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
self.renders.set(self.renders.get() + 1);
div()
.debug_selector(|| "panel-test-field".to_string())
.size_full()
.child(Input::new("split-field", self.input.clone()))
}
}
impl Panel for FieldView {
fn title(&self, _cx: &App) -> SharedString {
"Field".into()
}
}
/// A marker view.
fn tag(cx: &mut App, selector: &'static str) -> Entity<TagView> {
cx.new(|_| TagView::new(selector))
@@ -989,3 +1014,49 @@ fn zoom_ends_when_another_split_panel_is_shown(cx: &mut TestAppContext) {
"the split is back once another panel is shown"
);
}
/// The split panel is cached: it repaints for its own changes, not for other panels'.
#[gpui::test]
fn a_split_panel_repaints_for_its_own_changes_only(cx: &mut TestAppContext) {
let renders = Rc::new(Cell::new(0));
let (input, main, field) = cx.update(|cx| {
let input = InputState::new(cx);
let field = cx.new(|_| FieldView {
input: input.clone(),
renders: Rc::clone(&renders),
});
(input, tag(cx, "panel-test-main"), field)
});
let seeded_main = main.clone();
let seeded_field = field.clone();
let (mut cx, _stack) = stack_window(cx, move |stack, cx| {
stack.insert(PanelSlot::Main, "main", Arc::new(seeded_main), cx);
stack.insert(PanelSlot::Split, "split", Arc::new(seeded_field), cx);
});
let rendered = renders.get();
cx.update(|window, cx| input.update(cx, |input, cx| input.set_value("hey", window, cx)));
cx.run_until_parked();
let typed = cx.update(|_, cx| input.read(cx).value().to_string());
assert_eq!(typed, "hey");
assert!(
renders.get() > rendered,
"an edit in the split panel repaints it"
);
let rendered = renders.get();
cx.update(|_, cx| main.update(cx, |_, cx| cx.notify()));
cx.run_until_parked();
assert_eq!(
renders.get(),
rendered,
"another panel's change leaves the split panel as it was"
);
cx.update(|_, cx| field.update(cx, |_, cx| cx.notify()));
cx.run_until_parked();
assert!(
renders.get() > rendered,
"the split panel's own change repaints it"
);
}