diff --git a/README.md b/README.md index 77e045f701d..7074692f500 100644 --- a/README.md +++ b/README.md @@ -312,6 +312,13 @@ Source lookup and hit-test candidates are derived from the frozen tree when queried. The system has no incrementally maintained layout tree, damage graph, retained display list, GPU compositor, or persistent window. +Inline SVG object geometry is collected before clipping and paint-tree +simplification, then frozen with its CSS viewport in that same layout pass. +Computed paint styles are supplied separately from the original SVG XML, so +they cannot change author selector matching or inflate the encoded-input +budget. Geometry queries read the published numeric results without reparsing +the SVG or mixing live child geometry with an older outer layout. + ## Benchmark The following measurements show Moli's current capability envelope. They cover diff --git a/moli-cdp-smoke/moli_cdp_smoke/groups/svg_rect.py b/moli-cdp-smoke/moli_cdp_smoke/groups/svg_rect.py index 4e25275179c..7d56585706f 100644 --- a/moli-cdp-smoke/moli_cdp_smoke/groups/svg_rect.py +++ b/moli-cdp-smoke/moli_cdp_smoke/groups/svg_rect.py @@ -1,9 +1,80 @@ from __future__ import annotations +import base64 from typing import Any -from ..assertions import assert_equal, record_contract -from ..config import REPO_ROOT +from ..assertions import SmokeError, assert_equal, record_contract +from ..config import REPO_ROOT, is_moli_browser +from ..diagnostics import new_cdp_session +from ..png_image import decode_png + + +async def _check_inline_svg(page: Any, results: list[dict[str, Any]]) -> None: + session = await new_cdp_session(page.context, page) + + async def capture() -> Any: + response = await session.send("Page.captureScreenshot", {"format": "png"}) + return decode_png(base64.b64decode(response["data"])) + + cases = [ + ("original_style_selector", '', [0, 0, 20, 20]), + ("original_id_selector", '', [0, 0, 20, 20]), + ("empty_clip_geometry", '', [10, 20, 30, 40]), + ("nested_visible_geometry", '', [12, 23, 30, 40]), + ] + try: + for name, content, expected in cases: + await page.evaluate("""content => { + document.head.innerHTML=''; + document.body.innerHTML=''+content+''; + }""", content) + image = await capture() + observed = await page.evaluate("""() => { + const e=document.querySelector('body>svg>svg,rect'), r=e.getBoundingClientRect(); + return {rect:[r.x,r.y,r.width,r.height], count:e.getClientRects().length}; + }""") + assert_equal(observed, {"rect": expected, "count": 1}, name) + if name.startswith("original_"): + assert_equal(image.pixel(10, 10), (255, 0, 0, 255), name + " paint") + assert_equal(image.pixel(50, 10), (255, 255, 255, 255), name + " unmatched transform") + record_contract(results, "svg/" + name, observed=observed, + contract="Final computed styles and source geometry preserve original SVG XML identity.", + source="Chromium 145.0.7632.116 executable comparison (2026-11-13)", commands=["Runtime.evaluate", "Page.captureScreenshot"]) + + await page.evaluate("""() => { + document.body.innerHTML=''+''.repeat(30000)+''; + }""") + image = await capture() + if any(channel > 2 for channel in image.pixel(0, 0)[:3]): + raise SmokeError("690 KB SVG disappeared after applying computed styles") + record_contract(results, "svg/original_source_budget", observed={"circles": 30000}, + contract="Derived styles do not inflate the bounded encoded SVG input.", + source="Chromium 145.0.7632.116 executable comparison (2026-11-13)", commands=["Page.captureScreenshot"]) + + await page.evaluate("""() => { + document.body.innerHTML=''+ + ''.repeat(1000)+''; + }""") + await capture() + count = await page.evaluate("""() => { + const r=document.createRange();r.selectNodeContents(document.querySelector('svg')); + return r.getClientRects().length; + }""") + assert_equal(count, 1000, "SVG Range geometry batch") + observed = await page.evaluate("""() => { + document.querySelector('svg').style.left='300px'; + document.querySelector('rect').setAttribute('x','30'); + return [document.querySelector('svg'),document.querySelector('rect')].map(e=>e.getBoundingClientRect().x); + }""") + assert_equal(observed, [100, 110] if is_moli_browser() else [300, 330], "coherent SVG geometry publication") + await capture() + updated = await page.evaluate("document.querySelector('rect').getBoundingClientRect().x") + assert_equal(updated, 330, "SVG geometry after publication") + record_contract(results, "svg/coherent_batch_publication", observed={"count": count, "immediate": observed, "published": updated}, + contract="SVG object and viewport coordinates come from one publication; Moli freezes ordinary queries, Chromium flushes live layout.", + source="Chromium executable comparison and Moli frozen-layout contract", commands=["Runtime.evaluate", "Page.captureScreenshot"]) + finally: + await session.detach() async def run_svg_rect_group( @@ -24,5 +95,6 @@ async def run_svg_rect_group( commands=["Runtime.evaluate"], observed=observed, ) + await _check_inline_svg(page, results) finally: await context.close() diff --git a/moli-dom/src/native/html_serialization/engine.rs b/moli-dom/src/native/html_serialization/engine.rs index 93dadc7e3bd..d4a93d0d878 100644 --- a/moli-dom/src/native/html_serialization/engine.rs +++ b/moli-dom/src/native/html_serialization/engine.rs @@ -54,7 +54,6 @@ struct HtmlSerializationOptions<'a> { // whose owner Document has different scripting state from the outer tree. scripting_enabled_for_node: &'a dyn Fn(NativeNodeId) -> bool, shadow_root_provider: Option<&'a dyn HtmlShadowRootProvider>, - attribute_overrides: Option<&'a dyn Fn(NativeNodeId) -> Vec<(String, String)>>, } impl<'a> HtmlSerializationOptions<'a> { @@ -66,7 +65,6 @@ impl<'a> HtmlSerializationOptions<'a> { target, scripting_enabled_for_node, shadow_root_provider: None, - attribute_overrides: None, } } @@ -267,9 +265,6 @@ fn serialize_html_node_frame<'a, S>( out.push('>'); } NodeData::Element(element) => { - let overrides = options - .attribute_overrides - .map(|attributes| attributes(node_id)); out.push('<'); out.push_str(element.local_name()); if let Some(is_name) = element.custom_element_is_name() @@ -283,31 +278,12 @@ fn serialize_html_node_frame<'a, S>( if out.limit_exceeded() { return; } - if overrides.as_ref().is_some_and(|attributes| { - attributes - .iter() - .any(|(name, _)| attribute.name_matches(name)) - }) { - continue; - } out.push(' '); attribute.push_html_serialized_name(|part| out.push_str(part)); out.push_str("=\""); escape_html_attribute(attribute.value(), out); out.push('"'); } - if let Some(overrides) = overrides { - for (name, value) in overrides { - if out.limit_exceeded() { - return; - } - out.push(' '); - out.push_str(&name); - out.push_str("=\""); - escape_html_attribute(&value, out); - out.push('"'); - } - } out.push('>'); if !is_void_html_element(element.namespace(), element.local_name()) { @@ -506,24 +482,18 @@ pub(super) fn serialize_html_with_limit( dom: &NativeDom, node_id: NativeNodeId, max_bytes: usize, -) -> Result, HtmlSerializationLimitExceeded> { - serialize_html_with_limit_and_attributes(dom, node_id, max_bytes, None) -} - -pub(super) fn serialize_html_with_limit_and_attributes( - dom: &NativeDom, - node_id: NativeNodeId, - max_bytes: usize, - attributes: Option<&dyn Fn(NativeNodeId) -> Vec<(String, String)>>, ) -> Result, HtmlSerializationLimitExceeded> { let scripting_enabled_for_node = |_: NativeNodeId| true; let mut out = BoundedHtmlSerialization::new(max_bytes); - let mut options = HtmlSerializationOptions::new( - HtmlSerializationTarget::IncludeNode, - &scripting_enabled_for_node, - ); - options.attribute_overrides = attributes; - if !serialize_html_into_sink(dom, node_id, options, &mut out) { + if !serialize_html_into_sink( + dom, + node_id, + HtmlSerializationOptions::new( + HtmlSerializationTarget::IncludeNode, + &scripting_enabled_for_node, + ), + &mut out, + ) { return Ok(None); } out.finish().map(Some) diff --git a/moli-dom/src/native/html_serialization/mod.rs b/moli-dom/src/native/html_serialization/mod.rs index 331b8c2cd07..fe7a953a991 100644 --- a/moli-dom/src/native/html_serialization/mod.rs +++ b/moli-dom/src/native/html_serialization/mod.rs @@ -8,7 +8,7 @@ pub(super) use engine::{ HtmlSerializationTarget, HtmlSerializedShadowRoot, escape_html_attribute_into_string, serialize_html_with_shadow_root_provider, }; -use engine::{serialize_html, serialize_html_with_limit, serialize_html_with_limit_and_attributes}; +use engine::{serialize_html, serialize_html_with_limit}; /// A bounded serialization stopped before appending bytes past its limit. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -73,18 +73,6 @@ impl NativeDom { serialize_html_with_limit(self, node_id, max_bytes) } - /// Bounded serialization for derived consumers that need resolved attributes - /// without mutating or cloning the live DOM. Replacement names must be valid - /// qualified attribute names; values are escaped by the serializer. - pub fn outer_html_with_limit_and_attributes( - &self, - node_id: NativeNodeId, - max_bytes: usize, - attributes: &dyn Fn(NativeNodeId) -> Vec<(String, String)>, - ) -> Result, HtmlSerializationLimitExceeded> { - serialize_html_with_limit_and_attributes(self, node_id, max_bytes, Some(attributes)) - } - pub fn inner_html(&self, node_id: NativeNodeId) -> Option { self.inner_html_with_scripting_enabled(node_id, true) } diff --git a/moli-dom/src/native/html_serialization/tests.rs b/moli-dom/src/native/html_serialization/tests.rs index af8b308a6fe..4bfb450e992 100644 --- a/moli-dom/src/native/html_serialization/tests.rs +++ b/moli-dom/src/native/html_serialization/tests.rs @@ -9,44 +9,6 @@ fn scripting_enabled(_: NativeNodeId) -> bool { true } -#[test] -fn bounded_attribute_projection_preserves_live_dom_and_escapes_values() { - let mut dom = NativeDom::new_html(test_url()); - let root = dom.create_element("div"); - let child = dom.create_element("span"); - dom.set_attribute(root, "style", "color:red"); - dom.append_child(root, child); - let original = dom.outer_html(root).unwrap(); - let attributes = |node| { - if node == root { - vec![("style".into(), "font-family:\"A&B\"".into())] - } else { - vec![("id".into(), "derived".into())] - } - }; - let projected = dom - .outer_html_with_limit_and_attributes(root, 512, &attributes) - .unwrap() - .unwrap(); - assert_eq!( - projected, - "
" - ); - assert_eq!(dom.outer_html(root).unwrap(), original); - assert_eq!( - dom.outer_html_with_limit_and_attributes(root, projected.len(), &attributes) - .unwrap() - .unwrap(), - projected - ); - assert_eq!( - dom.outer_html_with_limit_and_attributes(root, projected.len() - 1, &attributes), - Err(HtmlSerializationLimitExceeded { - max_bytes: projected.len() - 1 - }) - ); -} - #[test] fn template_contents_require_the_exact_html_element_identity() { for (namespace, name, is_template) in [ diff --git a/moli-renderer-v8/src/layout_renderer/inline_svg.rs b/moli-renderer-v8/src/layout_renderer/inline_svg.rs index 9b524ec20c1..4e4d019fbb4 100644 --- a/moli-renderer-v8/src/layout_renderer/inline_svg.rs +++ b/moli-renderer-v8/src/layout_renderer/inline_svg.rs @@ -1,15 +1,19 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // // This is a narrow port of Blitz's inline-SVG replaced-element bridge. The -// live SVG subtree remains owned by NativeDom; a fresh paint pass serializes -// it into one bounded, immutable `usvg::Tree`. No SVG child layout tree or -// cross-pass resource cache is retained here. +// live SVG subtree remains owned by NativeDom; a layout pass serializes its +// original XML into one bounded, immutable `usvg::Tree`. Only numeric source +// geometry survives with the outer frozen layout; paint retains the image. // // The isolated tree also needs document CSS: sample the computed SVG paint -// and text inputs while serializing, without changing the live DOM. Geometry -// queries use the same decoder and font shaping as paint. +// and text inputs separately, after matching selectors on original attributes. +// Geometry and paint share one decode and the same font shaping. -use std::{cell::RefCell, collections::HashSet, sync::Arc}; +use std::{ + cell::RefCell, + collections::{HashMap, HashSet}, + sync::Arc, +}; use moli_layout::{LayoutImageResource, PaintColor, ReplacedMetrics, ResolvedLayoutStyle}; use style::color::ColorSpace; @@ -40,48 +44,44 @@ pub(super) fn replaced_metrics(element: &Element) -> ReplacedMetrics { } } -pub(super) fn replaced_resource( - runtime: &PageScriptHost, - node: DomHandle, - style: &ResolvedLayoutStyle, - reads: &RefCell>, -) -> Option { - let svg = Arc::new(parse_live_svg(runtime, node, style, reads, None)?); - // Inline SVG box sizing comes from Stylo's width/height presentation - // hints. The vector object's own dimensions must use the same resolved - // root font context, so use the parsed tree size rather than the - // context-free metadata probe (which deliberately cannot resolve `em`). - let tree_size = svg.tree().size(); - Some(LayoutImageResource { - intrinsic_width: tree_size.width(), - intrinsic_height: tree_size.height(), - pixels: None, - svg: Some(svg), - }) +#[cfg(test)] +thread_local! { static PARSE_COUNT: std::cell::Cell = const { std::cell::Cell::new(0) }; } + +#[cfg(test)] +pub(crate) fn parse_count() -> usize { + PARSE_COUNT.with(std::cell::Cell::get) } -pub(super) struct GeometryTarget<'a> { - pub node: DomHandle, - pub id: &'a str, - pub viewport: moli_layout::LayoutSize, -} - -pub(super) fn parse_live_svg( +pub(super) fn layout_content( runtime: &PageScriptHost, root: DomHandle, root_style: &ResolvedLayoutStyle, + viewport: moli_layout::LayoutSize, reads: &RefCell>, - geometry: Option>, -) -> Option { + paint: bool, +) -> Option> { + if viewport.width <= 0.0 || viewport.height <= 0.0 { + return None; + } let host = runtime.dom_host(); + // Admit the original XML, before adding any embedding information. + let source = host + .dom() + .outer_html_with_limit( + root, + moli_image::MAX_ENCODED_SVG_BYTES + .saturating_sub(SERIALIZED_SOURCE_FIXED_INJECTION_RESERVE), + ) + .ok() + .flatten()?; + let source = prepare_source(source)?; + let mut elements = Vec::new(); + let mut pending = vec![(root, None)]; let mut referenced_ids = HashSet::new(); - let mut pending = vec![root]; - while let Some(node) = pending.pop() { - if let Some(element) = host.node(node).and_then(|node| node.as_element()) - && element.is_svg_element("use") - && let Some(id) = element - .attribute("href") - .or_else(|| { + while let Some((node, parent)) = pending.pop() { + let parent = if let Some(element) = host.node(node).and_then(|node| node.as_element()) { + if element.is_svg_element("use") { + let href = element.attribute("href").or_else(|| { element .attributes() .iter() @@ -90,63 +90,60 @@ pub(super) fn parse_live_svg( && attribute.local_name() == "href" }) .map(|attribute| attribute.value()) - }) - .and_then(|href| href.strip_prefix('#')) - { - referenced_ids.insert(id); - } - pending.extend(host.dom().child_ids(node)); - } - let attributes = |node| { - let mut attributes = Vec::new(); - let Some(element) = host.node(node).and_then(|node| node.as_element()) else { - return attributes; + }); + if let Some(id) = href.and_then(|href| href.strip_prefix('#')) { + referenced_ids.insert(id); + } + } + let index = elements.len(); + elements.push((node, parent)); + Some(index) + } else { + parent }; - if element.namespace() != "http://www.w3.org/2000/svg" { - return attributes; - } - if let Some(geometry) = geometry.as_ref() - && node == geometry.node - && element.attribute("id").is_none_or(str::is_empty) - { - attributes.push(("id".into(), geometry.id.into())); - } - // A referenced definition inherits at its instance, not at its - // original DOM position. This also applies to references outside - // . Preserve their authored inheritance instead of freezing it. - let mut parent = Some(node); - while let Some(ancestor) = parent { - if host - .node(ancestor) - .and_then(|node| node.as_element()) - .is_some_and(|element| { - element.is_svg_element("defs") - || (ancestor != root - && element - .attribute("id") - .is_some_and(|id| referenced_ids.contains(id))) - }) - { - return attributes; - } - if ancestor == root { - break; - } - parent = host.dom().parent_node(ancestor); + pending.extend( + host.dom() + .child_ids(node) + .collect::>() + .into_iter() + .rev() + .map(|node| (node, parent)), + ); + } + let mut profiles = HashMap::::new(); + let mut styles = Vec::with_capacity(elements.len()); + let mut referenced_scope = vec![false; elements.len()]; + for (index, (node, parent)) in elements.iter().copied().enumerate() { + let element = host + .node(node) + .and_then(|node| node.as_element()) + .expect("serialized SVG element"); + referenced_scope[index] = index != 0 + && (parent.is_some_and(|parent| referenced_scope[parent]) + || element.is_svg_element("defs") + || element + .attribute("id") + .is_some_and(|id| referenced_ids.contains(id))); + if referenced_scope[index] || element.namespace() != "http://www.w3.org/2000/svg" { + styles.push(None); + continue; } let mut declarations = if node == root { - let mut declarations = computed_root_declarations(root_style); - // The CSS replaced-element box applies the outer SVG transform. - // Reapplying it inside the vector resource would transform both - // paint and client geometry twice. Descendant SVG transforms stay. + let mut declarations = computed_svg_declarations(root_style); + // The outer CSS box already owns its transform and opacity. append_serialized_declaration(&mut declarations, "transform", "none"); + append_serialized_declaration(&mut declarations, "opacity", "1"); + for (name, value) in [("width", viewport.width), ("height", viewport.height)] { + append_serialized_declaration(&mut declarations, name, &format!("{value}px")); + } declarations } else { let Some(computed) = reads.borrow_mut().read(node).computed_values() else { - return attributes; + styles.push(None); + continue; }; let style = ResolvedLayoutStyle::from_stylo(computed); - let mut declarations = computed_root_declarations(&style); + let mut declarations = computed_svg_declarations(&style); let computed = style.stylo_computed_values().expect("resolved SVG style"); for (name, value) in [ ("display", computed.clone_display().to_css_string()), @@ -158,87 +155,72 @@ pub(super) fn parse_live_svg( } declarations }; - if let Some(geometry) = geometry.as_ref() - && node == root - { - for (name, value) in [ - ("width", geometry.viewport.width), - ("height", geometry.viewport.height), - ] { - attributes.push((name.into(), value.to_string())); - append_serialized_declaration(&mut declarations, name, &format!("{value}px")); - } + if let Some(profile) = profiles.get(&declarations) { + styles.push(Some(profile.clone())); + } else { + let properties = + moli_css_parse::parse_declaration_list(&declarations, Default::default()) + .into_iter() + .map(|property| { + moli_image::SvgStyleProperty::new(property.name, &property.value) + }) + .collect::>(); + let profile: moli_image::SvgElementStyle = Arc::from(properties); + profiles.insert(std::mem::take(&mut declarations), profile.clone()); + styles.push(Some(profile)); } - let declarations = merge_computed_declarations( - element.attribute("style").unwrap_or_default(), - &declarations, - ); - attributes.push(("style".into(), declarations)); - attributes - }; - let source_limit = - moli_image::MAX_ENCODED_SVG_BYTES.saturating_sub(SERIALIZED_SOURCE_FIXED_INJECTION_RESERVE); - let source = - match host - .dom() - .outer_html_with_limit_and_attributes(root, source_limit, &attributes) - { - Ok(Some(source)) => source, - Ok(None) => return None, - Err(error) => { - tracing::debug!( - node = root.index(), - error = ?error, - "fresh inline SVG serialization exceeded its input budget" - ); - return None; - } - }; - let Some(source) = prepare_source(source) else { - tracing::debug!( - node = root.index(), - "inline SVG serialization did not produce an SVG root" - ); - return None; - }; - match moli_image::decode_svg_image(source.as_bytes()) { - Ok(svg) => Some(svg), + } + #[cfg(test)] + PARSE_COUNT.with(|count| count.set(count.get() + 1)); + let scene = match moli_image::decode_inline_svg_scene( + source.as_bytes(), + &styles, + (viewport.width, viewport.height), + ) { + Ok(scene) => scene, Err(error) => { tracing::debug!( node = root.index(), - error = ?error, - "fresh inline SVG resource parse failed" + ?error, + "inline SVG scene decode failed" ); - None + return None; } - } -} - -fn merge_computed_declarations(authored: &str, computed: &str) -> String { - // usvg's simplecss parser stops at an empty declaration and gives the - // first !important declaration precedence. Normalize authored CSS and - // remove the properties whose final values have already been sampled. - let options = moli_css_parse::DeclarationParseOptions::default(); - let computed = moli_css_parse::parse_declaration_list(computed, options); - let mut declarations = String::new(); - for property in moli_css_parse::parse_declaration_list(authored, options) { - if !computed - .iter() - .any(|projected| projected.name.eq_ignore_ascii_case(&property.name)) - { - declarations.push_str(&property.name); - declarations.push(':'); - declarations.push_str(&property.value); - if property.important { - declarations.push_str(" !important"); + }; + let objects = scene + .objects + .into_iter() + .filter_map(|geometry| { + if geometry.element_index == 0 { + return None; } - declarations.push(';'); + let (source, _) = *elements.get(geometry.element_index)?; + let [x, y, width, height] = geometry.bounds; + let [a, b, c, d, e, f] = geometry.transform; + let map = |x, y| moli_layout::LayoutPoint::new(a * x + c * y + e, b * x + d * y + f); + Some(( + source, + moli_layout::LayoutQuad { + points: [ + map(x, y), + map(x + width, y), + map(x + width, y + height), + map(x, y + height), + ], + }, + )) + }) + .collect(); + let image = paint.then(|| { + let size = scene.image.tree().size(); + LayoutImageResource { + intrinsic_width: size.width(), + intrinsic_height: size.height(), + pixels: None, + svg: Some(Arc::new(scene.image)), } - } - for property in computed { - append_serialized_declaration(&mut declarations, &property.name, &property.value); - } - declarations + }); + Some(moli_layout::LayoutSvgContent { image, objects }) } fn prepare_source(mut source: String) -> Option { @@ -267,7 +249,7 @@ fn prepare_source(mut source: String) -> Option { Some(source) } -fn computed_root_declarations(style: &ResolvedLayoutStyle) -> String { +fn computed_svg_declarations(style: &ResolvedLayoutStyle) -> String { let mut declarations = inherited_context_declarations(style.current_color(), style.font_size()); let Some(computed) = style.stylo_computed_values() else { return declarations; @@ -276,8 +258,8 @@ fn computed_root_declarations(style: &ResolvedLayoutStyle) -> String { // Blink paints every SVG LayoutObject from its ComputedStyle. Moli's // bounded usvg bridge instead serializes the live subtree, so document // stylesheets are no longer present when usvg reparses it. Snapshot the - // root's inherited SVG paint group into that isolated document. Child - // declarations still override inherited values normally. + // element's computed paint group into the isolated scene as final values, + // without changing the XML that author selectors match. let current_color = computed.clone_color(); append_svg_paint( &mut declarations, @@ -342,7 +324,7 @@ fn computed_root_declarations(style: &ResolvedLayoutStyle) -> String { append_serialized_declaration( &mut declarations, "font-family", - // Attribute projection escapes quoted family names at serialization. + // Kept out of XML attributes, including quoted family names. &computed.clone_font_family().to_css_string(), ); append_serialized_declaration( diff --git a/moli-renderer-v8/src/layout_renderer/mod.rs b/moli-renderer-v8/src/layout_renderer/mod.rs index c7027f42123..8551c67077b 100644 --- a/moli-renderer-v8/src/layout_renderer/mod.rs +++ b/moli-renderer-v8/src/layout_renderer/mod.rs @@ -1,7 +1,8 @@ mod inline_svg; +#[cfg(test)] +pub(crate) use inline_svg::parse_count as svg_parse_count; mod source_view; mod style_resolver; -mod svg_geometry; use std::collections::HashMap; @@ -12,8 +13,6 @@ use moli_layout::{ use crate::{document_runtime::DomHandle, native_bridge::PageScriptHost}; -pub(crate) use svg_geometry::svg_client_rect; - pub(crate) fn build_native_layout_pass( runtime: &PageScriptHost, root: DomHandle, @@ -55,14 +54,13 @@ fn build_native_layout_pass_recursive( let source = source_view::NativeLayoutSourceView::with_paint_resources( runtime, root, - request.requests_paint().then(|| { - style_resolver::layout_style_read_scope( - runtime, - document, - request.viewport, - environment_override, - ) - }), + style_resolver::layout_style_read_scope( + runtime, + document, + request.viewport, + environment_override, + ), + request.requests_paint(), ); let source_ready = profile_started.map(|_| std::time::Instant::now()); let mut styles = style_resolver::NativeLayoutStyleResolver::new( diff --git a/moli-renderer-v8/src/layout_renderer/source_view.rs b/moli-renderer-v8/src/layout_renderer/source_view.rs index 3460f1e7f39..4fb72241cd0 100644 --- a/moli-renderer-v8/src/layout_renderer/source_view.rs +++ b/moli-renderer-v8/src/layout_renderer/source_view.rs @@ -23,26 +23,29 @@ pub(super) struct NativeLayoutSourceView<'a> { runtime: &'a PageScriptHost, root: DomHandle, document: Option, - paint_styles: Option>>, + styles: RefCell>, + paint_resources: bool, text_selections: HashMap, } impl<'a> NativeLayoutSourceView<'a> { #[cfg(test)] pub(super) fn new(runtime: &'a PageScriptHost, root: DomHandle) -> Self { - Self::with_paint_resources(runtime, root, None) + Self::with_paint_resources(runtime, root, StyleObservation::new(runtime), false) } pub(super) fn with_paint_resources( runtime: &'a PageScriptHost, root: DomHandle, - paint_styles: Option>, + styles: StyleObservation<'a>, + paint_resources: bool, ) -> Self { Self { runtime, root, document: runtime.dom_host().owner_document_handle(root), - paint_styles: paint_styles.map(RefCell::new), + styles: RefCell::new(styles), + paint_resources, text_selections: document_text_selections(runtime, root), } } @@ -239,9 +242,11 @@ impl LayoutSource for NativeLayoutSourceView<'_> { fn replaced_image( &self, node: Self::NodeId, - style: &moli_layout::ResolvedLayoutStyle, + _style: &moli_layout::ResolvedLayoutStyle, ) -> Option { - let paint_styles = self.paint_styles.as_ref()?; + if !self.paint_resources { + return None; + } let semantics = self .host() .node(node) @@ -257,9 +262,6 @@ impl LayoutSource for NativeLayoutSourceView<'_> { svg: ready.svg, }) } - Some(LayoutReplacedKind::Svg) => { - super::inline_svg::replaced_resource(self.runtime, node, style, paint_styles) - } Some(LayoutReplacedKind::Canvas) => { let pixels = self.runtime.canvas_pixels_for_layout(node)?; Some(LayoutImageResource { @@ -274,7 +276,9 @@ impl LayoutSource for NativeLayoutSourceView<'_> { } fn css_image_resource(&self, resolved_url: &str) -> Option { - self.paint_styles.as_ref()?; + if !self.paint_resources { + return None; + } let parsed = url::Url::parse(resolved_url).ok()?; // Blink shares the fetched bytes using a fragment-free cache key, but // then applies SVG view/element-fragment semantics separately. Until @@ -293,6 +297,22 @@ impl LayoutSource for NativeLayoutSourceView<'_> { svg: ready.svg, }) } + + fn svg_content( + &self, + node: DomHandle, + style: &moli_layout::ResolvedLayoutStyle, + viewport: moli_layout::LayoutSize, + ) -> Option> { + super::inline_svg::layout_content( + self.runtime, + node, + style, + viewport, + &self.styles, + self.paint_resources, + ) + } } fn document_text_selections( diff --git a/moli-renderer-v8/src/layout_renderer/svg_geometry.rs b/moli-renderer-v8/src/layout_renderer/svg_geometry.rs deleted file mode 100644 index cc9be835ffc..00000000000 --- a/moli-renderer-v8/src/layout_renderer/svg_geometry.rs +++ /dev/null @@ -1,158 +0,0 @@ -use std::cell::RefCell; - -use moli_layout::{ - LayoutError, LayoutPoint, LayoutQuad, LayoutQuery, LayoutQueryAnswer, ResolvedLayoutStyle, -}; - -use crate::{ - document_runtime::DomHandle, - native_bridge::{PageScriptHost, element::StyleObservation}, -}; - -use super::inline_svg::{GeometryTarget, parse_live_svg}; - -/// SVG graphics have object geometry rather than CSS layout boxes. CSSOM View -/// requires a single transformed object rectangle for these elements. -pub(crate) fn svg_client_rect( - runtime: &PageScriptHost, - document: DomHandle, - source: DomHandle, -) -> Result>, LayoutError> { - let host = runtime.dom_host(); - let Some(element) = host.node(source).and_then(|node| node.as_element()) else { - return Ok(None); - }; - if element.namespace() != "http://www.w3.org/2000/svg" { - return Ok(None); - } - let mut root = source; - let mut ancestor = host.dom().parent_node(source); - while let Some(parent) = ancestor { - let Some(parent_element) = host.node(parent).and_then(|node| node.as_element()) else { - break; - }; - if parent_element.namespace() != "http://www.w3.org/2000/svg" { - break; - } - root = parent; - ancestor = host.dom().parent_node(parent); - } - if root == source - || host - .node(root) - .is_none_or(|node| node.local_name() != Some("svg")) - { - // The outer SVG has a CSS replaced-element box, just like . - return Ok(None); - } - let mut reads = StyleObservation::new(runtime); - let mut ancestor = Some(source); - while let Some(node) = ancestor { - if host - .node(node) - .and_then(|node| node.as_element()) - .is_some_and(|element| { - element.namespace() == "http://www.w3.org/2000/svg" - && matches!( - element.local_name(), - "defs" | "symbol" | "marker" | "pattern" | "clipPath" | "mask" - ) - }) - { - return Ok(Some(Vec::new())); - } - if let Some(computed) = reads.read(node).computed_values() - && computed.clone_display().is_none() - { - return Ok(Some(Vec::new())); - } - ancestor = host.dom().parent_node(node); - if ancestor == Some(document) { - break; - } - } - let Some(computed) = reads.read(root).computed_values() else { - return Ok(Some(Vec::new())); - }; - let style = ResolvedLayoutStyle::from_stylo(computed); - let model = match runtime - .answer_layout_query_for_document(document, &LayoutQuery::BoxModel { source: root })? - { - LayoutQueryAnswer::BoxModel(model) => model, - _ => unreachable!("SVG viewport box model query"), - }; - let metrics = match runtime - .answer_layout_query_for_document(document, &LayoutQuery::ElementMetrics { source: root })? - { - LayoutQueryAnswer::ElementMetrics(metrics) => metrics, - _ => unreachable!("SVG viewport metrics query"), - }; - // A newly inserted SVG may not yet have a box in the published layout. - // Its local geometry can still be measured, using its SVG viewport; once - // layout publishes the outer box, include that box's placement/transforms. - let metadata = super::inline_svg::replaced_metrics( - host.node(root) - .and_then(|node| node.as_element()) - .expect("SVG root"), - ); - let viewport = metrics - .as_ref() - .map(|metrics| metrics.content_size) - .unwrap_or_else(|| { - moli_layout::LayoutSize::new( - metadata.intrinsic_width.unwrap_or(300.0), - metadata.intrinsic_height.unwrap_or(150.0), - ) - }); - if viewport.width <= 0.0 || viewport.height <= 0.0 { - return Ok(Some(Vec::new())); - } - let marker = format!("__moli_svg_geometry_{}", source.index()); - let id = element - .attribute("id") - .filter(|id| !id.is_empty()) - .unwrap_or(&marker); - let Some(svg) = parse_live_svg( - runtime, - root, - &style, - &RefCell::new(reads), - Some(GeometryTarget { - node: source, - id, - viewport, - }), - ) else { - return Ok(Some(Vec::new())); - }; - let Some(node) = svg.tree().node_by_id(id) else { - return Ok(Some(Vec::new())); - }; - let bounds = node.bounding_box(); - let transform = node.abs_transform(); - let map = |x, y| { - let x2 = transform.sx * x + transform.kx * y + transform.tx; - let y2 = transform.ky * x + transform.sy * y + transform.ty; - if let Some(model) = model.as_ref() { - let [origin, right, _, bottom] = model.content.points; - LayoutPoint::new( - origin.x - + (right.x - origin.x) * x2 / viewport.width - + (bottom.x - origin.x) * y2 / viewport.height, - origin.y - + (right.y - origin.y) * x2 / viewport.width - + (bottom.y - origin.y) * y2 / viewport.height, - ) - } else { - LayoutPoint::new(x2, y2) - } - }; - Ok(Some(vec![LayoutQuad { - points: [ - map(bounds.left(), bounds.top()), - map(bounds.right(), bounds.top()), - map(bounds.right(), bounds.bottom()), - map(bounds.left(), bounds.bottom()), - ], - }])) -} diff --git a/moli-renderer-v8/src/native_bridge/element/geometry/provider.rs b/moli-renderer-v8/src/native_bridge/element/geometry/provider.rs index 67a6b7ab0fb..3c12f881f67 100644 --- a/moli-renderer-v8/src/native_bridge/element/geometry/provider.rs +++ b/moli-renderer-v8/src/native_bridge/element/geometry/provider.rs @@ -44,12 +44,6 @@ fn published_geometry_query( query: &LayoutQuery, ) -> Result, LayoutError> { if runtime.layout_policy().uses_real_layout() { - if let LayoutQuery::ClientRects { source } = query - && let Some(rects) = - crate::layout_renderer::svg_client_rect(runtime, document, *source)? - { - return Ok(LayoutQueryAnswer::ClientRects(rects)); - } runtime.answer_layout_query_for_document(document, query) } else { Ok(answer_mock_query(runtime, document, query)) @@ -72,16 +66,7 @@ pub(crate) fn published_geometry_batch( batch: &LayoutQueryBatch, ) -> Result, LayoutError> { if runtime.layout_policy().uses_real_layout() { - let mut answers = runtime.answer_layout_for_document(document, batch)?; - for (query, answer) in batch.queries.iter().zip(&mut answers.answers) { - if let LayoutQuery::ClientRects { source } = query - && let Some(rects) = - crate::layout_renderer::svg_client_rect(runtime, document, *source)? - { - *answer = LayoutQueryAnswer::ClientRects(rects); - } - } - Ok(answers) + runtime.answer_layout_for_document(document, batch) } else { Ok(answer_mock_queries( runtime, diff --git a/moli-renderer-v8/src/runtime/page_vm/tests/inline_svg_paint.rs b/moli-renderer-v8/src/runtime/page_vm/tests/inline_svg_paint.rs index 2ab8e6ccbf1..c1556279c4f 100644 --- a/moli-renderer-v8/src/runtime/page_vm/tests/inline_svg_paint.rs +++ b/moli-renderer-v8/src/runtime/page_vm/tests/inline_svg_paint.rs @@ -1,5 +1,116 @@ use super::*; +#[tokio::test(flavor = "current_thread")] +async fn inline_svg_final_styles_do_not_become_author_selector_attributes() { + run_page_vm_async_test(async move { + let loader = crate::network::ResourceRequestClient::new(&FetchConfig::default())?; + let mut page_vm = test_page_vm_with_loader_and_document_url( + &loader, Vec::new(), Url::parse("https://example.com/svg-original-attributes.html")?, + ); + page_vm.vm_mut().eval(r##" + document.head.innerHTML = ''; + document.body.innerHTML = ` + + + `; + 'installed' + "##)?; + page_vm.vm_mut().sync_live_document_style_sources(); + let snapshot = page_vm.vm_mut().screenshot_layout_snapshot(moli_layout::PaintViewport::new(100, 50, 1.0))?.unwrap(); + assert_eq!(page_vm.vm_mut().eval("JSON.stringify((r=>[r.x,r.y,r.width,r.height])(document.querySelector('rect').getBoundingClientRect()))")?, "[0,0,20,20]"); + assert_eq!(page_vm.vm_mut().eval("document.querySelector('rect').getAttributeNames().join(',')")?, "width,height,fill"); + let raster = moli_paint::raster_snapshot(&snapshot)?; + let pixel = |x: usize| &raster.rgba[(10 * raster.width as usize + x) * 4..][..4]; + assert_eq!(pixel(10), [255, 0, 0, 255]); + assert_eq!(pixel(50), [255, 255, 255, 255]); + assert_eq!(pixel(70), [255, 255, 255, 255]); + Ok::<_, anyhow::Error>(()) + }).await.expect("final SVG styles must not change selector matching"); +} + +#[tokio::test(flavor = "current_thread")] +async fn inline_svg_dense_source_keeps_its_original_input_budget() { + run_page_vm_async_test(async move { + let loader = crate::network::ResourceRequestClient::new(&FetchConfig::default())?; + let mut page_vm = test_page_vm_with_loader_and_document_url( + &loader, Vec::new(), Url::parse("https://example.com/svg-dense.html")?, + ); + page_vm.vm_mut().eval(r#" + document.head.innerHTML = ''; + document.body.innerHTML = '' + ''.repeat(30000) + ''; + 'installed' + "#)?; + page_vm.vm_mut().sync_live_document_style_sources(); + let snapshot = page_vm.vm_mut().screenshot_layout_snapshot(moli_layout::PaintViewport::new(100, 100, 1.0))?.unwrap(); + assert_eq!(snapshot.svg_images.len(), 1, "690 KB of original XML must remain a vector image"); + let raster = moli_paint::raster_snapshot(&snapshot)?; + // The sampled quarter-circle edge is antialiased; repeated source-over + // composition can round to 1 rather than exactly 0. + assert!(raster.rgba[..3].iter().all(|channel| *channel <= 2)); + assert_eq!(raster.rgba[3], 255); + Ok::<_, anyhow::Error>(()) + }).await.expect("derived styles must not consume the encoded SVG input budget"); +} + +#[tokio::test(flavor = "current_thread")] +async fn inline_svg_batch_geometry_uses_one_frozen_scene() { + run_page_vm_async_test(async move { + let loader = crate::network::ResourceRequestClient::new(&FetchConfig::default())?; + let mut page_vm = test_page_vm_with_loader_and_document_url( + &loader, Vec::new(), Url::parse("https://example.com/svg-frozen-geometry.html")?, + ); + page_vm.vm_mut().eval(r#" + document.head.innerHTML = ''; + document.body.innerHTML = '' + ''.repeat(1000) + ''; + 'installed' + "#)?; + page_vm.vm_mut().sync_live_document_style_sources(); + let before = crate::layout_renderer::svg_parse_count(); + page_vm.vm_mut().screenshot_layout_snapshot(moli_layout::PaintViewport::new(500, 150, 1.0))?; + assert_eq!(crate::layout_renderer::svg_parse_count() - before, 1); + let frozen = crate::layout_renderer::svg_parse_count(); + assert_eq!(page_vm.vm_mut().eval("(()=>{const r=document.createRange();r.selectNodeContents(document.querySelector('svg'));return r.getClientRects().length})()")?, "1000"); + assert_eq!(crate::layout_renderer::svg_parse_count(), frozen, "a batch must only read the published numeric geometry"); + assert_eq!(page_vm.vm_mut().eval(r#"(()=>{ + document.querySelector('svg').style.left='300px'; + document.querySelector('rect').setAttribute('x','30'); + return JSON.stringify([document.querySelector('svg').getBoundingClientRect().x,document.querySelector('rect').getBoundingClientRect().x]); + })()"#)?, "[100,110]", "both coordinate levels must stay in the same frozen publication"); + assert_eq!(crate::layout_renderer::svg_parse_count(), frozen); + page_vm.vm_mut().screenshot_layout_snapshot(moli_layout::PaintViewport::new(500, 150, 1.0))?; + assert_eq!(page_vm.vm_mut().eval("document.querySelector('rect').getBoundingClientRect().x")?, "330"); + assert_eq!(crate::layout_renderer::svg_parse_count() - frozen, 1); + Ok::<_, anyhow::Error>(()) + }).await.expect("SVG geometry must share its outer layout's publication"); +} + +#[tokio::test(flavor = "current_thread")] +async fn inline_svg_geometry_keeps_clipped_and_flattened_source_elements() { + run_page_vm_async_test(async move { + let loader = crate::network::ResourceRequestClient::new(&FetchConfig::default())?; + let mut page_vm = test_page_vm_with_loader_and_document_url( + &loader, Vec::new(), Url::parse("https://example.com/svg-source-geometry.html")?, + ); + page_vm.vm_mut().eval(r##" + document.head.innerHTML = ''; + document.body.innerHTML = ` + + + + + + + `; + 'installed' + "##)?; + page_vm.vm_mut().sync_live_document_style_sources(); + page_vm.vm_mut().screenshot_layout_snapshot(moli_layout::PaintViewport::new(300, 150, 1.0))?; + assert_eq!(page_vm.vm_mut().eval(r#"JSON.stringify(['#clipped','#group','#nested'].flatMap(s=>[...document.querySelectorAll(s)]).concat([...document.querySelectorAll('#same')]).map(e=>{const r=e.getBoundingClientRect();return [r.x,r.y,r.width,r.height]}))"#)?, + "[[10,20,30,40],[10,20,30,40],[12,23,48,40],[12,23,30,40],[50,23,10,40]]"); + Ok::<_, anyhow::Error>(()) + }).await.expect("object geometry must not depend on retained paint nodes or unique author IDs"); +} + #[tokio::test(flavor = "current_thread")] async fn inline_svg_client_rects_include_graphics_text_and_viewport_transforms() { run_page_vm_async_test(async move {