Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust
Rust ai-agentsai-toolsbrowserbrowser-automationcloud-browserheadlessheadless-browserkitesurfplaywrightpuppeteerrustservoweb-crawlerweb-crawlingweb-scraperweb-scraping
fix(paint): cover large repeated raster backgrounds
ldm0b3d0d5231a39
diff --git a/moli-layout/src/paint/background.rs b/moli-layout/src/paint/background.rsindex 8fbac447f..065d34853 100644--- a/moli-layout/src/paint/background.rs+++ b/moli-layout/src/paint/background.rs@@ -409,6 +409,42 @@ fn background_tiles_with_mode(Some(tiles)}+/// Continuous raster tiling can be encoded as one bounded image brush.+/// Keep the existing explicit-tile path for gaps, one-axis repetition, and SVG.+fn continuous_background_tile(+ areas: BoxAreas,+ layer: &ImageLayerStyles<'_>,+ mode: BackgroundSizeComputeMode,+) -> Option<(LayoutRect, LayoutRect)> {+ use BackgroundRepeatKeyword::{Repeat, Round};++ let BackgroundRepeat(repeat_x, repeat_y) = *layer.repeat;+ if !matches!(repeat_x, Repeat | Round) || !matches!(repeat_y, Repeat | Round) {+ return None;+ }+ let origin = areas.rect(layer.origin);+ let (position, size) =+ compute_layer_position_and_size(layer, origin.width, origin.height, mode);+ let tile = LayoutRect::new(+ origin.x + position.x,+ origin.y + position.y,+ size.width,+ size.height,+ );+ let bounds = larger_clip_area(areas, layer.clip, layer.origin).unwrap_or(origin);+ if [tile, bounds].iter().any(|rect| {+ !rect.x.is_finite()+ || !rect.y.is_finite()+ || !rect.width.is_finite()+ || !rect.height.is_finite()+ || rect.width <= f32::EPSILON+ || rect.height <= f32::EPSILON+ }) {+ return None;+ }+ Some((tile, bounds))+}+pub(super) fn project_url_image_layer<N>(layout_box: &LayoutBox<N>,layer: &ImageLayerStyles<'_>,@@ -445,24 +481,32 @@ pub(super) fn project_url_image_layer<N>(else {return;};- let Some(tiles) = background_tiles_with_mode(- areas,- layer,- BackgroundSizeComputeMode::Size(object_width, object_height),- ) else {- push_diagnostic_once(- snapshot,- kind.repeat_budget_code(),- format!(- "{} exceeds the per-layer 500 tile software-paint budget",- layout_box.source_label- ),- );- return;+ let mode = BackgroundSizeComputeMode::Size(object_width, object_height);+ let repeated = if kind == CssImageLayerKind::Background && resource.pixels.is_some() {+ continuous_background_tile(areas, layer, mode)+ } else {+ None+ };+ let tiles = if repeated.is_some() {+ // No allocation or work proportional to the number of repetitions.+ Vec::new()+ } else {+ let Some(tiles) = background_tiles_with_mode(areas, layer, mode) else {+ push_diagnostic_once(+ snapshot,+ kind.repeat_budget_code(),+ format!(+ "{} exceeds the per-layer 500 tile software-paint budget",+ layout_box.source_label+ ),+ );+ return;+ };+ if tiles.is_empty() {+ return;+ }+ tiles};- if tiles.is_empty() {- return;- }if push_clip {let Some(clip_shape) = paint_space.pixel_snapped_box_shape(clip_shape) else {@@ -484,13 +528,24 @@ pub(super) fn project_url_image_layer<N>(}},);- for destination in tiles {+ if let Some((destination, bounds)) = repeated {snapshot.push_fragment(PaintFragment::Image(PaintImage {image,destination: paint_space.pre_transform_rect(destination),+ repeat_bounds: Some(paint_space.pre_transform_rect(bounds)),sampling,transform: paint_space.property_transform(),}));+ } else {+ for destination in tiles {+ snapshot.push_fragment(PaintFragment::Image(PaintImage {+ image,+ destination: paint_space.pre_transform_rect(destination),+ repeat_bounds: None,+ sampling,+ transform: paint_space.property_transform(),+ }));+ }}} else if let Some(svg) = resource.svg.clone() {let image = snapshot.add_svg_image(svg);diff --git a/moli-layout/src/paint/image.rs b/moli-layout/src/paint/image.rsindex 863c3c5a9..fabc952d3 100644--- a/moli-layout/src/paint/image.rs+++ b/moli-layout/src/paint/image.rs@@ -139,6 +139,7 @@ pub(super) fn project_replaced_image<N>(snapshot.push_fragment(PaintFragment::Image(PaintImage {image,destination,+ repeat_bounds: None,sampling,transform: image_transform,}));diff --git a/moli-layout/src/snapshot.rs b/moli-layout/src/snapshot.rsindex ad8f24fd9..832e43c27 100644--- a/moli-layout/src/snapshot.rs+++ b/moli-layout/src/snapshot.rs@@ -583,7 +583,12 @@ pub enum PaintImageSampling {#[derive(Clone, Debug, PartialEq)]pub struct PaintImage {pub image: PaintImageId,+ /// One image tile, before the property transform.pub destination: PaintRect,+ /// When present, repeat the tile continuously on both axes inside these+ /// finite bounds, in the same coordinate space as `destination`.+ /// The tile phase and size stay fractional; only the coverage is snapped.+ pub repeat_bounds: Option<PaintRect>,pub sampling: PaintImageSampling,pub transform: PaintTransform2D,}diff --git a/moli-paint/src/pdf/primitives.rs b/moli-paint/src/pdf/primitives.rsindex 83a2c5dd0..be8085f28 100644--- a/moli-paint/src/pdf/primitives.rs+++ b/moli-paint/src/pdf/primitives.rs@@ -216,6 +216,11 @@ impl<'a, 's> PdfPainter<'a, 's> {self.clips.pop();self.clip_shapes.pop();}+ PaintFragment::Image(image) if image.repeat_bounds.is_some() => {+ // PDF's native image command draws one tile. Reuse the bounded+ // raster fallback for a repeated brush without expanding tiles.+ self.rasterize(std::slice::from_ref(fragment))?;+ }PaintFragment::Image(image) => {let resource = self.snapshot.image(image.image).expect("validated image");let interpolate = image.sampling == moli_layout::PaintImageSampling::Linear;@@ -492,7 +497,10 @@ fn fragment_bounds(fragment: &PaintFragment) -> Option<Rect> {clip, transform, ..} => (super::rect(clip.bounds()), *transform),PaintFragment::SvgImage(image) => (super::rect(image.destination), image.transform),- PaintFragment::Image(image) => (super::rect(image.destination), image.transform),+ PaintFragment::Image(image) => (+ super::rect(image.repeat_bounds.unwrap_or(image.destination)),+ image.transform,+ ),PaintFragment::Border {rect, transform, ..} => (super::rect(*rect), *transform),diff --git a/moli-paint/src/pdf/tests.rs b/moli-paint/src/pdf/tests.rsindex f20540b27..5d2df357b 100644--- a/moli-paint/src/pdf/tests.rs+++ b/moli-paint/src/pdf/tests.rs@@ -397,3 +397,63 @@ fn native_path_fill_rules_reach_pdf_vector_operators() {}}}++#[test]+fn repeated_images_fill_the_clipped_pdf_region() {+ let mut snapshot = snapshot();+ let image = snapshot.add_image(Arc::new(+ moli_image::RgbaImage::try_new(2, 1, vec![255, 0, 0, 255, 0, 255, 0, 255]).unwrap(),+ ));+ snapshot.push_fragment(PaintFragment::push_clip(PaintRect::new(+ 12.0, 10.0, 32.0, 16.0,+ )));+ snapshot.push_fragment(PaintFragment::Image(moli_layout::PaintImage {+ image,+ destination: PaintRect::new(8.0, 8.0, 2.0, 1.0),+ repeat_bounds: Some(PaintRect::new(8.0, 8.0, 40.0, 20.0)),+ sampling: moli_layout::PaintImageSampling::Nearest,+ transform: PaintTransform2D::IDENTITY,+ }));+ snapshot.push_fragment(PaintFragment::PopLayer);+ let doc = document(&snapshot, &options());+ let repeated_images: Vec<_> = doc+ .objects+ .values()+ .filter_map(|object| object.as_stream().ok())+ .filter(|stream| {+ stream.dict.get(b"Subtype").and_then(|v| v.as_name()).ok() == Some(b"Image")+ && stream.dict.get(b"Width").and_then(|v| v.as_i64()).ok() == Some(64)+ && stream.dict.get(b"Height").and_then(|v| v.as_i64()).ok() == Some(32)+ })+ .map(|stream| stream.decompressed_content().expect("PDF image bytes"))+ .filter(|bytes| bytes.len() == 64 * 32 * 3)+ .collect();+ assert_eq!(repeated_images.len(), 1, "one bounded RGB image in the PDF");+ for (index, pixel) in repeated_images[0].chunks_exact(3).enumerate() {+ let expected = if ((index % 64) / 2).is_multiple_of(2) {+ [255, 0, 0]+ } else {+ [0, 255, 0]+ };+ assert_eq!(pixel, expected, "PDF pattern at pixel {index}");+ }+}++#[test]+fn pdf_rejects_nonfinite_image_repeat_bounds() {+ let mut snapshot = snapshot();+ let image = snapshot.add_image(Arc::new(+ moli_image::RgbaImage::try_new(1, 1, vec![255; 4]).unwrap(),+ ));+ snapshot.push_fragment(PaintFragment::Image(moli_layout::PaintImage {+ image,+ destination: PaintRect::new(0.0, 0.0, 1.0, 1.0),+ repeat_bounds: Some(PaintRect::new(0.0, 0.0, f32::NAN, 20.0)),+ sampling: moli_layout::PaintImageSampling::Nearest,+ transform: PaintTransform2D::IDENTITY,+ }));+ assert!(matches!(+ pdf_snapshot(&snapshot, &options()),+ Err(PdfError::Encoding(_))+ ));+}diff --git a/moli-paint/src/pdf/validation.rs b/moli-paint/src/pdf/validation.rsindex d421c3108..15f7c551d 100644--- a/moli-paint/src/pdf/validation.rs+++ b/moli-paint/src/pdf/validation.rs@@ -82,7 +82,10 @@ pub(super) fn validate(snapshot: &PaintSnapshot) -> Result<(), PdfError> {glyphs(&shadow.run) && point(shadow.offset) && shadow.blur_radius.is_finite(),shadow.run.transform,),- PaintFragment::Image(image) => (rect(image.destination), image.transform),+ PaintFragment::Image(image) => (+ rect(image.destination) && image.repeat_bounds.is_none_or(rect),+ image.transform,+ ),PaintFragment::SvgImage(image) => (rect(image.destination), image.transform),PaintFragment::PopLayer => continue,};diff --git a/moli-paint/src/raster/tests.rs b/moli-paint/src/raster/tests.rsindex b75de7bb3..b71c44578 100644--- a/moli-paint/src/raster/tests.rs+++ b/moli-paint/src/raster/tests.rs@@ -188,6 +188,7 @@ fn snapshot_image_resource_rasterizes_without_copying_the_owned_pixels() {snapshot.push_fragment(PaintFragment::Image(PaintImage {image,destination: PaintRect::new(0.0, 0.0, 4.0, 2.0),+ repeat_bounds: None,sampling: PaintImageSampling::Nearest,transform: PaintTransform2D::IDENTITY,}));@@ -206,6 +207,31 @@ fn snapshot_image_resource_rasterizes_without_copying_the_owned_pixels() {);}+#[test]+fn repeated_snapshot_image_preserves_fractional_period_and_finite_bounds() {+ let mut snapshot = snapshot(24, 8, 1.0);+ let image = snapshot.add_image(Arc::new(+ moli_image::RgbaImage::try_new(2, 1, vec![255, 0, 0, 255, 0, 255, 0, 255]).unwrap(),+ ));+ snapshot.push_fragment(PaintFragment::Image(PaintImage {+ image,+ destination: PaintRect::new(-0.5, 0.0, 3.5, 2.0),+ repeat_bounds: Some(PaintRect::new(0.0, 0.0, 21.0, 6.0)),+ sampling: PaintImageSampling::Nearest,+ transform: PaintTransform2D::IDENTITY,+ }));+ let rendered = raster_snapshot(&snapshot).expect("fractional repeated image");+ for x in [0, 3, 7, 10, 14, 17] {+ assert_eq!(pixel(&rendered, x, 1), [255, 0, 0, 255], "red at {x}");+ }+ for x in [1, 2, 5, 8, 9, 12, 15, 16, 19] {+ assert_eq!(pixel(&rendered, x, 1), [0, 255, 0, 255], "green at {x}");+ }+ assert_eq!(pixel(&rendered, 21, 1), [255; 4]);+ assert_eq!(pixel(&rendered, 1, 6), [255; 4]);+ assert_eq!(snapshot.fragments.len(), 1);+}+#[test]fn snapshot_svg_resource_rasterizes_at_its_resolved_destination_size() {let svg = Arc::new(@@ -276,6 +302,7 @@ fn missing_snapshot_image_resource_is_rejected_before_backend_creation() {snapshot.push_fragment(PaintFragment::Image(PaintImage {image: moli_layout::PaintImageId::from_index(0),destination: PaintRect::new(0.0, 0.0, 1.0, 1.0),+ repeat_bounds: None,sampling: PaintImageSampling::Linear,transform: PaintTransform2D::IDENTITY,}));diff --git a/moli-paint/src/scene/image.rs b/moli-paint/src/scene/image.rsindex 7a307697d..56fc4d20d 100644--- a/moli-paint/src/scene/image.rs+++ b/moli-paint/src/scene/image.rs@@ -9,14 +9,15 @@//! Raster resource and parsed SVG commands with shared destination geometry.-use crate::geometry::device_transform;+use crate::geometry::{device_transform, to_backend_rect};use anyrender::PaintScene;use moli_layout::{PaintImage, PaintImageSampling, PaintRect, PaintSnapshot, PaintSvgImage, pixel_snap_paint_rect,};use peniko::kurbo::Affine;use peniko::{- Blob, Extend, ImageAlphaType, ImageBrush, ImageData, ImageFormat, ImageQuality, ImageSampler,+ Blob, Extend, Fill, ImageAlphaType, ImageBrush, ImageData, ImageFormat, ImageQuality,+ ImageSampler,};pub(super) fn paint_image(@@ -28,8 +29,18 @@ pub(super) fn paint_image(let Some(resource) = snapshot.image(image.image) else {return;};- let Some(destination) = pixel_snapped_image_destination(image.destination) else {- return;+ let destination = if image.repeat_bounds.is_some() {+ // Snapping one tile would change its period and accumulate phase error+ // over the fill. Only the finite fill bounds use box pixel snapping.+ if to_backend_rect(image.destination).is_none() {+ return;+ }+ image.destination+ } else {+ let Some(destination) = pixel_snapped_image_destination(image.destination) else {+ return;+ };+ destination};if resource.image.width == 0 || resource.image.height == 0 {return;@@ -38,6 +49,11 @@ pub(super) fn paint_image(PaintImageSampling::Nearest => ImageQuality::Low,PaintImageSampling::Linear => ImageQuality::Medium,};+ let extend = if image.repeat_bounds.is_some() {+ Extend::Repeat+ } else {+ Extend::Pad+ };let brush = ImageBrush {image: ImageData {data: Blob::new(resource.image.clone()),@@ -47,8 +63,8 @@ pub(super) fn paint_image(height: resource.image.height,},sampler: ImageSampler {- x_extend: Extend::Pad,- y_extend: Extend::Pad,+ x_extend: extend,+ y_extend: extend,quality,alpha: 1.0,},@@ -59,10 +75,23 @@ pub(super) fn paint_image(f64::from(destination.width) / f64::from(resource.image.width),f64::from(destination.height) / f64::from(resource.image.height),);- scene.draw_image(- brush.as_ref(),- device_transform(image.transform, scale) * image_to_destination,- );+ if let Some(bounds) = image.repeat_bounds {+ let Some(bounds) = pixel_snap_paint_rect(bounds).and_then(to_backend_rect) else {+ return;+ };+ scene.fill(+ Fill::NonZero,+ device_transform(image.transform, scale),+ brush.as_ref(),+ Some(image_to_destination),+ &bounds,+ );+ } else {+ scene.draw_image(+ brush.as_ref(),+ device_transform(image.transform, scale) * image_to_destination,+ );+ }}pub(super) fn paint_svg_image(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.rsindex 9c7df8309..fe9fbc268 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@@ -1,5 +1,6 @@use super::*;+mod image_repeat;mod planar_transforms;mod print;mod transform_precision;diff --git a/moli-renderer-v8/src/runtime/page_vm/tests/rendering_update/image_repeat.rs b/moli-renderer-v8/src/runtime/page_vm/tests/rendering_update/image_repeat.rsnew file mode 100644index 000000000..a194d82db--- /dev/null+++ b/moli-renderer-v8/src/runtime/page_vm/tests/rendering_update/image_repeat.rs@@ -0,0 +1,150 @@+use super::*;++async fn ready_background_snapshot(+ pixels: moli_image::RgbaImage,+ css: &'static str,+ markup: &'static str,+) -> anyhow::Result<(moli_layout::PaintSnapshot, serde_json::Value)> {+ run_page_vm_async_test(async move {+ let encoded = moli_image::encode_png(&pixels)?;+ let image_url = format!(+ "data:image/png;base64,{}",+ base64::engine::general_purpose::STANDARD.encode(encoded.bytes),+ );+ let loader = crate::network::ResourceRequestClient::new(&FetchConfig::default())?;+ loader.set_optional_resource_fetch_mask(+ crate::protocol_types::OptionalResourceFetchMask::IMAGE,+ );+ let mut page = test_page_vm_with_loader_and_document_url(+ &loader,+ Vec::new(),+ Url::parse("https://example.com/raster-background-repeat.html")?,+ );+ page.vm_mut()+ .set_layout_policy(moli_page_types::LayoutPolicy::OnDemand);+ let executor = page.local_executor.clone();+ executor+ .run(async move {+ let css = css.replace("__IMAGE_URL__", &image_url);+ page.vm_mut().eval(&format!(+ "document.head.innerHTML='<style id=fixture></style>';document.getElementById('fixture').textContent={};document.body.innerHTML={};'installed'",+ serde_json::to_string(&css)?,+ serde_json::to_string(markup)?,+ ))?;+ page.vm_mut().sync_live_document_style_sources();+ let viewport = moli_layout::PaintViewport::new(96, 80, 1.0);+ // Establish readiness independently of the projection assertion.+ // This is an ordinary OnDemand screen paint, with no Print job.+ page.vm_mut()+ .screenshot_layout_snapshot(viewport)?+ .expect("image fixture has a layout root");+ let completion = page.vm().css_image_completion_notify_for_test();+ tokio::time::timeout(std::time::Duration::from_secs(3), async {+ loop {+ let notified = completion.notified();+ if page.vm().css_image_resource_is_ready_for_test(&image_url) {+ break;+ }+ notified.await;+ }+ })+ .await?;+ let snapshot = page+ .vm_mut()+ .screenshot_layout_snapshot(viewport)?+ .expect("ready image fixture has a layout root");+ let geometry = page.vm_mut().eval(+ "JSON.stringify((()=>{const r=document.getElementById('asset').getBoundingClientRect();return [r.x,r.y,r.width,r.height]})())",+ )?;+ Ok((snapshot, serde_json::from_str(&geometry)?))+ })+ .await+ })+ .await+}++fn image_pixel(image: &moli_paint::RasterImage, x: u32, y: u32) -> [u8; 4] {+ let offset = ((y * image.width + x) * 4) as usize;+ image.rgba[offset..offset + 4].try_into().unwrap()+}++fn assert_one_repeat_image(snapshot: &moli_layout::PaintSnapshot) {+ assert_eq!(+ snapshot+ .fragments+ .iter()+ .filter(|fragment| matches!(fragment, moli_layout::PaintFragment::Image(_)))+ .count(),+ 1,+ "continuous raster repetition must have bounded paint work",+ );+ assert!(snapshot.diagnostics.iter().all(|diagnostic| {+ diagnostic.code != "background-repeat-budget-exceeded"+ && diagnostic.code != "background-image-resource-unavailable"+ }));+}++#[tokio::test]+async fn raster_url_background_repeats_beyond_the_explicit_tile_budget() {+ let (snapshot, geometry) = ready_background_snapshot(+ moli_image::RgbaImage::try_new(1, 1, vec![17, 85, 221, 255]).unwrap(),+ r#"+html,body{margin:0;padding:0;background:white;scrollbar-width:none}+#asset{position:absolute;left:8px;top:8px;width:40px;height:20px;+background:magenta url("__IMAGE_URL__")}+"#,+ "<div id=asset></div>",+ )+ .await+ .expect("ready 1x1 background fixture");+ assert_eq!(geometry, serde_json::json!([8, 8, 40, 20]));+ let image = moli_paint::raster_snapshot(&snapshot).expect("background raster");+ for y in 8..28 {+ for x in 8..48 {+ assert_eq!(image_pixel(&image, x, y), [17, 85, 221, 255], "({x},{y})");+ }+ }+ assert_eq!(image_pixel(&image, 7, 12), [255; 4]);+ assert_eq!(image_pixel(&image, 48, 12), [255; 4]);+ assert_eq!(image_pixel(&image, 12, 28), [255; 4]);+ assert_one_repeat_image(&snapshot);+}++#[tokio::test]+async fn raster_url_background_repeat_preserves_pattern_position_transform_clip_and_alpha() {+ let (snapshot, geometry) = ready_background_snapshot(+ moli_image::RgbaImage::try_new(+ 2,+ 2,+ vec![255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 128, 0, 0, 0, 0],+ )+ .unwrap(),+ r#"+html,body{margin:0;padding:0;background:white;scrollbar-width:none}+#clip{position:absolute;left:8px;top:8px;width:64px;height:40px;overflow:hidden}+#asset{position:absolute;left:0;top:0;width:96px;height:64px;+transform:translate(3px,5px);background-image:url("__IMAGE_URL__");+background-position:1px 1px;image-rendering:pixelated}+"#,+ "<div id=clip><div id=asset></div></div>",+ )+ .await+ .expect("ready 2x2 background fixture");+ assert_eq!(geometry, serde_json::json!([11, 13, 96, 64]));+ let image = moli_paint::raster_snapshot(&snapshot).expect("periodic background raster");+ // Tile origin is (12,14): element offset + property transform + position.+ // Sampling both near and far pixels rules out stretching one tile to fit.+ for (x, y) in [(12, 14), (26, 22), (68, 44)] {+ assert_eq!(image_pixel(&image, x, y), [255, 0, 0, 255]);+ assert_eq!(image_pixel(&image, x + 1, y), [0, 255, 0, 255]);+ let alpha = image_pixel(&image, x, y + 1);+ assert!((126..=129).contains(&alpha[0]), "{alpha:?}");+ assert!((126..=129).contains(&alpha[1]), "{alpha:?}");+ assert_eq!(&alpha[2..], &[255, 255]);+ assert_eq!(image_pixel(&image, x + 1, y + 1), [255; 4]);+ }+ for (x, y) in [(10, 20), (20, 12), (72, 20), (20, 48)] {+ assert_eq!(image_pixel(&image, x, y), [255; 4], "clip at ({x},{y})");+ }+ assert_one_repeat_image(&snapshot);+}