Skip to content

armgit / moli

Public Imported from GitHub
0

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

Unify pre-transform paint coordinate state

ldm0e2aa24db1425
diff --git a/moli-layout/src/lib.rs b/moli-layout/src/lib.rs
index cfe2bed13..eec93627f 100644
--- a/moli-layout/src/lib.rs
+++ b/moli-layout/src/lib.rs
@@ -5,6 +5,10 @@
//! styles; all source/style borrows and per-pass caches are gone before the
//! returned [`FrozenLayoutTree`] or [`PaintSnapshot`] crosses into a consumer.
+/// Number of fixed layout subpixels in one CSS pixel, matching Blink's
+/// `LayoutUnit` precision.
+pub const LAYOUT_SUBPIXELS_PER_CSS_PIXEL: f32 = 64.0;
+
mod builder;
mod capture;
mod containment;
@@ -66,7 +70,8 @@ pub use snapshot::{
PaintPathElement, PaintPoint, PaintRadialGradient, PaintRect, PaintShape, PaintSize,
PaintSnapshot, PaintStroke, PaintSvgImage, PaintSvgImageId, PaintSvgImageResource,
PaintTextDecoration, PaintTextDecorationStyle, PaintTextShadow, PaintTransform2D,
- PaintViewport,
+ PaintViewport, pixel_snap_paint_axis, pixel_snap_paint_axis_allowing_zero,
+ pixel_snap_paint_rect,
};
pub use source::{
LayoutElementCategory, LayoutElementMetadata, LayoutElementSemantics, LayoutFormControlData,
diff --git a/moli-layout/src/paint/background.rs b/moli-layout/src/paint/background.rs
index 573f10688..525056305 100644
--- a/moli-layout/src/paint/background.rs
+++ b/moli-layout/src/paint/background.rs
@@ -21,6 +21,7 @@ use style::{
};
use super::{
+ PaintSpace,
geometry::{BoxAreas, BoxModelBox},
push_diagnostic_once,
};
@@ -103,7 +104,7 @@ impl<'a> ImageLayerStyles<'a> {
pub(super) fn project_background_color<N>(
layout_box: &LayoutBox<N>,
areas: BoxAreas,
- transform: LayoutTransform2D,
+ paint_space: PaintSpace,
color: PaintColor,
snapshot: &mut PaintSnapshot,
text_clip_mask: &impl Fn(&mut PaintSnapshot),
@@ -120,36 +121,46 @@ pub(super) fn project_background_color<N>(
.map(BoxModelBox::from)
.unwrap_or(BoxModelBox::Border);
if clip == BoxModelBox::Text {
- begin_background_text_clip_layer(areas, transform, snapshot);
+ let Some(shape) = begin_background_text_clip_layer(areas, paint_space, snapshot) else {
+ return;
+ };
snapshot.push_fragment(PaintFragment::Fill {
- shape: areas.shape(BoxModelBox::Border),
+ shape: shape.clone(),
brush: PaintBrush::Solid(color),
- transform,
+ transform: paint_space.property_transform(),
});
- finish_background_text_clip_layer(areas, transform, snapshot, text_clip_mask);
+ finish_background_text_clip_layer(
+ shape,
+ paint_space.property_transform(),
+ snapshot,
+ text_clip_mask,
+ );
return;
}
diagnose_background_clip_fallback(layout_box, clip, snapshot);
- let shape = areas.shape(clip);
+ let Some(shape) = paint_space.pixel_snapped_box_shape(areas.shape(clip)) else {
+ return;
+ };
if shape.bounds().width <= 0.0 || shape.bounds().height <= 0.0 {
return;
}
snapshot.push_fragment(PaintFragment::Fill {
shape,
brush: PaintBrush::Solid(color),
- transform,
+ transform: paint_space.property_transform(),
});
}
pub(super) fn project_background_layers<N>(
layout_box: &LayoutBox<N>,
areas: BoxAreas,
- transform: LayoutTransform2D,
+ paint_space: PaintSpace,
snapshot: &mut PaintSnapshot,
text_clip_mask: &impl Fn(&mut PaintSnapshot),
) where
N: Copy + Debug + Eq + Hash,
{
+ let transform = paint_space.local_transform();
let Some(computed) = layout_box.style.stylo_computed_values() else {
return;
};
@@ -198,14 +209,23 @@ pub(super) fn project_background_layers<N>(
if tiles.is_empty() {
continue;
}
- if clips_to_text {
- begin_background_text_clip_layer(areas, transform, snapshot);
+ let text_clip_shape = if clips_to_text {
+ let Some(shape) =
+ begin_background_text_clip_layer(areas, paint_space, snapshot)
+ else {
+ continue;
+ };
+ Some(shape)
} else {
+ let Some(clip_shape) = paint_space.pixel_snapped_box_shape(clip_shape) else {
+ continue;
+ };
snapshot.push_fragment(PaintFragment::PushClip {
shape: clip_shape,
- transform,
+ transform: paint_space.property_transform(),
});
- }
+ None
+ };
for tile in tiles {
if let Some(brush) = project_gradient(gradient, tile, &current_color) {
snapshot.push_fragment(PaintFragment::Fill {
@@ -215,8 +235,13 @@ pub(super) fn project_background_layers<N>(
});
}
}
- if clips_to_text {
- finish_background_text_clip_layer(areas, transform, snapshot, text_clip_mask);
+ if let Some(shape) = text_clip_shape {
+ finish_background_text_clip_layer(
+ shape,
+ paint_space.property_transform(),
+ snapshot,
+ text_clip_mask,
+ );
} else {
snapshot.push_fragment(PaintFragment::PopLayer);
}
@@ -231,7 +256,7 @@ pub(super) fn project_background_layers<N>(
.get(layer_index)
.and_then(Option::as_ref),
areas,
- transform,
+ paint_space,
snapshot,
CssImageLayerKind::Background,
true,
@@ -263,24 +288,26 @@ pub(super) fn project_background_layers<N>(
/// `DestIn` operation cannot consume the page backdrop.
fn begin_background_text_clip_layer(
areas: BoxAreas,
- transform: LayoutTransform2D,
+ paint_space: PaintSpace,
snapshot: &mut PaintSnapshot,
-) {
+) -> Option<PaintShape> {
+ let clip = paint_space.pixel_snapped_box_shape(areas.shape(BoxModelBox::Border))?;
snapshot.push_fragment(PaintFragment::PushLayer {
opacity: 1.0 - f32::EPSILON,
blend_mode: PaintBlendMode::Normal,
composite: PaintCompositeMode::SrcOver,
- clip: areas.shape(BoxModelBox::Border),
- transform,
+ clip: clip.clone(),
+ transform: paint_space.property_transform(),
filter: None,
});
+ Some(clip)
}
/// Applies opaque glyph ink to the isolated background with `DestIn` and
/// closes both layers. The text projection deliberately ignores foreground
/// fill color and shadows; only glyph/decorations alpha contributes.
fn finish_background_text_clip_layer(
- areas: BoxAreas,
+ clip: PaintShape,
transform: LayoutTransform2D,
snapshot: &mut PaintSnapshot,
text_clip_mask: &impl Fn(&mut PaintSnapshot),
@@ -289,7 +316,7 @@ fn finish_background_text_clip_layer(
opacity: 1.0,
blend_mode: PaintBlendMode::Normal,
composite: PaintCompositeMode::DestIn,
- clip: areas.shape(BoxModelBox::Border),
+ clip,
transform,
filter: None,
});
@@ -384,7 +411,7 @@ pub(super) fn project_url_image_layer<N>(
layer: &ImageLayerStyles<'_>,
resource: Option<&LayoutImageResource>,
areas: BoxAreas,
- transform: LayoutTransform2D,
+ paint_space: PaintSpace,
snapshot: &mut PaintSnapshot,
kind: CssImageLayerKind,
push_clip: bool,
@@ -435,9 +462,12 @@ pub(super) fn project_url_image_layer<N>(
}
if push_clip {
+ let Some(clip_shape) = paint_space.pixel_snapped_box_shape(clip_shape) else {
+ return;
+ };
snapshot.push_fragment(PaintFragment::PushClip {
shape: clip_shape,
- transform,
+ transform: paint_space.property_transform(),
});
}
if let Some(pixels) = resource.pixels.clone() {
@@ -454,9 +484,9 @@ pub(super) fn project_url_image_layer<N>(
for destination in tiles {
snapshot.push_fragment(PaintFragment::Image(PaintImage {
image,
- destination,
+ destination: paint_space.pre_transform_rect(destination),
sampling,
- transform,
+ transform: paint_space.property_transform(),
}));
}
} else if let Some(svg) = resource.svg.clone() {
@@ -464,8 +494,8 @@ pub(super) fn project_url_image_layer<N>(
for destination in tiles {
snapshot.push_fragment(PaintFragment::SvgImage(PaintSvgImage {
image,
- destination,
- transform,
+ destination: paint_space.pre_transform_rect(destination),
+ transform: paint_space.property_transform(),
}));
}
}
diff --git a/moli-layout/src/paint/image.rs b/moli-layout/src/paint/image.rs
index 75232e89f..863c3c5a9 100644
--- a/moli-layout/src/paint/image.rs
+++ b/moli-layout/src/paint/image.rs
@@ -12,25 +12,25 @@ use style::{
};
use super::{
+ PaintSpace,
geometry::{BoxAreas, BoxModelBox},
- paint_space::PaintSpace,
};
use crate::{
- LayoutBoxId, LayoutPoint, LayoutRect, LayoutReplacedKind, LayoutSize, LayoutTransform2D,
- PaintBorderColors, PaintBorderStyle, PaintBorderStyles, PaintColor, PaintCornerRadii,
- PaintDiagnostic, PaintDiagnosticSeverity, PaintEdgeSizes, PaintFragment, PaintImage,
- PaintImageSampling, PaintSnapshot, PaintSvgImage, projection::OutputProjection,
+ LayoutBoxId, LayoutPoint, LayoutRect, LayoutReplacedKind, LayoutSize, PaintBorderColors,
+ PaintBorderStyle, PaintBorderStyles, PaintColor, PaintCornerRadii, PaintDiagnostic,
+ PaintDiagnosticSeverity, PaintEdgeSizes, PaintFragment, PaintImage, PaintImageSampling,
+ PaintSnapshot, PaintSvgImage, projection::OutputProjection,
};
pub(super) fn project_replaced_image<N>(
projection: &OutputProjection<'_, N>,
id: LayoutBoxId,
- transform: LayoutTransform2D,
paint_space: PaintSpace,
snapshot: &mut PaintSnapshot,
) where
N: Copy + Debug + Eq + Hash,
{
+ let transform = paint_space.local_transform();
let layout_box = &projection.world.boxes[id.index()];
let Some(kind) = layout_box
.element_semantics()
@@ -46,13 +46,13 @@ pub(super) fn project_replaced_image<N>(
}
let Some(resource) = layout_box.replaced_image.as_ref() else {
if kind == LayoutReplacedKind::Image {
- project_unavailable_image(projection, id, transform, snapshot);
+ project_unavailable_image(projection, id, paint_space, snapshot);
}
return;
};
if resource.pixels.is_none() && resource.svg.is_none() {
if kind == LayoutReplacedKind::Image {
- project_unavailable_image(projection, id, transform, snapshot);
+ project_unavailable_image(projection, id, paint_space, snapshot);
}
return;
}
@@ -132,7 +132,7 @@ pub(super) fn project_replaced_image<N>(
transform,
});
}
- let destination = paint_space.offset_rect(destination);
+ let destination = paint_space.pre_transform_rect(destination);
let image_transform = paint_space.property_transform();
if let Some(pixels) = resource.pixels.clone() {
let image = snapshot.add_image(pixels);
@@ -166,7 +166,7 @@ fn replaced_content_clip_needed(areas: BoxAreas, destination: LayoutRect) -> boo
fn project_unavailable_image<N>(
projection: &OutputProjection<'_, N>,
id: LayoutBoxId,
- transform: LayoutTransform2D,
+ paint_space: PaintSpace,
snapshot: &mut PaintSnapshot,
) where
N: Copy + Debug + Eq + Hash,
@@ -190,12 +190,12 @@ fn project_unavailable_image<N>(
}
let light_gray = PaintColor::new(211.0 / 255.0, 211.0 / 255.0, 211.0 / 255.0, 1.0);
snapshot.push_fragment(PaintFragment::Border {
- rect: content_rect,
+ rect: paint_space.pre_transform_rect(content_rect),
widths: PaintEdgeSizes::new(1.0, 1.0, 1.0, 1.0),
colors: PaintBorderColors::all(light_gray),
styles: PaintBorderStyles::all(PaintBorderStyle::Solid),
radii: PaintCornerRadii::ZERO,
- transform,
+ transform: paint_space.property_transform(),
});
}
diff --git a/moli-layout/src/paint/inline_boxes.rs b/moli-layout/src/paint/inline_boxes.rs
index fe6055bfc..f40f4feb0 100644
--- a/moli-layout/src/paint/inline_boxes.rs
+++ b/moli-layout/src/paint/inline_boxes.rs
@@ -11,19 +11,17 @@ use std::{fmt::Debug, hash::Hash};
use taffy::ResolveOrZero;
use super::{
+ PaintSpace,
background::{project_background_color, project_background_layers},
geometry::{BoxAreas, inset_radii},
text::TextClipMaskScope,
};
-use crate::{
- LayoutBox, LayoutRect, LayoutTransform2D, LayoutWorld, PaintEdgeSizes, PaintFragment,
- PaintSnapshot,
-};
+use crate::{LayoutBox, LayoutRect, LayoutWorld, PaintEdgeSizes, PaintFragment, PaintSnapshot};
pub(super) fn project_inline_box_fragments<N>(
world: &LayoutWorld<N>,
owner: &LayoutBox<N>,
- transform: LayoutTransform2D,
+ paint_space: PaintSpace,
include_backgrounds: bool,
snapshot: &mut PaintSnapshot,
text_clip_mask: &impl Fn(TextClipMaskScope, &mut PaintSnapshot),
@@ -141,7 +139,7 @@ pub(super) fn project_inline_box_fragments<N>(
project_background_color(
inline_box,
areas,
- transform,
+ paint_space,
color,
snapshot,
&project_text_clip_mask,
@@ -149,7 +147,7 @@ pub(super) fn project_inline_box_fragments<N>(
project_background_layers(
inline_box,
areas,
- transform,
+ paint_space,
snapshot,
&project_text_clip_mask,
);
@@ -158,12 +156,12 @@ pub(super) fn project_inline_box_fragments<N>(
let colors = style.border_colors();
if widths.has_positive_edge() && colors.has_visible_edge() {
snapshot.push_fragment(PaintFragment::Border {
- rect,
+ rect: paint_space.pre_transform_rect(rect),
widths,
colors,
styles: style.border_styles(),
radii,
- transform,
+ transform: paint_space.property_transform(),
});
}
}
diff --git a/moli-layout/src/paint/mask.rs b/moli-layout/src/paint/mask.rs
index 709c01346..5557569bf 100644
--- a/moli-layout/src/paint/mask.rs
+++ b/moli-layout/src/paint/mask.rs
@@ -16,6 +16,7 @@ use style::{
};
use super::{
+ PaintSpace,
background::{
CssImageLayerKind, ImageLayerStyles, background_tiles, get_cyclic, project_url_image_layer,
},
@@ -23,8 +24,8 @@ use super::{
push_diagnostic_once,
};
use crate::{
- LayoutBox, LayoutTransform2D, PaintBlendMode, PaintCompositeMode, PaintFragment, PaintShape,
- PaintSnapshot, ResolvedLayoutStyle, gradient::project_gradient,
+ LayoutBox, PaintBlendMode, PaintCompositeMode, PaintFragment, PaintShape, PaintSnapshot,
+ ResolvedLayoutStyle, gradient::project_gradient,
};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -66,11 +67,12 @@ pub(super) fn inspect_css_mask(style: &ResolvedLayoutStyle) -> CssMaskPlan {
pub(super) fn project_css_mask<N>(
layout_box: &LayoutBox<N>,
areas: BoxAreas,
- transform: LayoutTransform2D,
+ paint_space: PaintSpace,
snapshot: &mut PaintSnapshot,
) where
N: Copy + Debug + Eq + Hash,
{
+ let transform = paint_space.local_transform();
let Some(computed) = layout_box.style.stylo_computed_values() else {
return;
};
@@ -136,7 +138,7 @@ pub(super) fn project_css_mask<N>(
.get(index)
.and_then(Option::as_ref),
areas,
- transform,
+ paint_space,
snapshot,
CssImageLayerKind::Mask,
false,
diff --git a/moli-layout/src/paint/mod.rs b/moli-layout/src/paint/mod.rs
index d47324889..25f5c3fda 100644
--- a/moli-layout/src/paint/mod.rs
+++ b/moli-layout/src/paint/mod.rs
@@ -6,7 +6,6 @@ mod geometry;
mod image;
mod inline_boxes;
mod mask;
-mod paint_space;
mod table;
mod text;
@@ -20,7 +19,6 @@ use geometry::{BoxAreas, BoxModelBox, canonical_shape, inset_radii};
use image::project_replaced_image;
use inline_boxes::project_inline_box_fragments;
use mask::{CssMaskPlan, inspect_css_mask, project_css_mask};
-use paint_space::PaintSpaceMap;
use style::values::generics::image::GenericImage;
use table::project_collapsed_table_borders;
use text::{TextClipMaskScope, project_text, project_text_clip_mask};
@@ -29,7 +27,9 @@ use crate::{
LayoutBox, LayoutBoxId, LayoutClipChainId, LayoutElementCategory, LayoutFormControlKind,
LayoutInputControlKind, LayoutReplacedKind, LayoutWorld, PaintColor, PaintDiagnostic,
PaintDiagnosticSeverity, PaintEdgeSizes, PaintFragment, PaintShape, PaintSnapshot,
- capture::ResolvedPaintCapture, projection::OutputProjection, stacking::PaintOrderEvent,
+ capture::ResolvedPaintCapture,
+ projection::{OutputProjection, PaintSpace},
+ stacking::PaintOrderEvent,
};
#[derive(Clone, Copy, Debug, Default)]
@@ -39,6 +39,25 @@ struct ContextPaintState {
clip_path_layer: bool,
}
+impl PaintSpace {
+ /// Pixel-snap canonical CSS box geometry after ordinary layout offsets
+ /// and before property transforms.
+ fn pixel_snapped_box_shape(self, shape: PaintShape) -> Option<PaintShape> {
+ match shape {
+ PaintShape::Rect(rect) => {
+ crate::pixel_snap_paint_rect(self.pre_transform_rect(rect)).map(PaintShape::Rect)
+ }
+ PaintShape::RoundedRect { rect, radii } => {
+ crate::pixel_snap_paint_rect(self.pre_transform_rect(rect))
+ .map(|rect| PaintShape::RoundedRect { rect, radii })
+ }
+ // BoxAreas only constructs rectilinear or rounded box geometry.
+ // Arbitrary paths retain their own authored coordinate contract.
+ PaintShape::Path(_) => None,
+ }
+ }
+}
+
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum UnavailableReplacedContentPaint {
OpaquePlaceholder,
@@ -67,10 +86,9 @@ where
snapshot.viewport_to_surface = capture.viewport_to_surface;
snapshot.content_size = projection.document_content_size();
snapshot.diagnostics = projection.diagnostics.clone();
- let paint_spaces = PaintSpaceMap::build(projection, capture.viewport_to_surface);
-
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| {
project_background_text_clip_mask(
projection,
@@ -82,7 +100,7 @@ where
project_background_layers(
&projection.world.boxes[background.index()],
BoxAreas::for_rect(capture.viewport_rect),
- transform,
+ paint_space,
&mut snapshot,
&text_clip_mask,
);
@@ -106,7 +124,8 @@ where
let geometry = &projection.boxes[id.index()];
let viewport_transform = projection.coordinate_spaces
[geometry.coordinate_space.index()]
- .local_to_viewport;
+ .paint
+ .local_transform();
let transform = capture.viewport_to_surface.concatenate(viewport_transform);
let areas = BoxAreas::for_box(projection, id);
let clip_path_layer = match project_clip_path(style, areas) {
@@ -263,7 +282,6 @@ where
project_box_contents(
projection,
id,
- &paint_spaces,
embedded_frames,
capture.include_backgrounds,
&mut snapshot,
@@ -298,10 +316,10 @@ where
if state.mask_layer {
let layout_box = &projection.world.boxes[id.index()];
let geometry = &projection.boxes[id.index()];
- let transform = capture.viewport_to_surface.concatenate(
- projection.coordinate_spaces[geometry.coordinate_space.index()]
- .local_to_viewport,
- );
+ let paint_space = projection.coordinate_spaces
+ [geometry.coordinate_space.index()]
+ .paint_space(capture.viewport_to_surface);
+ let transform = paint_space.local_transform();
let areas = BoxAreas::for_box(projection, id);
snapshot.push_fragment(PaintFragment::PushLayer {
opacity: 1.0,
@@ -311,7 +329,7 @@ where
transform,
filter: None,
});
- project_css_mask(layout_box, areas, transform, &mut snapshot);
+ project_css_mask(layout_box, areas, paint_space, &mut snapshot);
snapshot.push_fragment(PaintFragment::PopLayer); // DestIn mask
snapshot.push_fragment(PaintFragment::PopLayer); // isolation
}
@@ -356,7 +374,9 @@ where
chain.retain(|node| node.owner.is_some());
for node in &chain {
let transform = snapshot.viewport_to_surface.concatenate(
- projection.coordinate_spaces[node.coordinate_space.index()].local_to_viewport,
+ projection.coordinate_spaces[node.coordinate_space.index()]
+ .paint
+ .local_transform(),
);
let shape = node.owner.map_or(PaintShape::Rect(node.rect), |owner| {
let layout_box = &projection.world.boxes[owner.index()];
@@ -452,14 +472,17 @@ fn project_box_background<N>(
return;
}
let geometry = &projection.boxes[id.index()];
- let transform = snapshot.viewport_to_surface.concatenate(
- projection.coordinate_spaces[geometry.coordinate_space.index()].local_to_viewport,
- );
+ let paint_space = projection.coordinate_spaces[geometry.coordinate_space.index()]
+ .paint_space(snapshot.viewport_to_surface);
let areas = BoxAreas::for_box(projection, id);
let rect = areas.border_rect;
let radii = areas.border_radii;
- let shadows = layout_box.style.box_shadows(rect, radii, transform);
+ let shadows = layout_box.style.box_shadows(
+ paint_space.pre_transform_rect(rect),
+ radii,
+ paint_space.property_transform(),
+ );
if include_backgrounds && propagated_background != Some(id) {
let mut color = layout_box.style.background_color();
@@ -500,12 +523,12 @@ fn project_box_background<N>(
project_background_color(
layout_box,
areas,
- transform,
+ paint_space,
color,
snapshot,
&text_clip_mask,
);
- project_background_layers(layout_box, areas, transform, snapshot, &text_clip_mask);
+ project_background_layers(layout_box, areas, paint_space, snapshot, &text_clip_mask);
}
let layout = layout_box.final_layout;
@@ -524,12 +547,12 @@ fn project_box_background<N>(
&& colors.has_visible_edge()
{
snapshot.push_fragment(PaintFragment::Border {
- rect,
+ rect: paint_space.pre_transform_rect(rect),
widths,
colors,
styles: layout_box.style.border_styles(),
radii,
- transform,
+ transform: paint_space.property_transform(),
});
}
}
@@ -587,7 +610,9 @@ fn project_box_text_clip_mask<N>(
}
let geometry = &projection.boxes[id.index()];
let transform = snapshot.viewport_to_surface.concatenate(
- projection.coordinate_spaces[geometry.coordinate_space.index()].local_to_viewport,
+ projection.coordinate_spaces[geometry.coordinate_space.index()]
+ .paint
+ .local_transform(),
);
let clip_count = push_clip_chain(projection, projection.content_clips[id.index()], snapshot);
project_text_clip_mask(layout_box, transform, snapshot, scope);
@@ -606,13 +631,16 @@ fn project_outset_box_shadows<N>(
return;
}
let geometry = &projection.boxes[id.index()];
- let transform = snapshot.viewport_to_surface.concatenate(
- projection.coordinate_spaces[geometry.coordinate_space.index()].local_to_viewport,
- );
+ let paint_space = projection.coordinate_spaces[geometry.coordinate_space.index()]
+ .paint_space(snapshot.viewport_to_surface);
let areas = BoxAreas::for_box(projection, id);
for shadow in layout_box
.style
- .box_shadows(areas.border_rect, areas.border_radii, transform)
+ .box_shadows(
+ paint_space.pre_transform_rect(areas.border_rect),
+ areas.border_radii,
+ paint_space.property_transform(),
+ )
.into_iter()
.filter(|shadow| !shadow.inset)
.rev()
@@ -644,16 +672,16 @@ fn project_box_outline<N>(
return;
}
let geometry = &projection.boxes[id.index()];
- let transform = snapshot.viewport_to_surface.concatenate(
- projection.coordinate_spaces[geometry.coordinate_space.index()].local_to_viewport,
- );
+ let paint_space = projection.coordinate_spaces[geometry.coordinate_space.index()]
+ .paint_space(snapshot.viewport_to_surface);
let radii = layout_box
.style
.border_radii(geometry.border_box.width, geometry.border_box.height);
- if let Some(outline) = layout_box
- .style
- .outline_fragment(geometry.border_box, radii, transform)
- {
+ if let Some(outline) = layout_box.style.outline_fragment(
+ paint_space.pre_transform_rect(geometry.border_box),
+ radii,
+ paint_space.property_transform(),
+ ) {
snapshot.push_fragment(outline);
}
}
@@ -661,7 +689,6 @@ fn project_box_outline<N>(
fn project_box_contents<N>(
projection: &OutputProjection<'_, N>,
id: LayoutBoxId,
- paint_spaces: &PaintSpaceMap,
embedded_frames: &mut HashMap<LayoutBoxId, PaintSnapshot>,
include_backgrounds: bool,
snapshot: &mut PaintSnapshot,
@@ -673,9 +700,9 @@ fn project_box_contents<N>(
return;
}
let geometry = &projection.boxes[id.index()];
- let transform = snapshot.viewport_to_surface.concatenate(
- projection.coordinate_spaces[geometry.coordinate_space.index()].local_to_viewport,
- );
+ let paint_space = projection.coordinate_spaces[geometry.coordinate_space.index()]
+ .paint_space(snapshot.viewport_to_surface);
+ let transform = paint_space.local_transform();
if let Some(child) = embedded_frames.remove(&id) {
let content = BoxAreas::for_box(projection, id).content_rect;
let local_to_surface =
@@ -686,7 +713,7 @@ fn project_box_contents<N>(
local_to_surface,
);
}
- project_replaced_image(projection, id, transform, paint_spaces.get(id), snapshot);
+ 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);
@@ -694,7 +721,7 @@ fn project_box_contents<N>(
project_inline_box_fragments(
projection.world,
layout_box,
- transform,
+ paint_space,
include_backgrounds,
snapshot,
&text_clip_mask,
diff --git a/moli-layout/src/paint/paint_space.rs b/moli-layout/src/paint/paint_space.rs
deleted file mode 100644
index d59bda52f..000000000
--- a/moli-layout/src/paint/paint_space.rs
+++ /dev/null
@@ -1,205 +0,0 @@
-use std::{fmt::Debug, hash::Hash};
-
-use crate::{
- LayoutBoxId, LayoutPoint, LayoutRect, LayoutTransform2D, projection::OutputProjection,
-};
-
-/// Transient paint coordinates for operations that must snap before CSS
-/// property transforms are applied.
-///
-/// The retained layout output continues to use one exact local-to-viewport
-/// transform. This split representation exists only while producing a paint
-/// snapshot: ordinary layout offsets remain in `paint_offset`, while scroll
-/// and CSS transforms are committed to `property_transform`.
-#[derive(Clone, Copy, Debug, PartialEq)]
-pub(super) struct PaintSpace {
- paint_offset: LayoutPoint,
- property_transform: LayoutTransform2D,
-}
-
-impl PaintSpace {
- fn new(property_transform: LayoutTransform2D) -> Self {
- Self {
- paint_offset: LayoutPoint::ZERO,
- property_transform,
- }
- }
-
- fn translate_layout(&mut self, offset: LayoutPoint) {
- self.paint_offset = LayoutPoint::new(
- self.paint_offset.x + offset.x,
- self.paint_offset.y + offset.y,
- );
- }
-
- fn establish_property_transform(&mut self, transform: LayoutTransform2D) {
- self.property_transform = self
- .property_transform
- .concatenate(LayoutTransform2D::translation(
- self.paint_offset.x,
- self.paint_offset.y,
- ))
- .concatenate(transform);
- self.paint_offset = LayoutPoint::ZERO;
- }
-
- pub(super) fn offset_rect(self, rect: LayoutRect) -> LayoutRect {
- LayoutRect::new(
- rect.x + self.paint_offset.x,
- rect.y + self.paint_offset.y,
- rect.width,
- rect.height,
- )
- }
-
- pub(super) const fn property_transform(self) -> LayoutTransform2D {
- self.property_transform
- }
-
- #[cfg(test)]
- fn exact_transform(self) -> LayoutTransform2D {
- self.property_transform
- .concatenate(LayoutTransform2D::translation(
- self.paint_offset.x,
- self.paint_offset.y,
- ))
- }
-}
-
-/// Per-box paint spaces derived once for a single snapshot and then discarded.
-pub(super) struct PaintSpaceMap {
- spaces: Vec<PaintSpace>,
-}
-
-impl PaintSpaceMap {
- pub(super) fn build<N>(
- projection: &OutputProjection<'_, N>,
- viewport_to_surface: LayoutTransform2D,
- ) -> Self
- where
- N: Copy + Debug + Eq + Hash,
- {
- let box_count = projection.world.boxes.len();
- let mut spaces = vec![None; box_count];
- let mut visiting = vec![false; box_count];
- let viewport_scroll =
- projection.scroll_extents[projection.world.root.index()].applied_offset;
-
- for index in 0..box_count {
- resolve_box_space(
- index,
- projection,
- viewport_to_surface,
- viewport_scroll,
- &mut spaces,
- &mut visiting,
- );
- }
-
- Self {
- spaces: spaces
- .into_iter()
- .map(|space| space.expect("validated layout boxes have a paint space"))
- .collect(),
- }
- }
-
- pub(super) fn get(&self, id: LayoutBoxId) -> PaintSpace {
- self.spaces[id.index()]
- }
-}
-
-fn resolve_box_space<N>(
- index: usize,
- projection: &OutputProjection<'_, N>,
- viewport_to_surface: LayoutTransform2D,
- viewport_scroll: LayoutPoint,
- spaces: &mut [Option<PaintSpace>],
- visiting: &mut [bool],
-) -> PaintSpace
-where
- N: Copy + Debug + Eq + Hash,
-{
- if let Some(space) = spaces[index] {
- return space;
- }
- assert!(
- !visiting[index],
- "layout-parent cycles are rejected before paint projection"
- );
- visiting[index] = true;
-
- let layout_box = &projection.world.boxes[index];
- let parent = layout_box.layout_parent;
- let mut space = if let Some(parent) = parent {
- let parent_space = resolve_box_space(
- parent.index(),
- projection,
- viewport_to_surface,
- viewport_scroll,
- spaces,
- visiting,
- );
- let mut space = parent_space;
- let parent_scroll = &projection.scroll_extents[parent.index()];
- if parent != projection.world.root && parent_scroll.is_scroll_container {
- let offset = parent_scroll.applied_offset;
- space
- .establish_property_transform(LayoutTransform2D::translation(-offset.x, -offset.y));
- }
- space
- } else {
- let is_viewport_anchored = layout_box.style.is_fixed_positioned();
- let transform = if is_viewport_anchored {
- viewport_to_surface
- } else {
- viewport_to_surface.concatenate(LayoutTransform2D::translation(
- -viewport_scroll.x,
- -viewport_scroll.y,
- ))
- };
- PaintSpace::new(transform)
- };
-
- let location = layout_box.final_layout.location;
- space.translate_layout(LayoutPoint::new(location.x, location.y));
- if layout_box.style.establishes_paint_property_space() {
- space.establish_property_transform(projection.resolved_transforms[index]);
- }
-
- visiting[index] = false;
- spaces[index] = Some(space);
- space
-}
-
-#[cfg(test)]
-mod tests {
- use super::PaintSpace;
- use crate::{LayoutPoint, LayoutRect, LayoutTransform2D};
-
- #[test]
- fn ordinary_layout_offsets_remain_in_pre_transform_paint_space() {
- let mut space = PaintSpace::new(LayoutTransform2D::IDENTITY);
- space.translate_layout(LayoutPoint::new(0.0, 12.5));
-
- assert_eq!(
- space.offset_rect(LayoutRect::new(0.0, 0.0, 100.0, 12.5)),
- LayoutRect::new(0.0, 12.5, 100.0, 12.5)
- );
- assert_eq!(space.property_transform(), LayoutTransform2D::IDENTITY);
- }
-
- #[test]
- fn committing_a_property_transform_preserves_exact_geometry() {
- let mut space = PaintSpace::new(LayoutTransform2D::translation(3.0, 4.0));
- space.translate_layout(LayoutPoint::new(7.25, 11.5));
- let before = space
- .exact_transform()
- .concatenate(LayoutTransform2D::scale(2.0, 3.0));
-
- space.establish_property_transform(LayoutTransform2D::scale(2.0, 3.0));
-
- assert_eq!(space.paint_offset, LayoutPoint::ZERO);
- assert_eq!(space.exact_transform(), before);
- }
-}
diff --git a/moli-layout/src/paint/table.rs b/moli-layout/src/paint/table.rs
index 9b2d77269..d91dee723 100644
--- a/moli-layout/src/paint/table.rs
+++ b/moli-layout/src/paint/table.rs
@@ -24,9 +24,8 @@ pub(super) fn project_collapsed_table_borders<N>(
return;
};
let geometry = &projection.boxes[id.index()];
- let transform = snapshot.viewport_to_surface.concatenate(
- projection.coordinate_spaces[geometry.coordinate_space.index()].local_to_viewport,
- );
+ let paint_space = projection.coordinate_spaces[geometry.coordinate_space.index()]
+ .paint_space(snapshot.viewport_to_surface);
for segment in borders.segments() {
let mut widths = PaintEdgeSizes::default();
@@ -42,12 +41,12 @@ pub(super) fn project_collapsed_table_borders<N>(
styles.left = segment.style;
}
snapshot.push_fragment(PaintFragment::Border {
- rect: segment.rect,
+ rect: paint_space.pre_transform_rect(segment.rect),
widths,
colors,
styles,
radii: PaintCornerRadii::ZERO,
- transform,
+ transform: paint_space.property_transform(),
});
}
}
diff --git a/moli-layout/src/projection.rs b/moli-layout/src/projection.rs
index 43cbaa4d6..c3619577d 100644
--- a/moli-layout/src/projection.rs
+++ b/moli-layout/src/projection.rs
@@ -4,6 +4,7 @@ use taffy::ResolveOrZero;
use crate::layout_tree::LayoutCoordinateSpace;
use crate::stacking::{PaintOrderEvent, build_paint_order};
+use crate::style::ResolvedLayoutTransform;
use crate::{
FrozenCoordinateSpace, FrozenLayoutBox, FrozenLayoutTree, LayoutAnonymousReason,
LayoutBoxGeometry, LayoutBoxId, LayoutClipChainId, LayoutClipNode, LayoutCoordinateSpaceId,
@@ -71,7 +72,6 @@ where
.filter(|diagnostic| diagnostic.severity == PaintDiagnosticSeverity::Warning)
.count(),
};
-
let tree = projection.into_frozen_tree(content_size);
Ok(LayoutPassResult::new(
tree,
@@ -81,6 +81,73 @@ where
))
}
+/// Blink-like linear paint space for one projected coordinate space.
+///
+/// Chromium describes this space as the combination of a transform and a
+/// paint offset. Keeping those two values together lets paint snap geometry
+/// before applying CSS and scroll property transforms.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub(crate) struct PaintSpace {
+ pub(crate) paint_offset: LayoutPoint,
+ property_transform: LayoutTransform2D,
+}
+
+impl PaintSpace {
+ pub(crate) const ROOT: Self = Self {
+ paint_offset: LayoutPoint::ZERO,
+ property_transform: LayoutTransform2D::IDENTITY,
+ };
+
+ pub(crate) fn with_outer_transform(self, outer: LayoutTransform2D) -> Self {
+ Self {
+ paint_offset: self.paint_offset,
+ property_transform: outer.concatenate(self.property_transform),
+ }
+ }
+
+ pub(crate) fn local_transform(self) -> LayoutTransform2D {
+ self.property_transform
+ .concatenate(LayoutTransform2D::translation(
+ self.paint_offset.x,
+ self.paint_offset.y,
+ ))
+ }
+
+ pub(crate) fn pre_transform_rect(self, rect: LayoutRect) -> LayoutRect {
+ LayoutRect::new(
+ rect.x + self.paint_offset.x,
+ rect.y + self.paint_offset.y,
+ rect.width,
+ rect.height,
+ )
+ }
+
+ pub(crate) const fn property_transform(self) -> LayoutTransform2D {
+ self.property_transform
+ }
+}
+
+/// One coordinate space while output and paint projection are both live.
+///
+/// The public layout space retains exact CSS geometry for queries. `paint`
+/// may deliberately diverge at transform boundaries because Blink rounds the
+/// property translation and carries only the transform-safe subpixel residue.
+#[derive(Clone, Debug, PartialEq)]
+pub(crate) struct ProjectedCoordinateSpace {
+ pub(crate) layout: LayoutCoordinateSpace,
+ pub(crate) paint: PaintSpace,
+}
+
+impl ProjectedCoordinateSpace {
+ fn into_layout_space(self) -> LayoutCoordinateSpace {
+ self.layout
+ }
+
+ pub(crate) fn paint_space(&self, outer: LayoutTransform2D) -> PaintSpace {
+ self.paint.with_outer_transform(outer)
+ }
+}
+
pub(crate) struct OutputProjection<'a, N>
where
N: Copy + Debug + Eq + Hash,
@@ -95,11 +162,11 @@ where
fragments: Vec<LayoutFragment>,
scroll_proxy_links: Vec<(N, LayoutOutputBoxId)>,
pub(crate) scroll_extents: Vec<LayoutScrollExtent>,
- pub(crate) coordinate_spaces: Vec<LayoutCoordinateSpace>,
+ pub(crate) coordinate_spaces: Vec<ProjectedCoordinateSpace>,
pub(crate) clip_chain: Vec<LayoutClipNode>,
paint_order_count: usize,
pub(crate) diagnostics: Vec<PaintDiagnostic>,
- pub(crate) resolved_transforms: Vec<LayoutTransform2D>,
+ resolved_transforms: Vec<ResolvedLayoutTransform>,
overflow: Vec<LayoutRect>,
viewport_anchored: Vec<bool>,
direct_fragments: Vec<Option<LayoutFragmentId>>,
@@ -143,7 +210,7 @@ where
clip_chain: Vec::new(),
paint_order_count: 0,
diagnostics: Vec::new(),
- resolved_transforms: vec![LayoutTransform2D::IDENTITY; count],
+ resolved_transforms: vec![ResolvedLayoutTransform::IDENTITY; count],
overflow: vec![LayoutRect::ZERO; count],
viewport_anchored: vec![false; count],
direct_fragments: vec![None; count],
@@ -199,7 +266,7 @@ where
let resolved = layout_box
.style
.resolved_2d_transform(border_box.width, border_box.height);
- self.resolved_transforms[index] = resolved.transform;
+ self.resolved_transforms[index] = resolved;
if resolved.has_unsupported_3d {
self.diagnostics.push(PaintDiagnostic::new(
"transform-3d-geometry-fallback",
@@ -308,7 +375,8 @@ where
};
let location = self.world.boxes[index].final_layout.location;
let layout_translation = LayoutTransform2D::translation(location.x, location.y);
- let local_to_parent = layout_translation.concatenate(self.resolved_transforms[index]);
+ let local_to_parent =
+ layout_translation.concatenate(self.resolved_transforms[index].transform);
let mapped = local_to_parent
.map_rect(visual_overflow)
.bounding_rect()
@@ -386,13 +454,16 @@ where
fn build_coordinate_spaces(&mut self) -> Result<(), LayoutError> {
let mut spaces = vec![None; self.world.boxes.len() + 1];
- spaces[0] = Some(LayoutCoordinateSpace {
- id: LayoutCoordinateSpaceId::from_index(0),
- owner: None,
- parent: None,
- local_to_parent: LayoutTransform2D::IDENTITY,
- local_to_document: LayoutTransform2D::IDENTITY,
- local_to_viewport: LayoutTransform2D::IDENTITY,
+ spaces[0] = Some(ProjectedCoordinateSpace {
+ layout: LayoutCoordinateSpace {
+ id: LayoutCoordinateSpaceId::from_index(0),
+ owner: None,
+ parent: None,
+ local_to_parent: LayoutTransform2D::IDENTITY,
+ local_to_document: LayoutTransform2D::IDENTITY,
+ local_to_viewport: LayoutTransform2D::IDENTITY,
+ },
+ paint: PaintSpace::ROOT,
});
let mut state = vec![0_u8; self.world.boxes.len()];
for index in 0..self.world.boxes.len() {
@@ -644,7 +715,7 @@ where
let root_layout = self.world.boxes[root].final_layout.location;
let layout_translation = LayoutTransform2D::translation(root_layout.x, root_layout.y);
let overflow = layout_translation
- .concatenate(self.resolved_transforms[root])
+ .concatenate(self.resolved_transforms[root].transform)
.map_rect(self.overflow[root])
.bounding_rect()
.union(
@@ -660,7 +731,10 @@ where
fn into_frozen_tree(self, content_size: LayoutSize) -> FrozenLayoutTree<N> {
let root_box = LayoutOutputBoxId::from_index(self.world.root.index());
- let mut coordinate_spaces = self.coordinate_spaces.into_iter();
+ let mut coordinate_spaces = self
+ .coordinate_spaces
+ .into_iter()
+ .map(ProjectedCoordinateSpace::into_layout_space);
let viewport_coordinate_space = FrozenCoordinateSpace::from(
coordinate_spaces
.next()
@@ -702,15 +776,108 @@ where
}
}
+#[derive(Clone, Copy)]
+struct SubpixelPropagation {
+ x: bool,
+ y: bool,
+}
+
+impl SubpixelPropagation {
+ const BOTH: Self = Self { x: true, y: true };
+ const NONE: Self = Self { x: false, y: false };
+
+ fn through_transform(transform: LayoutTransform2D) -> Self {
+ let [scale_x, skew_y, skew_x, scale_y, _, _] = transform.coefficients;
+ if skew_x != 0.0 || skew_y != 0.0 {
+ return Self::NONE;
+ }
+ Self {
+ x: scale_x == 1.0,
+ y: scale_y == 1.0,
+ }
+ }
+}
+
+fn establish_property_space(
+ state: PaintSpace,
+ property_transform: LayoutTransform2D,
+ propagation: SubpixelPropagation,
+) -> PaintSpace {
+ let rounded_offset = LayoutPoint::new(
+ crate::snapshot::round_layout_pixel(f64::from(state.paint_offset.x)) as f32,
+ crate::snapshot::round_layout_pixel(f64::from(state.paint_offset.y)) as f32,
+ );
+ let residual = LayoutPoint::new(
+ state.paint_offset.x - rounded_offset.x,
+ state.paint_offset.y - rounded_offset.y,
+ );
+ PaintSpace {
+ property_transform: state
+ .property_transform
+ .concatenate(LayoutTransform2D::translation(
+ rounded_offset.x,
+ rounded_offset.y,
+ ))
+ .concatenate(property_transform),
+ paint_offset: LayoutPoint::new(
+ if propagation.x { residual.x } else { 0.0 },
+ if propagation.y { residual.y } else { 0.0 },
+ ),
+ }
+}
+
+fn resolve_paint_space(
+ parent: Option<PaintSpace>,
+ viewport_scroll: LayoutPoint,
+ is_viewport_anchored: bool,
+ parent_scroll: Option<LayoutPoint>,
+ location: LayoutPoint,
+ resolved_transform: ResolvedLayoutTransform,
+) -> PaintSpace {
+ let mut state = parent.unwrap_or(PaintSpace {
+ property_transform: if is_viewport_anchored {
+ LayoutTransform2D::IDENTITY
+ } else {
+ LayoutTransform2D::translation(-viewport_scroll.x, -viewport_scroll.y)
+ },
+ paint_offset: LayoutPoint::ZERO,
+ });
+
+ // A scroll container establishes a property space even at scroll offset
+ // zero. Commit the rounded translation while retaining its fractional
+ // residue for descendant snapping, then apply scrolling outside it.
+ if let Some(parent_scroll) = parent_scroll {
+ state = establish_property_space(
+ state,
+ LayoutTransform2D::translation(-parent_scroll.x, -parent_scroll.y),
+ SubpixelPropagation::BOTH,
+ );
+ }
+ state.paint_offset = LayoutPoint::new(
+ state.paint_offset.x + location.x,
+ state.paint_offset.y + location.y,
+ );
+
+ if resolved_transform.establishes_property_space {
+ let propagation = if resolved_transform.has_unsupported_3d {
+ SubpixelPropagation::NONE
+ } else {
+ SubpixelPropagation::through_transform(resolved_transform.transform)
+ };
+ state = establish_property_space(state, resolved_transform.transform, propagation);
+ }
+ state
+}
+
#[allow(clippy::too_many_arguments)]
fn resolve_coordinate_space<N>(
index: usize,
world: &LayoutWorld<N>,
viewport_scroll: LayoutPoint,
scroll_extents: &[LayoutScrollExtent],
- resolved_transforms: &[LayoutTransform2D],
+ resolved_transforms: &[ResolvedLayoutTransform],
viewport_anchored: &mut [bool],
- spaces: &mut [Option<LayoutCoordinateSpace>],
+ spaces: &mut [Option<ProjectedCoordinateSpace>],
state: &mut [u8],
) -> Result<(), LayoutError>
where
@@ -755,7 +922,7 @@ where
Some(parent) => spaces
.get(parent.index() + 1)
.and_then(Option::as_ref)
- .map(|space| space.local_to_document)
+ .map(|space| space.layout.local_to_document)
.ok_or(LayoutError::InvalidBoxReference {
index: parent.index(),
})?,
@@ -766,32 +933,56 @@ where
|parent| viewport_anchored[parent.index()],
);
viewport_anchored[index] = is_viewport_anchored;
- let parent_scroll = parent_box.map_or(LayoutPoint::ZERO, |parent| {
- if parent == world.root {
- LayoutPoint::ZERO
- } else {
- scroll_extents[parent.index()].applied_offset
- }
+ let parent_scroll = parent_box.and_then(|parent| {
+ (parent != world.root && scroll_extents[parent.index()].is_scroll_container)
+ .then_some(scroll_extents[parent.index()].applied_offset)
});
+ let applied_parent_scroll = parent_scroll.unwrap_or(LayoutPoint::ZERO);
let location = layout_box.final_layout.location;
- let local_to_parent =
- LayoutTransform2D::translation(location.x - parent_scroll.x, location.y - parent_scroll.y)
- .concatenate(resolved_transforms[index]);
+ let local_to_parent = LayoutTransform2D::translation(
+ location.x - applied_parent_scroll.x,
+ location.y - applied_parent_scroll.y,
+ )
+ .concatenate(resolved_transforms[index].transform);
let local_to_document = if parent_box.is_none() && is_viewport_anchored {
LayoutTransform2D::translation(viewport_scroll.x, viewport_scroll.y)
.concatenate(local_to_parent)
} else {
parent_transform.concatenate(local_to_parent)
};
- let local_to_viewport = LayoutTransform2D::translation(-viewport_scroll.x, -viewport_scroll.y)
- .concatenate(local_to_document);
- spaces[index + 1] = Some(LayoutCoordinateSpace {
- id: LayoutCoordinateSpaceId::from_index(index + 1),
- owner: Some(LayoutOutputBoxId::from_index(index)),
- parent: Some(parent_space),
- local_to_parent,
- local_to_document,
- local_to_viewport,
+ let parent_paint_state = match parent_box {
+ Some(parent) => Some(
+ spaces
+ .get(parent.index() + 1)
+ .and_then(Option::as_ref)
+ .map(|space| space.paint)
+ .ok_or(LayoutError::InvalidBoxReference {
+ index: parent.index(),
+ })?,
+ ),
+ None => None,
+ };
+ let paint = resolve_paint_space(
+ parent_paint_state,
+ viewport_scroll,
+ is_viewport_anchored,
+ parent_scroll,
+ LayoutPoint::new(location.x, location.y),
+ resolved_transforms[index],
+ );
+ let exact_local_to_viewport =
+ LayoutTransform2D::translation(-viewport_scroll.x, -viewport_scroll.y)
+ .concatenate(local_to_document);
+ spaces[index + 1] = Some(ProjectedCoordinateSpace {
+ layout: LayoutCoordinateSpace {
+ id: LayoutCoordinateSpaceId::from_index(index + 1),
+ owner: Some(LayoutOutputBoxId::from_index(index)),
+ parent: Some(parent_space),
+ local_to_parent,
+ local_to_document,
+ local_to_viewport: exact_local_to_viewport,
+ },
+ paint,
});
state[index] = 2;
Ok(())
@@ -928,3 +1119,111 @@ where
margin: margin_box,
}
}
+
+#[cfg(test)]
+mod paint_space_tests {
+ use super::*;
+
+ fn property_transform(transform: LayoutTransform2D) -> ResolvedLayoutTransform {
+ ResolvedLayoutTransform {
+ transform,
+ has_unsupported_3d: false,
+ establishes_property_space: true,
+ }
+ }
+
+ #[test]
+ fn ordinary_offsets_accumulate_without_an_extra_property_transform() {
+ let root = resolve_paint_space(
+ None,
+ LayoutPoint::ZERO,
+ false,
+ None,
+ LayoutPoint::ZERO,
+ ResolvedLayoutTransform::IDENTITY,
+ );
+ let ordinary = resolve_paint_space(
+ Some(root),
+ LayoutPoint::ZERO,
+ false,
+ None,
+ LayoutPoint::new(0.0, 12.5),
+ ResolvedLayoutTransform::IDENTITY,
+ );
+ assert_eq!(ordinary.paint_offset, LayoutPoint::new(0.0, 12.5));
+ assert_eq!(ordinary.property_transform, LayoutTransform2D::IDENTITY);
+ assert_eq!(
+ ordinary.local_transform(),
+ LayoutTransform2D::translation(0.0, 12.5)
+ );
+ }
+
+ #[test]
+ fn translation_property_space_keeps_the_fractional_residual() {
+ let transformed = resolve_paint_space(
+ Some(PaintSpace {
+ paint_offset: LayoutPoint::new(0.75, 0.25),
+ property_transform: LayoutTransform2D::IDENTITY,
+ }),
+ LayoutPoint::ZERO,
+ false,
+ None,
+ LayoutPoint::ZERO,
+ property_transform(LayoutTransform2D::translation(5.0, 7.0)),
+ );
+ assert_eq!(transformed.paint_offset, LayoutPoint::new(-0.25, 0.25));
+ assert_eq!(
+ transformed.property_transform,
+ LayoutTransform2D::translation(6.0, 7.0)
+ );
+ assert_eq!(
+ transformed.local_transform(),
+ LayoutTransform2D::translation(5.75, 7.25)
+ );
+ }
+
+ #[test]
+ fn scale_discards_only_the_residual_on_scaled_axes() {
+ let transformed = resolve_paint_space(
+ Some(PaintSpace {
+ paint_offset: LayoutPoint::new(0.75, 0.75),
+ property_transform: LayoutTransform2D::IDENTITY,
+ }),
+ LayoutPoint::ZERO,
+ false,
+ None,
+ LayoutPoint::ZERO,
+ property_transform(LayoutTransform2D::scale(2.0, 1.0)),
+ );
+ assert_eq!(transformed.paint_offset, LayoutPoint::new(0.0, -0.25));
+ assert_eq!(
+ transformed.property_transform,
+ LayoutTransform2D::translation(1.0, 1.0)
+ .concatenate(LayoutTransform2D::scale(2.0, 1.0))
+ );
+ }
+
+ #[test]
+ fn scroll_property_space_exists_at_zero_offset_and_preserves_residual() {
+ let scrolled_child = resolve_paint_space(
+ Some(PaintSpace {
+ paint_offset: LayoutPoint::new(0.75, 0.0),
+ property_transform: LayoutTransform2D::IDENTITY,
+ }),
+ LayoutPoint::ZERO,
+ false,
+ Some(LayoutPoint::ZERO),
+ LayoutPoint::new(0.125, 0.0),
+ ResolvedLayoutTransform::IDENTITY,
+ );
+ assert_eq!(
+ scrolled_child.property_transform,
+ LayoutTransform2D::translation(1.0, 0.0)
+ );
+ assert_eq!(scrolled_child.paint_offset, LayoutPoint::new(-0.125, 0.0));
+ assert_eq!(
+ scrolled_child.local_transform(),
+ LayoutTransform2D::translation(0.875, 0.0)
+ );
+ }
+}
diff --git a/moli-layout/src/snapshot.rs b/moli-layout/src/snapshot.rs
index 08e33a5bd..25ed191d1 100644
--- a/moli-layout/src/snapshot.rs
+++ b/moli-layout/src/snapshot.rs
@@ -58,6 +58,58 @@ impl Default for PaintColor {
/// Paint-facing compatibility name for a canonical CSS-pixel rectangle.
pub type PaintRect = crate::LayoutRect;
+/// Snap one paint-space extent to whole layout pixels while preserving a
+/// non-trivial nonzero size.
+///
+/// This is Blink's `SnapSizeToPixel` contract over Moli's shared 1/64 layout
+/// grid. The returned location and size must be used together: the size is
+/// sensitive to the fractional part of the location.
+pub fn pixel_snap_paint_axis(location: f32, size: f32) -> (f32, f32) {
+ pixel_snap_paint_axis_impl(location, size, false)
+}
+
+/// Snap one paint-space extent to whole layout pixels, allowing a thin extent
+/// to collapse to zero.
+///
+/// Border inner edges use this variant, matching Blink's
+/// `SnapSizeToPixelAllowingZero` behavior.
+pub fn pixel_snap_paint_axis_allowing_zero(location: f32, size: f32) -> (f32, f32) {
+ pixel_snap_paint_axis_impl(location, size, true)
+}
+
+fn pixel_snap_paint_axis_impl(location: f32, size: f32, allow_zero: bool) -> (f32, f32) {
+ let location = f64::from(location);
+ let size = f64::from(size);
+ let fraction = location % 1.0;
+ let snapped_location = round_layout_pixel(location);
+ let mut snapped_size = round_layout_pixel(fraction + size) - round_layout_pixel(fraction);
+ let layout_unit_epsilon = 1.0 / f64::from(crate::LAYOUT_SUBPIXELS_PER_CSS_PIXEL);
+ if !allow_zero && snapped_size == 0.0 && size.abs() > 4.0 * layout_unit_epsilon {
+ snapped_size = size.signum();
+ }
+ (snapped_location as f32, snapped_size as f32)
+}
+
+pub(crate) fn round_layout_pixel(value: f64) -> f64 {
+ (value + 0.5).floor()
+}
+
+/// Pixel-snap a positive finite rectangle in pre-transform paint space.
+pub fn pixel_snap_paint_rect(rect: PaintRect) -> Option<PaintRect> {
+ if !rect.x.is_finite()
+ || !rect.y.is_finite()
+ || !rect.width.is_finite()
+ || !rect.height.is_finite()
+ || rect.width <= 0.0
+ || rect.height <= 0.0
+ {
+ return None;
+ }
+ let (x, width) = pixel_snap_paint_axis(rect.x, rect.width);
+ let (y, height) = pixel_snap_paint_axis(rect.y, rect.height);
+ (width > 0.0 && height > 0.0).then(|| PaintRect::new(x, y, width, height))
+}
+
/// Paint-facing compatibility name for a canonical CSS-pixel point.
pub type PaintPoint = crate::LayoutPoint;
@@ -1086,6 +1138,18 @@ mod tests {
fn assert_source_free<T: Send + Sync + 'static>() {}
+ #[test]
+ fn paint_pixel_snapping_preserves_blink_layout_unit_semantics() {
+ assert_eq!(pixel_snap_paint_axis(0.0, 3.0 / 64.0), (0.0, 0.0));
+ assert_eq!(pixel_snap_paint_axis(0.0, 5.0 / 64.0), (0.0, 1.0));
+ assert_eq!(pixel_snap_paint_axis(0.5, 1.5), (1.0, 1.0));
+ assert_eq!(pixel_snap_paint_axis_allowing_zero(0.5, 0.5), (1.0, 0.0));
+ assert_eq!(
+ pixel_snap_paint_rect(PaintRect::new(151.09375, 24.0, 90.0, 90.0)),
+ Some(PaintRect::new(151.0, 24.0, 90.0, 90.0))
+ );
+ }
+
#[test]
fn snapshot_is_owned_and_source_free() {
assert_source_free::<PaintSnapshot>();
diff --git a/moli-layout/src/style.rs b/moli-layout/src/style.rs
index 8387128bb..fff3969af 100644
--- a/moli-layout/src/style.rs
+++ b/moli-layout/src/style.rs
@@ -309,12 +309,14 @@ enum GeneratedContent {
pub(crate) struct ResolvedLayoutTransform {
pub(crate) transform: LayoutTransform2D,
pub(crate) has_unsupported_3d: bool,
+ pub(crate) establishes_property_space: bool,
}
impl ResolvedLayoutTransform {
- const IDENTITY: Self = Self {
+ pub(crate) const IDENTITY: Self = Self {
transform: LayoutTransform2D::IDENTITY,
has_unsupported_3d: false,
+ establishes_property_space: false,
};
}
@@ -1121,22 +1123,22 @@ impl ResolvedLayoutStyle {
self.pointer_events
}
- pub(crate) const fn establishes_paint_property_space(&self) -> bool {
- self.establishes_transform_containing_block
- }
-
pub(crate) fn resolved_2d_transform(&self, width: f32, height: f32) -> ResolvedLayoutTransform {
if let Some(transform) = self.synthetic_transform {
return ResolvedLayoutTransform {
transform,
has_unsupported_3d: false,
+ establishes_property_space: true,
};
}
- self.computed
+ let mut resolved = self
+ .computed
.as_ref()
.map_or(ResolvedLayoutTransform::IDENTITY, |computed| {
resolve_stylo_2d_transform(computed.get_box(), width, height)
- })
+ });
+ resolved.establishes_property_space = self.establishes_transform_containing_block;
+ resolved
}
pub(crate) fn is_absolute_positioned(&self) -> bool {
@@ -1844,6 +1846,7 @@ fn resolve_stylo_2d_transform(
ResolvedLayoutTransform {
transform: resolved,
has_unsupported_3d,
+ establishes_property_space: false,
}
}
diff --git a/moli-layout/tests/phase4_layout_contract.rs b/moli-layout/tests/phase4_layout_contract.rs
index 46d8285b8..2e8288ebf 100644
--- a/moli-layout/tests/phase4_layout_contract.rs
+++ b/moli-layout/tests/phase4_layout_contract.rs
@@ -1129,13 +1129,14 @@ fn unavailable_images_use_zero_default_size_and_a_content_box_outline() {
colors,
transform,
..
- } if *rect == PaintRect::new(0.0, 0.0, 80.0, 40.0)
+ } if rect.width == 80.0
+ && rect.height == 40.0
&& *widths == moli_layout::PaintEdgeSizes::new(1.0, 1.0, 1.0, 1.0)
&& colors.top == light_gray
&& colors.right == light_gray
&& colors.bottom == light_gray
&& colors.left == light_gray
- && transform.map_point(moli_layout::LayoutPoint::ZERO)
+ && transform.map_point(moli_layout::LayoutPoint::new(rect.x, rect.y))
== moli_layout::LayoutPoint::new(0.0, 150.0)
)
}),
diff --git a/moli-paint/src/raster/mod.rs b/moli-paint/src/raster/mod.rs
index fcb153824..00cd115ae 100644
--- a/moli-paint/src/raster/mod.rs
+++ b/moli-paint/src/raster/mod.rs
@@ -22,6 +22,7 @@ use moli_layout::{
PaintGradientHueDirection, PaintImage, PaintImageSampling, PaintLineCap, PaintLineJoin,
PaintPath, PaintPathElement, PaintRect, PaintShape, PaintSnapshot, PaintStroke, PaintSvgImage,
PaintTextDecoration, PaintTextDecorationStyle, PaintTextShadow, PaintTransform2D,
+ pixel_snap_paint_axis, pixel_snap_paint_axis_allowing_zero, pixel_snap_paint_rect,
};
use peniko::{
BlendMode, Blob, Color, Compose, Extend, Fill, Gradient, ImageAlphaType, ImageBrush, ImageData,
@@ -763,44 +764,13 @@ fn paint_svg_image(
}
fn pixel_snapped_image_destination(destination: PaintRect) -> Option<PaintRect> {
- if !destination.x.is_finite()
- || !destination.y.is_finite()
- || !destination.width.is_finite()
- || !destination.height.is_finite()
- || destination.width <= 0.0
- || destination.height <= 0.0
- {
- return None;
- }
-
- // Layout and CSSOM keep fractional geometry. Paint projection has moved
- // ordinary layout offsets into this destination while leaving scroll/CSS
- // transforms on the fragment, so snapping here happens in the same
- // pre-transform space as Blink's ToPixelSnappedRect.
- let (x, width) = pixel_snap_image_axis(destination.x, destination.width);
- let (y, height) = pixel_snap_image_axis(destination.y, destination.height);
- (width > 0.0 && height > 0.0).then(|| PaintRect::new(x, y, width, height))
-}
-
-fn pixel_snap_image_axis(location: f32, size: f32) -> (f32, f32) {
- let location = f64::from(location);
- let size = f64::from(size);
- let fraction = location % 1.0;
- let snapped_location = round_layout_pixel(location);
- let mut snapped_size = round_layout_pixel(fraction + size) - round_layout_pixel(fraction);
-
- // Blink's SnapSizeToPixel keeps a non-trivial LayoutUnit extent visible.
- // LayoutUnit has six fractional bits; this threshold belongs to the paint
- // compatibility rule and does not impose precision on Taffy.
- const MIN_NON_EMPTY_SIZE: f64 = 4.0 / 64.0;
- if snapped_size == 0.0 && size > MIN_NON_EMPTY_SIZE {
- snapped_size = 1.0;
- }
- (snapped_location as f32, snapped_size as f32)
-}
-
-fn round_layout_pixel(value: f64) -> f64 {
- (value + 0.5).floor()
+ // Image geometry remains fractional for layout and CSSOM. Snapshot
+ // projection has already applied ordinary paint offsets while preserving
+ // CSS/scroll property transforms; rasterization only snaps the image quad
+ // in that pre-transform paint space. Adjacent fractional images therefore
+ // share one pixel boundary, matching Blink's
+ // ToPixelSnappedRect/SnapSizeToPixel contract.
+ pixel_snap_paint_rect(destination)
}
fn paint_border(
@@ -817,6 +787,9 @@ fn paint_border(
return;
};
let widths = sanitize_border_widths(widths, rect.width() as f32, rect.height() as f32);
+ let Some((rect, widths)) = pixel_snapped_border_geometry(rect, widths) else {
+ return;
+ };
let radii = normalize_radii(radii, rect.width(), rect.height());
if paint_uniform_solid_border(scene, rect, widths, colors, styles, radii, transform) {
return;
@@ -839,6 +812,47 @@ fn paint_border(
}
}
+/// Resolve the outer and inner border edges onto the layout-pixel grid.
+///
+/// Blink independently snaps `PixelSnappedContouredBorder` and
+/// `PixelSnappedContouredInnerBorder`. Reconstructing the four used widths
+/// from those two rectangles preserves that contract for asymmetric and
+/// fractional borders instead of merely rounding the outer origin.
+fn pixel_snapped_border_geometry(
+ rect: Rect,
+ widths: PaintEdgeSizes,
+) -> Option<(Rect, PaintEdgeSizes)> {
+ let (outer_x, outer_width) = pixel_snap_paint_axis(rect.x0 as f32, rect.width() as f32);
+ let (outer_y, outer_height) = pixel_snap_paint_axis(rect.y0 as f32, rect.height() as f32);
+ if outer_width <= 0.0 || outer_height <= 0.0 {
+ return None;
+ }
+
+ let inner_x = rect.x0 as f32 + widths.left;
+ let inner_y = rect.y0 as f32 + widths.top;
+ let inner_width = (rect.width() as f32 - widths.left - widths.right).max(0.0);
+ let inner_height = (rect.height() as f32 - widths.top - widths.bottom).max(0.0);
+ let (inner_x, inner_width) = pixel_snap_paint_axis_allowing_zero(inner_x, inner_width);
+ let (inner_y, inner_height) = pixel_snap_paint_axis_allowing_zero(inner_y, inner_height);
+
+ let outer = Rect::new(
+ f64::from(outer_x),
+ f64::from(outer_y),
+ f64::from(outer_x + outer_width),
+ f64::from(outer_y + outer_height),
+ );
+ let widths = PaintEdgeSizes::new(
+ (inner_y - outer_y).clamp(0.0, outer_height),
+ (outer.x1 as f32 - (inner_x + inner_width)).clamp(0.0, outer_width),
+ (outer.y1 as f32 - (inner_y + inner_height)).clamp(0.0, outer_height),
+ (inner_x - outer_x).clamp(0.0, outer_width),
+ );
+ Some((
+ outer,
+ sanitize_border_widths(widths, outer_width, outer_height),
+ ))
+}
+
#[derive(Clone, Copy)]
enum BorderEdge {
Top,
@@ -2456,6 +2470,26 @@ mod tests {
assert_eq!(pixel(&image, 3, 3), [255, 255, 255, 255]);
}
+ #[test]
+ fn fractional_box_borders_snap_before_rasterization() {
+ let green = PaintColor::new(0.0, 1.0, 0.0, 1.0);
+ let gray = PaintColor::new(128.0 / 255.0, 128.0 / 255.0, 128.0 / 255.0, 1.0);
+ let rect = PaintRect::new(1.09375, 1.0, 6.0, 6.0);
+ let mut snapshot = snapshot(8, 8, 1.0);
+ snapshot.push_fragment(PaintFragment::solid_rect(rect, green));
+ snapshot.push_fragment(PaintFragment::border(
+ rect,
+ PaintEdgeSizes::new(1.0, 1.0, 1.0, 1.0),
+ PaintBorderColors::all(gray),
+ ));
+
+ let image = raster_snapshot(&snapshot).unwrap();
+ for coordinate in 1..7 {
+ assert_eq!(pixel(&image, 1, coordinate), [128, 128, 128, 255]);
+ assert_eq!(pixel(&image, 6, coordinate), [128, 128, 128, 255]);
+ }
+ }
+
#[test]
fn rectangular_clip_scopes_bound_following_fragments() {
let mut snapshot = snapshot(4, 2, 1.0);
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 1e319ff1d..70438ab0b 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
@@ -775,8 +775,14 @@ document.body.innerHTML = `<div id=centered></div><div id=definite-parent><div i
let index = ((y * image.width + x) * 4) as usize;
<[u8; 4]>::try_from(&image.rgba[index..index + 4]).expect("RGBA pixel")
};
+ // Blink retains the fractional layout origin for DOM geometry, but
+ // box background painting snaps the fill rect to device pixels.
+ // The 975px box therefore paints [233, 1208), with no half-covered
+ // pixel at either edge at device scale 1.
+ assert_eq!(pixel(232, 10), [255, 255, 255, 255]);
assert_eq!(pixel(233, 10), [255, 0, 0, 255]);
- assert_eq!(pixel(232, 10), [255, 127, 127, 255]);
+ assert_eq!(pixel(1207, 10), [255, 0, 0, 255]);
+ assert_eq!(pixel(1208, 10), [255, 255, 255, 255]);
assert_eq!(pixel(5, 230), [0, 0, 255, 255]);
assert_eq!(pixel(5, 505), [0, 255, 0, 255]);
Ok::<_, anyhow::Error>(())