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): cull paint outside captures

ldm0112cfda8cb1e
diff --git a/moli-layout/src/inline.rs b/moli-layout/src/inline.rs
index 6c3332add..6a58509eb 100644
--- a/moli-layout/src/inline.rs
+++ b/moli-layout/src/inline.rs
@@ -276,9 +276,30 @@ pub(crate) struct InlineFragments {
pub(crate) struct InlineLineFragment {
pub(crate) line_index: usize,
pub(crate) rect: PaintRect,
+ /// Conservative glyph/decoration/shadow ink used only by capture culling.
+ /// CSSOM line geometry continues to use `rect`.
+ pub(crate) paint_bounds: InlinePaintBounds,
pub(crate) baseline: f32,
}
+#[derive(Clone, Copy, Debug, Default, PartialEq)]
+pub(crate) enum InlinePaintBounds {
+ #[default]
+ Empty,
+ Bounded(PaintRect),
+ Unbounded,
+}
+
+impl InlinePaintBounds {
+ fn include(&mut self, rect: PaintRect) {
+ *self = match *self {
+ Self::Empty => Self::Bounded(rect),
+ Self::Bounded(current) => Self::Bounded(current.union(rect)),
+ Self::Unbounded => Self::Unbounded,
+ };
+ }
+}
+
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct InlineSourceFragment {
pub(crate) line_index: usize,
@@ -306,6 +327,11 @@ pub(crate) fn build_inline_fragments(
let mut fragments = InlineFragments::default();
let mut box_fragments = HashMap::<(usize, usize), FragmentAccumulator>::new();
let mut source_fragments = HashMap::<SourceFragmentKey, FragmentAccumulator>::new();
+ let style_paint_outsets = layout
+ .styles()
+ .iter()
+ .map(text_style_paint_outsets)
+ .collect::<Vec<_>>();
for (line_index, line) in layout.lines().enumerate() {
let metrics = line.metrics();
@@ -326,6 +352,12 @@ pub(crate) fn build_inline_fragments(
fragments.lines.push(InlineLineFragment {
line_index,
rect: line_rect,
+ paint_bounds: context
+ .selection
+ .as_ref()
+ .map_or(InlinePaintBounds::Empty, |_| {
+ InlinePaintBounds::Bounded(line_rect)
+ }),
baseline: placement.map_or(metrics.baseline, |placement| placement.baseline),
});
if let Some(placement) = placement {
@@ -368,6 +400,24 @@ pub(crate) fn build_inline_fragments(
cluster.advance().max(0.0),
(ascent + descent).max(0.0),
);
+ if let Some(style) = layout.styles().get(style_index)
+ && style.brush.paint
+ {
+ // Parley exposes typographic cluster boxes rather than
+ // exact outline bounds. A two-em guard is deliberately
+ // conservative for italic/color-glyph overhang, while the
+ // style sidecar adds arbitrary CSS shadow/decoration
+ // displacement. This work happens once, alongside final
+ // fragment materialization, not during every paint.
+ let glyph_guard = run.font_size().max(0.0) * 2.0 + 1.0;
+ let line = &mut fragments.lines[line_index];
+ match style_paint_outsets.get(style_index).copied().flatten() {
+ Some(outsets) => {
+ line.paint_bounds.include(outsets.outset(rect, glyph_guard))
+ }
+ None => line.paint_bounds = InlinePaintBounds::Unbounded,
+ }
+ }
for unit in overlapping_output_ranges(&context.text_units, &range) {
for ancestor in &unit.ancestors {
box_fragments
@@ -472,6 +522,63 @@ pub(crate) fn build_inline_fragments(
fragments
}
+#[derive(Clone, Copy, Debug, Default)]
+struct TextPaintOutsets {
+ top: f32,
+ right: f32,
+ bottom: f32,
+ left: f32,
+}
+
+impl TextPaintOutsets {
+ fn outset(self, rect: PaintRect, guard: f32) -> PaintRect {
+ let top = self.top.max(0.0) + guard;
+ let right = self.right.max(0.0) + guard;
+ let bottom = self.bottom.max(0.0) + guard;
+ let left = self.left.max(0.0) + guard;
+ PaintRect::new(
+ rect.x - left,
+ rect.y - top,
+ (rect.width + left + right).max(0.0),
+ (rect.height + top + bottom).max(0.0),
+ )
+ }
+}
+
+fn text_style_paint_outsets(style: &parley::layout::Style<TextBrush>) -> Option<TextPaintOutsets> {
+ let mut outsets = TextPaintOutsets::default();
+ for shadow in style
+ .brush
+ .shadows
+ .iter()
+ .filter(|shadow| shadow.color.alpha > 0.0)
+ {
+ if !shadow.offset.x.is_finite()
+ || !shadow.offset.y.is_finite()
+ || !shadow.blur_radius.is_finite()
+ {
+ return None;
+ }
+ let blur = shadow.blur_radius.max(0.0) * 4.0 + 1.0;
+ outsets.left = outsets.left.max(blur - shadow.offset.x);
+ outsets.right = outsets.right.max(blur + shadow.offset.x);
+ outsets.top = outsets.top.max(blur - shadow.offset.y);
+ outsets.bottom = outsets.bottom.max(blur + shadow.offset.y);
+ }
+
+ let decoration = style.brush.decoration;
+ if decoration.underline || decoration.overline || decoration.line_through {
+ // Normal decoration ink remains inside the guarded typographic box.
+ // Authored underline offsets can move it arbitrarily far away.
+ let displaced = decoration.underline_offset.unwrap_or_default().abs()
+ + decoration.thickness.unwrap_or(1.0).max(0.0) * 3.0
+ + 1.0;
+ outsets.top = outsets.top.max(displaced);
+ outsets.bottom = outsets.bottom.max(displaced);
+ }
+ Some(outsets)
+}
+
/// Breaks a shared IFC text stream while preserving CSS `break-spaces`
/// trailing-space semantics that Parley 0.10 does not model directly.
pub(crate) fn break_inline_lines(
diff --git a/moli-layout/src/layout_tree/pass_result.rs b/moli-layout/src/layout_tree/pass_result.rs
index 9bd4aee16..b6f3c0ace 100644
--- a/moli-layout/src/layout_tree/pass_result.rs
+++ b/moli-layout/src/layout_tree/pass_result.rs
@@ -54,6 +54,15 @@ pub struct LayoutPassMetrics {
pub numeric_feedback_invalidated_node_count: usize,
pub box_count: usize,
pub fragment_count: usize,
+ /// Paint-order events considered for this capture before viewport culling.
+ pub paint_event_count: usize,
+ /// Paint-order events skipped because their conservative ink bounds did
+ /// not intersect the capture cull rect.
+ pub paint_culled_event_count: usize,
+ /// Final inline lines considered across foreground and text-mask paint.
+ pub paint_text_line_count: usize,
+ /// Inline lines whose conservative ink bounds missed the capture.
+ pub paint_culled_text_line_count: usize,
pub paint_operation_count: usize,
pub fallback_count: usize,
}
diff --git a/moli-layout/src/paint/background.rs b/moli-layout/src/paint/background.rs
index 525056305..9eba47ff2 100644
--- a/moli-layout/src/paint/background.rs
+++ b/moli-layout/src/paint/background.rs
@@ -107,7 +107,7 @@ pub(super) fn project_background_color<N>(
paint_space: PaintSpace,
color: PaintColor,
snapshot: &mut PaintSnapshot,
- text_clip_mask: &impl Fn(&mut PaintSnapshot),
+ text_clip_mask: &mut impl FnMut(&mut PaintSnapshot),
) where
N: Copy + Debug + Eq + Hash,
{
@@ -156,7 +156,7 @@ pub(super) fn project_background_layers<N>(
areas: BoxAreas,
paint_space: PaintSpace,
snapshot: &mut PaintSnapshot,
- text_clip_mask: &impl Fn(&mut PaintSnapshot),
+ text_clip_mask: &mut impl FnMut(&mut PaintSnapshot),
) where
N: Copy + Debug + Eq + Hash,
{
@@ -310,7 +310,7 @@ fn finish_background_text_clip_layer(
clip: PaintShape,
transform: LayoutTransform2D,
snapshot: &mut PaintSnapshot,
- text_clip_mask: &impl Fn(&mut PaintSnapshot),
+ text_clip_mask: &mut impl FnMut(&mut PaintSnapshot),
) {
snapshot.push_fragment(PaintFragment::PushLayer {
opacity: 1.0,
diff --git a/moli-layout/src/paint/cull.rs b/moli-layout/src/paint/cull.rs
new file mode 100644
index 000000000..bc486a67d
--- /dev/null
+++ b/moli-layout/src/paint/cull.rs
@@ -0,0 +1,519 @@
+//! Capture-aware conservative paint culling.
+//!
+//! Blink maps a cull rect through its paint property trees and falls back to
+//! an infinite rect below effects that can move pixels. Moli has a linear
+//! paint-order stream instead of retained paint chunks, so this module builds
+//! the equivalent one-shot sidecar: exact event ink bounds, balanced stacking
+//! context ranges, and the few boundaries where descendant culling must stop.
+
+use std::{fmt::Debug, hash::Hash};
+
+use super::{
+ filters::{expanded_filter_clip, project_filters},
+ geometry::BoxAreas,
+};
+use crate::{
+ LayoutBoxId, LayoutPoint, LayoutRect, LayoutTransform2D, PaintFilter, PaintFragment,
+ inline::InlinePaintBounds, projection::OutputProjection, stacking::PaintOrderEvent,
+};
+
+const CULL_ANTIALIAS_MARGIN: f32 = 1.0;
+
+#[derive(Clone, Copy, Debug, PartialEq)]
+enum PaintCullBounds {
+ Empty,
+ Bounded(LayoutRect),
+ Unbounded,
+}
+
+impl PaintCullBounds {
+ fn include(&mut self, other: Self) {
+ *self = match (*self, other) {
+ (Self::Unbounded, _) | (_, Self::Unbounded) => Self::Unbounded,
+ (Self::Empty, other) => other,
+ (current, Self::Empty) => current,
+ (Self::Bounded(current), Self::Bounded(other)) => Self::Bounded(current.union(other)),
+ };
+ }
+
+ fn misses(self, region: PaintCullRegion) -> bool {
+ match (self, region) {
+ (Self::Empty, _) => true,
+ (Self::Unbounded, _) | (_, PaintCullRegion::Infinite) => false,
+ (Self::Bounded(bounds), PaintCullRegion::Bounded(cull)) => {
+ !rects_intersect(bounds, cull)
+ }
+ }
+ }
+}
+
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub(super) enum PaintCullRegion {
+ Bounded(LayoutRect),
+ Infinite,
+}
+
+impl PaintCullRegion {
+ pub(super) fn for_capture(rect: LayoutRect) -> Self {
+ Self::Bounded(outset_rect(
+ rect,
+ CULL_ANTIALIAS_MARGIN,
+ CULL_ANTIALIAS_MARGIN,
+ CULL_ANTIALIAS_MARGIN,
+ CULL_ANTIALIAS_MARGIN,
+ ))
+ }
+
+ pub(super) fn local_rect(self, local_to_viewport: LayoutTransform2D) -> Option<LayoutRect> {
+ let Self::Bounded(rect) = self else {
+ return None;
+ };
+ let inverse = local_to_viewport.inverse()?;
+ let mapped = inverse.map_rect(rect).bounding_rect();
+ rect_is_finite(mapped).then_some(mapped)
+ }
+}
+
+#[derive(Clone, Copy, Debug)]
+struct PaintCullPlanEntry {
+ bounds: PaintCullBounds,
+ matching_pop: Option<usize>,
+ disables_descendant_culling: bool,
+}
+
+impl Default for PaintCullPlanEntry {
+ fn default() -> Self {
+ Self {
+ bounds: PaintCullBounds::Unbounded,
+ matching_pop: None,
+ disables_descendant_culling: false,
+ }
+ }
+}
+
+#[derive(Debug)]
+struct ContextAccumulator {
+ push_index: usize,
+ id: LayoutBoxId,
+ bounds: PaintCullBounds,
+}
+
+pub(super) struct PaintCullPlan {
+ entries: Vec<PaintCullPlanEntry>,
+}
+
+impl PaintCullPlan {
+ pub(super) fn build<N>(projection: &OutputProjection<'_, N>) -> Self
+ where
+ N: Copy + Debug + Eq + Hash,
+ {
+ let mut entries = vec![PaintCullPlanEntry::default(); projection.paint_events.len()];
+ let mut contexts = Vec::<ContextAccumulator>::new();
+
+ for (index, event) in projection.paint_events.iter().copied().enumerate() {
+ match event {
+ PaintOrderEvent::PushStackingContext(id) => {
+ contexts.push(ContextAccumulator {
+ push_index: index,
+ id,
+ bounds: PaintCullBounds::Empty,
+ });
+ }
+ PaintOrderEvent::PopStackingContext(id) => {
+ let Some(context) = contexts.pop() else {
+ continue;
+ };
+ debug_assert_eq!(context.id, id);
+ let (bounds, disables_descendant_culling) =
+ context_output_bounds(projection, id, context.bounds);
+ entries[context.push_index] = PaintCullPlanEntry {
+ bounds,
+ matching_pop: Some(index),
+ disables_descendant_culling,
+ };
+ entries[index] = PaintCullPlanEntry {
+ bounds,
+ matching_pop: None,
+ disables_descendant_culling: false,
+ };
+ if let Some(parent) = contexts.last_mut() {
+ parent.bounds.include(bounds);
+ }
+ }
+ _ => {
+ let bounds = event_ink_bounds(projection, event);
+ entries[index] = PaintCullPlanEntry {
+ bounds,
+ matching_pop: None,
+ disables_descendant_culling: false,
+ };
+ if let Some(context) = contexts.last_mut() {
+ context.bounds.include(bounds);
+ }
+ }
+ }
+ }
+
+ debug_assert!(contexts.is_empty(), "paint-order contexts must be balanced");
+ Self { entries }
+ }
+
+ pub(super) fn event_misses(&self, index: usize, region: PaintCullRegion) -> bool {
+ self.entries[index].bounds.misses(region)
+ }
+
+ pub(super) fn matching_pop(&self, index: usize) -> Option<usize> {
+ self.entries[index].matching_pop
+ }
+
+ pub(super) fn disables_descendant_culling(&self, index: usize) -> bool {
+ self.entries[index].disables_descendant_culling
+ }
+}
+
+fn event_ink_bounds<N>(
+ projection: &OutputProjection<'_, N>,
+ event: PaintOrderEvent,
+) -> PaintCullBounds
+where
+ N: Copy + Debug + Eq + Hash,
+{
+ match event {
+ PaintOrderEvent::BoxOutsetShadow(id) => outset_shadow_bounds(projection, id),
+ PaintOrderEvent::BoxBackground(id) => box_background_bounds(projection, id),
+ PaintOrderEvent::TableCollapsedBorders(id) => table_border_bounds(projection, id),
+ PaintOrderEvent::BoxContents(id) => box_contents_bounds(projection, id),
+ PaintOrderEvent::BoxOutline(id) => box_outline_bounds(projection, id),
+ PaintOrderEvent::PushStackingContext(_) | PaintOrderEvent::PopStackingContext(_) => {
+ PaintCullBounds::Empty
+ }
+ }
+}
+
+fn box_background_bounds<N>(
+ projection: &OutputProjection<'_, N>,
+ id: LayoutBoxId,
+) -> PaintCullBounds
+where
+ N: Copy + Debug + Eq + Hash,
+{
+ let layout_box = &projection.world.boxes[id.index()];
+ if layout_box.inline_flattened || !layout_box.style.is_visible() {
+ return PaintCullBounds::Empty;
+ }
+ let bounds = map_box_rect(projection, id, projection.boxes[id.index()].border_box);
+ if matches!(bounds, PaintCullBounds::Empty) && layout_box.is_replaced() {
+ // Replaced-content projection can publish a fallback diagnostic even
+ // when its used box has no ink. Do not make diagnostics depend on the
+ // capture cull rect.
+ PaintCullBounds::Unbounded
+ } else {
+ bounds
+ }
+}
+
+fn box_contents_bounds<N>(projection: &OutputProjection<'_, N>, id: LayoutBoxId) -> PaintCullBounds
+where
+ N: Copy + Debug + Eq + Hash,
+{
+ let layout_box = &projection.world.boxes[id.index()];
+ if !layout_box.style.is_visible() {
+ return PaintCullBounds::Empty;
+ }
+ let mut local = projection.boxes[id.index()].border_box;
+ if let Some(context) = layout_box.inline_layout.as_ref() {
+ let layout = layout_box.final_layout;
+ let origin = LayoutPoint::new(
+ layout.border.left + layout.padding.left,
+ layout.border.top + layout.padding.top,
+ );
+ for line in &context.fragments.lines {
+ match line.paint_bounds {
+ InlinePaintBounds::Empty => {}
+ InlinePaintBounds::Bounded(bounds) => {
+ local = local.union(offset_rect(bounds, origin));
+ }
+ InlinePaintBounds::Unbounded => return PaintCullBounds::Unbounded,
+ }
+ }
+ }
+ let bounds = map_box_rect(projection, id, local);
+ if matches!(bounds, PaintCullBounds::Empty) && layout_box.is_replaced() {
+ PaintCullBounds::Unbounded
+ } else {
+ bounds
+ }
+}
+
+fn table_border_bounds<N>(projection: &OutputProjection<'_, N>, id: LayoutBoxId) -> PaintCullBounds
+where
+ N: Copy + Debug + Eq + Hash,
+{
+ let layout_box = &projection.world.boxes[id.index()];
+ if !layout_box.style.is_visible() {
+ return PaintCullBounds::Empty;
+ }
+ let Some(borders) = layout_box.collapsed_table_borders.as_ref() else {
+ return PaintCullBounds::Empty;
+ };
+ let mut bounds = PaintCullBounds::Empty;
+ for segment in borders.segments() {
+ bounds.include(map_box_rect(projection, id, segment.rect));
+ }
+ bounds
+}
+
+fn outset_shadow_bounds<N>(projection: &OutputProjection<'_, N>, id: LayoutBoxId) -> PaintCullBounds
+where
+ N: Copy + Debug + Eq + Hash,
+{
+ let layout_box = &projection.world.boxes[id.index()];
+ if layout_box.inline_flattened || !layout_box.style.is_visible() {
+ return PaintCullBounds::Empty;
+ }
+ let geometry = &projection.boxes[id.index()];
+ let paint_space = projection.coordinate_spaces[geometry.coordinate_space.index()].paint;
+ let areas = BoxAreas::for_box(projection, id);
+ let mut bounds = PaintCullBounds::Empty;
+ for shadow in layout_box
+ .style
+ .box_shadows(
+ paint_space.pre_transform_rect(areas.border_rect),
+ areas.border_radii,
+ paint_space.property_transform(),
+ )
+ .into_iter()
+ .filter(|shadow| !shadow.inset && shadow.color.alpha > 0.0)
+ {
+ if !shadow.blur_radius.is_finite()
+ || !shadow.spread_radius.is_finite()
+ || !shadow.offset.x.is_finite()
+ || !shadow.offset.y.is_finite()
+ {
+ return PaintCullBounds::Unbounded;
+ }
+ // Match the software rasterizer's deliberately conservative shadow
+ // clip. Keeping the same four-sigma blur guard makes the culler unable
+ // to discard any pixels the backend could still touch.
+ let spread = shadow.spread_radius.max(0.0);
+ let blur = shadow.blur_radius.max(0.0);
+ let extent = spread + blur * 4.0 + shadow.offset.x.hypot(shadow.offset.y) + 1.0;
+ let shifted = LayoutRect::new(
+ shadow.rect.x + shadow.offset.x,
+ shadow.rect.y + shadow.offset.y,
+ shadow.rect.width,
+ shadow.rect.height,
+ );
+ bounds.include(map_rect(
+ shadow.transform,
+ outset_rect(shifted, extent, extent, extent, extent),
+ ));
+ }
+ bounds
+}
+
+fn box_outline_bounds<N>(projection: &OutputProjection<'_, N>, id: LayoutBoxId) -> PaintCullBounds
+where
+ N: Copy + Debug + Eq + Hash,
+{
+ let layout_box = &projection.world.boxes[id.index()];
+ if layout_box.inline_flattened || !layout_box.style.is_visible() {
+ return PaintCullBounds::Empty;
+ }
+ let geometry = &projection.boxes[id.index()];
+ let paint_space = projection.coordinate_spaces[geometry.coordinate_space.index()].paint;
+ let mut bounds = PaintCullBounds::Empty;
+ let radii = layout_box
+ .style
+ .border_radii(geometry.border_box.width, geometry.border_box.height);
+ if let Some(PaintFragment::Border {
+ rect, transform, ..
+ }) = layout_box.style.outline_fragment(
+ paint_space.pre_transform_rect(geometry.border_box),
+ radii,
+ paint_space.property_transform(),
+ ) {
+ bounds.include(map_rect(transform, rect));
+ }
+
+ let extent = &projection.scroll_extents[id.index()];
+ let scrollbar_transform = if id == projection.world.root {
+ LayoutTransform2D::IDENTITY
+ } else {
+ paint_space.local_transform()
+ };
+ for rect in [
+ extent.horizontal_scrollbar.map(|scrollbar| scrollbar.frame),
+ extent.vertical_scrollbar.map(|scrollbar| scrollbar.frame),
+ extent.scrollbar_corner,
+ ]
+ .into_iter()
+ .flatten()
+ {
+ bounds.include(map_rect(scrollbar_transform, rect));
+ }
+ bounds
+}
+
+fn context_output_bounds<N>(
+ projection: &OutputProjection<'_, N>,
+ id: LayoutBoxId,
+ source_bounds: PaintCullBounds,
+) -> (PaintCullBounds, bool)
+where
+ N: Copy + Debug + Eq + Hash,
+{
+ let filters = project_filters(&projection.world.boxes[id.index()].style);
+ let moves_pixels = filters.effects.iter().any(filter_moves_pixels);
+ let unsupported_transform = projection.resolved_transform_has_unsupported_3d(id);
+ if unsupported_transform {
+ return (PaintCullBounds::Unbounded, true);
+ }
+ let PaintCullBounds::Bounded(viewport_bounds) = source_bounds else {
+ return (source_bounds, moves_pixels);
+ };
+ if !moves_pixels {
+ return (source_bounds, false);
+ }
+
+ let geometry = &projection.boxes[id.index()];
+ let transform = projection.coordinate_spaces[geometry.coordinate_space.index()]
+ .paint
+ .local_transform();
+ let Some(inverse) = transform.inverse() else {
+ return (PaintCullBounds::Unbounded, true);
+ };
+ let local_bounds = inverse.map_rect(viewport_bounds).bounding_rect();
+ if !rect_is_finite(local_bounds) {
+ return (PaintCullBounds::Unbounded, true);
+ }
+ (
+ map_rect(
+ transform,
+ expanded_filter_clip(local_bounds, &filters.effects),
+ ),
+ true,
+ )
+}
+
+fn filter_moves_pixels(filter: &PaintFilter) -> bool {
+ matches!(
+ filter,
+ PaintFilter::Blur(_) | PaintFilter::DropShadow { .. }
+ )
+}
+
+fn map_box_rect<N>(
+ projection: &OutputProjection<'_, N>,
+ id: LayoutBoxId,
+ rect: LayoutRect,
+) -> PaintCullBounds
+where
+ N: Copy + Debug + Eq + Hash,
+{
+ let geometry = &projection.boxes[id.index()];
+ let transform = projection.coordinate_spaces[geometry.coordinate_space.index()]
+ .paint
+ .local_transform();
+ map_rect(transform, rect)
+}
+
+fn map_rect(transform: LayoutTransform2D, rect: LayoutRect) -> PaintCullBounds {
+ if !transform.is_finite() || !rect_is_finite(rect) {
+ return PaintCullBounds::Unbounded;
+ }
+ if rect.width <= 0.0 || rect.height <= 0.0 {
+ return PaintCullBounds::Empty;
+ }
+ let mapped = transform.map_rect(rect).bounding_rect();
+ if !rect_is_finite(mapped) {
+ PaintCullBounds::Unbounded
+ } else if mapped.width <= 0.0 || mapped.height <= 0.0 {
+ PaintCullBounds::Empty
+ } else {
+ PaintCullBounds::Bounded(mapped)
+ }
+}
+
+pub(super) fn rects_intersect(left: LayoutRect, right: LayoutRect) -> bool {
+ rect_is_finite(left)
+ && rect_is_finite(right)
+ && left.width >= 0.0
+ && left.height >= 0.0
+ && right.width >= 0.0
+ && right.height >= 0.0
+ && left.x <= right.right()
+ && left.right() >= right.x
+ && left.y <= right.bottom()
+ && left.bottom() >= right.y
+}
+
+fn rect_is_finite(rect: LayoutRect) -> bool {
+ [rect.x, rect.y, rect.width, rect.height]
+ .into_iter()
+ .all(f32::is_finite)
+}
+
+fn offset_rect(rect: LayoutRect, offset: LayoutPoint) -> LayoutRect {
+ LayoutRect::new(
+ rect.x + offset.x,
+ rect.y + offset.y,
+ rect.width,
+ rect.height,
+ )
+}
+
+fn outset_rect(rect: LayoutRect, top: f32, right: f32, bottom: f32, left: f32) -> LayoutRect {
+ LayoutRect::new(
+ rect.x - left,
+ rect.y - top,
+ (rect.width + left + right).max(0.0),
+ (rect.height + top + bottom).max(0.0),
+ )
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn touching_and_partially_overlapping_rects_are_kept() {
+ let capture = LayoutRect::new(0.0, 0.0, 100.0, 100.0);
+ assert!(rects_intersect(
+ capture,
+ LayoutRect::new(100.0, 20.0, 10.0, 10.0)
+ ));
+ assert!(rects_intersect(
+ capture,
+ LayoutRect::new(99.0, 99.0, 10.0, 10.0)
+ ));
+ assert!(!rects_intersect(
+ capture,
+ LayoutRect::new(101.0, 20.0, 10.0, 10.0)
+ ));
+ }
+
+ #[test]
+ fn singular_or_non_finite_mappings_disable_culling() {
+ assert_eq!(
+ PaintCullRegion::Bounded(LayoutRect::new(0.0, 0.0, 10.0, 10.0))
+ .local_rect(LayoutTransform2D::scale(0.0, 0.0)),
+ None
+ );
+ assert_eq!(
+ map_rect(
+ LayoutTransform2D::new([f64::NAN, 0.0, 0.0, 1.0, 0.0, 0.0]),
+ LayoutRect::new(0.0, 0.0, 10.0, 10.0),
+ ),
+ PaintCullBounds::Unbounded
+ );
+ }
+
+ #[test]
+ fn capture_cull_rect_keeps_an_antialias_guard_band() {
+ assert_eq!(
+ PaintCullRegion::for_capture(LayoutRect::new(10.0, 20.0, 30.0, 40.0)),
+ PaintCullRegion::Bounded(LayoutRect::new(9.0, 19.0, 32.0, 42.0))
+ );
+ }
+}
diff --git a/moli-layout/src/paint/inline_boxes.rs b/moli-layout/src/paint/inline_boxes.rs
index f40f4feb0..58f6c2b41 100644
--- a/moli-layout/src/paint/inline_boxes.rs
+++ b/moli-layout/src/paint/inline_boxes.rs
@@ -24,7 +24,8 @@ pub(super) fn project_inline_box_fragments<N>(
paint_space: PaintSpace,
include_backgrounds: bool,
snapshot: &mut PaintSnapshot,
- text_clip_mask: &impl Fn(TextClipMaskScope, &mut PaintSnapshot),
+ local_cull: Option<LayoutRect>,
+ text_clip_mask: &mut impl FnMut(TextClipMaskScope, &mut PaintSnapshot),
) where
N: Copy + Debug + Eq + Hash,
{
@@ -91,6 +92,9 @@ pub(super) fn project_inline_box_fragments<N>(
if rect.width <= 0.0 || rect.height <= 0.0 {
continue;
}
+ if local_cull.is_some_and(|cull| !super::cull::rects_intersect(rect, cull)) {
+ continue;
+ }
let color = style.background_color();
let radii = style.border_radii(rect.width, rect.height);
let widths = PaintEdgeSizes::new(
@@ -132,7 +136,7 @@ pub(super) fn project_inline_box_fragments<N>(
// Flattened inline descendants share the owner's Parley output. Give
// the callback an explicit target so text.rs selects this structural
// inline's glyph runs before background.rs applies the fragment clip.
- let project_text_clip_mask = |snapshot: &mut PaintSnapshot| {
+ let mut project_text_clip_mask = |snapshot: &mut PaintSnapshot| {
text_clip_mask(TextClipMaskScope::InlineBox(fragment.box_id), snapshot);
};
if include_backgrounds {
@@ -142,14 +146,14 @@ pub(super) fn project_inline_box_fragments<N>(
paint_space,
color,
snapshot,
- &project_text_clip_mask,
+ &mut project_text_clip_mask,
);
project_background_layers(
inline_box,
areas,
paint_space,
snapshot,
- &project_text_clip_mask,
+ &mut project_text_clip_mask,
);
}
diff --git a/moli-layout/src/paint/mod.rs b/moli-layout/src/paint/mod.rs
index 66062e805..716ff79a6 100644
--- a/moli-layout/src/paint/mod.rs
+++ b/moli-layout/src/paint/mod.rs
@@ -1,5 +1,6 @@
mod background;
mod clip_path;
+mod cull;
mod filters;
mod form_controls;
mod geometry;
@@ -14,6 +15,7 @@ use std::{collections::HashMap, fmt::Debug, hash::Hash};
use background::{project_background_color, project_background_layers};
use clip_path::{ClipPathUnsupported, project_clip_path};
+use cull::{PaintCullPlan, PaintCullRegion};
use filters::{expanded_filter_clip, project_filters};
use form_controls::project_form_control_appearance;
use geometry::{BoxAreas, BoxModelBox, canonical_shape, inset_radii};
@@ -41,6 +43,19 @@ struct ContextPaintState {
clip_path_layer: bool,
}
+#[derive(Clone, Copy, Debug, Default)]
+pub(crate) struct PaintProjectionMetrics {
+ pub(crate) event_count: usize,
+ pub(crate) culled_event_count: usize,
+ pub(crate) text_line_count: usize,
+ pub(crate) culled_text_line_count: usize,
+}
+
+pub(crate) struct PaintProjectionResult {
+ pub(crate) snapshot: PaintSnapshot,
+ pub(crate) metrics: PaintProjectionMetrics,
+}
+
/// Paint-property-tree cursor for ordinary overflow clips.
///
/// `OutputProjection` already interns every clip as a stable chain node. Keep
@@ -117,7 +132,7 @@ pub(crate) fn project_paint_snapshot<N>(
projection: &OutputProjection<'_, N>,
capture: ResolvedPaintCapture,
embedded_frames: &mut HashMap<LayoutBoxId, PaintSnapshot>,
-) -> PaintSnapshot
+) -> PaintProjectionResult
where
N: Copy + Debug + Eq + Hash,
{
@@ -132,14 +147,22 @@ where
snapshot.viewport_to_surface = capture.viewport_to_surface;
snapshot.content_size = projection.document_content_size();
snapshot.diagnostics = projection.diagnostics.clone();
+ let cull_plan = PaintCullPlan::build(projection);
+ let mut metrics = PaintProjectionMetrics {
+ event_count: projection.paint_events.len(),
+ ..PaintProjectionMetrics::default()
+ };
+ let mut current_cull = PaintCullRegion::for_capture(capture.viewport_rect);
if let Some(background) = propagated_background {
let transform = capture.viewport_to_surface;
let paint_space = PaintSpace::ROOT.with_outer_transform(transform);
- let text_clip_mask = |snapshot: &mut PaintSnapshot| {
+ let mut text_clip_mask = |snapshot: &mut PaintSnapshot| {
project_background_text_clip_mask(
projection,
background,
TextClipMaskScope::AllGlyphs,
+ current_cull,
+ &mut metrics,
snapshot,
);
};
@@ -148,14 +171,45 @@ where
BoxAreas::for_rect(capture.viewport_rect),
paint_space,
&mut snapshot,
- &text_clip_mask,
+ &mut text_clip_mask,
);
}
+ let mut context_cull_regions = Vec::new();
let mut context_layers = Vec::new();
let mut active_clips = ActivePaintClipChain::default();
- for event in &projection.paint_events {
- match *event {
+ let mut event_index = 0usize;
+ while event_index < projection.paint_events.len() {
+ let event = projection.paint_events[event_index];
+ if let PaintOrderEvent::PushStackingContext(_) = event {
+ // Context boundaries reset ordinary overflow clips even when the
+ // complete balanced range is outside this capture.
+ active_clips.clear(&mut snapshot);
+ if cull_plan.event_misses(event_index, current_cull)
+ && let Some(pop_index) = cull_plan.matching_pop(event_index)
+ {
+ metrics.culled_event_count = metrics
+ .culled_event_count
+ .saturating_add(pop_index - event_index + 1);
+ event_index = pop_index + 1;
+ continue;
+ }
+ context_cull_regions.push(current_cull);
+ if cull_plan.disables_descendant_culling(event_index) {
+ // Like Blink's infinite cull rect below a pixel-moving
+ // filter/perspective boundary: source pixels outside the
+ // capture may still contribute to visible output.
+ current_cull = PaintCullRegion::Infinite;
+ }
+ } else if !matches!(event, PaintOrderEvent::PopStackingContext(_))
+ && cull_plan.event_misses(event_index, current_cull)
+ {
+ metrics.culled_event_count = metrics.culled_event_count.saturating_add(1);
+ event_index += 1;
+ continue;
+ }
+
+ match event {
PaintOrderEvent::BoxOutsetShadow(id) => {
active_clips.transition_to(
projection,
@@ -165,7 +219,6 @@ where
project_outset_box_shadows(projection, id, &mut snapshot);
}
PaintOrderEvent::PushStackingContext(id) => {
- active_clips.clear(&mut snapshot);
let layout_box = &projection.world.boxes[id.index()];
let style = &layout_box.style;
let geometry = &projection.boxes[id.index()];
@@ -316,6 +369,8 @@ where
propagated_background,
embedded_frames.contains_key(&id),
capture.include_backgrounds,
+ current_cull,
+ &mut metrics,
&mut snapshot,
);
}
@@ -330,6 +385,8 @@ where
id,
embedded_frames,
capture.include_backgrounds,
+ current_cull,
+ &mut metrics,
&mut snapshot,
);
}
@@ -399,12 +456,17 @@ where
})
)
);
+ current_cull = context_cull_regions
+ .pop()
+ .expect("stacking cull regions are structurally balanced");
}
}
+ event_index += 1;
}
active_clips.clear(&mut snapshot);
debug_assert!(context_layers.is_empty());
- snapshot
+ debug_assert!(context_cull_regions.is_empty());
+ PaintProjectionResult { snapshot, metrics }
}
fn owned_clip_chain<N>(
@@ -539,6 +601,8 @@ fn project_box_background<N>(
propagated_background: Option<LayoutBoxId>,
has_embedded_frame: bool,
include_backgrounds: bool,
+ cull: PaintCullRegion,
+ metrics: &mut PaintProjectionMetrics,
snapshot: &mut PaintSnapshot,
) where
N: Copy + Debug + Eq + Hash,
@@ -588,11 +652,13 @@ fn project_box_background<N>(
}
None => {}
}
- let text_clip_mask = |snapshot: &mut PaintSnapshot| {
+ let mut text_clip_mask = |snapshot: &mut PaintSnapshot| {
project_background_text_clip_mask(
projection,
id,
TextClipMaskScope::AllGlyphs,
+ cull,
+ metrics,
snapshot,
);
};
@@ -602,9 +668,15 @@ fn project_box_background<N>(
paint_space,
color,
snapshot,
- &text_clip_mask,
+ &mut text_clip_mask,
+ );
+ project_background_layers(
+ layout_box,
+ areas,
+ paint_space,
+ snapshot,
+ &mut text_clip_mask,
);
- project_background_layers(layout_box, areas, paint_space, snapshot, &text_clip_mask);
}
let layout = layout_box.final_layout;
@@ -642,11 +714,13 @@ fn project_background_text_clip_mask<N>(
projection: &OutputProjection<'_, N>,
root: LayoutBoxId,
scope: TextClipMaskScope,
+ cull: PaintCullRegion,
+ metrics: &mut PaintProjectionMetrics,
snapshot: &mut PaintSnapshot,
) where
N: Copy + Debug + Eq + Hash,
{
- project_box_text_clip_mask(projection, root, scope, snapshot);
+ project_box_text_clip_mask(projection, root, scope, cull, metrics, snapshot);
// A block/background root owns every descendant IFC. A flattened inline
// instead selects its runs from the shared root IFC, then includes only
@@ -668,7 +742,14 @@ fn project_background_text_clip_mask<N>(
while let Some(id) = stack.pop() {
let layout_box = &projection.world.boxes[id.index()];
stack.extend(layout_box.children.iter().rev().copied());
- project_box_text_clip_mask(projection, id, TextClipMaskScope::AllGlyphs, snapshot);
+ project_box_text_clip_mask(
+ projection,
+ id,
+ TextClipMaskScope::AllGlyphs,
+ cull,
+ metrics,
+ snapshot,
+ );
}
}
@@ -676,6 +757,8 @@ fn project_box_text_clip_mask<N>(
projection: &OutputProjection<'_, N>,
id: LayoutBoxId,
scope: TextClipMaskScope,
+ cull: PaintCullRegion,
+ metrics: &mut PaintProjectionMetrics,
snapshot: &mut PaintSnapshot,
) where
N: Copy + Debug + Eq + Hash,
@@ -685,13 +768,13 @@ fn project_box_text_clip_mask<N>(
return;
}
let geometry = &projection.boxes[id.index()];
- let transform = snapshot.viewport_to_surface.concatenate(
- projection.coordinate_spaces[geometry.coordinate_space.index()]
- .paint
- .local_transform(),
- );
+ let viewport_transform = projection.coordinate_spaces[geometry.coordinate_space.index()]
+ .paint
+ .local_transform();
+ 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, snapshot, scope);
+ project_text_clip_mask(layout_box, transform, local_cull, metrics, snapshot, scope);
pop_clips(clip_count, snapshot);
}
@@ -767,6 +850,8 @@ fn project_box_contents<N>(
id: LayoutBoxId,
embedded_frames: &mut HashMap<LayoutBoxId, PaintSnapshot>,
include_backgrounds: bool,
+ cull: PaintCullRegion,
+ metrics: &mut PaintProjectionMetrics,
snapshot: &mut PaintSnapshot,
) where
N: Copy + Debug + Eq + Hash,
@@ -776,6 +861,10 @@ fn project_box_contents<N>(
return;
}
let geometry = &projection.boxes[id.index()];
+ let viewport_transform = projection.coordinate_spaces[geometry.coordinate_space.index()]
+ .paint
+ .local_transform();
+ let local_cull = cull.local_rect(viewport_transform);
let paint_space = projection.coordinate_spaces[geometry.coordinate_space.index()]
.paint_space(snapshot.viewport_to_surface);
let transform = paint_space.local_transform();
@@ -791,8 +880,8 @@ fn project_box_contents<N>(
}
project_replaced_image(projection, id, paint_space, snapshot);
project_form_control_appearance(layout_box, geometry.border_box, transform, snapshot);
- let text_clip_mask = |scope: TextClipMaskScope, snapshot: &mut PaintSnapshot| {
- project_background_text_clip_mask(projection, id, scope, snapshot);
+ let mut text_clip_mask = |scope: TextClipMaskScope, snapshot: &mut PaintSnapshot| {
+ project_background_text_clip_mask(projection, id, scope, cull, metrics, snapshot);
};
project_inline_box_fragments(
projection.world,
@@ -800,9 +889,10 @@ fn project_box_contents<N>(
paint_space,
include_backgrounds,
snapshot,
- &text_clip_mask,
+ local_cull,
+ &mut text_clip_mask,
);
- project_text(layout_box, transform, snapshot);
+ project_text(layout_box, transform, local_cull, metrics, snapshot);
}
fn unavailable_replaced_content_paint<N>(
diff --git a/moli-layout/src/paint/text.rs b/moli-layout/src/paint/text.rs
index 5d5335bb9..a302ee0c9 100644
--- a/moli-layout/src/paint/text.rs
+++ b/moli-layout/src/paint/text.rs
@@ -1,9 +1,10 @@
use parley::{Affinity, Cursor, PositionedLayoutItem, Selection};
+use super::{PaintProjectionMetrics, cull::rects_intersect};
use crate::{
LayoutBox, LayoutBoxId, LayoutRect, LayoutTransform2D, PaintBrush, PaintColor, PaintFragment,
PaintGlyph, PaintGlyphRun, PaintShape, PaintSnapshot, PaintTextDecoration, PaintTextShadow,
- inline::{InlineFormattingContext, InlineObjectRole, InlineSelection},
+ inline::{InlineFormattingContext, InlineObjectRole, InlinePaintBounds, InlineSelection},
};
const SELECTION_COLOR: PaintColor = PaintColor::new(180.0 / 255.0, 213.0 / 255.0, 1.0, 1.0);
@@ -41,11 +42,15 @@ pub(super) enum TextClipMaskScope {
pub(super) fn project_text<N>(
layout_box: &LayoutBox<N>,
transform: LayoutTransform2D,
+ local_cull: Option<LayoutRect>,
+ metrics: &mut PaintProjectionMetrics,
snapshot: &mut PaintSnapshot,
) {
project_text_phase(
layout_box,
transform,
+ local_cull,
+ metrics,
snapshot,
TextPaintPhase::Foreground,
None,
@@ -61,12 +66,16 @@ pub(super) fn project_text<N>(
pub(super) fn project_text_clip_mask<N>(
layout_box: &LayoutBox<N>,
transform: LayoutTransform2D,
+ local_cull: Option<LayoutRect>,
+ metrics: &mut PaintProjectionMetrics,
snapshot: &mut PaintSnapshot,
scope: TextClipMaskScope,
) {
project_text_phase(
layout_box,
transform,
+ local_cull,
+ metrics,
snapshot,
TextPaintPhase::ClipMask,
Some(scope),
@@ -76,6 +85,8 @@ pub(super) fn project_text_clip_mask<N>(
fn project_text_phase<N>(
layout_box: &LayoutBox<N>,
transform: LayoutTransform2D,
+ local_cull: Option<LayoutRect>,
+ metrics: &mut PaintProjectionMetrics,
snapshot: &mut PaintSnapshot,
phase: TextPaintPhase,
mask_scope: Option<TextClipMaskScope>,
@@ -97,12 +108,51 @@ fn project_text_phase<N>(
origin_x,
origin_y,
transform,
+ local_cull,
snapshot,
);
}
let mut active_inline_boxes = Vec::new();
for (line_index, line) in text_layout.lines().enumerate() {
+ metrics.text_line_count = metrics.text_line_count.saturating_add(1);
+ let line_is_culled =
+ local_cull.is_some_and(|cull| {
+ context.fragments.lines.get(line_index).is_some_and(|line| {
+ match line.paint_bounds {
+ InlinePaintBounds::Empty => true,
+ InlinePaintBounds::Unbounded => false,
+ InlinePaintBounds::Bounded(bounds) => {
+ let bounds = LayoutRect::new(
+ origin_x + bounds.x,
+ origin_y + bounds.y,
+ bounds.width,
+ bounds.height,
+ );
+ !rects_intersect(bounds, cull)
+ }
+ }
+ })
+ });
+ if line_is_culled {
+ metrics.culled_text_line_count = metrics.culled_text_line_count.saturating_add(1);
+ // A background-clip:text replay tracks structural inline start/end
+ // markers across lines. Even when a line's glyph ink is culled,
+ // retain that tiny state transition so a later visible line uses
+ // the correct InlineBox mask scope.
+ if mask_scope.is_some() {
+ for item in line.items() {
+ if let PositionedLayoutItem::InlineBox(positioned) = item {
+ update_active_inline_boxes(
+ context,
+ positioned.id,
+ &mut active_inline_boxes,
+ );
+ }
+ }
+ }
+ continue;
+ }
let line_placement = context.line_placements.get(line_index);
for (item_index, item) in line.items().enumerate() {
let glyph_run = match item {
@@ -248,6 +298,7 @@ fn project_selection(
origin_x: f32,
origin_y: f32,
transform: LayoutTransform2D,
+ local_cull: Option<LayoutRect>,
snapshot: &mut PaintSnapshot,
) {
let Some(selection) = context.selection.as_ref() else {
@@ -268,7 +319,10 @@ fn project_selection(
(rect.x1 - rect.x0).max(0.0) as f32,
(rect.y1 - rect.y0).max(0.0) as f32,
);
- if rect.width > 0.0 && rect.height > 0.0 {
+ if rect.width > 0.0
+ && rect.height > 0.0
+ && local_cull.is_none_or(|cull| rects_intersect(rect, cull))
+ {
snapshot.push_fragment(PaintFragment::Fill {
shape: PaintShape::Rect(rect),
brush: PaintBrush::Solid(SELECTION_COLOR),
@@ -296,7 +350,10 @@ fn project_selection(
(rect.x1 - rect.x0).max(1.5) as f32,
(rect.y1 - rect.y0).max(0.0) as f32,
);
- if rect.height > 0.0 && color.alpha > 0.0 {
+ if rect.height > 0.0
+ && color.alpha > 0.0
+ && local_cull.is_none_or(|cull| rects_intersect(rect, cull))
+ {
snapshot.push_fragment(PaintFragment::Fill {
shape: PaintShape::Rect(rect),
brush: PaintBrush::Solid(*color),
diff --git a/moli-layout/src/projection.rs b/moli-layout/src/projection.rs
index 3186e44d6..15f5edb8b 100644
--- a/moli-layout/src/projection.rs
+++ b/moli-layout/src/projection.rs
@@ -61,6 +61,7 @@ where
.iter_mut()
.filter_map(|(id, (_, snapshot))| snapshot.paint.take().map(|paint| (*id, paint)))
.collect::<HashMap<_, _>>();
+ let mut paint_projection_metrics = crate::paint::PaintProjectionMetrics::default();
let mut paint_snapshot = paint_capture
.map(|request| {
request
@@ -69,7 +70,11 @@ where
crate::paint::project_paint_snapshot(&projection, capture, &mut embedded_paint)
})
})
- .transpose()?;
+ .transpose()?
+ .map(|output| {
+ paint_projection_metrics = output.metrics;
+ output.snapshot
+ });
let mut diagnostics = paint_snapshot
.as_ref()
.map(|snapshot| snapshot.diagnostics.clone())
@@ -106,6 +111,10 @@ where
.numeric_feedback_invalidated_node_count,
box_count: projection.boxes.len(),
fragment_count: projection.fragments.len(),
+ paint_event_count: paint_projection_metrics.event_count,
+ paint_culled_event_count: paint_projection_metrics.culled_event_count,
+ paint_text_line_count: paint_projection_metrics.text_line_count,
+ paint_culled_text_line_count: paint_projection_metrics.culled_text_line_count,
paint_operation_count: paint_snapshot
.as_ref()
.map_or(0, |snapshot| snapshot.fragments.len()),
@@ -303,6 +312,10 @@ where
}
}
+ pub(crate) fn resolved_transform_has_unsupported_3d(&self, id: LayoutBoxId) -> bool {
+ self.resolved_transforms[id.index()].has_unsupported_3d
+ }
+
fn scrollbar_gutter_thickness(&self, id: LayoutBoxId, axis: LayoutScrollbarAxis) -> f32 {
if id == self.world.root {
self.world
diff --git a/moli-layout/tests/main_layout_contract.rs b/moli-layout/tests/main_layout_contract.rs
index 857a7689c..da684601c 100644
--- a/moli-layout/tests/main_layout_contract.rs
+++ b/moli-layout/tests/main_layout_contract.rs
@@ -2,10 +2,11 @@ use std::collections::HashMap;
use moli_layout::{
DocumentLayoutServices, LayoutDisplay, LayoutElementCategory, LayoutElementSemantics,
- LayoutError, LayoutNamespace, LayoutPosition, LayoutReplacedKind, LayoutSource,
- LayoutSourceKind, LayoutStyleResolver, PaintBlendMode, PaintColor, PaintFragment, PaintRect,
- PaintSnapshot, PaintViewport, ReplacedMetrics, ResolvedLayoutElementStyles,
- ResolvedLayoutStyle, ScreenshotLayoutRequest, build_screenshot_snapshot,
+ LayoutError, LayoutFlushReason, LayoutNamespace, LayoutPassRequest, LayoutPosition,
+ LayoutReplacedKind, LayoutSource, LayoutSourceKind, LayoutStyleResolver, PaintBlendMode,
+ PaintCaptureRequest, PaintColor, PaintFragment, PaintRect, PaintSnapshot, PaintViewport,
+ ReplacedMetrics, ResolvedLayoutElementStyles, ResolvedLayoutStyle, ScreenshotLayoutRequest,
+ build_layout_pass, build_screenshot_snapshot,
};
use style::Atom;
use taffy::{
@@ -1240,7 +1241,22 @@ fn block_margin_collapse_matches_parent_child_and_sibling_rules() {
.0
.insert(4, fixed_box(LayoutDisplay::Block, 800.0, 5.0, GREEN));
- let snapshot = render(&source, &mut styles, PaintViewport::new(800, 100, 1.0));
+ // This test inspects all three painted boxes to validate margin collapse,
+ // so request the document surface instead of relying on offscreen viewport
+ // paint that capture culling now intentionally omits.
+ let snapshot = build_layout_pass(
+ &source,
+ &mut styles,
+ &mut DocumentLayoutServices::new(),
+ LayoutPassRequest::with_capture(
+ PaintViewport::new(800, 100, 1.0),
+ LayoutFlushReason::Test,
+ PaintCaptureRequest::full_document(),
+ ),
+ )
+ .unwrap()
+ .into_paint_snapshot()
+ .expect("full-document paint");
assert_rect(
solid_rect(&snapshot, RED),
PaintRect::new(0.0, 30.0, 400.0, 20.0),
diff --git a/moli-layout/tests/phase5_output_contract.rs b/moli-layout/tests/phase5_output_contract.rs
index 1175d6aef..0173e62ec 100644
--- a/moli-layout/tests/phase5_output_contract.rs
+++ b/moli-layout/tests/phase5_output_contract.rs
@@ -514,6 +514,209 @@ fn non_viewport_captures_omit_only_the_root_scrollbars() {
}
}
+#[test]
+fn viewport_paint_culls_offscreen_events_without_losing_transformed_or_fixed_content() {
+ let source = Source(vec![
+ Node::element("root", vec![1, 2, 3, 4, 5]),
+ Node::element("visible", Vec::new()),
+ Node::element("deep", Vec::new()),
+ Node::element("transformed-into-view", Vec::new()),
+ Node::element("viewport-fixed", Vec::new()),
+ Node::element("offscreen-context", vec![6]),
+ Node::element("offscreen-context-child", Vec::new()),
+ ]);
+ let mut styles = Styles::default();
+ styles.0.insert(
+ 0,
+ fixed_size(LayoutDisplay::Block, 120.0, 800.0).with_position(LayoutPosition::Relative),
+ );
+ let absolute = |top: f32, color: PaintColor| {
+ ResolvedLayoutStyle::synthetic(
+ LayoutDisplay::Block,
+ Style {
+ position: Position::Absolute,
+ inset: Rect {
+ left: length(10.0),
+ right: LengthPercentageAuto::auto(),
+ top: length(top),
+ bottom: LengthPercentageAuto::auto(),
+ },
+ size: Size {
+ width: length(30.0),
+ height: length(20.0),
+ },
+ ..Style::default()
+ },
+ color,
+ )
+ .with_position(LayoutPosition::Absolute)
+ };
+ let red = PaintColor::new(1.0, 0.0, 0.0, 1.0);
+ let blue = PaintColor::new(0.0, 0.0, 1.0, 1.0);
+ let green = PaintColor::new(0.0, 1.0, 0.0, 1.0);
+ let magenta = PaintColor::new(1.0, 0.0, 1.0, 1.0);
+ let yellow = PaintColor::new(1.0, 1.0, 0.0, 1.0);
+ styles.0.insert(1, absolute(10.0, red));
+ styles.0.insert(2, absolute(500.0, blue));
+ styles.0.insert(
+ 3,
+ absolute(500.0, green).with_2d_transform(LayoutTransform2D::translation(0.0, -480.0)),
+ );
+ styles.0.insert(
+ 4,
+ ResolvedLayoutStyle::synthetic(
+ LayoutDisplay::Block,
+ Style {
+ position: Position::Absolute,
+ inset: Rect {
+ left: length(60.0),
+ right: LengthPercentageAuto::auto(),
+ top: length(30.0),
+ bottom: LengthPercentageAuto::auto(),
+ },
+ size: Size {
+ width: length(30.0),
+ height: length(20.0),
+ },
+ ..Style::default()
+ },
+ magenta,
+ )
+ .with_position(LayoutPosition::Fixed),
+ );
+ styles.0.insert(
+ 5,
+ absolute(700.0, PaintColor::TRANSPARENT).with_opacity(0.5),
+ );
+ styles.0.insert(
+ 6,
+ ResolvedLayoutStyle::synthetic(
+ LayoutDisplay::Block,
+ Style {
+ size: Size {
+ width: length(30.0),
+ height: length(20.0),
+ },
+ ..Style::default()
+ },
+ yellow,
+ ),
+ );
+
+ let viewport = build_with_request(
+ &source,
+ &mut styles,
+ LayoutPassRequest::with_paint(LayoutViewport::new(120, 100, 1.0), LayoutFlushReason::Test),
+ );
+ let colors = viewport
+ .paint_snapshot()
+ .expect("viewport paint")
+ .fragments
+ .iter()
+ .filter_map(PaintFragment::solid_fill)
+ .map(|(_, color, _)| color)
+ .collect::<Vec<_>>();
+ assert!(colors.contains(&red));
+ assert!(
+ colors.contains(&green),
+ "the CSS transform moves this box into view"
+ );
+ assert!(
+ colors.contains(&magenta),
+ "fixed content is tested in viewport space"
+ );
+ assert!(!colors.contains(&blue));
+ assert!(!colors.contains(&yellow));
+ assert!(viewport.metrics.paint_event_count > 0);
+ assert!(viewport.metrics.paint_culled_event_count > 0);
+ assert!(
+ viewport.metrics.paint_culled_event_count < viewport.metrics.paint_event_count,
+ "visible paint must remain after culling"
+ );
+ assert_balanced_paint_stack(&viewport.paint_snapshot().expect("viewport paint").fragments);
+
+ let full_document = build_with_request(
+ &source,
+ &mut styles,
+ LayoutPassRequest::with_capture(
+ LayoutViewport::new(120, 100, 1.0),
+ LayoutFlushReason::Test,
+ PaintCaptureRequest::full_document(),
+ ),
+ );
+ let full_colors = full_document
+ .paint_snapshot()
+ .expect("full-document paint")
+ .fragments
+ .iter()
+ .filter_map(PaintFragment::solid_fill)
+ .map(|(_, color, _)| color)
+ .collect::<Vec<_>>();
+ assert!(full_colors.contains(&blue));
+ assert!(full_colors.contains(&yellow));
+ assert!(
+ full_document.metrics.paint_culled_event_count < viewport.metrics.paint_culled_event_count,
+ "the larger capture should discard fewer paint events"
+ );
+
+ let deep_clip = build_with_request(
+ &source,
+ &mut styles,
+ LayoutPassRequest::with_capture(
+ LayoutViewport::new(120, 100, 1.0),
+ LayoutFlushReason::Test,
+ PaintCaptureRequest::page_clip(LayoutRect::new(0.0, 490.0, 120.0, 40.0), 1.0),
+ ),
+ );
+ let clip_colors = deep_clip
+ .paint_snapshot()
+ .expect("page clip paint")
+ .fragments
+ .iter()
+ .filter_map(PaintFragment::solid_fill)
+ .map(|(_, color, _)| color)
+ .collect::<Vec<_>>();
+ assert!(clip_colors.contains(&blue));
+ assert!(!clip_colors.contains(&red));
+ assert!(!clip_colors.contains(&green));
+}
+
+#[test]
+fn viewport_paint_skips_final_inline_lines_outside_the_capture() {
+ const LONG_TEXT: &str = "one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen twenty one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen twenty one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen twenty";
+ let source = Source(vec![
+ Node::element("root", vec![1]),
+ Node::text("long-text", LONG_TEXT),
+ ]);
+ let mut styles = Styles::default();
+ styles.0.insert(
+ 0,
+ resolved(
+ LayoutDisplay::Block,
+ Style {
+ size: Size {
+ width: length(80.0),
+ height: Dimension::auto(),
+ },
+ ..Style::default()
+ },
+ ),
+ );
+
+ let output = build_with_request(
+ &source,
+ &mut styles,
+ LayoutPassRequest::with_paint(LayoutViewport::new(100, 50, 1.0), LayoutFlushReason::Test),
+ );
+ assert!(output.metrics.paint_text_line_count > 10);
+ assert!(output.metrics.paint_culled_text_line_count > 0);
+ assert!(
+ output.metrics.paint_culled_text_line_count < output.metrics.paint_text_line_count,
+ "the first viewport lines must still paint"
+ );
+ assert!(output.paint_snapshot().is_some());
+}
+
#[test]
fn auto_scrollbar_feedback_reveals_the_perpendicular_axis() {
let source = Source(vec![
diff --git a/moli-renderer-v8/src/native_bridge/context_host/layout.rs b/moli-renderer-v8/src/native_bridge/context_host/layout.rs
index 0ceb8681e..6607fb5be 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/layout.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/layout.rs
@@ -271,6 +271,10 @@ impl JsContextHost {
.numeric_feedback_invalidated_node_count,
box_count = metrics.box_count,
fragment_count = metrics.fragment_count,
+ paint_event_count = metrics.paint_event_count,
+ paint_culled_event_count = metrics.paint_culled_event_count,
+ paint_text_line_count = metrics.paint_text_line_count,
+ paint_culled_text_line_count = metrics.paint_culled_text_line_count,
paint_operation_count = metrics.paint_operation_count,
fallback_count = metrics.fallback_count,
);
diff --git a/moli-renderer-v8/src/native_bridge/element/geometry/mock/queries.rs b/moli-renderer-v8/src/native_bridge/element/geometry/mock/queries.rs
index 497e21bb5..7d50e25a9 100644
--- a/moli-renderer-v8/src/native_bridge/element/geometry/mock/queries.rs
+++ b/moli-renderer-v8/src/native_bridge/element/geometry/mock/queries.rs
@@ -159,6 +159,10 @@ pub(crate) fn answer_queries(
numeric_feedback_invalidated_node_count: 0,
box_count: 0,
fragment_count: 0,
+ paint_event_count: 0,
+ paint_culled_event_count: 0,
+ paint_text_line_count: 0,
+ paint_culled_text_line_count: 0,
paint_operation_count: 0,
fallback_count: 1,
},
diff --git a/moli-renderer-v8/src/runtime/page_vm/tests/rendering_update.rs b/moli-renderer-v8/src/runtime/page_vm/tests/rendering_update.rs
index ea8836d64..ebcdd13b4 100644
--- a/moli-renderer-v8/src/runtime/page_vm/tests/rendering_update.rs
+++ b/moli-renderer-v8/src/runtime/page_vm/tests/rendering_update.rs
@@ -2102,6 +2102,75 @@ document.getElementById('masked').style.setProperty('mask-repeat','no-repeat');
.expect("clip/filter/mask screenshot fixture should run");
}
+#[tokio::test(flavor = "current_thread")]
+async fn screenshot_culling_keeps_outset_ink_that_reaches_the_viewport() {
+ run_page_vm_async_test(async move {
+ let loader =
+ crate::network::ResourceRequestClient::new(&FetchConfig::default()).expect("loader");
+ let mut page_vm = test_page_vm_with_loader_and_document_url(
+ &loader,
+ Vec::new(),
+ Url::parse("https://example.com/paint-culling-outsets.html")?,
+ );
+ page_vm.vm_mut().eval(
+ r#"
+document.head.innerHTML = `<style>
+html,body{margin:0;padding:0;background:white;height:220px}
+.case{position:absolute;width:20px;height:10px;background:transparent}
+#shadow{left:5px;top:60px;box-shadow:0 -15px 0 0 rgb(255,0,0)}
+#outline{left:40px;top:57px;outline:5px solid rgb(0,128,0);outline-offset:5px}
+#filtered{left:75px;top:55px;width:10px;background:rgb(0,0,255);filter:blur(8px)}
+#discarded{left:5px;top:170px;background:rgb(255,255,0)}
+</style>`;
+document.body.innerHTML = '<div id=shadow class=case></div><div id=outline class=case></div><div id=filtered class=case></div><div id=discarded class=case></div>';
+'installed'
+"#,
+ )?;
+ let snapshot = page_vm
+ .vm_mut()
+ .screenshot_layout_snapshot(moli_layout::PaintViewport::new(100, 50, 1.0))?
+ .expect("culling fixture must retain a layout root");
+
+ assert!(snapshot.fragments.iter().all(|fragment| {
+ !matches!(
+ fragment,
+ moli_layout::PaintFragment::Fill {
+ brush: moli_layout::PaintBrush::Solid(color),
+ ..
+ } if *color == moli_layout::PaintColor::new(1.0, 1.0, 0.0, 1.0)
+ )
+ }));
+ let mut depth = 0usize;
+ for fragment in &snapshot.fragments {
+ match fragment {
+ moli_layout::PaintFragment::PushLayer { .. }
+ | moli_layout::PaintFragment::PushClip { .. } => depth += 1,
+ moli_layout::PaintFragment::PopLayer => {
+ depth = depth.checked_sub(1).expect("paint stack underflow")
+ }
+ _ => {}
+ }
+ }
+ assert_eq!(depth, 0, "culled stacking contexts must remain balanced");
+
+ let image = moli_paint::raster_snapshot(&snapshot)?;
+ let pixel = |x: u32, y: u32| {
+ let index = ((y * image.width + x) * 4) as usize;
+ <[u8; 4]>::try_from(&image.rgba[index..index + 4]).expect("RGBA pixel")
+ };
+ assert_eq!(pixel(10, 47), [255, 0, 0, 255]);
+ assert_eq!(pixel(45, 48), [0, 128, 0, 255]);
+ let filtered = pixel(80, 48);
+ assert!(
+ filtered[2] > filtered[0] && filtered[2] > filtered[1],
+ "blurred blue ink should reach the capture from below it: {filtered:?}"
+ );
+ Ok::<_, anyhow::Error>(())
+ })
+ .await
+ .expect("outset paint culling fixture should run");
+}
+
#[tokio::test(flavor = "current_thread")]
async fn screenshot_resolves_css_gradient_domains_hints_and_interpolation_like_chromium() {
run_page_vm_async_test(async move {