Skip to content

armgit / moli

Public Imported from GitHub
0

Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust

perf(layout): reuse shaped inline layouts across probes

ldm0ac439e328e44
diff --git a/moli-layout/src/inline.rs b/moli-layout/src/inline.rs
index 1d5ec7268..3d1b030ad 100644
--- a/moli-layout/src/inline.rs
+++ b/moli-layout/src/inline.rs
@@ -133,10 +133,17 @@ pub(crate) struct InlineStructuralBox {
pub(crate) include_used_font_metrics: bool,
}
-#[derive(Clone, Debug)]
+#[derive(Debug)]
pub(crate) struct InlineFormattingContext {
pub(crate) root_style: LayoutBoxId,
- pub(crate) unbroken: Layout<TextBrush>,
+ /// Reusable Parley layout for intrinsic and final-width probes. Line
+ /// breaking replaces only Parley's line output while retaining the shaped
+ /// runs, clusters, glyphs, and their allocations, so probes must not clone
+ /// the complete shaped paragraph.
+ pub(crate) measurement_layout: Option<Layout<TextBrush>>,
+ /// The accepted `PerformLayout` result consumed by paint and CSSOM. This is
+ /// kept separate from the reusable measurement layout so a later intrinsic
+ /// probe cannot overwrite the last accepted line layout.
pub(crate) laid_out: Option<Layout<TextBrush>>,
pub(crate) text_units: Vec<InlineTextUnit>,
pub(crate) source_map: Vec<InlineSourceMapEntry>,
@@ -161,6 +168,18 @@ pub(crate) struct InlineFormattingContext {
pub(crate) fragments: InlineFragments,
}
+/// Restores the reusable Parley paragraph to its shaped, unbroken state before
+/// another inline measurement probe.
+///
+/// `text-align: justify` mutates whitespace cluster advances. Parley undoes
+/// those adjustments when a new line breaker is created, so this reset must
+/// happen before intrinsic content widths are read for the next probe. Dropping
+/// the breaker immediately also clears the previous line output while retaining
+/// its vector capacity and all shaped runs, clusters, and glyphs.
+pub(crate) fn reset_inline_layout_for_probe(layout: &mut Layout<TextBrush>) {
+ drop(layout.break_lines());
+}
+
#[derive(Clone, Copy, Debug)]
pub(crate) struct InlineStrutMetrics {
line_ascent: f32,
@@ -1667,7 +1686,7 @@ impl InlineBuildInput {
.collect();
InlineFormattingContext {
root_style: self.root_style,
- unbroken: layout,
+ measurement_layout: Some(layout),
laid_out: None,
text_units: self.units,
source_map: self.source_map,
@@ -2436,6 +2455,75 @@ mod tests {
}
}
+ #[test]
+ fn parley_shaped_layout_can_be_rebroken_across_probe_widths() {
+ let text = "alpha beta gamma delta epsilon";
+ let mut font_context = parley::FontContext::new();
+ let mut layout_context = parley::LayoutContext::<TextBrush>::new();
+ let mut builder = layout_context.style_run_builder(&mut font_context, text, 1.0, true);
+ let style = builder.push_style(TextStyle::default());
+ builder.push_style_run(style, ..);
+ let shaped = builder.build(text);
+ let mut reused = shaped.clone();
+
+ let signature = |layout: &Layout<TextBrush>| {
+ (
+ layout.width(),
+ layout.full_width(),
+ layout.height(),
+ layout
+ .lines()
+ .map(|line| (line.text_range(), line.break_reason(), *line.metrics()))
+ .collect::<Vec<_>>(),
+ )
+ };
+
+ // Exercise the same order used by Taffy: intrinsic constraints may
+ // alternate with definite widths, and a scrollbar correction may ask
+ // the accepted paragraph to break at another width later in the pass.
+ for width in [45.0, 160.0, 65.0, 160.0] {
+ reused.break_all_lines(Some(width));
+ let mut fresh = shaped.clone();
+ fresh.break_all_lines(Some(width));
+ assert_eq!(signature(&reused), signature(&fresh));
+ }
+ }
+
+ #[test]
+ fn parley_probe_reset_removes_justification_before_intrinsic_widths() {
+ let text = "alpha beta gamma delta epsilon zeta eta theta";
+ let mut font_context = parley::FontContext::new();
+ let mut layout_context = parley::LayoutContext::<TextBrush>::new();
+ let mut builder = layout_context.style_run_builder(&mut font_context, text, 1.0, true);
+ let style = builder.push_style(TextStyle::default());
+ builder.push_style_run(style, ..);
+ let shaped = builder.build(text);
+ let expected = shaped.calculate_content_widths();
+ let mut reused = shaped.clone();
+
+ reused.break_all_lines(Some(120.0));
+ reused.align(
+ parley::Alignment::Justify,
+ parley::AlignmentOptions {
+ align_when_overflowing: false,
+ },
+ );
+ let justified = reused.calculate_content_widths();
+ assert!(
+ justified.max > expected.max,
+ "the regression fixture must expose justification-mutated cluster advances"
+ );
+
+ reset_inline_layout_for_probe(&mut reused);
+ let restored = reused.calculate_content_widths();
+ assert_eq!(restored.min, expected.min);
+ assert_eq!(restored.max, expected.max);
+ assert!(
+ reused.is_empty(),
+ "a fresh probe must not retain the previous line output"
+ );
+ }
+
#[test]
fn intrinsic_line_summary_matches_materialized_line_placements() {
let root = LayoutBoxId::from_index(0);
@@ -2450,7 +2538,7 @@ mod tests {
let context = InlineFormattingContext {
root_style: root,
- unbroken: layout.clone(),
+ measurement_layout: Some(layout.clone()),
laid_out: None,
text_units: Vec::new(),
source_map: Vec::new(),
diff --git a/moli-layout/src/taffy_tree.rs b/moli-layout/src/taffy_tree.rs
index e7a891dfa..37476e8f2 100644
--- a/moli-layout/src/taffy_tree.rs
+++ b/moli-layout/src/taffy_tree.rs
@@ -19,7 +19,7 @@ use crate::{
inline::{
InlineFormattingContext, InlineFragments, InlineLinePlacement, InlineObjectRole,
break_inline_lines, build_inline_fragments, build_inline_line_placements,
- measure_inline_lines, relative_atomic_inset_offset,
+ measure_inline_lines, relative_atomic_inset_offset, reset_inline_layout_for_probe,
},
positioned::resolve_absolute_axis_margins,
replaced::measure_replaced,
@@ -1871,6 +1871,16 @@ where
.inline_layout
.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
+ // measure callback, so paint never observes probe line breaks.
+ let mut text_layout = inline_context.measurement_layout.take();
+ let final_reuses_accepted_layout = final_layout_requested && text_layout.is_none();
+ if final_reuses_accepted_layout {
+ text_layout = inline_context.laid_out.take();
+ }
let mut measurement = None;
let context = LeafLayoutContext::new(resolved_aspect_ratio, scrollbar_insets);
let mut output = compute_leaf_layout_with_context(
@@ -1879,6 +1889,8 @@ where
context,
resolve_stylo_calc_value,
|known_dimensions, available_space| {
+ let text_layout = text_layout
+ .get_or_insert_with(|| inline_context.laid_out.clone().unwrap_or_default());
let result = self.measure_inline_context(
id,
inputs,
@@ -1886,6 +1898,7 @@ where
available_space,
alignment,
&inline_context,
+ text_layout,
is_floated,
block_context,
);
@@ -1894,8 +1907,12 @@ where
size
},
);
+ let measurement_was_produced = measurement.is_some();
if let Some(mut measurement) = measurement {
+ let text_layout = text_layout
+ .as_ref()
+ .expect("an inline measurement must retain its Parley layout");
let padding = style
.padding
.resolve_or_zero(inputs.parent_size.width, resolve_stylo_calc_value);
@@ -1950,9 +1967,10 @@ where
.as_ref()
.expect("final inline layout must retain line placements");
let fragments =
- build_inline_fragments(&inline_context, &measurement.layout, line_placements);
+ build_inline_fragments(&inline_context, text_layout, line_placements);
self.position_inline_objects(
&inline_context,
+ text_layout,
&measurement,
Point {
x: padding.left + border.left + scrollbar_insets.left,
@@ -1966,10 +1984,19 @@ where
.line_placements
.take()
.expect("final inline layout lost its line placements");
- inline_context.laid_out = Some(measurement.layout);
}
}
+ if final_layout_requested && measurement_was_produced {
+ inline_context.laid_out = text_layout;
+ } else if final_reuses_accepted_layout {
+ // Preserve the previously accepted lines if a future Taffy leaf
+ // fast path can satisfy PerformLayout without invoking measure.
+ inline_context.laid_out = text_layout;
+ } else {
+ inline_context.measurement_layout = text_layout;
+ }
+
self.boxes[id.index()].inline_layout = Some(inline_context);
output
}
@@ -1982,9 +2009,17 @@ where
available_space: Size<AvailableSpace>,
alignment: parley::Alignment,
context: &InlineFormattingContext,
+ layout: &mut parley::Layout<crate::stylo_to_parley::TextBrush>,
is_floated: bool,
block_context: Option<&mut BlockContext<'_>>,
) -> InlineMeasurement {
+ // A previous probe may have justified its accepted lines, which
+ // changes whitespace cluster advances in place. Start the next probe
+ // by asking Parley to undo that line-specific state before intrinsic
+ // widths inspect the shared shaped paragraph. This clears only line
+ // output and retains the expensive shaping allocations.
+ reset_inline_layout_for_probe(layout);
+
let child_inputs = LayoutInput {
run_mode: inputs.run_mode,
sizing_mode: SizingMode::InherentSize,
@@ -2014,7 +2049,6 @@ where
// actual basis here.
let percentage_basis =
inline_percentage_basis(available_space.width, inputs.sizing_purpose);
- let mut layout = context.unbroken.clone();
let mut atomic = vec![None; context.objects.len()];
let mut atomic_baseline_ascents = vec![None; context.objects.len()];
let mut structural_edge_contributions = vec![false; context.objects.len()];
@@ -2245,7 +2279,7 @@ where
);
self.break_inline_lines_with_floats(
context,
- &mut layout,
+ layout,
width,
child_inputs,
&mut content_context,
@@ -2269,7 +2303,7 @@ where
);
self.break_inline_lines_with_floats(
context,
- &mut layout,
+ layout,
width,
child_inputs,
&mut content_context,
@@ -2283,7 +2317,7 @@ where
float_height = Some(alignment_float_height);
}
} else {
- break_inline_lines(context, &mut layout, max_advance);
+ break_inline_lines(context, layout, max_advance);
}
layout.align(
alignment,
@@ -2295,7 +2329,7 @@ where
let (line_metrics, line_placements) = if inputs.run_mode == RunMode::PerformLayout {
let (placements, metrics) = build_inline_line_placements(
context,
- &layout,
+ layout,
&atomic_baseline_ascents,
&structural_edge_contributions,
);
@@ -2304,7 +2338,7 @@ where
(
measure_inline_lines(
context,
- &layout,
+ layout,
&atomic_baseline_ascents,
&structural_edge_contributions,
),
@@ -2325,7 +2359,6 @@ where
first_baseline: line_metrics.first_baseline,
last_baseline: line_metrics.last_baseline,
has_non_phantom_line: line_metrics.has_non_phantom_line,
- layout,
atomic,
floats,
percentage_basis,
@@ -2465,6 +2498,7 @@ where
fn position_inline_objects(
&mut self,
context: &InlineFormattingContext,
+ layout: &parley::Layout<crate::stylo_to_parley::TextBrush>,
measurement: &InlineMeasurement,
content_offset: Point<f32>,
containing_block_size: Size<f32>,
@@ -2479,7 +2513,7 @@ where
floated.parent_width,
);
}
- for (line_index, line) in measurement.layout.lines().enumerate() {
+ for (line_index, line) in layout.lines().enumerate() {
let line_placement = measurement
.line_placements
.as_ref()
@@ -2714,7 +2748,6 @@ struct InlineMeasurement {
first_baseline: Option<f32>,
last_baseline: Option<f32>,
has_non_phantom_line: bool,
- layout: parley::Layout<crate::stylo_to_parley::TextBrush>,
atomic: Vec<Option<AtomicMeasurement>>,
floats: Vec<InlineFloatPlacement>,
percentage_basis: Option<f32>,
@@ -2785,7 +2818,7 @@ fn single_subject_block_alignment_offset(alignment: Option<AlignContent>, free_s
fn empty_inline_context() -> InlineFormattingContext {
InlineFormattingContext {
root_style: LayoutBoxId::from_index(0),
- unbroken: parley::Layout::default(),
+ measurement_layout: Some(parley::Layout::default()),
laid_out: None,
text_units: Vec::new(),
source_map: Vec::new(),
diff --git a/moli-layout/tests/phase5_output_contract.rs b/moli-layout/tests/phase5_output_contract.rs
index 35f52c939..757f2d208 100644
--- a/moli-layout/tests/phase5_output_contract.rs
+++ b/moli-layout/tests/phase5_output_contract.rs
@@ -766,6 +766,64 @@ fn auto_scrollbar_feedback_reveals_the_perpendicular_axis() {
assert!(extent.vertical_scrollbar.is_some());
}
+#[test]
+fn scrollbar_feedback_rebreaks_the_reused_inline_layout_at_its_final_width() {
+ const TEXT: &str = "alpha beta gamma delta epsilon zeta eta theta iota kappa";
+ let source = Source(vec![
+ Node::element("root", vec![1]),
+ Node::element("scroller", vec![2]),
+ Node::text("text", TEXT),
+ ]);
+ let mut styles = Styles::default();
+ styles
+ .0
+ .insert(0, fixed_size(LayoutDisplay::Block, 320.0, 240.0));
+ styles.0.insert(
+ 1,
+ resolved(
+ LayoutDisplay::Block,
+ Style {
+ size: Size {
+ width: length(100.0),
+ height: length(40.0),
+ },
+ overflow: Point {
+ x: Overflow::Scroll,
+ y: Overflow::Scroll,
+ },
+ ..Style::default()
+ },
+ ),
+ );
+
+ let feedback = build(&source, &mut styles);
+ assert_eq!(feedback.metrics.numeric_layout_pass_count, 2);
+ assert_eq!(
+ feedback.element_metrics_for_source(1).unwrap().client_size,
+ moli_layout::LayoutSize::new(85.0, 25.0),
+ );
+ let feedback_text = feedback.client_rects_for_source(2);
+
+ // Lay out the same paragraph directly at the converged 85px content
+ // width. Its line fragments must match the scrollbar-corrected result;
+ // otherwise paint retained the first pass's 100px Parley lines.
+ styles.0.insert(
+ 1,
+ resolved(
+ LayoutDisplay::Block,
+ Style {
+ size: Size {
+ width: length(85.0),
+ height: Dimension::auto(),
+ },
+ ..Style::default()
+ },
+ ),
+ );
+ let direct = build(&source, &mut styles);
+ assert_eq!(feedback_text, direct.client_rects_for_source(2));
+}
+
#[test]
fn scrollbar_feedback_prepares_static_position_placeholders_once() {
let source = Source(vec![