From 71d0761b1890bd782ff59dbc53fef235fd129cae Mon Sep 17 00:00:00 2001 From: ldm0 Date: Wed, 7 Oct 2026 18:44:28 +0800 Subject: [PATCH] fix(svg): sample SMIL paths with native presentation clocks --- .../svg_runtime/animation.rs | 230 ++++++---- .../src/native_bridge/context_host/core.rs | 1 + .../context_host/host_environment.rs | 3 + .../src/native_bridge/context_host/mod.rs | 2 + .../native_bridge/context_host/svg_smil.rs | 421 ++++++++++++++++++ .../element/styles/declaration/observation.rs | 9 + .../src/script_vm/browsing_contexts.rs | 5 + .../live_document/geometry_and_svg.rs | 63 +-- moli-renderer-v8/src/script_vm/tests/mod.rs | 1 + .../script_vm/tests/svg_smil_path_timing.js | 80 ++++ .../script_vm/tests/svg_smil_path_timing.rs | 99 ++++ moli-renderer-v8/src/style_engine/computed.rs | 9 + moli-svg/src/lib.rs | 5 + moli-svg/src/timing.rs | 316 +++++++++++++ 14 files changed, 1139 insertions(+), 105 deletions(-) create mode 100644 moli-renderer-v8/src/native_bridge/context_host/svg_smil.rs create mode 100644 moli-renderer-v8/src/script_vm/tests/svg_smil_path_timing.js create mode 100644 moli-renderer-v8/src/script_vm/tests/svg_smil_path_timing.rs create mode 100644 moli-svg/src/timing.rs diff --git a/moli-renderer-v8/src/context_bootstrap/svg_runtime/animation.rs b/moli-renderer-v8/src/context_bootstrap/svg_runtime/animation.rs index 57c8e1ef225..dacfa4018a2 100644 --- a/moli-renderer-v8/src/context_bootstrap/svg_runtime/animation.rs +++ b/moli-renderer-v8/src/context_bootstrap/svg_runtime/animation.rs @@ -5,7 +5,7 @@ use crate::{ document_runtime::DomHandle, native_bridge::{ PageScriptHost, - document::{SVG_NS, detached_native_object_for_handle}, + document::detached_native_object_for_handle, element::{node_event_handler_getter_function, node_event_handler_setter_function}, node_runtime_and_handle_from_object_or_detached, throw_dom_exception, }, @@ -13,6 +13,15 @@ use crate::{ web_api_interfaces, webidl, }; +fn svg_receiver_runtime_and_handle<'s>( + scope: &mut v8::PinScope<'s, '_>, + args: &v8::FunctionCallbackArguments<'s>, +) -> anyhow::Result<(*mut PageScriptHost, DomHandle)> { + let receiver = moli_webapi_declare::web_api_object_target(scope, args.this()) + .expect("generated receiver check validates native SVG identity"); + node_runtime_and_handle_from_object_or_detached(scope, receiver) +} + #[derive(WebApiFunctionTemplate)] #[webapi(interface = web_api_interfaces::SVGAnimationElement, enumerable)] struct SvgAnimationDeclaration { @@ -39,16 +48,31 @@ struct SvgAnimationDeclaration { get_current_time: (), #[webapi(method = "getSimpleDuration", length = 0, callback = get_simple_duration)] get_simple_duration: (), - #[webapi(method = "beginElement", length = 0, callback = unsupported_timing)] + #[webapi(method = "beginElement", length = 0, callback = begin_element)] begin_element: (), - #[webapi(method = "beginElementAt", length = 1, callback = unsupported_timing_at)] + #[webapi(method = "beginElementAt", length = 1, callback = begin_element_at)] begin_element_at: (), - #[webapi(method = "endElement", length = 0, callback = unsupported_timing)] + #[webapi(method = "endElement", length = 0, callback = end_element)] end_element: (), - #[webapi(method = "endElementAt", length = 1, callback = unsupported_timing_at)] + #[webapi(method = "endElementAt", length = 1, callback = end_element_at)] end_element_at: (), } +#[derive(WebApiFunctionTemplate)] +#[webapi(interface = web_api_interfaces::SVGSVGElement, enumerable)] +struct SvgTimeContainerDeclaration { + #[webapi(method = "pauseAnimations", length = 0, callback = pause_animations)] + pause_animations: (), + #[webapi(method = "unpauseAnimations", length = 0, callback = unpause_animations)] + unpause_animations: (), + #[webapi(method = "animationsPaused", length = 0, callback = animations_paused)] + animations_paused: (), + #[webapi(method = "getCurrentTime", length = 0, callback = get_current_time)] + get_current_time: (), + #[webapi(method = "setCurrentTime", length = 1, callback = set_current_time)] + set_current_time: (), +} + pub(super) fn install_bindings<'s>( scope: &mut v8::PinScope<'s, '_, ()>, template: v8::Local<'s, v8::FunctionTemplate>, @@ -57,61 +81,21 @@ pub(super) fn install_bindings<'s>( if name == "SVGAnimationElement" { let prototype = template.prototype_template(scope); SvgAnimationDeclaration::initialize_prototype_template(scope, prototype); + } else if name == "SVGSVGElement" { + let prototype = template.prototype_template(scope); + SvgTimeContainerDeclaration::initialize_prototype_template(scope, prototype); } } -fn target_element(runtime: &PageScriptHost, animation: DomHandle) -> Option { - let dom = runtime.dom_host(); - if !dom.is_connected_to_document(animation) { - return None; - } - let href = dom - .get_attribute_ns(animation, None, "href") - .or_else(|| dom.get_attribute_ns(animation, Some("http://www.w3.org/1999/xlink"), "href")) - .unwrap_or_default(); - let target = if href.is_empty() { - dom.node(animation)?.parent_node()? - } else { - let fragment = if let Some(fragment) = href.strip_prefix('#') { - fragment.to_owned() - } else { - let document = dom.owner_document_handle(animation)?; - let mut url = runtime - .document_base_url_for_handle(document) - .join(&href) - .ok()?; - let fragment = url.fragment()?.to_owned(); - url.set_fragment(None); - let mut document_url = runtime.document_url_for_handle(document); - document_url.set_fragment(None); - if url != document_url { - return None; - } - fragment - }; - if fragment.is_empty() { - return None; - } - let id = percent_encoding::percent_decode_str(&fragment).decode_utf8_lossy(); - let root = dom.root_node_handle(animation)?; - dom.element_handle_by_id_in_subtree(root, &id)? - }; - dom.node(target) - .is_some_and(|node| node.namespace() == Some(SVG_NS)) - .then_some(target) -} - fn target_element_getter<'s>( scope: &mut v8::PinScope<'s, '_>, args: v8::FunctionCallbackArguments<'s>, mut rv: v8::ReturnValue<'s, v8::Value>, ) { - let Ok((runtime_ptr, handle)) = - node_runtime_and_handle_from_object_or_detached(scope, args.this()) - else { + let Ok((runtime_ptr, handle)) = svg_receiver_runtime_and_handle(scope, &args) else { return; }; - let target = target_element(unsafe { &*runtime_ptr }, handle); + let target = unsafe { &*runtime_ptr }.svg_animation_target(handle); let Some(target) = target.and_then(|handle| detached_native_object_for_handle(scope, runtime_ptr, handle)) else { @@ -121,14 +105,17 @@ fn target_element_getter<'s>( rv.set(target.into()); } -// Native DOM, interface identity and handler dispatch are supported. A SMIL -// time container is not yet scheduled, so no current interval exists. Timing -// controls fail explicitly instead of pretending to start an animation. fn get_start_time<'s>( scope: &mut v8::PinScope<'s, '_>, - _args: v8::FunctionCallbackArguments<'s>, - _rv: v8::ReturnValue<'s, v8::Value>, + args: v8::FunctionCallbackArguments<'s>, + mut rv: v8::ReturnValue<'s, v8::Value>, ) { + if let Ok((runtime, handle)) = svg_receiver_runtime_and_handle(scope, &args) + && let Some(start) = unsafe { &*runtime }.svg_animation_start_time(handle) + { + rv.set_double(f64::from(start as f32)); + return; + } throw_dom_exception( scope, "InvalidStateError", @@ -138,60 +125,143 @@ fn get_start_time<'s>( } fn get_current_time<'s>( - _scope: &mut v8::PinScope<'s, '_>, - _args: v8::FunctionCallbackArguments<'s>, + scope: &mut v8::PinScope<'s, '_>, + args: v8::FunctionCallbackArguments<'s>, mut rv: v8::ReturnValue<'s, v8::Value>, ) { - rv.set_double(0.0); + if let Ok((runtime, handle)) = svg_receiver_runtime_and_handle(scope, &args) { + rv.set_double(f64::from( + unsafe { &*runtime }.svg_presentation_time(handle) as f32, + )); + } } fn get_simple_duration<'s>( scope: &mut v8::PinScope<'s, '_>, - _args: v8::FunctionCallbackArguments<'s>, - _rv: v8::ReturnValue<'s, v8::Value>, + args: v8::FunctionCallbackArguments<'s>, + mut rv: v8::ReturnValue<'s, v8::Value>, ) { + if let Ok((runtime, handle)) = svg_receiver_runtime_and_handle(scope, &args) + && let Some(duration) = unsafe { &*runtime }.svg_animation_simple_duration(handle) + { + rv.set_double(f64::from(duration as f32)); + return; + } throw_dom_exception( scope, "NotSupportedError", 9, - "SVG animation durations are not implemented.", + "The animation has no finite simple duration.", ); } -fn unsupported_timing<'s>( +fn add_instance<'s>( scope: &mut v8::PinScope<'s, '_>, - _args: v8::FunctionCallbackArguments<'s>, - _rv: v8::ReturnValue<'s, v8::Value>, + args: &v8::FunctionCallbackArguments<'s>, + begin: bool, + offset: f32, ) { - throw_dom_exception( - scope, - "NotSupportedError", - 9, - "SVG animation timing is not implemented.", - ); + if let Ok((runtime, handle)) = svg_receiver_runtime_and_handle(scope, args) { + unsafe { &*runtime }.add_svg_animation_instance(handle, begin, offset); + } } #[derive(webidl::WebIdlArgs)] #[webidl(prefix = "SVGAnimationElement")] struct TimingOffsetArgs { - #[webidl(required, converter = "double")] - offset: f64, + #[webidl(required, converter = "float")] + offset: f32, } -fn unsupported_timing_at<'s>( +fn begin_element<'s>( scope: &mut v8::PinScope<'s, '_>, args: v8::FunctionCallbackArguments<'s>, - rv: v8::ReturnValue<'s, v8::Value>, + _rv: v8::ReturnValue<'s, v8::Value>, +) { + add_instance(scope, &args, true, 0.0); +} + +fn end_element<'s>( + scope: &mut v8::PinScope<'s, '_>, + args: v8::FunctionCallbackArguments<'s>, + _rv: v8::ReturnValue<'s, v8::Value>, +) { + add_instance(scope, &args, false, 0.0); +} + +fn begin_element_at<'s>( + scope: &mut v8::PinScope<'s, '_>, + args: v8::FunctionCallbackArguments<'s>, + _rv: v8::ReturnValue<'s, v8::Value>, ) { let Some(parsed) = webidl::parse_args::(scope, &args) else { return; }; - if !(parsed.offset as f32).is_finite() { - webidl::throw_type_error( - scope, - "SVG animation offset is outside the finite float range.", - ); + add_instance(scope, &args, true, parsed.offset); +} + +fn end_element_at<'s>( + scope: &mut v8::PinScope<'s, '_>, + args: v8::FunctionCallbackArguments<'s>, + _rv: v8::ReturnValue<'s, v8::Value>, +) { + if let Some(parsed) = webidl::parse_args::(scope, &args) { + add_instance(scope, &args, false, parsed.offset); + } +} + +#[derive(webidl::WebIdlArgs)] +#[webidl(prefix = "SVGSVGElement.setCurrentTime")] +struct SeekArgs { + #[webidl(required, converter = "float")] + seconds: f32, +} + +fn set_current_time<'s>( + scope: &mut v8::PinScope<'s, '_>, + args: v8::FunctionCallbackArguments<'s>, + _rv: v8::ReturnValue<'s, v8::Value>, +) { + let Some(parsed) = webidl::parse_args::(scope, &args) else { return; + }; + if let Ok((runtime, handle)) = svg_receiver_runtime_and_handle(scope, &args) { + unsafe { &*runtime }.seek_svg_animations(handle, parsed.seconds); + } +} + +fn set_paused<'s>( + scope: &mut v8::PinScope<'s, '_>, + args: &v8::FunctionCallbackArguments<'s>, + pause: bool, +) { + if let Ok((runtime, handle)) = svg_receiver_runtime_and_handle(scope, args) { + unsafe { &*runtime }.pause_svg_animations(handle, pause); + } +} + +fn pause_animations<'s>( + scope: &mut v8::PinScope<'s, '_>, + args: v8::FunctionCallbackArguments<'s>, + _rv: v8::ReturnValue<'s, v8::Value>, +) { + set_paused(scope, &args, true); +} + +fn unpause_animations<'s>( + scope: &mut v8::PinScope<'s, '_>, + args: v8::FunctionCallbackArguments<'s>, + _rv: v8::ReturnValue<'s, v8::Value>, +) { + set_paused(scope, &args, false); +} + +fn animations_paused<'s>( + scope: &mut v8::PinScope<'s, '_>, + args: v8::FunctionCallbackArguments<'s>, + mut rv: v8::ReturnValue<'s, v8::Value>, +) { + if let Ok((runtime, handle)) = svg_receiver_runtime_and_handle(scope, &args) { + rv.set_bool(unsafe { &*runtime }.svg_animations_paused(handle)); } - unsupported_timing(scope, args, rv); } diff --git a/moli-renderer-v8/src/native_bridge/context_host/core.rs b/moli-renderer-v8/src/native_bridge/context_host/core.rs index 3493b7889b1..fac17559a04 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/core.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/core.rs @@ -522,6 +522,7 @@ impl PageScriptHost { claimed_child_histories: HashMap::new(), rendering_updates: super::rendering_updates::RenderingUpdateState::default(), animation_frames: super::animation_frames::AnimationFrameState::default(), + svg_smil: RefCell::new(super::svg_smil::SvgSmilState::default()), scroll_observable_effect_batch: super::interaction_batch::ScrollObservableEffectBatchState::default(), view_transition_updates: diff --git a/moli-renderer-v8/src/native_bridge/context_host/host_environment.rs b/moli-renderer-v8/src/native_bridge/context_host/host_environment.rs index 90293a602f7..99472bc51e5 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/host_environment.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/host_environment.rs @@ -2060,6 +2060,9 @@ impl PageScriptHost { document_handle: DomHandle, ready_state: DocumentReadyState, ) -> bool { + if ready_state == DocumentReadyState::Complete { + self.record_svg_document_begin(document_handle); + } self.dom_host_mut() .set_document_ready_state_for_handle(document_handle, ready_state) } diff --git a/moli-renderer-v8/src/native_bridge/context_host/mod.rs b/moli-renderer-v8/src/native_bridge/context_host/mod.rs index 29a4648be68..9e7495928af 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/mod.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/mod.rs @@ -76,6 +76,7 @@ mod child_frame_navigation; mod child_frame_runtime; mod child_runtime_script_order; mod document_parser_owner; +mod svg_smil; pub(crate) use child_frame_runtime::install_child_window_proxy_access_check_handlers; pub(crate) use child_frame_runtime::{ install_synthetic_window_access_check_handlers, synthetic_window_context_can_access, @@ -1047,6 +1048,7 @@ pub(crate) struct PageScriptHost { claimed_child_histories: HashMap>, rendering_updates: rendering_updates::RenderingUpdateState, animation_frames: animation_frames::AnimationFrameState, + svg_smil: RefCell, scroll_observable_effect_batch: interaction_batch::ScrollObservableEffectBatchState, view_transition_updates: view_transition_updates::ViewTransitionUpdateState, media_element_events: media_element_events::MediaElementEventState, diff --git a/moli-renderer-v8/src/native_bridge/context_host/svg_smil.rs b/moli-renderer-v8/src/native_bridge/context_host/svg_smil.rs new file mode 100644 index 00000000000..63f1164133b --- /dev/null +++ b/moli-renderer-v8/src/native_bridge/context_host/svg_smil.rs @@ -0,0 +1,421 @@ +use std::{collections::HashMap, time::Instant}; + +use moli_svg::{ + SvgAnimationInstanceTimes, SvgAnimationRestart, SvgAnimationTiming, SvgPresentationClock, + parse_clock_value, +}; +use style::values::{ + animated::{Animate, Procedure}, + computed::DProperty, + specified::svg_path::SVGPathData, +}; + +use super::PageScriptHost; +use crate::{document_runtime::DomHandle, native_bridge::document::SVG_NS}; + +pub(super) struct SvgSmilState { + epoch: Instant, + clocks: HashMap, + instances: HashMap, + effects: HashMap, +} + +struct FragmentEffects { + version: u64, + targets: HashMap>, +} + +impl Default for SvgSmilState { + fn default() -> Self { + Self { + epoch: Instant::now(), + clocks: HashMap::new(), + instances: HashMap::new(), + effects: HashMap::new(), + } + } +} + +impl SvgSmilState { + fn now(&self) -> f64 { + self.epoch.elapsed().as_secs_f64() + } +} + +impl PageScriptHost { + /// All nested SVG elements in one SVG document fragment share its clock. + /// An intervening non-SVG element (for example in foreignObject) starts a + /// new fragment. Merely having an associated synthetic Window is not enough. + pub(crate) fn svg_animation_fragment(&self, handle: DomHandle) -> Option { + let dom = self.dom_host(); + let mut current = handle; + let mut root = None; + loop { + let node = dom.node(current)?; + if node.namespace() != Some(SVG_NS) { + break; + } + if node.local_name() == Some("svg") { + root = Some(current); + } + let Some(parent) = node.parent_node() else { + break; + }; + current = parent; + } + root + } + + pub(crate) fn record_svg_document_begin(&self, document: DomHandle) { + if self.window_endpoint_for_document(document).is_none() { + return; + } + let mut state = self.svg_smil.borrow_mut(); + let now = state.now(); + let mut nodes = vec![document]; + while let Some(handle) = nodes.pop() { + if self.dom_host().node(handle).is_some_and(|node| { + node.namespace() == Some(SVG_NS) && node.local_name() == Some("svg") + }) && self.svg_animation_fragment(handle) == Some(handle) + { + state.clocks.entry(handle).or_default().start(now); + } + nodes.extend(self.dom_host().child_nodes(handle).unwrap_or_default()); + } + } + + fn with_svg_clock( + &self, + root: DomHandle, + update: impl FnOnce(&mut SvgPresentationClock, f64) -> R, + ) -> R { + let dom = self.dom_host(); + let active = dom.is_connected_to_document(root) + && dom.owner_document_handle(root).is_some_and(|document| { + self.window_endpoint_for_document(document).is_some() + && self.document_ready_state_for_handle(document) == "complete" + }); + let mut state = self.svg_smil.borrow_mut(); + let now = state.now(); + let clock = state.clocks.entry(root).or_default(); + if active { + clock.start(now); + } + update(clock, now) + } + + pub(crate) fn svg_presentation_time(&self, handle: DomHandle) -> f64 { + self.svg_animation_fragment(handle) + .map(|root| self.with_svg_clock(root, |clock, now| clock.current_time(now))) + .unwrap_or(0.0) + } + + pub(crate) fn svg_animations_paused(&self, handle: DomHandle) -> bool { + self.svg_animation_fragment(handle) + .is_some_and(|root| self.with_svg_clock(root, |clock, _| clock.is_paused())) + } + + pub(crate) fn pause_svg_animations(&self, handle: DomHandle, pause: bool) { + if self.svg_animation_fragment(handle) == Some(handle) { + self.with_svg_clock(handle, |clock, now| { + if pause { + clock.pause(now); + } else { + clock.unpause(now); + } + }); + } + } + + pub(crate) fn seek_svg_animations(&self, handle: DomHandle, seconds: f32) { + if self.svg_animation_fragment(handle) == Some(handle) { + self.with_svg_clock(handle, |clock, now| clock.seek(now, f64::from(seconds))); + } + } + + pub(crate) fn svg_animation_target(&self, animation: DomHandle) -> Option { + let dom = self.dom_host(); + if !dom.is_connected_to_document(animation) { + return None; + } + let href = dom + .get_attribute_ns(animation, None, "href") + .or_else(|| { + dom.get_attribute_ns(animation, Some("http://www.w3.org/1999/xlink"), "href") + }) + .unwrap_or_default(); + let target = if href.is_empty() { + dom.node(animation)?.parent_node()? + } else { + let fragment = if let Some(fragment) = href.strip_prefix('#') { + fragment.to_owned() + } else { + let document = dom.owner_document_handle(animation)?; + let mut url = self + .document_base_url_for_handle(document) + .join(&href) + .ok()?; + let fragment = url.fragment()?.to_owned(); + url.set_fragment(None); + let mut document_url = self.document_url_for_handle(document); + document_url.set_fragment(None); + if url != document_url { + return None; + } + fragment + }; + if fragment.is_empty() { + return None; + } + let id = percent_encoding::percent_decode_str(&fragment).decode_utf8_lossy(); + dom.element_handle_by_id_in_subtree(dom.root_node_handle(animation)?, &id)? + }; + dom.node(target) + .is_some_and(|node| node.namespace() == Some(SVG_NS)) + .then_some(target) + } + + pub(crate) fn svg_animation_simple_duration(&self, animation: DomHandle) -> Option { + self.dom_host() + .get_attribute(animation, "dur") + .and_then(|raw| parse_clock_value(&raw)) + .filter(|v| *v >= 0.0) + } + + fn svg_animation_timing(&self, animation: DomHandle) -> SvgAnimationTiming { + let attribute = |name| self.dom_host().get_attribute(animation, name); + let times = |raw: Option, default| { + raw.map(|raw| raw.split(';').filter_map(parse_clock_value).collect()) + .unwrap_or(default) + }; + SvgAnimationTiming { + begins: times(attribute("begin"), vec![0.0]), + ends: times(attribute("end"), vec![]), + simple_duration: self + .svg_animation_simple_duration(animation) + .unwrap_or(f64::INFINITY), + repeat_count: attribute("repeatCount") + .map(|raw| { + if raw == "indefinite" { + f64::INFINITY + } else { + raw.parse::() + .ok() + .filter(|v| v.is_finite() && *v > 0.0) + .unwrap_or(1.0) + } + }) + .unwrap_or(1.0), + repeat_duration: attribute("repeatDur") + .and_then(|raw| parse_clock_value(&raw)) + .filter(|v| *v >= 0.0) + .unwrap_or(f64::INFINITY), + freeze: attribute("fill").as_deref() == Some("freeze"), + restart: match attribute("restart").as_deref() { + Some("never") => SvgAnimationRestart::Never, + Some("whenNotActive") => SvgAnimationRestart::WhenNotActive, + _ => SvgAnimationRestart::Always, + }, + } + } + + pub(crate) fn svg_animation_start_time(&self, animation: DomHandle) -> Option { + self.svg_animation_target(animation)?; + let time = self.svg_presentation_time(animation); + let timing = self.svg_animation_timing(animation); + let state = self.svg_smil.borrow(); + timing + .current_interval( + state + .instances + .get(&animation) + .unwrap_or(&SvgAnimationInstanceTimes::default()), + time, + ) + .map(|interval| interval.begin) + } + + pub(crate) fn add_svg_animation_instance( + &self, + animation: DomHandle, + begin: bool, + offset: f32, + ) { + if self.svg_animation_fragment(animation).is_none() { + return; + } + let time = self.svg_presentation_time(animation) + f64::from(offset); + let mut state = self.svg_smil.borrow_mut(); + let instances = state.instances.entry(animation).or_default(); + let list = if begin { + &mut instances.begins + } else { + &mut instances.ends + }; + if !list.contains(&time) { + list.push(time); + } + } + + /// Native path sampling is applied to an observation's typed style, shared + /// by CSSOM, SVG geometry and box construction. Its base cascade and the + /// authored d attribute remain unchanged. + pub(crate) fn sampled_svg_path( + &self, + target: DomHandle, + base: &DProperty, + ) -> Option { + let dom = self.dom_host(); + if !dom.node(target).is_some_and(|node| { + node.namespace() == Some(SVG_NS) && node.local_name() == Some("path") + }) || !dom.is_connected_to_document(target) + { + return None; + } + let root = self.svg_animation_fragment(target)?; + let time = self.svg_presentation_time(root); + if !self.with_svg_clock(root, |clock, _| clock.has_started()) { + return None; + } + let animations = { + let mut state = self.svg_smil.borrow_mut(); + let version = dom.dom_version(); + if state + .effects + .get(&root) + .is_none_or(|effects| effects.version != version) + { + let mut targets: HashMap> = HashMap::new(); + let mut nodes = vec![root]; + while let Some(handle) = nodes.pop() { + if dom.node(handle).is_some_and(|node| { + node.namespace() == Some(SVG_NS) + && matches!(node.local_name(), Some("animate" | "set")) + }) && self.svg_animation_fragment(handle) == Some(root) + && let Some(target) = self.svg_animation_target(handle) + { + targets.entry(target).or_default().push(handle); + } + let children = dom.child_nodes(handle).unwrap_or_default(); + nodes.extend(children.into_iter().rev()); + } + state + .effects + .insert(root, FragmentEffects { version, targets }); + } + state.effects.get(&root)?.targets.get(&target)?.clone() + }; + let mut result = None; + for animation in animations { + if dom.get_attribute(animation, "attributeName").as_deref() != Some("d") { + continue; + } + let timing = self.svg_animation_timing(animation); + let progress = { + let state = self.svg_smil.borrow(); + timing.sample_progress( + state + .instances + .get(&animation) + .unwrap_or(&SvgAnimationInstanceTimes::default()), + time, + ) + }; + let Some(progress) = progress else { + continue; + }; + if let Some(path) = sample_path(self, animation, base, progress) { + result = Some(path); + } + } + result + } +} + +fn sample_path( + runtime: &PageScriptHost, + animation: DomHandle, + base: &DProperty, + progress: f64, +) -> Option { + let dom = runtime.dom_host(); + let attribute = |name| dom.get_attribute(animation, name); + let parse = |raw: &str| { + let (path, valid) = SVGPathData::parse_bytes(raw.as_bytes()); + valid.then_some(path) + }; + if dom.node(animation)?.local_name() == Some("set") { + return parse(&attribute("to")?); + } + // Do not silently interpret unsupported additive/spline/paced functions as + // linear replacement. They need their own composition and distance model. + if attribute("additive").as_deref() == Some("sum") + || attribute("accumulate").as_deref() == Some("sum") + { + return None; + } + let discrete = match attribute("calcMode").as_deref() { + None | Some("linear") => false, + Some("discrete") => true, + _ => return None, + }; + let paths = if let Some(values) = attribute("values") { + values + .split(';') + .map(|raw| parse(raw.trim())) + .collect::>>()? + } else { + let from = if let Some(from) = attribute("from") { + parse(&from)? + } else { + match base { + DProperty::Path(path) => path.clone(), + DProperty::None => return None, + } + }; + vec![from, parse(&attribute("to")?)?] + }; + if paths.is_empty() { + return None; + } + if paths.len() == 1 { + return paths.into_iter().next(); + } + let count = paths.len(); + let times = if let Some(times) = attribute("keyTimes") { + let times = times + .split(';') + .map(|v| v.trim().parse::().ok()) + .collect::>>()?; + if times.len() != count + || times[0] != 0.0 + || (!discrete && times[count - 1] != 1.0) + || !times + .iter() + .all(|v| v.is_finite() && (0.0..=1.0).contains(v)) + || !times.windows(2).all(|pair| pair[0] <= pair[1]) + { + return None; + } + times + } else { + let denominator = if discrete { count } else { count - 1 } as f64; + (0..count).map(|i| i as f64 / denominator).collect() + }; + let index = times + .iter() + .rposition(|time| *time <= progress) + .unwrap_or(0); + if discrete || index == count - 1 { + return Some(paths[index].clone()); + } + let span = times[index + 1] - times[index]; + let progress = if span == 0.0 { + 1.0 + } else { + (progress - times[index]) / span + }; + paths[index] + .animate(&paths[index + 1], Procedure::Interpolate { progress }) + .ok() +} diff --git a/moli-renderer-v8/src/native_bridge/element/styles/declaration/observation.rs b/moli-renderer-v8/src/native_bridge/element/styles/declaration/observation.rs index 33ed2cb7baf..5fd14b522a1 100644 --- a/moli-renderer-v8/src/native_bridge/element/styles/declaration/observation.rs +++ b/moli-renderer-v8/src/native_bridge/element/styles/declaration/observation.rs @@ -430,6 +430,15 @@ impl<'a> StyleObservation<'a> { self.runtime .complete_computed_style_observation(document, &input_epochs); } + let stylo_style = stylo_style.map(|style| { + match self + .runtime + .sampled_svg_path(handle, &style.computed_values().clone_d()) + { + Some(path) => style.with_svg_path(path), + None => style, + } + }); ComputedStyleRead { runtime: self.runtime, handle, diff --git a/moli-renderer-v8/src/script_vm/browsing_contexts.rs b/moli-renderer-v8/src/script_vm/browsing_contexts.rs index 3195c3caa53..8b6a2e2b807 100644 --- a/moli-renderer-v8/src/script_vm/browsing_contexts.rs +++ b/moli-renderer-v8/src/script_vm/browsing_contexts.rs @@ -46,6 +46,11 @@ impl ScriptVm { state: crate::dom::native::DocumentReadyState, ) -> Result<()> { self.document_runtime.set_document_ready_state(state); + if state == crate::dom::native::DocumentReadyState::Complete { + self._context_host + .borrow() + .record_svg_document_begin(self.document_runtime.document_handle()); + } Ok(()) } diff --git a/moli-renderer-v8/src/script_vm/tests/dom_elements/live_document/geometry_and_svg.rs b/moli-renderer-v8/src/script_vm/tests/dom_elements/live_document/geometry_and_svg.rs index d2df1921ec4..a45767856ed 100644 --- a/moli-renderer-v8/src/script_vm/tests/dom_elements/live_document/geometry_and_svg.rs +++ b/moli-renderer-v8/src/script_vm/tests/dom_elements/live_document/geometry_and_svg.rs @@ -4069,31 +4069,6 @@ fn svg_animation_elements_use_native_interfaces_and_event_handlers() { ); } -#[test] -fn svg_animation_timing_shim_validates_arguments_before_reporting_unsupported() { - let mut vm = new_parsed_test_vm( - "https://svg-animation-timing.test/", - "", - ); - assert_eq!(vm.eval(r#" - (() => { - const other = document.getElementById('child').contentWindow; - for (const realm of [window, other]) { - const element = document.createElementNS('http://www.w3.org/2000/svg', 'animate'); - for (const name of ['beginElement', 'endElement', 'beginElementAt', 'endElementAt']) { - let error, conversions = 0; - try {realm.SVGAnimationElement.prototype[name].call(element, {valueOf() {conversions++; return 0.25;}});} - catch (caught) {error = caught;} - if (!(error instanceof realm.DOMException) || error.name !== 'NotSupportedError') throw Error(name + ' shim error'); - if (conversions !== (name.endsWith('At') ? 1 : 0)) throw Error(name + ' argument conversion'); - if (element.getCurrentTime() !== 0) throw Error('shim cannot advance the timeline'); - } - } - return true; - })() - "#).unwrap(), "true"); -} - #[test] fn svg_filter_primitives_expose_native_dom_attributes() { let mut vm = new_parsed_test_vm("https://svg-filter-dom.test/", ""); @@ -4165,3 +4140,41 @@ fn namespaced_attribute_values_preserve_utf16_and_namespace_identity() { "true" ); } + +#[test] +fn svg_animation_time_controls_convert_arguments_without_a_fragment() { + let mut vm = new_parsed_test_vm( + "https://svg-animation-timing.test/", + "", + ); + assert_eq!(vm.eval(r#" + (() => { + const other = document.getElementById('child').contentWindow; + for (const realm of [window, other]) { + const element = document.createElementNS('http://www.w3.org/2000/svg', 'animate'); + for (const name of ['beginElement', 'endElement', 'beginElementAt', 'endElementAt']) { + let conversions = 0; + const method = realm.SVGAnimationElement.prototype[name]; + const result = method.call(element, {valueOf() {conversions++; return 0.25;}}); + if (result !== undefined) throw Error(name + ' detached return value'); + if (conversions !== (name.endsWith('At') ? 1 : 0)) throw Error(name + ' argument conversion'); + if (element.getCurrentTime() !== 0) throw Error('detached animation cannot advance the timeline'); + if (name.endsWith('At')) { + for (const value of [NaN, Infinity, -Infinity, 1e100, Symbol(), 1n]) { + let error; + try { method.call(element, value); } catch (caught) { error = caught; } + if (Object.getPrototypeOf(error) !== realm.TypeError.prototype) throw Error(name + ' invalid float realm'); + } + let error; + try { method.call(element); } catch (caught) { error = caught; } + if (Object.getPrototypeOf(error) !== realm.TypeError.prototype) throw Error(name + ' required argument'); + const sentinel = {}; + try { method.call(element, {valueOf() {throw sentinel;}}); } catch (caught) { error = caught; } + if (error !== sentinel || element.getCurrentTime() !== 0) throw Error(name + ' original conversion exception'); + } + } + } + return true; + })() + "#).unwrap(), "true"); +} diff --git a/moli-renderer-v8/src/script_vm/tests/mod.rs b/moli-renderer-v8/src/script_vm/tests/mod.rs index cac87262cc1..b9dfaeb579c 100644 --- a/moli-renderer-v8/src/script_vm/tests/mod.rs +++ b/moli-renderer-v8/src/script_vm/tests/mod.rs @@ -2486,6 +2486,7 @@ mod svg_number_validation; mod svg_path_data; mod svg_redraw_methods; mod svg_root_factory_receivers; +mod svg_smil_path_timing; mod svg_switch_mpath_interfaces; mod svg_tree_queries; mod svg_uri_reference; diff --git a/moli-renderer-v8/src/script_vm/tests/svg_smil_path_timing.js b/moli-renderer-v8/src/script_vm/tests/svg_smil_path_timing.js new file mode 100644 index 00000000000..d7507d30a70 --- /dev/null +++ b/moli-renderer-v8/src/script_vm/tests/svg_smil_path_timing.js @@ -0,0 +1,80 @@ +(() => { + const checks=[], ns='http://www.w3.org/2000/svg', realms=[window,document.querySelector('iframe').contentWindow]; + const check=(name,fn)=>{try{checks.push({name,passed:fn()===true});}catch(error){checks.push({name,passed:false,error:String(error)});}}; + const raises=(realm,fn,name='TypeError')=>{try{fn();}catch(e){return Object.getPrototypeOf(e)===realm[name].prototype;}return false;}; + const values='M0 0L10 10;M20 40L50 70'; + const close=(a,b)=>Math.abs(a-b)<1e-4; + const coordinates=path=>(getComputedStyle(path).getPropertyValue('d').match(/-?\d+(?:\.\d+)?(?:e[+-]?\d+)?/gi)||[]).map(Number); + const equals=(a,b)=>a.length===b.length&&a.every((v,i)=>close(v,b[i])); + const make=(owner,attributes={})=>{ + const doc=owner.document, svg=doc.createElementNS(ns,'svg'),path=doc.createElementNS(ns,'path'),animation=doc.createElementNS(ns,'animate'); + path.setAttribute('d','M0 0L10 10'); + for(const [k,v] of Object.entries({attributeName:'d',dur:'10s',values,...attributes}))animation.setAttribute(k,v); + path.append(animation);svg.append(path);doc.body.append(svg);svg.pauseAnimations();svg.setCurrentTime(0);return {svg,path,animation}; + }; + for(const [ci,callee] of realms.entries()){ + const methods=['pauseAnimations','unpauseAnimations','animationsPaused','getCurrentTime','setCurrentTime']; + const invoke=(name,receiver,args=[])=>{ + const fn=Object.getOwnPropertyDescriptor(callee.SVGSVGElement.prototype,name)?.value; + if(typeof fn!=='function')throw Error('Missing SVGSVGElement.'+name); + return Reflect.apply(fn,receiver,args); + }; + for(const name of methods)check(`${ci}/smil/metadata/${name}`,()=>{ + const d=Object.getOwnPropertyDescriptor(callee.SVGSVGElement.prototype,name); + return typeof d?.value==='function'&&d.enumerable&&d.configurable&&d.writable&&d.value.name===name&& + d.value.length===(name==='setCurrentTime'?1:0)&&Object.getPrototypeOf(d.value)===callee.Function.prototype; + }); + for(const [oi,owner] of realms.entries()){ + const prefix=`${ci}/${oi}/smil/`, sample=(f,t)=>{invoke('setCurrentTime',f.svg,[t]);return coordinates(f.path);}; + check(prefix+'clock-pause-seek-resume',()=>{ + const f=make(owner);if(invoke('animationsPaused',f.svg)!==true)return false; + invoke('setCurrentTime',f.svg,[7]);invoke('pauseAnimations',f.svg); + if(invoke('getCurrentTime',f.svg)!==7||f.animation.getCurrentTime()!==7)return false; + invoke('unpauseAnimations',f.svg);if(invoke('animationsPaused',f.svg)!==false||invoke('getCurrentTime',f.svg)<7)return false; + invoke('pauseAnimations',f.svg);const t=invoke('getCurrentTime',f.svg);return invoke('getCurrentTime',f.svg)===t; + }); + check(prefix+'negative-seek-clamped',()=>{const f=make(owner);invoke('setCurrentTime',f.svg,[-5]);return invoke('getCurrentTime',f.svg)===0;}); + check(prefix+'binary32-seek-conversion',()=>{const f=make(owner);invoke('setCurrentTime',f.svg,[1.1]);return invoke('getCurrentTime',f.svg)===Math.fround(1.1);}); + check(prefix+'pending-seek-before-connection',()=>{const s=owner.document.createElementNS(ns,'svg');invoke('pauseAnimations',s);invoke('setCurrentTime',s,[17]);if(invoke('getCurrentTime',s)!==0)return false;owner.document.body.append(s);return invoke('getCurrentTime',s)===17;}); + check(prefix+'independent-fragments',()=>{const a=make(owner),b=make(owner);invoke('setCurrentTime',a.svg,[4]);invoke('setCurrentTime',b.svg,[9]);return invoke('getCurrentTime',a.svg)===4&&invoke('getCurrentTime',b.svg)===9;}); + for(const [time,expected] of [[0,[0,0,10,10]],[2.5,[5,10,20,25]],[5,[10,20,30,40]],[7.5,[15,30,40,55]]])check(prefix+'typed-path-at-'+time,()=>{ + const f=make(owner);const actual=sample(f,time),end=f.path.getPointAtLength(1e6); + return equals(actual,expected)&&close(end.x,expected[2])&&close(end.y,expected[3])&& + f.path.getAttribute('d')==='M0 0L10 10'&&equals(f.path.getPathData().flatMap(s=>s.values),[0,0,10,10]); + }); + check(prefix+'setPathData-updates-base-during-animation',()=>{ + const f=make(owner);sample(f,5);f.path.setPathData([{type:'M',values:[0,0]},{type:'L',values:[200,200]}]); + return f.path.getAttribute('d')==='M 0 0 L 200 200'&&equals(coordinates(f.path),[10,20,30,40])&& + equals(f.path.getPathData().flatMap(s=>s.values),[0,0,200,200]); + }); + check(prefix+'freeze-final-sample',()=>{const f=make(owner,{fill:'freeze'});return equals(sample(f,20),[20,40,50,70]);}); + check(prefix+'remove-restores-base',()=>{const f=make(owner);return equals(sample(f,20),[0,0,10,10]);}); + check(prefix+'fractional-repeat-freeze',()=>{const f=make(owner,{fill:'freeze',repeatCount:'2.5'});return equals(sample(f,25),[10,20,30,40]);}); + check(prefix+'repeat-interior-and-final',()=>{const f=make(owner,{fill:'freeze',repeatCount:'2'});return equals(sample(f,15),[10,20,30,40])&&equals(sample(f,20),[20,40,50,70]);}); + check(prefix+'values-keyTimes',()=>{const f=make(owner,{values:'M0 0L10 10;M20 40L50 70;M40 80L90 130',keyTimes:'0;0.25;1'});return equals(sample(f,2.5),[20,40,50,70])&&equals(sample(f,6.25),[30,60,70,100]);}); + check(prefix+'discrete-sampling',()=>{const f=make(owner,{calcMode:'discrete'});return equals(sample(f,4),[0,0,10,10])&&equals(sample(f,6),[20,40,50,70]);}); + check(prefix+'from-to-sampling',()=>{const f=make(owner,{from:'M10 20L30 40',to:'M30 40L50 60'});f.animation.removeAttribute('values');return equals(sample(f,5),[20,30,40,50]);}); + check(prefix+'to-only-uses-base',()=>{const f=make(owner,{to:'M20 40L50 70'});f.animation.removeAttribute('values');return equals(sample(f,5),[10,20,30,40]);}); + check(prefix+'DOM-begin-and-end-instance-times',()=>{ + const f=make(owner,{begin:'indefinite',fill:'freeze'});if(!raises(callee,()=>Reflect.apply(callee.SVGAnimationElement.prototype.getStartTime,f.animation,[]),'DOMException'))return false; + invoke('setCurrentTime',f.svg,[10]);Reflect.apply(callee.SVGAnimationElement.prototype.beginElementAt,f.animation,[2]); + if(f.animation.getStartTime()!==12)return false; + if(!equals(sample(f,17),[10,20,30,40]))return false; + Reflect.apply(callee.SVGAnimationElement.prototype.endElementAt,f.animation,[1]);return equals(sample(f,19),[12,24,34,46]); + }); + check(prefix+'immediate-begin-restarts',()=>{const f=make(owner,{begin:'indefinite'});invoke('setCurrentTime',f.svg,[3]);f.animation.beginElement();if(f.animation.getStartTime()!==3)return false;sample(f,8);f.animation.beginElement();invoke('setCurrentTime',f.svg,[8]);return f.animation.getStartTime()===8&&equals(coordinates(f.path),[0,0,10,10]);}); + check(prefix+'restart-never',()=>{const f=make(owner,{restart:'never'});sample(f,5);f.animation.beginElement();return f.animation.getStartTime()===0&&equals(coordinates(f.path),[10,20,30,40]);}); + check(prefix+'restart-whenNotActive',()=>{const f=make(owner,{restart:'whenNotActive'});sample(f,5);f.animation.beginElement();return f.animation.getStartTime()===0&&equals(coordinates(f.path),[10,20,30,40]);}); + check(prefix+'animated-href-target',()=>{const f=make(owner);f.path.id='smil-target-'+ci+'-'+oi;f.svg.append(f.animation);f.animation.setAttribute('href','#'+f.path.id);return equals(sample(f,5),[10,20,30,40]);}); + check(prefix+'attribute-removal-stops-sampling',()=>{const f=make(owner);sample(f,5);f.animation.remove();return equals(coordinates(f.path),[0,0,10,10]);}); + for(const [dur,expected] of [['250ms',.25],['2min',120],['1h',3600],['01:02:03.5',3723.5],['02:03.5',123.5],[' 3.5s ',3.5]])check(prefix+'duration-'+dur,()=>{const f=make(owner,{dur});return f.animation.getSimpleDuration()===Math.fround(expected);}); + for(const dur of ['indefinite','media','NaN','-1s','garbage'])check(prefix+'indefinite-duration-'+dur,()=>{const f=make(owner,{dur});try{f.animation.getSimpleDuration();}catch(e){return e.name==='NotSupportedError';}return false;}); + for(const value of [NaN,Infinity,-Infinity,1e100,Symbol(),1n])check(prefix+'invalid-time-'+String(value),()=>{const f=make(owner);invoke('setCurrentTime',f.svg,[4]);return raises(callee,()=>invoke('setCurrentTime',f.svg,[value]))&&invoke('getCurrentTime',f.svg)===4;}); + check(prefix+'conversion-before-seek-and-original-exception',()=>{const f=make(owner),sentinel={};invoke('setCurrentTime',f.svg,[4]);let old;invoke('setCurrentTime',f.svg,[{valueOf(){old=invoke('getCurrentTime',f.svg);return 7;}}]);try{invoke('setCurrentTime',f.svg,[{valueOf(){throw sentinel;}}]);}catch(e){return e===sentinel&&old===4&&invoke('getCurrentTime',f.svg)===7;}return false;}); + const f={svg:owner.document.createElementNS(ns,'svg'),path:owner.document.createElementNS(ns,'path')};f.svg.append(f.path);owner.document.body.append(f.svg);const revoked=Proxy.revocable(f.svg,{});revoked.revoke();let traps=0; + const invalid=[{},Object.create(callee.SVGSVGElement.prototype),Object.create(f.svg),new Proxy(f.svg,{get(){traps++;throw 42;},getPrototypeOf(){traps++;throw 42;}}),revoked.proxy,f.path,owner.document.createElement('div'),null,undefined]; + for(const [ri,receiver] of invalid.entries())for(const name of methods)check(prefix+'brand-'+ri+'-'+name,()=>{let conversion=0;return raises(callee,()=>invoke(name,receiver,[{valueOf(){conversion++;return 5;}}]))&&conversion===0&&traps===0;}); + } + } + globalThis.__svgSmilPathTimingResults={complete:true,total:checks.length,passed:checks.filter(c=>c.passed).length,checks};globalThis.__uiEventResults=__svgSmilPathTimingResults;return true; +})() diff --git a/moli-renderer-v8/src/script_vm/tests/svg_smil_path_timing.rs b/moli-renderer-v8/src/script_vm/tests/svg_smil_path_timing.rs new file mode 100644 index 00000000000..4e3e2664d2d --- /dev/null +++ b/moli-renderer-v8/src/script_vm/tests/svg_smil_path_timing.rs @@ -0,0 +1,99 @@ +use super::*; + +#[test] +fn svg_smil_path_sampling_preserves_base_values_and_webidl_contracts() { + let mut vm = new_storage_page_task_executor_test_vm("https://svg-smil-path-timing.test/"); + vm.set_document_ready_state(crate::dom::native::DocumentReadyState::Complete) + .unwrap(); + vm.eval("document.body.innerHTML = ''") + .unwrap(); + vm.eval(include_str!("svg_smil_path_timing.js")).unwrap(); + assert_eq!( + vm.eval("JSON.stringify(__svgSmilPathTimingResults.checks.filter(row => !row.passed))") + .unwrap(), + "[]" + ); + assert_eq!(vm.eval("__svgSmilPathTimingResults.complete && __svgSmilPathTimingResults.total === 358 && __svgSmilPathTimingResults.passed === 358").unwrap(), "true"); +} + +#[test] +fn svg_time_controls_use_registered_native_proxy_identity() { + let mut vm = new_storage_page_task_executor_test_vm("https://svg-smil-native-proxy.test/"); + vm.set_document_ready_state(crate::dom::native::DocumentReadyState::Complete) + .unwrap(); + vm.eval("document.body.innerHTML = ''; globalThis.svgReceiver = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); document.body.append(svgReceiver)").unwrap(); + let context = &vm.page_default_context as *const _; + vm.with_context_scope_by_ptr_and_checkpoint_for_test(context, |scope, _| { + let global = scope.get_current_context().global(scope); + let target = global + .get(scope, crate::util::v8str(scope, "svgReceiver").into()) + .unwrap(); + let target = v8::Local::::try_from(target).unwrap(); + let handler = crate::util::new_null_prototype_object(scope); + let proxy = v8::Proxy::new(scope, target, handler).unwrap(); + moli_webapi_declare::register_web_api_proxy(scope, proxy).unwrap(); + assert!(crate::web_api_interfaces::SVGSVGElement::is_instance( + scope, + proxy.into() + )); + assert_eq!( + global.create_data_property( + scope, + crate::util::v8str(scope, "svgNativeProxy").into(), + proxy.into() + ), + Some(true) + ); + Ok(()) + }) + .unwrap(); + assert_eq!(vm.eval(r#"(() => { + const realm = document.querySelector('iframe').contentWindow; + const P = realm.SVGSVGElement.prototype; + P.pauseAnimations.call(svgNativeProxy); + P.setCurrentTime.call(svgNativeProxy, 9); + if (P.getCurrentTime.call(svgReceiver) !== 9 || !P.animationsPaused.call(svgNativeProxy)) return false; + let conversions = 0, traps = 0; + const author = new Proxy(svgNativeProxy, {get() { traps++; throw 42; }, getPrototypeOf() { traps++; throw 42; }}); + const revoked = Proxy.revocable(svgNativeProxy, {}); revoked.revoke(); + for (const receiver of [author, revoked.proxy, Object.create(svgReceiver)]) { + try { P.setCurrentTime.call(receiver, {valueOf() { conversions++; return 3; }}); return false; } + catch (error) { if (Object.getPrototypeOf(error) !== realm.TypeError.prototype) return false; } + } + return conversions === 0 && traps === 0 && P.getCurrentTime.call(svgReceiver) === 9; + })()"#).unwrap(), "true"); +} + +#[test] +fn svg_fragment_clocks_preserve_pending_seek_and_document_begin() { + let mut vm = new_storage_page_task_executor_test_vm("https://svg-smil-document-begin.test/"); + vm.eval( + r#" + document.body.innerHTML = ''; + globalThis.rootSvg = document.getElementById('root'); + globalThis.nestedSvg = document.getElementById('nested'); + rootSvg.pauseAnimations(); rootSvg.setCurrentTime(7); + "#, + ) + .unwrap(); + assert_eq!(vm.eval("rootSvg.getCurrentTime()").unwrap(), "0"); + vm.set_document_ready_state(crate::dom::native::DocumentReadyState::Complete) + .unwrap(); + assert_eq!( + vm.eval( + r#"(() => { + if (rootSvg.getCurrentTime() !== 7 || nestedSvg.getCurrentTime() !== 7) return false; + nestedSvg.setCurrentTime(99); nestedSvg.unpauseAnimations(); + if (rootSvg.getCurrentTime() !== 7 || !nestedSvg.animationsPaused()) return false; + const windowless = document.implementation.createHTMLDocument(''); + const svg = windowless.createElementNS('http://www.w3.org/2000/svg', 'svg'); + windowless.body.append(svg); svg.pauseAnimations(); svg.setCurrentTime(9); + if (svg.getCurrentTime() !== 0) return false; + document.body.append(svg); + return svg.getCurrentTime() === 9 && svg.animationsPaused(); + })()"# + ) + .unwrap(), + "true" + ); +} diff --git a/moli-renderer-v8/src/style_engine/computed.rs b/moli-renderer-v8/src/style_engine/computed.rs index eee517b4446..331146623a3 100644 --- a/moli-renderer-v8/src/style_engine/computed.rs +++ b/moli-renderer-v8/src/style_engine/computed.rs @@ -166,6 +166,15 @@ pub(crate) struct ComputedRenderedStyleFacts { } impl StyloComputedStyleSnapshot { + pub(crate) fn with_svg_path( + mut self, + path: style::values::specified::svg_path::SVGPathData, + ) -> Self { + ServoArc::make_mut(&mut self.primary) + .mutate_svg() + .set_d(style::values::computed::DProperty::Path(path)); + self + } fn from_primary(primary: ServoArc) -> Self { Self { primary, diff --git a/moli-svg/src/lib.rs b/moli-svg/src/lib.rs index d60d9e1c35f..014df6f430d 100644 --- a/moli-svg/src/lib.rs +++ b/moli-svg/src/lib.rs @@ -3,6 +3,7 @@ mod helpers; mod length; mod matrix; mod path; +mod timing; mod transform; pub use geometry::{ @@ -16,6 +17,10 @@ pub use length::{ }; pub use matrix::{SvgMatrixComponents, serialize_number}; pub use path::{SvgPathSegment, parse_path_segments}; +pub use timing::{ + SvgAnimationInstanceTimes, SvgAnimationInterval, SvgAnimationRestart, SvgAnimationTiming, + SvgPresentationClock, parse_clock_value, +}; pub use transform::{ SvgTransform, SvgTransformKind, consolidate_transform_matrices, parse_transform_attribute, serialize_transform_list, diff --git a/moli-svg/src/timing.rs b/moli-svg/src/timing.rs new file mode 100644 index 00000000000..a8d0ecb5581 --- /dev/null +++ b/moli-svg/src/timing.rs @@ -0,0 +1,316 @@ +//! Presentation clocks and interval evaluation for SVG declarative animation. +//! Wall time is supplied by the owner, so seeking never rewrites DOM attributes +//! and paused clocks can be sampled deterministically. + +#[derive(Debug, Default)] +pub struct SvgPresentationClock { + started: bool, + paused: bool, + position: f64, + anchor: f64, +} + +impl SvgPresentationClock { + pub fn start(&mut self, now: f64) { + if !self.started { + self.started = true; + self.anchor = now; + } + } + + pub fn current_time(&self, now: f64) -> f64 { + if !self.started { + 0.0 + } else if self.paused { + self.position + } else { + self.position + (now - self.anchor).max(0.0) + } + } + + pub fn seek(&mut self, now: f64, seconds: f64) { + self.position = seconds.max(0.0); + self.anchor = now; + } + + pub fn pause(&mut self, now: f64) { + if !self.paused { + if self.started { + self.position = self.current_time(now); + } + self.anchor = now; + self.paused = true; + } + } + + pub fn unpause(&mut self, now: f64) { + if self.paused { + self.anchor = now; + self.paused = false; + } + } + + pub fn is_paused(&self) -> bool { + self.paused + } + + pub fn has_started(&self) -> bool { + self.started + } +} + +/// SMIL clock values. Offsets may have a sign; simple durations may not. +/// Reject non-grammar Rust float spellings such as NaN, infinity and exponents. +pub fn parse_clock_value(raw: &str) -> Option { + let raw = raw.trim_matches(|c: char| c.is_ascii_whitespace()); + let (sign, raw) = if let Some(raw) = raw.strip_prefix('-') { + (-1.0, raw) + } else { + (1.0, raw.strip_prefix('+').unwrap_or(raw)) + }; + fn decimal(raw: &str) -> Option { + let mut dots = 0; + let mut digits = 0; + for c in raw.bytes() { + if c == b'.' { + dots += 1; + } else if c.is_ascii_digit() { + digits += 1; + } else { + return None; + } + } + if digits == 0 || dots > 1 { + return None; + } + raw.parse::().ok().filter(|v| v.is_finite()) + } + let parts: Vec<_> = raw.split(':').collect(); + let seconds = match parts.as_slice() { + [offset] => { + let (number, scale) = if let Some(n) = offset.strip_suffix("ms") { + (n, 0.001) + } else if let Some(n) = offset.strip_suffix("min") { + (n, 60.0) + } else if let Some(n) = offset.strip_suffix('h') { + (n, 3600.0) + } else { + (offset.strip_suffix('s').unwrap_or(offset), 1.0) + }; + decimal(number)? * scale + } + [minutes, seconds] | [_, minutes, seconds] => { + if minutes.len() != 2 || !minutes.bytes().all(|c| c.is_ascii_digit()) { + return None; + } + let whole_seconds = seconds.split('.').next()?; + if whole_seconds.len() != 2 || !whole_seconds.bytes().all(|c| c.is_ascii_digit()) { + return None; + } + let minutes = decimal(minutes)?; + let seconds = decimal(seconds)?; + if minutes >= 60.0 || seconds >= 60.0 { + return None; + } + let hours = if parts.len() == 3 { + if parts[0].len() < 2 || !parts[0].bytes().all(|c| c.is_ascii_digit()) { + return None; + } + decimal(parts[0])? + } else { + 0.0 + }; + hours * 3600.0 + minutes * 60.0 + seconds + } + _ => return None, + }; + seconds.is_finite().then_some(sign * seconds) +} + +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub enum SvgAnimationRestart { + #[default] + Always, + WhenNotActive, + Never, +} + +#[derive(Clone, Debug, Default)] +pub struct SvgAnimationInstanceTimes { + pub begins: Vec, + pub ends: Vec, +} + +#[derive(Debug)] +pub struct SvgAnimationTiming { + pub begins: Vec, + pub ends: Vec, + pub simple_duration: f64, + pub repeat_count: f64, + pub repeat_duration: f64, + pub freeze: bool, + pub restart: SvgAnimationRestart, +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct SvgAnimationInterval { + pub begin: f64, + pub end: f64, +} + +impl SvgAnimationTiming { + pub fn intervals(&self, instances: &SvgAnimationInstanceTimes) -> Vec { + let mut begins = self.begins.clone(); + begins.extend_from_slice(&instances.begins); + begins.sort_by(f64::total_cmp); + begins.dedup(); + let mut ends = self.ends.clone(); + ends.extend_from_slice(&instances.ends); + ends.sort_by(f64::total_cmp); + let duration = (self.simple_duration * self.repeat_count).min(self.repeat_duration); + let mut intervals: Vec = Vec::new(); + for begin in begins { + if let Some(previous) = intervals.last_mut() { + match self.restart { + SvgAnimationRestart::Never => break, + SvgAnimationRestart::WhenNotActive if begin < previous.end => continue, + _ => previous.end = previous.end.min(begin), + } + } + let end = ends + .iter() + .copied() + .find(|end| *end >= begin) + .unwrap_or(f64::INFINITY) + .min(begin + duration); + intervals.push(SvgAnimationInterval { begin, end }); + } + intervals + } + + pub fn current_interval( + &self, + instances: &SvgAnimationInstanceTimes, + time: f64, + ) -> Option { + self.intervals(instances) + .into_iter() + .find(|interval| interval.end > time) + } + + pub fn sample_progress(&self, instances: &SvgAnimationInstanceTimes, time: f64) -> Option { + let interval = self + .intervals(instances) + .into_iter() + .rev() + .find(|interval| interval.begin <= time)?; + let finished = time >= interval.end; + if finished && !self.freeze { + return None; + } + let elapsed = time.min(interval.end) - interval.begin; + if self.simple_duration == 0.0 { + return Some(1.0); + } + if !self.simple_duration.is_finite() { + return Some(0.0); + } + let fraction = (elapsed / self.simple_duration).fract(); + Some(if finished && fraction == 0.0 && elapsed > 0.0 { + 1.0 + } else { + fraction + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn presentation_clock_preserves_pending_seek_and_pause_continuity() { + let mut clock = SvgPresentationClock::default(); + clock.seek(2.0, 7.0); + clock.pause(3.0); + assert_eq!(clock.current_time(4.0), 0.0); + clock.start(10.0); + assert_eq!(clock.current_time(20.0), 7.0); + clock.unpause(20.0); + assert_eq!(clock.current_time(21.5), 8.5); + clock.pause(22.0); + clock.pause(30.0); + assert_eq!(clock.current_time(100.0), 9.0); + clock.seek(100.0, -5.0); + assert_eq!(clock.current_time(200.0), 0.0); + } + + #[test] + fn clock_values_validate_grammar_and_units() { + for (raw, seconds) in [ + ("250ms", 0.25), + ("2min", 120.0), + ("1h", 3600.0), + ("01:02:03.5", 3723.5), + ("02:03.5", 123.5), + (" +3.5s ", 3.5), + ("-0.5s", -0.5), + (".5", 0.5), + ] { + assert_eq!(parse_clock_value(raw), Some(seconds), "{raw}"); + } + for raw in [ + "", "NaN", "Infinity", "1e2", "1 2", "1:02", "01:60", "01:00:60", "1:00:00", "1ss", + "1..2", + ] { + assert_eq!(parse_clock_value(raw), None, "{raw}"); + } + } + + fn timing() -> SvgAnimationTiming { + SvgAnimationTiming { + begins: vec![0.0], + ends: vec![], + simple_duration: 10.0, + repeat_count: 2.5, + repeat_duration: f64::INFINITY, + freeze: true, + restart: SvgAnimationRestart::Always, + } + } + + #[test] + fn repeating_intervals_freeze_at_the_fractional_final_sample() { + let timing = timing(); + let instances = SvgAnimationInstanceTimes::default(); + for (time, progress) in [ + (5.0, 0.5), + (10.0, 0.0), + (15.0, 0.5), + (25.0, 0.5), + (50.0, 0.5), + ] { + assert_eq!(timing.sample_progress(&instances, time), Some(progress)); + } + let mut timing = timing; + timing.repeat_count = 2.0; + assert_eq!(timing.sample_progress(&instances, 20.0), Some(1.0)); + timing.freeze = false; + assert_eq!(timing.sample_progress(&instances, 20.0), None); + } + + #[test] + fn instance_times_obey_restart_and_end_constraints() { + let mut timing = timing(); + let instances = SvgAnimationInstanceTimes { + begins: vec![5.0, 30.0], + ends: vec![33.0], + }; + assert_eq!(timing.current_interval(&instances, 6.0).unwrap().begin, 5.0); + assert_eq!(timing.sample_progress(&instances, 34.0), Some(0.3)); + timing.restart = SvgAnimationRestart::WhenNotActive; + assert_eq!(timing.current_interval(&instances, 6.0).unwrap().begin, 0.0); + timing.restart = SvgAnimationRestart::Never; + assert_eq!(timing.current_interval(&instances, 30.0), None); + } +}