perf(layout): retain validated construction and inline work

Retain reusable box objects, topology, shaped inline inputs and eligible
numeric results through the optional caller-owned working set. Validate
source, styles, fonts and constraints before reuse, with the shared cold
constructor for unsupported graphs. Cover block, Grid and Table and keep
eight complete measurement entries per owner.
This commit is contained in:
ldm0
2026-11-22 03:42:05 +08:00
parent 3f596863f1
commit f44a31ff42
34 changed files with 7253 additions and 143 deletions
+157 -51
View File
@@ -25,6 +25,9 @@ use crate::{
};
use style::values::generics::image::GenericImage;
mod retained_construction;
pub(crate) use retained_construction::ConstructionInputs;
/// Constructs a complete pass-local CSS box tree from a borrowed source view.
pub fn build_layout_world<S, R>(
source: &S,
@@ -37,6 +40,28 @@ where
BoxBuilder::new(source, styles).build()
}
/// Reuse a validated construction graph before running the ordinary builder.
/// The source records exist only for callers retaining a working set; style,
/// resources and numeric working state still belong to this pass.
pub(crate) fn build_layout_world_with_retained_inputs<S, R>(
source: &S,
styles: &mut R,
previous: Option<&mut crate::working_set::RetainedWork<S::NodeId>>,
) -> Result<LayoutWorld<S::NodeId>, LayoutError>
where
S: LayoutSource,
R: LayoutStyleResolver<S::NodeId>,
{
if let Some(previous) = previous
&& let Some(world) = retained_construction::try_restore(source, styles, previous)?
{
return Ok(world);
}
let mut builder = BoxBuilder::new(source, styles);
builder.construction_inputs = Some(Box::new(ConstructionInputs::new(source)));
builder.build()
}
struct BoxBuilder<'a, S, R>
where
S: LayoutSource,
@@ -51,6 +76,7 @@ where
source_root: Option<S::NodeId>,
root_is_html: bool,
viewport_body_candidate: Option<ViewportBodyCandidate<S::NodeId>>,
construction_inputs: Option<Box<ConstructionInputs<S::NodeId>>>,
}
impl AnonymousInlineRunRole {
@@ -87,6 +113,7 @@ where
source_root: None,
root_is_html: false,
viewport_body_candidate: None,
construction_inputs: None,
}
}
@@ -118,10 +145,7 @@ where
};
let (mut root_style, root_before, root_after) = root_styles.into_parts();
let root_metrics = self.source.replaced_metrics(source_root);
if root_semantics.is_hidden_input()
|| (root_style.display() == LayoutDisplay::Contents
&& root_semantics.display_contents_is_none())
{
if suppresses_element_box(&root_semantics, &root_style) {
// A LayoutWorld always needs a carrier root for Taffy and paint.
// Preserve that internal carrier but give it the correct no-box
// used display and never construct source descendants.
@@ -137,6 +161,13 @@ where
) {
root_style.mark_intrinsic_form_control_container();
}
self.record_element_input(
source_root,
&root_semantics,
Some(&root_style),
root_before.is_some(),
root_after.is_some(),
);
let root_kind = principal_kind(&root_semantics, &root_style);
let root_generates_principal_box = root_style.display() != LayoutDisplay::None;
let mut root = self.principal_box(
@@ -204,6 +235,13 @@ where
);
}
world.css_image_references = self.css_image_references;
if self
.construction_inputs
.as_ref()
.is_some_and(|inputs| inputs.supports_graph(&world))
{
world.construction_inputs = self.construction_inputs;
}
Ok(world)
}
@@ -241,26 +279,21 @@ where
match source_kind {
LayoutSourceKind::Comment | LayoutSourceKind::Other => {
self.validate_non_element_semantics(source_node, source_kind)?;
if let Some(inputs) = &mut self.construction_inputs {
inputs.record_ignored(self.source, source_node, source_kind);
}
Ok(Vec::new())
}
LayoutSourceKind::Text => {
self.validate_non_element_semantics(source_node, source_kind)?;
let Some(text) = self.source.text(source_node) else {
let text = self.source.text(source_node).map(Arc::<str>::from);
if let Some(inputs) = &mut self.construction_inputs {
inputs.record_text(self.source, source_node, text.as_ref());
}
let Some(text) = text else {
return Ok(Vec::new());
};
let id = world.allocate(LayoutWorld::new_box(
Some(source_node),
None,
None,
self.source.label(source_node),
None,
None,
None,
LayoutBoxKind::Text,
ResolvedLayoutStyle::text_leaf_from(inherited_style),
Some(Arc::from(text)),
));
world.boxes[id.index()].text_selection = self.source.text_selection(source_node);
let id = world.allocate(self.text_box(source_node, inherited_style, text));
world.map_source(source_node, id);
Ok(vec![id])
}
@@ -283,22 +316,11 @@ where
let semantics =
self.validated_element_semantics(source_node, self.source.node_kind(source_node))?;
let Some(styles) = self.styles.element_styles(source_node)? else {
self.record_element_input(source_node, &semantics, None, false, false);
return Ok(Vec::new());
};
let (mut style, before, after) = styles.into_parts();
if self.viewport_body_candidate.is_none()
&& self.root_is_html
&& self
.source_root
.is_some_and(|root| self.source.flat_parent(source_node) == Some(root))
&& semantics.is_html_element("body")
{
self.viewport_body_candidate = Some(ViewportBodyCandidate {
source: source_node,
overflow: style.overflow_modes(),
blocks_propagation: style.applies_any_viewport_containment(),
});
}
self.note_viewport_body_candidate(source_node, &semantics, &style);
let metrics = self.source.replaced_metrics(source_node);
if semantics.is_replaced() {
style.mark_replaced(
@@ -311,10 +333,14 @@ where
style.mark_intrinsic_form_control_container();
}
if semantics.is_hidden_input()
|| (style.display() == LayoutDisplay::Contents
&& semantics.display_contents_is_none())
{
self.record_element_input(
source_node,
&semantics,
Some(&style),
before.is_some(),
after.is_some(),
);
if suppresses_element_box(&semantics, &style) {
return Ok(Vec::new());
}
@@ -365,6 +391,44 @@ where
result
}
fn record_element_input(
&mut self,
node: S::NodeId,
semantics: &LayoutElementSemantics,
style: Option<&ResolvedLayoutStyle>,
before: bool,
after: bool,
) {
if self.construction_inputs.as_mut().is_some_and(|inputs| {
!inputs.record_element(self.source, node, semantics, style, before, after)
}) {
// An unsupported construction decision makes the complete graph
// ineligible. Its normal shared builder path remains unchanged.
self.construction_inputs = None;
}
}
fn note_viewport_body_candidate(
&mut self,
node: S::NodeId,
semantics: &LayoutElementSemantics,
style: &ResolvedLayoutStyle,
) {
if self.viewport_body_candidate.is_none()
&& self.root_is_html
&& self
.source_root
.is_some_and(|root| self.source.flat_parent(node) == Some(root))
&& semantics.is_html_element("body")
{
self.viewport_body_candidate = Some(ViewportBodyCandidate {
source: node,
overflow: style.overflow_modes(),
blocks_propagation: style.applies_any_viewport_containment(),
});
}
}
/// Converts the construction-only body candidate into the final viewport
/// policy before the world crosses into numeric layout. No body computed
/// style is retained by `LayoutWorld`.
@@ -417,36 +481,69 @@ where
style: ResolvedLayoutStyle,
metrics: Option<crate::ReplacedMetrics>,
) -> crate::LayoutBox<S::NodeId> {
let replaced_context = build_replaced_context(&semantics, metrics, &style);
let mut layout_box = LayoutWorld::new_box(
Some(source_node),
None,
None,
source_label,
None,
Some(semantics.clone()),
Some(semantics),
None,
kind,
style.clone(),
style,
None,
);
layout_box.replaced_context = replaced_context;
layout_box.replaced_image = self.source.replaced_image(source_node, &style);
if !matches!(
self.refresh_principal_inputs(&mut layout_box, metrics);
layout_box
}
/// Shared source sampling for cold construction and owned graph updates.
fn refresh_principal_inputs(
&mut self,
layout_box: &mut crate::LayoutBox<S::NodeId>,
metrics: Option<crate::ReplacedMetrics>,
) {
let source_node = layout_box.source.expect("a principal box has a source");
let semantics = layout_box
.element_semantics
.as_ref()
.expect("principal semantics");
let style = &layout_box.style;
layout_box.replaced_context = build_replaced_context(semantics, metrics, style);
layout_box.replaced_image = self.source.replaced_image(source_node, style);
layout_box.css_images = if !matches!(
style.display(),
LayoutDisplay::None | LayoutDisplay::Contents
) {
layout_box.css_images = self.css_image_resources(source_node, &style);
}
// DOM scroll state is stored in CSSOM units. Numeric layout operates
// in effective-zoomed CSS pixels, so import the sampled state into the
// same coordinate space as the box geometry.
let scroll_offset = self.source.scroll_offset(source_node);
let effective_zoom = style.effective_zoom();
layout_box.scroll_offset = crate::LayoutPoint::new(
scroll_offset.x * effective_zoom,
scroll_offset.y * effective_zoom,
self.css_image_resources(source_node, style)
} else {
crate::source::LayoutCssImageResources::default()
};
// Source scroll is in CSSOM units; numeric geometry uses effective zoom.
let offset = self.source.scroll_offset(source_node);
let zoom = style.effective_zoom();
layout_box.scroll_offset = crate::LayoutPoint::new(offset.x * zoom, offset.y * zoom);
}
fn text_box(
&self,
source: S::NodeId,
inherited_style: &ResolvedLayoutStyle,
text: Arc<str>,
) -> crate::LayoutBox<S::NodeId> {
let mut layout_box = LayoutWorld::new_box(
Some(source),
None,
None,
self.source.label(source),
None,
None,
None,
LayoutBoxKind::Text,
ResolvedLayoutStyle::text_leaf_from(inherited_style),
Some(text),
);
layout_box.text_selection = self.source.text_selection(source);
layout_box
}
@@ -1327,6 +1424,9 @@ where
}
self.seen_sources.insert(*child, parent_label.clone());
}
if let Some(inputs) = &mut self.construction_inputs {
inputs.record_children(parent, &children);
}
Ok(children)
}
@@ -1391,6 +1491,12 @@ struct ViewportBodyCandidate<N> {
blocks_propagation: bool,
}
fn suppresses_element_box(semantics: &LayoutElementSemantics, style: &ResolvedLayoutStyle) -> bool {
style.display() == LayoutDisplay::None
|| semantics.is_hidden_input()
|| (style.display() == LayoutDisplay::Contents && semantics.display_contents_is_none())
}
fn build_replaced_context(
semantics: &LayoutElementSemantics,
metrics: Option<crate::ReplacedMetrics>,
@@ -0,0 +1,553 @@
//! Validation of source inputs before reusing an existing construction graph.
//!
//! These records describe the source frontier, including nodes that generated
//! no box. The normalized graph has one owner in `RetainedWork::graph`.
//! Unsupported shapes use the ordinary builder; there is no second anonymous
//! box, table, pseudo-element or form-control construction algorithm here.
use std::{fmt::Debug, hash::Hash, sync::Arc, time::Instant};
use super::{BoxBuilder, principal_kind, suppresses_element_box};
use crate::{
LayoutBoxId, LayoutBoxKind, LayoutDisplay, LayoutElementCategory, LayoutElementSemantics,
LayoutError, LayoutNamespace, LayoutPosition, LayoutSource, LayoutSourceKind,
LayoutStyleResolver, LayoutWorld, ResolvedLayoutStyle, style::InlineWhiteSpaceCollapse,
working_set::RetainedWork,
};
#[derive(Clone, Debug, PartialEq, Eq)]
enum ElementShape {
MissingStyle,
Suppressed,
Principal {
kind: LayoutBoxKind,
display: LayoutDisplay,
position: LayoutPosition,
out_of_flow: bool,
white_space: InlineWhiteSpaceCollapse,
},
}
impl ElementShape {
fn from_inputs(
semantics: &LayoutElementSemantics,
style: Option<&ResolvedLayoutStyle>,
before: bool,
after: bool,
) -> Option<Self> {
let Some(style) = style else {
return Some(Self::MissingStyle);
};
if suppresses_element_box(semantics, style) {
// Descendants and pseudos are not consumed while this frontier is
// suppressed. Its semantics and current suppression are checked
// again before every reuse, including head and body script nodes.
return Some(Self::Suppressed);
}
let kind = principal_kind(semantics, style);
if !matches!(
semantics.category,
LayoutElementCategory::Generic | LayoutElementCategory::Table(_)
) || !matches!(
style.display(),
LayoutDisplay::Block
| LayoutDisplay::FlowRoot
| LayoutDisplay::Grid
| LayoutDisplay::Table
| LayoutDisplay::InlineTable
| LayoutDisplay::TableCaption
| LayoutDisplay::TableRowGroup
| LayoutDisplay::TableHeaderGroup
| LayoutDisplay::TableFooterGroup
| LayoutDisplay::TableRow
| LayoutDisplay::TableCell
| LayoutDisplay::TableColumnGroup
| LayoutDisplay::TableColumn
) || (semantics
.category
.child_box_policy(semantics.is_replaced(), style.display())
== crate::ChildBoxPolicy::None
&& kind != LayoutBoxKind::TableColumn)
|| style.is_floated()
|| before
|| after
{
return None;
}
// Admit the shared builder's actual source-backed graph, not a second
// set of flow/Grid/table normalization rules. Anonymous repairs and
// discarded principal styles are checked against the finished graph.
// A table column is a source-backed leaf with no private replaced or
// form-control contents; its unconsumed descendants stay outside the
// recorded frontier. Numeric parents and table/grid data stay fresh.
Some(Self::Principal {
kind,
display: style.display(),
position: style.position(),
out_of_flow: style.is_out_of_flow(),
white_space: style.white_space_collapse(),
})
}
}
#[derive(Clone, Debug)]
enum SourceInputKind {
Element {
semantics: LayoutElementSemantics,
shape: ElementShape,
},
Text(Option<Arc<str>>),
Ignored(LayoutSourceKind),
}
impl SourceInputKind {
fn node_kind(&self) -> LayoutSourceKind {
match self {
Self::Element { .. } => LayoutSourceKind::Element,
Self::Text(_) => LayoutSourceKind::Text,
Self::Ignored(kind) => *kind,
}
}
}
#[derive(Clone, Debug)]
struct SourceInput<N> {
node: N,
parent: Option<N>,
kind: SourceInputKind,
// None marks a frontier the shared builder did not descend into. Some
// records the exact canonical flat-child sequence, including ignored and
// subsequently compacted-away nodes, rather than the produced box list.
children: Option<Vec<N>>,
}
#[derive(Clone, Debug)]
pub(crate) struct ConstructionInputs<N> {
root: N,
root_is_document_element: bool,
quirks_mode: style::context::QuirksMode,
sources: Vec<SourceInput<N>>,
reused_boxes: usize,
reused_owned_boxes: usize,
}
impl<N> ConstructionInputs<N>
where
N: Copy + Debug + Eq + Hash,
{
pub(super) fn new<S: LayoutSource<NodeId = N>>(source: &S) -> Self {
Self {
root: source.root(),
root_is_document_element: source.root_is_document_element(),
quirks_mode: source.quirks_mode(),
sources: Vec::new(),
reused_boxes: 0,
reused_owned_boxes: 0,
}
}
pub(crate) fn reused_boxes(&self) -> usize {
self.reused_boxes
}
pub(crate) fn reused_owned_boxes(&self) -> usize {
self.reused_owned_boxes
}
pub(super) fn record_element<S: LayoutSource<NodeId = N>>(
&mut self,
source: &S,
node: N,
semantics: &LayoutElementSemantics,
style: Option<&ResolvedLayoutStyle>,
before: bool,
after: bool,
) -> bool {
let Some(shape) = ElementShape::from_inputs(semantics, style, before, after) else {
return false;
};
self.sources.push(SourceInput {
node,
parent: source.flat_parent(node),
kind: SourceInputKind::Element {
semantics: semantics.clone(),
shape,
},
children: None,
});
true
}
pub(super) fn record_text<S: LayoutSource<NodeId = N>>(
&mut self,
source: &S,
node: N,
text: Option<&Arc<str>>,
) {
self.sources.push(SourceInput {
node,
parent: source.flat_parent(node),
kind: SourceInputKind::Text(text.cloned()),
children: None,
});
}
pub(super) fn record_ignored<S: LayoutSource<NodeId = N>>(
&mut self,
source: &S,
node: N,
kind: LayoutSourceKind,
) {
self.sources.push(SourceInput {
node,
parent: source.flat_parent(node),
kind: SourceInputKind::Ignored(kind),
children: None,
});
}
pub(super) fn record_children(&mut self, parent: N, children: &[N]) {
// Eligible nodes have no pseudos, so the element whose child stream
// is about to be traversed is still the last recorded source.
let input = self.sources.last_mut().expect("parent source was recorded");
assert_eq!(input.node, parent);
input.children = Some(children.to_vec());
}
pub(super) fn supports_graph(&self, world: &LayoutWorld<N>) -> bool {
// A mixture of blocks and meaningful text can require wrappers even
// when every element has an eligible principal style. Only the actual
// shared builder's final graph decides whether this pass is admitted.
world.display_contents_mapping.is_empty()
&& world.boxes.iter().enumerate().all(|(index, layout_box)| {
layout_box.source.is_some()
&& layout_box.owner.is_none()
&& layout_box.pseudo.is_none()
&& layout_box.anonymous_reason.is_none()
&& !layout_box.outside_list_marker
&& matches!(
layout_box.kind,
LayoutBoxKind::PrincipalBlock
| LayoutBoxKind::PrincipalFlowRoot
| LayoutBoxKind::PrincipalGrid
| LayoutBoxKind::TableWrapper
| LayoutBoxKind::InlineTableWrapper
| LayoutBoxKind::TableCaption
| LayoutBoxKind::TableRowGroup
| LayoutBoxKind::TableHeaderGroup
| LayoutBoxKind::TableFooterGroup
| LayoutBoxKind::TableRow
| LayoutBoxKind::TableCell
| LayoutBoxKind::TableColumnGroup
| LayoutBoxKind::TableColumn
| LayoutBoxKind::Text
)
&& layout_box.structural_parent == layout_box.parent
&& layout_box
.parent
.is_none_or(|parent| parent.index() < index)
})
// Styles are restored in produced principal-box order. Table
// column groups may discard otherwise eligible element subtrees;
// those frontiers must not leave unmatched style records here.
&& self.sources.iter().filter_map(|input| match &input.kind {
SourceInputKind::Element { shape: ElementShape::Principal { .. }, .. } => Some(input.node),
_ => None,
}).eq(world.boxes.iter().filter(|layout_box| layout_box.kind != LayoutBoxKind::Text).map(|layout_box| layout_box.source.expect("supported graph has sources")))
}
/// Charge visible allocations by capacity. Shared source text and
/// semantics are conservatively charged here as well as at graph owners;
/// no computed-style or font payload is retained by these records.
pub(crate) fn estimated_retained_bytes(&self) -> usize {
fn allocation<T>(values: &Vec<T>) -> usize {
values.capacity().saturating_mul(std::mem::size_of::<T>())
}
let mut bytes = std::mem::size_of::<Self>().saturating_add(allocation(&self.sources));
for input in &self.sources {
if let Some(children) = &input.children {
bytes = bytes.saturating_add(allocation(children));
}
match &input.kind {
SourceInputKind::Element { semantics, .. } => {
bytes = bytes.saturating_add(semantics.local_name.len());
if let LayoutNamespace::Other(namespace) = &semantics.namespace {
bytes = bytes.saturating_add(namespace.len());
}
if let Some(control) = &semantics.metadata.form_control {
bytes = bytes
.saturating_add(control.value.len())
.saturating_add(control.placeholder.len())
.saturating_add(allocation(&control.option_labels));
bytes = control
.option_labels
.iter()
.fold(bytes, |bytes, label| bytes.saturating_add(label.len()));
}
}
SourceInputKind::Text(text) => {
bytes = bytes.saturating_add(text.as_deref().map_or(0, str::len));
}
SourceInputKind::Ignored(_) => {}
}
}
bytes
}
#[cfg(test)]
pub(crate) fn reserve_source_capacity_for_test(&mut self, additional: usize) {
self.sources.reserve(additional);
}
}
pub(super) fn try_restore<S, R>(
source: &S,
styles: &mut R,
previous: &mut RetainedWork<S::NodeId>,
) -> Result<Option<LayoutWorld<S::NodeId>>, LayoutError>
where
S: LayoutSource,
R: LayoutStyleResolver<S::NodeId>,
{
let Some(inputs) = previous.construction_inputs() else {
return Ok(None);
};
let started = moli_trace::cpu_profile_enabled().then(Instant::now);
if source.root() != inputs.root
|| source.root_is_document_element() != inputs.root_is_document_element
|| source.quirks_mode() != inputs.quirks_mode
|| previous.root() != LayoutBoxId::from_index(0)
|| previous.root_is_document_element() != inputs.root_is_document_element
|| previous.quirks_mode() != inputs.quirks_mode
{
return Ok(None);
}
let mut builder = BoxBuilder::new(source, styles);
builder.source_root = Some(inputs.root);
builder.root_is_html = inputs.sources.first().is_some_and(|input| {
matches!(&input.kind, SourceInputKind::Element { semantics, .. } if semantics.is_html_element("html"))
});
let principal_count = inputs
.sources
.iter()
.filter(|input| {
matches!(
input.kind,
SourceInputKind::Element {
shape: ElementShape::Principal { .. },
..
}
)
})
.count();
// The eligible graph is allocated in source preorder and compaction
// preserves that order. Keep the current styles in the same sequence,
// avoiding a hash table that repeatedly moves these large owned values.
let mut current_styles = Vec::with_capacity(principal_count);
for input in &inputs.sources {
if source.node_kind(input.node) != input.kind.node_kind()
|| source.flat_parent(input.node) != input.parent
{
return Ok(None);
}
match &input.kind {
SourceInputKind::Element { semantics, shape } => {
if source.element_semantics(input.node).as_ref() != Some(semantics)
|| (semantics.replaced.is_none()
&& source.replaced_metrics(input.node).is_some())
{
return Ok(None);
}
let (style, before, after) = match builder.styles.element_styles(input.node)? {
Some(styles) => {
let (style, before, after) = styles.into_parts();
(Some(style), before.is_some(), after.is_some())
}
None => (None, false, false),
};
if let Some(style) = style.as_ref() {
builder.note_viewport_body_candidate(input.node, semantics, style);
}
if ElementShape::from_inputs(semantics, style.as_ref(), before, after).as_ref()
!= Some(shape)
{
return Ok(None);
}
if matches!(shape, ElementShape::Principal { .. }) {
current_styles.push((
input.node,
style.expect("a principal source has a current style"),
));
}
}
SourceInputKind::Text(text) => {
if source.element_semantics(input.node).is_some()
|| source.replaced_metrics(input.node).is_some()
|| source.text(input.node) != text.as_deref()
{
return Ok(None);
}
}
SourceInputKind::Ignored(_) => {
if source.element_semantics(input.node).is_some()
|| source.replaced_metrics(input.node).is_some()
{
return Ok(None);
}
}
}
if let Some(children) = &input.children
&& !source
.flat_children(input.node)
.eq(children.iter().copied())
{
return Ok(None);
}
}
let validation_finished = started.map(|_| Instant::now());
let checked_source_count = inputs.sources.len();
let mut current_styles = current_styles.into_iter();
// Compute compatibility against the old input residence before changing
// even one retained style. All fresh styles remain owned for calc safety.
if previous.owned_construction().is_some() {
let mut fresh_styles: Vec<ResolvedLayoutStyle> = Vec::with_capacity(previous.box_count());
let mut selections = Vec::with_capacity(previous.box_count());
let mut unchanged = Vec::with_capacity(previous.box_count());
for old in previous.construction_boxes() {
let node = old
.source
.expect("owned construction requires source boxes");
let style = if old.kind == LayoutBoxKind::Text {
let parent = old.parent.expect("a retained text source has a parent");
ResolvedLayoutStyle::text_leaf_from(&fresh_styles[parent.index()])
} else {
let (styled_node, style) =
current_styles.next().expect("validated principal style");
assert_eq!(styled_node, node, "retained principal order changed");
style
};
let selection = if old.kind == LayoutBoxKind::Text {
source.text_selection(node)
} else {
None
};
unchanged.push(crate::working_set::same_inline_style_input(
&old, &style, selection,
));
fresh_styles.push(style);
selections.push(selection);
}
// The shape is still the existing graph. This temporary world moves
// the original allocations and creates only fresh pass bookkeeping.
let mut world = previous
.take_owned_construction()
.expect("owned graph was validated");
let unchanged = crate::working_set::propagate_inline_changes(&world, unchanged);
previous.prepare_owned_inline_inputs(unchanged);
for ((layout_box, style), selection) in
world.boxes.iter_mut().zip(fresh_styles).zip(selections)
{
let node = layout_box.source.expect("owned source box");
layout_box.source_label.clone_from(&source.label(node));
LayoutWorld::refresh_box_style(layout_box, style);
if layout_box.kind == LayoutBoxKind::Text {
layout_box.text_selection = selection;
} else {
builder.refresh_principal_inputs(layout_box, None);
}
}
builder.finalize_viewport_scroll_policy(&mut world);
world.css_image_references = builder.css_image_references;
world.validate_invariants()?;
let mut current_inputs = previous
.take_construction_inputs()
.expect("validated construction inputs");
current_inputs.reused_boxes = world.len();
current_inputs.reused_owned_boxes = world.len();
world.construction_inputs = Some(current_inputs);
if let (Some(started), Some(validated)) = (started, validation_finished) {
tracing::info!(target: "moli_cpu_profile", stage = "layout_construction_reuse",
source_validation_us = validated.duration_since(started).as_micros(),
graph_restore_us = validated.elapsed().as_micros(), checked_source_count,
reused_construction_boxes = world.len(), reused_owned_boxes = world.len());
}
return Ok(Some(world));
}
// Every source dependency and every structural decision has now matched.
// Restore the already normalized graph and freshly sample box inputs with
// the same helpers used by BoxBuilder. Width/paint changes may replace a
// ComputedValues owner without requiring a new construction graph.
let mut world: Option<LayoutWorld<S::NodeId>> = None;
for (index, old) in previous.construction_boxes().enumerate() {
let node = old.source.expect("retained construction requires a source");
let mut layout_box = if old.kind == LayoutBoxKind::Text {
let parent = old.parent.expect("a retained text source has a parent");
let inherited_style = &world
.as_ref()
.expect("the root precedes its text descendants")
.boxes[parent.index()]
.style;
builder.text_box(
node,
inherited_style,
old.text.cloned().expect("a retained text box owns text"),
)
} else {
let (styled_node, style) = current_styles
.next()
.expect("all principal source styles were validated");
assert_eq!(styled_node, node, "retained principal source order changed");
builder.principal_box(
node,
source.label(node),
old.element_semantics
.expect("a retained principal box has element semantics")
.clone(),
old.kind,
style,
// Eligible principals are non-replaced and the validation
// above already sampled and checked this exact current input.
None,
)
};
layout_box.structural_parent = old.structural_parent;
layout_box.parent = old.parent;
layout_box.children = old.children.to_vec();
layout_box.inline_formatting_context = old.inline_formatting_context;
if let Some(world) = &mut world {
let id = world.allocate(layout_box);
assert_eq!(id.index(), index);
world.map_source(node, id);
} else {
let mut root = LayoutWorld::new(layout_box, inputs.root_is_document_element);
root.reserve_box_capacity(previous.box_capacity_hint());
root.quirks_mode = inputs.quirks_mode;
root.map_source(node, root.root());
world = Some(root);
}
}
let mut world = world.expect("a retained construction graph has a root");
builder.finalize_viewport_scroll_policy(&mut world);
world.css_image_references = builder.css_image_references;
world.validate_invariants()?;
let mut current_inputs = previous
.take_construction_inputs()
.expect("a restored construction graph has validated inputs");
current_inputs.reused_boxes = world.len();
current_inputs.reused_owned_boxes = 0;
world.construction_inputs = Some(current_inputs);
if let (Some(started), Some(validated)) = (started, validation_finished) {
tracing::info!(
target: "moli_cpu_profile",
stage = "layout_construction_reuse",
source_validation_us = validated.duration_since(started).as_micros(),
graph_restore_us = validated.elapsed().as_micros(),
checked_source_count,
reused_construction_boxes = world.len(),
reused_owned_boxes = 0,
);
}
Ok(Some(world))
}
+182 -5
View File
@@ -2,8 +2,9 @@
//
// The one-Parley-tree-per-IFC shape follows DioxusLabs/blitz commit
// d788124ab881f9bb537cb452ec1d837604a374a8, especially
// `layout/construct.rs::build_inline_layout_into`. Moli deliberately
// keeps the item stream, source mapping, and Parley layout pass-local.
// `layout/construct.rs::build_inline_layout_into`. The default pipeline keeps
// the item stream, source mapping, and Parley layout pass-local. An optional
// working set retains owned preparation and validated local numeric results.
// Relative positioning of atomic inline boxes additionally follows Blitz
// commit 4a9be930accc971675d5730e4fde3cfa13c3b57e.
@@ -31,6 +32,9 @@ use crate::{
text::{DocumentLayoutServices, InlineFontMetrics},
};
mod numeric_reuse;
pub(crate) use numeric_reuse::{InlineMeasurementInputs, InlineNumericInputs, InlineNumericReuse};
/// Resolve the relative inset applied after Parley has positioned an atomic
/// inline box. Taffy cannot do this itself because atomic IFC children are
/// represented as Parley inline objects and their final locations are written
@@ -479,6 +483,154 @@ struct InlineBoxBlockPlacement {
}
impl InlineFormattingContext {
/// Validate all retained construction IDs before transferring an IFC into
/// a different graph. Parley styles/objects use local indices into these
/// maps; none may silently name an unrelated fresh construction slot.
pub(crate) fn references_only(&self, mut contains: impl FnMut(LayoutBoxId) -> bool) -> bool {
contains(self.root_style)
&& self.text_units.iter().all(|unit| {
contains(unit.style_box)
&& unit.ancestors.iter().copied().all(&mut contains)
&& unit.sources.iter().all(|source| contains(source.box_id))
})
&& self.source_map.iter().all(|source| contains(source.box_id))
&& self.objects.iter().all(|object| {
contains(object.box_id) && object.ancestors.iter().copied().all(&mut contains)
})
&& self.style_parents.iter().copied().all(&mut contains)
&& self
.structural_boxes
.iter()
.all(|state| contains(state.box_id) && contains(state.parent))
&& self
.fragments
.text
.iter()
.all(|fragment| contains(fragment.box_id))
&& self
.fragments
.boxes
.iter()
.all(|fragment| contains(fragment.box_id))
&& self.line_placements.iter().all(|placement| {
placement
.box_block_placements
.iter()
.all(|state| contains(state.box_id))
})
}
/// Retain one paragraph and its source mapping. A validated final numeric
/// entry can also keep its accepted lines and local fragments; all other
/// IFCs retain preparation alone.
pub(crate) fn prepare_for_retention(&mut self, preserve_numeric: bool) {
if preserve_numeric && self.laid_out.is_some() {
// Intrinsic probes clone lazily when required. Do not retain both
// that scratch paragraph and the accepted final output by default.
self.measurement_layout = None;
return;
}
// PerformLayout may have moved the only shaped paragraph into the
// accepted output. Transfer it back before retiring line placement;
// the next measurement replaces its lines for the new constraints.
if self.measurement_layout.is_none() {
self.measurement_layout = self.laid_out.take();
} else {
self.laid_out = None;
}
self.line_placements = Vec::new();
self.fragments = InlineFragments::default();
}
/// Our own final-output vectors, excluding the IFC struct and Parley
/// paragraphs already charged by `estimated_retained_preparation_bytes`.
pub(crate) fn estimated_retained_numeric_bytes(&self) -> usize {
fn allocation<T>(values: &Vec<T>) -> usize {
values.capacity().saturating_mul(std::mem::size_of::<T>())
}
self.line_placements.iter().fold(
allocation(&self.line_placements)
.saturating_add(allocation(&self.fragments.lines))
.saturating_add(allocation(&self.fragments.text))
.saturating_add(allocation(&self.fragments.boxes)),
|bytes, placement| {
bytes
.saturating_add(allocation(&placement.item_offsets))
.saturating_add(allocation(&placement.glyph_offsets))
.saturating_add(allocation(&placement.box_block_placements))
},
)
}
/// Admission charge, excluding the inline struct and shared font payloads.
///
/// Our own vectors use their capacities. Parley's public API does not
/// expose capacities for shaped runs, characters, clusters, glyphs, or
/// line-breaking buffers. Those use a text-length model instead; this is
/// not a measured byte count or a proven upper bound. Do not walk glyphs
/// or lines merely to account for a warm paragraph on every frame.
pub(crate) fn estimated_retained_preparation_bytes(&self) -> usize {
fn allocation<T>(values: &Vec<T>) -> usize {
values.capacity().saturating_mul(std::mem::size_of::<T>())
}
let mut bytes = self
.text
.capacity()
.saturating_add(allocation(&self.text_units))
.saturating_add(allocation(&self.source_map))
.saturating_add(allocation(&self.objects))
.saturating_add(allocation(&self.font_metrics))
.saturating_add(allocation(&self.style_parents))
.saturating_add(allocation(&self.structural_boxes));
for unit in &self.text_units {
bytes = bytes
.saturating_add(allocation(&unit.ancestors))
.saturating_add(allocation(&unit.sources));
}
for object in &self.objects {
bytes = bytes.saturating_add(allocation(&object.ancestors));
}
for layout in [&self.measurement_layout, &self.laid_out]
.into_iter()
.flatten()
{
// This admission weight includes opaque shaping arrays and line
// capacity. Multiple glyphs per character and dependency changes
// can defeat this estimate; precise accounting needs a Parley API.
const PARLEY_BYTES_PER_TEXT_BYTE: usize = 128;
const PARLEY_BYTES_PER_STYLE: usize = 256;
const PARLEY_BYTES_PER_INLINE_BOX: usize = 128;
bytes = bytes
.saturating_add(layout.text_len().saturating_mul(PARLEY_BYTES_PER_TEXT_BYTE))
.saturating_add(layout.styles().len().saturating_mul(PARLEY_BYTES_PER_STYLE))
.saturating_add(
layout
.inline_boxes()
.len()
.saturating_mul(PARLEY_BYTES_PER_INLINE_BOX),
);
// Brushes share their shadow arrays. Charging each reference is
// conservative, avoids an allocation for a deduplication index,
// and captures large authored arrays independently of text length.
for style in layout.styles() {
for brush in std::iter::once(&style.brush)
.chain(style.underline.as_ref().map(|decoration| &decoration.brush))
.chain(
style
.strikethrough
.as_ref()
.map(|decoration| &decoration.brush),
)
{
bytes = bytes.saturating_add(brush.shadows.len().saturating_mul(
std::mem::size_of::<crate::stylo_to_parley::TextShadowBrush>(),
));
}
}
}
bytes
}
pub(crate) fn object(&self, id: u64) -> Option<&InlineObject> {
usize::try_from(id)
.ok()
@@ -2011,14 +2163,37 @@ pub(crate) fn prepare_inline_contexts<N>(
services: &mut DocumentLayoutServices,
) where
N: Copy + Debug + Eq + Hash,
{
prepare_inline_contexts_with_retained_inputs(world, services, false);
}
pub(crate) fn prepare_inline_contexts_with_retained_inputs<N>(
world: &mut LayoutWorld<N>,
services: &mut DocumentLayoutServices,
retain_prepared: bool,
) -> usize
where
N: Copy + Debug + Eq + Hash,
{
let profile_started = moli_trace::cpu_profile_enabled().then(std::time::Instant::now);
let mut collection_elapsed = std::time::Duration::ZERO;
let mut preparation_elapsed = std::time::Duration::ZERO;
let mut prepared_context_count = 0usize;
let mut text_unit_count = 0usize;
for layout_box in &mut world.boxes {
layout_box.inline_layout = None;
let mut reused_context_count = 0usize;
world.prepare_inline_storage();
for (index, layout_box) in world.boxes.iter_mut().enumerate() {
if retain_prepared {
if let Some(context) = world.inline_layouts[index].as_mut() {
let preserve_numeric = world
.inline_numeric_reuse
.as_ref()
.is_some_and(|reuse| reuse.contains(LayoutBoxId::from_index(index)));
context.prepare_for_retention(preserve_numeric);
}
} else {
world.inline_layouts[index] = None;
}
layout_box.inline_context_owner = None;
layout_box.inline_flattened = false;
layout_box.inline_static_position = None;
@@ -2054,7 +2229,7 @@ pub(crate) fn prepare_inline_contexts<N>(
preparation_elapsed += started.elapsed();
prepared_context_count += 1;
}
world.boxes[owner.index()].inline_layout = Some(context);
world.inline_layouts[owner.index()] = Some(context);
initialized = true;
}
if initialized {
@@ -2069,9 +2244,11 @@ pub(crate) fn prepare_inline_contexts<N>(
collection_us = collection_elapsed.as_micros(),
preparation_us = preparation_elapsed.as_micros(),
prepared_context_count,
reused_context_count,
text_unit_count,
);
}
reused_context_count
}
struct InlineBuildInput {
+328
View File
@@ -0,0 +1,328 @@
//! Final and size-only IFC results for an optional, document-owned working set.
//!
//! The accepted Parley layout and local fragments stay on their existing IFC
//! owner. This sidecar validates final numeric inputs and separately retains
//! bounded complete measurements under their exact constraints. It is
//! restored together with an unchanged IFC after construction/font validation;
//! ordinary one-shot worlds never allocate its per-owner index or entries.
use style::Atom;
use taffy::{
AvailableSpace, CompactLength, LayoutInput, LayoutOutput, Rect, ResolvedAspectRatio, RunMode,
Style, WritingMode,
};
use crate::{LayoutBoxId, LayoutDisplay, style::InlineDirection};
mod measurement;
pub(crate) use measurement::InlineMeasurementInputs;
use measurement::InlineMeasurements;
/// Inputs outside the shaped paragraph and its exact computed-style owner.
/// Preserve Taffy's input dependencies, including percentage bases, purpose
/// and requested axis. Only proven-unused raw width constraints are normalized
/// in the comparison copy. The parent classification changes fit-content
/// behavior even when the child's own physical constraints have not changed.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct InlineNumericInputs {
pub(crate) layout: LayoutInput,
pub(crate) writing_mode: WritingMode,
pub(crate) resolved_aspect_ratio: Option<ResolvedAspectRatio>,
pub(crate) scrollbar_insets: Rect<f32>,
pub(crate) display: LayoutDisplay,
pub(crate) alignment: parley::Alignment,
pub(crate) direction: InlineDirection,
pub(crate) parent_is_flex_or_grid: bool,
}
impl InlineNumericInputs {
fn comparison_key(mut self, style: &Style<Atom>) -> Self {
fn finite_nonnegative(value: f32) -> bool {
value.is_finite() && value >= 0.0
}
fn absolute(value: CompactLength) -> bool {
value.tag() == CompactLength::LENGTH_TAG && value.value().is_finite()
}
fn absolute_or_auto(value: CompactLength) -> bool {
value.tag() == CompactLength::AUTO_TAG || absolute(value)
}
if self.layout.run_mode != RunMode::PerformLayout
|| self.writing_mode != WritingMode::HorizontalTb
|| self.layout.parent_writing_mode != WritingMode::HorizontalTb
|| !self
.layout
.known_dimensions
.width
.is_some_and(finite_nonnegative)
|| !self
.layout
.parent_size
.width
.is_some_and(finite_nonnegative)
|| !matches!(self.layout.available_space.width, AvailableSpace::Definite(width) if finite_nonnegative(width))
|| ![
style.size.width.into_raw(),
style.size.height.into_raw(),
style.min_size.width.into_raw(),
style.min_size.height.into_raw(),
style.max_size.width.into_raw(),
style.max_size.height.into_raw(),
style.margin.left.into_raw(),
style.margin.right.into_raw(),
style.margin.top.into_raw(),
style.margin.bottom.into_raw(),
]
.into_iter()
.all(absolute_or_auto)
|| ![
style.padding.left.into_raw(),
style.padding.right.into_raw(),
style.padding.top.into_raw(),
style.padding.bottom.into_raw(),
style.border.left.into_raw(),
style.border.right.into_raw(),
style.border.top.into_raw(),
style.border.bottom.into_raw(),
]
.into_iter()
.all(absolute)
{
return self;
}
// Taffy 645bf5a, compute/leaf.rs::resolve_available_axis, applies
// resolve_used_axis(known_width, ...) before maybe_set overrides the
// raw available width. With only absolute/auto size and edge values,
// the raw parent width cannot change that resolved content width or
// the final box. Moli's pure-text measurement uses the content width;
// known_width also disables its shrink-to-fit branch. This allows an
// unchanged fixed-width IFC to survive the auto-scrollbar feedback
// pass without reproducing any of the shared sizing calculations.
//
// Normalize only this comparison copy; layout receives the original
// inputs. Keep definite sentinels, so an unknown input that fails the
// checks above cannot collide with a normalized key. All other input
// fields and the full actual numeric style remain part of the key.
self.layout.parent_size.width = Some(0.0);
self.layout.available_space.width = AvailableSpace::Definite(0.0);
self
}
}
#[derive(Debug)]
struct InlineNumericEntry {
owner: LayoutBoxId,
inputs: InlineNumericInputs,
// Compare the actual numeric projection at the call boundary, including
// temporary adapter overrides. Retained construction inputs keep the
// computed owner alive for any calc pointers held by this projection.
style: Style<Atom>,
output: LayoutOutput,
restored: bool,
}
#[derive(Debug)]
pub(crate) struct InlineNumericReuse {
// Keep entries dense: most boxes are not eligible IFC owners. The small
// index exists only when the caller opted into a retained working set.
entries: Vec<InlineNumericEntry>,
owner_slots: Vec<Option<usize>>,
retained_hits: usize,
measurements: Option<Box<InlineMeasurements>>,
}
impl InlineNumericReuse {
pub(crate) fn new(box_count: usize) -> Self {
Self {
entries: Vec::new(),
owner_slots: vec![None; box_count],
retained_hits: 0,
measurements: None,
}
}
pub(crate) fn contains(&self, owner: LayoutBoxId) -> bool {
self.owner_slots
.get(owner.index())
.is_some_and(Option::is_some)
|| self
.measurements
.as_ref()
.is_some_and(|cache| cache.contains(owner))
}
pub(crate) fn retain_owners(&mut self, keep: impl FnMut(LayoutBoxId) -> bool) {
self.retain_owners_for_box_count(self.owner_slots.len(), keep);
}
/// Reindex unchanged owners in a freshly constructed graph without
/// remapping any ID. New slots start empty; removed owners cannot return
/// if the graph later grows. Retained capacity remains admission-charged.
pub(crate) fn retain_owners_for_box_count(
&mut self,
box_count: usize,
mut keep: impl FnMut(LayoutBoxId) -> bool,
) {
self.entries
.retain(|entry| entry.owner.index() < box_count && keep(entry.owner));
self.owner_slots.clear();
self.owner_slots.resize(box_count, None);
for (slot, entry) in self.entries.iter().enumerate() {
self.owner_slots[entry.owner.index()] = Some(slot);
}
if let Some(cache) = &mut self.measurements {
cache.retain_owners(box_count, keep);
}
}
/// Begin a new pass after the caller has validated the surviving owners.
/// Newly computed entries in this pass remain distinct from restored ones.
pub(crate) fn reset_hits(&mut self) {
self.retained_hits = 0;
for entry in &mut self.entries {
entry.restored = true;
}
if let Some(cache) = &mut self.measurements {
cache.reset_hits();
}
}
/// Number of final computations skipped using validated prior-pass data.
/// This counts calls, not distinct owners; local newly computed hits do
/// not contribute to evidence of cross-pass reuse.
pub(crate) fn hits(&self) -> usize {
self.retained_hits
}
pub(crate) fn measurement_hits(&self) -> usize {
self.measurements.as_ref().map_or(0, |cache| cache.hits())
}
pub(crate) fn lookup_measurement(
&mut self,
owner: LayoutBoxId,
inputs: InlineMeasurementInputs,
style: &Style<Atom>,
) -> Option<LayoutOutput> {
self.measurements.as_mut()?.lookup(owner, inputs, style)
}
pub(crate) fn store_measurement(
&mut self,
owner: LayoutBoxId,
inputs: InlineMeasurementInputs,
style: Style<Atom>,
output: LayoutOutput,
) {
let box_count = self.owner_slots.len();
self.measurements
.get_or_insert_with(|| Box::new(InlineMeasurements::new(box_count)))
.store(owner, inputs, style, output);
}
pub(crate) fn lookup(
&mut self,
owner: LayoutBoxId,
inputs: InlineNumericInputs,
style: &Style<Atom>,
) -> Option<LayoutOutput> {
let slot = self.owner_slots.get(owner.index()).copied().flatten()?;
let entry = &self.entries[slot];
if entry.inputs != inputs.comparison_key(style) || entry.style != *style {
return None;
}
if entry.restored {
self.retained_hits = self.retained_hits.saturating_add(1);
}
Some(entry.output.clone())
}
pub(crate) fn remove(&mut self, owner: LayoutBoxId) {
let Some(slot) = self
.owner_slots
.get_mut(owner.index())
.and_then(Option::take)
else {
return;
};
self.entries.swap_remove(slot);
if let Some(moved) = self.entries.get(slot) {
self.owner_slots[moved.owner.index()] = Some(slot);
}
}
pub(crate) fn store(
&mut self,
owner: LayoutBoxId,
inputs: InlineNumericInputs,
style: Style<Atom>,
output: LayoutOutput,
) {
self.remove(owner);
// Numeric placeholders have no IFC input owner and must never enter
// the persistent construction graph's index.
assert!(owner.index() < self.owner_slots.len());
self.owner_slots[owner.index()] = Some(self.entries.len());
let inputs = inputs.comparison_key(&style);
self.entries.push(InlineNumericEntry {
owner,
inputs,
style,
output,
restored: false,
});
}
/// Owned sidecar buffers; shared Atom and computed-style payloads follow
/// the working set's existing exclusion from estimated admission charge.
pub(crate) fn estimated_retained_bytes(&self) -> usize {
self.entries
.iter()
.fold(
std::mem::size_of::<Self>()
.saturating_add(allocation(&self.entries))
.saturating_add(allocation(&self.owner_slots)),
|bytes, entry| bytes.saturating_add(style_allocation(&entry.style)),
)
.saturating_add(
self.measurements
.as_ref()
.map_or(0, |cache| cache.estimated_retained_bytes()),
)
}
}
fn allocation<T>(values: &Vec<T>) -> usize {
values.capacity().saturating_mul(std::mem::size_of::<T>())
}
fn style_allocation(style: &Style<Atom>) -> usize {
fn line_names(names: &Vec<Vec<Atom>>) -> usize {
names.iter().fold(allocation(names), |bytes, line| {
bytes.saturating_add(allocation(line))
})
}
fn template(tracks: &Vec<taffy::GridTemplateComponent<Atom>>) -> usize {
tracks.iter().fold(allocation(tracks), |bytes, track| {
let extra = match track {
taffy::GridTemplateComponent::Single(_) => 0,
taffy::GridTemplateComponent::Repeat(repetition) => allocation(&repetition.tracks)
.saturating_add(line_names(&repetition.line_names)),
};
bytes.saturating_add(extra)
})
}
template(&style.grid_template_rows)
.saturating_add(template(&style.grid_template_columns))
.saturating_add(allocation(&style.grid_auto_rows))
.saturating_add(allocation(&style.grid_auto_columns))
.saturating_add(line_names(&style.grid_template_row_names))
.saturating_add(line_names(&style.grid_template_column_names))
.saturating_add(
style
.grid_template_areas
.as_ref()
.map_or(0, |areas| allocation(&areas.areas)),
)
}
@@ -0,0 +1,239 @@
//! Bounded size-only results; accepted line layouts remain on their IFC owner.
use style::Atom;
use taffy::{LayoutOutput, RunMode, Style};
use super::{InlineNumericInputs, allocation, style_allocation};
use crate::LayoutBoxId;
// Each owner can be probed under several intrinsic/definite constraints. Keep
// a small LRU rather than replacing its accepted final-layout result.
// Match Blink's per-object complete-measure LRU; this is not a document quota.
const CAPACITY: usize = 8;
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct InlineMeasurementInputs {
pub(crate) numeric: InlineNumericInputs,
// Full table measurements request baselines even when both dimensions
// are known; ordinary size probes may use Taffy's size-only shortcut.
pub(crate) measure_baselines: bool,
}
#[derive(Debug)]
struct ResultEntry {
inputs: InlineMeasurementInputs,
style: Style<Atom>,
output: LayoutOutput,
restored: bool,
}
#[derive(Debug)]
struct OwnerEntry {
owner: LayoutBoxId,
results: Vec<ResultEntry>,
}
#[derive(Debug)]
pub(super) struct InlineMeasurements {
owners: Vec<OwnerEntry>,
slots: Vec<Option<usize>>,
retained_hits: usize,
}
impl InlineMeasurements {
pub(super) fn new(box_count: usize) -> Self {
Self {
owners: Vec::new(),
slots: vec![None; box_count],
retained_hits: 0,
}
}
pub(super) fn contains(&self, owner: LayoutBoxId) -> bool {
self.slots.get(owner.index()).is_some_and(Option::is_some)
}
pub(super) fn retain_owners(
&mut self,
box_count: usize,
mut keep: impl FnMut(LayoutBoxId) -> bool,
) {
self.owners
.retain(|entry| entry.owner.index() < box_count && keep(entry.owner));
self.slots.clear();
self.slots.resize(box_count, None);
for (slot, entry) in self.owners.iter().enumerate() {
self.slots[entry.owner.index()] = Some(slot);
}
}
pub(super) fn reset_hits(&mut self) {
self.retained_hits = 0;
for owner in &mut self.owners {
for result in &mut owner.results {
result.restored = true;
}
}
}
pub(super) fn hits(&self) -> usize {
self.retained_hits
}
pub(super) fn lookup(
&mut self,
owner: LayoutBoxId,
inputs: InlineMeasurementInputs,
style: &Style<Atom>,
) -> Option<LayoutOutput> {
let slot = self.slots.get(owner.index()).copied().flatten()?;
let results = &mut self.owners[slot].results;
let index = results
.iter()
.position(|result| result.inputs == inputs && result.style == *style)?;
let result = results.remove(index);
let output = result.output.clone();
if result.restored {
self.retained_hits = self.retained_hits.saturating_add(1);
}
results.push(result);
Some(output)
}
pub(super) fn store(
&mut self,
owner: LayoutBoxId,
inputs: InlineMeasurementInputs,
style: Style<Atom>,
output: LayoutOutput,
) {
assert_eq!(inputs.numeric.layout.run_mode, RunMode::ComputeSize);
assert!(owner.index() < self.slots.len());
let slot = *self.slots[owner.index()].get_or_insert_with(|| {
let slot = self.owners.len();
self.owners.push(OwnerEntry {
owner,
results: Vec::new(),
});
slot
});
let results = &mut self.owners[slot].results;
if let Some(index) = results
.iter()
.position(|result| result.inputs == inputs && result.style == style)
{
results.remove(index);
} else if results.len() == CAPACITY {
results.remove(0);
}
results.push(ResultEntry {
inputs,
style,
output,
restored: false,
});
}
pub(super) fn estimated_retained_bytes(&self) -> usize {
self.owners.iter().fold(
std::mem::size_of::<Self>()
.saturating_add(allocation(&self.owners))
.saturating_add(allocation(&self.slots)),
|bytes, owner| {
owner.results.iter().fold(
bytes.saturating_add(allocation(&owner.results)),
|bytes, result| bytes.saturating_add(style_allocation(&result.style)),
)
},
)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{LayoutDisplay, style::InlineDirection};
use taffy::{AvailableSpace, Rect, Size, WritingMode};
fn inputs(width: f32) -> InlineMeasurementInputs {
InlineMeasurementInputs {
numeric: InlineNumericInputs {
layout: taffy::LayoutInput {
run_mode: RunMode::ComputeSize,
available_space: Size {
width: AvailableSpace::Definite(width),
height: AvailableSpace::MaxContent,
},
..taffy::LayoutInput::HIDDEN
},
writing_mode: WritingMode::HorizontalTb,
resolved_aspect_ratio: None,
scrollbar_insets: Rect::zero(),
display: LayoutDisplay::Block,
alignment: parley::Alignment::Start,
direction: InlineDirection::Ltr,
parent_is_flex_or_grid: false,
},
measure_baselines: true,
}
}
#[test]
fn inline_measurements_bound_results_and_distinguish_retained_hits() {
let owner = LayoutBoxId::from_index(0);
let style = Style::default();
let mut cache = InlineMeasurements::new(1);
for width in 0..CAPACITY {
cache.store(
owner,
inputs(width as f32),
style.clone(),
LayoutOutput::HIDDEN,
);
}
assert!(cache.lookup(owner, inputs(0.0), &style).is_some());
assert_eq!(cache.hits(), 0);
cache.reset_hits();
assert!(cache.lookup(owner, inputs(0.0), &style).is_some());
assert_eq!(cache.hits(), 1);
cache.store(owner, inputs(100.0), style.clone(), LayoutOutput::DEFAULT);
assert_eq!(
cache.lookup(owner, inputs(100.0), &style),
Some(LayoutOutput::DEFAULT)
);
assert_eq!(cache.hits(), 1, "new results are not previous-pass hits");
assert!(cache.lookup(owner, inputs(1.0), &style).is_none());
assert!(cache.lookup(owner, inputs(0.0), &style).is_some());
for width in 100..140 {
cache.store(
owner,
inputs(width as f32),
style.clone(),
LayoutOutput::HIDDEN,
);
assert_eq!(cache.owners[0].results.len(), CAPACITY);
}
}
#[test]
fn inline_measurement_owner_retirement_releases_keys_and_never_revives_them() {
let mut cache = InlineMeasurements::new(3);
let owner = LayoutBoxId::from_index(2);
let style = Style {
grid_template_row_names: vec![Vec::with_capacity(1024)],
..Style::default()
};
cache.store(owner, inputs(100.0), style, LayoutOutput::DEFAULT);
let charged = cache.estimated_retained_bytes();
cache.retain_owners(1, |_| true);
assert!(!cache.contains(owner));
assert!(cache.owners.is_empty());
assert!(cache.estimated_retained_bytes() < charged);
cache.retain_owners(3, |_| true);
assert!(
cache
.lookup(owner, inputs(100.0), &Style::default())
.is_none()
);
}
}
+11 -5
View File
@@ -1,9 +1,12 @@
//! One-shot CSS box construction, numeric layout, and owned paint projection.
//! Shared CSS box construction, numeric layout, and owned paint projection.
//!
//! The crate knows Stylo and Taffy but never knows Moli's live DOM or V8
//! runtime. Renderer-owned adapters lend a canonical source view and resolve
//! styles; all source/style borrows and per-pass caches are gone before the
//! returned [`FrozenLayoutTree`] or [`PaintSnapshot`] crosses into a consumer.
//! styles; source/resolver borrows never escape a pass. The default pipeline
//! releases its working state, while an explicit [`LayoutWorkingSet`] can keep
//! validated construction inputs, text preparation and eligible final inline
//! results across passes. Published
//! [`FrozenLayoutTree`] and [`PaintSnapshot`] values remain independent.
/// Number of fixed layout subpixels in one CSS pixel, matching Blink's
/// `LayoutUnit` precision.
@@ -41,6 +44,7 @@ mod table_role;
mod taffy_tree;
mod text;
mod text_normalization;
mod working_set;
mod world;
pub use anonymous_style::LayoutAnonymousStyleContext;
@@ -74,8 +78,9 @@ pub use normalize_source::{
pub use pass::{
EmbeddedFrameRenderer, EmbeddedFrameSnapshot, LayoutFrameCoverage, LayoutPassRequest,
PreparedLayoutPass, ScreenshotLayoutRequest, build_layout_pass,
build_layout_pass_with_embedded_frames, build_screenshot_snapshot, finish_prepared_layout_pass,
prepare_layout_pass,
build_layout_pass_with_embedded_frames, build_layout_pass_with_working_set,
build_screenshot_snapshot, finish_prepared_layout_pass, prepare_layout_pass,
prepare_layout_pass_with_working_set,
};
pub use scrollbar::{
LayoutControlSurfaceHit, LayoutScrollbarAxis, LayoutScrollbarColors, LayoutScrollbarCornerHit,
@@ -113,6 +118,7 @@ pub use text::{
WebFontRegistration, WebFontRegistrationError, WebFontRegistrationOutcome,
WebFontRegistrationScope, WebFontStyle, WebFontUnicodeRange, validate_web_font_bytes,
};
pub use working_set::{LayoutWorkingSet, LayoutWorkingSetStats};
pub use world::{
LayoutAnonymousReason, LayoutBox, LayoutBoxId, LayoutBoxKind, LayoutCapabilityDiagnostic,
LayoutWorld,
+1 -1
View File
@@ -446,7 +446,7 @@ where
);
local_overflow = LayoutRect::new(left, top, right - left, bottom - top);
}
if let Some(context) = layout_box.inline_layout.as_ref() {
if let Some(context) = world.inline_layouts[id.index()].as_ref() {
let origin = LayoutPoint::new(
layout.border.left
+ layout.padding.left
+12 -6
View File
@@ -186,16 +186,20 @@ where
PaintOrderEvent::BoxContents(id)
| PaintOrderEvent::InlineContents(id)
| PaintOrderEvent::BoxText(id) => box_contents_bounds(projection, id),
PaintOrderEvent::BoxCaret(id) => caret_rect(&projection.world.boxes[id.index()])
.map_or(PaintCullBounds::Empty, |rect| {
map_box_rect(projection, id, rect)
}),
PaintOrderEvent::BoxCaret(id) => caret_rect(
&projection.world.boxes[id.index()],
projection.world.inline_layouts[id.index()].as_ref(),
)
.map_or(PaintCullBounds::Empty, |rect| {
map_box_rect(projection, id, rect)
}),
PaintOrderEvent::InlineSelection {
owner, start, end, ..
} => {
let mut bounds = PaintCullBounds::Empty;
range_selection_rects(
&projection.world.boxes[owner.index()],
projection.world.inline_layouts[owner.index()].as_ref(),
Some(&(start..end)),
|rect| {
bounds.include(map_box_rect(projection, owner, rect));
@@ -209,7 +213,9 @@ where
}
PaintOrderEvent::InlineText { owner, line, .. } => {
let layout_box = &projection.world.boxes[owner.index()];
let context = layout_box.inline_layout.as_ref().unwrap();
let context = projection.world.inline_layouts[owner.index()]
.as_ref()
.unwrap();
match context.fragments.lines[line].paint_bounds {
InlinePaintBounds::Empty => PaintCullBounds::Empty,
InlinePaintBounds::Unbounded => PaintCullBounds::Unbounded,
@@ -261,7 +267,7 @@ where
return PaintCullBounds::Empty;
}
let mut local = projection.boxes[id.index()].border_box;
if let Some(context) = layout_box.inline_layout.as_ref() {
if let Some(context) = projection.world.inline_layouts[id.index()].as_ref() {
let layout = layout_box.final_layout;
let origin = LayoutPoint::new(
layout.border.left + layout.padding.left,
+4 -3
View File
@@ -16,12 +16,12 @@ use super::{
geometry::{BoxAreas, inset_radii},
text::TextClipMaskScope,
};
use crate::{LayoutBox, LayoutRect, LayoutWorld, PaintEdgeSizes, PaintFragment, PaintSnapshot};
use crate::{LayoutBoxId, LayoutRect, LayoutWorld, PaintEdgeSizes, PaintFragment, PaintSnapshot};
#[allow(clippy::too_many_arguments)]
pub(super) fn project_inline_box_fragments<N>(
world: &LayoutWorld<N>,
owner: &LayoutBox<N>,
owner_id: LayoutBoxId,
selected_fragment: Option<usize>,
paint_space: PaintSpace,
include_backgrounds: bool,
@@ -31,9 +31,10 @@ pub(super) fn project_inline_box_fragments<N>(
) where
N: Copy + Debug + Eq + Hash,
{
let Some(context) = owner.inline_layout.as_ref() else {
let Some(context) = world.inline_layouts[owner_id.index()].as_ref() else {
return;
};
let owner = &world.boxes[owner_id.index()];
let owner_layout = owner.final_layout;
let origin_x = owner_layout.border.left + owner_layout.padding.left;
let origin_y = owner_layout.border.top + owner_layout.padding.top;
+15 -3
View File
@@ -458,6 +458,7 @@ where
};
project_selection(
&projection.world.boxes[id.index()],
projection.world.inline_layouts[id.index()].as_ref(),
space
.paint_space(snapshot.viewport_to_surface)
.local_transform(),
@@ -507,7 +508,9 @@ where
.local_transform();
let text = inline_text.entry(owner).or_insert_with(|| {
InlineTextPaint::new(
layout_box.inline_layout.as_ref().unwrap(),
projection.world.inline_layouts[owner.index()]
.as_ref()
.unwrap(),
snapshot.retain_text_semantics,
)
});
@@ -940,7 +943,15 @@ fn project_box_text_clip_mask<N>(
let local_cull = cull.local_rect(viewport_transform);
let transform = snapshot.viewport_to_surface.concatenate(viewport_transform);
let clip_count = push_clip_chain(projection, projection.content_clips[id.index()], snapshot);
project_text_clip_mask(layout_box, transform, local_cull, metrics, snapshot, scope);
project_text_clip_mask(
layout_box,
projection.world.inline_layouts[id.index()].as_ref(),
transform,
local_cull,
metrics,
snapshot,
scope,
);
pop_clips(clip_count, snapshot);
}
@@ -1065,7 +1076,7 @@ fn project_inline_contents<N>(
};
project_inline_box_fragments(
projection.world,
layout_box,
id,
selected_fragment,
paint_space,
include_backgrounds,
@@ -1097,6 +1108,7 @@ fn project_box_text<N>(
.local_transform();
project_text(
layout_box,
projection.world.inline_layouts[id.index()].as_ref(),
transform,
cull.local_rect(viewport_transform),
metrics,
+33 -13
View File
@@ -44,6 +44,7 @@ pub(super) enum TextClipMaskScope {
/// resulting rectangles cross the owned snapshot boundary.
pub(super) fn project_text<N>(
layout_box: &LayoutBox<N>,
context: Option<&InlineFormattingContext>,
transform: LayoutTransform2D,
local_cull: Option<LayoutRect>,
metrics: &mut PaintProjectionMetrics,
@@ -51,6 +52,7 @@ pub(super) fn project_text<N>(
) {
project_text_phase(
layout_box,
context,
transform,
local_cull,
metrics,
@@ -68,6 +70,7 @@ pub(super) fn project_text<N>(
/// is consumed by a `DestIn` layer, so only alpha is observable.
pub(super) fn project_text_clip_mask<N>(
layout_box: &LayoutBox<N>,
context: Option<&InlineFormattingContext>,
transform: LayoutTransform2D,
local_cull: Option<LayoutRect>,
metrics: &mut PaintProjectionMetrics,
@@ -76,6 +79,7 @@ pub(super) fn project_text_clip_mask<N>(
) {
project_text_phase(
layout_box,
context,
transform,
local_cull,
metrics,
@@ -87,6 +91,7 @@ pub(super) fn project_text_clip_mask<N>(
fn project_text_phase<N>(
layout_box: &LayoutBox<N>,
context: Option<&InlineFormattingContext>,
transform: LayoutTransform2D,
local_cull: Option<LayoutRect>,
metrics: &mut PaintProjectionMetrics,
@@ -94,7 +99,7 @@ fn project_text_phase<N>(
phase: TextPaintPhase,
mask_scope: Option<TextClipMaskScope>,
) {
let Some(context) = layout_box.inline_layout.as_ref() else {
let Some(context) = context else {
return;
};
let Some(text_layout) = context.laid_out.as_ref() else {
@@ -105,7 +110,14 @@ fn project_text_phase<N>(
let origin_y = layout.border.top + layout.padding.top;
if phase == TextPaintPhase::Foreground {
project_selection(layout_box, transform, local_cull, snapshot, None);
project_selection(
layout_box,
Some(context),
transform,
local_cull,
snapshot,
None,
);
}
let text: Option<std::sync::Arc<str>> = (snapshot.retain_text_semantics
@@ -419,7 +431,14 @@ impl<'a> InlineTextPaint<'a> {
.cloned()
.reduce(|range, cluster| range.start.min(cluster.start)..range.end.max(cluster.end))
{
project_selection(layout_box, transform, local_cull, snapshot, Some(&range));
project_selection(
layout_box,
Some(context),
transform,
local_cull,
snapshot,
Some(&range),
);
}
let paint = TextRunPaint {
origin_x,
@@ -447,21 +466,18 @@ impl<'a> InlineTextPaint<'a> {
pub(super) fn project_selection<N>(
layout_box: &LayoutBox<N>,
context: Option<&InlineFormattingContext>,
transform: LayoutTransform2D,
local_cull: Option<LayoutRect>,
snapshot: &mut PaintSnapshot,
text_range: Option<&std::ops::Range<usize>>,
) {
let Some(selection) = layout_box
.inline_layout
.as_ref()
.and_then(|context| context.selection.as_ref())
else {
let Some(selection) = context.and_then(|context| context.selection.as_ref()) else {
return;
};
match selection {
InlineSelection::Range(_) => {
range_selection_rects(layout_box, text_range, |rect| {
range_selection_rects(layout_box, context, text_range, |rect| {
if local_cull.is_none_or(|cull| rects_intersect(rect, cull)) {
snapshot.push_fragment(PaintFragment::Fill {
fill_rule: crate::PaintFillRule::NonZero,
@@ -473,7 +489,7 @@ pub(super) fn project_selection<N>(
});
}
InlineSelection::Caret { color, .. } => {
let Some(rect) = caret_rect(layout_box) else {
let Some(rect) = caret_rect(layout_box, context) else {
return;
};
if local_cull.is_none_or(|cull| rects_intersect(rect, cull)) {
@@ -491,13 +507,14 @@ pub(super) fn project_selection<N>(
/// One range geometry path for normal text, glyphless fragments, and culling.
pub(super) fn range_selection_rects<N>(
layout_box: &LayoutBox<N>,
context: Option<&InlineFormattingContext>,
text_range: Option<&std::ops::Range<usize>>,
mut emit: impl FnMut(LayoutRect),
) {
if !layout_box.style.is_visible() {
return;
}
let Some(context) = layout_box.inline_layout.as_ref() else {
let Some(context) = context else {
return;
};
let Some(text_layout) = context.laid_out.as_ref() else {
@@ -534,11 +551,14 @@ pub(super) fn range_selection_rects<N>(
/// Use the same caret ink for event culling and painting, independently of
/// glyph runs and the containing box's border bounds.
pub(super) fn caret_rect<N>(layout_box: &LayoutBox<N>) -> Option<LayoutRect> {
pub(super) fn caret_rect<N>(
layout_box: &LayoutBox<N>,
context: Option<&InlineFormattingContext>,
) -> Option<LayoutRect> {
if !layout_box.style.is_visible() {
return None;
}
let context = layout_box.inline_layout.as_ref()?;
let context = context?;
let text_layout = context.laid_out.as_ref()?;
let InlineSelection::Caret { offset, color } = context.selection.as_ref()? else {
return None;
+100 -15
View File
@@ -234,22 +234,39 @@ where
R: LayoutStyleResolver<S::NodeId>,
F: EmbeddedFrameRenderer<S::NodeId>,
{
finish_prepared_layout_pass(
prepare_layout_pass(source, styles, request)?,
source,
services,
frames,
)
build_layout_pass_with_working_set(source, styles, services, request, frames, None)
}
/// Runs the shared pipeline with optional document-owned computation state.
/// A failed pass retires its working state; publication of the frozen result
/// remains the caller's separate responsibility.
pub fn build_layout_pass_with_working_set<S, R, F>(
source: &S,
styles: &mut R,
services: &mut DocumentLayoutServices,
request: LayoutPassRequest,
frames: &mut F,
working_set: Option<&mut crate::LayoutWorkingSet<S::NodeId>>,
) -> Result<LayoutPassResult<S::NodeId>, LayoutError>
where
S: LayoutSource,
R: LayoutStyleResolver<S::NodeId>,
F: EmbeddedFrameRenderer<S::NodeId>,
{
let prepared = prepare_layout_pass_with_working_set(source, styles, request, working_set)?;
finish_prepared_layout_pass(prepared, source, services, frames)
}
/// Owned box construction and control preparation for one layout demand.
/// The style resolver can be released before shaping, geometry, and child
/// document layout consume this value.
pub struct PreparedLayoutPass<N>
pub struct PreparedLayoutPass<'working, N>
where
N: Copy + std::fmt::Debug + Eq + std::hash::Hash,
{
world: LayoutWorld<N>,
working_set: Option<&'working mut crate::LayoutWorkingSet<N>>,
previous: Option<crate::working_set::RetainedWork<N>>,
request: LayoutPassRequest,
started: Instant,
box_tree_elapsed: Duration,
@@ -257,18 +274,38 @@ where
form_control_elapsed: Duration,
}
pub fn prepare_layout_pass<S, R>(
pub fn prepare_layout_pass<'working, S, R>(
source: &S,
styles: &mut R,
request: LayoutPassRequest,
) -> Result<PreparedLayoutPass<S::NodeId>, LayoutError>
) -> Result<PreparedLayoutPass<'working, S::NodeId>, LayoutError>
where
S: LayoutSource,
R: LayoutStyleResolver<S::NodeId>,
{
prepare_layout_pass_with_working_set(source, styles, request, None)
}
pub fn prepare_layout_pass_with_working_set<'working, S, R>(
source: &S,
styles: &mut R,
request: LayoutPassRequest,
mut working_set: Option<&'working mut crate::LayoutWorkingSet<S::NodeId>>,
) -> Result<PreparedLayoutPass<'working, S::NodeId>, LayoutError>
where
S: LayoutSource,
R: LayoutStyleResolver<S::NodeId>,
{
let started = Instant::now();
// Take before any fallible work so an error cannot leave reusable state
// associated with inputs whose construction or projection failed.
let mut previous = working_set.as_deref_mut().and_then(|set| set.take());
let phase_started = Instant::now();
let mut world = build_layout_world(source, styles)?;
let mut world = if working_set.is_some() {
crate::builder::build_layout_world_with_retained_inputs(source, styles, previous.as_mut())?
} else {
build_layout_world(source, styles)?
};
world.environment = request.environment;
let box_tree_elapsed = phase_started.elapsed();
debug_assert!(
@@ -286,6 +323,8 @@ where
let form_control_elapsed = phase_started.elapsed();
Ok(PreparedLayoutPass {
world,
working_set,
previous,
request,
started,
box_tree_elapsed,
@@ -295,7 +334,7 @@ where
}
pub fn finish_prepared_layout_pass<S, F>(
prepared: PreparedLayoutPass<S::NodeId>,
prepared: PreparedLayoutPass<'_, S::NodeId>,
source: &S,
services: &mut DocumentLayoutServices,
frames: &mut F,
@@ -305,17 +344,41 @@ where
F: EmbeddedFrameRenderer<S::NodeId>,
{
let PreparedLayoutPass {
mut world,
world,
working_set,
previous,
request,
started,
box_tree_elapsed,
list_marker_elapsed,
form_control_elapsed,
} = prepared;
let font_inputs = working_set.as_ref().map(|_| services.font_inputs());
let (mut world, reused_box_slots) = if let Some(fonts) = font_inputs.as_ref() {
crate::working_set::update_working_tree(previous, world, fonts)
} else {
(world, 0)
};
if working_set.is_some() && world.inline_numeric_reuse.is_none() {
// Reuse validated metadata when input matching restored it. Allocate
// only for a cold working set; one-shot passes retain the old path.
world.inline_numeric_reuse = Some(Box::new(crate::inline::InlineNumericReuse::new(
world.len(),
)));
}
let phase_started = Instant::now();
prepare_inline_contexts(&mut world, services);
let reused_inline_contexts = if working_set.is_some() {
crate::inline::prepare_inline_contexts_with_retained_inputs(&mut world, services, true)
} else {
prepare_inline_contexts(&mut world, services);
0
};
let inline_preparation_elapsed = phase_started.elapsed();
world.validate_invariants()?;
// Numeric layout may append static-position placeholders. Their IDs and
// results are pass-local; only the normalized construction graph is a
// candidate for the next pass's input comparison.
let construction_box_count = world.len();
let phase_started = Instant::now();
let numeric_metrics = compute_world_layout_with_scrollbars(&mut world, request.viewport);
let object_geometry = prepare_svg_content(&mut world, source);
@@ -360,7 +423,7 @@ where
}
}
let embedded_frame_elapsed = phase_started.elapsed();
finish_layout_pass(
let mut result = finish_layout_pass(
&world,
source,
request.viewport,
@@ -386,7 +449,29 @@ where
numeric_feedback_overflow_recomputed_node_count: numeric_metrics
.feedback_overflow_recomputed_node_count,
},
)
)?;
if let (Some(working_set), Some(fonts)) = (working_set, font_inputs) {
let retention_started = moli_trace::cpu_profile_enabled().then(Instant::now);
working_set.publish(
world,
fonts,
reused_box_slots,
reused_inline_contexts,
construction_box_count,
);
// Admission and releasing the pass-only output are part of the cost
// of this retained pass, not invisible work after its elapsed metric.
result.metrics.elapsed = started.elapsed();
if let Some(retention_started) = retention_started {
tracing::info!(
target: "moli_cpu_profile",
stage = "layout_working_set",
retention_us = retention_started.elapsed().as_micros(),
stats = ?working_set.stats(),
);
}
}
Ok(result)
}
fn prepare_svg_content<S: LayoutSource>(
+2 -5
View File
@@ -663,7 +663,7 @@ where
self.register_box_fragment(index, fragment);
}
let Some(context) = layout_box.inline_layout.as_ref() else {
let Some(context) = self.world.inline_layouts[index].as_ref() else {
continue;
};
let layout = layout_box.final_layout;
@@ -790,10 +790,7 @@ where
// Index the shaped line and its hit fragments once. Repeated
// runs must not scan the paragraph or all its text nodes.
let lines = text_owners.entry(owner).or_insert_with(|| {
let context = self.world.boxes[owner.index()]
.inline_layout
.as_ref()
.unwrap();
let context = self.world.inline_layouts[owner.index()].as_ref().unwrap();
let layout = context.laid_out.as_ref().unwrap();
let mut lines = layout
.lines()
+5 -7
View File
@@ -110,8 +110,8 @@ impl InlineOrder {
entries: vec![Vec::new(); world.boxes.len()],
atomic_lines: vec![None; world.boxes.len()],
};
for (owner_index, layout_box) in world.boxes.iter().enumerate() {
let Some(context) = &layout_box.inline_layout else {
for (owner_index, context) in world.inline_layouts.iter().enumerate() {
let Some(context) = context else {
continue;
};
if !context
@@ -460,7 +460,7 @@ fn collect_contents<N>(
tree_order,
));
}
if layout_box.inline_layout.is_some() && !inline.split[id.index()] {
if world.inline_layouts[id.index()].is_some() && !inline.split[id.index()] {
let mut entry = PaintEntry::event(PaintOrderEvent::InlineContents(id), tree_order);
entry.order.3 = 1;
flow.inline_contents.push(entry);
@@ -469,8 +469,7 @@ fn collect_contents<N>(
flow.inline_contents.push(text);
}
if inline.split[id.index()]
&& layout_box
.inline_layout
&& world.inline_layouts[id.index()]
.as_ref()
.is_some_and(|context| matches!(context.selection, Some(InlineSelection::Caret { .. })))
{
@@ -485,8 +484,7 @@ fn collect_contents<N>(
let (owner, line, item) = match *event {
PaintOrderEvent::InlineBox { owner, fragment } => (
owner,
world.boxes[owner.index()]
.inline_layout
world.inline_layouts[owner.index()]
.as_ref()
.unwrap()
.fragments
+13
View File
@@ -582,6 +582,19 @@ impl std::fmt::Debug for ResolvedLayoutStyle {
}
impl ResolvedLayoutStyle {
/// Keep only the owned computed-style residence and scalar inline inputs
/// needed to validate retained preparation. Numeric/grid/generated-content
/// allocations are pass-local; the next pass installs a fresh full style.
pub(crate) fn prepare_for_construction_retention(&mut self) {
let float = self.taffy.float;
self.taffy = Style {
float,
..Style::default()
};
self.generated_content = GeneratedContent::None;
self.list_marker_type = LayoutListMarkerType::None;
}
/// Converts one retained Stylo style while preserving its allocation for
/// the full lifetime of the pass-local Taffy projection.
pub fn from_stylo(computed: ServoArc<ComputedValues>) -> Self {
+1 -1
View File
@@ -625,7 +625,7 @@ where
world.boxes[child.index()].unrounded_layout.location.y += offset;
}
}
if let Some(context) = &mut world.boxes[cell.index()].inline_layout {
if let Some(context) = &mut world.inline_layouts[cell.index()] {
for line in &mut context.line_placements {
line.translate_block_axis(offset);
}
+303 -13
View File
@@ -19,9 +19,10 @@ use crate::{
LayoutWorld, PaintRect, PaintViewport,
inline::{
InlineContentWidthsMemo, InlineEdgeContribution, InlineFormattingContext, InlineFragments,
InlineLinePlacement, InlineObjectRole, break_inline_lines, build_inline_fragments,
build_inline_line_placements, measure_inline_lines, position_inline_edges,
relative_atomic_inset_offset, reset_inline_layout_for_probe,
InlineLinePlacement, InlineMeasurementInputs, InlineNumericInputs, InlineObjectRole,
break_inline_lines, build_inline_fragments, build_inline_line_placements,
measure_inline_lines, position_inline_edges, relative_atomic_inset_offset,
reset_inline_layout_for_probe,
},
positioned::{
FlexCrossAxisStaticContext, HorizontalStaticEdge, PhysicalStaticPosition,
@@ -138,6 +139,7 @@ pub(crate) fn prepare_world_layout<N>(
where
N: Copy + Debug + Eq + Hash,
{
world.prepare_inline_storage();
world.resolved_grid_tracks.clear();
world.native_grid_details.clear();
for index in 0..world.boxes.len() {
@@ -694,13 +696,11 @@ where
+ gap
}
};
let item_baseline = world.boxes[item.index()]
.inline_layout
let item_baseline = world.inline_layouts[item.index()]
.as_ref()
.and_then(|context| context.line_placements.first())
.map(|line| item_layout.border.top + item_layout.padding.top + line.baseline);
let marker_baseline = world.boxes[marker.index()]
.inline_layout
let marker_baseline = world.inline_layouts[marker.index()]
.as_ref()
.and_then(|context| context.line_placements.first())
.map(|line| line.baseline)
@@ -1158,7 +1158,7 @@ fn inline_box_containing_rect<N>(
where
N: Copy + Debug + Eq + Hash,
{
let context = world.boxes[owner.index()].inline_layout.as_ref()?;
let context = world.inline_layouts[owner.index()].as_ref()?;
context
.fragments
.boxes
@@ -2162,6 +2162,67 @@ where
let writing_mode = self.boxes[id.index()].style.writing_mode();
let resolved_aspect_ratio = self.boxes[id.index()].resolved_aspect_ratio();
let is_floated = box_is_effectively_floated(self, id);
let alignment = self.boxes[id.index()].style.text_align();
let final_layout_requested = inputs.run_mode == RunMode::PerformLayout;
let numeric_inputs = (self.inline_numeric_reuse.is_some()
&& self
.table_cell_percentage_height
.is_none_or(|(cell, _)| cell != id)
&& !self.boxes[id.index()].kind.is_internal_table_box()
&& !is_floated
&& !block_context
.as_ref()
.is_some_and(|context| context.has_floats())
&& self.inline_layouts[id.index()]
.as_ref()
.is_some_and(|context| context.objects.is_empty()))
.then(|| InlineNumericInputs {
layout: inputs,
writing_mode,
resolved_aspect_ratio,
scrollbar_insets,
display: self.boxes[id.index()].style.display(),
alignment,
direction: self.boxes[id.index()].style.direction(),
parent_is_flex_or_grid: self.boxes[id.index()].layout_parent.is_some_and(|parent| {
let display = self.boxes[parent.index()].style.display();
display.is_flex_container() || display.is_grid_container()
}),
});
let measurement_inputs = numeric_inputs
.filter(|_| inputs.run_mode == RunMode::ComputeSize)
.map(|numeric| InlineMeasurementInputs {
numeric,
measure_baselines: self.measure_baselines,
});
if let Some(measurement_inputs) = measurement_inputs
&& let Some(reuse) = self.inline_numeric_reuse.as_mut()
&& let Some(output) = reuse.lookup_measurement(id, measurement_inputs, &style)
{
// Size-only pure-text probes neither position children nor publish
// accepted lines. Keep every constraint/purpose and baseline mode
// exact, independently of the owner's final-layout key.
return output;
}
let final_numeric_inputs = numeric_inputs.filter(|_| !self.measure_baselines);
if final_layout_requested && let Some(reuse) = self.inline_numeric_reuse.as_mut() {
let has_accepted_output = self.inline_layouts[id.index()]
.as_ref()
.is_some_and(|context| context.laid_out.is_some());
if let Some(numeric_inputs) = final_numeric_inputs
&& has_accepted_output
&& let Some(output) = reuse.lookup(id, numeric_inputs, &style)
{
// Pure-text results contain only local geometry. With no
// floats, the normal algorithm neither reads BFC offsets
// nor mutates its float state. The parent still positions
// this box and projection uses the current frame/scroll.
return output;
}
// The following calculation can replace accepted lines. Its
// old key must not survive an ineligible or changed request.
reuse.remove(id);
}
// The 0.15 leaf contract takes space after margins. Both the native
// block parent and the IFC float parent already supply that space.
let leaf_inputs = inputs;
@@ -2176,12 +2237,9 @@ where
} else {
leaf_inputs
};
let alignment = self.boxes[id.index()].style.text_align();
let mut inline_context = self.boxes[id.index()]
.inline_layout
let mut inline_context = self.inline_layouts[id.index()]
.take()
.unwrap_or_else(empty_inline_context);
let final_layout_requested = inputs.run_mode == RunMode::PerformLayout;
// Reuse one mutable Parley paragraph throughout the ordinary
// intrinsic -> final sequence. A later intrinsic probe clones lazily
// from the accepted result, and only if Taffy actually invokes the
@@ -2325,7 +2383,21 @@ where
}
inline_context.content_widths = content_widths;
self.boxes[id.index()].inline_layout = Some(inline_context);
if let Some(reuse) = self.inline_numeric_reuse.as_mut() {
if let Some(measurement_inputs) = measurement_inputs
&& measurement_was_produced
{
// A known-size shortcut does no text work. Storing it would
// allocate and charge a cache to avoid a few scalar operations.
reuse.store_measurement(id, measurement_inputs, style, output.clone());
} else if final_layout_requested
&& measurement_was_produced
&& let Some(numeric_inputs) = final_numeric_inputs
{
reuse.store(id, numeric_inputs, style, output.clone());
}
}
self.inline_layouts[id.index()] = Some(inline_context);
output
}
@@ -3250,6 +3322,9 @@ impl<N: Copy + Debug + Eq + Hash> taffy::LayoutContainingBlock for LayoutWorld<N
fn add_hoisted_children(&mut self, _: NodeId, _: &[NodeId]) {}
}
#[cfg(test)]
mod measurement_tests;
#[cfg(test)]
mod tests {
use super::{inline_percentage_basis, round_layout_to_css_subpixels};
@@ -3380,6 +3455,221 @@ mod tests {
);
}
#[test]
fn retained_inline_numeric_output_survives_intrinsic_probes() {
fn text_world() -> LayoutWorld<u8> {
let text = "alpha beta gamma delta epsilon zeta eta theta";
let mut fonts = parley::FontContext::new();
let mut layouts = parley::LayoutContext::<crate::stylo_to_parley::TextBrush>::new();
let mut builder = layouts.style_run_builder(&mut fonts, text, 1.0, true);
let style = builder.push_style(parley::TextStyle::default());
builder.push_style_run(style, ..);
let mut inline = super::empty_inline_context();
inline.measurement_layout = Some(builder.build(text));
let mut world = LayoutWorld::new(synthetic_block_box(0, Style::default()), false);
world.boxes[0].style = ResolvedLayoutStyle::from_stylo(
style::properties::ComputedValues::initial_values_with_font_override(
style::properties::style_structs::Font::initial_values(),
),
);
world.boxes[0]
.style
.force_layout_display(LayoutDisplay::Block);
world.prepare_inline_storage();
world.inline_layouts[0] = Some(inline);
world.inline_numeric_reuse = Some(Box::new(crate::inline::InlineNumericReuse::new(1)));
world
}
fn output_signature(
world: &LayoutWorld<u8>,
) -> (
usize,
f32,
f32,
Vec<crate::inline::InlineLinePlacement>,
Vec<crate::inline::InlineLineFragment>,
) {
let inline = world.inline_layouts[0].as_ref().unwrap();
let accepted = inline.laid_out.as_ref().unwrap();
(
accepted.len(),
accepted.width(),
accepted.height(),
inline.line_placements.clone(),
inline.fragments.lines.clone(),
)
}
let mut world = text_world();
let owner = world.root();
let inputs = LayoutInput {
run_mode: RunMode::PerformLayout,
sizing_mode: SizingMode::InherentSize,
sizing_purpose: SizingPurpose::Layout,
axis: RequestedAxis::Both,
block_auto_behavior: AutoSizeBehavior::FitContent,
known_dimensions: Size {
width: Some(60.0),
height: None,
},
known_dimensions_are_definite: Size {
width: true,
height: true,
},
parent_size: Size {
width: Some(240.0),
height: None,
},
parent_writing_mode: WritingMode::HorizontalTb,
available_space: Size {
width: AvailableSpace::Definite(60.0),
height: AvailableSpace::MaxContent,
},
vertical_margins_are_collapsible: Line::FALSE,
};
let first = world.compute_inline_formatting_context(owner, inputs, None);
let accepted = output_signature(&world);
assert!(
!accepted.4.is_empty(),
"the accepted result must contain actual lines"
);
assert_eq!(world.inline_numeric_reuse.as_ref().unwrap().hits(), 0);
world.inline_layouts[0]
.as_mut()
.unwrap()
.prepare_for_retention(true);
world.inline_numeric_reuse.as_mut().unwrap().reset_hits();
let probe = LayoutInput {
run_mode: RunMode::ComputeSize,
sizing_purpose: SizingPurpose::IntrinsicContribution,
known_dimensions: Size::NONE,
known_dimensions_are_definite: Size {
width: false,
height: false,
},
available_space: Size {
width: AvailableSpace::MaxContent,
height: AvailableSpace::MaxContent,
},
..inputs
};
world.compute_inline_formatting_context(owner, probe, None);
assert_eq!(output_signature(&world), accepted);
assert!(
world.inline_layouts[0]
.as_ref()
.unwrap()
.measurement_layout
.is_some()
);
assert_eq!(world.inline_numeric_reuse.as_ref().unwrap().hits(), 0);
let warm = world.compute_inline_formatting_context(owner, inputs, None);
assert_eq!(warm, first);
assert_eq!(output_signature(&world), accepted);
assert_eq!(world.inline_numeric_reuse.as_ref().unwrap().hits(), 1);
// A different final width must replace the key and accepted paragraph,
// even though the preceding intrinsic probe left scratch lines behind.
let changed = LayoutInput {
known_dimensions: Size {
width: Some(180.0),
height: None,
},
available_space: Size {
width: AvailableSpace::Definite(180.0),
height: AvailableSpace::MaxContent,
},
..inputs
};
let updated = world.compute_inline_formatting_context(owner, changed, None);
let mut cold = text_world();
let cold_output = cold.compute_inline_formatting_context(owner, changed, None);
assert_eq!(updated, cold_output);
assert_eq!(output_signature(&world), output_signature(&cold));
assert_eq!(updated.size.width, 180.0);
assert_eq!(world.inline_numeric_reuse.as_ref().unwrap().hits(), 1);
// Numeric adapters can override the projected style without replacing
// its computed owner. Keep the exact same LayoutInput and paragraph;
// the style key must still reject the previously accepted result.
let computed = world.boxes[0]
.style
.stylo_computed_values()
.unwrap()
.clone();
world.inline_numeric_reuse.as_mut().unwrap().reset_hits();
let numeric_style = &mut world.boxes[0].style.taffy;
numeric_style.size.height = Dimension::length(150.0);
numeric_style.padding.top = taffy::LengthPercentage::length(7.0);
numeric_style.padding.bottom = taffy::LengthPercentage::length(11.0);
numeric_style.padding.left = taffy::LengthPercentage::length(13.0);
numeric_style.align_content = taffy::AlignContent::END;
assert!(style::servo_arc::Arc::ptr_eq(
&computed,
world.boxes[0].style.stylo_computed_values().unwrap(),
));
let overridden = world.compute_inline_formatting_context(owner, changed, None);
assert_ne!(overridden, updated);
assert_eq!(world.inline_numeric_reuse.as_ref().unwrap().hits(), 0);
let mut cold_override = text_world();
cold_override.inline_numeric_reuse = None;
cold_override.boxes[0].style = world.boxes[0].style.clone();
let cold_overridden = cold_override.compute_inline_formatting_context(owner, changed, None);
assert_eq!(overridden, cold_overridden);
assert_eq!(output_signature(&world), output_signature(&cold_override));
// A scrollbar feedback pass changes the parent's raw width budget.
// The same known width with absolute/auto sizing still produces the
// same content constraints, so retain the accepted final paragraph.
let mut fixed = text_world();
let raw_narrow = LayoutInput {
parent_size: Size {
width: Some(240.0),
..changed.parent_size
},
available_space: Size {
width: AvailableSpace::Definite(240.0),
..changed.available_space
},
..changed
};
let fixed_output = fixed.compute_inline_formatting_context(owner, raw_narrow, None);
let fixed_signature = output_signature(&fixed);
assert_eq!(fixed_output.size.width, 180.0);
fixed.inline_layouts[0]
.as_mut()
.unwrap()
.prepare_for_retention(true);
fixed.inline_numeric_reuse.as_mut().unwrap().reset_hits();
// Only these two raw widths change; known/definite dimensions and
// the actual numeric style remain the same for both computations.
let raw_wide = LayoutInput {
parent_size: Size {
width: Some(320.0),
..raw_narrow.parent_size
},
available_space: Size {
width: AvailableSpace::Definite(320.0),
..raw_narrow.available_space
},
..raw_narrow
};
let reused = fixed.compute_inline_formatting_context(owner, raw_wide, None);
assert_eq!(fixed.inline_numeric_reuse.as_ref().unwrap().hits(), 1);
assert_eq!(reused, fixed_output);
assert_eq!(output_signature(&fixed), fixed_signature);
let mut cold_fixed = text_world();
cold_fixed.inline_numeric_reuse = None;
let cold_recomputed = cold_fixed.compute_inline_formatting_context(owner, raw_wide, None);
assert_eq!(reused, cold_recomputed);
assert_eq!(output_signature(&fixed), output_signature(&cold_fixed));
}
#[test]
fn repeated_block_measurement_preserves_collapsible_margin_sets() {
let mut child_style = Style::default();
@@ -0,0 +1,311 @@
use super::*;
use crate::ResolvedLayoutStyle;
use taffy::WritingMode;
fn text_world(retained: bool) -> LayoutWorld<u8> {
let text = "alpha beta gamma delta epsilon zeta eta theta";
let mut fonts = parley::FontContext::new();
let mut layouts = parley::LayoutContext::<crate::stylo_to_parley::TextBrush>::new();
let mut builder = layouts.style_run_builder(&mut fonts, text, 1.0, true);
let style = builder.push_style(parley::TextStyle::default());
builder.push_style_run(style, ..);
let mut inline = empty_inline_context();
inline.text = text.to_owned();
inline.measurement_layout = Some(builder.build(text));
let mut style = ResolvedLayoutStyle::from_stylo(
style::properties::ComputedValues::initial_values_with_font_override(
style::properties::style_structs::Font::initial_values(),
),
);
style.force_layout_display(crate::LayoutDisplay::Block);
let layout_box = LayoutWorld::new_box(
Some(0),
None,
None,
"text".to_owned(),
None,
None,
None,
LayoutBoxKind::PrincipalBlock,
style,
None,
);
let mut world = LayoutWorld::new(layout_box, false);
world.prepare_inline_storage();
world.inline_layouts[0] = Some(inline);
if retained {
world.inline_numeric_reuse = Some(Box::new(crate::inline::InlineNumericReuse::new(1)));
}
world
}
fn inputs() -> LayoutInput {
LayoutInput {
run_mode: RunMode::ComputeSize,
sizing_mode: SizingMode::InherentSize,
sizing_purpose: SizingPurpose::Layout,
axis: taffy::RequestedAxis::Both,
known_dimensions: Size {
width: Some(60.0),
height: Some(20.0),
},
known_dimensions_are_definite: Size {
width: true,
height: true,
},
parent_size: Size {
width: Some(240.0),
height: None,
},
parent_writing_mode: WritingMode::HorizontalTb,
available_space: Size {
width: AvailableSpace::Definite(60.0),
height: AvailableSpace::MaxContent,
},
block_auto_behavior: AutoSizeBehavior::FitContent,
vertical_margins_are_collapsible: taffy::Line::FALSE,
}
}
fn measure(world: &mut LayoutWorld<u8>, inputs: LayoutInput, baselines: bool) -> LayoutOutput {
world.measure_baselines = baselines;
let output = world.compute_inline_formatting_context(world.root(), inputs, None);
world.measure_baselines = false;
output
}
#[test]
fn inline_measurement_baselines_and_purposes_do_not_alias_final_layout() {
let mut world = text_world(true);
let final_inputs = LayoutInput {
run_mode: RunMode::PerformLayout,
..inputs()
};
let accepted_output = measure(&mut world, final_inputs, false);
let signature = |world: &LayoutWorld<u8>| {
let inline = world.inline_layouts[0].as_ref().unwrap();
let accepted = inline.laid_out.as_ref().unwrap();
(
accepted.len(),
accepted.width(),
accepted.height(),
inline.line_placements.clone(),
inline.fragments.lines.clone(),
)
};
let accepted = signature(&world);
assert!(!accepted.4.is_empty());
let before = world
.inline_numeric_reuse
.as_ref()
.unwrap()
.estimated_retained_bytes();
let plain = measure(&mut world, inputs(), false);
assert_eq!(
world
.inline_numeric_reuse
.as_ref()
.unwrap()
.estimated_retained_bytes(),
before,
"known-size shortcuts must not allocate measurement storage"
);
let baseline = measure(&mut world, inputs(), true);
assert!(plain.baselines.first.is_none());
assert!(baseline.baselines.first.is_some());
assert_ne!(plain, baseline);
world.inline_numeric_reuse.as_mut().unwrap().reset_hits();
assert_eq!(measure(&mut world, inputs(), true), baseline);
assert_eq!(measure(&mut world, inputs(), false), plain);
assert_eq!(
world
.inline_numeric_reuse
.as_ref()
.unwrap()
.measurement_hits(),
1
);
assert_eq!(world.inline_numeric_reuse.as_ref().unwrap().hits(), 0);
assert_eq!(signature(&world), accepted);
for width in [
AvailableSpace::MinContent,
AvailableSpace::MaxContent,
AvailableSpace::Definite(180.0),
] {
for purpose in [SizingPurpose::IntrinsicContribution, SizingPurpose::Layout] {
let probe = LayoutInput {
known_dimensions: Size::NONE,
known_dimensions_are_definite: Size {
width: false,
height: false,
},
available_space: Size {
width,
height: AvailableSpace::MaxContent,
},
sizing_purpose: purpose,
..inputs()
};
let expected = measure(&mut text_world(false), probe, true);
assert_eq!(measure(&mut world, probe, true), expected);
world.inline_numeric_reuse.as_mut().unwrap().reset_hits();
assert_eq!(measure(&mut world, probe, true), expected);
assert_eq!(
world
.inline_numeric_reuse
.as_ref()
.unwrap()
.measurement_hits(),
1
);
assert_eq!(signature(&world), accepted);
}
}
assert_eq!(measure(&mut world, final_inputs, false), accepted_output);
assert_eq!(signature(&world), accepted);
assert_eq!(world.inline_numeric_reuse.as_ref().unwrap().hits(), 1);
}
#[test]
fn inline_measurements_revalidate_full_constraints_and_numeric_style() {
let mut world = text_world(true);
let base = inputs();
let probes = [
base,
LayoutInput {
known_dimensions: Size {
width: Some(180.0),
height: None,
},
..base
},
LayoutInput {
known_dimensions_are_definite: Size {
width: false,
height: false,
},
..base
},
LayoutInput {
parent_size: Size {
width: Some(320.0),
height: Some(80.0),
},
..base
},
LayoutInput {
parent_writing_mode: WritingMode::VerticalRl,
..base
},
LayoutInput {
available_space: Size {
width: AvailableSpace::MinContent,
height: AvailableSpace::Definite(40.0),
},
..base
},
LayoutInput {
axis: taffy::RequestedAxis::Horizontal,
..base
},
LayoutInput {
vertical_margins_are_collapsible: taffy::Line {
start: true,
end: true,
},
..base
},
];
for (index, probe) in probes.into_iter().enumerate() {
for baselines in [false, true] {
let mut cold = text_world(false);
if index % 2 == 1 {
world.boxes[0].style.taffy.min_size.width = taffy::style_helpers::length(80.0);
cold.boxes[0].style.taffy.min_size.width = taffy::style_helpers::length(80.0);
} else {
world.boxes[0].style.taffy.min_size.width = taffy::style_helpers::auto();
}
let expected = measure(&mut cold, probe, baselines);
assert_eq!(measure(&mut world, probe, baselines), expected);
world.inline_numeric_reuse.as_mut().unwrap().reset_hits();
assert_eq!(measure(&mut world, probe, baselines), expected);
if baselines {
assert_eq!(
world
.inline_numeric_reuse
.as_ref()
.unwrap()
.measurement_hits(),
1
);
}
}
}
let owner = world.root();
world.table_cell_percentage_height = Some((owner, false));
world.inline_numeric_reuse.as_mut().unwrap().reset_hits();
measure(&mut world, base, true);
assert_eq!(
world
.inline_numeric_reuse
.as_ref()
.unwrap()
.measurement_hits(),
0
);
}
#[test]
fn numeric_cache_growth_keeps_box_viewport_and_invalidation_owners_distinct() {
let mut world = text_world(false);
let output = measure(&mut world, inputs(), true);
let input = LayoutInput {
run_mode: RunMode::PerformLayout,
..inputs()
};
let root = world.root().to_taffy();
assert_eq!(world.cache_get(root, &input), None);
world.cache_store(root, &input, output.clone());
assert_eq!(world.cache_get(root, &input), Some(output.clone()));
assert_eq!(
world.cache_get(
root,
&LayoutInput {
sizing_purpose: SizingPurpose::IntrinsicContribution,
..input
}
),
None
);
// The old viewport ID becomes a real box ID when numeric preparation
// appends a box. Its cache must start empty, without losing viewport work.
let sibling = world.viewport_taffy_node();
let mut viewport_output = output.clone();
viewport_output.size.width += 10.0;
world.cache_store(sibling, &input, viewport_output.clone());
let mut extra = text_world(false).boxes.remove(0);
extra.source = Some(1);
world.boxes.push(extra);
assert_eq!(world.cache_get(sibling, &input), None);
let viewport = world.viewport_taffy_node();
assert_eq!(
world.cache_get(viewport, &input),
Some(viewport_output.clone())
);
let mut sibling_output = output;
sibling_output.size.width += 20.0;
world.cache_store(sibling, &input, sibling_output.clone());
world.cache_clear(root);
assert_eq!(world.cache_get(root, &input), None);
assert_eq!(
world.cache_get(sibling, &input),
Some(sibling_output.clone())
);
assert_eq!(world.cache_get(viewport, &input), Some(viewport_output));
world.cache_clear(viewport);
assert_eq!(world.cache_get(viewport, &input), None);
assert_eq!(world.cache_get(sibling, &input), Some(sibling_output));
}
+61
View File
@@ -877,6 +877,16 @@ struct RegisteredWebFont {
membership: WebFontMembership,
}
impl PartialEq for RegisteredWebFont {
fn eq(&self, other: &Self) -> bool {
self.face == other.face
&& self.source_key == other.source_key
&& self.membership == other.membership
&& (self.sfnt_bytes.id() == other.sfnt_bytes.id()
|| self.sfnt_bytes.as_ref() == other.sfnt_bytes.as_ref())
}
}
impl RegisteredWebFont {
fn priority(&self, slot: &str, order: &WebFontOrder) -> WebFontPriority {
order.get(slot).copied().unwrap_or_else(|| {
@@ -889,6 +899,49 @@ impl RegisteredWebFont {
}
}
/// Exact resource inputs for a retained text result. Font bytes remain shared
/// with their registrations; neither hash equality nor a family name alone
/// identifies a font replacement or a temporary stylesheet-font selection.
#[derive(Clone, PartialEq)]
pub(crate) struct LayoutFontInputs {
system_font_policy: SystemFontPolicy,
web_fonts: BTreeMap<String, RegisteredWebFont>,
web_font_order: WebFontOrder,
}
impl LayoutFontInputs {
/// Admission estimate for this copied registry's metadata. BTreeMap does
/// not expose its node capacity, so its nodes use a per-entry model. Font
/// payloads remain shared with the document service and are excluded; this
/// is neither their resident size nor an allocator-byte upper bound.
pub(crate) fn estimated_metadata_bytes(&self) -> usize {
let entry_charge = std::mem::size_of::<(String, RegisteredWebFont)>()
.saturating_mul(2)
.saturating_add(4 * std::mem::size_of::<usize>());
let fonts = self.web_fonts.iter().fold(0usize, |bytes, (slot, font)| {
bytes
.saturating_add(entry_charge)
.saturating_add(slot.capacity())
.saturating_add(font.source_key.as_ref().map_or(0, String::capacity))
.saturating_add(font.face.family_name.capacity())
.saturating_add(
font.face
.unicode_ranges
.capacity()
.saturating_mul(std::mem::size_of::<WebFontUnicodeRange>()),
)
});
let order_charge = std::mem::size_of::<(String, WebFontPriority)>()
.saturating_mul(2)
.saturating_add(4 * std::mem::size_of::<usize>());
self.web_font_order.iter().fold(fonts, |bytes, (slot, _)| {
bytes
.saturating_add(order_charge)
.saturating_add(slot.capacity())
})
}
}
/// Lazily initialized text resources reused by successive layout demands for
/// one committed Document.
///
@@ -935,6 +988,14 @@ impl Default for DocumentLayoutServices {
}
impl DocumentLayoutServices {
pub(crate) fn font_inputs(&self) -> LayoutFontInputs {
LayoutFontInputs {
system_font_policy: self.system_font_policy,
web_fonts: self.web_fonts.clone(),
web_font_order: self.web_font_order.clone(),
}
}
/// Creates an uninitialized document sidecar.
pub const fn new() -> Self {
Self {
+566
View File
@@ -0,0 +1,566 @@
//! Owned computation state, separate from the published immutable geometry.
//!
//! The shared box constructor can restore a supported graph after validating
//! its source dependencies. Supported graphs retain their owned box storage;
//! changed or unsupported graphs use fresh construction. Exact old inputs
//! validate retained slot identities and unchanged inline preparation. Eligible inline numeric results additionally reuse their exact
//! input keys; all remaining numeric work uses the same shared backend.
use std::{collections::HashMap, fmt::Debug, hash::Hash, sync::Arc};
use style::{properties::ComputedValues, servo_arc::Arc as ServoArc};
use crate::{
LayoutAnonymousReason, LayoutBox, LayoutBoxId, LayoutBoxKind, LayoutDisplay,
LayoutElementSemantics, LayoutPseudo, LayoutTextSelection, LayoutWorld, ResolvedLayoutStyle,
builder::ConstructionInputs,
inline::{InlineFormattingContext, InlineNumericReuse},
style::{
InlineDirection, InlineTextTransform, InlineUnicodeBidi, InlineVerticalAlign,
InlineWhiteSpaceCollapse,
},
text::LayoutFontInputs,
};
#[cfg(test)]
mod construction_retention_tests;
#[cfg(test)]
mod numeric_tests;
#[cfg(test)]
mod owned_construction_tests;
mod partial;
mod retention;
#[cfg(test)]
mod tests;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct LayoutWorkingSetStats {
pub retained_boxes: usize,
pub retained_text_bytes: usize,
/// Estimated storage of retained buffers. Includes visible allocation
/// capacities and an opaque Parley storage model, but excludes shared
/// computed-style/font payloads and allocator metadata. Shared source text
/// may be counted more than once; this is not resident-memory accounting.
pub estimated_retained_bytes: usize,
/// Construction slots whose retained identities matched the fresh pass.
/// A complete topology match counts the graph; partial restoration counts
/// only restored plain IFC owners and their validated direct text leaves.
/// This does not count reused allocations, preparation skips or numeric work.
pub reused_box_slots: usize,
/// Boxes answered by a validated retained construction graph, through
/// either in-place owned updates or compact graph materialization. This is
/// zero for cold construction, including inline-only restoration.
pub reused_construction_boxes: usize,
/// Box objects reused in place after complete source-frontier validation.
pub reused_owned_boxes: usize,
/// Retained box objects, rather than compact comparison records.
pub retained_owned_boxes: usize,
pub reused_inline_contexts: usize,
/// Final numeric calls answered by a validated result from a previous
/// pass. This counts calls, not unique owners or hits on newly computed
/// results within the current pass.
pub reused_inline_numeric_layouts: usize,
/// Size-only pure-text probes answered by exact constraints from a
/// previous pass. Separate from final layout and same-pass cache hits.
pub reused_inline_measurements: usize,
/// Estimated components of the currently retained computation state.
pub estimated_graph_bytes: usize,
/// The graph storage attributable to optional source dependencies used to
/// validate construction reuse. Already included in `estimated_graph_bytes`.
pub estimated_construction_bytes: usize,
/// Total retained inline storage, including `estimated_inline_numeric_bytes`.
pub estimated_inline_bytes: usize,
/// The inline storage attributable to retained numeric keys/results and
/// visible placement/fragment capacities. Opaque Parley storage remains
/// in the preparation model and is not counted a second time here.
pub estimated_inline_numeric_bytes: usize,
pub estimated_font_metadata_bytes: usize,
}
/// Optional, caller-owned state for one exact document and layout view.
///
/// The caller clears this at owner retirement and keeps transient views out
/// of the canonical slot. It contains no source/resolver borrow. Box IDs are
/// private to their construction identities. A changed graph is built fresh;
/// only independently validated, unmoved inline closures may retain their
/// preparation. No old ID is remapped to a different source. Clearing affects cost.
pub struct LayoutWorkingSet<N>
where
N: Copy + Debug + Eq + Hash,
{
retained: Option<RetainedWork<N>>,
stats: LayoutWorkingSetStats,
}
pub(crate) struct RetainedWork<N>
where
N: Copy + Debug + Eq + Hash,
{
graph: RetainedGraph<N>,
// Pass-local validation result prepared before updating owned box inputs.
prepared_inline_inputs: Option<Vec<bool>>,
construction_inputs: Option<Box<ConstructionInputs<N>>>,
// Allocation hint only. Numeric-only boxes are rebuilt, never retained as
// construction identities, but their previous count avoids late growth.
pass_box_count: usize,
// Most construction boxes do not own an IFC. Store only the real owners,
// without embedding a large Option<IFC> or allocating one Box per owner.
inline_contexts: Vec<(LayoutBoxId, InlineFormattingContext)>,
inline_numeric_reuse: Option<Box<InlineNumericReuse>>,
root: LayoutBoxId,
root_is_document_element: bool,
quirks_mode: style::context::QuirksMode,
fonts: LayoutFontInputs,
}
/// A single graph owner. Unsupported graphs retain compact
/// comparison inputs; supported graphs may keep the actual construction
/// objects. Neither representation retains paint resources or valid Taffy work.
pub(crate) enum RetainedGraph<N> {
Compact(Vec<RetainedBox<N>>),
Owned {
boxes: Vec<LayoutBox<N>>,
source_mapping: HashMap<N, LayoutBoxId>,
},
}
/// Borrowed comparison inputs shared by the two retention representations.
pub(crate) struct RetainedBoxRef<'a, N> {
pub(crate) source: Option<N>,
pub(crate) owner: Option<N>,
pub(crate) pseudo: Option<LayoutPseudo>,
pub(crate) kind: LayoutBoxKind,
pub(crate) anonymous_reason: Option<LayoutAnonymousReason>,
pub(crate) structural_parent: Option<LayoutBoxId>,
pub(crate) parent: Option<LayoutBoxId>,
pub(crate) children: &'a [LayoutBoxId],
pub(crate) inline_formatting_context: bool,
pub(crate) outside_list_marker: bool,
computed: Option<&'a ServoArc<ComputedValues>>,
inline_style: InlineStyleInputs,
pub(crate) element_semantics: Option<&'a LayoutElementSemantics>,
pub(crate) text: Option<&'a Arc<str>>,
text_selection: Option<LayoutTextSelection>,
}
impl<N: Copy> RetainedBoxRef<'_, N> {
fn from_compact(old: &RetainedBox<N>) -> RetainedBoxRef<'_, N> {
RetainedBoxRef {
source: old.source,
owner: old.owner,
pseudo: old.pseudo,
kind: old.kind,
anonymous_reason: old.anonymous_reason,
structural_parent: old.structural_parent,
parent: old.parent,
children: &old.children,
inline_formatting_context: old.inline_formatting_context,
outside_list_marker: old.outside_list_marker,
computed: old.computed.as_ref(),
inline_style: old.inline_style,
element_semantics: old.element_semantics.as_ref(),
text: old.text.as_ref(),
text_selection: old.text_selection,
}
}
fn from_owned(old: &LayoutBox<N>) -> RetainedBoxRef<'_, N> {
RetainedBoxRef {
source: old.source,
owner: old.owner,
pseudo: old.pseudo,
kind: old.kind,
anonymous_reason: old.anonymous_reason,
structural_parent: old.structural_parent,
parent: old.parent,
children: &old.children,
inline_formatting_context: old.inline_formatting_context,
outside_list_marker: old.outside_list_marker,
computed: old.style.stylo_computed_values(),
inline_style: InlineStyleInputs::from_style(&old.style),
element_semantics: old.element_semantics.as_ref(),
text: old.text.as_ref(),
text_selection: old.text_selection,
}
}
}
/// The retained construction graph and exact inputs used by inline matching.
/// Numeric styles/results, paint resources and diagnostic strings are omitted.
pub(crate) struct RetainedBox<N> {
pub(crate) source: Option<N>,
pub(crate) owner: Option<N>,
pub(crate) pseudo: Option<LayoutPseudo>,
pub(crate) kind: LayoutBoxKind,
pub(crate) anonymous_reason: Option<LayoutAnonymousReason>,
pub(crate) structural_parent: Option<LayoutBoxId>,
pub(crate) parent: Option<LayoutBoxId>,
pub(crate) children: Vec<LayoutBoxId>,
pub(crate) inline_formatting_context: bool,
pub(crate) outside_list_marker: bool,
// Owning the Arc prevents address reuse from turning a replaced computed
// style into a false pointer-equality match on a later pass.
computed: Option<ServoArc<ComputedValues>>,
inline_style: InlineStyleInputs,
pub(crate) element_semantics: Option<LayoutElementSemantics>,
pub(crate) text: Option<Arc<str>>,
text_selection: Option<LayoutTextSelection>,
}
#[derive(Clone, Copy, PartialEq)]
struct InlineStyleInputs {
display: LayoutDisplay,
out_of_flow: bool,
floated: bool,
white_space_collapse: InlineWhiteSpaceCollapse,
text_transform: InlineTextTransform,
direction: InlineDirection,
unicode_bidi: InlineUnicodeBidi,
vertical_align: InlineVerticalAlign,
writing_mode: taffy::WritingMode,
includes_used_font_metrics: bool,
}
impl InlineStyleInputs {
fn from_style(style: &ResolvedLayoutStyle) -> Self {
Self {
display: style.display(),
out_of_flow: style.is_out_of_flow(),
floated: style.is_floated(),
white_space_collapse: style.white_space_collapse(),
text_transform: style.text_transform(),
direction: style.direction(),
unicode_bidi: style.unicode_bidi(),
vertical_align: style.vertical_align(),
writing_mode: style.writing_mode(),
includes_used_font_metrics: style.includes_used_font_metrics(),
}
}
}
impl<N> RetainedWork<N>
where
N: Copy + Debug + Eq + Hash,
{
pub(crate) fn construction_inputs(&self) -> Option<&ConstructionInputs<N>> {
self.construction_inputs.as_deref()
}
pub(crate) fn box_count(&self) -> usize {
match &self.graph {
RetainedGraph::Compact(boxes) => boxes.len(),
RetainedGraph::Owned { boxes, .. } => boxes.len(),
}
}
pub(crate) fn box_at(&self, index: usize) -> Option<RetainedBoxRef<'_, N>> {
match &self.graph {
RetainedGraph::Compact(boxes) => boxes.get(index).map(RetainedBoxRef::from_compact),
RetainedGraph::Owned { boxes, .. } => boxes.get(index).map(RetainedBoxRef::from_owned),
}
}
pub(crate) fn construction_boxes(
&self,
) -> impl ExactSizeIterator<Item = RetainedBoxRef<'_, N>> {
(0..self.box_count()).map(|index| self.box_at(index).expect("construction slot exists"))
}
pub(crate) fn owned_construction(&self) -> Option<(&[LayoutBox<N>], &HashMap<N, LayoutBoxId>)> {
match &self.graph {
RetainedGraph::Owned {
boxes,
source_mapping,
} => Some((boxes, source_mapping)),
RetainedGraph::Compact(_) => None,
}
}
pub(crate) fn take_owned_construction(&mut self) -> Option<LayoutWorld<N>> {
self.owned_construction()?;
let RetainedGraph::Owned {
boxes,
source_mapping,
} = std::mem::replace(&mut self.graph, RetainedGraph::Compact(Vec::new()))
else {
unreachable!()
};
let mut world =
LayoutWorld::from_construction(boxes, source_mapping, self.root_is_document_element);
world.quirks_mode = self.quirks_mode;
Some(world)
}
/// Discard dependent old outputs while their computed-style owners still
/// reside on the retained graph. Never compare after installing new inputs.
pub(crate) fn prepare_owned_inline_inputs(&mut self, unchanged: Vec<bool>) {
self.inline_contexts
.retain(|(owner, _)| unchanged[owner.index()]);
if let Some(numeric) = &mut self.inline_numeric_reuse {
numeric.retain_owners(|owner| unchanged.get(owner.index()).copied().unwrap_or(false));
}
self.prepared_inline_inputs = Some(unchanged);
}
pub(crate) fn take_construction_inputs(&mut self) -> Option<Box<ConstructionInputs<N>>> {
self.construction_inputs.take()
}
pub(crate) fn box_capacity_hint(&self) -> usize {
self.pass_box_count
}
pub(crate) const fn root(&self) -> LayoutBoxId {
self.root
}
pub(crate) const fn root_is_document_element(&self) -> bool {
self.root_is_document_element
}
pub(crate) const fn quirks_mode(&self) -> style::context::QuirksMode {
self.quirks_mode
}
}
impl<N> Default for LayoutWorkingSet<N>
where
N: Copy + Debug + Eq + Hash,
{
fn default() -> Self {
Self::new()
}
}
impl<N> LayoutWorkingSet<N>
where
N: Copy + Debug + Eq + Hash,
{
pub fn new() -> Self {
Self {
retained: None,
stats: LayoutWorkingSetStats::default(),
}
}
pub fn clear(&mut self) {
self.retained = None;
self.stats = LayoutWorkingSetStats::default();
}
pub const fn stats(&self) -> LayoutWorkingSetStats {
self.stats
}
pub(crate) fn take(&mut self) -> Option<RetainedWork<N>> {
self.stats = LayoutWorkingSetStats::default();
self.retained.take()
}
pub(crate) fn publish(
&mut self,
mut world: LayoutWorld<N>,
fonts: LayoutFontInputs,
reused_box_slots: usize,
reused_inline_contexts: usize,
construction_box_count: usize,
) {
self.clear();
// Numeric placeholders belong to this pass, not the retained graph.
assert!(construction_box_count <= world.boxes.len());
let pass_box_count = world.boxes.len();
world.boxes.truncate(construction_box_count);
world.inline_layouts.truncate(construction_box_count);
let text_bytes = world.boxes.iter().fold(0usize, |bytes, layout_box| {
bytes.saturating_add(layout_box.text.as_deref().map_or(0, str::len))
});
self.stats.reused_box_slots = reused_box_slots;
self.stats.reused_construction_boxes = world
.construction_inputs
.as_ref()
.map_or(0, |inputs| inputs.reused_boxes());
self.stats.reused_owned_boxes = world
.construction_inputs
.as_ref()
.map_or(0, |inputs| inputs.reused_owned_boxes());
self.stats.reused_inline_contexts = reused_inline_contexts;
self.stats.reused_inline_numeric_layouts = world
.inline_numeric_reuse
.as_ref()
.map_or(0, |numeric| numeric.hits());
self.stats.reused_inline_measurements = world
.inline_numeric_reuse
.as_ref()
.map_or(0, |numeric| numeric.measurement_hits());
let retained = RetainedWork::from_world(world, fonts, pass_box_count);
let estimate = retained.estimated_retention();
self.stats.retained_boxes = retained.box_count();
self.stats.retained_owned_boxes = retained
.owned_construction()
.map_or(0, |(boxes, _)| boxes.len());
self.stats.retained_text_bytes = text_bytes;
self.stats.estimated_retained_bytes = estimate.total();
self.stats.estimated_graph_bytes = estimate.graph;
self.stats.estimated_construction_bytes = estimate.construction;
self.stats.estimated_inline_bytes = estimate.inline;
self.stats.estimated_inline_numeric_bytes = estimate.inline_numeric;
self.stats.estimated_font_metadata_bytes = estimate.font_metadata;
self.retained = Some(retained);
}
}
pub(crate) fn update_working_tree<N>(
previous: Option<RetainedWork<N>>,
mut current: LayoutWorld<N>,
fonts: &LayoutFontInputs,
) -> (LayoutWorld<N>, usize)
where
N: Copy + Debug + Eq + Hash,
{
let Some(mut previous) = previous else {
return (current, 0);
};
if previous.fonts != *fonts
|| previous.root != current.root
|| previous.root_is_document_element != current.root_is_document_element
|| previous.quirks_mode != current.quirks_mode
{
return (current, 0);
}
let (unchanged, count) = if let Some(unchanged) = previous.prepared_inline_inputs.take() {
(unchanged, current.len())
} else if same_topology(&previous, &current) {
(
unchanged_inline_subtrees(&previous, &current),
current.len(),
)
} else {
// The shared constructor has already rebuilt the changed graph. Do
// not revive that graph or remap IDs: only a bounded, independently
// validated local IFC can keep its owned preparation and output.
partial::unchanged_plain_inline_contexts(&previous, &current)
};
current.prepare_inline_storage();
for (owner, inline) in previous.inline_contexts {
if unchanged.get(owner.index()).copied().unwrap_or(false) {
// Restore only valid owned preparation. All newly constructed
// style, source, intrinsic, scroll and resource inputs stay fresh.
current.inline_layouts[owner.index()] = Some(inline);
}
}
if let Some(mut numeric) = previous.inline_numeric_reuse {
let mut has_retained_output = false;
numeric.retain_owners_for_box_count(current.len(), |owner| {
let keep = unchanged.get(owner.index()).copied().unwrap_or(false)
&& current
.inline_layouts
.get(owner.index())
.and_then(Option::as_ref)
.is_some_and(|inline| inline.laid_out.is_some());
has_retained_output |= keep;
keep
});
if has_retained_output {
// Only entries surviving graph, font and inline-input validation
// count as results restored from a previous pass.
numeric.reset_hits();
current.inline_numeric_reuse = Some(numeric);
}
}
(current, count)
}
fn unchanged_inline_subtrees<N>(previous: &RetainedWork<N>, current: &LayoutWorld<N>) -> Vec<bool>
where
N: Copy + Debug + Eq + Hash,
{
let unchanged = previous
.construction_boxes()
.zip(&current.boxes)
.map(|(old, new)| same_inline_input(&old, new))
.collect::<Vec<_>>();
propagate_inline_changes(current, unchanged)
}
pub(crate) fn propagate_inline_changes<N>(
current: &LayoutWorld<N>,
mut unchanged: Vec<bool>,
) -> Vec<bool>
where
N: Copy + Debug + Eq + Hash,
{
// Construction indices need not be preorder: anonymous wrappers can be
// allocated after their children. Propagate dependency changes bottom-up
// through the actual normalized forest, once per edge.
let mut remaining = current
.boxes
.iter()
.map(|layout_box| layout_box.children.len())
.collect::<Vec<_>>();
let mut leaves = remaining
.iter()
.enumerate()
.filter_map(|(index, children)| (*children == 0).then_some(index))
.collect::<Vec<_>>();
while let Some(index) = leaves.pop() {
if let Some(parent) = current.boxes[index].parent {
let parent = parent.index();
unchanged[parent] &= unchanged[index];
remaining[parent] -= 1;
if remaining[parent] == 0 {
leaves.push(parent);
}
}
}
unchanged
}
fn same_topology<N>(old: &RetainedWork<N>, new: &LayoutWorld<N>) -> bool
where
N: Copy + Debug + Eq + Hash,
{
old.root == new.root
&& old.root_is_document_element == new.root_is_document_element
&& old.quirks_mode == new.quirks_mode
&& old.box_count() == new.boxes.len()
&& old
.construction_boxes()
.zip(&new.boxes)
.all(|(old, new)| same_box_identity(&old, new) && old.children == new.children)
}
fn same_box_identity<N: PartialEq>(old: &RetainedBoxRef<'_, N>, new: &LayoutBox<N>) -> bool {
old.source == new.source
&& old.owner == new.owner
&& old.pseudo == new.pseudo
&& old.kind == new.kind
&& old.anonymous_reason == new.anonymous_reason
&& old.structural_parent == new.structural_parent
&& old.parent == new.parent
&& old.inline_formatting_context == new.inline_formatting_context
&& old.outside_list_marker == new.outside_list_marker
}
fn same_inline_input<N>(old: &RetainedBoxRef<'_, N>, new: &LayoutBox<N>) -> bool {
same_inline_style_input(old, &new.style, new.text_selection)
&& old.element_semantics == new.element_semantics.as_ref()
&& old.text == new.text.as_ref()
}
pub(crate) fn same_inline_style_input<N>(
old: &RetainedBoxRef<'_, N>,
style: &ResolvedLayoutStyle,
selection: Option<LayoutTextSelection>,
) -> bool {
let (Some(old_computed), Some(new_computed)) = (old.computed, style.stylo_computed_values())
else {
// Synthetic styles may be adjusted independently of a computed owner.
// Keep their normal builder path until they have an explicit input key.
return false;
};
ServoArc::ptr_eq(old_computed, new_computed)
&& old.text_selection == selection
&& old.inline_style == InlineStyleInputs::from_style(style)
}
@@ -0,0 +1,257 @@
use super::*;
use crate::{
DocumentLayoutServices, LayoutElementCategory, LayoutError, LayoutNamespace, LayoutSource,
LayoutSourceKind, LayoutStyleResolver, PaintColor, ResolvedLayoutElementStyles,
builder::{build_layout_world, build_layout_world_with_retained_inputs},
};
struct Source {
hidden_name: Arc<str>,
children: [Vec<usize>; 3],
}
impl Source {
fn new() -> Self {
Self {
hidden_name: Arc::from("hidden-construction-dependency"),
children: [vec![1, 2], Vec::new(), Vec::new()],
}
}
}
impl LayoutSource for Source {
type NodeId = usize;
type ChildIter<'a> = std::iter::Copied<std::slice::Iter<'a, usize>>;
fn root(&self) -> usize {
0
}
fn flat_parent(&self, node: usize) -> Option<usize> {
(node != 0).then_some(0)
}
fn flat_children(&self, node: usize) -> Self::ChildIter<'_> {
self.children[node].iter().copied()
}
fn node_kind(&self, node: usize) -> LayoutSourceKind {
if node == 1 {
LayoutSourceKind::Text
} else {
LayoutSourceKind::Element
}
}
fn element_semantics(&self, node: usize) -> Option<LayoutElementSemantics> {
match node {
0 => Some(LayoutElementSemantics::new(
LayoutNamespace::Html,
"div",
LayoutElementCategory::Generic,
None,
)),
2 => Some(LayoutElementSemantics::new(
LayoutNamespace::Html,
self.hidden_name.clone(),
LayoutElementCategory::Generic,
None,
)),
_ => None,
}
}
fn text(&self, node: usize) -> Option<&str> {
(node == 1).then_some("construction input")
}
fn label(&self, node: usize) -> String {
format!("source {node}")
}
}
struct Styles {
root_display: LayoutDisplay,
}
impl Styles {
fn block() -> Self {
Self {
root_display: LayoutDisplay::Block,
}
}
}
impl LayoutStyleResolver<usize> for Styles {
fn element_styles(
&mut self,
node: usize,
) -> Result<Option<ResolvedLayoutElementStyles>, LayoutError> {
Ok(Some(ResolvedLayoutElementStyles::from_primary(
ResolvedLayoutStyle::synthetic(
if node == 2 {
LayoutDisplay::None
} else {
self.root_display
},
taffy::Style::default(),
PaintColor::TRANSPARENT,
),
)))
}
}
fn construction_world(source: &Source) -> LayoutWorld<usize> {
build_layout_world_with_retained_inputs(source, &mut Styles::block(), None).unwrap()
}
#[test]
fn construction_dependency_capacity_is_reported_until_clear() {
let fonts = DocumentLayoutServices::new().font_inputs();
let mut baseline = LayoutWorkingSet::default();
let pass = construction_world(&Source::new());
let count = pass.len();
baseline.publish(pass, fonts.clone(), 0, 0, count);
let baseline_stats = baseline.stats();
assert!(baseline_stats.estimated_construction_bytes > 0);
let source = Source::new();
let dependency = Arc::downgrade(&source.hidden_name);
let mut pass = construction_world(&source);
let inputs = pass.construction_inputs.as_mut().unwrap();
inputs.reserve_source_capacity_for_test(4096);
let dependency_bytes = inputs.estimated_retained_bytes();
assert!(dependency_bytes > baseline_stats.estimated_construction_bytes + 1024);
drop(source);
let mut work = LayoutWorkingSet::default();
let count = pass.len();
work.publish(pass, fonts, 0, 0, count);
let stats = work.stats();
assert_eq!(stats.retained_boxes, count);
assert!(stats.estimated_retained_bytes > baseline_stats.estimated_retained_bytes);
assert_eq!(stats.estimated_construction_bytes, dependency_bytes);
assert_eq!(
stats.estimated_retained_bytes,
stats.estimated_graph_bytes
+ stats.estimated_inline_bytes
+ stats.estimated_font_metadata_bytes
);
assert!(work.retained.is_some());
assert!(dependency.upgrade().is_some());
work.clear();
assert!(
dependency.upgrade().is_none(),
"clear releases source dependencies"
);
}
#[test]
fn clear_and_drop_release_dependencies_for_sources_without_boxes() {
for explicit_clear in [false, true] {
let source = Source::new();
let dependency = Arc::downgrade(&source.hidden_name);
let pass = construction_world(&source);
assert!(
pass.boxes
.iter()
.all(|layout_box| layout_box.source != Some(2))
);
drop(source);
assert!(dependency.upgrade().is_some());
let mut work = LayoutWorkingSet::default();
let count = pass.len();
work.publish(
pass,
DocumentLayoutServices::new().font_inputs(),
0,
0,
count,
);
assert!(
work.retained
.as_ref()
.unwrap()
.construction_inputs()
.is_some()
);
assert!(dependency.upgrade().is_some());
if explicit_clear {
work.clear();
assert_eq!(work.stats(), LayoutWorkingSetStats::default());
assert!(dependency.upgrade().is_none());
}
drop(work);
assert!(dependency.upgrade().is_none());
}
}
#[test]
fn one_shot_and_unsupported_construction_do_not_retain_source_dependencies() {
for ordinary in [false, true] {
let source = Source::new();
let dependency = Arc::downgrade(&source.hidden_name);
let pass = if ordinary {
build_layout_world(&source, &mut Styles::block()).unwrap()
} else {
build_layout_world_with_retained_inputs(
&source,
&mut Styles {
root_display: LayoutDisplay::Flex,
},
None,
)
.unwrap()
};
assert!(pass.construction_inputs.is_none());
drop(source);
assert!(dependency.upgrade().is_none());
let mut work = LayoutWorkingSet::default();
let count = pass.len();
work.publish(
pass,
DocumentLayoutServices::new().font_inputs(),
0,
0,
count,
);
assert_eq!(work.stats().estimated_construction_bytes, 0);
assert_eq!(work.stats().reused_construction_boxes, 0);
assert!(
work.retained
.as_ref()
.unwrap()
.construction_inputs()
.is_none()
);
}
}
#[test]
fn construction_reuse_statistics_reset_after_eviction() {
let source = Source::new();
let fonts = DocumentLayoutServices::new().font_inputs();
let mut work = LayoutWorkingSet::default();
let pass = construction_world(&source);
let count = pass.len();
work.publish(pass, fonts.clone(), 0, 0, count);
assert_eq!(work.stats().reused_construction_boxes, 0);
let mut previous = work.take();
let pass =
build_layout_world_with_retained_inputs(&source, &mut Styles::block(), previous.as_mut())
.unwrap();
let count = pass.len();
let (pass, reused) = update_working_tree(previous, pass, &fonts);
work.publish(pass, fonts.clone(), reused, 0, count);
assert_eq!(work.stats().reused_construction_boxes, count);
work.clear();
assert_eq!(work.stats(), LayoutWorkingSetStats::default());
let pass = construction_world(&source);
let count = pass.len();
work.publish(pass, fonts, 0, 0, count);
assert_eq!(work.stats().reused_construction_boxes, 0);
}
@@ -0,0 +1,367 @@
use super::*;
use crate::{
DocumentLayoutServices,
inline::{InlineContentWidthsMemo, InlineFragments, InlineNumericInputs, InlineSourceFragment},
};
fn numeric_world(
fragment_capacity: usize,
accepted: bool,
numeric_style: taffy::Style<style::Atom>,
) -> LayoutWorld<usize> {
let mut world = super::tests::world(None);
let owner = world.root;
world.boxes[owner.index()].inline_formatting_context = true;
let style = &world.boxes[owner.index()].style;
let inputs = InlineNumericInputs {
layout: taffy::LayoutInput {
run_mode: taffy::RunMode::PerformLayout,
..taffy::LayoutInput::HIDDEN
},
writing_mode: style.writing_mode(),
resolved_aspect_ratio: None,
scrollbar_insets: taffy::Rect {
left: 0.0,
right: 0.0,
top: 0.0,
bottom: 0.0,
},
display: style.display(),
alignment: style.text_align(),
direction: style.direction(),
parent_is_flex_or_grid: false,
};
let mut numeric = InlineNumericReuse::new(world.len());
numeric.store(owner, inputs, numeric_style, taffy::LayoutOutput::DEFAULT);
world.inline_numeric_reuse = Some(Box::new(numeric));
world.prepare_inline_storage();
world.inline_layouts[owner.index()] = Some(InlineFormattingContext {
text: String::new(),
root_style: owner,
measurement_layout: Some(parley::Layout::default()),
laid_out: accepted.then(parley::Layout::default),
content_widths: InlineContentWidthsMemo::default(),
text_units: Vec::new(),
source_map: Vec::new(),
selection: None,
objects: Vec::new(),
font_metrics: Vec::new(),
parent_strut: None,
uses_quirks_line_height: false,
root_includes_used_font_metrics: false,
style_parents: Vec::new(),
structural_boxes: Vec::new(),
line_placements: Vec::new(),
fragments: InlineFragments {
text: Vec::with_capacity(fragment_capacity),
..InlineFragments::default()
},
});
world
}
#[test]
fn retained_processed_text_capacity_is_reported_while_retained() {
let fonts = DocumentLayoutServices::new().font_inputs();
let mut baseline = LayoutWorkingSet::default();
baseline.publish(
numeric_world(0, true, taffy::Style::default()),
fonts.clone(),
0,
0,
1,
);
let baseline_stats = baseline.stats();
let mut work = LayoutWorkingSet::default();
let mut pass = numeric_world(0, true, taffy::Style::default());
let text = &mut pass.inline_layouts[0].as_mut().unwrap().text;
*text = String::with_capacity(8192);
let owned_text_bytes = text.capacity();
assert!(text.is_empty());
work.publish(pass, fonts, 0, 0, 1);
let stats = work.stats();
assert_eq!(stats.retained_boxes, 1);
assert!(stats.estimated_retained_bytes > 0);
assert_eq!(
stats.estimated_inline_bytes,
baseline_stats.estimated_inline_bytes + owned_text_bytes
);
assert!(work.retained.is_some());
}
#[test]
fn retained_numeric_output_capacity_is_reported_while_retained() {
let fonts = DocumentLayoutServices::new().font_inputs();
let mut baseline = LayoutWorkingSet::default();
baseline.publish(
numeric_world(0, true, taffy::Style::default()),
fonts.clone(),
0,
0,
1,
);
let baseline_stats = baseline.stats();
assert!(baseline_stats.estimated_inline_numeric_bytes > 0);
let mut work = LayoutWorkingSet::default();
let pass = numeric_world(1024, true, taffy::Style::default());
let output_bytes = pass.inline_layouts[0]
.as_ref()
.unwrap()
.fragments
.text
.capacity()
* std::mem::size_of::<InlineSourceFragment>();
work.publish(pass, fonts, 0, 0, 1);
let stats = work.stats();
assert_eq!(stats.retained_boxes, 1);
assert!(stats.estimated_retained_bytes > 0);
assert_eq!(
stats.estimated_inline_numeric_bytes,
baseline_stats.estimated_inline_numeric_bytes + output_bytes
);
assert_eq!(
stats.estimated_retained_bytes,
stats.estimated_graph_bytes
+ stats.estimated_inline_bytes
+ stats.estimated_font_metadata_bytes
);
assert!(work.retained.is_some());
}
#[test]
fn retained_numeric_style_key_capacity_is_reported_while_retained() {
let fonts = DocumentLayoutServices::new().font_inputs();
let mut baseline = LayoutWorkingSet::default();
baseline.publish(
numeric_world(0, true, taffy::Style::default()),
fonts.clone(),
0,
0,
1,
);
let baseline_stats = baseline.stats();
let mut work = LayoutWorkingSet::default();
let names = Vec::<style::Atom>::with_capacity(1024);
let owned_key_bytes = names.capacity() * std::mem::size_of::<style::Atom>();
let numeric_style = taffy::Style {
grid_template_row_names: vec![names],
..taffy::Style::default()
};
work.publish(numeric_world(0, true, numeric_style), fonts, 0, 0, 1);
let stats = work.stats();
assert!(
stats.estimated_inline_numeric_bytes
>= baseline_stats.estimated_inline_numeric_bytes + owned_key_bytes
);
assert!(work.retained.is_some());
}
#[test]
fn measurement_and_final_results_survive_until_explicit_clear() {
let fonts = DocumentLayoutServices::new().font_inputs();
let mut baseline = LayoutWorkingSet::default();
baseline.publish(
numeric_world(0, true, taffy::Style::default()),
fonts.clone(),
0,
0,
1,
);
let base_bytes = baseline.stats().estimated_retained_bytes;
let mut pass = numeric_world(0, true, taffy::Style::default());
let owner = pass.root;
let style = &pass.boxes[0].style;
let inputs = crate::inline::InlineMeasurementInputs {
numeric: InlineNumericInputs {
layout: taffy::LayoutInput {
run_mode: taffy::RunMode::ComputeSize,
..taffy::LayoutInput::HIDDEN
},
writing_mode: style.writing_mode(),
resolved_aspect_ratio: None,
scrollbar_insets: taffy::Rect::zero(),
display: style.display(),
alignment: style.text_align(),
direction: style.direction(),
parent_is_flex_or_grid: false,
},
measure_baselines: true,
};
let numeric_style = taffy::Style {
grid_template_row_names: vec![Vec::with_capacity(2048)],
..taffy::Style::default()
};
let lookup_style = numeric_style.clone();
pass.inline_numeric_reuse
.as_mut()
.unwrap()
.store_measurement(owner, inputs, numeric_style, taffy::LayoutOutput::DEFAULT);
let measured = pass
.inline_numeric_reuse
.as_ref()
.unwrap()
.estimated_retained_bytes();
assert!(measured > base_bytes + 1024);
let mut work = LayoutWorkingSet::default();
work.publish(pass, fonts, 0, 0, 1);
assert!(work.stats().estimated_retained_bytes > base_bytes + 1024);
let retained = work.retained.as_mut().unwrap();
let numeric = retained.inline_numeric_reuse.as_mut().unwrap();
assert!(numeric.contains(owner));
assert!(
numeric
.lookup_measurement(owner, inputs, &lookup_style)
.is_some()
);
assert!(retained.inline_contexts[0].1.laid_out.is_some());
work.clear();
assert_eq!(work.stats(), LayoutWorkingSetStats::default());
}
#[test]
fn numeric_entries_without_accepted_outputs_release_their_retained_buffers() {
let fonts = DocumentLayoutServices::new().font_inputs();
for absent_ifc in [false, true] {
let mut pass = numeric_world(1024, false, taffy::Style::default());
if absent_ifc {
pass.inline_layouts[0] = None;
}
let mut work = LayoutWorkingSet::default();
work.publish(pass, fonts.clone(), 0, 0, 1);
assert_eq!(work.stats().estimated_inline_numeric_bytes, 0);
let retained = work.retained.as_ref().unwrap();
assert!(retained.inline_numeric_reuse.is_none());
if let Some((_, inline)) = retained.inline_contexts.first() {
assert!(inline.measurement_layout.is_some());
assert!(inline.laid_out.is_none());
assert_eq!(inline.fragments.text.capacity(), 0);
}
}
}
#[test]
fn retained_numeric_output_preserves_one_paragraph_until_explicit_eviction() {
let source_text: Arc<str> = Arc::from("owner input");
let source_weak = Arc::downgrade(&source_text);
let mut pass = numeric_world(64, true, taffy::Style::default());
pass.boxes[0].text = Some(source_text);
let mut work = LayoutWorkingSet::default();
work.publish(pass, DocumentLayoutServices::new().font_inputs(), 0, 0, 1);
let retained = work.retained.as_ref().unwrap();
assert!(retained.inline_numeric_reuse.is_some());
let (_, inline) = &retained.inline_contexts[0];
assert!(inline.measurement_layout.is_none());
assert!(inline.laid_out.is_some());
assert!(inline.fragments.text.capacity() >= 64);
assert!(work.stats().estimated_inline_numeric_bytes > 0);
work.clear();
assert!(work.retained.is_none());
assert_eq!(work.stats(), LayoutWorkingSetStats::default());
assert!(source_weak.upgrade().is_none());
}
#[test]
fn partial_numeric_owner_index_grows_shrinks_and_rejects_removed_entries() {
let mut world = numeric_world(0, true, taffy::Style::default());
let style = &world.boxes[0].style;
let inputs = InlineNumericInputs {
layout: taffy::LayoutInput {
run_mode: taffy::RunMode::PerformLayout,
..taffy::LayoutInput::HIDDEN
},
writing_mode: style.writing_mode(),
resolved_aspect_ratio: None,
scrollbar_insets: taffy::Rect {
left: 0.0,
right: 0.0,
top: 0.0,
bottom: 0.0,
},
display: style.display(),
alignment: style.text_align(),
direction: style.direction(),
parent_is_flex_or_grid: false,
};
let mut numeric = world.inline_numeric_reuse.take().unwrap();
numeric.retain_owners_for_box_count(257, |_| true);
assert!(
numeric.estimated_retained_bytes()
>= std::mem::size_of::<InlineNumericReuse>()
+ 257 * std::mem::size_of::<Option<usize>>()
);
let last = LayoutBoxId::from_index(256);
let mut old_output = taffy::LayoutOutput::DEFAULT;
old_output.size.width = 17.0;
numeric.store(last, inputs, taffy::Style::default(), old_output);
assert_eq!(
numeric
.lookup(last, inputs, &taffy::Style::default())
.unwrap()
.size
.width,
17.0
);
// The caller's predicate deliberately accepts everything: the new graph
// bound itself must retire an out-of-range owner before rebuilding slots.
numeric.retain_owners_for_box_count(1, |_| true);
assert!(!numeric.contains(last));
assert!(
numeric
.lookup(last, inputs, &taffy::Style::default())
.is_none()
);
numeric.retain_owners_for_box_count(257, |_| true);
assert!(
!numeric.contains(last),
"regrowth must not revive a removed dense slot"
);
let mut new_output = taffy::LayoutOutput::DEFAULT;
new_output.size.width = 29.0;
numeric.store(last, inputs, taffy::Style::default(), new_output);
assert_eq!(
numeric
.lookup(last, inputs, &taffy::Style::default())
.unwrap()
.size
.width,
29.0
);
assert_eq!(
numeric
.lookup(LayoutBoxId::from_index(0), inputs, &taffy::Style::default())
.unwrap()
.size
.width,
0.0
);
// Shrinking the logical graph keeps this allocation available for the
// next append. Its remaining capacity must still be reported.
numeric.retain_owners_for_box_count(1, |_| true);
let fonts = DocumentLayoutServices::new().font_inputs();
let fresh = numeric_world(0, true, taffy::Style::default());
let fresh_numeric_bytes = fresh
.inline_numeric_reuse
.as_ref()
.unwrap()
.estimated_retained_bytes();
let excess = numeric.estimated_retained_bytes() - fresh_numeric_bytes;
assert!(excess >= 256 * std::mem::size_of::<Option<usize>>());
let mut baseline = LayoutWorkingSet::default();
baseline.publish(fresh, fonts.clone(), 0, 0, 1);
let baseline_stats = baseline.stats();
world.inline_numeric_reuse = Some(numeric);
let mut work = LayoutWorkingSet::default();
work.publish(world, fonts, 0, 0, 1);
assert_eq!(
work.stats().estimated_retained_bytes,
baseline_stats.estimated_retained_bytes + excess
);
assert_eq!(
work.stats().estimated_inline_numeric_bytes,
baseline_stats.estimated_inline_numeric_bytes + excess
);
assert!(work.retained.is_some());
}
@@ -0,0 +1,680 @@
use std::collections::HashMap;
mod grid;
mod table;
use super::*;
use crate::{
DocumentLayoutServices, EmbeddedFrameRenderer, EmbeddedFrameSnapshot, LayoutElementCategory,
LayoutError, LayoutFlushReason, LayoutImageResource, LayoutNamespace, LayoutPassRequest,
LayoutPassResult, LayoutPoint, LayoutQuery, LayoutSource, LayoutSourceKind,
LayoutStyleResolver, LayoutViewport, PaintColor, ResolvedLayoutElementStyles,
build_layout_pass, build_layout_pass_with_working_set,
builder::{build_layout_world, build_layout_world_with_retained_inputs},
};
#[derive(Clone)]
struct Node {
children: Vec<usize>,
text: Option<String>,
}
impl Node {
fn element(children: Vec<usize>) -> Self {
Self {
children,
text: None,
}
}
fn text(text: &str) -> Self {
Self {
children: Vec::new(),
text: Some(text.into()),
}
}
}
#[derive(Clone)]
struct Source {
nodes: Vec<Node>,
semantics: HashMap<usize, LayoutElementSemantics>,
hidden_name: Arc<str>,
scroll: LayoutPoint,
selection: Option<LayoutTextSelection>,
label_revision: usize,
}
impl Source {
fn new() -> Self {
Self {
nodes: vec![
Node::element(vec![1, 3, 5]),
Node::element(vec![2]),
Node::text("first paragraph"),
Node::element(vec![4]),
Node::text("second paragraph"),
Node::element(Vec::new()),
],
semantics: HashMap::new(),
hidden_name: Arc::from("owned-hidden-dependency"),
scroll: LayoutPoint::ZERO,
selection: None,
label_revision: 0,
}
}
}
impl LayoutSource for Source {
type NodeId = usize;
type ChildIter<'a> = std::iter::Copied<std::slice::Iter<'a, usize>>;
fn root(&self) -> usize {
0
}
fn flat_parent(&self, node: usize) -> Option<usize> {
self.nodes
.iter()
.position(|parent| parent.children.contains(&node))
}
fn flat_children(&self, node: usize) -> Self::ChildIter<'_> {
self.nodes[node].children.iter().copied()
}
fn node_kind(&self, node: usize) -> LayoutSourceKind {
if self.nodes[node].text.is_some() {
LayoutSourceKind::Text
} else {
LayoutSourceKind::Element
}
}
fn element_semantics(&self, node: usize) -> Option<LayoutElementSemantics> {
(self.node_kind(node) == LayoutSourceKind::Element).then(|| {
if let Some(semantics) = self.semantics.get(&node) {
return semantics.clone();
}
LayoutElementSemantics::new(
LayoutNamespace::Html,
if node == 5 {
self.hidden_name.clone()
} else {
Arc::from("div")
},
LayoutElementCategory::Generic,
None,
)
})
}
fn text(&self, node: usize) -> Option<&str> {
self.nodes[node].text.as_deref()
}
fn label(&self, node: usize) -> String {
format!("source-{node}-revision-{}", self.label_revision)
}
fn text_selection(&self, node: usize) -> Option<LayoutTextSelection> {
(node == 2).then_some(self.selection).flatten()
}
fn scroll_offset(&self, node: usize) -> LayoutPoint {
if node == 1 {
self.scroll
} else {
LayoutPoint::ZERO
}
}
}
struct Styles {
root_display: LayoutDisplay,
first_width: f32,
color: PaintColor,
hidden: bool,
fail_at: Option<usize>,
visited: Vec<usize>,
font_style: Option<ResolvedLayoutStyle>,
positioned: Option<(usize, crate::LayoutPosition)>,
}
impl Styles {
fn new() -> Self {
Self {
root_display: LayoutDisplay::Block,
first_width: 100.0,
color: PaintColor::WHITE,
hidden: true,
fail_at: None,
visited: Vec::new(),
font_style: None,
positioned: None,
}
}
}
impl LayoutStyleResolver<usize> for Styles {
fn element_styles(
&mut self,
node: usize,
) -> Result<Option<ResolvedLayoutElementStyles>, LayoutError> {
self.visited.push(node);
if self.fail_at == Some(node) {
return Err(LayoutError::style_resolution(
node.to_string(),
"injected late source validation failure",
));
}
let display = match node {
0 => self.root_display,
5 if self.hidden => LayoutDisplay::None,
_ => LayoutDisplay::Block,
};
let width = match node {
0 => 320.0,
1 => self.first_width,
_ => 140.0,
};
let size = taffy::Size {
width: taffy::Dimension::length(width),
height: taffy::Dimension::length(if node == 0 { 120.0 } else { 40.0 }),
};
let style = if let Some(base) = &self.font_style {
let mut style = base.clone();
style.force_layout_display(display);
style.taffy.size = size;
style
} else {
ResolvedLayoutStyle::synthetic(
display,
taffy::Style {
size,
..taffy::Style::default()
},
self.color,
)
};
let style = if let Some((target, position)) = self.positioned {
if target == node {
style.with_position(position)
} else {
style
}
} else {
style
};
Ok(Some(ResolvedLayoutElementStyles::from_primary(style)))
}
}
fn owned_parts(
work: &LayoutWorkingSet<usize>,
) -> (&Vec<LayoutBox<usize>>, &HashMap<usize, LayoutBoxId>) {
match &work.retained.as_ref().expect("retained work").graph {
RetainedGraph::Owned {
boxes,
source_mapping,
} => (boxes, source_mapping),
RetainedGraph::Compact(_) => panic!("fixture must admit its owned construction"),
}
}
fn publish(world: LayoutWorld<usize>, work: &mut LayoutWorkingSet<usize>) {
let count = world.len();
work.publish(
world,
DocumentLayoutServices::new().font_inputs(),
0,
0,
count,
);
}
#[test]
fn owned_construction_moves_the_box_and_child_allocations_across_passes() {
let mut source = Source::new();
let mut styles = Styles::new();
let mut pass = build_layout_world_with_retained_inputs(&source, &mut styles, None).unwrap();
pass.boxes.reserve_exact(17);
pass.boxes[0].children.reserve_exact(11);
pass.source_mapping.reserve(13);
let box_pointer = pass.boxes.as_ptr();
let box_capacity = pass.boxes.capacity();
let child_pointer = pass.boxes[0].children.as_ptr();
let child_capacity = pass.boxes[0].children.capacity();
let mapping_capacity = pass.source_mapping.capacity();
let mapping = pass.source_mapping.clone();
let mut work = LayoutWorkingSet::default();
publish(pass, &mut work);
let (boxes, source_mapping) = owned_parts(&work);
assert_eq!(boxes.as_ptr(), box_pointer);
assert_eq!(boxes.capacity(), box_capacity);
assert_eq!(boxes[0].children.as_ptr(), child_pointer);
assert_eq!(boxes[0].children.capacity(), child_capacity);
assert_eq!(source_mapping.capacity(), mapping_capacity);
assert_eq!(source_mapping, &mapping);
// These observations span one continuously owned allocation, through
// take/restore/publish. No address is compared after cache eviction.
source.scroll = LayoutPoint::new(3.0, 7.0);
source.selection = Some(LayoutTextSelection::new(1, 4));
source.label_revision = 1;
styles.first_width = 200.0;
styles.color = PaintColor::new(0.25, 0.5, 0.75, 1.0);
let mut previous = work.take();
let pass =
build_layout_world_with_retained_inputs(&source, &mut styles, previous.as_mut()).unwrap();
assert_eq!(pass.boxes.as_ptr(), box_pointer);
assert_eq!(pass.boxes.capacity(), box_capacity);
assert_eq!(pass.boxes[0].children.as_ptr(), child_pointer);
assert_eq!(pass.boxes[0].children.capacity(), child_capacity);
assert_eq!(pass.source_mapping, mapping);
assert_eq!(pass.source_mapping.capacity(), mapping_capacity);
assert_eq!(
pass.construction_inputs
.as_ref()
.unwrap()
.reused_owned_boxes(),
pass.len()
);
let first = &pass.boxes[pass.source_box(1).unwrap().index()];
assert_eq!(
first.style.taffy.size.width,
taffy::Dimension::length(200.0)
);
assert_eq!(first.style.background_color(), styles.color);
assert_eq!(first.scroll_offset, source.scroll);
assert_eq!(first.source_label, source.label(1));
let text = &pass.boxes[pass.source_box(2).unwrap().index()];
assert_eq!(text.text_selection, source.selection);
assert_eq!(text.source_label, source.label(2));
let (pass, _) =
update_working_tree(previous, pass, &DocumentLayoutServices::new().font_inputs());
publish(pass, &mut work);
assert_eq!(owned_parts(&work).0.as_ptr(), box_pointer);
assert_eq!(owned_parts(&work).0[0].children.as_ptr(), child_pointer);
assert_eq!(work.stats().reused_owned_boxes, work.stats().retained_boxes);
}
#[test]
fn owned_construction_shape_changes_rebuild_current_source_mappings() {
for change in 0..4 {
let mut source = Source::new();
let mut styles = Styles::new();
let mut work = LayoutWorkingSet::default();
publish(
build_layout_world_with_retained_inputs(&source, &mut styles, None).unwrap(),
&mut work,
);
owned_parts(&work);
match change {
0 => {
source.nodes[0].children.push(6);
source.nodes.push(Node::element(vec![7]));
source.nodes.push(Node::text("appended paragraph"));
}
1 => source.nodes[0].children.swap(0, 1),
2 => styles.hidden = false,
3 => styles.root_display = LayoutDisplay::Flex,
_ => unreachable!(),
}
let mut previous = work.take();
let pass = build_layout_world_with_retained_inputs(&source, &mut styles, previous.as_mut())
.unwrap();
assert_eq!(
pass.construction_inputs
.as_ref()
.map_or(0, |inputs| inputs.reused_owned_boxes()),
0
);
let cold = build_layout_world(&source, &mut styles).unwrap();
assert_eq!(pass.source_mapping, cold.source_mapping);
assert_eq!(pass.display_contents_mapping, cold.display_contents_mapping);
assert_eq!(pass.len(), cold.len());
for (actual, expected) in pass.boxes.iter().zip(&cold.boxes) {
assert_eq!(actual.source, expected.source);
assert_eq!(actual.kind, expected.kind);
assert_eq!(actual.parent, expected.parent);
assert_eq!(actual.structural_parent, expected.structural_parent);
assert_eq!(actual.children, expected.children);
assert_eq!(actual.text, expected.text);
}
let (pass, _) =
update_working_tree(previous, pass, &DocumentLayoutServices::new().font_inputs());
publish(pass, &mut work);
assert_eq!(work.stats().reused_owned_boxes, 0);
if change == 3 {
assert!(matches!(
work.retained.as_ref().unwrap().graph,
RetainedGraph::Compact(_)
));
assert!(
work.retained
.as_ref()
.unwrap()
.construction_inputs()
.is_none()
);
} else {
owned_parts(&work);
}
}
}
#[test]
fn owned_construction_capacity_is_reported_even_when_slots_are_unused() {
let source = Source::new();
let mut styles = Styles::new();
let baseline_pass =
build_layout_world_with_retained_inputs(&source, &mut styles, None).unwrap();
let base_box_capacity = baseline_pass.boxes.capacity();
let base_child_capacity = baseline_pass.boxes[0].children.capacity();
let mut baseline = LayoutWorkingSet::default();
publish(baseline_pass, &mut baseline);
owned_parts(&baseline);
let mut pass = build_layout_world_with_retained_inputs(&source, &mut styles, None).unwrap();
pass.boxes.reserve_exact(31);
pass.boxes[0].children.reserve_exact(23);
let additional = (pass.boxes.capacity() - base_box_capacity)
* std::mem::size_of::<LayoutBox<usize>>()
+ (pass.boxes[0].children.capacity() - base_child_capacity)
* std::mem::size_of::<LayoutBoxId>();
let mut grown = LayoutWorkingSet::default();
publish(pass, &mut grown);
owned_parts(&grown);
assert_eq!(
grown.stats().retained_boxes,
baseline.stats().retained_boxes
);
assert_eq!(
grown.stats().estimated_retained_bytes,
baseline.stats().estimated_retained_bytes + additional
);
}
#[test]
fn owned_construction_releases_paint_resources_and_owned_dependencies() {
for explicit_clear in [false, true] {
let source = Source::new();
let dependency = Arc::downgrade(&source.hidden_name);
let mut pass =
build_layout_world_with_retained_inputs(&source, &mut Styles::new(), None).unwrap();
let pixels = Arc::new(moli_image::RgbaImage::try_new(1, 1, vec![0; 4]).unwrap());
let pixels_weak = Arc::downgrade(&pixels);
let image = LayoutImageResource {
intrinsic_width: 1.0,
intrinsic_height: 1.0,
pixels: Some(pixels),
svg: None,
};
pass.boxes[0].replaced_image = Some(image.clone());
pass.boxes[0].css_images.background = vec![Some(image.clone())];
pass.boxes[0].css_images.mask = vec![Some(image)];
drop(source);
let mut work = LayoutWorkingSet::default();
publish(pass, &mut work);
let (boxes, _) = owned_parts(&work);
assert!(boxes[0].replaced_image.is_none());
assert_eq!(boxes[0].css_images.background.capacity(), 0);
assert_eq!(boxes[0].css_images.mask.capacity(), 0);
assert!(pixels_weak.upgrade().is_none());
assert!(dependency.upgrade().is_some());
if explicit_clear {
work.clear();
assert!(dependency.upgrade().is_none());
assert_eq!(work.stats(), LayoutWorkingSetStats::default());
}
drop(work);
assert!(dependency.upgrade().is_none());
}
}
struct NoFrames;
impl EmbeddedFrameRenderer<usize> for NoFrames {
fn render_embedded_frame(
&mut self,
_: usize,
_: LayoutViewport,
) -> Result<Option<EmbeddedFrameSnapshot<usize>>, LayoutError> {
Ok(None)
}
}
fn compare_with_cold<R: LayoutStyleResolver<usize>>(
source: &Source,
styles: &mut R,
services: &mut DocumentLayoutServices,
work: &mut LayoutWorkingSet<usize>,
) -> LayoutPassResult<usize> {
let request =
LayoutPassRequest::with_paint(LayoutViewport::new(320, 240, 1.0), LayoutFlushReason::Test);
let retained = build_layout_pass_with_working_set(
source,
styles,
services,
request,
&mut NoFrames,
Some(work),
)
.unwrap();
let cold = build_layout_pass(source, styles, services, request).unwrap();
assert_eq!(retained.tree.boxes, cold.tree.boxes);
assert_eq!(retained.tree.fragments, cold.tree.fragments);
assert_eq!(retained.paint_snapshot(), cold.paint_snapshot());
for source in 0..source.nodes.len() {
for query in [
LayoutQuery::ElementMetrics { source },
LayoutQuery::ClientRects { source },
LayoutQuery::TextRangeRects {
source,
utf16_range: 0..usize::MAX,
},
LayoutQuery::IntersectionGeometry {
target: source,
root: None,
},
LayoutQuery::UsedGridTracks { source },
] {
assert_eq!(retained.answer_query(&query), cold.answer_query(&query));
}
}
for y in (0..240).step_by(23) {
for x in (0..320).step_by(29) {
let point = LayoutPoint::new(x as f32, y as f32);
assert_eq!(retained.hit_test(point, false), cold.hit_test(point, false));
}
}
retained
}
#[test]
fn owned_construction_updates_match_cold_and_evicted_output_without_mutating_a_frozen_sample() {
let mut source = Source::new();
let mut styles = Styles::new();
let mut services = DocumentLayoutServices::new();
let mut work = LayoutWorkingSet::default();
let first = compare_with_cold(&source, &mut styles, &mut services, &mut work);
owned_parts(&work);
let frozen_boxes = first.tree.boxes.clone();
let frozen_fragments = first.tree.fragments.clone();
styles.first_width = 200.0;
styles.color = PaintColor::new(1.0, 0.25, 0.0, 1.0);
source.scroll = LayoutPoint::new(0.0, 9.0);
source.selection = Some(LayoutTextSelection::new(0, 5));
let warm = compare_with_cold(&source, &mut styles, &mut services, &mut work);
assert!(work.stats().reused_owned_boxes > 0);
assert_eq!(first.tree.boxes, frozen_boxes);
assert_eq!(first.tree.fragments, frozen_fragments);
work.clear();
let evicted = compare_with_cold(&source, &mut styles, &mut services, &mut work);
assert_eq!(work.stats().reused_owned_boxes, 0);
assert_eq!(warm.tree.boxes, evicted.tree.boxes);
assert_eq!(warm.tree.fragments, evicted.tree.fragments);
assert_eq!(warm.paint_snapshot(), evicted.paint_snapshot());
}
#[test]
fn owned_construction_late_validation_error_discards_checkout_and_recovers_cold() {
let source = Source::new();
let dependency = Arc::downgrade(&source.hidden_name);
let mut styles = Styles::new();
let mut services = DocumentLayoutServices::new();
let mut work = LayoutWorkingSet::default();
drop(compare_with_cold(
&source,
&mut styles,
&mut services,
&mut work,
));
owned_parts(&work);
drop(source);
assert!(dependency.upgrade().is_some());
let source = Source::new();
styles.first_width = 200.0;
styles.fail_at = Some(3);
styles.visited.clear();
let error = build_layout_pass_with_working_set(
&source,
&mut styles,
&mut services,
LayoutPassRequest::new(LayoutViewport::new(320, 240, 1.0), LayoutFlushReason::Test),
&mut NoFrames,
Some(&mut work),
)
.err()
.expect("later principal style must fail");
assert!(matches!(error, LayoutError::StyleResolution { .. }));
assert_eq!(styles.visited, [0, 1, 3]);
assert!(work.retained.is_none());
assert_eq!(work.stats(), LayoutWorkingSetStats::default());
assert!(dependency.upgrade().is_none());
styles.fail_at = None;
compare_with_cold(&source, &mut styles, &mut services, &mut work);
assert_eq!(work.stats().reused_owned_boxes, 0);
owned_parts(&work);
}
fn assert_medium_owned_construction(paragraphs: usize) {
use style::values::computed::font::{
FamilyName, FontFamily, FontFamilyList, FontFamilyNameSyntax, SingleFontFamily,
};
let mut source = Source::new();
source.nodes = vec![Node::element(Vec::with_capacity(paragraphs))];
for _ in 0..paragraphs {
let owner = source.nodes.len();
source.nodes[0].children.push(owner);
source.nodes.push(Node::element(vec![owner + 1]));
source.nodes.push(Node::text("ABCD"));
}
let mut font = style::properties::style_structs::Font::initial_values();
font.set_font_family(FontFamily {
families: FontFamilyList {
list: style::ArcSlice::from_iter(std::iter::once(SingleFontFamily::FamilyName(
FamilyName {
name: style::Atom::from("Moli Ahem"),
syntax: FontFamilyNameSyntax::Quoted,
},
))),
},
is_system_font: false,
is_initial: false,
});
let mut styles = Styles::new();
styles.hidden = false;
styles.font_style = Some(
ResolvedLayoutStyle::from_stylo(
style::properties::ComputedValues::initial_values_with_font_override(font),
)
.with_text_metrics(16.0, 20.0),
);
let mut services =
DocumentLayoutServices::with_system_font_policy(crate::SystemFontPolicy::Disabled);
services
.register_web_font(crate::WebFontRegistration::new(
"owned-medium-ahem",
crate::WebFontFace::new("Moli Ahem"),
include_bytes!("../../tests/fixtures/moli-ahem.ttf").to_vec(),
))
.unwrap();
let mut work = LayoutWorkingSet::default();
let request =
LayoutPassRequest::with_paint(LayoutViewport::new(1280, 720, 1.0), LayoutFlushReason::Test);
let cold = build_layout_pass_with_working_set(
&source,
&mut styles,
&mut services,
request,
&mut NoFrames,
Some(&mut work),
)
.unwrap();
let retained_capacity = match &work.retained.as_ref().unwrap().graph {
RetainedGraph::Owned { boxes, .. } => (Some(boxes.capacity()), None),
RetainedGraph::Compact(boxes) => (None, Some(boxes.capacity())),
};
eprintln!(
"owned-medium paragraphs={paragraphs} sizeof_layout_box={} owned_capacity={:?} \
compact_capacity={:?} stats={:?}",
std::mem::size_of::<LayoutBox<usize>>(),
retained_capacity.0,
retained_capacity.1,
work.stats(),
);
let construction_count = 1 + 2 * paragraphs;
assert_eq!(work.stats().retained_boxes, construction_count);
assert_eq!(work.stats().retained_boxes, construction_count);
assert_eq!(work.stats().retained_owned_boxes, construction_count);
assert_eq!(work.stats().reused_owned_boxes, 0);
let box_pointer = owned_parts(&work).0.as_ptr();
let box_capacity = owned_parts(&work).0.capacity();
let warm = build_layout_pass_with_working_set(
&source,
&mut styles,
&mut services,
request,
&mut NoFrames,
Some(&mut work),
)
.unwrap();
eprintln!(
"owned-medium-warm paragraphs={paragraphs} owned_capacity={} stats={:?}",
owned_parts(&work).0.capacity(),
work.stats(),
);
assert_eq!(work.stats().retained_owned_boxes, construction_count);
assert_eq!(work.stats().reused_owned_boxes, construction_count);
assert_eq!(owned_parts(&work).0.as_ptr(), box_pointer);
assert_eq!(owned_parts(&work).0.capacity(), box_capacity);
let one_shot = build_layout_pass(&source, &mut styles, &mut services, request).unwrap();
for actual in [&cold, &warm] {
assert_eq!(actual.tree.boxes, one_shot.tree.boxes);
assert_eq!(actual.tree.fragments, one_shot.tree.fragments);
assert_eq!(actual.paint_snapshot(), one_shot.paint_snapshot());
for source in 0..construction_count {
let query = LayoutQuery::ElementMetrics { source };
assert_eq!(actual.answer_query(&query), one_shot.answer_query(&query));
}
}
}
#[test]
fn owned_construction_1024_text_blocks_retain_and_reuse_their_allocation() {
assert_medium_owned_construction(1024);
}
#[test]
fn owned_construction_1152_text_blocks_retain_and_reuse_their_allocation() {
assert_medium_owned_construction(1152);
}
#[test]
fn owned_construction_4096_text_blocks_retain_and_reuse_their_allocation() {
assert_medium_owned_construction(4096);
}
@@ -0,0 +1,204 @@
use super::*;
struct GridStyles {
base: Styles,
first_track: f32,
order: i32,
placement: i16,
auto_flow: taffy::GridAutoFlow,
child_display: Option<LayoutDisplay>,
}
impl GridStyles {
fn new() -> Self {
let mut base = Styles::new();
base.root_display = LayoutDisplay::Grid;
Self {
base,
first_track: 160.0,
order: 0,
placement: 0,
auto_flow: taffy::GridAutoFlow::Row,
child_display: None,
}
}
}
impl LayoutStyleResolver<usize> for GridStyles {
fn element_styles(
&mut self,
node: usize,
) -> Result<Option<ResolvedLayoutElementStyles>, LayoutError> {
let Some(styles) = self.base.element_styles(node)? else {
return Ok(None);
};
let (mut style, _, _) = styles.into_parts();
if node == 0 {
let fixed: taffy::TrackSizingFunction = taffy::style_helpers::length(self.first_track);
let flexible: taffy::TrackSizingFunction = taffy::style_helpers::fr(1.0);
style.taffy.grid_template_columns = vec![fixed.into(), flexible.into()];
style.taffy.grid_template_column_names = vec![Vec::new(); 3];
style.taffy.grid_auto_flow = self.auto_flow;
}
if node == 1 {
style = style.with_order(self.order);
if self.placement != 0 {
style.taffy.grid_column = taffy::Line {
start: taffy::style_helpers::line(self.placement),
end: taffy::style_helpers::span(1),
};
}
if let Some(display) = self.child_display {
style.force_layout_display(display);
}
}
Ok(Some(ResolvedLayoutElementStyles::from_primary(style)))
}
}
fn assert_owned(work: &LayoutWorkingSet<usize>) {
assert!(work.stats().retained_owned_boxes > 0, "{:#?}", work.stats());
owned_parts(work);
}
#[test]
fn grid_owned_objects_refresh_tracks_order_placement_and_auto_flow() {
let source = Source::new();
let mut styles = GridStyles::new();
let mut services = DocumentLayoutServices::new();
let mut work = LayoutWorkingSet::default();
let first = compare_with_cold(&source, &mut styles, &mut services, &mut work);
assert_owned(&work);
let pointer = owned_parts(&work).0.as_ptr();
let capacity = owned_parts(&work).0.capacity();
let children = owned_parts(&work).0[0].children.as_ptr();
let frozen = first.tree.boxes.clone();
let first_tracks = first.answer_query(&LayoutQuery::UsedGridTracks { source: 0 });
for change in 0..4 {
match change {
0 => styles.first_track = 96.0,
1 => styles.order = 2,
2 => styles.placement = 2,
3 => styles.auto_flow = taffy::GridAutoFlow::ColumnDense,
_ => unreachable!(),
}
let current = compare_with_cold(&source, &mut styles, &mut services, &mut work);
assert_eq!(work.stats().reused_owned_boxes, work.stats().retained_boxes);
assert_eq!(owned_parts(&work).0.as_ptr(), pointer);
assert_eq!(owned_parts(&work).0.capacity(), capacity);
assert_eq!(owned_parts(&work).0[0].children.as_ptr(), children);
assert_eq!(first.tree.boxes, frozen);
assert_ne!(
current.answer_query(&LayoutQuery::UsedGridTracks { source: 0 }),
first_tracks
);
}
}
#[test]
fn grid_source_and_display_changes_rebuild_before_warming_again() {
for change in 0..4 {
let mut source = Source::new();
let mut styles = GridStyles::new();
let mut services = DocumentLayoutServices::new();
let mut work = LayoutWorkingSet::default();
compare_with_cold(&source, &mut styles, &mut services, &mut work);
assert_owned(&work);
match change {
0 => source.nodes[0].children.swap(0, 1),
1 => source.nodes[2].text = Some("changed grid item".into()),
2 => styles.base.hidden = false,
3 => styles.base.root_display = LayoutDisplay::Block,
_ => unreachable!(),
}
compare_with_cold(&source, &mut styles, &mut services, &mut work);
assert_eq!(work.stats().reused_owned_boxes, 0);
assert_owned(&work);
compare_with_cold(&source, &mut styles, &mut services, &mut work);
assert!(work.stats().reused_owned_boxes > 0);
}
}
#[test]
fn grid_anonymous_text_and_contents_keep_using_the_shared_cold_builder() {
for contents in [false, true] {
let mut source = Source::new();
let mut styles = GridStyles::new();
let mut services = DocumentLayoutServices::new();
let mut work = LayoutWorkingSet::default();
compare_with_cold(&source, &mut styles, &mut services, &mut work);
if contents {
styles.child_display = Some(LayoutDisplay::Contents);
} else {
source.nodes.push(Node::text("anonymous grid item"));
source.nodes[0].children.insert(0, 6);
}
for _ in 0..2 {
compare_with_cold(&source, &mut styles, &mut services, &mut work);
assert_eq!(work.stats().reused_construction_boxes, 0);
assert_eq!(work.stats().retained_owned_boxes, 0);
assert!(
work.retained
.as_ref()
.unwrap()
.construction_inputs()
.is_none()
);
}
}
}
#[test]
fn grid_ignored_whitespace_and_positioned_items_match_cold_after_style_updates() {
let mut source = Source::new();
source.nodes.push(Node::text(" \n\t "));
source.nodes[0].children.insert(0, 6);
let mut styles = GridStyles::new();
styles.base.positioned = Some((3, crate::LayoutPosition::Absolute));
let mut services = DocumentLayoutServices::new();
let mut work = LayoutWorkingSet::default();
compare_with_cold(&source, &mut styles, &mut services, &mut work);
assert_owned(&work);
styles.first_track = 80.0;
styles.base.first_width = 180.0;
source.scroll = LayoutPoint::new(0.0, 9.0);
source.selection = Some(LayoutTextSelection::new(1, 5));
compare_with_cold(&source, &mut styles, &mut services, &mut work);
assert!(work.stats().reused_owned_boxes > 0);
source.nodes[6].text = Some("now a meaningful grid text item".into());
compare_with_cold(&source, &mut styles, &mut services, &mut work);
assert_eq!(work.stats().retained_owned_boxes, 0);
}
#[test]
fn grid_compact_restoration_and_clear_preserve_current_answers() {
let source = Source::new();
let mut styles = GridStyles::new();
let mut services = DocumentLayoutServices::new();
let mut work = LayoutWorkingSet::default();
compare_with_cold(&source, &mut styles, &mut services, &mut work);
assert_owned(&work);
let owned_charge = work.stats().estimated_retained_bytes;
let mut compact = work.take().unwrap();
compact.compact_graph();
let compact_charge = compact.estimated_retention().total();
assert!(compact_charge < owned_charge);
work.retained = Some(compact);
assert_eq!(work.stats().retained_owned_boxes, 0);
assert!(
work.retained
.as_ref()
.unwrap()
.construction_inputs()
.is_some()
);
styles.first_track = 80.0;
let warm = compare_with_cold(&source, &mut styles, &mut services, &mut work);
assert!(work.stats().reused_construction_boxes > 0);
assert_eq!(work.stats().reused_owned_boxes, 0);
work.clear();
let evicted = compare_with_cold(&source, &mut styles, &mut services, &mut work);
assert_eq!(work.stats().reused_construction_boxes, 0);
assert_eq!(warm.tree.boxes, evicted.tree.boxes);
assert_eq!(warm.paint_snapshot(), evicted.paint_snapshot());
}
@@ -0,0 +1,374 @@
use super::*;
use crate::LayoutTableRole;
struct TableStyles {
base: Styles,
displays: HashMap<usize, LayoutDisplay>,
aspect_ratio: Option<f32>,
}
impl LayoutStyleResolver<usize> for TableStyles {
fn element_styles(
&mut self,
node: usize,
) -> Result<Option<ResolvedLayoutElementStyles>, LayoutError> {
let Some(styles) = self.base.element_styles(node)? else {
return Ok(None);
};
let (mut style, _, _) = styles.into_parts();
let display = self
.displays
.get(&node)
.copied()
.unwrap_or(LayoutDisplay::Block);
style.force_layout_display(display);
style.taffy.size = taffy::Size {
width: taffy::Dimension::auto(),
height: taffy::Dimension::auto(),
};
if node == 0 {
style.taffy.size.width = taffy::Dimension::length(320.0);
}
if node == 4 {
style.taffy.size.width = taffy::Dimension::length(self.base.first_width);
}
style.taffy.aspect_ratio = self.aspect_ratio;
Ok(Some(ResolvedLayoutElementStyles::from_primary(style)))
}
}
fn fixture() -> (Source, TableStyles) {
let mut source = Source::new();
source.nodes = vec![
Node::element(vec![1]),
Node::element(vec![3]),
Node::text("first paragraph"),
Node::element(vec![4, 5]),
Node::element(vec![2]),
Node::element(vec![6]),
Node::text("second paragraph"),
];
for (node, tag, role) in [
(0, "table", LayoutTableRole::Table),
(1, "tbody", LayoutTableRole::BodyGroup),
(3, "tr", LayoutTableRole::Row),
(4, "td", LayoutTableRole::Cell),
(5, "td", LayoutTableRole::Cell),
] {
source.semantics.insert(
node,
LayoutElementSemantics::new(
LayoutNamespace::Html,
tag,
LayoutElementCategory::Table(role),
None,
),
);
}
let mut base = Styles::new();
base.hidden = false;
let styles = TableStyles {
base,
displays: HashMap::from([
(0, LayoutDisplay::Table),
(1, LayoutDisplay::TableRowGroup),
(3, LayoutDisplay::TableRow),
(4, LayoutDisplay::TableCell),
(5, LayoutDisplay::TableCell),
]),
aspect_ratio: None,
};
(source, styles)
}
#[test]
fn table_owned_graph_refreshes_styles_and_preserves_cold_paint_and_queries() {
let (mut source, mut styles) = fixture();
let mut services = DocumentLayoutServices::new();
let mut work = LayoutWorkingSet::default();
let first = compare_with_cold(&source, &mut styles, &mut services, &mut work);
let frozen = first.tree.boxes.clone();
let pointer = owned_parts(&work).0.as_ptr();
let children = owned_parts(&work).0[0].children.as_ptr();
for step in 0..3 {
styles.base.first_width = 180.0 + step as f32 * 10.0;
styles.base.color = PaintColor::new(0.25, 0.5, 0.75, 1.0);
styles.aspect_ratio = Some(1.0 + step as f32);
source.selection = Some(LayoutTextSelection::new(1, 5));
source.label_revision = step + 1;
compare_with_cold(&source, &mut styles, &mut services, &mut work);
assert_eq!(work.stats().reused_owned_boxes, work.stats().retained_boxes);
assert_eq!(owned_parts(&work).0.as_ptr(), pointer);
assert_eq!(owned_parts(&work).0[0].children.as_ptr(), children);
for layout_box in owned_parts(&work).0 {
if layout_box.kind.is_internal_table_box() {
assert!(layout_box.style.taffy.aspect_ratio.is_none());
}
}
assert_eq!(first.tree.boxes, frozen);
}
}
#[test]
fn table_semantic_spans_and_source_order_rebuild_before_warming_again() {
for change in 0..3 {
let (mut source, mut styles) = fixture();
let mut services = DocumentLayoutServices::new();
let mut work = LayoutWorkingSet::default();
compare_with_cold(&source, &mut styles, &mut services, &mut work);
owned_parts(&work);
match change {
0 => {
source
.semantics
.get_mut(&4)
.unwrap()
.metadata
.table
.as_mut()
.unwrap()
.column_span = 2
}
1 => source.nodes[3].children.swap(0, 1),
2 => {
styles.displays.insert(1, LayoutDisplay::TableHeaderGroup);
}
_ => unreachable!(),
}
compare_with_cold(&source, &mut styles, &mut services, &mut work);
assert_eq!(work.stats().reused_owned_boxes, 0);
compare_with_cold(&source, &mut styles, &mut services, &mut work);
assert!(work.stats().reused_owned_boxes > 0);
}
}
#[test]
fn table_anonymous_repair_keeps_using_the_shared_cold_constructor() {
for malformed in [false, true] {
let (mut source, mut styles) = fixture();
let mut services = DocumentLayoutServices::new();
let mut work = LayoutWorkingSet::default();
compare_with_cold(&source, &mut styles, &mut services, &mut work);
if malformed {
styles.displays.insert(4, LayoutDisplay::Block);
} else {
source.nodes.push(Node::text("needs an anonymous cell"));
source.nodes[3].children.insert(0, 7);
}
for _ in 0..2 {
compare_with_cold(&source, &mut styles, &mut services, &mut work);
assert_eq!(work.stats().retained_owned_boxes, 0);
assert_eq!(work.stats().reused_construction_boxes, 0);
}
}
}
#[test]
fn table_compact_restoration_and_clear_preserve_complete_output() {
let (source, mut styles) = fixture();
let mut services = DocumentLayoutServices::new();
let mut work = LayoutWorkingSet::default();
compare_with_cold(&source, &mut styles, &mut services, &mut work);
owned_parts(&work);
let owned = work.stats().estimated_retained_bytes;
let mut retained = work.take().unwrap();
retained.compact_graph();
let compact = retained.estimated_retention().total();
assert!(compact < owned);
work.retained = Some(retained);
styles.base.first_width = 170.0;
let warm = compare_with_cold(&source, &mut styles, &mut services, &mut work);
assert!(work.stats().reused_construction_boxes > 0);
assert_eq!(work.stats().reused_owned_boxes, 0);
work.clear();
let cold = compare_with_cold(&source, &mut styles, &mut services, &mut work);
assert_eq!(work.stats().reused_construction_boxes, 0);
assert_eq!(warm.tree.boxes, cold.tree.boxes);
assert_eq!(warm.paint_snapshot(), cold.paint_snapshot());
}
#[test]
fn table_owned_refresh_normalizes_internal_styles_before_numeric_layout() {
let (source, mut styles) = fixture();
styles.aspect_ratio = Some(1.0);
let world = build_layout_world_with_retained_inputs(&source, &mut styles, None).unwrap();
for layout_box in &world.boxes {
if layout_box.kind.is_internal_table_box() {
assert_eq!(layout_box.style.taffy.aspect_ratio, None);
}
}
let mut work = LayoutWorkingSet::default();
publish(world, &mut work);
owned_parts(&work);
styles.aspect_ratio = Some(2.0);
let mut previous = work.take();
let world =
build_layout_world_with_retained_inputs(&source, &mut styles, previous.as_mut()).unwrap();
assert_eq!(
world
.construction_inputs
.as_ref()
.unwrap()
.reused_owned_boxes(),
world.len()
);
assert_eq!(
world.boxes[world.root.index()].style.taffy.aspect_ratio,
Some(2.0)
);
for layout_box in &world.boxes {
if layout_box.kind.is_internal_table_box() {
assert_eq!(
layout_box.style.taffy.aspect_ratio, None,
"{:?}",
layout_box.kind
);
}
}
}
#[test]
fn table_caption_columns_and_visual_sections_match_the_shared_cold_layout() {
let (mut source, mut styles) = fixture();
source.nodes.extend([
Node::element(vec![8]),
Node::text("caption"),
Node::element(vec![10]),
Node::element(vec![19]),
Node::element(vec![12]),
Node::element(vec![13]),
Node::element(vec![14]),
Node::text("footer"),
Node::element(vec![16]),
Node::element(vec![17]),
Node::element(vec![18]),
Node::text("header"),
Node::text("ignored column descendant"),
]);
source.nodes[0].children = vec![7, 9, 11, 1, 15];
for (node, tag, role, display) in [
(
7,
"caption",
LayoutTableRole::Caption,
LayoutDisplay::TableCaption,
),
(
9,
"colgroup",
LayoutTableRole::ColumnGroup,
LayoutDisplay::TableColumnGroup,
),
(
10,
"col",
LayoutTableRole::Column,
LayoutDisplay::TableColumn,
),
(
11,
"tfoot",
LayoutTableRole::FooterGroup,
LayoutDisplay::TableFooterGroup,
),
(12, "tr", LayoutTableRole::Row, LayoutDisplay::TableRow),
(13, "td", LayoutTableRole::Cell, LayoutDisplay::TableCell),
(
15,
"thead",
LayoutTableRole::HeaderGroup,
LayoutDisplay::TableHeaderGroup,
),
(16, "tr", LayoutTableRole::Row, LayoutDisplay::TableRow),
(17, "td", LayoutTableRole::Cell, LayoutDisplay::TableCell),
] {
source.semantics.insert(
node,
LayoutElementSemantics::new(
LayoutNamespace::Html,
tag,
LayoutElementCategory::Table(role),
None,
),
);
styles.displays.insert(node, display);
}
let mut services = DocumentLayoutServices::new();
let mut work = LayoutWorkingSet::default();
compare_with_cold(&source, &mut styles, &mut services, &mut work);
owned_parts(&work);
// The shared constructor never consumes column descendants.
source.nodes[19].text = Some("still ignored".into());
compare_with_cold(&source, &mut styles, &mut services, &mut work);
assert_eq!(work.stats().reused_owned_boxes, work.stats().retained_boxes);
styles.displays.insert(0, LayoutDisplay::InlineTable);
compare_with_cold(&source, &mut styles, &mut services, &mut work);
assert_eq!(work.stats().reused_owned_boxes, 0);
compare_with_cold(&source, &mut styles, &mut services, &mut work);
assert!(work.stats().reused_owned_boxes > 0);
source
.semantics
.get_mut(&10)
.unwrap()
.metadata
.table
.as_mut()
.unwrap()
.span = 2;
compare_with_cold(&source, &mut styles, &mut services, &mut work);
assert_eq!(work.stats().reused_owned_boxes, 0);
}
#[test]
fn table_discarded_column_group_elements_do_not_enter_the_retained_style_sequence() {
let (mut source, mut styles) = fixture();
source.nodes.extend([
Node::element(vec![8]),
Node::element(vec![9]),
Node::text("discarded"),
]);
source.nodes[0].children.insert(0, 7);
source.semantics.insert(
7,
LayoutElementSemantics::new(
LayoutNamespace::Html,
"colgroup",
LayoutElementCategory::Table(LayoutTableRole::ColumnGroup),
None,
),
);
styles.displays.insert(7, LayoutDisplay::TableColumnGroup);
let mut services = DocumentLayoutServices::new();
let mut work = LayoutWorkingSet::default();
for _ in 0..2 {
compare_with_cold(&source, &mut styles, &mut services, &mut work);
assert_eq!(work.stats().reused_construction_boxes, 0);
assert_eq!(work.stats().retained_owned_boxes, 0);
}
}
#[test]
fn table_inline_wrapper_inside_an_atomic_parent_keeps_current_geometry() {
let (mut source, mut styles) = fixture();
source.nodes[0].children = vec![7];
source.nodes.push(Node::element(vec![1]));
source.semantics.remove(&0);
source.semantics.insert(
7,
LayoutElementSemantics::new(
LayoutNamespace::Html,
"table",
LayoutElementCategory::Table(LayoutTableRole::Table),
None,
),
);
styles.displays.insert(0, LayoutDisplay::Block);
styles.displays.insert(7, LayoutDisplay::InlineTable);
let mut services = DocumentLayoutServices::new();
let mut work = LayoutWorkingSet::default();
compare_with_cold(&source, &mut styles, &mut services, &mut work);
owned_parts(&work);
styles.base.first_width = 200.0;
compare_with_cold(&source, &mut styles, &mut services, &mut work);
assert_eq!(work.stats().reused_owned_boxes, work.stats().retained_boxes);
}
+139
View File
@@ -0,0 +1,139 @@
//! Conservative IFC transfer after the shared constructor changes topology.
//!
//! This does not preserve construction or remap IDs. The first supported local
//! closure is an ordinary source-backed block with direct text children. More
//! complex inline/anonymous/list/table/control structure takes the cold path.
use std::{fmt::Debug, hash::Hash};
use super::{RetainedBoxRef, RetainedWork, same_box_identity, same_inline_input};
use crate::{
LayoutBoxId, LayoutBoxKind, LayoutDisplay, LayoutElementCategory, LayoutNamespace, LayoutWorld,
};
pub(super) fn unchanged_plain_inline_contexts<N>(
previous: &RetainedWork<N>,
current: &LayoutWorld<N>,
) -> (Vec<bool>, usize)
where
N: Copy + Debug + Eq + Hash,
{
let mut unchanged = vec![false; current.len()];
let mut matched_slots = 0;
for (owner, inline) in &previous.inline_contexts {
let Some(old) = previous.box_at(owner.index()) else {
continue;
};
let Some(new) = current.boxes.get(owner.index()) else {
continue;
};
if !plain_block(&old)
|| !old.inline_formatting_context
|| old.children.is_empty()
|| !same_box_identity(&old, new)
|| old.children != new.children
|| !same_inline_input(&old, new)
|| inline.root_style != *owner
|| !inline.objects.is_empty()
|| !inline.structural_boxes.is_empty()
|| !unchanged_ancestor_context(previous, current, *owner)
{
continue;
}
let unchanged_children = old.children.iter().copied().all(|child| {
let Some(old_child) = previous.box_at(child.index()) else {
return false;
};
let Some(new_child) = current.boxes.get(child.index()) else {
return false;
};
old_child.kind == LayoutBoxKind::Text
&& old_child.source.is_some()
&& old_child.owner.is_none()
&& old_child.pseudo.is_none()
&& old_child.anonymous_reason.is_none()
&& !old_child.outside_list_marker
&& !old_child.inline_formatting_context
&& old_child.parent == Some(*owner)
&& old_child.structural_parent == Some(*owner)
&& old_child.children.is_empty()
&& same_box_identity(&old_child, new_child)
&& old_child.children == new_child.children
&& same_inline_input(&old_child, new_child)
});
if !unchanged_children
|| !inline.references_only(|id| id == *owner || old.children.contains(&id))
{
continue;
}
unchanged[owner.index()] = true;
// These closures cannot overlap: each consists of one block and its
// direct Text leaves. Changed ancestor child lists are not counted as
// reused construction identities, nor is the shared builder skipped.
matched_slots += 1 + old.children.len();
}
(unchanged, matched_slots)
}
fn plain_block<N>(layout_box: &RetainedBoxRef<'_, N>) -> bool {
layout_box.source.is_some()
&& layout_box.owner.is_none()
&& layout_box.pseudo.is_none()
&& layout_box.anonymous_reason.is_none()
&& !layout_box.outside_list_marker
&& layout_box.structural_parent == layout_box.parent
&& matches!(
layout_box.kind,
LayoutBoxKind::PrincipalBlock | LayoutBoxKind::PrincipalFlowRoot
)
&& matches!(
layout_box.inline_style.display,
LayoutDisplay::Block | LayoutDisplay::FlowRoot
)
&& !layout_box.inline_style.out_of_flow
&& !layout_box.inline_style.floated
&& layout_box
.element_semantics
.as_ref()
.is_some_and(|semantics| {
semantics.namespace == LayoutNamespace::Html
&& semantics.category == LayoutElementCategory::Generic
&& semantics.replaced.is_none()
&& semantics.metadata.form_control.is_none()
})
}
fn unchanged_ancestor_context<N>(
previous: &RetainedWork<N>,
current: &LayoutWorld<N>,
owner: LayoutBoxId,
) -> bool
where
N: Copy + Debug + Eq + Hash,
{
let mut child = owner;
let mut parent = previous.box_at(owner.index()).unwrap().parent;
// Both graphs came from the shared constructor. Parent identities name
// their actual edges; do not scan every sibling list once per paragraph.
// The bound also makes a malformed cycle an ordinary reuse rejection.
for _ in 0..previous.box_count() {
let Some(id) = parent else {
return child == previous.root;
};
let Some(old) = previous.box_at(id.index()) else {
return false;
};
let Some(new) = current.boxes.get(id.index()) else {
return false;
};
if !plain_block(&old) || !same_box_identity(&old, new) || !same_inline_input(&old, new) {
return false;
}
// Siblings are not plain-text shaping inputs. Their construction,
// numeric constraints, floats, positioning and projection are fresh.
// Eligible final numeric reuse still checks its existing full key.
child = id;
parent = old.parent;
}
false
}
+232
View File
@@ -0,0 +1,232 @@
use std::{fmt::Debug, hash::Hash, sync::Arc};
use super::{InlineStyleInputs, RetainedBox, RetainedGraph, RetainedWork};
use crate::{
LayoutBoxId, LayoutNamespace, LayoutWorld, inline::InlineFormattingContext,
text::LayoutFontInputs,
};
fn allocation<T>(capacity: usize) -> usize {
capacity.saturating_mul(std::mem::size_of::<T>())
}
pub(super) struct RetentionEstimate {
pub(super) graph: usize,
pub(super) construction: usize,
pub(super) inline: usize,
pub(super) inline_numeric: usize,
pub(super) font_metadata: usize,
}
impl RetentionEstimate {
pub(super) fn total(&self) -> usize {
self.graph
.saturating_add(self.inline)
.saturating_add(self.font_metadata)
}
}
impl<N> RetainedWork<N>
where
N: Copy + Debug + Eq + Hash,
{
pub(super) fn from_world(
mut world: LayoutWorld<N>,
fonts: LayoutFontInputs,
pass_box_count: usize,
) -> Self {
let mut inline_numeric_reuse = world.inline_numeric_reuse.take();
if let Some(numeric) = &mut inline_numeric_reuse {
let mut has_retained_output = false;
numeric.retain_owners(|owner| {
let keep = world
.inline_layouts
.get(owner.index())
.and_then(Option::as_ref)
.is_some_and(|inline| inline.laid_out.is_some());
has_retained_output |= keep;
keep
});
if !has_retained_output {
inline_numeric_reuse = None;
}
}
let inline_count = world
.inline_layouts
.iter()
.filter(|inline| inline.is_some())
.count();
let mut inline_contexts = Vec::with_capacity(inline_count);
for (index, inline) in world.inline_layouts.iter_mut().enumerate() {
if let Some(mut inline) = inline.take() {
let owner = LayoutBoxId::from_index(index);
let preserve_numeric = inline_numeric_reuse
.as_ref()
.is_some_and(|numeric| numeric.contains(owner));
inline.prepare_for_retention(preserve_numeric);
inline_contexts.push((owner, inline));
}
}
let graph = if world.construction_inputs.is_some() {
for layout_box in &mut world.boxes {
// Retain construction ownership, not derived numeric results
// or paint resources. Clearing a length would still pin its
// backing allocation, so release pass-local containers here.
layout_box.layout_parent = None;
layout_box.layout_children = Vec::new();
layout_box.positioned_containing_block = None;
layout_box.inline_static_position = None;
layout_box.inline_context_owner = None;
layout_box.inline_flattened = false;
layout_box.scroll_offset = crate::LayoutPoint::ZERO;
layout_box.replaced_context = None;
layout_box.replaced_image = None;
layout_box.css_images = Default::default();
layout_box.collapsed_table_border_part = false;
layout_box.clear_numeric_cache_slot();
layout_box.table_measure_cache = None;
layout_box.unrounded_layout = taffy::Layout::with_order(0);
layout_box.final_layout = taffy::Layout::with_order(0);
layout_box.capability_diagnostics = Vec::new();
layout_box.style.prepare_for_construction_retention();
}
RetainedGraph::Owned {
boxes: std::mem::take(&mut world.boxes),
source_mapping: std::mem::take(&mut world.source_mapping),
}
} else {
RetainedGraph::Compact(compact_boxes(std::mem::take(&mut world.boxes)))
};
Self {
graph,
prepared_inline_inputs: None,
construction_inputs: world.construction_inputs.take(),
pass_box_count,
inline_contexts,
inline_numeric_reuse,
root: world.root,
root_is_document_element: world.root_is_document_element,
quirks_mode: world.quirks_mode,
fonts,
}
}
/// Compare compact and owned representations in tests. Production retains
/// owned construction when the graph supports it.
#[cfg(test)]
pub(super) fn compact_graph(&mut self) {
let old = std::mem::replace(&mut self.graph, RetainedGraph::Compact(Vec::new()));
self.graph = match old {
RetainedGraph::Owned { boxes, .. } => RetainedGraph::Compact(compact_boxes(boxes)),
compact => compact,
};
}
pub(super) fn estimated_retention(&self) -> RetentionEstimate {
let construction = self
.construction_inputs
.as_ref()
.map_or(0, |inputs| inputs.estimated_retained_bytes());
let storage = match &self.graph {
RetainedGraph::Compact(boxes) => allocation::<RetainedBox<N>>(boxes.capacity()),
RetainedGraph::Owned {
boxes,
source_mapping,
} => {
// HashMap exposes usable capacity, not allocator bucket bytes.
// Conservatively allow two bucket slots per usable entry plus
// controls; this is a storage estimate, not physical memory.
let buckets = source_mapping.capacity().saturating_mul(2);
let mapping = allocation::<(N, LayoutBoxId)>(buckets)
.saturating_add(buckets)
.saturating_add(16);
let labels = boxes.iter().fold(0usize, |bytes, layout_box| {
bytes
.saturating_add(layout_box.source_label.capacity())
.saturating_add(layout_box.owner_label.as_ref().map_or(0, String::capacity))
});
allocation::<crate::LayoutBox<N>>(boxes.capacity())
.saturating_add(mapping)
.saturating_add(labels)
}
};
let mut graph = std::mem::size_of::<Self>()
.saturating_add(storage)
.saturating_add(construction);
let child_capacity = match &self.graph {
RetainedGraph::Compact(boxes) => boxes.iter().map(|b| b.children.capacity()).sum(),
RetainedGraph::Owned { boxes, .. } => boxes.iter().map(|b| b.children.capacity()).sum(),
};
graph = graph.saturating_add(allocation::<LayoutBoxId>(child_capacity));
for layout_box in self.construction_boxes() {
graph = graph.saturating_add(layout_box.text.map_or(0, |text| text.len()));
if let Some(semantics) = &layout_box.element_semantics {
graph = graph.saturating_add(semantics.local_name.len());
if let LayoutNamespace::Other(namespace) = &semantics.namespace {
graph = graph.saturating_add(namespace.len());
}
if let Some(control) = &semantics.metadata.form_control {
graph = graph
.saturating_add(control.value.len())
.saturating_add(control.placeholder.len())
.saturating_add(allocation::<Arc<str>>(control.option_labels.capacity()));
graph = control
.option_labels
.iter()
.fold(graph, |bytes, label| bytes.saturating_add(label.len()));
}
}
}
// The IFC estimator excludes the struct itself. Charge its actual
// vector slot here, only for real IFC owners, alongside owned buffers
// and the existing model for opaque Parley paragraph storage.
let inline_preparation = self.inline_contexts.iter().fold(
allocation::<(LayoutBoxId, InlineFormattingContext)>(self.inline_contexts.capacity()),
|bytes, (_, inline)| {
bytes.saturating_add(inline.estimated_retained_preparation_bytes())
},
);
// Final output vectors remain owned by eligible IFCs. The sidecar
// accounts for its own allocation and key storage; neither estimate
// substitutes source length for visible output-buffer capacities.
let inline_numeric = self.inline_contexts.iter().fold(
self.inline_numeric_reuse
.as_ref()
.map_or(0, |numeric| numeric.estimated_retained_bytes()),
|bytes, (_, inline)| bytes.saturating_add(inline.estimated_retained_numeric_bytes()),
);
RetentionEstimate {
graph,
construction,
inline: inline_preparation.saturating_add(inline_numeric),
inline_numeric,
font_metadata: self.fonts.estimated_metadata_bytes(),
}
}
}
fn compact_boxes<N>(boxes: Vec<crate::LayoutBox<N>>) -> Vec<RetainedBox<N>> {
// Never use an in-place IntoIter collect: the large LayoutBox allocation
// must actually be released before charging the compact representation.
let mut compact = Vec::with_capacity(boxes.len());
for mut layout_box in boxes {
compact.push(RetainedBox {
source: layout_box.source,
owner: layout_box.owner,
pseudo: layout_box.pseudo,
kind: layout_box.kind,
anonymous_reason: layout_box.anonymous_reason,
structural_parent: layout_box.structural_parent,
parent: layout_box.parent,
children: std::mem::take(&mut layout_box.children),
inline_formatting_context: layout_box.inline_formatting_context,
outside_list_marker: layout_box.outside_list_marker,
inline_style: InlineStyleInputs::from_style(&layout_box.style),
computed: layout_box.style.computed.take(),
element_semantics: layout_box.element_semantics.take(),
text: layout_box.text.take(),
text_selection: layout_box.text_selection,
});
}
compact
}
+162
View File
@@ -0,0 +1,162 @@
use std::sync::Arc;
use super::*;
use crate::{
DocumentLayoutServices, LayoutBoxKind, LayoutDisplay, LayoutElementCategory,
LayoutElementSemantics, LayoutFormControlData, LayoutImageResource, LayoutNamespace,
PaintColor, ResolvedLayoutStyle,
};
pub(super) fn world(text: Option<Arc<str>>) -> LayoutWorld<usize> {
LayoutWorld::new(
LayoutWorld::new_box(
Some(0),
Some(0),
None,
"root".into(),
Some("root".into()),
None,
None,
LayoutBoxKind::PrincipalBlock,
ResolvedLayoutStyle::synthetic(
LayoutDisplay::Block,
taffy::Style::default(),
PaintColor::TRANSPARENT,
),
text,
),
true,
)
}
#[test]
fn retained_work_drops_pass_image_resources_but_keeps_reusable_source_inputs() {
let pixels = Arc::new(moli_image::RgbaImage::try_new(1, 1, vec![0; 4]).unwrap());
let image_weak = Arc::downgrade(&pixels);
let resource = LayoutImageResource {
intrinsic_width: 1.0,
intrinsic_height: 1.0,
pixels: Some(pixels),
svg: None,
};
let text: Arc<str> = Arc::from("retained input");
let text_weak = Arc::downgrade(&text);
let mut world = world(Some(text));
world.boxes[0].replaced_image = Some(resource.clone());
world.boxes[0].css_images.background = vec![Some(resource.clone())];
world.boxes[0].css_images.mask = vec![Some(resource)];
let fonts = DocumentLayoutServices::new().font_inputs();
let mut work = LayoutWorkingSet::default();
work.publish(world, fonts, 0, 0, 1);
assert_eq!(work.stats().retained_boxes, 1);
assert!(
image_weak.upgrade().is_none(),
"working state must not pin paint images"
);
assert!(
text_weak.upgrade().is_some(),
"source comparison still owns its input"
);
work.clear();
assert!(
text_weak.upgrade().is_none(),
"eviction must release retained source inputs"
);
assert_eq!(work.stats().estimated_retained_bytes, 0);
}
#[test]
fn retained_control_payload_capacity_is_reported_and_released_on_clear() {
fn control_world(label: Arc<str>) -> LayoutWorld<usize> {
let mut world = world(None);
let mut semantics = LayoutElementSemantics::new(
LayoutNamespace::Html,
"select",
LayoutElementCategory::Generic,
None,
);
semantics.metadata.form_control = Some(LayoutFormControlData {
option_labels: vec![label],
..LayoutFormControlData::default()
});
world.boxes[0].element_semantics = Some(semantics);
world
}
let fonts = DocumentLayoutServices::new().font_inputs();
let mut baseline = LayoutWorkingSet::default();
baseline.publish(control_world(Arc::from("")), fonts.clone(), 0, 0, 1);
let mut work = LayoutWorkingSet::default();
let label: Arc<str> = Arc::from("a".repeat(64 * 1024));
let label_weak = Arc::downgrade(&label);
work.publish(control_world(label), fonts, 0, 0, 1);
let stats = work.stats();
assert!(stats.estimated_retained_bytes > baseline.stats().estimated_retained_bytes);
assert_eq!(stats.retained_boxes, 1);
assert_eq!(stats.retained_text_bytes, 0);
assert_eq!(
stats.estimated_retained_bytes,
stats.estimated_graph_bytes
+ stats.estimated_inline_bytes
+ stats.estimated_font_metadata_bytes
);
assert!(label_weak.upgrade().is_some());
work.clear();
assert!(label_weak.upgrade().is_none());
}
#[test]
fn numeric_placeholders_do_not_survive_as_construction_graph_members() {
let mut previous = world(None);
let placeholder = world(None).boxes.remove(0);
let placeholder_id = previous.allocate(placeholder);
previous.boxes[0].layout_children.push(placeholder_id);
let fonts = DocumentLayoutServices::new().font_inputs();
let mut work = LayoutWorkingSet::default();
work.publish(previous, fonts.clone(), 0, 0, 1);
assert_eq!(work.stats().retained_boxes, 1);
let (fresh, reused) = update_working_tree(work.take(), world(None), &fonts);
assert_eq!(
reused, 1,
"numeric-only boxes must not invalidate a stable graph"
);
assert_eq!(fresh.boxes.len(), 1);
assert!(fresh.boxes[0].layout_children.is_empty());
}
#[test]
fn compact_retention_discards_pass_only_allocation_capacity() {
let fonts = DocumentLayoutServices::new().font_inputs();
let mut baseline = LayoutWorkingSet::default();
baseline.publish(world(None), fonts.clone(), 0, 0, 1);
let baseline_bytes = baseline.stats().estimated_retained_bytes;
let mut work = LayoutWorkingSet::default();
let mut pass = world(None);
// Pass capacity can outlive its numeric placeholders until publication.
// Retaining that full LayoutBox allocation defeats the compact graph.
pass.boxes.reserve(1024);
work.publish(pass, fonts, 0, 0, 1);
assert_eq!(work.stats().retained_boxes, 1);
assert_eq!(work.stats().estimated_retained_bytes, baseline_bytes);
}
#[test]
fn retained_text_above_the_former_document_limit_survives_until_clear() {
let text: Arc<str> = Arc::from("x".repeat(512 * 1024));
let weak = Arc::downgrade(&text);
let mut work = LayoutWorkingSet::default();
work.publish(
world(Some(text)),
DocumentLayoutServices::new().font_inputs(),
0,
0,
1,
);
assert_eq!(work.stats().retained_text_bytes, 512 * 1024);
assert!(weak.upgrade().is_some());
work.clear();
assert!(weak.upgrade().is_none());
}
+74 -15
View File
@@ -247,8 +247,6 @@ pub struct LayoutBox<N> {
pub(crate) style: ResolvedLayoutStyle,
pub(crate) text: Option<Arc<str>>,
pub(crate) text_selection: Option<crate::LayoutTextSelection>,
/// Shared text/inline layout owned by this formatting-context root.
pub(crate) inline_layout: Option<InlineFormattingContext>,
/// Outermost IFC that consumes this box as a flattened or atomic item.
pub(crate) inline_context_owner: Option<LayoutBoxId>,
/// Text, `<br>`, and non-atomic inline boxes are laid out by their owner IFC
@@ -541,6 +539,11 @@ impl Default for ViewportLayoutState {
}
impl<N> LayoutBox<N> {
/// A retained construction box must not refer into a dropped world's cache.
pub(crate) fn clear_numeric_cache_slot(&mut self) {
self.cache_slot = None;
}
pub fn kind(&self) -> LayoutBoxKind {
self.kind
}
@@ -641,6 +644,10 @@ where
pub(crate) resolved_grid_tracks: HashMap<LayoutBoxId, LayoutResolvedGridTracks>,
/// Native track positions and names read by Taffy's out-of-flow pass.
pub(crate) native_grid_details: HashMap<LayoutBoxId, DetailedLayoutInfo<Atom>>,
/// Pass-only IFC scratch indexed by construction/numeric box ID. Keep its
/// large empty slots out of persistent box objects. Retention extracts
/// only actual owners into the existing sparse working-set storage.
pub(crate) inline_layouts: Vec<Option<InlineFormattingContext>>,
pub(crate) source_mapping: HashMap<N, LayoutBoxId>,
pub(crate) display_contents_mapping: HashMap<N, Vec<LayoutBoxId>>,
pub(crate) root: LayoutBoxId,
@@ -652,6 +659,12 @@ where
pub(crate) viewport_scroll_policy: ViewportScrollPolicy,
pub(crate) viewport_layout: ViewportLayoutState,
pub(crate) css_image_references: Vec<LayoutCssImageReference<N>>,
/// Optional source dependencies for validating a retained construction
/// graph. Ordinary one-shot construction creates no dependency storage.
pub(crate) construction_inputs: Option<Box<crate::builder::ConstructionInputs<N>>>,
/// Optional accepted inline results for callers retaining computation
/// across passes. One-shot callers allocate no per-box reuse metadata.
pub(crate) inline_numeric_reuse: Option<Box<crate::inline::InlineNumericReuse>>,
/// Full numeric measurement retains baselines without publishing layouts.
pub(crate) measure_baselines: bool,
/// The active table cell's used height need not be a percentage guarantee.
@@ -666,13 +679,26 @@ where
N: Copy + Debug + Eq + Hash,
{
pub(crate) fn new(root: LayoutBox<N>, root_is_document_element: bool) -> Self {
Self::from_construction(vec![root], HashMap::new(), root_is_document_element)
}
/// Installs the unique owned construction graph with fresh pass-local
/// environment, viewport and numeric bookkeeping. The graph's vector and
/// child allocations are moved, never materialized from comparison records.
pub(crate) fn from_construction(
boxes: Vec<LayoutBox<N>>,
source_mapping: HashMap<N, LayoutBoxId>,
root_is_document_element: bool,
) -> Self {
let count = boxes.len();
Self {
boxes: vec![root],
boxes,
box_caches: Vec::new(),
collapsed_table_borders: HashMap::new(),
resolved_grid_tracks: HashMap::new(),
native_grid_details: HashMap::new(),
source_mapping: HashMap::new(),
source_mapping,
inline_layouts: Vec::new(),
display_contents_mapping: HashMap::new(),
root: LayoutBoxId::from_index(0),
root_is_document_element,
@@ -681,11 +707,13 @@ where
viewport_scroll_policy: ViewportScrollPolicy::default(),
viewport_layout: ViewportLayoutState::default(),
css_image_references: Vec::new(),
construction_inputs: None,
inline_numeric_reuse: None,
measure_baselines: false,
table_cell_percentage_height: None,
numeric_layout_tracking: false,
numeric_layout_touched: Vec::new(),
numeric_layout_touched_marks: vec![false],
numeric_layout_touched_marks: vec![false; count],
}
}
@@ -725,10 +753,23 @@ where
&mut self.box_caches[(slot.get() - 1) as usize]
}
pub(crate) fn prepare_inline_storage(&mut self) {
self.inline_layouts.resize_with(self.boxes.len(), || None);
}
pub fn root(&self) -> LayoutBoxId {
self.root
}
/// A validated graph knows its required extent. Reserve once before
/// materializing it instead of repeatedly moving the large box records.
/// This is only a pass-local allocation hint, including prior numeric-only
/// records; it neither restores those records nor creates source mappings.
pub(crate) fn reserve_box_capacity(&mut self, count: usize) {
self.boxes
.reserve_exact(count.saturating_sub(self.boxes.len()));
}
pub(crate) fn is_viewport_defining_body(&self, id: LayoutBoxId) -> bool {
self.viewport_scroll_policy.defining_body() == Some(id)
}
@@ -853,6 +894,9 @@ where
pub(crate) fn allocate(&mut self, layout_box: LayoutBox<N>) -> LayoutBoxId {
let id = LayoutBoxId::from_index(self.boxes.len());
self.boxes.push(layout_box);
if !self.inline_layouts.is_empty() {
self.inline_layouts.push(None);
}
self.numeric_layout_touched_marks.push(false);
id
}
@@ -970,6 +1014,10 @@ where
}
}
// Construction normalization precedes IFC preparation. No prepared
// references may be silently remapped by this source-tree compaction.
assert!(self.inline_layouts.iter().all(Option::is_none));
self.inline_layouts = Vec::new();
let mut compacted = Vec::with_capacity(next_index);
for (index, mut layout_box) in self.boxes.drain(..).enumerate() {
if !reachable[index] {
@@ -1185,6 +1233,26 @@ where
Ok(())
}
pub(crate) fn refresh_box_style(layout_box: &mut LayoutBox<N>, mut style: ResolvedLayoutStyle) {
Self::normalize_box_style(layout_box.kind, &mut style);
layout_box.capability_diagnostics = default_capability_diagnostics(
layout_box.kind,
layout_box.element_semantics.as_ref(),
&style,
);
layout_box.style = style;
}
fn normalize_box_style(kind: LayoutBoxKind, style: &mut ResolvedLayoutStyle) {
if kind.is_internal_table_box() {
// Keep the authored/computed value in `preferred_aspect_ratio`.
// The table formatter supplies internal track and cell sizes;
// construction and retained refresh must suppress the same
// numeric projection before generic sizing consumes it.
style.taffy.aspect_ratio = None;
}
}
pub(crate) fn new_box(
source: Option<N>,
owner: Option<N>,
@@ -1197,15 +1265,7 @@ where
mut style: ResolvedLayoutStyle,
text: Option<Arc<str>>,
) -> LayoutBox<N> {
if kind.is_internal_table_box() {
// Keep the authored/computed value in `preferred_aspect_ratio`.
// Only the numeric backend projection is suppressed: CSS Sizing
// excludes internal table boxes from `aspect-ratio`, and the table
// formatter supplies their used track and cell sizes. Chromium
// represents the same boundary with its table-cell constraint
// space before generic block-size resolution.
style.taffy.aspect_ratio = None;
}
Self::normalize_box_style(kind, &mut style);
let capability_diagnostics =
default_capability_diagnostics(kind, element_semantics.as_ref(), &style);
LayoutBox {
@@ -1228,7 +1288,6 @@ where
style,
text,
text_selection: None,
inline_layout: None,
inline_context_owner: None,
inline_flattened: false,
outside_list_marker: false,
@@ -16,6 +16,15 @@ use taffy::{
style_helpers::{length, percent},
};
#[path = "phase5_output_contract/working_set.rs"]
mod working_set;
#[path = "phase5_output_contract/working_set_construction.rs"]
mod working_set_construction;
#[path = "phase5_output_contract/working_set_numeric.rs"]
mod working_set_numeric;
#[path = "phase5_output_contract/working_set_styles.rs"]
mod working_set_styles;
#[derive(Clone)]
struct Node {
label: &'static str,
@@ -0,0 +1,394 @@
use super::*;
use moli_layout::{
EmbeddedFrameRenderer, EmbeddedFrameSnapshot, LayoutWorkingSet, WebFontFace,
WebFontRegistration, build_layout_pass_with_working_set,
};
struct NoFrames;
impl EmbeddedFrameRenderer<usize> for NoFrames {
fn render_embedded_frame(
&mut self,
_: usize,
_: LayoutViewport,
) -> Result<Option<EmbeddedFrameSnapshot<usize>>, LayoutError> {
Ok(None)
}
}
fn fixture() -> (Source, Styles, DocumentLayoutServices) {
let source = Source(vec![
Node::element("root", vec![1, 3]),
Node::element("first", vec![2]),
Node::text("first-text", "alpha beta gamma delta epsilon"),
Node::element("second", vec![4]),
Node::text("second-text", "one two three four five six"),
]);
let (mut font_style, services) = fixed_inline_font();
font_style.force_layout_display(LayoutDisplay::Block);
let styles = Styles(HashMap::from([
(0, resolved(LayoutDisplay::Block, Style::default())),
(1, font_style.clone()),
(3, font_style),
]));
(source, styles, services)
}
fn compare_pass(
source: &Source,
styles: &mut Styles,
services: &mut DocumentLayoutServices,
work: &mut LayoutWorkingSet<usize>,
width: u32,
) -> LayoutPassResult<usize> {
compare_source_pass(source, source.0.len(), styles, services, work, width)
}
fn compare_source_pass(
source: &impl LayoutSource<NodeId = usize>,
node_count: usize,
styles: &mut Styles,
services: &mut DocumentLayoutServices,
work: &mut LayoutWorkingSet<usize>,
width: u32,
) -> LayoutPassResult<usize> {
let request = LayoutPassRequest::with_paint(
LayoutViewport::new(width, 240, 1.0),
LayoutFlushReason::Test,
);
let retained = build_layout_pass_with_working_set(
source,
styles,
services,
request,
&mut NoFrames,
Some(work),
)
.unwrap();
let fresh = build_layout_pass(source, styles, services, request).unwrap();
assert_eq!(retained.tree.boxes, fresh.tree.boxes);
assert_eq!(retained.tree.fragments, fresh.tree.fragments);
assert_eq!(retained.paint_snapshot(), fresh.paint_snapshot());
for node in 0..node_count {
for query in [
LayoutQuery::ElementMetrics { source: node },
LayoutQuery::TextRangeRects {
source: node,
utf16_range: 0..usize::MAX,
},
LayoutQuery::IntersectionGeometry {
target: node,
root: None,
},
] {
assert_eq!(retained.answer_query(&query), fresh.answer_query(&query));
}
}
for y in (0..240).step_by(8) {
for x in (0..width).step_by(8) {
let point = LayoutPoint::new(x as f32, y as f32);
assert_eq!(
retained.hit_test(point, false),
fresh.hit_test(point, false)
);
}
}
retained
}
struct DynamicInputs {
source: Source,
selection: Option<moli_layout::LayoutTextSelection>,
image_size: Option<f32>,
}
impl LayoutSource for DynamicInputs {
type NodeId = usize;
type ChildIter<'a> = <Source as LayoutSource>::ChildIter<'a>;
fn root(&self) -> usize {
self.source.root()
}
fn flat_parent(&self, node: usize) -> Option<usize> {
self.source.flat_parent(node)
}
fn flat_children(&self, node: usize) -> Self::ChildIter<'_> {
self.source.flat_children(node)
}
fn node_kind(&self, node: usize) -> LayoutSourceKind {
self.source.node_kind(node)
}
fn text(&self, node: usize) -> Option<&str> {
self.source.text(node)
}
fn label(&self, node: usize) -> String {
self.source.label(node)
}
fn element_semantics(&self, node: usize) -> Option<LayoutElementSemantics> {
if node == 5 {
Some(LayoutElementSemantics::new(
LayoutNamespace::Html,
"img",
LayoutElementCategory::Generic,
Some(moli_layout::LayoutReplacedKind::Image),
))
} else {
self.source.element_semantics(node)
}
}
fn text_selection(&self, node: usize) -> Option<moli_layout::LayoutTextSelection> {
(node == 2).then_some(self.selection).flatten()
}
fn replaced_metrics(&self, node: usize) -> Option<moli_layout::ReplacedMetrics> {
(node == 5).then(|| moli_layout::ReplacedMetrics {
intrinsic_width: self.image_size,
intrinsic_height: self.image_size,
..Default::default()
})
}
}
#[test]
fn retained_work_updates_selection_and_inline_image_sizes() {
let (source, mut styles, mut services) = fixture();
let mut source = DynamicInputs {
source,
selection: None,
image_size: Some(20.0),
};
source
.source
.0
.push(Node::html_element("image", "img", vec![]));
source.source.0[1].children.push(5);
let mut image_style = styles.0[&1].clone();
image_style.force_layout_display(LayoutDisplay::Inline);
styles.0.insert(5, image_style);
let mut work = LayoutWorkingSet::default();
compare_source_pass(&source, 6, &mut styles, &mut services, &mut work, 100);
for size in [45.0, 0.0, 180.0, 20.0] {
source.image_size = Some(size);
let pass = compare_source_pass(&source, 6, &mut styles, &mut services, &mut work, 100);
assert_eq!(work.stats().reused_inline_contexts, 2);
assert_eq!(
pass.tree
.element_metrics_for_source(5)
.unwrap()
.offset_size
.width,
size
);
}
for selection in [
Some(moli_layout::LayoutTextSelection::new(0, 10)),
Some(moli_layout::LayoutTextSelection::new(4, 4)),
None,
] {
source.selection = selection;
compare_source_pass(&source, 6, &mut styles, &mut services, &mut work, 100);
assert_eq!(work.stats().reused_inline_contexts, 1);
compare_source_pass(&source, 6, &mut styles, &mut services, &mut work, 100);
assert_eq!(work.stats().reused_inline_contexts, 2);
}
}
#[test]
fn retained_work_tracks_active_stylesheet_fonts_across_temporary_services() {
let (source, mut styles, mut services) = fixture();
// Memberships are cumulative: retire the fixture's manual registration
// before testing a face that is available only through its stylesheet.
assert!(services.remove_web_font("fixed"));
services
.register_web_font(
WebFontRegistration::new(
"fixed",
WebFontFace::new("Moli Ahem"),
include_bytes!("../fixtures/moli-ahem.ttf").to_vec(),
)
.with_stylesheet_scope(),
)
.unwrap();
let mut work = LayoutWorkingSet::default();
compare_pass(&source, &mut styles, &mut services, &mut work, 100);
for active in [false, true, false, true] {
services.with_active_stylesheet_fonts(
|_| active,
|selected| {
compare_pass(&source, &mut styles, selected, &mut work, 100);
assert_eq!(work.stats().reused_inline_contexts, 0);
},
);
services.with_active_stylesheet_fonts(
|_| active,
|selected| {
compare_pass(&source, &mut styles, selected, &mut work, 100);
assert_eq!(work.stats().reused_inline_contexts, 2);
},
);
}
}
#[test]
fn retained_work_rebreaks_text_for_current_constraints_and_survives_eviction() {
let (source, mut styles, mut services) = fixture();
let mut work = LayoutWorkingSet::default();
let first = compare_pass(&source, &mut styles, &mut services, &mut work, 320);
assert_eq!(work.stats().retained_boxes, 5);
assert_eq!(work.stats().reused_inline_contexts, 0);
let narrow = compare_pass(&source, &mut styles, &mut services, &mut work, 80);
assert_eq!(work.stats().reused_box_slots, 5);
assert_eq!(work.stats().reused_inline_contexts, 2);
assert!(
narrow.text_range_rects(2, 0..usize::MAX).len()
> first.text_range_rects(2, 0..usize::MAX).len()
);
for width in [240, 64, 400, 80, 320] {
compare_pass(&source, &mut styles, &mut services, &mut work, width);
assert_eq!(work.stats().reused_inline_contexts, 2);
work.clear();
compare_pass(&source, &mut styles, &mut services, &mut work, width);
assert_eq!(work.stats().reused_inline_contexts, 0);
}
}
#[test]
fn retained_work_invalidates_changed_text_and_style_without_discarding_other_paragraphs() {
let (mut source, mut styles, mut services) = fixture();
let mut work = LayoutWorkingSet::default();
compare_pass(&source, &mut styles, &mut services, &mut work, 100);
source.0[2].text = Some("changed content wraps onto different lines");
compare_pass(&source, &mut styles, &mut services, &mut work, 100);
assert_eq!(work.stats().reused_inline_contexts, 1);
let changed = styles.0[&1].clone().with_text_metrics(24.0, 30.0);
styles.0.insert(1, changed);
compare_pass(&source, &mut styles, &mut services, &mut work, 100);
assert_eq!(work.stats().reused_inline_contexts, 1);
compare_pass(&source, &mut styles, &mut services, &mut work, 100);
assert_eq!(work.stats().reused_inline_contexts, 2);
}
#[test]
fn retained_work_retires_box_ids_when_structure_changes() {
let (mut source, mut styles, mut services) = fixture();
let mut work = LayoutWorkingSet::default();
compare_pass(&source, &mut styles, &mut services, &mut work, 100);
// Reordering keeps the same node count but gives the constructor different
// box IDs. No old inline source map may survive this graph replacement.
source.0[0].children.reverse();
compare_pass(&source, &mut styles, &mut services, &mut work, 100);
assert_eq!(work.stats().reused_box_slots, 0);
assert_eq!(work.stats().reused_inline_contexts, 0);
styles
.0
.get_mut(&1)
.unwrap()
.force_layout_display(LayoutDisplay::Inline);
compare_pass(&source, &mut styles, &mut services, &mut work, 100);
assert_eq!(work.stats().reused_box_slots, 0);
compare_pass(&source, &mut styles, &mut services, &mut work, 100);
assert!(work.stats().reused_inline_contexts > 0);
source.0[0].children.retain(|node| *node != 1);
compare_pass(&source, &mut styles, &mut services, &mut work, 100);
assert_eq!(work.stats().reused_box_slots, 0);
}
#[test]
fn numeric_static_placeholders_do_not_retire_unchanged_text_inputs() {
let (mut source, mut styles, mut services) = fixture();
source.0[0].children.push(5);
source.0.extend([
Node::element("static-block", vec![6, 7]),
Node::element("content", vec![]),
Node::element("absolute", vec![]),
]);
styles
.0
.insert(5, fixed_size(LayoutDisplay::Block, 100.0, 50.0));
styles
.0
.insert(6, fixed_size(LayoutDisplay::Block, 80.0, 30.0));
styles.0.insert(
7,
fixed_size(LayoutDisplay::Block, 20.0, 20.0).with_position(LayoutPosition::Absolute),
);
let mut work = LayoutWorkingSet::default();
for width in [320, 100, 320] {
let pass = compare_pass(&source, &mut styles, &mut services, &mut work, width);
assert_eq!(
pass.metrics.box_count, 9,
"numeric layout adds one placeholder"
);
assert_eq!(work.stats().retained_boxes, 8, "placeholder is pass-local");
if width == 100 {
assert_eq!(work.stats().reused_inline_contexts, 2);
}
}
}
#[test]
fn retained_work_invalidates_fonts_even_when_family_and_slot_are_unchanged() {
let (source, mut styles, mut services) = fixture();
let mut work = LayoutWorkingSet::default();
compare_pass(&source, &mut styles, &mut services, &mut work, 100);
services
.register_web_font(WebFontRegistration::new(
"fixed",
WebFontFace::new("Moli Ahem"),
include_bytes!("../fixtures/moli-hebrew-emoji.ttf").to_vec(),
))
.unwrap();
compare_pass(&source, &mut styles, &mut services, &mut work, 100);
assert_eq!(work.stats().reused_inline_contexts, 0);
compare_pass(&source, &mut styles, &mut services, &mut work, 100);
assert_eq!(work.stats().reused_inline_contexts, 2);
assert!(services.remove_web_font("fixed"));
compare_pass(&source, &mut styles, &mut services, &mut work, 100);
assert_eq!(work.stats().reused_inline_contexts, 0);
}
#[test]
fn retained_work_tracks_font_descriptors_with_identical_payloads() {
let (source, mut styles, mut services) = fixture();
let mut work = LayoutWorkingSet::default();
compare_pass(&source, &mut styles, &mut services, &mut work, 100);
for end in [0x60, 0x7f, 0x60, 0x7f] {
services
.register_web_font(WebFontRegistration::new(
"fixed",
WebFontFace::new("Moli Ahem")
.with_unicode_ranges([moli_layout::WebFontUnicodeRange::new(0, end)]),
include_bytes!("../fixtures/moli-ahem.ttf").to_vec(),
))
.unwrap();
compare_pass(&source, &mut styles, &mut services, &mut work, 100);
assert_eq!(work.stats().reused_inline_contexts, 0);
compare_pass(&source, &mut styles, &mut services, &mut work, 100);
assert_eq!(work.stats().reused_inline_contexts, 2);
}
}
#[test]
fn failed_passes_do_not_leave_stale_retained_state() {
let (source, mut styles, mut services) = fixture();
let mut work = LayoutWorkingSet::default();
compare_pass(&source, &mut styles, &mut services, &mut work, 100);
let root_style = styles.0.remove(&0).unwrap();
let error = build_layout_pass_with_working_set(
&source,
&mut styles,
&mut services,
LayoutPassRequest::new(LayoutViewport::new(100, 240, 1.0), LayoutFlushReason::Test),
&mut NoFrames,
Some(&mut work),
)
.err()
.expect("missing root style must fail");
assert!(matches!(error, LayoutError::MissingRootStyle { .. }));
assert_eq!(work.stats().retained_boxes, 0);
styles.0.insert(0, root_style);
compare_pass(&source, &mut styles, &mut services, &mut work, 100);
assert_eq!(work.stats().reused_inline_contexts, 0);
}
@@ -0,0 +1,389 @@
use super::*;
use moli_layout::{
EmbeddedFrameRenderer, EmbeddedFrameSnapshot, LayoutPseudo, LayoutWorkingSet,
build_layout_pass_with_working_set,
};
use style::values::{
computed::{
CSSPixelLength, LengthPercentage, NonNegativeLengthPercentage, length::Size as ComputedSize,
},
generics::NonNegative,
};
struct NoFrames;
impl EmbeddedFrameRenderer<usize> for NoFrames {
fn render_embedded_frame(
&mut self,
_: usize,
_: LayoutViewport,
) -> Result<Option<EmbeddedFrameSnapshot<usize>>, LayoutError> {
Ok(None)
}
}
fn block_width(style: &ResolvedLayoutStyle, width: f32) -> ResolvedLayoutStyle {
let mut computed = (**style.stylo_computed_values().unwrap()).clone();
let width: NonNegativeLengthPercentage =
NonNegative(LengthPercentage::new_length(CSSPixelLength::new(width)));
computed
.mutate_position()
.set_width(ComputedSize::LengthPercentage(width));
let mut style = ResolvedLayoutStyle::from_stylo(style::servo_arc::Arc::new(computed));
style.force_layout_display(LayoutDisplay::Block);
style
}
fn fixture() -> (Source, Styles, DocumentLayoutServices) {
let source = Source(vec![
Node::element("root", vec![1, 3, 5, 7]),
Node::element("changing", vec![2]),
Node::text("changing-text", "alpha beta gamma delta epsilon"),
Node::element("stable", vec![4]),
Node::text("stable-text", "one two three four five six"),
Node::element("fixed-scroller", vec![6]),
Node::element("empty-block", vec![]),
Node::element("hidden-frontier", vec![8]),
Node::text("hidden-text", "initial hidden text"),
]);
let (font, services) = fixed_inline_font();
let mut hidden = font.clone();
hidden.force_layout_display(LayoutDisplay::None);
let styles = Styles(HashMap::from([
(0, block_width(&font, 320.0)),
(1, block_width(&font, 100.0)),
(3, block_width(&font, 160.0)),
(
5,
resolved(
LayoutDisplay::Block,
Style {
size: Size {
width: length(60.0),
height: length(40.0),
},
overflow: Point {
// The synthetic adapter maps Taffy's Scroll to CSS auto.
x: Overflow::Scroll,
y: Overflow::Scroll,
},
..Style::default()
},
)
.with_position(LayoutPosition::Fixed),
),
(6, fixed_size(LayoutDisplay::Block, 40.0, 400.0)),
(7, hidden),
]));
(source, styles, services)
}
fn assert_same_output(
retained: &LayoutPassResult<usize>,
cold: &LayoutPassResult<usize>,
node_count: usize,
) {
assert_eq!(retained.tree.boxes, cold.tree.boxes);
assert_eq!(retained.tree.fragments, cold.tree.fragments);
assert_eq!(retained.paint_snapshot(), cold.paint_snapshot());
assert_eq!(
retained.answer_query(&LayoutQuery::DocumentMetrics),
cold.answer_query(&LayoutQuery::DocumentMetrics),
);
for source in 0..node_count {
for query in [
LayoutQuery::BoxModel { source },
LayoutQuery::ClientRects { source },
LayoutQuery::ContentQuads { source },
LayoutQuery::ElementMetrics { source },
LayoutQuery::UsedGridTracks { source },
LayoutQuery::ScrollIntoViewGeometry { source },
LayoutQuery::TextRangeRects {
source,
utf16_range: 0..usize::MAX,
},
LayoutQuery::TextRangeRects {
source,
utf16_range: 2..2,
},
LayoutQuery::IntersectionGeometry {
target: source,
root: None,
},
LayoutQuery::EventOffset {
source,
point: LayoutPoint::new(32.0, 48.0),
},
] {
assert_eq!(
retained.answer_query(&query),
cold.answer_query(&query),
"{query:?}",
);
}
}
for y in (0..240).step_by(19) {
for x in (0..320).step_by(23) {
let point = LayoutPoint::new(x as f32, y as f32);
for query in [
LayoutQuery::HitTest {
point,
ignore_pointer_events_none: false,
},
LayoutQuery::HitTestAll {
point,
ignore_pointer_events_none: true,
},
LayoutQuery::CaretPosition { point },
] {
assert_eq!(retained.answer_query(&query), cold.answer_query(&query));
}
}
}
}
fn compare_with_cold(
source: &Source,
styles: &mut impl LayoutStyleResolver<usize>,
services: &mut DocumentLayoutServices,
work: &mut LayoutWorkingSet<usize>,
) -> LayoutPassResult<usize> {
let request =
LayoutPassRequest::with_paint(LayoutViewport::new(320, 240, 1.0), LayoutFlushReason::Test);
let retained = build_layout_pass_with_working_set(
source,
styles,
services,
request,
&mut NoFrames,
Some(work),
)
.unwrap();
let cold = build_layout_pass(source, styles, services, request).unwrap();
assert_same_output(&retained, &cold, source.0.len());
retained
}
fn assert_eviction_preserves_output(
source: &Source,
styles: &mut impl LayoutStyleResolver<usize>,
services: &mut DocumentLayoutServices,
work: &mut LayoutWorkingSet<usize>,
expected: &LayoutPassResult<usize>,
) {
work.clear();
let evicted = compare_with_cold(source, styles, services, work);
assert_eq!(work.stats().reused_construction_boxes, 0);
assert_same_output(&evicted, expected, source.0.len());
}
fn prime_graph_reuse(
source: &Source,
styles: &mut Styles,
services: &mut DocumentLayoutServices,
work: &mut LayoutWorkingSet<usize>,
) -> LayoutPassResult<usize> {
compare_with_cold(source, styles, services, work);
assert_eq!(work.stats().reused_construction_boxes, 0);
let old = styles.0[&1].clone();
let changed = block_width(&old, 180.0);
assert!(!style::servo_arc::Arc::ptr_eq(
old.stylo_computed_values().unwrap(),
changed.stylo_computed_values().unwrap(),
));
styles.0.insert(1, changed);
let warm = compare_with_cold(source, styles, services, work);
assert!(
work.stats().reused_construction_boxes > 0,
"{:?}",
work.stats()
);
assert_eq!(
warm.element_metrics_for_source(1)
.unwrap()
.offset_size
.width,
180.0,
);
warm
}
#[test]
fn width_changes_skip_construction_with_hidden_and_out_of_flow_sources() {
let (source, mut styles, mut services) = fixture();
let mut work = LayoutWorkingSet::default();
let warm = prime_graph_reuse(&source, &mut styles, &mut services, &mut work);
assert_eq!(
work.stats().reused_construction_boxes,
work.stats().retained_boxes
);
assert!(!warm.text_range_rects(2, 0..usize::MAX).is_empty());
assert!(warm.element_metrics_for_source(5).is_some());
assert!(warm.element_metrics_for_source(6).is_some());
assert!(warm.element_metrics_for_source(7).is_none());
assert_eviction_preserves_output(&source, &mut styles, &mut services, &mut work, &warm);
}
#[test]
fn hidden_and_missing_style_frontiers_are_rechecked_before_graph_reuse() {
for missing_style in [false, true] {
let (mut source, mut styles, mut services) = fixture();
if missing_style {
styles.0.remove(&7);
}
let mut work = LayoutWorkingSet::default();
let hidden = prime_graph_reuse(&source, &mut styles, &mut services, &mut work);
assert!(hidden.text_range_rects(8, 0..usize::MAX).is_empty());
// A suppressed subtree need not be walked while hidden. Once its
// frontier becomes visible, its current descendants must be built.
source.0[8].text = Some("text changed while the subtree was hidden");
compare_with_cold(&source, &mut styles, &mut services, &mut work);
let visible_style = block_width(&styles.0[&1], 120.0);
styles.0.insert(7, visible_style);
let visible = compare_with_cold(&source, &mut styles, &mut services, &mut work);
assert_eq!(work.stats().reused_construction_boxes, 0);
assert!(visible.element_metrics_for_source(7).is_some());
assert!(!visible.text_range_rects(8, 0..usize::MAX).is_empty());
assert_eviction_preserves_output(&source, &mut styles, &mut services, &mut work, &visible);
}
}
#[test]
fn absent_empty_and_collapsible_text_cannot_hide_new_inline_runs() {
for (initial_text, preserve_whitespace) in [
(None, false),
(Some(""), false),
(Some(" \t\n"), false),
(Some(" \t\n"), true),
] {
let (mut source, mut styles, mut services) = fixture();
source.0[0].children.push(9);
let mut text = Node::text("suppressed-text", "");
text.text = initial_text;
source.0.push(text);
let mut work = LayoutWorkingSet::default();
let initial = prime_graph_reuse(&source, &mut styles, &mut services, &mut work);
assert!(initial.text_range_rects(9, 0..usize::MAX).is_empty());
if preserve_whitespace {
let mut computed = (**styles.0[&0].stylo_computed_values().unwrap()).clone();
computed.mutate_inherited_text().set_white_space_collapse(
style::computed_values::white_space_collapse::T::Preserve,
);
let mut changed = ResolvedLayoutStyle::from_stylo(style::servo_arc::Arc::new(computed));
changed.force_layout_display(LayoutDisplay::Block);
styles.0.insert(0, changed);
} else {
// NBSP is meaningful inline text even though CSS whitespace was
// discarded at the same source position in the previous pass.
source.0[9].text = Some("\u{00a0} visible");
}
let changed = compare_with_cold(&source, &mut styles, &mut services, &mut work);
assert_eq!(work.stats().reused_construction_boxes, 0);
assert!(changed.tree.boxes.len() > initial.tree.boxes.len());
assert_eviction_preserves_output(&source, &mut styles, &mut services, &mut work, &changed);
}
}
#[test]
fn a_contents_wrapper_rebuilds_principal_and_descendant_source_mapping() {
let (source, mut styles, mut services) = fixture();
let mut work = LayoutWorkingSet::default();
let initial = prime_graph_reuse(&source, &mut styles, &mut services, &mut work);
assert!(initial.source_output(1).unwrap().principal_box.is_some());
styles
.0
.get_mut(&1)
.unwrap()
.force_layout_display(LayoutDisplay::Contents);
let contents = compare_with_cold(&source, &mut styles, &mut services, &mut work);
assert_eq!(work.stats().reused_construction_boxes, 0);
assert!(
contents
.source_output(1)
.is_none_or(|node| node.principal_box.is_none())
);
assert!(!contents.text_range_rects(2, 0..usize::MAX).is_empty());
assert_eviction_preserves_output(&source, &mut styles, &mut services, &mut work, &contents);
}
struct PseudoStyles {
primary: Styles,
pseudo: HashMap<(usize, LayoutPseudo), ResolvedLayoutStyle>,
}
impl LayoutStyleResolver<usize> for PseudoStyles {
fn element_styles(
&mut self,
node: usize,
) -> Result<Option<ResolvedLayoutElementStyles>, LayoutError> {
Ok(self.primary.0.get(&node).cloned().map(|primary| {
ResolvedLayoutElementStyles::new(
primary,
self.pseudo.get(&(node, LayoutPseudo::Before)).cloned(),
self.pseudo.get(&(node, LayoutPseudo::After)).cloned(),
)
}))
}
}
#[test]
fn new_pseudos_invalidate_construction_even_with_the_same_principal_style() {
for (pseudo, text) in [
(LayoutPseudo::Before, ""),
(LayoutPseudo::Before, "prefix"),
(LayoutPseudo::After, "suffix"),
] {
let (source, mut primary, mut services) = fixture();
let mut work = LayoutWorkingSet::default();
let initial = prime_graph_reuse(&source, &mut primary, &mut services, &mut work);
let principal = primary.0[&1].clone();
let mut generated = principal.clone().with_generated_text(text);
generated.force_layout_display(LayoutDisplay::Inline);
let mut styles = PseudoStyles {
primary,
pseudo: HashMap::from([((1, pseudo), generated)]),
};
assert!(style::servo_arc::Arc::ptr_eq(
principal.stylo_computed_values().unwrap(),
styles.primary.0[&1].stylo_computed_values().unwrap(),
));
let changed = compare_with_cold(&source, &mut styles, &mut services, &mut work);
assert_eq!(work.stats().reused_construction_boxes, 0);
assert!(changed.tree.boxes.len() > initial.tree.boxes.len());
assert_eviction_preserves_output(&source, &mut styles, &mut services, &mut work, &changed);
}
}
#[test]
fn flattened_children_order_and_parent_changes_retire_the_old_graph() {
let (mut source, mut styles, mut services) = fixture();
let mut work = LayoutWorkingSet::default();
let initial = prime_graph_reuse(&source, &mut styles, &mut services, &mut work);
// LayoutSource exposes the flattened tree. Reordering the same identities
// models slot reassignment without inventing a second DOM implementation.
source.0[0].children.swap(0, 1);
let reordered = compare_with_cold(&source, &mut styles, &mut services, &mut work);
assert_eq!(work.stats().reused_construction_boxes, 0);
assert_ne!(
reordered.text_range_rects(2, 0..usize::MAX),
initial.text_range_rects(2, 0..usize::MAX),
);
compare_with_cold(&source, &mut styles, &mut services, &mut work);
assert!(work.stats().reused_construction_boxes > 0);
// Preserve node IDs, text and element styles but change each text node's
// flattened parent. Its inherited width and IFC source owner must follow.
source.0[1].children = vec![4];
source.0[3].children = vec![2];
let reparented = compare_with_cold(&source, &mut styles, &mut services, &mut work);
assert_eq!(work.stats().reused_construction_boxes, 0);
assert_ne!(
reparented.text_range_rects(2, 0..usize::MAX),
reordered.text_range_rects(2, 0..usize::MAX),
);
assert_eviction_preserves_output(&source, &mut styles, &mut services, &mut work, &reparented);
}
@@ -0,0 +1,973 @@
use super::*;
use moli_layout::{
EmbeddedFrameRenderer, EmbeddedFrameSnapshot, LayoutWorkingSet,
build_layout_pass_with_working_set,
};
use style::values::{
computed::{
CSSPixelLength, LengthPercentage, NonNegativeLengthPercentage, Percentage,
length::Size as ComputedSize,
},
generics::NonNegative,
};
use taffy::{AlignItems, Clear, FlexDirection, Float};
struct NoFrames;
impl EmbeddedFrameRenderer<usize> for NoFrames {
fn render_embedded_frame(
&mut self,
_: usize,
_: LayoutViewport,
) -> Result<Option<EmbeddedFrameSnapshot<usize>>, LayoutError> {
Ok(None)
}
}
fn css_length(value: f32) -> NonNegativeLengthPercentage {
NonNegative(LengthPercentage::new_length(CSSPixelLength::new(value)))
}
fn css_percent(value: f32) -> NonNegativeLengthPercentage {
NonNegative(LengthPercentage::new_percent(Percentage(value)))
}
fn block_style_from_computed(
base: &ResolvedLayoutStyle,
update: impl FnOnce(&mut style::properties::ComputedValues),
) -> ResolvedLayoutStyle {
let mut computed = (**base.stylo_computed_values().unwrap()).clone();
update(&mut computed);
let mut resolved = ResolvedLayoutStyle::from_stylo(style::servo_arc::Arc::new(computed));
resolved.force_layout_display(LayoutDisplay::Block);
resolved
}
fn compare_with_cold(
source: &Source,
styles: &mut Styles,
services: &mut DocumentLayoutServices,
work: &mut LayoutWorkingSet<usize>,
) -> LayoutPassResult<usize> {
compare_with_cold_at_viewport(
source,
styles,
services,
work,
LayoutViewport::new(400, 320, 1.0),
)
}
fn compare_with_cold_at_viewport(
source: &Source,
styles: &mut Styles,
services: &mut DocumentLayoutServices,
work: &mut LayoutWorkingSet<usize>,
viewport: LayoutViewport,
) -> LayoutPassResult<usize> {
let request = LayoutPassRequest::with_paint(viewport, LayoutFlushReason::Test);
let retained = build_layout_pass_with_working_set(
source,
styles,
services,
request,
&mut NoFrames,
Some(work),
)
.unwrap();
let cold = build_layout_pass(source, styles, services, request).unwrap();
assert_eq!(retained.tree.boxes, cold.tree.boxes);
assert_eq!(retained.tree.fragments, cold.tree.fragments);
assert_eq!(retained.paint_snapshot(), cold.paint_snapshot());
for node in 0..source.0.len() {
for query in [
LayoutQuery::ElementMetrics { source: node },
LayoutQuery::ClientRects { source: node },
LayoutQuery::TextRangeRects {
source: node,
utf16_range: 0..usize::MAX,
},
LayoutQuery::TextRangeRects {
source: node,
utf16_range: 2..2,
},
LayoutQuery::IntersectionGeometry {
target: node,
root: None,
},
] {
assert_eq!(retained.answer_query(&query), cold.answer_query(&query));
}
}
for y in (0..320).step_by(23) {
for x in (0..400).step_by(31) {
let point = LayoutPoint::new(x as f32, y as f32);
assert_eq!(retained.hit_test(point, false), cold.hit_test(point, false));
}
}
retained
}
fn assert_evicted_matches_cold(
source: &Source,
styles: &mut Styles,
services: &mut DocumentLayoutServices,
work: &mut LayoutWorkingSet<usize>,
) {
work.clear();
compare_with_cold(source, styles, services, work);
assert_eq!(work.stats().reused_inline_contexts, 0);
assert_eq!(work.stats().reused_inline_numeric_layouts, 0);
}
#[test]
fn retained_numeric_output_tracks_percentage_constraints_with_an_unchanged_child_style() {
let source = Source(vec![
Node::element("root", vec![1]),
Node::element("containing-block", vec![2]),
Node::element("paragraph", vec![3]),
Node::text("text", "alpha beta gamma delta epsilon zeta eta theta"),
]);
let (font, mut services) = fixed_inline_font();
let paragraph = block_style_from_computed(&font, |computed| {
use style::values::specified::align::{AlignFlags, ContentDistribution};
let position = computed.mutate_position();
position.set_width(ComputedSize::LengthPercentage(css_percent(0.75)));
position.set_height(ComputedSize::LengthPercentage(css_percent(0.6)));
position.set_align_content(ContentDistribution::new(AlignFlags::END));
let padding = computed.mutate_padding();
padding.set_padding_left(css_percent(0.025));
padding.set_padding_right(css_percent(0.05));
padding.set_padding_top(css_percent(0.025));
padding.set_padding_bottom(css_percent(0.05));
});
let mut styles = Styles(HashMap::from([
(0, fixed_size(LayoutDisplay::Block, 400.0, 320.0)),
(2, paragraph.clone()),
]));
let mut work = LayoutWorkingSet::default();
let mut previous_size = None;
for (width, height) in [
(200.0, 120.0),
(320.0, 300.0),
(240.0, 300.0),
(180.0, 180.0),
] {
styles
.0
.insert(1, fixed_size(LayoutDisplay::Block, width, height));
assert!(style::servo_arc::Arc::ptr_eq(
paragraph.stylo_computed_values().unwrap(),
styles.0[&2].stylo_computed_values().unwrap(),
));
let output = compare_with_cold(&source, &mut styles, &mut services, &mut work);
let size = output.element_metrics_for_source(2).unwrap().offset_size;
if let Some(previous) = previous_size {
assert_ne!(size, previous);
assert_eq!(work.stats().reused_inline_contexts, 1);
}
previous_size = Some(size);
assert!(!output.text_range_rects(3, 0..usize::MAX).is_empty());
compare_with_cold(&source, &mut styles, &mut services, &mut work);
assert!(work.stats().reused_inline_numeric_layouts > 0);
}
assert_evicted_matches_cold(&source, &mut styles, &mut services, &mut work);
}
#[test]
fn retained_numeric_output_keeps_parent_width_for_percentage_padding() {
let source = Source(vec![
Node::element("root", vec![1]),
Node::element("containing-block", vec![2]),
Node::element("paragraph", vec![3]),
Node::text("text", "alpha beta gamma delta"),
]);
let (font, mut services) = fixed_inline_font();
let paragraph = block_style_from_computed(&font, |computed| {
let position = computed.mutate_position();
position.set_box_sizing(style::computed_values::box_sizing::T::BorderBox);
position.set_width(ComputedSize::LengthPercentage(css_length(180.0)));
position.set_height(ComputedSize::LengthPercentage(css_length(120.0)));
let padding = computed.mutate_padding();
padding.set_padding_left(css_percent(0.05));
padding.set_padding_right(css_percent(0.05));
padding.set_padding_top(css_percent(0.05));
padding.set_padding_bottom(css_percent(0.05));
});
let mut styles = Styles(HashMap::from([
(0, fixed_size(LayoutDisplay::Block, 400.0, 320.0)),
(2, paragraph.clone()),
]));
let mut work = LayoutWorkingSet::default();
let mut previous_rects = None;
for parent_width in [200.0, 320.0, 240.0] {
styles
.0
.insert(1, fixed_size(LayoutDisplay::Block, parent_width, 220.0));
assert!(style::servo_arc::Arc::ptr_eq(
paragraph.stylo_computed_values().unwrap(),
styles.0[&2].stylo_computed_values().unwrap(),
));
let output = compare_with_cold(&source, &mut styles, &mut services, &mut work);
// Border-box sizing keeps the known outer dimensions unchanged;
// only the parent's percentage basis changes the content constraints.
assert_eq!(
output.element_metrics_for_source(2).unwrap().offset_size,
moli_layout::LayoutSize::new(180.0, 120.0),
);
let rects = output.text_range_rects(3, 0..usize::MAX);
assert!(!rects.is_empty());
if let Some(previous) = previous_rects {
assert_ne!(rects, previous);
assert_eq!(work.stats().reused_inline_contexts, 1);
}
assert_eq!(work.stats().reused_inline_numeric_layouts, 0);
previous_rects = Some(rects);
compare_with_cold(&source, &mut styles, &mut services, &mut work);
assert!(work.stats().reused_inline_numeric_layouts > 0);
}
assert_evicted_matches_cold(&source, &mut styles, &mut services, &mut work);
}
#[test]
fn retained_numeric_output_keeps_parent_width_for_calc_minimum_width() {
use style::typed_om::NumericBaseType;
use style::values::computed::calc::CalcPercentageLeaf;
use style::values::computed::length_percentage::{CalcNode, ComputedLeaf, Unpacked};
use style::values::generics::Optional;
let source = Source(vec![
Node::element("root", vec![1]),
Node::element("containing-block", vec![2]),
Node::element("paragraph", vec![3]),
Node::text("text", "alpha beta gamma delta"),
]);
let minimum_width = LengthPercentage::new_calc(
CalcNode::Sum(
vec![
CalcNode::Leaf(ComputedLeaf::Length(CSSPixelLength::new(10.0))),
CalcNode::Leaf(ComputedLeaf::Percentage(CalcPercentageLeaf::new(
0.5,
Optional::Some(NumericBaseType::Length),
))),
]
.into(),
),
Default::default(),
);
assert!(matches!(minimum_width.unpack(), Unpacked::Calc(_)));
let (font, mut services) = fixed_inline_font();
let paragraph = block_style_from_computed(&font, |computed| {
let position = computed.mutate_position();
position.set_box_sizing(style::computed_values::box_sizing::T::BorderBox);
position.set_width(ComputedSize::LengthPercentage(css_length(180.0)));
position.set_height(ComputedSize::LengthPercentage(css_length(120.0)));
position.set_min_width(ComputedSize::LengthPercentage(NonNegative(minimum_width)));
});
let mut styles = Styles(HashMap::from([
(0, fixed_size(LayoutDisplay::Block, 400.0, 320.0)),
(2, paragraph.clone()),
]));
let mut work = LayoutWorkingSet::default();
for (index, parent_width) in [200.0, 240.0, 360.0].into_iter().enumerate() {
styles
.0
.insert(1, fixed_size(LayoutDisplay::Block, parent_width, 220.0));
assert!(style::servo_arc::Arc::ptr_eq(
paragraph.stylo_computed_values().unwrap(),
styles.0[&2].stylo_computed_values().unwrap(),
));
let output = compare_with_cold(&source, &mut styles, &mut services, &mut work);
// The first width change leaves the known 180px border box unchanged.
// A calc-bearing style must still reject parent-width normalization;
// the final change also makes calc(50% + 10px) the active minimum.
let expected_width = 180.0_f32.max(parent_width * 0.5 + 10.0);
assert_eq!(
output.element_metrics_for_source(2).unwrap().offset_size,
moli_layout::LayoutSize::new(expected_width, 120.0),
);
if index > 0 {
assert_eq!(work.stats().reused_inline_contexts, 1);
}
assert_eq!(work.stats().reused_inline_numeric_layouts, 0);
compare_with_cold(&source, &mut styles, &mut services, &mut work);
assert!(work.stats().reused_inline_numeric_layouts > 0);
}
assert_evicted_matches_cold(&source, &mut styles, &mut services, &mut work);
}
#[test]
fn retained_numeric_output_observes_parent_display_with_an_unchanged_child_style() {
let source = Source(vec![
Node::element("root", vec![1]),
Node::element("changing-parent", vec![2]),
Node::element("paragraph", vec![3]),
Node::text("text", "aa bb"),
]);
let (mut paragraph, mut services) = fixed_inline_font();
paragraph.force_layout_display(LayoutDisplay::Block);
let mut styles = Styles(HashMap::from([
(0, fixed_size(LayoutDisplay::Block, 400.0, 320.0)),
(2, paragraph.clone()),
]));
let mut work = LayoutWorkingSet::default();
let mut widths = Vec::new();
for display in [
LayoutDisplay::Block,
LayoutDisplay::Flex,
LayoutDisplay::Grid,
LayoutDisplay::Block,
] {
styles.0.insert(
1,
resolved(
display,
Style {
size: Size {
width: length(200.0),
height: length(120.0),
},
flex_direction: FlexDirection::Column,
align_items: AlignItems::START,
// Taffy now honors justify-items for block children too.
// Keep normal block sizing while grid items shrink to fit.
justify_items: if display == LayoutDisplay::Grid {
AlignItems::START
} else {
AlignItems::NORMAL
},
..Style::default()
},
),
);
assert!(style::servo_arc::Arc::ptr_eq(
paragraph.stylo_computed_values().unwrap(),
styles.0[&2].stylo_computed_values().unwrap(),
));
let output = compare_with_cold(&source, &mut styles, &mut services, &mut work);
widths.push(
output
.element_metrics_for_source(2)
.unwrap()
.offset_size
.width,
);
compare_with_cold(&source, &mut styles, &mut services, &mut work);
assert_eq!(work.stats().reused_inline_contexts, 1);
assert!(work.stats().reused_inline_numeric_layouts > 0);
}
assert!(
widths[0] > widths[1],
"flex's unstretched child must shrink: {widths:?}"
);
assert!(
widths[0] > widths[2],
"grid's unstretched child must shrink: {widths:?}"
);
assert_eq!(widths[0], widths[3]);
assert_evicted_matches_cold(&source, &mut styles, &mut services, &mut work);
}
#[test]
fn retained_numeric_output_is_reprojected_after_parent_moves_and_scrolls() {
let mut source = Source(vec![
Node::element("root", vec![1]),
Node::element("scroller", vec![2]),
Node::element("positioned-parent", vec![3]),
Node::element("paragraph", vec![4]),
Node::text("text", "alpha beta gamma delta epsilon zeta eta theta"),
]);
let (font, mut services) = fixed_inline_font();
let paragraph = block_style_from_computed(&font, |computed| {
computed
.mutate_position()
.set_width(ComputedSize::LengthPercentage(css_length(120.0)));
});
let scroller_style = |left, top| {
resolved(
LayoutDisplay::Block,
Style {
size: Size {
width: length(180.0),
height: length(64.0),
},
overflow: Point {
x: Overflow::Hidden,
y: Overflow::Hidden,
},
margin: Rect {
left: length(left),
top: length(top),
right: length(0.0),
bottom: length(0.0),
},
..Style::default()
},
)
};
let parent_style = |relative_top| {
resolved(
LayoutDisplay::Block,
Style {
size: Size {
width: length(120.0),
height: length(220.0),
},
inset: Rect {
left: LengthPercentageAuto::auto(),
right: LengthPercentageAuto::auto(),
top: length(relative_top),
bottom: LengthPercentageAuto::auto(),
},
..Style::default()
},
)
.with_position(LayoutPosition::Relative)
};
let mut styles = Styles(HashMap::from([
(0, fixed_size(LayoutDisplay::Block, 400.0, 320.0)),
(1, scroller_style(0.0, 0.0)),
(2, parent_style(0.0)),
(3, paragraph),
]));
let mut work = LayoutWorkingSet::default();
let first = compare_with_cold(&source, &mut styles, &mut services, &mut work);
let mut previous_rects = first.text_range_rects(4, 0..usize::MAX);
assert!(!previous_rects.is_empty());
compare_with_cold(&source, &mut styles, &mut services, &mut work);
assert!(work.stats().reused_inline_numeric_layouts > 0);
for (left, top, relative_top, scroll) in [
(17.0, 11.0, 5.0, 20.0),
(3.0, 23.0, -4.0, 60.0),
(0.0, 0.0, 0.0, 0.0),
] {
styles.0.insert(1, scroller_style(left, top));
styles.0.insert(2, parent_style(relative_top));
source.0[1].scroll = LayoutPoint::new(0.0, scroll);
let output = compare_with_cold(&source, &mut styles, &mut services, &mut work);
assert!(work.stats().reused_inline_numeric_layouts > 0);
let rects = output.text_range_rects(4, 0..usize::MAX);
assert_ne!(rects, previous_rects);
previous_rects = rects;
let scroller_box = output.source_output(1).unwrap().principal_box.unwrap();
assert_eq!(
output.scroll_extent(scroller_box).unwrap().applied_offset,
LayoutPoint::new(0.0, scroll),
);
}
assert_evicted_matches_cold(&source, &mut styles, &mut services, &mut work);
}
#[test]
fn retained_numeric_output_is_not_reused_inside_external_float_exclusions() {
let source = Source(vec![
Node::element("root", vec![1, 2]),
Node::element("preceding-float", vec![]),
Node::element("paragraph", vec![3]),
Node::text("text", "alpha beta gamma delta epsilon zeta eta theta"),
]);
let (mut paragraph, mut services) = fixed_inline_font();
paragraph.force_layout_display(LayoutDisplay::Block);
let mut styles = Styles(HashMap::from([
(0, fixed_size(LayoutDisplay::Block, 200.0, 320.0)),
(2, paragraph),
]));
let mut work = LayoutWorkingSet::default();
let mut first_rects = None;
for width in [40.0, 90.0, 130.0] {
styles.0.insert(
1,
fixed_size(LayoutDisplay::Block, width, 100.0).with_float(Float::Left, Clear::None),
);
let output = compare_with_cold(&source, &mut styles, &mut services, &mut work);
let rects = output.text_range_rects(3, 0..usize::MAX);
assert!(!rects.is_empty());
if let Some(previous) = &first_rects {
assert_ne!(
&rects, previous,
"the preceding float must affect line slots"
);
} else {
first_rects = Some(rects);
}
compare_with_cold(&source, &mut styles, &mut services, &mut work);
assert_eq!(work.stats().reused_inline_contexts, 1);
assert_eq!(work.stats().reused_inline_numeric_layouts, 0);
}
assert_evicted_matches_cold(&source, &mut styles, &mut services, &mut work);
}
#[test]
fn retained_numeric_output_checks_resolved_gutters_on_the_same_computed_style() {
let source = Source(vec![
Node::element("root", vec![1]),
Node::element("paragraph-scroller", vec![2]),
Node::text("text", "alpha beta gamma delta epsilon zeta eta theta"),
]);
let (font, mut services) = fixed_inline_font();
let paragraph = block_style_from_computed(&font, |computed| {
let position = computed.mutate_position();
position.set_width(ComputedSize::LengthPercentage(css_length(180.0)));
position.set_height(ComputedSize::LengthPercentage(css_length(60.0)));
let box_style = computed.mutate_box();
box_style.set_overflow_x(style::values::computed::Overflow::Hidden);
box_style.set_overflow_y(style::values::computed::Overflow::Hidden);
});
let mut styles = Styles(HashMap::from([(
0,
fixed_size(LayoutDisplay::Block, 400.0, 320.0),
)]));
let mut work = LayoutWorkingSet::default();
let mut client_widths = Vec::new();
for (width, gutter) in [
(LayoutScrollbarWidth::Auto, LayoutScrollbarGutter::Stable),
(
LayoutScrollbarWidth::Thin,
LayoutScrollbarGutter::StableBothEdges,
),
(
LayoutScrollbarWidth::Auto,
LayoutScrollbarGutter::StableBothEdges,
),
] {
let mut changed = paragraph.clone();
changed.set_scrollbar_style(width, gutter, None);
assert!(style::servo_arc::Arc::ptr_eq(
paragraph.stylo_computed_values().unwrap(),
changed.stylo_computed_values().unwrap(),
));
styles.0.insert(1, changed);
let output = compare_with_cold(&source, &mut styles, &mut services, &mut work);
client_widths.push(
output
.element_metrics_for_source(1)
.unwrap()
.client_size
.width,
);
compare_with_cold(&source, &mut styles, &mut services, &mut work);
assert_eq!(work.stats().reused_inline_contexts, 1);
assert!(work.stats().reused_inline_numeric_layouts > 0);
}
assert!(
client_widths
.windows(2)
.all(|widths| widths[0] != widths[1])
);
assert_evicted_matches_cold(&source, &mut styles, &mut services, &mut work);
}
#[test]
fn retained_numeric_output_preserves_accepted_bidi_justified_and_vertical_lines() {
use style::computed_values::writing_mode::T as WritingMode;
use style::properties::generated::longhands::direction::computed_value::T as Direction;
use style::values::specified::TextAlignKeyword;
let source = Source(vec![
Node::element("root", vec![1]),
Node::element("paragraph", vec![2]),
Node::text("text", "alpha beta gamma delta epsilon zeta eta theta"),
]);
let (base, mut services) = fixed_inline_font();
let mut styles = Styles(HashMap::from([(
0,
fixed_size(LayoutDisplay::Block, 400.0, 320.0),
)]));
let mut work = LayoutWorkingSet::default();
for (writing_mode, direction, alignment) in [
(
WritingMode::HorizontalTb,
Direction::Ltr,
TextAlignKeyword::Start,
),
(
WritingMode::HorizontalTb,
Direction::Rtl,
TextAlignKeyword::Start,
),
(
WritingMode::HorizontalTb,
Direction::Ltr,
TextAlignKeyword::Justify,
),
(
WritingMode::VerticalRl,
Direction::Rtl,
TextAlignKeyword::Start,
),
(
WritingMode::VerticalLr,
Direction::Ltr,
TextAlignKeyword::End,
),
] {
let mut computed = (**base.stylo_computed_values().unwrap()).clone();
computed
.mutate_inherited_box()
.set_writing_mode(writing_mode);
computed.mutate_inherited_box().set_direction(direction);
computed.mutate_inherited_text().set_text_align(alignment);
computed.writing_mode =
style::logical_geometry::WritingMode::new(computed.get_inherited_box());
computed
.mutate_position()
.set_width(ComputedSize::LengthPercentage(css_length(160.0)));
computed
.mutate_position()
.set_height(ComputedSize::LengthPercentage(css_length(120.0)));
let mut paragraph = ResolvedLayoutStyle::from_stylo(style::servo_arc::Arc::new(computed));
paragraph.force_layout_display(LayoutDisplay::Block);
styles.0.insert(1, paragraph);
let first = compare_with_cold(&source, &mut styles, &mut services, &mut work);
assert!(!first.text_range_rects(2, 0..usize::MAX).is_empty());
assert_eq!(work.stats().reused_inline_numeric_layouts, 0);
let warm = compare_with_cold(&source, &mut styles, &mut services, &mut work);
assert!(work.stats().reused_inline_numeric_layouts > 0);
assert_eq!(first.tree.fragments, warm.tree.fragments);
assert_eq!(first.paint_snapshot(), warm.paint_snapshot());
}
assert_evicted_matches_cold(&source, &mut styles, &mut services, &mut work);
}
fn partial_plain_text_fixture() -> (Source, Styles, DocumentLayoutServices) {
let source = Source(vec![
Node::element("root", vec![1, 3]),
Node::element("first", vec![2]),
Node::text("first-text", "alpha beta gamma delta epsilon"),
Node::element("second", vec![4]),
Node::text("second-text", "one two three four five six seven"),
Node::element("tail", vec![6]),
Node::text(
"tail-text",
"new final paragraph with different line breaks",
),
]);
let (font, services) = fixed_inline_font();
let root = block_style_from_computed(&font, |computed| {
computed
.mutate_position()
.set_width(ComputedSize::LengthPercentage(css_length(300.0)));
});
let paragraph = block_style_from_computed(&font, |computed| {
computed
.mutate_position()
.set_width(ComputedSize::LengthPercentage(css_length(120.0)));
});
let styles = Styles(HashMap::from([
(0, root),
(1, paragraph.clone()),
(3, paragraph.clone()),
(5, paragraph),
]));
(source, styles, services)
}
#[test]
fn partial_ifc_numeric_owners_survive_growth_and_shrink_without_aliasing_shifted_ids() {
let (mut source, mut styles, mut services) = partial_plain_text_fixture();
let mut work = LayoutWorkingSet::default();
compare_with_cold(&source, &mut styles, &mut services, &mut work);
compare_with_cold(&source, &mut styles, &mut services, &mut work);
assert_eq!(work.stats().reused_inline_contexts, 2);
assert!(work.stats().reused_inline_numeric_layouts > 0);
source.0[0].children.push(5);
compare_with_cold(&source, &mut styles, &mut services, &mut work);
assert_eq!(work.stats().reused_construction_boxes, 0);
assert_eq!(work.stats().reused_inline_contexts, 2);
assert!(work.stats().reused_inline_numeric_layouts > 0);
// A new owner beyond the previous index length must have stored its own
// result successfully; this next pass must also be able to reuse it.
compare_with_cold(&source, &mut styles, &mut services, &mut work);
assert_eq!(work.stats().reused_inline_contexts, 3);
assert!(work.stats().reused_inline_numeric_layouts > 0);
source.0[0].children.pop();
compare_with_cold(&source, &mut styles, &mut services, &mut work);
assert_eq!(work.stats().reused_inline_contexts, 2);
assert!(work.stats().reused_inline_numeric_layouts > 0);
// The source IDs are stable, but both old construction owner IDs now name
// a different paragraph. None of their accepted outputs may migrate.
source.0[0].children.reverse();
compare_with_cold(&source, &mut styles, &mut services, &mut work);
assert_eq!(work.stats().reused_inline_contexts, 0);
assert_eq!(work.stats().reused_inline_numeric_layouts, 0);
compare_with_cold(&source, &mut styles, &mut services, &mut work);
assert_eq!(work.stats().reused_inline_contexts, 2);
source.0[0].children.insert(0, 5);
compare_with_cold(&source, &mut styles, &mut services, &mut work);
assert_eq!(work.stats().reused_inline_contexts, 0);
assert_eq!(work.stats().reused_inline_numeric_layouts, 0);
assert_evicted_matches_cold(&source, &mut styles, &mut services, &mut work);
}
#[test]
fn partial_ifc_rejects_internal_append_and_same_slot_font_replacement() {
let (mut source, mut styles, mut services) = partial_plain_text_fixture();
let mut work = LayoutWorkingSet::default();
compare_with_cold(&source, &mut styles, &mut services, &mut work);
compare_with_cold(&source, &mut styles, &mut services, &mut work);
assert_eq!(work.stats().reused_inline_contexts, 2);
// Grow the last existing IFC and the root in the same construction. Only
// the first complete paragraph can keep its old input/source-map closure.
source.0.push(Node::text(
"appended-text",
" appended inside the old paragraph",
));
source.0[3].children.push(7);
source.0[0].children.push(5);
compare_with_cold(&source, &mut styles, &mut services, &mut work);
assert_eq!(work.stats().reused_inline_contexts, 1);
compare_with_cold(&source, &mut styles, &mut services, &mut work);
assert_eq!(work.stats().reused_inline_contexts, 3);
assert!(work.stats().reused_inline_numeric_layouts > 0);
// A whole-document font change remains an unconditional invalidation even
// when partial graph matching could otherwise restore earlier paragraphs.
source.0[0].children.pop();
services
.register_web_font(moli_layout::WebFontRegistration::new(
"fixed",
moli_layout::WebFontFace::new("Moli Ahem"),
include_bytes!("../fixtures/moli-hebrew-emoji.ttf").to_vec(),
))
.unwrap();
compare_with_cold(&source, &mut styles, &mut services, &mut work);
assert_eq!(work.stats().reused_inline_contexts, 0);
assert_eq!(work.stats().reused_inline_numeric_layouts, 0);
compare_with_cold(&source, &mut styles, &mut services, &mut work);
assert_eq!(work.stats().reused_inline_contexts, 2);
assert_evicted_matches_cold(&source, &mut styles, &mut services, &mut work);
}
#[test]
fn partial_ifc_rejects_changed_ancestor_percentage_basis() {
let source = Source(vec![
Node::element("root", vec![1]),
Node::element("paragraph", vec![2]),
Node::text("text", "alpha beta gamma delta epsilon"),
Node::element("new-tail", vec![4]),
Node::text("new-tail-text", "one new paragraph"),
]);
let (font, mut services) = fixed_inline_font();
let root = block_style_from_computed(&font, |computed| {
computed
.mutate_position()
.set_width(ComputedSize::LengthPercentage(css_length(200.0)));
});
let paragraph = block_style_from_computed(&font, |computed| {
let position = computed.mutate_position();
position.set_box_sizing(style::computed_values::box_sizing::T::BorderBox);
position.set_width(ComputedSize::LengthPercentage(css_length(180.0)));
position.set_height(ComputedSize::LengthPercentage(css_length(120.0)));
let padding = computed.mutate_padding();
padding.set_padding_left(css_percent(0.05));
padding.set_padding_right(css_percent(0.05));
});
let mut source = source;
let mut styles = Styles(HashMap::from([
(0, root),
(1, paragraph.clone()),
(3, paragraph),
]));
let mut work = LayoutWorkingSet::default();
let first = compare_with_cold(&source, &mut styles, &mut services, &mut work);
compare_with_cold(&source, &mut styles, &mut services, &mut work);
assert!(work.stats().reused_inline_numeric_layouts > 0);
let paragraph_owner = styles.0[&1].stylo_computed_values().unwrap().clone();
// The paragraph's own style is unchanged, but its real ancestor changes
// the percentage-padding basis while the root also grows structurally.
// This narrow matcher must reject the old ancestor context altogether.
styles.0.insert(
0,
block_style_from_computed(&font, |computed| {
computed
.mutate_position()
.set_width(ComputedSize::LengthPercentage(css_length(300.0)));
}),
);
source.0[0].children.push(3);
assert!(style::servo_arc::Arc::ptr_eq(
&paragraph_owner,
styles.0[&1].stylo_computed_values().unwrap()
));
let changed = compare_with_cold(&source, &mut styles, &mut services, &mut work);
assert_eq!(work.stats().reused_inline_contexts, 0);
assert_eq!(work.stats().reused_inline_numeric_layouts, 0);
assert_ne!(
first.text_range_rects(2, 0..usize::MAX),
changed.text_range_rects(2, 0..usize::MAX)
);
assert_eq!(
changed.element_metrics_for_source(1).unwrap().offset_size,
moli_layout::LayoutSize::new(180.0, 120.0)
);
compare_with_cold(&source, &mut styles, &mut services, &mut work);
assert!(work.stats().reused_inline_numeric_layouts > 0);
assert_evicted_matches_cold(&source, &mut styles, &mut services, &mut work);
}
#[test]
fn partial_ifc_keeps_plain_text_but_rebuilds_unchanged_structural_inline() {
let (mut source, mut styles, mut services) = partial_plain_text_fixture();
let span = source.0.len();
source.0.push(Node::element("inline-span", vec![4]));
source.0[3].children = vec![span];
let mut inline = styles.0[&3].clone();
inline.force_layout_display(LayoutDisplay::Inline);
styles.0.insert(span, inline);
let mut work = LayoutWorkingSet::default();
compare_with_cold(&source, &mut styles, &mut services, &mut work);
compare_with_cold(&source, &mut styles, &mut services, &mut work);
assert_eq!(work.stats().reused_inline_contexts, 2);
source.0[0].children.push(5);
compare_with_cold(&source, &mut styles, &mut services, &mut work);
assert_eq!(work.stats().reused_construction_boxes, 0);
assert_eq!(
work.stats().reused_inline_contexts,
1,
"the plain paragraph alone is supported after the graph changes"
);
assert!(work.stats().reused_inline_numeric_layouts > 0);
compare_with_cold(&source, &mut styles, &mut services, &mut work);
assert_eq!(
work.stats().reused_inline_contexts,
3,
"exact topology still supports the unchanged structural inline"
);
assert_evicted_matches_cold(&source, &mut styles, &mut services, &mut work);
}
#[test]
fn partial_ifc_preserves_preparation_but_recomputes_percentage_padding_after_viewport_change() {
let mut source = Source(vec![
Node::element("root", vec![1]),
Node::element("paragraph", vec![2]),
Node::text("text", "alpha beta gamma delta epsilon"),
Node::element("new-tail", vec![4]),
Node::text("new-tail-text", "one new paragraph"),
]);
let (font, mut services) = fixed_inline_font();
let root = block_style_from_computed(&font, |computed| {
computed.mutate_position().set_width(ComputedSize::Auto);
});
let paragraph = block_style_from_computed(&font, |computed| {
let position = computed.mutate_position();
position.set_box_sizing(style::computed_values::box_sizing::T::BorderBox);
position.set_width(ComputedSize::LengthPercentage(css_length(180.0)));
position.set_height(ComputedSize::LengthPercentage(css_length(120.0)));
let padding = computed.mutate_padding();
padding.set_padding_left(css_percent(0.05));
padding.set_padding_right(css_percent(0.05));
});
let root_owner = root.stylo_computed_values().unwrap().clone();
let paragraph_owner = paragraph.stylo_computed_values().unwrap().clone();
let mut styles = Styles(HashMap::from([
(0, root),
(1, paragraph.clone()),
(3, paragraph),
]));
let mut work = LayoutWorkingSet::default();
let before_viewport = LayoutViewport::new(200, 320, 1.0);
let after_viewport = LayoutViewport::new(300, 320, 1.0);
let before = compare_with_cold_at_viewport(
&source,
&mut styles,
&mut services,
&mut work,
before_viewport,
);
compare_with_cold_at_viewport(
&source,
&mut styles,
&mut services,
&mut work,
before_viewport,
);
assert_eq!(work.stats().reused_inline_contexts, 1);
assert!(work.stats().reused_inline_numeric_layouts > 0);
// A real containing-block constraint changes without replacing either
// ComputedValues owner. Tail append forces the partial graph path; the
// old IFC can transfer, but its accepted numeric result cannot.
source.0[0].children.push(3);
let changed = compare_with_cold_at_viewport(
&source,
&mut styles,
&mut services,
&mut work,
after_viewport,
);
assert!(style::servo_arc::Arc::ptr_eq(
&root_owner,
styles.0[&0].stylo_computed_values().unwrap(),
));
assert!(style::servo_arc::Arc::ptr_eq(
&paragraph_owner,
styles.0[&1].stylo_computed_values().unwrap(),
));
assert_eq!(work.stats().reused_construction_boxes, 0);
assert_eq!(work.stats().reused_inline_contexts, 1);
assert_eq!(work.stats().reused_inline_numeric_layouts, 0);
assert_eq!(
before
.element_metrics_for_source(0)
.unwrap()
.offset_size
.width,
200.0
);
assert_eq!(
changed
.element_metrics_for_source(0)
.unwrap()
.offset_size
.width,
300.0
);
assert_eq!(
before.element_metrics_for_source(1).unwrap().offset_size,
moli_layout::LayoutSize::new(180.0, 120.0)
);
assert_eq!(
changed.element_metrics_for_source(1).unwrap().offset_size,
moli_layout::LayoutSize::new(180.0, 120.0)
);
assert_ne!(
before.text_range_rects(2, 0..usize::MAX),
changed.text_range_rects(2, 0..usize::MAX)
);
compare_with_cold_at_viewport(
&source,
&mut styles,
&mut services,
&mut work,
after_viewport,
);
assert_eq!(work.stats().reused_inline_contexts, 2);
assert!(work.stats().reused_inline_numeric_layouts > 0);
work.clear();
let evicted = compare_with_cold_at_viewport(
&source,
&mut styles,
&mut services,
&mut work,
after_viewport,
);
assert_eq!(work.stats().reused_inline_contexts, 0);
assert_eq!(work.stats().reused_inline_numeric_layouts, 0);
assert_eq!(evicted.tree.boxes, changed.tree.boxes);
assert_eq!(evicted.tree.fragments, changed.tree.fragments);
assert_eq!(evicted.paint_snapshot(), changed.paint_snapshot());
}
@@ -0,0 +1,102 @@
use super::*;
use moli_layout::{
EmbeddedFrameRenderer, EmbeddedFrameSnapshot, LayoutWorkingSet,
build_layout_pass_with_working_set,
};
struct NoFrames;
impl EmbeddedFrameRenderer<usize> for NoFrames {
fn render_embedded_frame(
&mut self,
_: usize,
_: LayoutViewport,
) -> Result<Option<EmbeddedFrameSnapshot<usize>>, LayoutError> {
Ok(None)
}
}
fn compare_with_cold_layout(
source: &Source,
styles: &mut Styles,
services: &mut DocumentLayoutServices,
work: &mut LayoutWorkingSet<usize>,
) -> LayoutPassResult<usize> {
let request =
LayoutPassRequest::with_paint(LayoutViewport::new(320, 240, 1.0), LayoutFlushReason::Test);
let retained = build_layout_pass_with_working_set(
source,
styles,
services,
request,
&mut NoFrames,
Some(work),
)
.unwrap();
let cold = build_layout_pass(source, styles, services, request).unwrap();
assert_eq!(retained.tree.boxes, cold.tree.boxes);
assert_eq!(retained.tree.fragments, cold.tree.fragments);
assert_eq!(retained.paint_snapshot(), cold.paint_snapshot());
for node in 0..source.0.len() {
let query = LayoutQuery::TextRangeRects {
source: node,
utf16_range: 0..usize::MAX,
};
assert_eq!(retained.answer_query(&query), cold.answer_query(&query));
}
retained
}
#[test]
fn retained_structural_inline_checks_overrides_on_the_same_computed_style() {
let source = Source(vec![
Node::element("root", vec![1, 6]),
Node::element("changing-paragraph", vec![2, 3, 5]),
Node::text("baseline-reference", "A"),
Node::html_element("shifted-inline", "span", vec![4]),
Node::text("shifted-text", "B"),
Node::text("trailing-text", "C"),
Node::element("stable-paragraph", vec![7]),
Node::text("stable-text", "unchanged"),
]);
let (mut paragraph_style, mut services) = fixed_inline_font();
let mut inline_style = paragraph_style.clone();
paragraph_style.force_layout_display(LayoutDisplay::Block);
inline_style.force_layout_display(LayoutDisplay::Inline);
let mut styles = Styles(HashMap::from([
(0, resolved(LayoutDisplay::Block, Style::default())),
(1, paragraph_style.clone()),
(3, inline_style.clone()),
(6, paragraph_style),
]));
let mut work = LayoutWorkingSet::default();
compare_with_cold_layout(&source, &mut styles, &mut services, &mut work);
assert_eq!(work.stats().reused_inline_contexts, 0);
compare_with_cold_layout(&source, &mut styles, &mut services, &mut work);
assert_eq!(work.stats().reused_inline_contexts, 2);
// The retained paragraph includes StartEdge/EndEdge objects whose
// structural box state stores vertical-align. A computed-style pointer
// alone must not authorize reusing that state after an adapter override.
for shift in [12.0, -7.0, 20.0, 0.0] {
let changed_style = inline_style.clone().with_inline_baseline_shift(shift);
assert!(style::servo_arc::Arc::ptr_eq(
inline_style.stylo_computed_values().unwrap(),
changed_style.stylo_computed_values().unwrap(),
));
styles.0.insert(3, changed_style);
let changed = compare_with_cold_layout(&source, &mut styles, &mut services, &mut work);
assert_eq!(work.stats().reused_inline_contexts, 1);
let reference = changed.text_range_rects(2, 0..1);
let shifted = changed.text_range_rects(4, 0..1);
assert_eq!(reference.len(), 1);
assert_eq!(shifted.len(), 1);
assert_close(
reference[0].bounding_rect().y - shifted[0].bounding_rect().y,
shift,
);
compare_with_cold_layout(&source, &mut styles, &mut services, &mut work);
assert_eq!(work.stats().reused_inline_contexts, 2);
}
}