mirror of
https://github.com/zed-industries/zed.git
synced 2026-12-03 05:51:27 +01:00
gpui: Keep measured layouts while their inputs are unchanged (#67223)
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
This commit is contained in:
@@ -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
|
||||
|
||||
+305
-137
@@ -598,6 +598,216 @@ struct TextLayoutInner {
|
||||
bounds: Option<Bounds<Pixels>>,
|
||||
}
|
||||
|
||||
/// What a text element's size depends on, and where its measurement is stored for
|
||||
/// painting.
|
||||
pub(crate) struct TextMeasure {
|
||||
text: SharedString,
|
||||
runs: Vec<TextRun>,
|
||||
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<Option<Pixels>>,
|
||||
available_space: Size<crate::AvailableSpace>,
|
||||
final_layout: bool,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) -> Size<Pixels> {
|
||||
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<Pixels> = 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<Vec<TextRun>>,
|
||||
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<Pixels> = 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<Pixels>, 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::<Pixels>()
|
||||
})
|
||||
};
|
||||
let fresh_size =
|
||||
|space: Size<crate::AvailableSpace>, 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};
|
||||
|
||||
@@ -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
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
+389
-47
@@ -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<T> = stacksafe::StackSafe<T>;
|
||||
#[cfg(not(feature = "stacker"))]
|
||||
type StackSafe<T> = T;
|
||||
|
||||
type MeasureFn =
|
||||
dyn FnMut(Size<Option<Pixels>>, Size<AvailableSpace>, &mut Window, &mut App) -> Size<Pixels>;
|
||||
type NodeContext = StackSafe<Box<MeasureFn>>;
|
||||
type NodeContext = StackSafe<Box<dyn Measure>>;
|
||||
|
||||
/// 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<Option<Pixels>>,
|
||||
available_space: Size<AvailableSpace>,
|
||||
final_layout: bool,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) -> Size<Pixels>;
|
||||
}
|
||||
|
||||
/// Replaces `previous` in place when it already holds a `KeyedMeasure<K, F>`, 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<K, F>(
|
||||
previous: &mut NodeContext,
|
||||
mut key: K,
|
||||
reuse: fn(&mut K, &mut K) -> bool,
|
||||
measure: F,
|
||||
) -> Result<bool, (K, F)>
|
||||
where
|
||||
K: 'static,
|
||||
F: FnMut(
|
||||
&K,
|
||||
Size<Option<Pixels>>,
|
||||
Size<AvailableSpace>,
|
||||
bool,
|
||||
&mut Window,
|
||||
&mut App,
|
||||
) -> Size<Pixels>
|
||||
+ 'static,
|
||||
{
|
||||
let previous: &mut Box<dyn Measure> = previous;
|
||||
let Some(previous) = (&mut **previous as &mut dyn Any).downcast_mut::<KeyedMeasure<K, F>>()
|
||||
else {
|
||||
return Err((key, measure));
|
||||
};
|
||||
let reused = reuse(&mut key, &mut previous.key);
|
||||
previous.key = key;
|
||||
previous.measure = measure;
|
||||
Ok(reused)
|
||||
}
|
||||
|
||||
fn box_measure<K, F>(key: K, measure: F) -> NodeContext
|
||||
where
|
||||
K: 'static,
|
||||
F: FnMut(
|
||||
&K,
|
||||
Size<Option<Pixels>>,
|
||||
Size<AvailableSpace>,
|
||||
bool,
|
||||
&mut Window,
|
||||
&mut App,
|
||||
) -> Size<Pixels>
|
||||
+ 'static,
|
||||
{
|
||||
let measure: Box<dyn Measure> = 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<K, F> {
|
||||
key: K,
|
||||
measure: F,
|
||||
}
|
||||
|
||||
impl<K, F> Measure for KeyedMeasure<K, F>
|
||||
where
|
||||
K: 'static,
|
||||
F: FnMut(
|
||||
&K,
|
||||
Size<Option<Pixels>>,
|
||||
Size<AvailableSpace>,
|
||||
bool,
|
||||
&mut Window,
|
||||
&mut App,
|
||||
) -> Size<Pixels>
|
||||
+ 'static,
|
||||
{
|
||||
fn measure(
|
||||
&mut self,
|
||||
known_dimensions: Size<Option<Pixels>>,
|
||||
available_space: Size<AvailableSpace>,
|
||||
final_layout: bool,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) -> Size<Pixels> {
|
||||
(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<NodeId>,
|
||||
frame: u64,
|
||||
/// Scale factor Taffy's cached device-pixel styles and measurements were computed at.
|
||||
scale_factor: Option<f32>,
|
||||
}
|
||||
|
||||
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<K, F>(
|
||||
&mut self,
|
||||
scope: PathHash,
|
||||
style: &Style,
|
||||
rem_size: Pixels,
|
||||
scale_factor: f32,
|
||||
measure: impl FnMut(
|
||||
Size<Option<Pixels>>,
|
||||
Size<AvailableSpace>,
|
||||
&mut Window,
|
||||
&mut App,
|
||||
) -> Size<Pixels>
|
||||
+ 'static,
|
||||
) -> LayoutId {
|
||||
let measure = Box::new(measure) as Box<MeasureFn>;
|
||||
#[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<Option<Pixels>>,
|
||||
Size<AvailableSpace>,
|
||||
bool,
|
||||
&mut Window,
|
||||
&mut App,
|
||||
) -> Size<Pixels>
|
||||
+ '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<NodeContext>,
|
||||
) -> 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<Frame>) {
|
||||
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<T>(
|
||||
cx: &mut TestAppContext,
|
||||
frames: Vec<Frame>,
|
||||
mut before_cached: impl FnMut(&Window),
|
||||
mut after_cached: impl FnMut(&Window) -> T,
|
||||
) -> Vec<T> {
|
||||
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::<Vec<_>>();
|
||||
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<Pixels>);
|
||||
/// A leaf whose size comes from its measure function, which captures it and is keyed
|
||||
/// by it.
|
||||
struct MeasuredLeaf {
|
||||
size: Size<Pixels>,
|
||||
measurements: Option<Rc<Cell<usize>>>,
|
||||
}
|
||||
|
||||
impl MeasuredLeaf {
|
||||
fn new(size: Size<Pixels>) -> Self {
|
||||
Self {
|
||||
size,
|
||||
measurements: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn with_counter(size: Size<Pixels>, measurements: Rc<Cell<usize>>) -> 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::<Vec<_>>();
|
||||
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::<Vec<_>>();
|
||||
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::<Vec<_>>();
|
||||
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::<Vec<_>>();
|
||||
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| {
|
||||
|
||||
@@ -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.
|
||||
///
|
||||
|
||||
@@ -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<V>(
|
||||
cache: &mut FxHashMap<Arc<CacheKey>, Arc<V>>,
|
||||
unused: &mut FxHashMap<Arc<CacheKey>, Arc<V>>,
|
||||
) {
|
||||
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<LineLayoutCacheState>,
|
||||
wrap_scratch: RefCell<WrapScratch>,
|
||||
@@ -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<Text>(
|
||||
&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<Pixels>,
|
||||
max_lines: Option<usize>,
|
||||
force_width: Option<Pixels>,
|
||||
}
|
||||
|
||||
@@ -801,6 +829,7 @@ struct CacheKeyRef<'a> {
|
||||
font_size: Pixels,
|
||||
runs: &'a [FontRun],
|
||||
wrap_width: Option<Pixels>,
|
||||
max_lines: Option<usize>,
|
||||
force_width: Option<Pixels>,
|
||||
}
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<F>(&mut self, style: Style, measure: F) -> LayoutId
|
||||
where
|
||||
F: Fn(Size<Option<Pixels>>, Size<AvailableSpace>, &mut Window, &mut App) -> Size<Pixels>
|
||||
+ '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<K, F>(
|
||||
&mut self,
|
||||
style: Style,
|
||||
key: K,
|
||||
measure: F,
|
||||
) -> LayoutId
|
||||
where
|
||||
K: PartialEq + 'static,
|
||||
F: Fn(Size<Option<Pixels>>, Size<AvailableSpace>, &mut Window, &mut App) -> Size<Pixels>
|
||||
+ '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<K, F>(
|
||||
&mut self,
|
||||
style: &Style,
|
||||
key: K,
|
||||
reuse: fn(&mut K, &mut K) -> bool,
|
||||
measure: F,
|
||||
) -> LayoutId
|
||||
where
|
||||
K: 'static,
|
||||
F: FnMut(
|
||||
&K,
|
||||
Size<Option<Pixels>>,
|
||||
Size<AvailableSpace>,
|
||||
bool,
|
||||
&mut Window,
|
||||
&mut App,
|
||||
) -> Size<Pixels>
|
||||
+ '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
|
||||
|
||||
Reference in New Issue
Block a user