Skip to content

armgit / moli

Public Imported from GitHub
0

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

Pixel-snap images in pre-transform paint space

ldm01b54b7446958
diff --git a/moli-layout/src/paint/image.rs b/moli-layout/src/paint/image.rs
index e80f61bea..75232e89f 100644
--- a/moli-layout/src/paint/image.rs
+++ b/moli-layout/src/paint/image.rs
@@ -11,7 +11,10 @@ use style::{
values::{computed::CSSPixelLength, specified::image::ImageRendering},
};
-use super::geometry::{BoxAreas, BoxModelBox};
+use super::{
+ geometry::{BoxAreas, BoxModelBox},
+ paint_space::PaintSpace,
+};
use crate::{
LayoutBoxId, LayoutPoint, LayoutRect, LayoutReplacedKind, LayoutSize, LayoutTransform2D,
PaintBorderColors, PaintBorderStyle, PaintBorderStyles, PaintColor, PaintCornerRadii,
@@ -23,6 +26,7 @@ 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,
@@ -128,20 +132,22 @@ pub(super) fn project_replaced_image<N>(
transform,
});
}
+ let destination = paint_space.offset_rect(destination);
+ let image_transform = paint_space.property_transform();
if let Some(pixels) = resource.pixels.clone() {
let image = snapshot.add_image(pixels);
snapshot.push_fragment(PaintFragment::Image(PaintImage {
image,
destination,
sampling,
- transform,
+ transform: image_transform,
}));
} else if let Some(svg) = resource.svg.clone() {
let image = snapshot.add_svg_image(svg);
snapshot.push_fragment(PaintFragment::SvgImage(PaintSvgImage {
image,
destination,
- transform,
+ transform: image_transform,
}));
}
if content_clip_needed {
diff --git a/moli-layout/src/paint/mod.rs b/moli-layout/src/paint/mod.rs
index 690362537..d47324889 100644
--- a/moli-layout/src/paint/mod.rs
+++ b/moli-layout/src/paint/mod.rs
@@ -6,6 +6,7 @@ mod geometry;
mod image;
mod inline_boxes;
mod mask;
+mod paint_space;
mod table;
mod text;
@@ -19,6 +20,7 @@ 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};
@@ -65,6 +67,7 @@ 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;
@@ -260,6 +263,7 @@ where
project_box_contents(
projection,
id,
+ &paint_spaces,
embedded_frames,
capture.include_backgrounds,
&mut snapshot,
@@ -657,6 +661,7 @@ 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,
@@ -681,7 +686,7 @@ fn project_box_contents<N>(
local_to_surface,
);
}
- project_replaced_image(projection, id, transform, snapshot);
+ project_replaced_image(projection, id, transform, paint_spaces.get(id), 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);
diff --git a/moli-layout/src/paint/paint_space.rs b/moli-layout/src/paint/paint_space.rs
new file mode 100644
index 000000000..d59bda52f
--- /dev/null
+++ b/moli-layout/src/paint/paint_space.rs
@@ -0,0 +1,205 @@
+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/projection.rs b/moli-layout/src/projection.rs
index 52c62b323..452fa0418 100644
--- a/moli-layout/src/projection.rs
+++ b/moli-layout/src/projection.rs
@@ -111,7 +111,7 @@ where
paint_order: Vec<LayoutFragmentId>,
hit_entries: Vec<LayoutHitTestEntry<N>>,
pub(crate) diagnostics: Vec<PaintDiagnostic>,
- resolved_transforms: Vec<LayoutTransform2D>,
+ pub(crate) resolved_transforms: Vec<LayoutTransform2D>,
overflow: Vec<LayoutRect>,
viewport_anchored: Vec<bool>,
direct_fragments: Vec<Option<LayoutFragmentId>>,
diff --git a/moli-layout/src/style.rs b/moli-layout/src/style.rs
index 486dd9f56..8387128bb 100644
--- a/moli-layout/src/style.rs
+++ b/moli-layout/src/style.rs
@@ -1121,6 +1121,10 @@ 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 {
diff --git a/moli-layout/tests/phase4_layout_contract.rs b/moli-layout/tests/phase4_layout_contract.rs
index 6d2075483..fe2ce922b 100644
--- a/moli-layout/tests/phase4_layout_contract.rs
+++ b/moli-layout/tests/phase4_layout_contract.rs
@@ -1,14 +1,14 @@
-use std::collections::HashMap;
+use std::{collections::HashMap, sync::Arc};
use moli_layout::{
DocumentLayoutServices, LayoutDisplay, LayoutElementCategory, LayoutElementMetadata,
LayoutElementSemantics, LayoutError, LayoutFormControlData, LayoutFormControlKind,
- LayoutInputControlKind, LayoutListData, LayoutListMarkerPosition, LayoutListMarkerType,
- LayoutListRole, LayoutNamespace, LayoutPosition, LayoutPseudo, LayoutReplacedKind,
- LayoutSource, LayoutSourceKind, LayoutStyleResolver, LayoutTableData, LayoutTableRole,
- LayoutTextSelection, PaintBrush, PaintColor, PaintFragment, PaintRect, PaintShape,
- PaintSnapshot, PaintViewport, ReplacedMetrics, ResolvedLayoutStyle, ScreenshotLayoutRequest,
- build_screenshot_snapshot,
+ LayoutImageResource, LayoutInputControlKind, LayoutListData, LayoutListMarkerPosition,
+ LayoutListMarkerType, LayoutListRole, LayoutNamespace, LayoutPosition, LayoutPseudo,
+ LayoutReplacedKind, LayoutSource, LayoutSourceKind, LayoutStyleResolver, LayoutTableData,
+ LayoutTableRole, LayoutTextSelection, PaintBrush, PaintColor, PaintFragment, PaintRect,
+ PaintShape, PaintSnapshot, PaintTransform2D, PaintViewport, ReplacedMetrics,
+ ResolvedLayoutStyle, ScreenshotLayoutRequest, build_screenshot_snapshot,
};
use style::Atom;
use taffy::{
@@ -28,6 +28,7 @@ struct Node {
text: Option<&'static str>,
children: Vec<usize>,
metrics: Option<ReplacedMetrics>,
+ image: Option<LayoutImageResource>,
selection: Option<LayoutTextSelection>,
}
@@ -51,6 +52,7 @@ impl Node {
text: None,
children,
metrics: None,
+ image: None,
selection: None,
}
}
@@ -63,6 +65,7 @@ impl Node {
text: Some(text),
children: Vec::new(),
metrics: None,
+ image: None,
selection: None,
}
}
@@ -81,6 +84,11 @@ impl Node {
self.metrics = Some(metrics);
self
}
+
+ fn with_image(mut self, image: LayoutImageResource) -> Self {
+ self.image = Some(image);
+ self
+ }
}
struct Source(Vec<Node>);
@@ -129,6 +137,14 @@ impl LayoutSource for Source {
fn replaced_metrics(&self, node: Self::NodeId) -> Option<ReplacedMetrics> {
self.0[node].metrics
}
+
+ fn replaced_image(
+ &self,
+ node: Self::NodeId,
+ _style: &ResolvedLayoutStyle,
+ ) -> Option<LayoutImageResource> {
+ self.0[node].image.clone()
+ }
}
#[derive(Default)]
@@ -749,6 +765,80 @@ fn degenerate_css_ratio_falls_back_to_the_replaced_intrinsic_ratio() {
);
}
+/// Regression for
+/// <https://wpt.live/css/css-sizing/image-fractional-height-with-wide-aspect-ratio.html>.
+#[test]
+fn fractional_replaced_images_project_contiguous_pre_transform_destinations() {
+ let svg = Arc::new(
+ moli_image::decode_svg_image(
+ br##"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 96 12"><rect width="96" height="12" fill="green"/></svg>"##,
+ )
+ .expect("fixture SVG should parse"),
+ );
+ let image = LayoutImageResource {
+ intrinsic_width: 96.0,
+ intrinsic_height: 12.0,
+ pixels: None,
+ svg: Some(svg),
+ };
+ let labels = [
+ "row-1", "row-2", "row-3", "row-4", "row-5", "row-6", "row-7", "row-8",
+ ];
+ let mut nodes = vec![Node::element(
+ "root",
+ "div",
+ LayoutElementCategory::Generic,
+ None,
+ (1..=8).collect(),
+ )];
+ nodes.extend(labels.into_iter().map(|label| {
+ Node::element(
+ label,
+ "img",
+ LayoutElementCategory::Generic,
+ Some(LayoutReplacedKind::Image),
+ Vec::new(),
+ )
+ .with_metrics(ReplacedMetrics {
+ intrinsic_width: Some(96.0),
+ intrinsic_height: Some(12.0),
+ intrinsic_ratio: Some(8.0),
+ ..ReplacedMetrics::default()
+ })
+ .with_image(image.clone())
+ }));
+ let source = Source(nodes);
+ let mut styles = Styles::default();
+ styles.primary.insert(
+ 0,
+ sized(LayoutDisplay::Block, 100.0, 100.0, PaintColor::TRANSPARENT),
+ );
+ for node in 1..=8 {
+ styles.primary.insert(
+ node,
+ sized(LayoutDisplay::Block, 100.0, 12.5, PaintColor::TRANSPARENT),
+ );
+ }
+
+ let snapshot = render(&source, &mut styles, 100, 101);
+ let images = snapshot
+ .fragments
+ .iter()
+ .filter_map(|fragment| match fragment {
+ PaintFragment::SvgImage(image) => Some(image),
+ _ => None,
+ })
+ .collect::<Vec<_>>();
+ assert_eq!(images.len(), 8);
+ for (row, image) in images.into_iter().enumerate() {
+ assert_eq!(
+ image.destination,
+ PaintRect::new(0.0, row as f32 * 12.5, 100.0, 12.5)
+ );
+ assert_eq!(image.transform, PaintTransform2D::IDENTITY);
+ }
+}
+
#[test]
fn replaced_attributes_canvas_defaults_and_image_button_share_resource_free_sizing() {
let source = Source(vec![
diff --git a/moli-paint/src/raster/mod.rs b/moli-paint/src/raster/mod.rs
index e0d8e1394..fcb153824 100644
--- a/moli-paint/src/raster/mod.rs
+++ b/moli-paint/src/raster/mod.rs
@@ -689,16 +689,10 @@ fn paint_image(
let Some(resource) = snapshot.image(image.image) else {
return;
};
- let destination = image.destination;
- 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
- || resource.image.width == 0
- || resource.image.height == 0
- {
+ let Some(destination) = pixel_snapped_image_destination(image.destination) else {
+ return;
+ };
+ if resource.image.width == 0 || resource.image.height == 0 {
return;
}
let quality = match image.sampling {
@@ -741,17 +735,11 @@ fn paint_svg_image(
let Some(resource) = snapshot.svg_image(image.image) else {
return;
};
- let destination = image.destination;
+ let Some(destination) = pixel_snapped_image_destination(image.destination) else {
+ return;
+ };
let tree_size = resource.image.tree().size();
- 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
- || tree_size.width() <= 0.0
- || tree_size.height() <= 0.0
- {
+ if tree_size.width() <= 0.0 || tree_size.height() <= 0.0 {
return;
}
let image_to_destination =
@@ -774,6 +762,47 @@ 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()
+}
+
fn paint_border(
scene: &mut impl PaintScene,
rect: PaintRect,
@@ -2340,6 +2369,46 @@ mod tests {
assert_eq!(Arc::strong_count(&svg), 1);
}
+ #[test]
+ fn fractional_svg_image_rows_share_pixel_snapped_boundaries() {
+ let svg = Arc::new(
+ moli_image::decode_svg_image(
+ br##"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 96 12"><rect width="96" height="12" fill="#008000"/></svg>"##,
+ )
+ .expect("fixture SVG should parse"),
+ );
+ let mut snapshot = PaintSnapshot::new(
+ PaintViewport::new(100, 101, 1.0),
+ PaintColor::new(1.0, 0.0, 0.0, 1.0),
+ );
+ let image = snapshot.add_svg_image(svg);
+ for row in 0..8 {
+ snapshot.push_fragment(PaintFragment::SvgImage(PaintSvgImage {
+ image,
+ destination: PaintRect::new(0.0, row as f32 * 12.5, 100.0, 12.5),
+ transform: PaintTransform2D::IDENTITY,
+ }));
+ }
+
+ let rendered = raster_snapshot(&snapshot).expect("SVG rows should rasterize");
+ for y in 0..100 {
+ for x in 0..100 {
+ assert_eq!(
+ pixel(&rendered, x, y),
+ [0, 128, 0, 255],
+ "unexpected image coverage at ({x}, {y})"
+ );
+ }
+ }
+ for x in 0..100 {
+ assert_eq!(
+ pixel(&rendered, x, 100),
+ [255, 0, 0, 255],
+ "SVG content escaped its snapped destination at ({x}, 100)"
+ );
+ }
+ }
+
#[test]
fn missing_snapshot_image_resource_is_rejected_before_backend_creation() {
let mut snapshot = snapshot(1, 1, 1.0);