Skip to content

Truly independent web browser

LibWeb: Move timelines and CSS animation updates to Rust

Andreas Klingb8a2e08b7224
diff --git a/Libraries/LibCompositing/Rust/src/animation_timing/calculations.rs b/Libraries/LibCompositing/Rust/src/animation_timing/calculations.rs
index 17907864cbd..025b351d285 100644
--- a/Libraries/LibCompositing/Rust/src/animation_timing/calculations.rs
+++ b/Libraries/LibCompositing/Rust/src/animation_timing/calculations.rs
@@ -52,8 +52,8 @@ pub fn intrinsic_iteration_duration(
Some(_) if iteration_count == 0.0 => TimeValue::zero(time_unit),
// Otherwise
Some(timeline_duration) => {
- // Return(100% - start delay - end delay) / iteration count
- // Note : Presently start and end delays are zero until such time as percentage based delays are supported.
+ // Return (100% - start delay - end delay) / iteration count
+ // Note: Presently start and end delays are zero until such time as percentage based delays are supported.
// AD-HOC: An effect fills its animation's attachment range rather than the whole timeline, which is what the
// timeline duration is here. This matches WebKit.
(timeline_duration - start_delay - end_delay) / iteration_count
@@ -71,7 +71,7 @@ pub fn convert_a_time_based_animation_to_a_proportional_animation(
) -> AnimationEffectTiming {
let mut timing = specified_timing_with(specified, TimeValue::zero(time_unit));
- // AD-HOC: We use the specified interation duration instead of the iteration duration here, see
+ // AD-HOC: We use the specified iteration duration instead of the iteration duration here, see
// https://github.com/w3c/csswg-drafts/pull/13170
// If the iteration duration is auto, then perform the following steps.
let Some(specified_iteration_duration) = specified.iteration_duration.time() else {
@@ -173,7 +173,7 @@ pub fn normalize_specified_timing(
timing.end_delay = TimeValue::milliseconds(specified.end_delay);
// 3. If iteration duration is auto:
- // AD-HOC: We use the specified interation duration instead of the iteration duration here, see
+ // AD-HOC: We use the specified iteration duration instead of the iteration duration here, see
// https://github.com/w3c/csswg-drafts/pull/13170
timing.iteration_duration = match specified.iteration_duration.time() {
// Set iteration duration = intrinsic iteration duration
@@ -196,8 +196,8 @@ pub fn normalize_specified_timing(
#[inline]
#[must_use]
pub fn animation_direction(animation: Option<&AnimationPlayback>) -> AnimationDirection {
- // "backwards" if the effect is associated with an animation and the associated animation’s playback rate is less
- // than zero; in all other cases, the animation direction is "forwards".
+ // “backwards” if the effect is associated with an animation and the associated animation’s playback rate is less
+ // than zero; in all other cases, the animation direction is “forward”.
match animation {
Some(animation) if animation.playback_rate < 0.0 => AnimationDirection::Backwards,
_ => AnimationDirection::Forwards,
@@ -208,10 +208,12 @@ pub fn animation_direction(animation: Option<&AnimationPlayback>) -> AnimationDi
#[inline]
#[must_use]
pub fn active_duration(timing: &AnimationEffectTiming) -> TimeValue {
- // The active duration is calculated as follows:
+ // The length of the active interval is called the active duration, and is determined by the iteration duration and
+ // iteration count as defined below.
// active duration = iteration duration × iteration count
- // If either the iteration duration or iteration count are zero, the active duration is zero. This clarification is
- // needed since the result of infinity multiplied by zero is undefined according to IEEE 754-2008.
+ // If either the iteration duration or iteration count are zero, the active duration is zero.
+ // Note: This clarification is needed since the result of infinity multiplied by zero is undefined according to
+ // IEEE 754-2008.
if timing.iteration_duration.value == 0.0 || timing.iteration_count == 0.0 {
return timing.zero();
}
@@ -222,8 +224,8 @@ pub fn active_duration(timing: &AnimationEffectTiming) -> TimeValue {
#[inline]
#[must_use]
pub fn end_time(timing: &AnimationEffectTiming) -> TimeValue {
- // 1. The end time of an animation effect is the result of evaluating
- // max(start delay + active duration + end delay, 0).
+ // The end time, of an animation effect is the result of evaluating
+ // max(start delay + active duration + end delay, 0).
max(
timing.start_delay + active_duration(timing) + timing.end_delay,
timing.zero(),
@@ -327,8 +329,8 @@ pub fn phase(
}
// https://www.w3.org/TR/web-animations-1/#animation-effect-active-phase
- // An animation effect is in the active phase if the animation effect’s local time is not unresolved and it is not
- // in either the before phase nor the after phase.
+ // An animation effect is in the active phase if the animation effect’s local time is not unresolved and it is
+ // neither in the before phase nor in the after phase.
AnimationEffectPhase::Active
}
@@ -400,7 +402,7 @@ pub fn overall_progress(
// 1. If the active time is unresolved, return unresolved.
let active_time = active_time?;
- // 2. Calculate an initial value for overall progress based on the first matching condition from below,
+ // 2. Calculate an initial value for overall progress based on the first matching condition below:
// -> If the iteration duration is zero,
let overall_progress = if timing.iteration_duration.value == 0.0 {
// If the animation effect is in the before phase, let overall progress be zero, otherwise, let it be equal to
@@ -513,7 +515,7 @@ pub fn simple_iteration_progress(timing: &AnimationEffectTiming, resolved: &Reso
Some(simple_iteration_progress)
}
-/// https://www.w3.org/TR/web-animations-1/#current-iteration
+/// https://drafts.csswg.org/web-animations-1/#current-iteration-index
#[must_use]
pub fn current_iteration(timing: &AnimationEffectTiming, resolved: &ResolvedEffectTiming) -> Option<f64> {
current_iteration_with(timing, resolved, || simple_iteration_progress(timing, resolved))
@@ -571,7 +573,7 @@ fn current_direction_with(
// -> Otherwise,
PlaybackDirection::Alternate | PlaybackDirection::AlternateReverse => {
- // 1. Let d be the current iteration.
+ // 1. Let d be the current iteration index.
let mut d = current_iteration_with(timing, resolved, simple_iteration_progress)
.expect("an effect with a resolved simple iteration progress has a current iteration");
@@ -644,7 +646,7 @@ pub fn transformed_progress_with(
// 2. Calculate the value of the before flag as follows:
- // 1. Determine the current direction using the procedure defined in §4.9.1 Calculating the directed progress.
+ // 1. Determine the current direction using the procedure defined in Calculating the directed progress.
// NB: Calculating the directed progress in step 1 determined it.
// 2. If the current direction is forwards, let going forwards be true, otherwise it is false.
@@ -655,8 +657,8 @@ pub fn transformed_progress_with(
let before_flag = (resolved.phase == AnimationEffectPhase::Before && going_forwards)
|| (resolved.phase == AnimationEffectPhase::After && !going_forwards);
- // 3. Return the result of evaluating the animation effect’s timing function passing directed progress as the input
- // progress value and before flag as the before flag.
+ // 3. Return the result of evaluating the effect easing function passing directed progress as the input progress
+ // value and before flag as the before flag.
Some(evaluate_timing_function(directed_progress, before_flag))
}
@@ -691,14 +693,12 @@ pub fn is_current(
};
let playback_rate = animation.playback_rate;
- // - the animation effect is associated with an animation with a playback rate > 0 and the animation effect is
- // in the before phase, or
+ // - the animation effect is in the before phase and is associated with an animation with a playback rate > 0, or
if playback_rate > 0.0 && phase == AnimationEffectPhase::Before {
return true;
}
- // - the animation effect is associated with an animation with a playback rate < 0 and the animation effect is
- // in the after phase, or
+ // - the animation effect is in the after phase and is associated with an animation with a playback rate < 0, or
if playback_rate < 0.0 && phase == AnimationEffectPhase::After {
return true;
}
@@ -714,8 +714,8 @@ pub fn is_current(
#[inline]
#[must_use]
pub fn is_in_effect(resolved: &ResolvedEffectTiming) -> bool {
- // An animation effect is in effect if its active time, as calculated according to the procedure in
- // §4.8.3.1 Calculating the active time, is not unresolved.
+ // An animation effect is in effect if its active time, as calculated according to the procedure in Calculating the
+ // active time, is not unresolved.
resolved.active_time.is_some()
}
@@ -725,7 +725,7 @@ pub fn is_in_effect(resolved: &ResolvedEffectTiming) -> bool {
#[inline]
#[must_use]
pub fn current_time_at(animation: &AnimationPlayback, timeline_time: Option<TimeValue>) -> Option<TimeValue> {
- // The current time is calculated from the first matching condition from below:
+ // The current time is calculated from the first matching condition below:
// -> If the animation’s hold time is resolved,
if let Some(hold_time) = animation.hold_time.get() {
@@ -743,7 +743,7 @@ pub fn current_time_at(animation: &AnimationPlayback, timeline_time: Option<Time
// -> Otherwise,
// current time = (timeline time - start time) × playback rate
// Where timeline time is the current time value of the associated timeline. The playback rate value is defined
- // in §4.4.15 Speed control.
+ // in Speed control.
Some((timeline_time - start_time) * animation.playback_rate)
}
diff --git a/Libraries/LibCompositing/Rust/src/animation_timing/time_value.rs b/Libraries/LibCompositing/Rust/src/animation_timing/time_value.rs
index cb999293e82..84fe73ec613 100644
--- a/Libraries/LibCompositing/Rust/src/animation_timing/time_value.rs
+++ b/Libraries/LibCompositing/Rust/src/animation_timing/time_value.rs
@@ -215,18 +215,6 @@ impl From<Option<f64>> for OptionalNumber {
mod tests {
use super::*;
- #[test]
- fn arithmetic_keeps_the_unit() {
- let a = TimeValue::percentage(30.0);
- let b = TimeValue::percentage(10.0);
- assert_eq!(a + b, TimeValue::percentage(40.0));
- assert_eq!(a - b, TimeValue::percentage(20.0));
- assert_eq!(a * 2.0, TimeValue::percentage(60.0));
- assert_eq!(a / 2.0, TimeValue::percentage(15.0));
- assert_eq!(a / b, 3.0);
- assert_eq!(-a, TimeValue::percentage(-30.0));
- }
-
#[test]
#[should_panic(expected = "different units")]
fn mixed_unit_arithmetic_panics() {
@@ -239,11 +227,6 @@ mod tests {
let _ = TimeValue::percentage(30.0) < TimeValue::milliseconds(10.0);
}
- #[test]
- fn mixed_unit_values_are_not_equal() {
- assert_ne!(TimeValue::percentage(0.0), TimeValue::milliseconds(0.0));
- }
-
#[test]
fn nan_orders_equal_and_max_keeps_the_first() {
let nan = TimeValue::milliseconds(f64::NAN);
@@ -254,13 +237,4 @@ mod tests {
assert!(max(f64::NAN, 0.0).is_nan());
assert_eq!(min(1.0, 2.0), 1.0);
}
-
- #[test]
- fn optionals_round_trip() {
- let time = TimeValue::milliseconds(5.0);
- assert_eq!(OptionalTimeValue::from(Some(time)).get(), Some(time));
- assert_eq!(OptionalTimeValue::from(None).get(), None);
- assert_eq!(OptionalNumber::from(Some(2.5)).get(), Some(2.5));
- assert_eq!(OptionalNumber::from(None).get(), None);
- }
}
diff --git a/Libraries/LibCompositing/Rust/src/visual_animation.rs b/Libraries/LibCompositing/Rust/src/visual_animation.rs
index 4ab84e555a0..5c5d142be1b 100644
--- a/Libraries/LibCompositing/Rust/src/visual_animation.rs
+++ b/Libraries/LibCompositing/Rust/src/visual_animation.rs
@@ -535,8 +535,8 @@ impl VisualAnimation {
if !local_time.is_finite() {
return None;
}
- // The compositor runs the animation at its playback rate from where the main thread anchored it, which holds
- // its local time.
+ // NB: The compositor runs the animation at its playback rate from where the main thread anchored it, which
+ // holds its local time.
let local_time = Some(TimeValue::milliseconds(local_time));
let playback = AnimationPlayback {
hold_time: OptionalTimeValue::from(local_time),
diff --git a/Libraries/LibWeb/Animations/Animatable.cpp b/Libraries/LibWeb/Animations/Animatable.cpp
index 75e09bc4d8d..28f54c960be 100644
--- a/Libraries/LibWeb/Animations/Animatable.cpp
+++ b/Libraries/LibWeb/Animations/Animatable.cpp
@@ -8,9 +8,6 @@
#include "Animatable.h"
#include <LibJS/HostClassBuilder.h>
-#include <LibWeb/Animations/AnimationTimeline.h>
-#include <LibWeb/CSS/CSSAnimation.h>
-#include <LibWeb/CSS/CSSTransition.h>
#include <LibWeb/CSS/StyleComputer.h>
#include <LibWeb/CSS/StyleEngineInput.h>
#include <LibWeb/DOM/AbstractElement.h>
@@ -24,44 +21,39 @@ namespace Web::Animations {
extern "C" {
// Called from Bindings/Rust/src/animations/animatable.rs.
-void web_animation_for_each_relevant_animation(JSObject* node_wrapper, bool subtree, void* context, void (*on_animation)(void* context, RustFFI::AnimationCell const*));
+void web_animation_for_each_associated_animation(JSObject* node_wrapper, bool subtree, void* context, void (*on_animation)(void* context, RustFFI::AnimationCell const*));
i32 web_animation_compare_elements_in_tree_order(void* first, void* second);
}
-void Animatable::for_each_relevant_animation(IncludeSubtree include_subtree, Function<void(AnimationRef const&)> const& callback) const
+// The associated animations of `element`, and of its descendants where `subtree` is set.
+static void for_each_associated_animation(DOM::Element const& element, bool subtree, Function<void(AnimationRef const&)> const& callback)
{
- for (auto const& record : associated_animations_unordered()) {
- // AD-HOC: SVG animation elements drive their animations with their own timing model, which script must not
- // be able to play, pause or cancel. Like other engines, do not expose them.
- if (record.timing_state().kind == RustFFI::FfiAnimationKind::Smil)
- continue;
- if (record.is_relevant())
- callback(record);
- }
+ for (auto const& record : element.associated_animations_unordered())
+ callback(record);
- if (include_subtree == IncludeSubtree::Yes) {
- static_cast<DOM::Element const*>(this)->for_each_child_of_type<DOM::Element>([&](auto const& child) {
- child.for_each_relevant_animation(IncludeSubtree::Yes, callback);
+ if (subtree) {
+ element.for_each_child_of_type<DOM::Element>([&](auto const& child) {
+ for_each_associated_animation(child, true, callback);
return IterationDecision::Continue;
});
}
}
-// NB: The Rust implementations of getAnimations() collect the relevant animations of an element, or of the subtree of a
-// node where `subtree` is set, with this, after the pending style changes are applied, and sort them themselves.
-void web_animation_for_each_relevant_animation(JSObject* node_wrapper, bool subtree, void* context, void (*on_animation)(void* context, RustFFI::AnimationCell const*))
+// NB: The Rust implementations of getAnimations() collect the associated animations of an element, or of the subtree
+// of a node where `subtree` is set, with this, after the pending style changes are applied, and keep the relevant
+// ones and sort them themselves.
+void web_animation_for_each_associated_animation(JSObject* node_wrapper, bool subtree, void* context, void (*on_animation)(void* context, RustFFI::AnimationCell const*))
{
auto& node = *Bindings::impl_from<DOM::Node>(JS::HostABI::object_from_abi(node_wrapper));
node.document().update_style();
- auto include_subtree = subtree ? Animatable::IncludeSubtree::Yes : Animatable::IncludeSubtree::No;
Function<void(AnimationRef const&)> push = [&](AnimationRef const& animation) { on_animation(context, &animation.record()); };
if (auto const* element = as_if<DOM::Element>(node)) {
- element->for_each_relevant_animation(include_subtree, push);
+ for_each_associated_animation(*element, subtree, push);
return;
}
- VERIFY(include_subtree == Animatable::IncludeSubtree::Yes);
+ VERIFY(subtree);
as<DOM::ParentNode>(node).for_each_child_of_type<DOM::Element>([&](auto const& child) {
- child.for_each_relevant_animation(Animatable::IncludeSubtree::Yes, push);
+ for_each_associated_animation(child, true, push);
return IterationDecision::Continue;
});
}
@@ -71,8 +63,7 @@ i32 web_animation_compare_elements_in_tree_order(void* first, void* second)
return compare_elements_in_tree_order_for_composite_order(first, second);
}
-// The list of the element, or of one of its known pseudo-elements, of the CSS animations and transitions it owns.
-static Optional<RustFFI::AnimationOwnerSlot> owner_slot(Optional<CSS::PseudoElement> pseudo_element)
+Optional<RustFFI::AnimationOwnerSlot> Animatable::owner_slot(Optional<CSS::PseudoElement> pseudo_element)
{
if (!pseudo_element.has_value())
return RustFFI::AnimationOwnerSlot { 0 };
@@ -81,14 +72,6 @@ static Optional<RustFFI::AnimationOwnerSlot> owner_slot(Optional<CSS::PseudoElem
return RustFFI::AnimationOwnerSlot { static_cast<u8>(to_underlying(*pseudo_element) + 1) };
}
-static RustFFI::FfiTransitionProperty transition_property(CSS::PropertyNameAndID const& property)
-{
- return {
- .property_id = to_underlying(property.id()),
- .custom_name = property.is_custom_property() ? property.name().raw_identity() : 0,
- };
-}
-
Animatable::~Animatable()
{
finalize_animations();
@@ -136,50 +119,37 @@ bool Animatable::has_associated_animations() const
return !associated_animations_unordered().is_empty();
}
-size_t Animatable::animation_lists_memory_size() const
-{
- return m_animations ? RustFFI::animations_element_animations_memory_size(m_animations) : 0;
-}
-
-bool Animatable::has_relevant_animations() const
+size_t Animatable::animation_record_memory_size(bool (*first_counted)(void*, RustFFI::KeyframeSet const*), void* context) const
{
- for (auto const& animation : associated_animations_unordered()) {
- if (animation.is_relevant())
- return true;
- }
- return false;
+ return m_animations ? RustFFI::animations_element_animations_record_memory_size(m_animations, first_counted, context) : 0;
}
void Animatable::associate_with_animation(AnimationRef const& animation)
{
- if (!RustFFI::animations_element_animations_associate(&ensure_animations(), &animation.record()))
+ auto& element = as<DOM::Element>(*this);
+ if (!RustFFI::animations_element_animations_associate(&ensure_animations(), &element.document().document_animations(), &animation.record(), element.document().is_in_style_stabilization_epoch()))
return;
// The style engine computes no record for an element whose animations compose its style.
- CSS::record_element_animations_changed(as<DOM::Element>(*this));
-
- as<DOM::Element>(*this).change_associated_animation_count_in_subtree(1);
- CSS::record_element_associated_with_animation(as<DOM::Element>(*this));
+ CSS::record_element_animations_changed(element);
- as<DOM::Element>(*this).document().associate_with_animation(animation);
+ element.change_associated_animation_count_in_subtree(1);
+ CSS::record_element_associated_with_animation(element);
}
void Animatable::disassociate_with_animation(AnimationRef const& animation, Optional<EffectRef> const& effect)
{
- auto was_associated = m_animations && RustFFI::animations_element_animations_disassociate(m_animations, &animation.record());
- CSS::record_element_animations_changed(as<DOM::Element>(*this));
+ auto& element = as<DOM::Element>(*this);
+ auto was_associated = RustFFI::animations_element_animations_disassociate(m_animations, &element.document().document_animations(), &animation.record(), effect.has_value() ? &effect->record() : nullptr);
+ CSS::record_element_animations_changed(element);
if (was_associated)
- as<DOM::Element>(*this).change_associated_animation_count_in_subtree(-1);
-
- as<DOM::Element>(*this).document().disassociate_with_animation(animation, effect);
+ element.change_associated_animation_count_in_subtree(-1);
}
void Animatable::on_document_changed(DOM::Document& old_document, DOM::Document& new_document)
{
- for (auto const& animation : associated_animations_unordered()) {
- old_document.disassociate_with_animation(animation, animation.effect());
- new_document.associate_with_animation(animation);
- }
+ if (m_animations)
+ RustFFI::animations_element_animations_move_to_document(m_animations, &old_document.document_animations(), &new_document.document_animations(), new_document.is_in_style_stabilization_epoch());
}
// The computation of an element's animation definitions matches them against the animations the element already has,
@@ -204,12 +174,7 @@ void Animatable::cancel_css_animations_and_transitions()
GC::RootVector<AnimationRef> animations;
RustFFI::animations_element_animations_cancel_css_animations_and_transitions(
- m_animations, style_engine_host_of(*this), style_node_of(*this), keep_animation_alive_in,
- [](void*, RustFFI::AnimationCell const* animation, void (*run)(void*), void* run_context) {
- HTML::TemporaryExecutionContext execution_context { HTML::relevant_realm(relevant_global_object_of(AnimationRef { *animation })) };
- run(run_context);
- },
- &animations, perform_host_effect);
+ m_animations, style_engine_host_of(*this), style_node_of(*this), keep_animation_alive_in, in_execution_context_of_animation, &animations, web_animation_perform_host_effect);
}
void Animatable::play_or_pause_css_animations_as_their_play_state_asks()
@@ -230,7 +195,7 @@ void Animatable::play_or_pause_css_animations_as_their_play_state_asks()
HTML::TemporaryExecutionContext execution_context { static_cast<Context*>(context)->element->document().relevant_settings_object() };
run(run_context);
},
- &context, perform_host_effect);
+ &context, web_animation_perform_host_effect);
}
bool Animatable::has_matching_transition_property_entry(Optional<CSS::PseudoElement> pseudo_element) const
@@ -243,39 +208,9 @@ bool Animatable::has_matching_transition_property_entry(Optional<CSS::PseudoElem
}
bool Animatable::has_existing_transitions(Optional<CSS::PseudoElement> pseudo_element) const
-{
- return !existing_transitions(pseudo_element).is_empty();
-}
-
-ElementAnimationList Animatable::existing_transitions(Optional<CSS::PseudoElement> pseudo_element) const
{
auto slot = owner_slot(pseudo_element);
- return { slot.has_value() ? m_animations : nullptr, RustFFI::ElementAnimationListKind::Transitions, slot.value_or(0) };
-}
-
-Optional<AnimationRef> Animatable::property_transition(Optional<CSS::PseudoElement> pseudo_element, CSS::PropertyNameAndID const& property) const
-{
- auto slot = owner_slot(pseudo_element);
- if (!m_animations || !slot.has_value())
- return {};
- auto const* transition = RustFFI::animations_element_animations_transition(m_animations, *slot, transition_property(property));
- if (!transition)
- return {};
- return AnimationRef { *transition };
-}
-
-void Animatable::commit_provisional_transition(Optional<CSS::PseudoElement> pseudo_element, AnimationRef const& transition, RustFFI::TransitionOrigin origin)
-{
- // NB: The record associates the transition with this element, its target, and holds it here where this element or
- // pseudo-element can own transitions.
- auto slot = owner_slot(pseudo_element);
- RustFFI::animations_css_transition_commit_provisional(&transition.record(), slot.has_value() ? &ensure_animations() : nullptr, slot.value_or(RustFFI::AnimationOwnerSlot { 0 }), origin, perform_host_effect);
-}
-
-void Animatable::remove_transition(Optional<CSS::PseudoElement> pseudo_element, CSS::PropertyNameAndID const& property)
-{
- if (auto slot = owner_slot(pseudo_element); slot.has_value())
- RustFFI::animations_element_animations_remove_transition(&ensure_animations(), *slot, transition_property(property));
+ return m_animations && slot.has_value() && RustFFI::animations_element_animations_count(m_animations, RustFFI::ElementAnimationListKind::Transitions, *slot) != 0;
}
void Animatable::visit_edges(JS::Cell::Visitor& visitor)
@@ -285,11 +220,6 @@ void Animatable::visit_edges(JS::Cell::Visitor& visitor)
RustFFI::animations_element_animations_for_each_host_cell(m_animations, &visitor, visit_host_cell);
}
-bool Animatable::can_own_css_animations_and_transitions(Optional<CSS::PseudoElement> pseudo_element)
-{
- return owner_slot(pseudo_element).has_value();
-}
-
bool Animatable::has_css_animations_or_transitions() const
{
return m_animations && RustFFI::animations_element_animations_has_css_animations_or_transitions(m_animations);
@@ -301,32 +231,4 @@ bool Animatable::has_css_defined_animations(Optional<CSS::PseudoElement> pseudo_
return m_animations && slot.has_value() && RustFFI::animations_element_animations_count(m_animations, RustFFI::ElementAnimationListKind::CssAnimations, *slot) != 0;
}
-GC::RootVector<AnimationRef> Animatable::css_defined_animations(Optional<CSS::PseudoElement> pseudo_element) const
-{
- GC::RootVector<AnimationRef> animations;
- auto slot = owner_slot(pseudo_element);
- if (!slot.has_value())
- return animations;
- for (auto const& animation : ElementAnimationList { m_animations, RustFFI::ElementAnimationListKind::CssAnimations, *slot })
- animations.append(animation);
- return animations;
-}
-
-void Animatable::set_css_defined_animations(Optional<CSS::PseudoElement> pseudo_element, ReadonlySpan<AnimationRef> animations)
-{
- auto slot = owner_slot(pseudo_element);
- if (!slot.has_value())
- return;
- // NB: Every element goes through this step; one that had no animations and still has none has nothing to hold or
- // publish.
- if (!m_animations && animations.is_empty())
- return;
-
- Vector<RustFFI::AnimationCell const*, 1> records;
- records.ensure_capacity(animations.size());
- for (auto const& animation : animations)
- records.unchecked_append(&animation.record());
- RustFFI::animations_element_animations_set_css_animations(&ensure_animations(), *slot, records.span(), style_engine_host_of(*this), style_node_of(*this));
-}
-
}
diff --git a/Libraries/LibWeb/Animations/Animatable.h b/Libraries/LibWeb/Animations/Animatable.h
index 8d9bafd171b..cfc3735cae3 100644
--- a/Libraries/LibWeb/Animations/Animatable.h
+++ b/Libraries/LibWeb/Animations/Animatable.h
@@ -18,13 +18,6 @@
#include <LibWeb/CSS/PropertyNameAndID.h>
#include <LibWeb/Export.h>
-namespace Web::CSS {
-
-class CSSAnimation;
-class CSSTransition;
-
-}
-
namespace Web::Animations {
// One of the lists of animations an element holds, which a loop over it reads entry by entry as it goes, so the loop
@@ -75,26 +68,21 @@ class WEB_API Animatable {
public:
virtual ~Animatable();
- enum class IncludeSubtree {
- No,
- Yes
- };
-
- // The relevant animations of the element, and of its descendants with IncludeSubtree::Yes, in no particular order.
- void for_each_relevant_animation(IncludeSubtree, Function<void(AnimationRef const&)> const&) const;
ElementAnimationList associated_animations_in_composite_order();
ElementAnimationList associated_animations_unordered() const;
void invalidate_associated_animation_composite_order();
- bool has_relevant_animations() const;
bool has_associated_animations() const;
+ // The element's lists of its animations, where it holds any.
+ RustFFI::ElementAnimations const* element_animations_if_created() const { return m_animations; }
// The element's lists of its animations, created where it holds none yet, which also follow what the element
// published of the effects that target it to the style engine.
RustFFI::ElementAnimations& ensure_animations();
// Forgets what the element published to the style engine of the effects that target it, as its identity there
// changes.
void forget_published_effect_descriptions();
- // The bytes of the element's lists of its animations and transitions, beside the animations themselves.
- size_t animation_lists_memory_size() const;
+ // The bytes of the element's lists of its animations and transitions, with the records of the animations associated
+ // with it and of their effects, and of the keyframe sets those run that `first_counted` answers are counted first.
+ size_t animation_record_memory_size(bool (*first_counted)(void*, RustFFI::KeyframeSet const*), void* context) const;
void associate_with_animation(AnimationRef const&);
// Disassociates the animation from the element, which `effect`, the animation's associated effect, targeted.
@@ -105,25 +93,15 @@ public:
// computed.
void play_or_pause_css_animations_as_their_play_state_asks();
- // Whether the element or the pseudo-element can own CSS animations and transitions, which only the known
- // pseudo-elements can.
- static bool can_own_css_animations_and_transitions(Optional<CSS::PseudoElement>);
+ // The list of the element, or of one of its known pseudo-elements, of the CSS animations and transitions it owns.
+ static Optional<RustFFI::AnimationOwnerSlot> owner_slot(Optional<CSS::PseudoElement>);
bool has_css_animations_or_transitions() const;
bool has_css_defined_animations(Optional<CSS::PseudoElement>) const;
- GC::RootVector<AnimationRef> css_defined_animations(Optional<CSS::PseudoElement>) const;
- void set_css_defined_animations(Optional<CSS::PseudoElement>, ReadonlySpan<AnimationRef>);
// Whether the installed style gives any longhand a matching transition-property entry, answered without listing them.
bool has_matching_transition_property_entry(Optional<CSS::PseudoElement>) const;
- // Commits a transition started provisionally, whose target is now associated with it, as the transition of its
- // property the element or pseudo-element holds.
- void commit_provisional_transition(Optional<CSS::PseudoElement>, AnimationRef const&, RustFFI::TransitionOrigin);
- void remove_transition(Optional<CSS::PseudoElement>, CSS::PropertyNameAndID const&);
bool has_existing_transitions(Optional<CSS::PseudoElement>) const;
- // The running or completed transition of each property the element or pseudo-element has.
- ElementAnimationList existing_transitions(Optional<CSS::PseudoElement>) const;
- Optional<AnimationRef> property_transition(Optional<CSS::PseudoElement>, CSS::PropertyNameAndID const&) const;
protected:
void visit_edges(JS::Cell::Visitor&);
diff --git a/Libraries/LibWeb/Animations/AnimationEffect.cpp b/Libraries/LibWeb/Animations/AnimationEffect.cpp
index ee19b408def..eb4f9e12506 100644
--- a/Libraries/LibWeb/Animations/AnimationEffect.cpp
+++ b/Libraries/LibWeb/Animations/AnimationEffect.cpp
@@ -8,7 +8,6 @@
#include <LibJS/HostClassBuilder.h>
#include <LibJS/Runtime/VM.h>
#include <LibWeb/Animations/AnimationEffect.h>
-#include <LibWeb/Animations/AnimationTimeline.h>
#include <LibWeb/Bindings/Wrappable.h>
#include <LibWeb/Bindings/WrapperWorld.h>
#include <LibWeb/CSS/ComputedStyleWorkingSet.h>
@@ -16,6 +15,7 @@
#include <LibWeb/CSS/Parser/Parser.h>
#include <LibWeb/CSS/PropertyID.h>
#include <LibWeb/CSS/StyleComputer.h>
+#include <LibWeb/CSS/StyleEngineInput.h>
#include <LibWeb/CSS/StyleInvalidation.h>
#include <LibWeb/CSS/StyleValues/KeywordStyleValue.h>
#include <LibWeb/CSS/StyleValues/StyleValueList.h>
@@ -69,25 +69,19 @@ AnimationUpdateContext::AnimationUpdateContext() = default;
extern "C" {
-// Declared in Bindings/Rust/src/animations/animation_effect.rs and keyframe_effect.rs.
+// Declared in Bindings/Rust/src/animations/animation_effect.rs and keyframe_effect.rs, and in
+// Bindings/Rust/src/dom/document.rs.
void web_animation_effect_visit_host_cells(RustFFI::AnimationEffectCell const*, void* visitor);
void web_animation_effect_set_target(RustFFI::AnimationEffectCell const*, DOM::Element*, bool update);
-void web_animation_effect_invalidate(RustFFI::AnimationEffectCell const*);
-void web_animation_effect_set_composite(RustFFI::AnimationEffectCell const*, CSS::StyleValueFFI::FfiCompositeOperation);
void web_animation_effect_set_keyframe_set(RustFFI::AnimationEffectCell const*, RustFFI::KeyframeSet const*);
DOM::Element* web_animation_element_of_wrapper(JSObject*);
JSObject* web_animation_wrap_element(void* realm, DOM::Element*);
-void* web_animation_document_timeline(JSObject* document_wrapper);
-}
-
-EffectRef EffectRef::create_keyframe_effect()
-{
- return EffectRef::adopt(*RustFFI::animations_effect_create());
+DOM::Document* web_animation_document_of_wrapper(JSObject* document_wrapper);
}
void EffectRef::visit_edges(GC::Cell::Visitor& visitor) const
{
- if (auto* effect = static_cast<GC::Cell*>(RustFFI::animations_effect_facade(&record()))) {
+ if (auto* effect = static_cast<GC::Cell*>(RustFFI::animations_effect_object_cell(&record()))) {
visitor.visit(effect);
return;
}
@@ -103,24 +97,35 @@ void web_animation_effect_visit_host_cells(RustFFI::AnimationEffectCell const* r
cell_visitor.visit(effect.target());
}
+// Sets the target element, and where `update`, notes what the keyframes read of it and invalidates the style the effect
+// produces.
void web_animation_effect_set_target(RustFFI::AnimationEffectCell const* record, DOM::Element* target, bool update)
{
- EffectRef { *record }.set_target(target, update ? EffectRef::InvalidateEffect::Yes : EffectRef::InvalidateEffect::No);
-}
+ EffectRef effect { *record };
+ // NB: The record associates the associated animation with the new target rather than the old.
+ RustFFI::animations_effect_set_target_element(record, target, web_animation_perform_host_effect);
+ if (!update)
+ return;
-void web_animation_effect_invalidate(RustFFI::AnimationEffectCell const* record)
-{
- EffectRef { *record }.invalidate();
+ if (target)
+ CSS::record_attr_names_read_by_keyframes(*target, effect.keyframe_set());
+ effect.invalidate();
+ // FIXME: We don't remove the animated style from the old target element as part of normal animated style update and
+ // it will remain "stuck" until its style is fully invalidated for some other reason.
}
-void web_animation_effect_set_composite(RustFFI::AnimationEffectCell const* record, CSS::StyleValueFFI::FfiCompositeOperation composite)
+// Sets the keyframes the effect runs, invalidating the style it produces where they change.
+void web_animation_effect_set_keyframe_set(RustFFI::AnimationEffectCell const* record, RustFFI::KeyframeSet const* keyframe_set_pointer)
{
- EffectRef { *record }.set_composite(composite);
-}
+ EffectRef effect { *record };
+ auto keyframe_set = KeyframeSetHandle::adopt(keyframe_set_pointer);
+ if (effect.keyframe_set() == keyframe_set)
+ return;
-void web_animation_effect_set_keyframe_set(RustFFI::AnimationEffectCell const* record, RustFFI::KeyframeSet const* keyframe_set)
-{
- EffectRef { *record }.set_keyframe_set(KeyframeSetHandle::adopt(keyframe_set));
+ RustFFI::animations_effect_set_keyframe_set(record, keyframe_set.ptr());
+ if (auto* target = effect.target())
+ CSS::record_attr_names_read_by_keyframes(*target, effect.keyframe_set());
+ effect.invalidate();
}
DOM::Element* web_animation_element_of_wrapper(JSObject* wrapper)
@@ -140,10 +145,9 @@ JSObject* web_animation_wrap_element(void* realm, DOM::Element* element)
return wrap_in_realm(realm, *element);
}
-void* web_animation_document_timeline(JSObject* document_wrapper)
+DOM::Document* web_animation_document_of_wrapper(JSObject* document_wrapper)
{
- auto& document = *Bindings::impl_from<DOM::Document>(JS::HostABI::object_from_abi(document_wrapper));
- return document.timeline().ptr();
+ return Bindings::impl_from<DOM::Document>(JS::HostABI::object_from_abi(document_wrapper));
}
AnimationUpdateContext::~AnimationUpdateContext()
@@ -181,12 +185,20 @@ void AnimationUpdateContext::publish()
// style. Collect them first, in composite order below every associated effect, or this
// update would rebuild the style without them.
Vector<EffectRef> effects_to_collect;
- target->document().style_computer().for_each_provisional_transition_effect(element, [&](EffectRef const& effect) {
- effects_to_collect.append(effect);
- });
+ RustFFI::FfiOwningElement owner {
+ .element = target.ptr(),
+ .pseudo_element = element.pseudo_element().has_value() ? to_underlying(*element.pseudo_element()) : u8 { 0 },
+ .has_pseudo_element = element.pseudo_element().has_value(),
+ };
+ for (size_t index = 0;; ++index) {
+ auto const* effect = RustFFI::animations_document_animations_proposed_transition_effect(&target->document().document_animations(), owner, index);
+ if (!effect)
+ break;
+ effects_to_collect.append(EffectRef { *effect });
+ }
for (auto const& animation : target->associated_animations_in_composite_order()) {
auto effect = animation.effect();
- if (!effect.has_value() || animation.timing_state().play_state == RustFFI::AnimationPlayState::Idle)
+ if (!effect.has_value() || animation.play_state() == RustFFI::AnimationPlayState::Idle)
continue;
if (effect->target() != target.ptr() || effect->pseudo_element_type() != element.pseudo_element())
continue;
@@ -233,9 +245,9 @@ void AnimationUpdateContext::publish()
// A timeline script observed ahead of its current time in this task is sampled at that time, as an update of the
// effects needing it is, or the style installed here and the one that update sampled would keep disagreeing about
// an effect that ended between the two times.
- AnimationTimeline::at_times_observed_ahead(document.associated_animation_timelines().begin(), document.associated_animation_timelines().end(), [&] {
- style_computer.refresh_animations_into_each(read, requests);
- });
+ auto refresh = [&] { style_computer.refresh_animations_into_each(read, requests); };
+ using Refresh = decltype(refresh);
+ RustFFI::animations_document_animations_at_times_observed_ahead(&document.document_animations(), &refresh, [](void* context) { (*static_cast<Refresh*>(context))(); });
publications.clear_with_capacity();
overlays.clear_with_capacity();
diff --git a/Libraries/LibWeb/Animations/AnimationEffect.h b/Libraries/LibWeb/Animations/AnimationEffect.h
index b2feab93a9f..076c11f1ee7 100644
--- a/Libraries/LibWeb/Animations/AnimationEffect.h
+++ b/Libraries/LibWeb/Animations/AnimationEffect.h
@@ -15,37 +15,12 @@
#include <LibWeb/Animations/KeyframeSetHandle.h>
#include <LibWeb/Animations/RecordHandles.h>
#include <LibWeb/Animations/RustFFI.h>
-#include <LibWeb/Animations/TimeValue.h>
#include <LibWeb/CSS/EasingFunction.h>
#include <LibWeb/CSS/InstalledStyle.h>
#include <LibWeb/CSS/PropertyNameAndID.h>
namespace Web::Animations {
-inline RustFFI::OptionalTimeValue to_ffi(Optional<TimeValue> const& time)
-{
- return { .value = time.value_or(TimeValue { TimeValue::Type::Milliseconds, 0 }), .has_value = time.has_value() };
-}
-
-inline Optional<TimeValue> from_ffi(RustFFI::OptionalTimeValue const& time)
-{
- if (!time.has_value)
- return {};
- return time.value;
-}
-
-inline Optional<double> from_ffi(RustFFI::OptionalNumber const& number)
-{
- if (!number.has_value)
- return {};
- return number.value;
-}
-
-inline RustFFI::OptionalNumber to_ffi(Optional<double> const& number)
-{
- return { .value = number.value_or(0), .has_value = number.has_value() };
-}
-
// This object lives for the duration of an animation update, and is used to store per-element data about animated CSS properties.
struct AnimationUpdateContext {
struct ElementData {
diff --git a/Libraries/LibWeb/Animations/AnimationTimeline.cpp b/Libraries/LibWeb/Animations/AnimationTimeline.cpp
deleted file mode 100644
index 8ea74f180f1..00000000000
--- a/Libraries/LibWeb/Animations/AnimationTimeline.cpp
+++ /dev/null
@@ -1,488 +0,0 @@
-/*
- * Copyright (c) 2023-2024, Matthew Olsson <[email protected]>.
- * Copyright (c) 2026, Callum Law <[email protected]>.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibGC/RootVector.h>
-#include <LibJS/HostClassBuilder.h>
-#include <LibJS/Runtime/VM.h>
-#include <LibWeb/Animations/AnimationEffect.h>
-#include <LibWeb/Animations/AnimationTimeline.h>
-#include <LibWeb/Animations/RecordHandles.h>
-#include <LibWeb/CSS/Parser/Parser.h>
-#include <LibWeb/CSS/StyleValues/ComputationContext.h>
-#include <LibWeb/DOM/Document.h>
-#include <LibWeb/DOM/Element.h>
-#include <LibWeb/HTML/EventLoop/EventLoop.h>
-#include <LibWeb/HTML/Scripting/Environments.h>
-#include <LibWeb/HighResolutionTime/TimeOrigin.h>
-#include <LibWeb/Layout/RenderDocument.h>
-#include <LibWeb/Layout/Viewport.h>
-#include <LibWeb/Painting/Scrolling.h>
-
-namespace Web::Animations {
-
-// Takes a reference to a calculated inset the style engine hands over, which may be null.
-static CSS::RustStyleValueHandle retain_calculated_inset(void const* value)
-{
- if (!value)
- return {};
- return CSS::RustStyleValueHandle::retained(static_cast<CSS::StyleValueFFI::StyleValueData const*>(value));
-}
-
-extern "C" {
-
-// Defined in Bindings/Rust/src/animations/animation_timeline.rs.
-void* web_animation_timeline_create(JSVM*, DOM::Document*, RustFFI::FfiTimelineDescription const*);
-RustFFI::TimelineCell const* web_animation_timeline_record(void* timeline);
-
-// Declared in Bindings/Rust/src/animations.
-void web_animation_timeline_did_create(void* timeline);
-RustFFI::OptionalTimeValue web_animation_timeline_current_time_for_observation(void* timeline);
-DOM::Element* web_scroll_timeline_source(void* timeline);
-DOM::Element* web_animation_document_scrolling_element(DOM::Document*);
-void web_internal_animation_timeline_set_time(void* timeline, RustFFI::OptionalNumber, bool for_observation);
-CSS::StyleValueFFI::StyleValueData const* web_animation_absolutize_style_value(DOM::Document*, CSS::StyleValueFFI::StyleValueData const*);
-}
-
-static RustFFI::FfiScrollTimelineSource source_to_ffi(AnimationTimeline::ScrollSource const& source)
-{
- return source.visit(
- [](GC::Ptr<DOM::Element const> const& element) -> RustFFI::FfiScrollTimelineSource {
- return { .element = const_cast<DOM::Element*>(element.ptr()), .is_anonymous = false, .scroller = 0, .target = nullptr, .pseudo_element = 0, .has_pseudo_element = false };
- },
- [](AnimationTimeline::AnonymousScrollSource const& anonymous_source) -> RustFFI::FfiScrollTimelineSource {
- auto pseudo_element = anonymous_source.target.pseudo_element();
- return {
- .element = nullptr,
- .is_anonymous = true,
- .scroller = to_underlying(anonymous_source.scroller),
- .target = const_cast<DOM::Element*>(&anonymous_source.target.element()),
- .pseudo_element = pseudo_element.has_value() ? to_underlying(*pseudo_element) : u8 { 0 },
- .has_pseudo_element = pseudo_element.has_value(),
- };
- });
-}
-
-static RustFFI::FfiViewTimelineInset inset_to_ffi(ViewTimelineInset const& inset)
-{
- auto edge = [](ViewTimelineInsetEdge const& edge) -> RustFFI::FfiViewTimelineInsetEdge {
- return { .is_auto = edge.is_auto, .px = edge.px, .percentage = edge.percentage, .calculated = edge.calculated.data() };
- };
- return { .start = edge(inset.start), .end = edge(inset.end) };
-}
-
-ViewTimelineInset view_timeline_inset_from_ffi(CSS::ComputedValuesFFI::FfiViewTimelineInset const& inset)
-{
- return {
- .start = { inset.start_is_auto, inset.start_px, inset.start_percentage, retain_calculated_inset(inset.start_calculated) },
- .end = { inset.end_is_auto, inset.end_px, inset.end_percentage, retain_calculated_inset(inset.end_calculated) },
- };
-}
-
-GC::Ref<AnimationTimeline> AnimationTimeline::create(DOM::Document& document, RustFFI::FfiTimelineDescription const& description)
-{
- return *static_cast<AnimationTimeline*>(web_animation_timeline_create(JS::HostABI::vm_to_abi(JS::VM::the()), &document, &description));
-}
-
-GC::Ref<AnimationTimeline> AnimationTimeline::create_document_timeline(DOM::Document& document, double origin_time)
-{
- return create(document, { .kind = RustFFI::FfiTimelineKind::Document, .origin_time = origin_time, .source = {}, .axis = 0, .inset = {} });
-}
-
-GC::Ref<AnimationTimeline> AnimationTimeline::create_scroll_timeline(DOM::Document& document, ScrollSource const& source, ScrollAxis axis)
-{
- return create(document, { .kind = RustFFI::FfiTimelineKind::Scroll, .origin_time = 0, .source = source_to_ffi(source), .axis = to_underlying(axis), .inset = {} });
-}
-
-GC::Ref<AnimationTimeline> AnimationTimeline::create_view_timeline(DOM::Document& document, DOM::AbstractElement subject, ScrollAxis axis, ViewTimelineInset const& inset)
-{
- return create(document,
- {
- .kind = RustFFI::FfiTimelineKind::View,
- .origin_time = 0,
- .source = source_to_ffi(AnonymousScrollSource { .scroller = CSS::Scroller::Nearest, .target = subject }),
- .axis = to_underlying(axis),
- .inset = inset_to_ffi(inset),
- });
-}
-
-GC::Ref<AnimationTimeline> AnimationTimeline::create_internal_timeline(DOM::Document& document)
-{
- return create(document, { .kind = RustFFI::FfiTimelineKind::Internal, .origin_time = 0, .source = {}, .axis = 0, .inset = {} });
-}
-
-RustFFI::TimelineCell const& AnimationTimeline::record() const
-{
- return *web_animation_timeline_record(const_cast<AnimationTimeline*>(this));
-}
-
-GC::Ref<DOM::Document> AnimationTimeline::associated_document() const
-{
- return *static_cast<DOM::Document*>(RustFFI::animations_timeline_document(&record()));
-}
-
-bool AnimationTimeline::is_scroll_timeline() const
-{
- auto kind = read().kind;
- return kind == RustFFI::FfiTimelineKind::Scroll || kind == RustFFI::FfiTimelineKind::View;
-}
-
-AnimationTimeline::CurrentTimeOverrideScope::CurrentTimeOverrideScope(AnimationTimeline& timeline, Optional<TimeValue> current_time)
- : m_timeline(timeline)
-{
- auto read = timeline.read();
- m_had_previous_current_time_override = read.has_style_sampling_override;
- m_previous_current_time_override = read.style_sampling_override;
- m_timeline->set_current_time_override_for_style_sampling(move(current_time));
-}
-
-AnimationTimeline::CurrentTimeOverrideScope::~CurrentTimeOverrideScope()
-{
- RustFFI::animations_timeline_set_style_sampling_override(&m_timeline->record(), m_had_previous_current_time_override, m_previous_current_time_override);
-}
-
-// https://drafts.csswg.org/web-animations-1/#dom-animationtimeline-currenttime
-Optional<TimeValue> AnimationTimeline::current_time() const
-{
- // NB: The record returns the current time for this timeline or null if this timeline is inactive.
- return from_ffi(read().sample.current_time);
-}
-
-u64 AnimationTimeline::task_generation() const
-{
- return associated_document()->relevant_settings_object().responsible_event_loop().task_generation();
-}
-
-Optional<TimeValue> AnimationTimeline::current_time_for_observation()
-{
- auto read = this->read();
- if (!read.sample.is_monotonically_increasing || !read.can_sample_current_time_at_timestamp)
- return from_ffi(read.sample.current_time);
-
- bool has_animation_without_per_frame_tick = false;
- for (auto const& animation : associated_animations()) {
- auto effect = animation.effect();
- if (!effect.has_value())
- continue;
- if (effect->per_frame_animation_tick_was_skipped() || effect->can_skip_per_frame_animation_tick()) {
- has_animation_without_per_frame_tick = true;
- break;
- }
- }
- if (!has_animation_without_per_frame_tick)
- return from_ffi(read.sample.current_time);
-
- auto& settings = associated_document()->relevant_settings_object();
- auto task_generation = settings.responsible_event_loop().task_generation();
- if (read.has_observation_task_generation && read.observation_task_generation == task_generation)
- return from_ffi(read.observed_current_time);
-
- // OPTIMIZATION: An animation skipped by the per-frame sampler does not keep the rendering update loop alive.
- // Sample document timelines only when script observes them, and at most once per event-loop task
- // so all reads within a stable state agree.
- auto timestamp = HighResolutionTime::relative_high_resolution_time(
- HighResolutionTime::unsafe_shared_current_time(), settings.global_object());
- auto observed_current_time = RustFFI::animations_timeline_current_time_at_timestamp(&record(), timestamp, true, task_generation);
- HTML::note_rendering_trace_event("animation timeline synchronized"sv);
- return from_ffi(observed_current_time);
-}
-
-bool AnimationTimeline::was_observed_ahead_in_current_task() const
-{
- auto read = this->read();
- return read.was_observed_ahead && read.observed_ahead_task_generation == task_generation();
-}
-
-Optional<TimeValue> AnimationTimeline::current_time_at_timestamp(double timestamp) const
-{
- return from_ffi(RustFFI::animations_timeline_current_time_at_timestamp(&record(), timestamp, false, 0));
-}
-
-void AnimationTimeline::update_current_time(double timestamp)
-{
- // https://drafts.csswg.org/scroll-animations-1/#ref-for-dom-animationtimeline-currenttime
- // NB: The record calculates the scroll progress from the layout of the scroller. The passed timestamp is ignored.
- if (is_scroll_timeline()) {
- // NB: Called during animation timeline update, which runs before layout is up to date.
- update_current_time_from_layout(false);
- return;
- }
- RustFFI::animations_timeline_update_current_time(&record(), timestamp, nullptr, task_generation(), false, update_associated_animations_of);
-}
-
-// https://drafts.csswg.org/scroll-animations-1/#stale-timelines
-bool AnimationTimeline::update_current_time_if_stale()
-{
- return update_current_time_from_layout(true);
-}
-
-void AnimationTimeline::update_associated_animations_of(void* timeline)
-{
- static_cast<AnimationTimeline*>(timeline)->update_associated_animations();
-}
-
-void AnimationTimeline::update_associated_animations()
-{
- // https://drafts.csswg.org/web-animations-1/#animation-frame-loop
- // Note: Due to the hierarchical nature of the timing model, updating the current time of a timeline also involves:
- // - Updating the current time of any animations associated with the timeline.
- // - Running the update an animation's finished state procedure for any animations whose current time has been
- // updated.
- // - Queueing animation events for any such animations.
- // NB: Since we dispatch events for all animations regardless of whether they have a timeline we handle them all together in Document::update_animations_and_send_events()
- HTML::note_rendering_trace_event("animation timeline updated its animations"sv);
- // NB: Updating an animation can run script that changes which animations are associated with this timeline. Skip
- // the ones it disassociates. The animations stay alive through it.
- GC::RootVector<AnimationRef> animations;
- auto associated_animations = this->associated_animations();
- for (auto const& animation : associated_animations)
- animations.append(animation);
- for (auto const& animation : animations) {
- if (associated_animations.contains(animation.record()))
- animation.update();
- }
-}
-
-// https://www.w3.org/TR/web-animations-1/#timeline-time-to-origin-relative-time
-Optional<double> AnimationTimeline::convert_a_timeline_time_to_an_origin_relative_time(Optional<TimeValue> timeline_time)
-{
- return from_ffi(RustFFI::animations_timeline_convert_to_origin_relative_time(&record(), to_ffi(timeline_time)));
-}
-
-// https://drafts.csswg.org/web-animations-2/#timeline-duration
-Optional<TimeValue> AnimationTimeline::duration() const
-{
- return from_ffi(read().duration);
-}
-
-AnimationTimeline::ScrollSource AnimationTimeline::scroll_source() const
-{
- auto source = read().source;
- if (!source.is_anonymous)
- return GC::Ptr<DOM::Element const> { static_cast<DOM::Element const*>(source.element) };
- Optional<CSS::PseudoElement> pseudo_element;
- if (source.has_pseudo_element)
- pseudo_element = static_cast<CSS::PseudoElement>(source.pseudo_element);
- return AnonymousScrollSource {
- .scroller = static_cast<CSS::Scroller>(source.scroller),
- .target = DOM::AbstractElement { *static_cast<DOM::Element*>(source.target), pseudo_element },
- };
-}
-
-GC::Ptr<DOM::Element const> AnimationTimeline::source() const
-{
- return scroll_source().visit(
- [](GC::Ptr<DOM::Element const> const& source) -> GC::Ptr<DOM::Element const> {
- return source;
- },
- [](AnonymousScrollSource const& anonymous_source) -> GC::Ptr<DOM::Element const> {
- switch (anonymous_source.scroller) {
- case CSS::Scroller::Root:
- return anonymous_source.target.document().document_element();
- case CSS::Scroller::Nearest: {
- GC::Ptr<DOM::Element const> ancestor = anonymous_source.target.parent_element();
-
- // Whether a box is a scroll container depends on its used overflow, which is visible for a body whose
- // overflow is propagated to the viewport. The document element stands for the viewport.
- Layout::ForcedReadScope read { anonymous_source.target.document() };
- while (ancestor && !ancestor->is_document_element()) {
- auto const* layout_node = ancestor->unsafe_layout_node(read);
- if (layout_node && layout_node->is_scroll_container())
- break;
- ancestor = ancestor->parent_element();
- }
-
- return ancestor;
- }
- case CSS::Scroller::Self:
- return anonymous_source.target.element();
- }
- VERIFY_NOT_REACHED();
- });
-}
-
-void AnimationTimeline::set_axis(ScrollAxis axis)
-{
- if (RustFFI::animations_scroll_timeline_set_axis_and_inset(&record(), to_underlying(axis), nullptr))
- update_current_time(0);
-}
-
-DOM::AbstractElement AnimationTimeline::view_subject() const
-{
- return scroll_source().get<AnonymousScrollSource>().target;
-}
-
-ViewTimelineInset AnimationTimeline::view_inset() const
-{
- auto inset = read().inset;
- auto edge = [](RustFFI::FfiViewTimelineInsetEdge const& edge) -> ViewTimelineInsetEdge {
- return { edge.is_auto, edge.px, edge.percentage, retain_calculated_inset(edge.calculated) };
- };
- return { edge(inset.start), edge(inset.end) };
-}
-
-void AnimationTimeline::set_axis_and_inset(ScrollAxis axis, ViewTimelineInset const& inset)
-{
- auto ffi_inset = inset_to_ffi(inset);
- if (RustFFI::animations_scroll_timeline_set_axis_and_inset(&record(), to_underlying(axis), &ffi_inset))
- update_current_time(0);
-}
-
-void AnimationTimeline::set_internal_time(Optional<double> time, bool for_observation)
-{
- RustFFI::animations_internal_timeline_set_time(&record(), to_ffi(time), for_observation, task_generation(), update_associated_animations_of);
-}
-
-bool AnimationTimeline::update_current_time_from_layout(bool only_if_stale)
-{
- // NB: The record measures the boxes the timeline follows where the render state of the document whose viewport or
- // element the source propagates to lays them out.
- RustFFI::FfiScrollTimelineBoxes boxes {
- .host = nullptr,
- .read = nullptr,
- .scroller = Compositing::RustFFI::NodeSlotId_INVALID,
- .has_scroll_node = false,
- .scroll_node = {},
- .scroller_style_node = 0,
- .subject = Compositing::RustFFI::NodeSlotId_INVALID,
- .subject_style_node = 0,
- };
- auto update = [&] {
- return RustFFI::animations_timeline_update_current_time(&record(), 0, &boxes, task_generation(), only_if_stale, update_associated_animations_of);
- };
-
- // https://drafts.csswg.org/scroll-animations-1/#scroll-notation
- // References to the root element propagate to the document viewport (which functions as its scroll container).
- auto const source = this->source();
- Variant<GC::Ptr<DOM::Element const>, GC::Ptr<DOM::Document>> propagated_source = source;
- if (source && source.ptr() == source->document().document_element())
- propagated_source = source->owner_document();
- if (propagated_source.visit([](auto const& source) { return source == nullptr; }))
- return update();
-
- Layout::ForcedReadScope read { propagated_source.visit([](auto const& source) -> DOM::Document const& { return source->document(); }) };
- auto const* layout_node = propagated_source.visit([&read](auto const& source) -> Layout::NodeWithStyle const* { return source->unsafe_layout_node(read); });
- if (!layout_node)
- return update();
-
- boxes.host = layout_node->document_host();
- boxes.read = read;
- boxes.scroller = Layout::Node::slot_id(layout_node);
- if (auto scroll_node = Painting::async_scroll_node_stable_id(*layout_node); scroll_node.has_value()) {
- boxes.has_scroll_node = true;
- boxes.scroll_node = { .node_id = scroll_node->node_id.value(), .kind = to_underlying(scroll_node->kind), .pseudo_element_type = scroll_node->pseudo_element_type };
- }
- boxes.scroller_style_node = propagated_source.visit(
- [](GC::Ptr<DOM::Element const> const& element) { return element->style_node_id().value(); },
- [](GC::Ptr<DOM::Document> const&) -> u32 { return 0; });
- // NB: A view timeline follows the box of its subject besides its scroller's.
- if (is_view_timeline()) {
- auto subject = view_subject();
- boxes.subject = Layout::Node::slot_id(subject.unsafe_layout_node(read));
- // NB: A clock tick finds the subject by its style node, which a pseudo-element does not name.
- if (!subject.pseudo_element().has_value())
- boxes.subject_style_node = subject.element().style_node_id().value();
- }
- return update();
-}
-
-ScrollAxis scroll_axis_from_css_axis(CSS::Axis axis)
-{
- switch (axis) {
- case CSS::Axis::Block:
- return ScrollAxis::Block;
- case CSS::Axis::Inline:
- return ScrollAxis::Inline;
- case CSS::Axis::X:
- return ScrollAxis::X;
- case CSS::Axis::Y:
- return ScrollAxis::Y;
- }
-
- VERIFY_NOT_REACHED();
-}
-
-// NB: What the Rust timelines ask of the host.
-void web_animation_timeline_did_create(void* cell)
-{
- auto& timeline = *static_cast<AnimationTimeline*>(cell);
- auto document = timeline.associated_document();
- document->associate_with_timeline(timeline);
- Optional<double> current_time;
- if (timeline.is_document_timeline()) {
- current_time = document->last_animation_frame_timestamp();
- if (!current_time.has_value()) {
- // The document hasn't processed an animation frame yet, we use the navigation start time, which is either
- // the time that the previous document started to be unloaded or the creation time of the current document.
- current_time = HighResolutionTime::relative_high_resolution_time(document->load_timing_info().navigation_start_time, document->relevant_settings_object().global_object());
- }
- } else if (timeline.is_scroll_timeline()) {
- // NB: The passed timestamp is ignored for ScrollTimelines so we can just pass 0 here.
- current_time = 0;
- }
- if (current_time.has_value())
- timeline.update_current_time(*current_time);
-}
-
-RustFFI::OptionalTimeValue web_animation_timeline_current_time_for_observation(void* cell)
-{
- return to_ffi(static_cast<AnimationTimeline*>(cell)->current_time_for_observation());
-}
-
-DOM::Element* web_scroll_timeline_source(void* cell)
-{
- auto& timeline = *static_cast<AnimationTimeline*>(cell);
- if (timeline.is_view_timeline()) {
- // The values of subject, source, and currentTime are all computed when any of them is requested or updated.
- auto subject = timeline.view_subject();
- subject.document().update_layout(DOM::UpdateLayoutReason::ViewTimelineSource);
-
- // If the source or subject of a ViewTimeline is an element whose principal box does not exist, [...] then the
- // ViewTimeline is inactive.
- // INTEROP: Its source is then null, as WebKit and Blink have it.
- for (GC::Ptr<DOM::Element const> element = &subject.element(); element; element = element->flat_tree_parent_element()) {
- if (!element->has_style() || element->installed_style().display_is_none())
- return nullptr;
- }
- } else {
- // The nearest scroll container is the nearest one by used overflow, which layout decides.
- auto scroll_source = timeline.scroll_source();
- if (auto const* anonymous_source = scroll_source.get_pointer<AnimationTimeline::AnonymousScrollSource>(); anonymous_source && anonymous_source->scroller == CSS::Scroller::Nearest)
- anonymous_source->target.document().update_layout(DOM::UpdateLayoutReason::ScrollTimelineSource);
- }
- return const_cast<DOM::Element*>(timeline.source().ptr());
-}
-
-DOM::Element* web_animation_document_scrolling_element(DOM::Document* document)
-{
- return const_cast<DOM::Element*>(document->scrolling_element().ptr());
-}
-
-void web_internal_animation_timeline_set_time(void* cell, RustFFI::OptionalNumber time, bool for_observation)
-{
- static_cast<AnimationTimeline*>(cell)->set_internal_time(from_ffi(time), for_observation);
-}
-
-// NB: Absolutizes a style value that script gave, as the document's values are.
-CSS::StyleValueFFI::StyleValueData const* web_animation_absolutize_style_value(DOM::Document* document, CSS::StyleValueFFI::StyleValueData const* value)
-{
- auto style_value = CSS::StyleValue::adopt_rust_style_value_data(CSS::StyleValueFFI::rust_style_value_retain(value));
- auto computed = style_value->absolutized(CSS::ComputationContext { .length_resolution_context = CSS::Length::ResolutionContext::for_document(*document) });
- return CSS::StyleValueFFI::rust_style_value_retain(computed->rust_style_value_data());
-}
-
-}
-
-// NB: What the timeline records ask of the document a timeline is associated with.
-extern "C" WEB_API bool ladybird_animations_document_is_active(void* document)
-{
- return static_cast<Web::DOM::Document const*>(document)->is_active();
-}
-
-extern "C" WEB_API void* ladybird_animations_element_node_document(void* element)
-{
- return &static_cast<Web::DOM::Element*>(element)->document();
-}
diff --git a/Libraries/LibWeb/Animations/AnimationTimeline.h b/Libraries/LibWeb/Animations/AnimationTimeline.h
deleted file mode 100644
index 1217b1da3e2..00000000000
--- a/Libraries/LibWeb/Animations/AnimationTimeline.h
+++ /dev/null
@@ -1,185 +0,0 @@
-/*
- * Copyright (c) 2023, Matthew Olsson <[email protected]>.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/Animations/AnimationEffect.h>
-#include <LibWeb/Animations/TimeValue.h>
-#include <LibWeb/Bindings/AnimationTimeline.h>
-#include <LibWeb/Bindings/RustInterface.h>
-#include <LibWeb/CSS/Enums.h>
-#include <LibWeb/CSS/StyleValues/RustStyleValueHandle.h>
-#include <LibWeb/ComputedValuesRustFFI.h>
-#include <LibWeb/DOM/AbstractElement.h>
-
-namespace Web::Animations {
-
-// https://drafts.csswg.org/scroll-animations-1/#enumdef-scrollaxis
-enum class ScrollAxis : u8 {
- Block,
- Inline,
- X,
- Y,
-};
-
-ScrollAxis scroll_axis_from_css_axis(CSS::Axis);
-
-// One side of the view progress visibility range: auto takes the scroll container's scroll padding, otherwise a length
-// plus a percentage of the scrollport.
-// https://drafts.csswg.org/scroll-animations-1/#view-timeline-inset
-struct ViewTimelineInsetEdge {
- bool is_auto { true };
- double px { 0 };
- double percentage { 0 };
- // NB: An inset only a calculation can describe, such as min(50%, 10px), resolves against the scrollport size.
- CSS::RustStyleValueHandle calculated {};
-
- bool operator==(ViewTimelineInsetEdge const&) const = default;
-};
-
-struct ViewTimelineInset {
- ViewTimelineInsetEdge start;
- ViewTimelineInsetEdge end;
-
- bool operator==(ViewTimelineInset const&) const = default;
-};
-
-// https://drafts.csswg.org/web-animations-2/#the-animationtimeline-interface
-// The cell of an AnimationTimeline, which Bindings/Rust/src/animations implements, of any of the interfaces that
-// inherit from it. The state of the timeline is its record.
-class WEB_API AnimationTimeline final : public Bindings::RustInterfaceCell {
- WEB_RUST_INTERFACE(AnimationTimeline, animation_timeline)
-
-public:
- // The source of an anonymous scroll timeline: the scroller it finds from its target.
- // https://drafts.csswg.org/scroll-animations-1/#scroll-notation
- struct AnonymousScrollSource {
- CSS::Scroller scroller;
- DOM::AbstractElement target;
-
- bool operator==(AnonymousScrollSource const& other) const = default;
- };
- using ScrollSource = Variant<GC::Ptr<DOM::Element const>, AnonymousScrollSource>;
-
- static GC::Ref<AnimationTimeline> create_document_timeline(DOM::Document&, double origin_time);
- static GC::Ref<AnimationTimeline> create_scroll_timeline(DOM::Document&, ScrollSource const&, ScrollAxis);
- static GC::Ref<AnimationTimeline> create_view_timeline(DOM::Document&, DOM::AbstractElement subject, ScrollAxis, ViewTimelineInset const&);
- static GC::Ref<AnimationTimeline> create_internal_timeline(DOM::Document&);
-
- class CurrentTimeOverrideScope {
- public:
- CurrentTimeOverrideScope(AnimationTimeline&, Optional<TimeValue>);
- ~CurrentTimeOverrideScope();
-
- CurrentTimeOverrideScope(CurrentTimeOverrideScope const&) = delete;
- CurrentTimeOverrideScope& operator=(CurrentTimeOverrideScope const&) = delete;
-
- private:
- GC::Ref<AnimationTimeline> m_timeline;
- bool m_had_previous_current_time_override { false };
- RustFFI::OptionalTimeValue m_previous_current_time_override;
- };
-
- // The timeline's state, which lives as long as the timeline.
- RustFFI::TimelineCell const& record() const;
-
- Optional<TimeValue> current_time() const;
- // What the timing model reads of the timeline now.
- RustFFI::TimelineSample sample() const { return read().sample; }
- // What moves the timeline as a clock tick samples it.
- RustFFI::TimelineClock clock() const { return read().clock; }
- Optional<TimeValue> current_time_for_observation();
- // Whether script observed the timeline in the current task at a time ahead of its current time.
- bool was_observed_ahead_in_current_task() const;
- // The current time at a timestamp, where the timeline can sample it there, and its current time otherwise.
- Optional<TimeValue> current_time_at_timestamp(double timestamp) const;
-
- // Runs the callback with every timeline in [timelines, end) that script observed ahead of its current time in the
- // current task sampled at the time script observed, so that what the callback samples agrees with what script read.
- template<typename Iterator, typename Callback>
- static void at_times_observed_ahead(Iterator timelines, Iterator end, Callback const& callback);
-
- // Updates the current time: a document timeline's from the timestamp, and a scroll timeline's from the layout of
- // its scroller, which ignores the timestamp.
- void update_current_time(double timestamp);
- // Updates the current time of a scroll timeline from the layout of its scroller where that changed it since its
- // last update, answering whether it did.
- bool update_current_time_if_stale();
-
- Optional<TimeValue> duration() const;
-
- GC::Ref<DOM::Document> associated_document() const;
-
- bool is_inactive() const { return read().is_inactive; }
- bool is_monotonically_increasing() const { return read().sample.is_monotonically_increasing; }
- bool is_document_timeline() const { return read().kind == RustFFI::FfiTimelineKind::Document; }
- // A scroll timeline, or a view timeline, which is one.
- bool is_scroll_timeline() const;
- bool is_view_timeline() const { return read().kind == RustFFI::FfiTimelineKind::View; }
- bool is_progress_based() const { return is_scroll_timeline(); }
-
- // https://www.w3.org/TR/web-animations-1/#timeline-time-to-origin-relative-time
- Optional<double> convert_a_timeline_time_to_an_origin_relative_time(Optional<TimeValue>);
- bool can_convert_a_timeline_time_to_an_origin_relative_time() const { return is_document_timeline(); }
-
- // NB: The animations associated with the timeline, none of which it keeps alive.
- WeakAnimationSetView associated_animations() const { return WeakAnimationSetView { *RustFFI::animations_timeline_associated_animations(&record()) }; }
-
- // The source, axis and inset of a scroll or view timeline.
- ScrollSource scroll_source() const;
- // https://drafts.csswg.org/scroll-animations-1/#dom-scrolltimeline-source
- GC::Ptr<DOM::Element const> source() const;
- ScrollAxis axis() const { return static_cast<ScrollAxis>(read().axis); }
- void set_axis(ScrollAxis);
- DOM::AbstractElement view_subject() const;
- ViewTimelineInset view_inset() const;
- void set_axis_and_inset(ScrollAxis, ViewTimelineInset const&);
-
- // Sets the time of the Internals interface's timeline, or the time a read of it observes.
- void set_internal_time(Optional<double>, bool for_observation);
-
-private:
- friend class DOM::Document;
-
- static GC::Ref<AnimationTimeline> create(DOM::Document&, RustFFI::FfiTimelineDescription const&);
-
- RustFFI::FfiTimeline read() const { return RustFFI::animations_timeline_read(&record()); }
- u64 task_generation() const;
- void update_associated_animations();
- // The host's function through which the record has the timeline update its associated animations.
- static void update_associated_animations_of(void* timeline);
-
- // Updates the current time of a scroll timeline from where the render state lays out the boxes the timeline
- // follows, unless that leaves it as it was where `only_if_stale`, answering whether it updated it.
- bool update_current_time_from_layout(bool only_if_stale);
-
- void set_current_time_override_for_style_sampling(Optional<TimeValue> value)
- {
- RustFFI::animations_timeline_set_style_sampling_override(&record(), true, to_ffi(value));
- }
- void clear_current_time_override_for_style_sampling() { RustFFI::animations_timeline_set_style_sampling_override(&record(), false, to_ffi(Optional<TimeValue> {})); }
-};
-
-ViewTimelineInset view_timeline_inset_from_ffi(CSS::ComputedValuesFFI::FfiViewTimelineInset const&);
-
-template<typename Iterator, typename Callback>
-void AnimationTimeline::at_times_observed_ahead(Iterator timelines, Iterator end, Callback const& callback)
-{
- if (timelines == end)
- return callback();
- auto& timeline = **timelines;
- ++timelines;
- if (!timeline.was_observed_ahead_in_current_task())
- return at_times_observed_ahead(timelines, end, callback);
- CurrentTimeOverrideScope override { timeline, timeline.current_time_for_observation() };
- at_times_observed_ahead(timelines, end, callback);
-}
-
-}
-
-// NB: What the timeline records ask of the document a timeline is associated with.
-extern "C" WEB_API bool ladybird_animations_document_is_active(void* document);
-extern "C" WEB_API void* ladybird_animations_element_node_document(void* element);
diff --git a/Libraries/LibWeb/Animations/KeyframeSetHandle.h b/Libraries/LibWeb/Animations/KeyframeSetHandle.h
index e540f1eb726..1e234b0f1d3 100644
--- a/Libraries/LibWeb/Animations/KeyframeSetHandle.h
+++ b/Libraries/LibWeb/Animations/KeyframeSetHandle.h
@@ -6,11 +6,10 @@
#pragma once
-#include <AK/AnyOf.h>
#include <AK/BinarySearch.h>
#include <AK/StdLibExtras.h>
#include <LibWeb/Animations/RustFFI.h>
-#include <LibWeb/CSS/PropertyNameAndID.h>
+#include <LibWeb/CSS/PropertyID.h>
namespace Web::Animations {
@@ -21,56 +20,16 @@ public:
TargetProperties() = default;
explicit TargetProperties(RustFFI::FfiKeyframeSetFacts const& facts)
: m_properties(facts.target_properties, facts.target_property_count)
- , m_custom_properties(facts.target_custom_properties, facts.target_custom_property_count)
{
}
- bool is_empty() const { return size() == 0; }
- size_t size() const { return m_properties.size() + m_custom_properties.size(); }
-
- bool contains(CSS::PropertyNameAndID const& property) const
+ bool contains(CSS::PropertyID property_id) const
{
- if (!property.is_custom_property())
- return binary_search(m_properties, static_cast<u16>(property.id())) != nullptr;
- return any_of(m_custom_properties, [&](size_t name) { return Utf16FlyString::from_raw(name) == property.name(); });
+ return binary_search(m_properties, static_cast<u16>(property_id)) != nullptr;
}
- class Iterator {
- public:
- CSS::PropertyNameAndID operator*() const
- {
- if (m_index < m_properties->m_properties.size())
- return CSS::PropertyNameAndID::from_id(static_cast<CSS::PropertyID>(m_properties->m_properties[m_index]));
- return CSS::PropertyNameAndID::from_name(Utf16FlyString::from_raw(m_properties->m_custom_properties[m_index - m_properties->m_properties.size()])).release_value();
- }
-
- Iterator& operator++()
- {
- ++m_index;
- return *this;
- }
-
- bool operator==(Iterator const& other) const { return m_index == other.m_index; }
-
- private:
- friend class TargetProperties;
-
- Iterator(TargetProperties const& properties, size_t index)
- : m_properties(&properties)
- , m_index(index)
- {
- }
-
- TargetProperties const* m_properties { nullptr };
- size_t m_index { 0 };
- };
-
- Iterator begin() const { return { *this, 0 }; }
- Iterator end() const { return { *this, size() }; }
-
private:
ReadonlySpan<u16> m_properties;
- ReadonlySpan<size_t> m_custom_properties;
};
// A borrowed view of an immutable keyframe set, valid for as long as what lent it holds the set.
@@ -86,8 +45,6 @@ public:
explicit operator bool() const { return m_set; }
bool operator==(KeyframeSetView const& other) const { return m_set == other.m_set; }
- size_t keyframe_count() const { return RustFFI::animations_keyframe_set_facts(m_set).keyframe_count; }
- RustFFI::FfiKeyframeValue value(size_t index, u16 property_id) const { return RustFFI::animations_keyframe_set_value(m_set, index, property_id); }
RustFFI::FfiKeyframeSetFacts facts() const { return RustFFI::animations_keyframe_set_facts(m_set); }
TargetProperties target_properties() const { return m_set ? TargetProperties { facts() } : TargetProperties {}; }
diff --git a/Libraries/LibWeb/Animations/NamedTimelines.cpp b/Libraries/LibWeb/Animations/NamedTimelines.cpp
index e0dffd47d0a..80967f7248c 100644
--- a/Libraries/LibWeb/Animations/NamedTimelines.cpp
+++ b/Libraries/LibWeb/Animations/NamedTimelines.cpp
@@ -6,7 +6,6 @@
#include <LibGC/Heap.h>
#include <LibWeb/Animations/NamedTimelines.h>
-#include <LibWeb/CSS/CSSAnimation.h>
#include <LibWeb/CSS/ComputedValues.h>
#include <LibWeb/CSS/StyleValues/StyleValue.h>
#include <LibWeb/DOM/Document.h>
@@ -14,7 +13,7 @@
#include <LibWeb/DOM/ShadowRoot.h>
#include <LibWeb/DOM/Text.h>
#include <LibWeb/HTML/HTMLSlotElement.h>
-#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
+#include <LibWeb/HTML/Scripting/Environments.h>
namespace Web::Animations {
@@ -36,10 +35,8 @@ void NamedTimelines::visit_edges(GC::Cell::Visitor& visitor)
visitor.visit(m_document);
for (auto& declaring_element : m_declaring_elements)
visitor.visit(declaring_element.element);
- for (auto& [key, timeline] : m_timelines) {
+ for (auto& [key, timeline] : m_timelines)
visitor.visit(key.element);
- visitor.visit(timeline);
- }
}
NamedTimelines::Declaration const* NamedTimelines::DeclaringElement::declaration_named(Utf16FlyString const& name) const
@@ -103,11 +100,17 @@ void NamedTimelines::refresh_declarations()
DeclaringElement declaring_element { .element = *element, .declarations = {}, .scopes_all_names = false, .scoped_names = {} };
CSS::ComputedValuesFFI::rust_animation_values_timeline_declarations(&values, &declaring_element, [](void* context, CSS::ComputedValuesFFI::FfiTimelineDeclaration const* declaration) {
+ // NB: The style engine hands over a reference to a calculated inset, which may be null.
+ auto retain = [](void const* value) {
+ return value ? CSS::RustStyleValueHandle::retained(static_cast<CSS::StyleValueFFI::StyleValueData const*>(value)) : CSS::RustStyleValueHandle {};
+ };
+ auto const& inset = declaration->view_inset;
static_cast<DeclaringElement*>(context)->declarations.append({
.name = CSS::css_string_from_rust(declaration->name),
.is_view = declaration->is_view,
- .axis = scroll_axis_from_css_axis(static_cast<CSS::Axis>(declaration->axis)),
- .view_inset = view_timeline_inset_from_ffi(declaration->view_inset),
+ .axis = declaration->axis,
+ .view_inset_start = { inset.start_is_auto, inset.start_px, inset.start_percentage, retain(inset.start_calculated) },
+ .view_inset_end = { inset.end_is_auto, inset.end_px, inset.end_percentage, retain(inset.end_calculated) },
});
});
auto scope = CSS::ComputedValuesFFI::rust_animation_values_timeline_scope(&values, &declaring_element, [](void* context, CSS::StyleValueFFI::CssString const* name) {
@@ -135,31 +138,39 @@ NamedTimelines::DeclaringElement const* NamedTimelines::declaring_element(DOM::E
return &m_declaring_elements[*index];
}
-GC::Ref<AnimationTimeline> NamedTimelines::timeline_for(DOM::Element& element, Declaration const& declaration)
+TimelineView NamedTimelines::timeline_for(DOM::Element& element, Declaration const& declaration)
{
+ auto edge = [](ViewTimelineInsetEdge const& edge) -> RustFFI::FfiViewTimelineInsetEdge {
+ return { .is_auto = edge.is_auto, .px = edge.px, .percentage = edge.percentage, .calculated = edge.calculated.data() };
+ };
+ RustFFI::FfiViewTimelineInset inset { .start = edge(declaration.view_inset_start), .end = edge(declaration.view_inset_end) };
+
TimelineKey key { element, declaration.name };
- if (auto existing = m_timelines.get(key); existing.has_value()) {
+ if (auto existing = m_timelines.get(key); existing.has_value() && existing->is_view_timeline() == declaration.is_view) {
// An element may only define one timeline per name, which keeps its identity while its axis and inset change.
- if (existing.value()->is_view_timeline() && declaration.is_view) {
- existing.value()->set_axis_and_inset(declaration.axis, declaration.view_inset);
- return *existing;
- }
- if (!existing.value()->is_view_timeline() && !declaration.is_view) {
- existing.value()->set_axis(declaration.axis);
- return *existing;
- }
+ // NB: The animations the timeline updates as they change stay alive through it, which can run script.
+ GC::RootVector<AnimationRef> updated_animations;
+ RustFFI::FfiTimelineAnimationsHost host { .context = &updated_animations, .keep_alive = keep_animation_alive_in, .perform = web_animation_perform_host_effect };
+ RustFFI::animations_scroll_timeline_set_axis_and_inset(&existing->record(), declaration.axis, declaration.is_view ? &inset : nullptr, &host);
+ return *existing;
}
- HTML::TemporaryExecutionContext context { m_document->relevant_settings_object() };
- auto timeline = declaration.is_view
- ? AnimationTimeline::create_view_timeline(m_document, DOM::AbstractElement { element }, declaration.axis, declaration.view_inset)
- : AnimationTimeline::create_scroll_timeline(m_document, GC::Ptr<DOM::Element const> { &element }, declaration.axis);
+ RustFFI::FfiTimelineDescription description {
+ .kind = declaration.is_view ? RustFFI::FfiTimelineKind::View : RustFFI::FfiTimelineKind::Scroll,
+ .origin_time = 0,
+ .source = declaration.is_view
+ ? RustFFI::FfiScrollTimelineSource { .element = nullptr, .is_anonymous = true, .scroller = to_underlying(CSS::Scroller::Nearest), .target = &element, .pseudo_element = 0, .has_pseudo_element = false }
+ : RustFFI::FfiScrollTimelineSource { .element = &element, .is_anonymous = false, .scroller = 0, .target = nullptr, .pseudo_element = 0, .has_pseudo_element = false },
+ .axis = declaration.axis,
+ .inset = inset,
+ };
+ TimelineView timeline { *RustFFI::animations_document_create_timeline(m_document.ptr(), &description) };
m_timelines.set(key, timeline);
return timeline;
}
// https://drafts.csswg.org/scroll-animations-1/#target-timeline
-GC::Ptr<AnimationTimeline> NamedTimelines::target_timeline(DOM::AbstractElement const& element, Utf16FlyString const& name)
+Optional<TimelineView> NamedTimelines::target_timeline(DOM::AbstractElement const& element, Utf16FlyString const& name)
{
refresh_declarations();
@@ -200,7 +211,7 @@ GC::Ptr<AnimationTimeline> NamedTimelines::target_timeline(DOM::AbstractElement
if (declaration && is_in_scope_of(candidate.element, current_element))
return timeline_for(candidate.element, *declaration);
}
- return nullptr;
+ return {};
}
// Otherwise, the target timeline for element's flat tree parent referencing name.
@@ -209,12 +220,30 @@ GC::Ptr<AnimationTimeline> NamedTimelines::target_timeline(DOM::AbstractElement
break;
current = DOM::AbstractElement { *parent };
}
- return nullptr;
+ return {};
+}
+
+namespace {
+
+// What looking up the named timelines of the CSS animations of the document again asks of the host.
+struct NamedTimelinesHostContext {
+ GC::Ref<NamedTimelines> named_timelines;
+ // NB: The animations stay alive while their timelines are looked up, which can run script.
+ GC::RootVector<AnimationRef> animations;
+};
+
+RustFFI::TimelineCell const* target_timeline_of_owner(void* context, RustFFI::FfiOwningElement owner, size_t name)
+{
+ DOM::AbstractElement target { *static_cast<DOM::Element*>(owner.element), owner.has_pseudo_element ? static_cast<CSS::PseudoElement>(owner.pseudo_element) : Optional<CSS::PseudoElement> {} };
+ auto timeline = static_cast<NamedTimelinesHostContext*>(context)->named_timelines->target_timeline(target, Utf16FlyString::from_raw(name));
+ return timeline.has_value() ? &timeline->record() : nullptr;
}
-void NamedTimelines::track_animation(AnimationRef const& animation)
+void keep_alive(void* context, RustFFI::AnimationCell const* animation)
{
- m_document->animations_following_named_timelines().set(animation);
+ keep_animation_alive_in(&static_cast<NamedTimelinesHostContext*>(context)->animations, animation);
+}
+
}
bool NamedTimelines::update_tracked_animations()
@@ -223,15 +252,15 @@ bool NamedTimelines::update_tracked_animations()
if (!m_tracked_animations_need_update)
return false;
m_tracked_animations_need_update = false;
- GC::RootVector<AnimationRef> animations;
- for (auto const& animation : m_document->animations_following_named_timelines())
- animations.append(animation);
- bool any_timeline_changed = false;
- for (auto const& animation : animations) {
- if (CSS::CSSAnimation::update_named_timeline(animation))
- any_timeline_changed = true;
- }
- return any_timeline_changed;
+ NamedTimelinesHostContext context { *this, {} };
+ RustFFI::FfiNamedTimelinesHost host {
+ .context = &context,
+ .target_timeline = target_timeline_of_owner,
+ .keep_alive = keep_alive,
+ .in_execution_context = in_execution_context_of_animation,
+ .perform = web_animation_perform_host_effect,
+ };
+ return m_document->update_named_timelines_of_animations(host);
}
}
diff --git a/Libraries/LibWeb/Animations/NamedTimelines.h b/Libraries/LibWeb/Animations/NamedTimelines.h
index ecc2e8368e6..66ad89ec325 100644
--- a/Libraries/LibWeb/Animations/NamedTimelines.h
+++ b/Libraries/LibWeb/Animations/NamedTimelines.h
@@ -12,8 +12,8 @@
#include <LibGC/Cell.h>
#include <LibGC/CellAllocator.h>
#include <LibGC/Ptr.h>
-#include <LibWeb/Animations/AnimationTimeline.h>
#include <LibWeb/Animations/RecordHandles.h>
+#include <LibWeb/CSS/StyleValues/RustStyleValueHandle.h>
#include <LibWeb/Forward.h>
namespace Web::Animations {
@@ -29,11 +29,7 @@ public:
[[nodiscard]] static GC::Ref<NamedTimelines> create(DOM::Document&);
// https://drafts.csswg.org/scroll-animations-1/#target-timeline
- GC::Ptr<AnimationTimeline> target_timeline(DOM::AbstractElement const&, Utf16FlyString const& name);
-
- // Tracks a CSS animation whose timeline is a named timeline, so that it follows the timeline its name finds as the
- // declarations of the document change.
- void track_animation(AnimationRef const&);
+ Optional<TimelineView> target_timeline(DOM::AbstractElement const&, Utf16FlyString const& name);
// Looks the timelines of the tracked animations up again, where the declarations of the document have changed.
// Returns whether any animation changed its timeline.
@@ -44,11 +40,23 @@ private:
virtual void visit_edges(GC::Cell::Visitor&) override;
+ // One side of the view progress visibility range: auto takes the scroll container's scroll padding, otherwise a
+ // length plus a percentage of the scrollport.
+ // https://drafts.csswg.org/scroll-animations-1/#view-timeline-inset
+ struct ViewTimelineInsetEdge {
+ bool is_auto { true };
+ double px { 0 };
+ double percentage { 0 };
+ // NB: An inset only a calculation can describe, such as min(50%, 10px), resolves against the scrollport size.
+ CSS::RustStyleValueHandle calculated {};
+ };
struct Declaration {
Utf16FlyString name;
bool is_view { false };
- ScrollAxis axis { ScrollAxis::Block };
- ViewTimelineInset view_inset;
+ // NB: The host's ScrollAxis, which numbers the axes as CSS::Axis does.
+ u8 axis { 0 };
+ ViewTimelineInsetEdge view_inset_start;
+ ViewTimelineInsetEdge view_inset_end;
};
struct DeclaringElement {
GC::Ref<DOM::Element> element;
@@ -65,7 +73,7 @@ private:
void refresh_declarations();
DeclaringElement const* declaring_element(DOM::Element const&) const;
- GC::Ref<AnimationTimeline> timeline_for(DOM::Element&, Declaration const&);
+ TimelineView timeline_for(DOM::Element&, Declaration const&);
GC::Ref<DOM::Document> m_document;
@@ -84,7 +92,8 @@ private:
struct TimelineKeyTraits : public DefaultTraits<TimelineKey> {
static unsigned hash(TimelineKey const& key) { return pair_int_hash(ptr_hash(key.element.ptr()), key.name.hash()); }
};
- HashMap<TimelineKey, GC::Ref<AnimationTimeline>, TimelineKeyTraits> m_timelines;
+ // NB: The document keeps the timelines alive.
+ HashMap<TimelineKey, TimelineView, TimelineKeyTraits> m_timelines;
// NB: The document holds the tracked animations, as its animations following named timelines.
bool m_tracked_animations_need_update { false };
diff --git a/Libraries/LibWeb/Animations/RecordHandles.cpp b/Libraries/LibWeb/Animations/RecordHandles.cpp
index 1b3f99fb965..cf2dc80200a 100644
--- a/Libraries/LibWeb/Animations/RecordHandles.cpp
+++ b/Libraries/LibWeb/Animations/RecordHandles.cpp
@@ -8,7 +8,6 @@
#include <LibJS/HostClassBuilder.h>
#include <LibJS/Runtime/Realm.h>
#include <LibWeb/Animations/AnimationEffect.h>
-#include <LibWeb/Animations/AnimationTimeline.h>
#include <LibWeb/Animations/RecordHandles.h>
#include <LibWeb/CSS/CSSStyleProperties.h>
#include <LibWeb/CSS/ComputedStyleWorkingSet.h>
@@ -41,7 +40,6 @@
#include <LibWeb/Layout/RenderDocument.h>
#include <LibWeb/Layout/Viewport.h>
#include <LibWeb/Namespace.h>
-#include <LibWeb/Painting/CompositorAnimationEffectState.h>
#include <LibWeb/Painting/Scrolling.h>
#include <LibWeb/SVG/SVGAnimationElement.h>
#include <LibWeb/SVG/SVGElement.h>
@@ -62,25 +60,15 @@ void visit_host_cell(void* visitor, void* cell, RustFFI::HostCellKind kind)
VERIFY_NOT_REACHED();
}
-extern "C" {
-
-// Declared in Bindings/Rust/src/css/animation_event.rs.
-void web_animation_visit_host_cells(RustFFI::AnimationCell const*, void* visitor);
-}
-
-void web_animation_visit_host_cells(RustFFI::AnimationCell const* animation, void* visitor)
-{
- RustFFI::animations_animation_visit_host_cells(animation, visitor, visit_host_cell);
-}
-
void keep_animation_alive_in(void* root_vector, RustFFI::AnimationCell const* animation)
{
static_cast<GC::RootVector<AnimationRef>*>(root_vector)->append(AnimationRef { *animation });
}
-i32 AnimationRef::composite_order(AnimationRef const& a, AnimationRef const& b)
+void in_execution_context_of_animation(void*, RustFFI::AnimationCell const* animation, void (*run)(void*), void* run_context)
{
- return RustFFI::animations_composite_order(&a.record(), &b.record(), compare_elements_in_tree_order_for_composite_order);
+ HTML::TemporaryExecutionContext execution_context { HTML::relevant_realm(relevant_global_object_of(AnimationRef { *animation })) };
+ run(run_context);
}
Optional<CSS::PseudoElement> EffectRef::pseudo_element_type() const
@@ -91,45 +79,20 @@ Optional<CSS::PseudoElement> EffectRef::pseudo_element_type() const
return static_cast<CSS::PseudoElement>(pseudo_element.kind);
}
-Optional<DOM::AbstractElement> EffectRef::target_abstract_element() const
+void EffectRef::invalidate() const
{
+ RustFFI::animations_effect_forget_what_the_host_concluded(&record());
if (auto* target = this->target())
- return DOM::AbstractElement { *target, pseudo_element_type() };
- return {};
-}
-
-CSS::EasingFunction::Descriptor EffectRef::timing_function_with_points_in(Vector<CSS::EasingFunction::LinearPoint>& storage) const
-{
- auto descriptor = RustFFI::animations_effect_timing_function(&record()).descriptor;
- storage.append(descriptor.linear_points, descriptor.linear_point_count);
- descriptor.linear_points = storage.data();
- descriptor.linear_point_count = storage.size();
- return descriptor;
-}
-
-RustFFI::FfiResolvedEffectTiming EffectRef::resolve_timing() const
-{
- auto animation = associated_animation();
- auto local_time = animation.has_value() ? animation->timing_state().current_time : to_ffi(Optional<TimeValue> {});
- return RustFFI::animations_effect_resolve_timing(&record(), local_time, timing().fill_mode, animation.has_value() ? &animation->record() : nullptr, false);
-}
-
-Painting::CompositorAnimationEffectState EffectRef::compositor_animation_state() const
-{
- return Painting::CompositorAnimationEffectState { RustFFI::animations_effect_compositor_animation_state(&record(), RustFFI::CompositorAnimationStateAccess::CreateIfMissing) };
+ target->document().set_needs_animated_style_update(*this);
}
-Optional<Painting::CompositorAnimationEffectState> EffectRef::existing_compositor_animation_state() const
-{
- if (auto* state = RustFFI::animations_effect_compositor_animation_state(&record(), RustFFI::CompositorAnimationStateAccess::Existing))
- return Painting::CompositorAnimationEffectState { state };
- return {};
-}
+// What the animation records ask of the host.
+extern "C" void web_animation_set_needs_animated_style_update(void const* effect, DOM::Element* target);
+extern "C" RustFFI::FfiTargetFacts web_animation_target_facts(DOM::Element* target, u32 wanted);
-bool EffectRef::has_retained_compositor_animations() const
+void web_animation_set_needs_animated_style_update(void const* effect, DOM::Element* target)
{
- auto state = existing_compositor_animation_state();
- return state.has_value() && state->has_retained();
+ target->document().set_needs_animated_style_update(EffectRef { *static_cast<RustFFI::AnimationEffectCell const*>(effect) });
}
// Whether nothing shows the target's style, as a display: none ancestor leaves the target without a box.
@@ -148,247 +111,6 @@ static bool target_is_unseen_in_display_none_subtree(DOM::Element const& target)
return !has_referenceable_svg_element;
}
-// NB: A custom property can feed the display of the target through var().
-bool EffectRef::may_animate_display() const
-{
- return any_of(target_properties(), [](auto const& property) {
- return property.id() == CSS::PropertyID::Display || property.is_custom_property();
- });
-}
-
-bool EffectRef::can_skip_per_frame_style_update() const
-{
- if (is_compositor_driven() || is_compositor_replaced())
- return true;
- if (is_offscreen_throttled() && all_of(target_properties(), [](auto const& property) {
- return !first_is_one_of(property.id(), CSS::PropertyID::Transform, CSS::PropertyID::Translate, CSS::PropertyID::Rotate, CSS::PropertyID::Scale);
- }))
- return true;
-
- auto* target = this->target();
- if (!target)
- return false;
-
- // An animation inside a box-less iframe can't affect its embedding document's rendering. Check the containers
- // before the target-local cache, since their layout can change without changing the target's style or layout box.
- // Reverse playback and effects with a finite end time need ticks to finish, even with an infinite iteration count.
- auto const timing = this->timing();
- if (auto animation = associated_animation(); animation.has_value()) {
- auto const state = animation->timing_state();
- if (state.playback.playback_rate > 0 && isinf(timing.iteration_count) && isinf(state.end_time.value)) {
- for (auto navigable = target->document().navigable(); navigable;) {
- auto container = navigable->container();
- if (!container)
- break;
- if (container->document().layout_is_up_to_date() && !container->has_layout_box())
- return true;
- navigable = container->document().navigable();
- }
- }
- }
-
- Layout::ForcedReadScope read { target->document() };
- auto skip_key = [&] {
- return RustFFI::PerFrameStyleUpdateSkipKey {
- .target_style_generation = target->animation_style_generation(),
- .target_subtree_style_generation = target->animation_subtree_style_generation(),
- .layout_node = bit_cast<FlatPtr>(target->unsafe_layout_node(read)),
- .target_is_connected = target->is_connected(),
- };
- };
- auto cache_result = [&](bool result) {
- if (target->document().layout_is_up_to_date()) {
- auto key = skip_key();
- RustFFI::animations_effect_note_per_frame_style_update_skip_decision(&record(), &key, result);
- }
- return result;
- };
- if (target->document().layout_is_up_to_date()) {
- auto key = skip_key();
- switch (RustFFI::animations_effect_per_frame_style_update_skip_decision(&record(), &key)) {
- case RustFFI::PerFrameStyleUpdateSkipDecision::CanSkip:
- HTML::note_rendering_trace_event("animation style skip cache hit"sv);
- return true;
- case RustFFI::PerFrameStyleUpdateSkipDecision::CannotSkip:
- HTML::note_rendering_trace_event("animation style skip cache hit"sv);
- return false;
- case RustFFI::PerFrameStyleUpdateSkipDecision::Stale:
- HTML::note_rendering_trace_event("animation style skip cache miss"sv);
- break;
- case RustFFI::PerFrameStyleUpdateSkipDecision::Unknown:
- break;
- }
- }
-
- // Restrict throttling within a rendered document to infinite transform-only effects until animation overflow
- // updates can also be throttled safely.
- if (!isinf(timing.iteration_count) || pseudo_element_type().has_value())
- return cache_result(false);
-
- if (!target->is_connected())
- return cache_result(true);
- if (target->document().layout_is_up_to_date() && !may_animate_display() && target_is_unseen_in_display_none_subtree(*target))
- return cache_result(true);
- if (!keyframe_set())
- return false;
- if (target_properties().is_empty() || any_of(target_properties(), [](auto const& property) {
- return !first_is_one_of(property.id(),
- CSS::PropertyID::Transform,
- CSS::PropertyID::Translate,
- CSS::PropertyID::Rotate,
- CSS::PropertyID::Scale);
- }))
- return cache_result(false);
-
- // NB: Transforms cannot affect rendering without a layout box. This also covers SVG content inside
- // display-none subtrees and closed details elements.
- if (target->document().layout_is_up_to_date() && !target->has_layout_box())
- return cache_result(true);
- if (target->namespace_uri() == Namespace::SVG)
- return cache_result(false);
-
- if (is_offscreen_throttled())
- return cache_result(true);
-
- if (!target->document().layout_is_up_to_date())
- return false;
- auto const* layout_node = target->unsafe_layout_node(read);
- if (!layout_node || layout_node->visibility() != CSS::Visibility::Hidden)
- return cache_result(false);
-
- bool has_visible_descendant = false;
- layout_node->for_each_in_inclusive_subtree_of_type<Layout::NodeWithStyle>([&](auto const& descendant) {
- if (descendant.visibility() != CSS::Visibility::Visible)
- return TraversalDecision::Continue;
- has_visible_descendant = true;
- return TraversalDecision::Break;
- });
- if (has_visible_descendant)
- return cache_result(false);
-
- return cache_result(true);
-}
-
-void EffectRef::set_composite(CSS::StyleValueFFI::FfiCompositeOperation composite) const
-{
- RustFFI::animations_effect_set_composite(&record(), composite);
- invalidate();
-}
-
-void EffectRef::set_keyframe_set(KeyframeSetHandle keyframe_set) const
-{
- if (this->keyframe_set() == keyframe_set)
- return;
-
- if (!RustFFI::animations_effect_set_keyframe_set(&record(), keyframe_set.ptr()))
- return;
- if (auto* target = this->target())
- CSS::record_attr_names_read_by_keyframes(*target, this->keyframe_set());
- invalidate();
-}
-
-void EffectRef::set_target(DOM::Element* target, InvalidateEffect invalidate) const
-{
- // NB: The record associates the associated animation with the new target rather than the old.
- RustFFI::animations_effect_set_target_element(&record(), target, perform_host_effect);
- if (invalidate == InvalidateEffect::No)
- return;
-
- if (target)
- CSS::record_attr_names_read_by_keyframes(*target, keyframe_set());
- this->invalidate();
- // FIXME: We don't remove the animated style from the old target element as part of normal animated style update and
- // it will remain "stuck" until it's style is fully invalidated for some other reason.
-}
-
-void EffectRef::set_target(DOM::AbstractElement abstract_element, InvalidateEffect invalidate) const
-{
- if (invalidate == InvalidateEffect::Yes) {
- set_target(&abstract_element.element());
- } else {
- VERIFY(!associated_animation().has_value());
- set_target(&abstract_element.element(), InvalidateEffect::No);
- CSS::record_attr_names_read_by_keyframes(abstract_element.element(), keyframe_set());
- }
- set_pseudo_element(abstract_element.pseudo_element());
-}
-
-void EffectRef::set_pseudo_element(Optional<CSS::PseudoElement> pseudo_element) const
-{
- if (!pseudo_element.has_value()) {
- RustFFI::animations_effect_set_pseudo_element(&record(), { .kind = 0, .serialization = 0 });
- return;
- }
- Utf16FlyString serialization { CSS::Selector::PseudoElementSelector { *pseudo_element }.serialize() };
- RustFFI::animations_effect_set_pseudo_element(&record(), { .kind = to_underlying(*pseudo_element), .serialization = serialization.raw_identity() });
-}
-
-void EffectRef::invalidate() const
-{
- RustFFI::animations_effect_forget_what_the_host_concluded(&record());
- if (auto* target = this->target())
- target->document().set_needs_animated_style_update(*this);
-}
-
-void EffectRef::request_observation_sample() const
-{
- if (set_flag(RustFFI::EffectFlag::NeedsObservationSample, true))
- note_observation_sample_requested();
-}
-
-bool EffectRef::request_element_scoped_observation_sample(u64 task_generation) const
-{
- switch (RustFFI::animations_effect_request_observation_sample_in_task(&record(), task_generation)) {
- case RustFFI::ObservationSampleRequest::AlreadyRequestedInTask:
- return false;
- case RustFFI::ObservationSampleRequest::Requested:
- return true;
- case RustFFI::ObservationSampleRequest::NewlyRequested:
- note_observation_sample_requested();
- return true;
- }
- VERIFY_NOT_REACHED();
-}
-
-void EffectRef::note_observation_sample_requested() const
-{
- if (auto* target = this->target())
- target->document().set_needs_animated_style_update(*this);
-}
-
-bool EffectRef::can_skip_per_frame_animation_tick() const
-{
- auto animation = associated_animation();
- auto const state = animation.has_value() ? animation->timing_state() : RustFFI::FfiAnimationTimingState {};
- auto const phase = animation.has_value() ? state.phase : resolve_timing().phase;
- auto const timing = this->timing();
-
- if (animation.has_value() && !state.playback.has_pending_play_task && !state.playback.has_pending_pause_task
- && state.play_state == RustFFI::AnimationPlayState::Running
- && state.playback.playback_rate > 0
- && state.has_monotonically_increasing_timeline
- && phase == RustFFI::AnimationEffectPhase::Before)
- return true;
-
- if (!is_compositor_driven() && !is_compositor_replaced() && !can_skip_per_frame_style_update())
- return false;
-
- // NB: Playing backward, an effect with an infinite iteration count finishes at time zero, and with a zero iteration
- // duration it finishes at its end time. No timer wakes the main thread for either.
- if (animation.has_value() && isinf(timing.iteration_count) && (state.playback.playback_rate < 0 || !isinf(state.end_time.value)))
- return false;
-
- // A compositor-handled one-iteration effect has a document timer that wakes the main thread at its active end.
- if ((is_compositor_driven() || is_compositor_replaced()) && (!isinf(timing.iteration_count) || is_observation_relevant_compositor_animation()))
- return true;
-
- // NB: Infinite effects cannot reach their natural end, and finite offscreen paint effects have an end timer.
- // Neither needs a continuous tick for animationend listeners.
- // NB: Starting or cancelling an active animation requests an update independently of playback.
- // Only iteration events require future updates while a visually throttled effect runs.
- return !css_animation_events_are_heard(state, phase == RustFFI::AnimationEffectPhase::Active);
-}
-
// Whether a listener on `target`, the nodes its events bubble to or its window hears an event `hears` names.
template<typename Hears>
static bool event_is_heard_at(DOM::Element& target, Hears const& hears)
@@ -405,39 +127,85 @@ static bool event_is_heard_at(DOM::Element& target, Hears const& hears)
return window && hears(*window);
}
-// Whether a listener hears the CSS animation events of the effect, whose associated animation's timing is `state`,
-// that need a tick: only its iteration events if `only_iteration_events`.
-bool EffectRef::css_animation_events_are_heard(RustFFI::FfiAnimationTimingState const& state, bool only_iteration_events) const
-{
- auto animation = associated_animation();
-
- // NB: SMIL animations raise time events at their animation element instead, which do not bubble.
- if (animation.has_value() && state.kind == RustFFI::FfiAnimationKind::Smil) {
- auto& animation_element = *static_cast<SVG::SVGAnimationElement*>(RustFFI::animations_smil_animation_element(&animation->record()));
- if (only_iteration_events)
- return animation_element.has_event_listener(HTML::EventNames::repeatEvent);
- return animation_element.has_event_listener(HTML::EventNames::beginEvent)
- || animation_element.has_event_listener(HTML::EventNames::endEvent)
- || animation_element.has_event_listener(HTML::EventNames::repeatEvent);
- }
-
- // Script animations do not dispatch CSS animation events, even when an ancestor listens for them.
- if (animation.has_value() && state.kind != RustFFI::FfiAnimationKind::CssAnimation)
+static bool target_fact_holds(DOM::Element& target, u32 fact)
+{
+ switch (fact) {
+ case RustFFI::TARGET_FACT_LAYOUT_IS_UP_TO_DATE:
+ return target.document().layout_is_up_to_date();
+ case RustFFI::TARGET_FACT_IS_CONNECTED:
+ return target.is_connected();
+ case RustFFI::TARGET_FACT_HAS_LAYOUT_BOX:
+ return target.has_layout_box();
+ case RustFFI::TARGET_FACT_IS_SVG:
+ return target.namespace_uri() == Namespace::SVG;
+ case RustFFI::TARGET_FACT_INSIDE_BOXLESS_CONTAINER:
+ for (auto navigable = target.document().navigable(); navigable;) {
+ auto container = navigable->container();
+ if (!container)
+ break;
+ if (container->document().layout_is_up_to_date() && !container->has_layout_box())
+ return true;
+ navigable = container->document().navigable();
+ }
return false;
-
- auto* target = this->target();
- VERIFY(target);
- return event_is_heard_at(*target, [only_iteration_events](DOM::EventTarget const& event_target) {
- if (only_iteration_events)
+ case RustFFI::TARGET_FACT_UNSEEN_IN_DISPLAY_NONE_SUBTREE:
+ return target_is_unseen_in_display_none_subtree(target);
+ case RustFFI::TARGET_FACT_HIDDEN_WITHOUT_VISIBLE_DESCENDANT: {
+ Layout::ForcedReadScope read { target.document() };
+ auto const* layout_node = target.unsafe_layout_node(read);
+ if (!layout_node || layout_node->visibility() != CSS::Visibility::Hidden)
+ return false;
+ bool has_visible_descendant = false;
+ layout_node->for_each_in_inclusive_subtree_of_type<Layout::NodeWithStyle>([&](auto const& descendant) {
+ if (descendant.visibility() != CSS::Visibility::Visible)
+ return TraversalDecision::Continue;
+ has_visible_descendant = true;
+ return TraversalDecision::Break;
+ });
+ return !has_visible_descendant;
+ }
+ case RustFFI::TARGET_FACT_HEARS_CSS_ANIMATION_EVENTS:
+ return event_is_heard_at(target, [](DOM::EventTarget const& event_target) {
+ return event_target.has_event_listener(HTML::EventNames::animationcancel)
+ || event_target.has_event_listener(HTML::EventNames::animationiteration)
+ || event_target.has_event_listener(HTML::EventNames::animationstart)
+ || event_target.has_event_listener(HTML::EventNames::webkitAnimationIteration)
+ || event_target.has_event_listener(HTML::EventNames::webkitAnimationStart);
+ });
+ case RustFFI::TARGET_FACT_HEARS_CSS_ANIMATION_ITERATION_EVENTS:
+ return event_is_heard_at(target, [](DOM::EventTarget const& event_target) {
return event_target.has_event_listener(HTML::EventNames::animationiteration)
|| event_target.has_event_listener(HTML::EventNames::webkitAnimationIteration);
+ });
+ case RustFFI::TARGET_FACT_HEARS_TIME_EVENTS:
+ return target.has_event_listener(HTML::EventNames::beginEvent)
+ || target.has_event_listener(HTML::EventNames::endEvent)
+ || target.has_event_listener(HTML::EventNames::repeatEvent);
+ case RustFFI::TARGET_FACT_HEARS_REPEAT_EVENT:
+ return target.has_event_listener(HTML::EventNames::repeatEvent);
+ }
+ VERIFY_NOT_REACHED();
+}
- return event_target.has_event_listener(HTML::EventNames::animationcancel)
- || event_target.has_event_listener(HTML::EventNames::animationiteration)
- || event_target.has_event_listener(HTML::EventNames::animationstart)
- || event_target.has_event_listener(HTML::EventNames::webkitAnimationIteration)
- || event_target.has_event_listener(HTML::EventNames::webkitAnimationStart);
- });
+RustFFI::FfiTargetFacts web_animation_target_facts(DOM::Element* target, u32 wanted)
+{
+ RustFFI::FfiTargetFacts answer {};
+ for (u32 fact = 1; fact <= wanted; fact <<= 1) {
+ if (!(wanted & fact))
+ continue;
+ if (fact == RustFFI::TARGET_FACT_SKIP_KEY) {
+ Layout::ForcedReadScope read { target->document() };
+ answer.key = {
+ .target_style_generation = target->animation_style_generation(),
+ .target_subtree_style_generation = target->animation_subtree_style_generation(),
+ .layout_node = bit_cast<FlatPtr>(target->unsafe_layout_node(read)),
+ .target_is_connected = target->is_connected(),
+ };
+ } else if (target_fact_holds(*target, fact)) {
+ answer.facts |= fact;
+ }
+ }
+ return answer;
}
static bool is_in_display_none_subtree_ignoring_animations(DOM::AbstractElement abstract_element)
@@ -461,7 +229,7 @@ void EffectRef::update_computed_properties(AnimationUpdateContext& context) cons
// keep their style under display: none.
DOM::AbstractElement abstract_element { *target, pseudo_element_type() };
if (abstract_element.pseudo_element().has_value()
- && !target_properties().contains(CSS::PropertyNameAndID::from_id(CSS::PropertyID::Display))
+ && !target_properties().contains(CSS::PropertyID::Display)
&& is_in_display_none_subtree_ignoring_animations(abstract_element))
return;
@@ -472,45 +240,31 @@ extern "C" {
// Declared in Bindings/Rust/src/animations/animation.rs.
void* web_animation_object_realm(RustFFI::AnimationCell const*);
-void* web_animation_object_event_target(RustFFI::AnimationCell const*);
-size_t web_animation_object_memory_size(RustFFI::AnimationCell const*);
-void web_animation_perform_promise_effect(JSVM*, RustFFI::FfiHostEffect const*);
-
-// Defined in Bindings/Rust/src/animations/exports.rs.
-void* web_animation_playback_event_create(JSVM*, void* realm, FlatPtr event_name, RustFFI::OptionalTimeValue current_time, RustFFI::OptionalTimeValue timeline_time);
+void web_animation_perform_object_effect(JSVM*, RustFFI::FfiHostEffect const*);
// What Bindings/Rust/src/animations asks of the host.
-void web_animation_perform_host_effect(RustFFI::FfiHostEffect const*);
-void web_animation_update_style_of_owning_element(RustFFI::AnimationCell const*);
-void web_animation_update_style_of_owning_element_document(RustFFI::AnimationCell const*);
+enum class StyleUpdateScope : u8 {
+ Element,
+ Document,
+};
+void web_animation_update_style_of_element(DOM::Element*, bool has_pseudo_element, u8 pseudo_element, StyleUpdateScope);
void* web_animation_realm_of_element(DOM::Element*);
-void* web_animation_document_timeline_of_document(DOM::Document*);
-void web_animation_visit_named_cells(RustFFI::AnimationCell const*, void* visitor);
-}
-
-static Optional<DOM::AbstractElement> owning_element_of(AnimationRef const& animation)
-{
- auto owner = RustFFI::animations_animation_owning_element(&animation.record());
- if (!owner.element)
- return {};
- Optional<CSS::PseudoElement> pseudo_element;
- if (owner.has_pseudo_element)
- pseudo_element = static_cast<CSS::PseudoElement>(owner.pseudo_element);
- return DOM::AbstractElement { *static_cast<DOM::Element*>(owner.element), pseudo_element };
+void* web_animation_realm_of_document(DOM::Document*);
+double web_animation_current_high_resolution_time(void* realm);
+void web_animation_append_pending_playback_event(DOM::Document*, RustFFI::AnimationCell const*, RustFFI::PlaybackEventType, RustFFI::OptionalTimeValue current_time, RustFFI::OptionalTimeValue timeline_time, RustFFI::OptionalNumber scheduled_event_time, double time_stamp);
+void web_animation_event_set_time_stamp(DOM::Event*, double time_stamp);
}
-// NB: Script observes a CSS animation or transition with the style of its owning element computed.
-void web_animation_update_style_of_owning_element(RustFFI::AnimationCell const* record)
+// NB: Script observes a CSS animation or transition with the style of its owning element computed, and the play state
+// of an animation with the style of the document of its owning element computed.
+void web_animation_update_style_of_element(DOM::Element* element, bool has_pseudo_element, u8 pseudo_element, StyleUpdateScope scope)
{
- if (auto owning_element = owning_element_of(AnimationRef { *record }); owning_element.has_value())
- owning_element->document().update_style_for_element(*owning_element, DOM::Document::StyleUpdateMode::OnlyIfNeeded);
-}
-
-// NB: Script observes the play state of an animation with the style of the document of its owning element computed.
-void web_animation_update_style_of_owning_element_document(RustFFI::AnimationCell const* record)
-{
- if (auto owning_element = owning_element_of(AnimationRef { *record }); owning_element.has_value())
- owning_element->document().update_style();
+ if (scope == StyleUpdateScope::Document) {
+ element->document().update_style();
+ return;
+ }
+ DOM::AbstractElement owning_element { *element, has_pseudo_element ? static_cast<CSS::PseudoElement>(pseudo_element) : Optional<CSS::PseudoElement> {} };
+ element->document().update_style_for_element(owning_element, DOM::Document::StyleUpdateMode::OnlyIfNeeded);
}
void* web_animation_realm_of_element(DOM::Element* element)
@@ -518,29 +272,35 @@ void* web_animation_realm_of_element(DOM::Element* element)
return &HTML::relevant_realm(element->document());
}
-void* web_animation_document_timeline_of_document(DOM::Document* document)
+void* web_animation_realm_of_document(DOM::Document* document)
{
- return document->timeline().ptr();
+ return &HTML::relevant_realm(*document);
}
-void web_animation_visit_named_cells(RustFFI::AnimationCell const* animation, void* visitor)
+double web_animation_current_high_resolution_time(void* realm)
{
- RustFFI::animations_animation_visit_named_cells(animation, visitor, visit_host_cell);
+ return HighResolutionTime::current_high_resolution_time(static_cast<JS::Realm*>(realm)->global_object());
}
-void set_owning_element(AnimationRef const& animation, DOM::AbstractElement owner)
+void web_animation_append_pending_playback_event(DOM::Document* document, RustFFI::AnimationCell const* animation, RustFFI::PlaybackEventType type, RustFFI::OptionalTimeValue current_time, RustFFI::OptionalTimeValue timeline_time, RustFFI::OptionalNumber scheduled_event_time, double time_stamp)
{
- auto pseudo_element = owner.pseudo_element();
- RustFFI::animations_animation_set_owning_element(&animation.record(), {
- .element = const_cast<DOM::Element*>(&owner.element()),
- .pseudo_element = pseudo_element.has_value() ? to_underlying(*pseudo_element) : u8 { 0 },
- .has_pseudo_element = pseudo_element.has_value(),
+ document->append_pending_animation_event(AnimationRef { *animation }, {
+ .kind = RustFFI::PendingAnimationEventKind::Playback,
+ .css_event_type = {},
+ .playback_event_type = type,
+ .time_event_type = {},
+ .detail = 0,
+ .elapsed_time = 0,
+ .current_time = current_time,
+ .timeline_time = timeline_time,
+ .scheduled_event_time = scheduled_event_time,
+ .time_stamp = time_stamp,
});
}
-size_t object_memory_size(AnimationRef const& animation)
+void web_animation_event_set_time_stamp(DOM::Event* event, double time_stamp)
{
- return web_animation_object_memory_size(&animation.record());
+ event->set_time_stamp(time_stamp);
}
void AnimationRef::visit_edges(GC::Cell::Visitor& visitor) const
@@ -548,45 +308,6 @@ void AnimationRef::visit_edges(GC::Cell::Visitor& visitor) const
RustFFI::animations_animation_visit_host_cells(&record(), &visitor, visit_host_cell);
}
-// https://www.w3.org/TR/web-animations-1/#animation-relevant
-bool AnimationRef::is_relevant() const
-{
- // NB: The local time of the associated effect is the current time of the animation.
- auto state = timing_state();
- return RustFFI::animations_is_relevant(&record(), state.has_effect ? state.current_time : to_ffi(Optional<TimeValue> {}));
-}
-
-void AnimationRef::update() const
-{
- RustFFI::animations_animation_update(&record(), perform_host_effect);
-}
-
-void AnimationRef::disassociate_from_target_if_inert() const
-{
- RustFFI::animations_animation_disassociate_from_target_if_inert(&record(), perform_host_effect);
-}
-
-void AnimationRef::run_pending_play_task_if_ready() const
-{
- RustFFI::animations_animation_run_pending_play_task_if_ready(&record(), perform_host_effect);
-}
-
-void AnimationRef::cancel(bool invalidate) const
-{
- // Note: When called from JS, we always want to invalidate the animation target's style. However, this method is
- // also called from the StyleComputer when the animation-name CSS property changes. That happens in the
- // middle of a cascade, and importantly, _before_ computing the animation effect stack, so there is no
- // need for another invalidation. It would also schedule a redundant follow-up reaction while the current
- // style computation is already updating the animation effect stack.
-
- // NB: Cancelling an animation that is not idle settles its promises and creates its cancel event.
- Optional<HTML::TemporaryExecutionContext> execution_context;
- if (timing_state().play_state != RustFFI::AnimationPlayState::Idle)
- execution_context.emplace(HTML::relevant_realm(relevant_global_object_of(*this)));
-
- RustFFI::animations_animation_cancel(&record(), invalidate, perform_host_effect);
-}
-
i32 compare_elements_in_tree_order_for_composite_order(void* first, void* second)
{
auto& first_element = *static_cast<DOM::Element*>(first);
@@ -594,15 +315,9 @@ i32 compare_elements_in_tree_order_for_composite_order(void* first, void* second
return first_element.document().compare_elements_in_tree_order_for_composite_order(first_element, second_element);
}
-// The realm of the object of the animation, or null where it has none.
-static JS::Realm* realm_of_object(AnimationRef const& animation)
-{
- return static_cast<JS::Realm*>(web_animation_object_realm(&animation.record()));
-}
-
JS::Object& relevant_global_object_of(AnimationRef const& animation)
{
- if (auto* realm = realm_of_object(animation))
+ if (auto* realm = static_cast<JS::Realm*>(web_animation_object_realm(&animation.record())))
return realm->global_object();
auto* element = static_cast<DOM::Element*>(RustFFI::animations_animation_owning_element(&animation.record()).element);
if (!element)
@@ -630,125 +345,7 @@ static void invalidate_effect(AnimationRef const& animation, ChangesPlan changes
effect->invalidate();
}
-// https://www.w3.org/TR/web-animations-1/#update-an-animations-finished-state
-// https://www.w3.org/TR/web-animations-1/#cancel-an-animation
-// https://www.w3.org/TR/web-animations-1/#remove-replaced-animations
-static Utf16FlyString const& playback_event_type_name(RustFFI::PlaybackEventType type)
-{
- switch (type) {
- case RustFFI::PlaybackEventType::Finish:
- return HTML::EventNames::finish;
- case RustFFI::PlaybackEventType::Cancel:
- return HTML::EventNames::cancel;
- case RustFFI::PlaybackEventType::Remove:
- return HTML::EventNames::remove;
- }
- VERIFY_NOT_REACHED();
-}
-
-// NB: A remove event is created in the realm of the document whose replaced animations are removed, which is the
-// document for timing of the animation, and whose pending animation event queue it joins.
-static JS::Realm& playback_event_realm(JS::Realm& realm, RustFFI::PlaybackEventType type, DOM::Document const* document_for_timing)
-{
- if (type == RustFFI::PlaybackEventType::Remove && document_for_timing)
- return HTML::relevant_realm(*document_for_timing);
- return realm;
-}
-
-// A new AnimationPlaybackEvent of the type, created in the realm.
-// https://drafts.csswg.org/web-animations-2/#animationplaybackevent
-static GC::Ref<DOM::Event> create_animation_playback_event(JS::Realm& realm, Utf16FlyString const& type, RustFFI::OptionalTimeValue current_time, RustFFI::OptionalTimeValue timeline_time)
-{
- auto* event = web_animation_playback_event_create(JS::HostABI::vm_to_abi(realm.vm()), &realm, type.to_utf16_string().into_raw(), current_time, timeline_time);
- return GC::Ref { *static_cast<DOM::Event*>(static_cast<GC::Cell*>(event)) };
-}
-
-static DOM::EventTarget& event_target_of_object(AnimationRef const& animation)
-{
- return *static_cast<DOM::EventTarget*>(static_cast<GC::Cell*>(web_animation_object_event_target(&animation.record())));
-}
-
-// https://www.w3.org/TR/web-animations-1/#animation-document-for-timing
-static GC::Ptr<DOM::Document> document_for_timing(AnimationRef const& animation)
-{
- // An animation’s document for timing is the Document with which its timeline is associated. If an animation is not
- // associated with a timeline, or its timeline is not associated with a document, then it has no document for
- // timing.
- auto* timeline = static_cast<AnimationTimeline*>(RustFFI::animations_animation_timeline(&animation.record()));
- if (!timeline)
- return {};
- return timeline->associated_document();
-}
-
-static void queue_playback_event(AnimationRef const& animation, JS::Realm& realm, RustFFI::FfiHostEffect const& effect)
-{
- auto is_finish = effect.playback_event_type == RustFFI::PlaybackEventType::Finish;
- auto document = document_for_timing(animation);
- auto& event_realm = playback_event_realm(realm, effect.playback_event_type, document.ptr());
-
- // If animation has a document for timing, then append the event to its document for timing's pending animation
- // event queue along with its target, animation.
- if (document) {
- // https://www.w3.org/TR/web-animations-1/#animation-time-to-origin-relative-time
- // NB: The procedure converted the time to a timeline time.
- Optional<double> scheduled_event_time;
- auto* timeline = static_cast<AnimationTimeline*>(RustFFI::animations_animation_timeline(&animation.record()));
- if (auto timeline_time = from_ffi(effect.scheduled_timeline_time); timeline_time.has_value()
- && timeline && !timeline->is_inactive() && timeline->can_convert_a_timeline_time_to_an_origin_relative_time())
- scheduled_event_time = timeline->convert_a_timeline_time_to_an_origin_relative_time(timeline_time);
- // NB: The queue holds what the event is, which the document creates as it dispatches it, with the time stamp
- // of now, when the event is created in the spec.
- document->append_pending_animation_event(animation, {
- .kind = RustFFI::PendingAnimationEventKind::Playback,
- .css_event_type = {},
- .playback_event_type = effect.playback_event_type,
- .time_event_type = {},
- .detail = 0,
- .elapsed_time = 0,
- .current_time = effect.current_time,
- .timeline_time = effect.timeline_time,
- .scheduled_event_time = to_ffi(scheduled_event_time),
- .time_stamp = HighResolutionTime::current_high_resolution_time(event_realm.global_object()),
- });
- return;
- }
-
- auto event = create_animation_playback_event(event_realm, playback_event_type_name(effect.playback_event_type), effect.current_time, effect.timeline_time);
- auto& target = event_target_of_object(animation);
-
- // Otherwise, queue a task to dispatch the event at animation. The task source for this task is the DOM manipulation
- // task source.
- if (!is_finish) {
- HTML::queue_global_task(HTML::Task::Source::DOMManipulation, realm.global_object(), GC::create_function(GC::Heap::the(), GC::captures(target, event), [](auto& target, auto& event) {
- target.dispatch_event(event);
- }));
- return;
- }
-
- // NB: The task to dispatch a finish event is created manually so its ID can be saved.
- auto& window_document = HTML::relevant_window(realm.global_object()).associated_document();
- auto task = HTML::Task::create(HTML::Task::Source::DOMManipulation, &window_document, GC::create_function(GC::Heap::the(), GC::captures(target, event), [](auto& target, auto& event) {
- target.dispatch_event(event);
- }));
- RustFFI::animations_animation_set_finish_notification_task(&animation.record(), task->id().value());
- (void)HTML::main_thread_event_loop().task_queue().add(task);
-}
-
-void dispatch_pending_playback_event(AnimationRef const& animation, DOM::Document const& document, RustFFI::FfiPendingAnimationEvent const& pending_event)
-{
- auto* realm = realm_of_object(animation);
- VERIFY(realm);
- auto event = create_animation_playback_event(playback_event_realm(*realm, pending_event.playback_event_type, &document), playback_event_type_name(pending_event.playback_event_type), pending_event.current_time, pending_event.timeline_time);
- event->set_time_stamp(pending_event.time_stamp);
- event_target_of_object(animation).dispatch_event(event);
-}
-
void web_animation_perform_host_effect(RustFFI::FfiHostEffect const* host_effect)
-{
- perform_host_effect(host_effect);
-}
-
-void perform_host_effect(RustFFI::FfiHostEffect const* host_effect)
{
auto const& effect = *host_effect;
AnimationRef animation { *effect.animation };
@@ -764,13 +361,8 @@ void perform_host_effect(RustFFI::FfiHostEffect const* host_effect)
case Kind::ReplaceFinishedPromise:
case Kind::ResolveFinishedPromise:
case Kind::RejectFinishedPromise:
- // NB: Only an animation with an object has promises script can observe.
- web_animation_perform_promise_effect(JS::HostABI::vm_to_abi(JS::VM::the()), host_effect);
- return;
case Kind::QueuePlaybackEvent:
- // NB: Only an animation with an object can hear its playback events.
- if (auto* realm = realm_of_object(animation))
- queue_playback_event(animation, *realm, effect);
+ web_animation_perform_object_effect(JS::HostABI::vm_to_abi(JS::VM::the()), host_effect);
return;
case Kind::QueueFinishNotificationTask: {
// NB: The task runs whether or not the animation has an object, as the finish notification steps note that the
@@ -779,7 +371,7 @@ void perform_host_effect(RustFFI::FfiHostEffect const* host_effect)
auto& document = HTML::relevant_window(global).associated_document();
auto task = HTML::Task::create(HTML::Task::Source::DOMManipulation, &document, GC::create_function(GC::Heap::the(), GC::captures(animation, global), [](AnimationRef const& animation, JS::Object& global) {
HTML::TemporaryExecutionContext context { HTML::relevant_realm(global) };
- RustFFI::animations_animation_run_finish_notification_steps(&animation.record(), perform_host_effect);
+ RustFFI::animations_animation_run_finish_notification_steps(&animation.record(), web_animation_perform_host_effect);
}));
RustFFI::animations_animation_set_finish_notification_task(&animation.record(), task->id().value());
(void)HTML::main_thread_event_loop().task_queue().add(move(task));
@@ -828,6 +420,161 @@ void perform_host_effect(RustFFI::FfiHostEffect const* host_effect)
VERIFY_NOT_REACHED();
}
+// NB: What the timelines associated with a document ask of it and of its layout.
+extern "C" {
+
+// Declared in Rust/src/animations/timeline_host.rs.
+RustFFI::DocumentAnimations* web_animation_document_animations(DOM::Document*);
+RustFFI::FfiDocumentClock web_animation_document_clock(DOM::Document*);
+void web_animation_find_scroll_timeline_boxes(RustFFI::FfiScrollTimelineSource const*, bool is_view, void* context, void (*measure)(void*, RustFFI::FfiScrollTimelineBoxes const*));
+DOM::Element* web_animation_scroll_timeline_source(RustFFI::FfiScrollTimelineSource const*, bool is_view);
+
+// Declared in Bindings/Rust/src/animations.
+DOM::Element* web_animation_document_scrolling_element(DOM::Document*);
+CSS::StyleValueFFI::StyleValueData const* web_animation_absolutize_style_value(DOM::Document*, CSS::StyleValueFFI::StyleValueData const*);
+}
+
+RustFFI::DocumentAnimations* web_animation_document_animations(DOM::Document* document)
+{
+ return &document->document_animations();
+}
+
+RustFFI::FfiDocumentClock web_animation_document_clock(DOM::Document* document)
+{
+ auto& settings = document->relevant_settings_object();
+ auto& global = settings.global_object();
+ return {
+ .now = HighResolutionTime::relative_high_resolution_time(HighResolutionTime::unsafe_shared_current_time(), global),
+ .task_generation = settings.responsible_event_loop().task_generation(),
+ .timeline_start_time = document->last_animation_frame_timestamp().value_or_lazy_evaluated([&] {
+ return HighResolutionTime::relative_high_resolution_time(document->load_timing_info().navigation_start_time, global);
+ }),
+ };
+}
+
+// The target an anonymous scroll timeline finds its scroller from.
+static DOM::AbstractElement anonymous_target(RustFFI::FfiScrollTimelineSource const& source)
+{
+ Optional<CSS::PseudoElement> pseudo_element;
+ if (source.has_pseudo_element)
+ pseudo_element = static_cast<CSS::PseudoElement>(source.pseudo_element);
+ return DOM::AbstractElement { *static_cast<DOM::Element*>(source.target), pseudo_element };
+}
+
+// https://drafts.csswg.org/scroll-animations-1/#dom-scrolltimeline-source
+static GC::Ptr<DOM::Element const> scroll_timeline_source(RustFFI::FfiScrollTimelineSource const& source)
+{
+ if (!source.is_anonymous)
+ return static_cast<DOM::Element const*>(source.element);
+ auto target = anonymous_target(source);
+ switch (static_cast<CSS::Scroller>(source.scroller)) {
+ case CSS::Scroller::Root:
+ return target.document().document_element();
+ case CSS::Scroller::Nearest: {
+ GC::Ptr<DOM::Element const> ancestor = target.flat_tree_parent_element();
+
+ // Whether a box is a scroll container depends on its used overflow, which is visible for a body whose
+ // overflow is propagated to the viewport. The document element stands for the viewport.
+ Layout::ForcedReadScope read { target.document() };
+ while (ancestor && !ancestor->is_document_element()) {
+ auto const* layout_node = ancestor->unsafe_layout_node(read);
+ if (layout_node && layout_node->is_scroll_container())
+ break;
+ ancestor = ancestor->flat_tree_parent_element();
+ }
+
+ return ancestor;
+ }
+ case CSS::Scroller::Self:
+ return target.element();
+ }
+ VERIFY_NOT_REACHED();
+}
+
+void web_animation_find_scroll_timeline_boxes(RustFFI::FfiScrollTimelineSource const* source, bool is_view, void* context, void (*measure)(void*, RustFFI::FfiScrollTimelineBoxes const*))
+{
+ // NB: The record measures the boxes the timeline follows where the render state of the document whose viewport or
+ // element the source propagates to lays them out.
+ RustFFI::FfiScrollTimelineBoxes boxes {
+ .host = nullptr,
+ .read = nullptr,
+ .scroller = Compositing::RustFFI::NodeSlotId_INVALID,
+ .has_scroll_node = false,
+ .scroll_node = {},
+ .scroller_style_node = 0,
+ .subject = Compositing::RustFFI::NodeSlotId_INVALID,
+ .subject_style_node = 0,
+ };
+
+ // https://drafts.csswg.org/scroll-animations-1/#scroll-notation
+ // References to the root element propagate to the document viewport (which functions as its scroll container).
+ auto const element = scroll_timeline_source(*source);
+ Variant<GC::Ptr<DOM::Element const>, GC::Ptr<DOM::Document>> propagated_source = element;
+ if (element && element.ptr() == element->document().document_element())
+ propagated_source = element->owner_document();
+ if (propagated_source.visit([](auto const& source) { return source == nullptr; }))
+ return measure(context, &boxes);
+
+ Layout::ForcedReadScope read { propagated_source.visit([](auto const& source) -> DOM::Document const& { return source->document(); }) };
+ auto const* layout_node = propagated_source.visit([&read](auto const& source) -> Layout::NodeWithStyle const* { return source->unsafe_layout_node(read); });
+ if (!layout_node)
+ return measure(context, &boxes);
+
+ boxes.host = layout_node->document_host();
+ boxes.read = read;
+ boxes.scroller = Layout::Node::slot_id(layout_node);
+ if (auto scroll_node = Painting::async_scroll_node_stable_id(*layout_node); scroll_node.has_value()) {
+ boxes.has_scroll_node = true;
+ boxes.scroll_node = { .node_id = scroll_node->node_id.value(), .kind = to_underlying(scroll_node->kind), .pseudo_element_type = scroll_node->pseudo_element_type };
+ }
+ boxes.scroller_style_node = propagated_source.visit(
+ [](GC::Ptr<DOM::Element const> const& element) { return element->style_node_id().value(); },
+ [](GC::Ptr<DOM::Document> const&) -> u32 { return 0; });
+ // NB: A view timeline follows the box of its subject besides its scroller's.
+ if (is_view) {
+ auto subject = anonymous_target(*source);
+ boxes.subject = Layout::Node::slot_id(subject.unsafe_layout_node(read));
+ // NB: A clock tick finds the subject by its style node, which a pseudo-element does not name.
+ if (!subject.pseudo_element().has_value())
+ boxes.subject_style_node = subject.element().style_node_id().value();
+ }
+ measure(context, &boxes);
+}
+
+DOM::Element* web_animation_scroll_timeline_source(RustFFI::FfiScrollTimelineSource const* source, bool is_view)
+{
+ if (is_view) {
+ // The values of subject, source, and currentTime are all computed when any of them is requested or updated.
+ auto subject = anonymous_target(*source);
+ subject.document().update_layout(DOM::UpdateLayoutReason::ViewTimelineSource);
+
+ // If the source or subject of a ViewTimeline is an element whose principal box does not exist, [...] then the
+ // ViewTimeline is inactive.
+ // INTEROP: Its source is then null, as WebKit and Blink have it.
+ for (GC::Ptr<DOM::Element const> element = &subject.element(); element; element = element->flat_tree_parent_element()) {
+ if (!element->has_style() || element->installed_style().display_is_none())
+ return nullptr;
+ }
+ } else if (source->is_anonymous && static_cast<CSS::Scroller>(source->scroller) == CSS::Scroller::Nearest) {
+ // The nearest scroll container is the nearest one by used overflow, which layout decides.
+ anonymous_target(*source).document().update_layout(DOM::UpdateLayoutReason::ScrollTimelineSource);
+ }
+ return const_cast<DOM::Element*>(scroll_timeline_source(*source).ptr());
+}
+
+DOM::Element* web_animation_document_scrolling_element(DOM::Document* document)
+{
+ return const_cast<DOM::Element*>(document->scrolling_element().ptr());
+}
+
+// NB: Absolutizes a style value that script gave, as the document's values are.
+CSS::StyleValueFFI::StyleValueData const* web_animation_absolutize_style_value(DOM::Document* document, CSS::StyleValueFFI::StyleValueData const* value)
+{
+ auto style_value = CSS::StyleValue::adopt_rust_style_value_data(CSS::StyleValueFFI::rust_style_value_retain(value));
+ auto computed = style_value->absolutized(CSS::ComputationContext { .length_resolution_context = CSS::Length::ResolutionContext::for_document(*document) });
+ return CSS::StyleValueFFI::rust_style_value_retain(computed->rust_style_value_data());
+}
+
// NB: What committing the computed styles of an animation answers its bindings.
enum class CommitStylesResult : u8 {
Committed,
@@ -901,7 +648,7 @@ extern "C" WEB_API CommitStylesResult web_animation_commit_styles(RustFFI::Anima
for (auto other_animation : target->associated_animations_in_composite_order()) {
auto other_effect = other_animation.effect();
if (other_effect.has_value() && !other_effect->pseudo_element_type().has_value()
- && RustFFI::animations_composite_order(&other_animation.record(), animation_cell, compare_elements_in_tree_order_for_composite_order) < 0)
+ && RustFFI::animations_animation_composite_order(&other_animation.record(), animation_cell, compare_elements_in_tree_order_for_composite_order) < 0)
effects.append(other_effect.release_value());
}
effects.append(*effect);
@@ -915,7 +662,8 @@ extern "C" WEB_API CommitStylesResult web_animation_commit_styles(RustFFI::Anima
// update above was, so the committed values are those of the time script read.
RefPtr<CSS::ComputedStyleWorkingSet> committed_style;
auto commit = [&] { committed_style = document.style_computer().compute_style_for_animation_commit(read, element, effects.span()); };
- AnimationTimeline::at_times_observed_ahead(document.associated_animation_timelines().begin(), document.associated_animation_timelines().end(), commit);
+ using Commit = decltype(commit);
+ RustFFI::animations_document_animations_at_times_observed_ahead(&document.document_animations(), &commit, [](void* context) { (*static_cast<Commit*>(context))(); });
auto style = committed_style.release_nonnull();
auto custom_properties = element.custom_property_data();
if (custom_properties && element.custom_property_data_is_animation_overlay())
@@ -972,4 +720,25 @@ extern "C" WEB_API double web_animation_effective_zoom_of_target(DOM::Element* t
return 1;
}
+// NB: What the timeline records ask of the document a timeline is associated with.
+extern "C" WEB_API void web_animation_note_rendering_trace_event(u8 const* event, size_t length);
+
+extern "C" WEB_API void web_animation_note_rendering_trace_event(u8 const* event, size_t length)
+{
+ HTML::note_rendering_trace_event(StringView { reinterpret_cast<char const*>(event), length });
+}
+
+}
+
+extern "C" WEB_API bool ladybird_animations_document_is_active(void* document);
+extern "C" WEB_API void* ladybird_animations_element_node_document(void* element);
+
+extern "C" WEB_API bool ladybird_animations_document_is_active(void* document)
+{
+ return static_cast<Web::DOM::Document const*>(document)->is_active();
+}
+
+extern "C" WEB_API void* ladybird_animations_element_node_document(void* element)
+{
+ return &static_cast<Web::DOM::Element*>(element)->document();
}
diff --git a/Libraries/LibWeb/Animations/RecordHandles.h b/Libraries/LibWeb/Animations/RecordHandles.h
index 023362e7fa7..0cc2952d51c 100644
--- a/Libraries/LibWeb/Animations/RecordHandles.h
+++ b/Libraries/LibWeb/Animations/RecordHandles.h
@@ -14,12 +14,6 @@
#include <LibWeb/CSS/EasingFunction.h>
#include <LibWeb/Forward.h>
-namespace Web::Painting {
-
-class CompositorAnimationEffectState;
-
-}
-
namespace Web::Animations {
struct AnimationUpdateContext;
@@ -105,27 +99,11 @@ public:
// https://www.w3.org/TR/web-animations-1/#animation-associated-effect
Optional<EffectRef> effect() const;
- // https://www.w3.org/TR/web-animations-1/#animation-relevant
- bool is_relevant() const;
-
- // What the host's per-frame decisions read of the animation now.
- RustFFI::FfiAnimationTimingState timing_state() const { return RustFFI::animations_animation_timing_state(&record(), false, 0); }
- // The same, with the current time of the animation at `timestamp` too.
- RustFFI::FfiAnimationTimingState timing_state_at_timestamp(double timestamp) const { return RustFFI::animations_animation_timing_state(&record(), true, timestamp); }
-
- // Updates the animation as its timeline updated its current time.
- void update() const;
- // https://www.w3.org/TR/web-animations-1/#dom-animation-cancel
- // Cancels the animation, invalidating the style of its target where `invalidate`.
- void cancel(bool invalidate = true) const;
- // Runs the pending play task of the animation if it is ready.
- void run_pending_play_task_if_ready() const;
- // Disassociates the animation from the target of its associated effect where it is inert, where a procedure
- // scheduled that.
- void disassociate_from_target_if_inert() const;
-
- // https://www.w3.org/TR/web-animations-1/#animation-composite-order
- static i32 composite_order(AnimationRef const&, AnimationRef const&);
+ // https://www.w3.org/TR/web-animations-1/#play-states
+ RustFFI::AnimationPlayState play_state() const { return RustFFI::animations_animation_play_state(&record()); }
+
+ // https://www.w3.org/TR/web-animations-1/#playback-rate
+ double playback_rate() const { return RustFFI::animations_animation_playback_rate(&record()); }
};
// A reference to the record of an animation effect.
@@ -133,10 +111,6 @@ class EffectRef : public RecordRef<EffectRef, RustFFI::AnimationEffectCell, Rust
public:
using RecordRef::RecordRef;
- // A new KeyframeEffect's state, with the default timing, no keyframes and no target, as a CSS animation or
- // transition creates its associated effect.
- static EffectRef create_keyframe_effect();
-
// Visits what keeps the element the record targets alive: the effect's AnimationEffect, or, for an effect without
// one, that element. A holder the GC traces visits this.
void visit_edges(GC::Cell::Visitor&) const;
@@ -149,67 +123,23 @@ public:
// https://www.w3.org/TR/web-animations-1/#effect-target
DOM::Element* target() const { return static_cast<DOM::Element*>(RustFFI::animations_effect_target(&record()).element); }
- enum class InvalidateEffect : bool {
- No,
- Yes,
- };
- // Sets the target element, and where `invalidate`, notes what the keyframes read of it and invalidates the style
- // the effect produces.
- void set_target(DOM::Element*, InvalidateEffect = InvalidateEffect::Yes) const;
- void set_target(DOM::AbstractElement, InvalidateEffect = InvalidateEffect::Yes) const;
- void set_pseudo_element(Optional<CSS::PseudoElement>) const;
Optional<CSS::PseudoElement> pseudo_element_type() const;
- Optional<DOM::AbstractElement> target_abstract_element() const;
// The keyframes the effect runs, which the view borrows until they change.
KeyframeSetView keyframe_set() const { return KeyframeSetView { RustFFI::animations_effect_keyframe_set(&record()) }; }
// https://www.w3.org/TR/web-animations-1/#target-property
// The properties the effect's keyframes animate, borrowed until its keyframes change.
TargetProperties target_properties() const { return keyframe_set().target_properties(); }
- bool composite_is_replace() const { return RustFFI::animations_effect_composite(&record()) == CSS::StyleValueFFI::FfiCompositeOperation::Replace; }
- // https://www.w3.org/TR/web-animations-1/#dom-keyframeeffect-composite
- void set_composite(CSS::StyleValueFFI::FfiCompositeOperation) const;
- // Sets the keyframes the effect runs, invalidating the style it produces where they change.
- void set_keyframe_set(KeyframeSetHandle) const;
- // The normalized timing the timing model reads of the effect.
- RustFFI::AnimationEffectTiming timing() const { return RustFFI::animations_effect_timing(&record()); }
- // The descriptor reads the timing function's control points from a copy in storage the caller keeps alive.
- CSS::EasingFunction::Descriptor timing_function_with_points_in(Vector<CSS::EasingFunction::LinearPoint>& storage) const;
-
- // The timing of the effect at its local time, the current time of its associated animation.
- RustFFI::FfiResolvedEffectTiming resolve_timing() const;
- void set_previous_phase_and_current_iteration(RustFFI::AnimationEffectPhase phase, double current_iteration) const { RustFFI::animations_effect_set_previous_phase_and_current_iteration(&record(), phase, current_iteration); }
-
bool has_flag(RustFFI::EffectFlag flag) const { return RustFFI::animations_effect_has_flag(&record(), flag); }
- bool set_flag(RustFFI::EffectFlag flag, bool value) const { return RustFFI::animations_effect_set_flag(&record(), flag, value); }
bool is_compositor_driven() const { return has_flag(RustFFI::EffectFlag::CompositorDriven); }
bool is_compositor_replaced() const { return has_flag(RustFFI::EffectFlag::CompositorReplaced); }
- bool is_offscreen_throttled() const { return has_flag(RustFFI::EffectFlag::OffscreenThrottled); }
- bool is_observation_relevant_compositor_animation() const { return has_flag(RustFFI::EffectFlag::ObservationRelevantCompositorAnimation); }
- bool per_frame_animation_tick_was_skipped() const { return has_flag(RustFFI::EffectFlag::PerFrameAnimationTickWasSkipped); }
-
- // Whether a compositor animation may run every property the effect targets.
- bool may_run_on_the_compositor() const { return RustFFI::animations_effect_may_run_on_the_compositor(&record()); }
- // The compositor animations built from this effect live in its record; the state is made when first needed.
- Painting::CompositorAnimationEffectState compositor_animation_state() const;
- Optional<Painting::CompositorAnimationEffectState> existing_compositor_animation_state() const;
- bool has_retained_compositor_animations() const;
// Invalidates the style the effect produces, forgetting what the host concluded of it.
void invalidate() const;
- bool can_skip_per_frame_style_update() const;
- bool can_skip_per_frame_animation_tick() const;
- void request_observation_sample() const;
- // Requests an observation sample on behalf of a read of an element, unless one was requested in the same task.
- bool request_element_scoped_observation_sample(u64 task_generation) const;
+ bool can_skip_per_frame_style_update() const { return RustFFI::animations_effect_can_skip_per_frame_style_update(&record()); }
// Samples the effect into the style of its target for the update.
void update_computed_properties(AnimationUpdateContext&) const;
-
-private:
- void note_observation_sample_requested() const;
- bool may_animate_display() const;
- bool css_animation_events_are_heard(RustFFI::FfiAnimationTimingState const&, bool only_iteration_events) const;
};
inline Optional<EffectRef> AnimationRef::effect() const
@@ -232,6 +162,8 @@ void visit_host_cell(void* visitor, void* cell, RustFFI::HostCellKind);
// Keeps an animation a procedure hands the host alive, as an AnimationRef appended to the GC::RootVector<AnimationRef>
// `root_vector`, for as long as that lives.
void keep_animation_alive_in(void* root_vector, RustFFI::AnimationCell const*);
+// Runs `run` with `run_context` in an execution context of the relevant realm of `animation`.
+void in_execution_context_of_animation(void*, RustFFI::AnimationCell const* animation, void (*run)(void*), void* run_context);
// The relevant global object of an animation: that of its object, or, for an animation that has none, that of the
// node document of the element that owns it or whose animation element it is.
@@ -239,21 +171,44 @@ JS::Object& relevant_global_object_of(AnimationRef const&);
// Performs what a procedure of an animation asked the host to do, which the host hands to the procedures to run. Only
// settling the promises of the animation and queueing its playback events need its object, and an animation that has
-// none has nothing to settle them for or to dispatch them at.
-void perform_host_effect(RustFFI::FfiHostEffect const*);
+// none has nothing to settle them for or to dispatch them at. Bindings/Rust/src/animations calls it too.
+extern "C" void web_animation_perform_host_effect(RustFFI::FfiHostEffect const*);
-// Creates the playback event the pending animation event queue of `document` holds of `animation`, and dispatches it
-// at the object of the animation.
-void dispatch_pending_playback_event(AnimationRef const&, DOM::Document const&, RustFFI::FfiPendingAnimationEvent const&);
+// Compares two DOM::Elements in tree order, as the composite order of their animations does.
+i32 compare_elements_in_tree_order_for_composite_order(void* first, void* second);
-// https://www.w3.org/TR/css-animations-2/#owning-element-section
-void set_owning_element(AnimationRef const&, DOM::AbstractElement);
+// A view of the record of a timeline associated with a document, which the document keeps alive for as long as it
+// lives.
+class TimelineView {
+public:
+ explicit TimelineView(RustFFI::TimelineCell const& record)
+ : m_record(&record)
+ {
+ }
-// The bytes of the objects script sees of an animation and of its associated effect, beside their records.
-size_t object_memory_size(AnimationRef const&);
+ RustFFI::TimelineCell const& record() const { return *m_record; }
-// Compares two DOM::Elements in tree order, as the composite order of their animations does.
-i32 compare_elements_in_tree_order_for_composite_order(void* first, void* second);
+ RustFFI::FfiTimeline read() const { return RustFFI::animations_timeline_read(m_record); }
+ Optional<RustFFI::TimeValue> current_time() const
+ {
+ auto current_time = read().current_time;
+ if (!current_time.has_value)
+ return {};
+ return current_time.value;
+ }
+ // A scroll timeline, or a view timeline, which is one.
+ bool is_scroll_timeline() const
+ {
+ auto kind = read().kind;
+ return kind == RustFFI::FfiTimelineKind::Scroll || kind == RustFFI::FfiTimelineKind::View;
+ }
+ bool is_view_timeline() const { return read().kind == RustFFI::FfiTimelineKind::View; }
+
+ bool operator==(TimelineView const& other) const { return m_record == other.m_record; }
+
+private:
+ RustFFI::TimelineCell const* m_record { nullptr };
+};
// A set of animation records that keeps none of them alive, which Rust owns. The record of an animation that dies
// leaves the set as the set is next enumerated.
@@ -264,11 +219,6 @@ public:
{
}
- bool set(AnimationRef const& animation) { return RustFFI::animations_weak_animation_set_insert(m_set, &animation.record()); }
- bool remove(RustFFI::AnimationCell const& animation) { return RustFFI::animations_weak_animation_set_remove(m_set, &animation); }
- bool contains(RustFFI::AnimationCell const& record) const { return RustFFI::animations_weak_animation_set_contains(m_set, &record); }
- bool is_empty() const { return begin() == end(); }
-
struct EndIterator { };
class Iterator {
@@ -322,4 +272,10 @@ protected:
RustFFI::WeakAnimationSet* m_set { nullptr };
};
+// NB: The animations associated with a timeline, none of which it keeps alive.
+inline WeakAnimationSetView associated_animations_of(TimelineView timeline)
+{
+ return WeakAnimationSetView { *RustFFI::animations_timeline_associated_animations(&timeline.record()) };
+}
+
}
diff --git a/Libraries/LibWeb/Animations/TimeValue.cpp b/Libraries/LibWeb/Animations/TimeValue.cpp
deleted file mode 100644
index 0b13cc6e128..00000000000
--- a/Libraries/LibWeb/Animations/TimeValue.cpp
+++ /dev/null
@@ -1,78 +0,0 @@
-/*
- * Copyright (c) 2025, Callum Law <[email protected]>.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include "TimeValue.h"
-#include <LibWeb/Animations/AnimationTimeline.h>
-#include <LibWeb/CSS/CSSUnitValue.h>
-#include <LibWeb/CSS/CalculationResolutionContext.h>
-#include <LibWeb/CSS/StyleValues/CalculatedStyleValue.h>
-
-namespace Web::Animations {
-
-TimeValue TimeValue::from_css_numberish(CSS::CSSNumberish const& time, CSS::ComputationContext const& computation_context)
-{
- if (time.has<double>())
- return { Type::Milliseconds, time.get<double>() };
-
- auto const& numeric_value = time.get<GC::Ref<CSS::CSSNumericValue>>();
-
- // NB: Skip creating a calculation node for simple unit values
- if (auto const* unit_value = as_if<CSS::CSSUnitValue>(*numeric_value)) {
- if (unit_value->type().matches_number({}))
- return { Type::Milliseconds, unit_value->value() };
-
- if (unit_value->type().matches_time({}))
- return { Type::Milliseconds, CSS::Time { unit_value->value(), CSS::string_to_time_unit(unit_value->unit()).release_value() }.to_milliseconds() };
-
- if (unit_value->type().matches_percentage())
- return { Type::Percentage, unit_value->value() };
-
- VERIFY_NOT_REACHED();
- }
-
- auto calculation_node = numeric_value->create_calculation_node().release_value();
-
- auto numeric_type = calculation_node.determine_type({});
- VERIFY(numeric_type.has_value());
-
- auto style_value = CSS::CalculatedStyleValue::create(move(calculation_node), numeric_type.release_value(), {});
-
- auto calculation_resolution_context = CSS::CalculationResolutionContext::from_computation_context(computation_context);
-
- if (style_value->resolves_to_number())
- return { Type::Milliseconds, style_value->resolve_number(calculation_resolution_context).value() };
-
- if (style_value->resolves_to_time())
- return { Type::Milliseconds, style_value->resolve_time(calculation_resolution_context)->to_milliseconds() };
-
- if (style_value->resolves_to_percentage())
- return { Type::Percentage, style_value->resolve_percentage(calculation_resolution_context).value().value() };
-
- VERIFY_NOT_REACHED();
-}
-
-TimeValue TimeValue::create_zero(GC::Ptr<AnimationTimeline> const& timeline)
-{
- if (timeline && timeline->is_progress_based())
- return TimeValue { Type::Percentage, 0.0 };
-
- return TimeValue { Type::Milliseconds, 0.0 };
-}
-
-CSS::CSSNumberish TimeValue::as_css_numberish() const
-{
- switch (type) {
- case Type::Milliseconds:
- return value;
- case Type::Percentage:
- GC::Ref<CSS::CSSNumericValue> numeric_value = CSS::CSSUnitValue::create(value, "percent"_utf16_fly_string);
- return numeric_value;
- }
-
- VERIFY_NOT_REACHED();
-}
-
-}
diff --git a/Libraries/LibWeb/Animations/TimeValue.h b/Libraries/LibWeb/Animations/TimeValue.h
deleted file mode 100644
index fe9f0124237..00000000000
--- a/Libraries/LibWeb/Animations/TimeValue.h
+++ /dev/null
@@ -1,104 +0,0 @@
-/*
- * Copyright (c) 2025, Callum Law <[email protected]>.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibGC/Root.h>
-#include <LibWeb/Forward.h>
-
-namespace Web::Animations {
-
-struct TimeValue {
- static TimeValue from_css_numberish(CSS::CSSNumberish const&, CSS::ComputationContext const&);
- static TimeValue create_zero(GC::Ptr<AnimationTimeline> const& timeline);
-
- enum class Type : u8 {
- Milliseconds,
- Percentage
- };
- Type type;
- double value;
-
- TimeValue operator-() const
- {
- return { type, -value };
- }
-
- TimeValue operator*(double other) const
- {
- return { type, value * other };
- }
-
- TimeValue operator-(TimeValue const& other) const
- {
- VERIFY(type == other.type);
- return { type, value - other.value };
- }
-
- TimeValue operator+(TimeValue const& other) const
- {
- VERIFY(type == other.type);
- return { type, value + other.value };
- }
-
- TimeValue operator/(double divisor) const
- {
- return { type, value / divisor };
- }
-
- double operator/(TimeValue const& other) const
- {
- VERIFY(type == other.type);
- return value / other.value;
- }
-
- int operator<=>(TimeValue const& other) const
- {
- VERIFY(type == other.type);
-
- if (value < other.value)
- return -1;
- if (value > other.value)
- return 1;
- return 0;
- }
-
- bool operator==(TimeValue const& other) const
- {
- return type == other.type && value == other.value;
- }
-
- CSS::CSSNumberish as_css_numberish() const;
-};
-
-// Nullable CSSNumberish is Variant<double, GC::Root<CSSNumericValue>, Empty> where Empty represents null.
-struct NullableCSSNumberish : FlattenVariant<Variant<Empty>, CSS::CSSNumberish> {
- using Variant::Variant;
-
- static NullableCSSNumberish from_optional_css_numberish_time(Optional<TimeValue> const& value)
- {
- if (value.has_value())
- return value->as_css_numberish();
-
- return {};
- }
-};
-
-}
-
-template<>
-struct AK::Formatter<Web::Animations::TimeValue> : Formatter<FormatString> {
- ErrorOr<void> format(FormatBuilder& builder, Web::Animations::TimeValue const& time)
- {
- switch (time.type) {
- case Web::Animations::TimeValue::Type::Milliseconds:
- return Formatter<FormatString>::format(builder, "{}ms"sv, time.value);
- case Web::Animations::TimeValue::Type::Percentage:
- return Formatter<FormatString>::format(builder, "{}%"sv, time.value);
- }
- return {};
- }
-};
diff --git a/Libraries/LibWeb/Bindings/Rust/src/animations/animatable.rs b/Libraries/LibWeb/Bindings/Rust/src/animations/animatable.rs
index 44dc34c954e..b5d635766d2 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/animations/animatable.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/animations/animatable.rs
@@ -7,16 +7,17 @@
//! https://drafts.csswg.org/web-animations-1/#the-animatable-interface-mixin
use core::ffi::c_void;
-use core::ptr::NonNull;
use ak::Utf16String;
use libjs_rust::api::{Gc, MarkedVec, Object};
use libweb_rust::AnimationRecordRef;
-use libweb_rust::web_animations::sort_in_composite_order;
+use libweb_rust::web_animations::{
+ element_node_document, sort_in_composite_order, web_animation_compare_elements_in_tree_order,
+};
use super::animation::{
- AnyAnimation, TimelineRangeValue, animation_object, default_document_timeline, parse_timeline_range_edge,
- perform_host_effect, realm_of_element,
+ AnyAnimation, TimelineRangeValue, animation_object, parse_timeline_range_edge, perform_host_effect,
+ realm_of_element,
};
use super::animation_timeline::{AnyAnimationTimeline, element_of_wrapper};
use super::keyframe_effect::{
@@ -27,14 +28,12 @@ use crate::bindings::conversions::CppInterface;
use crate::bindings::{CallContext, Exception, WebIdlResult};
unsafe extern "C" {
- fn web_animation_for_each_relevant_animation(
+ fn web_animation_for_each_associated_animation(
node_wrapper: *mut c_void,
subtree: bool,
context: *mut c_void,
on_animation: unsafe extern "C" fn(context: *mut c_void, animation: *const c_void),
);
- fn web_animation_compare_elements_in_tree_order(first: *mut c_void, second: *mut c_void) -> i32;
- fn ladybird_animations_element_node_document(element: *mut c_void) -> *mut c_void;
}
// https://drafts.csswg.org/web-animations-1/#dictdef-keyframeanimationoptions
@@ -65,14 +64,15 @@ pub(crate) fn animate(
// 1. Let target be the object on which this method was called.
let target = element_of_wrapper(*this);
- // SAFETY: The element is live, and so is its node document.
- let document = NonNull::new(unsafe { ladybird_animations_element_node_document(target.as_ptr()) })
- .expect("an element has a node document");
- let realm = realm_of_element(target);
// INTEROP: Like Chrome, the keyframes are processed before the range is parsed, so the keyframes' getters run first.
let keyframes = process_a_keyframes_argument(vm, keyframes)?;
+ // NB: The getters of the keyframes can move the target to another document, whose default document timeline the
+ // animation then gets.
+ let document = element_node_document(target);
+ let realm = realm_of_element(target);
+
let (effect_options, animation_options) = match options {
UnrestrictedDoubleOrKeyframeAnimationOptions::UnrestrictedDouble(duration) => (
UnrestrictedDoubleOrKeyframeEffectOptions::UnrestrictedDouble(duration),
@@ -112,11 +112,13 @@ pub(crate) fn animate(
)?;
// 3. If options is a KeyframeAnimationOptions object, let timeline be the timeline member of options or, if
- // timeline member of options is missing, be the default document timeline of the node document of the element
- // on which this method was called.
+ // timeline member of options is missing, the default document timeline of the node document of the element on
+ // which this method was called.
let timeline = match timeline_option {
Some(timeline) => timeline.map(|timeline| timeline.record().clone()),
- None => Some(default_document_timeline(document)),
+ None => Some(libweb_rust::web_animations::TimelineRecordRef::default_of_document(
+ document,
+ )),
};
// 4. Construct a new Animation object, animation, in the relevant Realm of target by using the same procedure as
@@ -172,8 +174,8 @@ pub(crate) fn get_animations<'vm>(
// 4. If options is passed with subtree set to true, then return the set of relevant animations for a subtree of
// target. Otherwise, return the set of relevant animations for target.
- // The returned list is sorted using the composite order described for the associated animations of effects in
- // §5.4.2 The effect stack.
+ // The list returned by the above algorithm is sorted using the composite order described for the associated
+ // animations of effects in § 5.4.2 The effect stack.
Ok(sorted_relevant_animations(this, options.subtree, cx))
}
@@ -192,13 +194,14 @@ pub(super) fn sorted_relevant_animations<'vm>(
let mut relevant_animations: Vec<AnimationRecordRef> = Vec::new();
// SAFETY: The wrapper is live, and the callback receives the list for as long as the call runs.
unsafe {
- web_animation_for_each_relevant_animation(
+ web_animation_for_each_associated_animation(
node.wrapper().as_ptr().cast(),
subtree,
(&raw mut relevant_animations).cast(),
on_animation,
);
}
+ relevant_animations.retain(AnimationRecordRef::is_exposed_relevant);
sort_in_composite_order(&mut relevant_animations, web_animation_compare_elements_in_tree_order);
diff --git a/Libraries/LibWeb/Bindings/Rust/src/animations/animation.rs b/Libraries/LibWeb/Bindings/Rust/src/animations/animation.rs
index 1f13e4b9b12..5be548f5052 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/animations/animation.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/animations/animation.rs
@@ -14,19 +14,22 @@ use core::ops::Deref;
use core::ptr::NonNull;
use ak::Utf16String;
-use libcompositing_rust::animation_timing::{OptionalTimeValue, TimeValue, TimeValueType};
+pub(crate) use libcompositing_rust::animation_timing::{AnimationPlayState, AnimationReplaceState};
+use libcompositing_rust::animation_timing::{OptionalNumber, OptionalTimeValue, TimeValue, TimeValueType};
use libjs_rust::api::{Gc, Realm, ThrowCompletionOr, Trace, Value, Visitor, Vm};
use libweb_rust::AnimationRecordRef;
use libweb_rust::web_animations::{
AnimationException, AnimationInterfaceKind, AnimationProcedure, AttachmentRangeEdgeValue, CssAnimationFlag,
EffectRecordRef, HostEffect, HostEffectKind, PROPERTY_ID_ANIMATION_RANGE_END, PROPERTY_ID_ANIMATION_RANGE_START,
- StyleValue, attachment_range_edge_from_computed_value, numeric_type_matches_time, parse_property_value,
- style_value_as_host_ptr, style_value_from_host,
+ PendingAnimationEvent, PlaybackEventType, StyleValue, attachment_range_edge_from_computed_value,
+ numeric_type_matches_time, parse_property_value, style_value_as_host_ptr, style_value_from_host,
};
use super::animation_effect::{AnyAnimationEffect, effect_object};
-use super::animation_playback_event::time_value_as_css_numberish;
-use super::animation_timeline::{AnyAnimationTimeline, timeline_object};
+use super::animation_playback_event::{
+ AnimationPlaybackEvent, AnimationPlaybackEventInit, time_value_as_css_numberish,
+};
+use super::animation_timeline::{AnyAnimationTimeline, timeline_object_of_record};
use super::document_timeline::document_of_realm;
use crate::bindings::conversions::ToJs;
use crate::bindings::event_target::{CppEventTarget, GetTheParent};
@@ -34,8 +37,8 @@ use crate::bindings::interface::{
Inherits, Ref, Wrappable, allocate, cell_from_abi, cell_into_abi, with_temporary_execution_context,
};
use crate::bindings::promise::{
- WebIdlPromise, create_promise, create_resolved_promise, mark_promise_as_handled, reject_promise_with_exception,
- resolve_promise,
+ TaskSource, WebIdlPromise, create_promise, mark_promise_as_handled, queue_a_global_task,
+ reject_promise_with_exception, resolve_promise,
};
use crate::bindings::{CallContext, Exception, WebIdlResult};
use crate::css::css_animation::CSSAnimation;
@@ -43,16 +46,30 @@ use crate::css::css_keyword_value::CSSKeywordValue;
use crate::css::css_numeric_value::{AnyCSSNumericValue, CSSNumberish};
use crate::css::css_transition::CSSTransition;
use crate::css::typed_om::reify_a_numeric_value;
+use crate::dom::event::EventInit;
unsafe extern "C" {
fn web_animation_perform_host_effect(effect: *const c_void);
- fn web_animation_update_style_of_owning_element(animation: *const c_void);
- fn web_animation_update_style_of_owning_element_document(animation: *const c_void);
+ fn web_animation_update_style_of_element(
+ element: *mut c_void,
+ has_pseudo_element: bool,
+ pseudo_element: u8,
+ scope: StyleUpdateScope,
+ );
fn web_animation_realm_of_element(element: *mut c_void) -> *mut c_void;
- fn web_animation_document_timeline_of_document(document: *mut c_void) -> *mut c_void;
- fn web_animation_timeline_current_time_for_observation(timeline: *mut c_void) -> OptionalTimeValue;
fn web_animation_absolutize_style_value(document: *mut c_void, value: *const c_void) -> *const c_void;
- fn web_animation_visit_named_cells(animation: *const c_void, visitor: *mut c_void);
+ fn web_animation_realm_of_document(document: *mut c_void) -> *mut c_void;
+ fn web_animation_current_high_resolution_time(realm: *mut c_void) -> f64;
+ fn web_animation_append_pending_playback_event(
+ document: *mut c_void,
+ animation: *const c_void,
+ r#type: PlaybackEventType,
+ current_time: OptionalTimeValue,
+ timeline_time: OptionalTimeValue,
+ scheduled_event_time: OptionalNumber,
+ time_stamp: f64,
+ );
+ fn web_animation_event_set_time_stamp(event: *mut c_void, time_stamp: f64);
fn web_animation_commit_styles(animation: *const c_void) -> CommitStylesResult;
}
@@ -65,23 +82,6 @@ enum CommitStylesResult {
TargetIsNotBeingRendered,
}
-// https://drafts.csswg.org/web-animations-1/#the-animationplaystate-enumeration
-#[derive(Clone, Copy)]
-pub(crate) enum AnimationPlayState {
- Idle,
- Running,
- Paused,
- Finished,
-}
-
-// https://drafts.csswg.org/web-animations-1/#the-animationreplacestate-enumeration
-#[derive(Clone, Copy)]
-pub(crate) enum AnimationReplaceState {
- Active,
- Removed,
- Persisted,
-}
-
// https://drafts.csswg.org/web-animations-2/#dictdef-timelinerangeoffset
pub(crate) struct TimelineRangeOffset {
pub(crate) range_name: Option<Option<Utf16String>>,
@@ -115,18 +115,42 @@ fn run(animation: &AnimationRecordRef, procedure: AnimationProcedure) -> WebIdlR
animation.run(procedure, perform_host_effect).map_err(exception_of)
}
+/// What the host computes the style of as script observes an animation.
+#[repr(u8)]
+#[derive(Clone, Copy)]
+enum StyleUpdateScope {
+ /// The style of the element, where it changed.
+ Element,
+ /// The style of the document of the element.
+ Document,
+}
+
+/// Has the host compute the style `scope` names of the owning element of the CSS animation or transition `animation`,
+/// where it has one.
+fn update_style_of_owning_element(animation: &AnimationRecordRef, scope: StyleUpdateScope) {
+ let Some((element, pseudo_element)) = animation.owning_element() else {
+ return;
+ };
+ // SAFETY: The animation keeps its owning element alive.
+ unsafe {
+ web_animation_update_style_of_element(
+ element.as_ptr(),
+ pseudo_element.is_some(),
+ pseudo_element.unwrap_or(0),
+ scope,
+ );
+ }
+}
+
/// Has the owning element of a CSS animation or transition compute its style, where the style changed.
pub(crate) fn update_style_if_needed(animation: &AnimationRecordRef) {
- // SAFETY: The animation is live.
- unsafe { web_animation_update_style_of_owning_element(animation.as_host_ptr()) };
+ // NB: Script observes a CSS animation or transition with the style of its owning element computed.
+ update_style_of_owning_element(animation, StyleUpdateScope::Element);
}
/// The current time of the timeline of the animation as script observes it, which is unresolved where it has none.
fn timeline_time_for_observation(animation: &AnimationRecordRef) -> Option<TimeValue> {
- let timeline = animation.timeline()?;
- let cell = timeline.facade()?;
- // SAFETY: The cell is the live object of the timeline of the animation.
- unsafe { web_animation_timeline_current_time_for_observation(cell.as_ptr()) }.get()
+ animation.timeline()?.current_time_for_observation()
}
/// https://www.w3.org/TR/web-animations-1/#animation-current-time
@@ -151,15 +175,78 @@ pub(crate) fn realm_of_element(element: NonNull<c_void>) -> Gc<Realm> {
}
}
-/// https://drafts.csswg.org/web-animations-1/#default-document-timeline
-/// Of the host's `DOM::Document`.
-pub(crate) fn default_document_timeline(document: NonNull<c_void>) -> libweb_rust::web_animations::TimelineRecordRef {
- // SAFETY: The document is live, and the host returns the live cell of its timeline.
- let cell = unsafe { web_animation_document_timeline_of_document(document.as_ptr()) };
- // SAFETY: The cell is the live cell of a timeline.
- unsafe { timeline_object(cell) }.record().clone()
+fn realm_of_document(document: NonNull<c_void>) -> Gc<Realm> {
+ // SAFETY: The document is live, and the host returns its live relevant realm.
+ unsafe {
+ Gc::from_non_null(
+ NonNull::new(web_animation_realm_of_document(document.as_ptr()).cast::<Realm>())
+ .expect("a document has a relevant realm"),
+ )
+ }
+}
+
+/// https://w3c.github.io/hr-time/#dfn-current-high-resolution-time
+/// Of the global object of the realm.
+fn current_high_resolution_time(realm: Gc<Realm>) -> f64 {
+ // SAFETY: The realm is live.
+ unsafe { web_animation_current_high_resolution_time(realm.as_ptr().cast()) }
+}
+
+// NB: A remove event is created in the realm of the document whose replaced animations are removed, which is the
+// document for timing of the animation, and whose pending animation event queue it joins.
+fn playback_event_realm(
+ object_realm: Gc<Realm>,
+ r#type: PlaybackEventType,
+ document_for_timing: Option<NonNull<c_void>>,
+) -> Gc<Realm> {
+ match document_for_timing {
+ Some(document) if r#type == PlaybackEventType::Remove => realm_of_document(document),
+ _ => object_realm,
+ }
+}
+
+// https://www.w3.org/TR/web-animations-1/#update-an-animations-finished-state
+// https://www.w3.org/TR/web-animations-1/#cancel-an-animation
+// https://www.w3.org/TR/web-animations-1/#remove-replaced-animations
+fn playback_event_type_name(r#type: PlaybackEventType) -> &'static [u8] {
+ match r#type {
+ PlaybackEventType::Finish => b"finish",
+ PlaybackEventType::Cancel => b"cancel",
+ PlaybackEventType::Remove => b"remove",
+ }
+}
+
+/// A new AnimationPlaybackEvent of the type, created in the realm, that neither bubbles nor can be canceled, and that the
+/// user agent dispatches.
+/// https://drafts.csswg.org/web-animations-2/#animationplaybackevent
+fn create_animation_playback_event(
+ vm: &Vm,
+ realm: Gc<Realm>,
+ r#type: PlaybackEventType,
+ current_time: Option<TimeValue>,
+ timeline_time: Option<TimeValue>,
+) -> Ref<AnimationPlaybackEvent> {
+ let event_init = AnimationPlaybackEventInit {
+ parent: EventInit {
+ bubbles: false,
+ cancelable: false,
+ composed: false,
+ },
+ current_time: current_time.map(|time| time_value_as_css_numberish(vm, time)),
+ timeline_time: timeline_time.map(|time| time_value_as_css_numberish(vm, time)),
+ };
+ let event = AnimationPlaybackEvent::create(
+ vm,
+ realm,
+ &Utf16String::from_ascii(playback_event_type_name(r#type)),
+ event_init,
+ );
+ event.event().set_is_trusted(true);
+ event
}
+/// https://drafts.csswg.org/web-animations-1/#default-document-timeline
+/// Of the host's `DOM::Document`.
/// https://html.spec.whatwg.org/multipage/webappapis.html#concept-relevant-realm
/// That of the object of the animation, or for a CSS animation or transition without one, of the document of its
/// owning element, and for the animation of an SVG animation element, of the document of that element.
@@ -203,8 +290,10 @@ unsafe impl Trace for Animation {
if let Some(promise) = self.current_finished_promise.get() {
visitor.visit(promise);
}
- // SAFETY: The animation holds a reference to the record, and the visitor is one LibGC passed in.
- unsafe { web_animation_visit_named_cells(self.record.as_host_ptr(), visitor.as_raw().cast()) };
+ self.record.for_each_named_cell(|cell, _| {
+ // SAFETY: The record names live cells of the host, which the animation keeps alive.
+ visitor.visit(unsafe { Gc::from_non_null(cell) });
+ });
}
}
@@ -287,8 +376,8 @@ impl AnyAnimation {
/// The object of the animation, if it has one.
pub(crate) fn existing_animation_object(animation: &AnimationRecordRef) -> Option<AnyAnimation> {
- let cell = animation.facade()?.as_ptr();
- // SAFETY: The facade of an animation is the live cell of its object, of the interface its kind picks.
+ let cell = animation.object_cell()?.as_ptr();
+ // SAFETY: The object cell of an animation is the live cell of its object, of the interface its kind picks.
Some(unsafe {
match animation.kind() {
AnimationInterfaceKind::Script => AnyAnimation::Animation(cell_from_abi(cell)),
@@ -319,7 +408,7 @@ pub(crate) fn animation_object(vm: &Vm, animation: &AnimationRecordRef) -> AnyAn
}
};
object.event_target_owner();
- animation.set_facade(NonNull::new(object.cell()));
+ animation.set_object_cell(NonNull::new(object.cell()));
object
}
@@ -341,7 +430,7 @@ impl Animation {
pub(crate) fn finalize_animation(&self) {
// NB: The record can outlive the animation until what holds the record is swept.
- self.record.set_facade(None);
+ self.record.did_finalize_object();
}
// https://www.w3.org/TR/web-animations-1/#dom-animation-animation
@@ -356,7 +445,9 @@ impl Animation {
// the current global object.
let timeline = match timeline {
Some(timeline) => timeline.map(|timeline| timeline.record().clone()),
- None => Some(default_document_timeline(document_of_realm(realm))),
+ None => Some(libweb_rust::web_animations::TimelineRecordRef::default_of_document(
+ document_of_realm(realm),
+ )),
};
Ok(Self::create(
@@ -377,9 +468,11 @@ impl Animation {
// 1. Let animation be a new Animation object.
let animation = allocate(vm, |_| Self::new(realm, AnimationRecordRef::new_script_animation()));
animation.event_target.set_owner(animation);
- animation.record.set_facade(NonNull::new(cell_into_abi(animation)));
+ animation.record.set_object_cell(NonNull::new(cell_into_abi(animation)));
- // 2. Run the procedure to set the timeline of an animation on animation passing timeline as the new timeline.
+ // 2. Run the procedure to set the timeline of an animation on animation passing timeline as the new timeline;
+ // or, if the timeline argument is missing, passing the default document timeline of the Document associated
+ // with the Window that is the current global object.
animation.record.set_timeline(timeline, perform_host_effect);
// 3. Run the procedure to set the associated effect of an animation on animation passing source as the new
@@ -422,15 +515,12 @@ impl Animation {
}
// https://www.w3.org/TR/web-animations-1/#dom-animation-timeline
- pub(crate) fn timeline(&self, _: &mut CallContext) -> WebIdlResult<Option<AnyAnimationTimeline>> {
+ pub(crate) fn timeline(&self, cx: &mut CallContext) -> WebIdlResult<Option<AnyAnimationTimeline>> {
update_style_if_needed(&self.record);
- Ok(self.record.timeline().map(|timeline| {
- let cell = timeline
- .facade()
- .expect("the timeline of an animation script reaches is alive");
- // SAFETY: The cell is the live cell of a timeline.
- unsafe { timeline_object(cell.as_ptr()) }
- }))
+ Ok(self
+ .record
+ .timeline()
+ .map(|timeline| timeline_object_of_record(cx.vm(), &timeline)))
}
// https://www.w3.org/TR/web-animations-1/#animation-set-the-timeline-of-an-animation
@@ -459,7 +549,7 @@ impl Animation {
// If all of the following conditions are true:
// - The animation is associated with a progress-based timeline, and
- // - time is not a CSSNumeric value with percent units:
+ // - time is not a CSSNumericValue with percent units:
if progress_based
&& !numeric_type
.as_ref()
@@ -523,7 +613,8 @@ impl Animation {
}
// https://www.w3.org/TR/web-animations-1/#dom-animation-starttime
- // https://www.w3.org/TR/web-animations-1/#set-the-start-time
+ // https://drafts.csswg.org/web-animations-1/#set-the-start-time
+ // https://drafts.csswg.org/web-animations-2/#set-the-start-time
pub(crate) fn set_start_time(&self, _: &mut CallContext, new_start_time: Option<CSSNumberish>) -> WebIdlResult<()> {
// Setting this attribute updates the start time using the procedure to set the start time of this object to
// the new value.
@@ -546,7 +637,8 @@ impl Animation {
Ok(current_time_for_observation(&self.record).map(|time| time_value_as_css_numberish(cx.vm(), time)))
}
- // https://www.w3.org/TR/web-animations-1/#animation-set-the-current-time
+ // https://drafts.csswg.org/web-animations-1/#animation-set-the-current-time
+ // https://drafts.csswg.org/web-animations-2/#set-the-current-time
pub(crate) fn set_current_time(&self, _: &mut CallContext, seek_time: Option<CSSNumberish>) -> WebIdlResult<()> {
// AD-HOC: We validate here instead of within silently_set_current_time so we have access to the `TimeValue`
// value within this function.
@@ -608,28 +700,16 @@ impl Animation {
// https://www.w3.org/TR/web-animations-1/#dom-animation-playstate
pub(crate) fn play_state(&self, _: &mut CallContext) -> WebIdlResult<AnimationPlayState> {
- use libweb_rust::web_animations::AnimationPlayState as RecordPlayState;
// NB: Script observes the play state of an animation with the style of the document of its owning element
// computed, at the current time it observes.
- // SAFETY: The animation is live.
- unsafe { web_animation_update_style_of_owning_element_document(self.record.as_host_ptr()) };
+ update_style_of_owning_element(&self.record, StyleUpdateScope::Document);
let current_time = current_time_for_observation(&self.record);
- Ok(match self.record.play_state_at(current_time) {
- RecordPlayState::Idle => AnimationPlayState::Idle,
- RecordPlayState::Running => AnimationPlayState::Running,
- RecordPlayState::Paused => AnimationPlayState::Paused,
- RecordPlayState::Finished => AnimationPlayState::Finished,
- })
+ Ok(self.record.play_state_at(current_time))
}
// https://www.w3.org/TR/web-animations-1/#dom-animation-replacestate
pub(crate) fn replace_state(&self, _: &mut CallContext) -> WebIdlResult<AnimationReplaceState> {
- use libweb_rust::web_animations::AnimationReplaceState as RecordReplaceState;
- Ok(match self.record.replace_state() {
- RecordReplaceState::Active => AnimationReplaceState::Active,
- RecordReplaceState::Removed => AnimationReplaceState::Removed,
- RecordReplaceState::Persisted => AnimationReplaceState::Persisted,
- })
+ Ok(self.record.replace_state())
}
// https://www.w3.org/TR/web-animations-1/#dom-animation-pending
@@ -647,12 +727,13 @@ impl Animation {
// resolved Promise with the animation itself as its value and created in the relevant Realm of the animation.
// NB: A promise the procedures replaced, which script did not ask for yet, is pending while the animation has
// a pending play or pause task.
- let promise = if self.record.pending() {
- create_promise(vm, self.realm)
- } else {
- create_resolved_promise(vm, self.realm, self.object().value_in(vm, self.realm))
- };
+ // NB: Resolving the promise with the animation reads its "then" property, which script can observe, so the
+ // promise is the current one before it is resolved.
+ let promise = create_promise(vm, self.realm);
self.current_ready_promise.set(Some(promise));
+ if !self.record.pending() {
+ resolve_promise(vm, promise, self.object().value_in(vm, self.realm));
+ }
promise
}
@@ -664,12 +745,12 @@ impl Animation {
// The current finished promise is initially a pending Promise object.
// NB: A promise the procedures resolved, which script did not ask for yet, is resolved while the animation is
// finished.
- let promise = if self.record.playback().is_finished {
- create_resolved_promise(vm, self.realm, self.object().value_in(vm, self.realm))
- } else {
- create_promise(vm, self.realm)
- };
+ // NB: As with the current ready promise, the promise is the current one before it is resolved.
+ let promise = create_promise(vm, self.realm);
self.current_finished_promise.set(Some(promise));
+ if self.record.playback().is_finished {
+ resolve_promise(vm, promise, self.object().value_in(vm, self.realm));
+ }
promise
}
@@ -685,13 +766,12 @@ impl Animation {
// NB: An animation that script observes finished ahead of the timeline's own current time settles its finished
// promise as it reads it, at the time it observes.
if let Some(timeline) = self.record.timeline() {
- use libweb_rust::web_animations::AnimationPlayState as RecordPlayState;
let observed_timeline_time = timeline_time_for_observation(&self.record);
let observed_current_time = self.record.current_time_at(observed_timeline_time);
let current_time = self.record.current_time_at(timeline.current_time());
if !self.record.playback().is_finished
- && self.record.play_state_at(current_time) != RecordPlayState::Finished
- && self.record.play_state_at(observed_current_time) == RecordPlayState::Finished
+ && self.record.play_state_at(current_time) != AnimationPlayState::Finished
+ && self.record.play_state_at(observed_current_time) == AnimationPlayState::Finished
{
let previous_override = timeline.style_sampling_override();
timeline.set_style_sampling_override(Some(observed_timeline_time));
@@ -744,9 +824,70 @@ impl Animation {
}
}
+ /// Creates an AnimationPlaybackEvent of the animation and appends it to the pending animation event queue of the
+ /// animation's document for timing, or queues a task to dispatch it at the animation without one, as a procedure
+ /// asked.
+ fn queue_playback_event(&self, vm: &Vm, effect: &HostEffect) {
+ let r#type = effect.playback_event_type;
+ let timeline = self.record.timeline();
+ let document_for_timing = timeline.as_ref().map(|timeline| timeline.document());
+ let event_realm = playback_event_realm(self.realm, r#type, document_for_timing);
+
+ // If animation has a document for timing, then append finishEvent to its document for timing's pending
+ // animation event queue along with its target, animation.
+ // NB: The same steps apply to cancelEvent and removeEvent.
+ if let (Some(timeline), Some(document)) = (timeline, document_for_timing) {
+ // https://www.w3.org/TR/web-animations-1/#animation-time-to-origin-relative-time
+ // NB: The procedure converted the time to a timeline time.
+ let scheduled_event_time = effect
+ .scheduled_timeline_time
+ .get()
+ .and_then(|time| timeline.convert_a_timeline_time_to_an_origin_relative_time(time));
+ // NB: The queue holds what the event is, which the document creates as it dispatches it, with the time
+ // stamp of now, when the event is created in the spec.
+ // SAFETY: The document and the animation are live.
+ unsafe {
+ web_animation_append_pending_playback_event(
+ document.as_ptr(),
+ self.record.as_host_ptr(),
+ r#type,
+ effect.current_time,
+ effect.timeline_time,
+ scheduled_event_time.into(),
+ current_high_resolution_time(event_realm),
+ );
+ }
+ return;
+ }
+
+ let event = create_animation_playback_event(
+ vm,
+ event_realm,
+ r#type,
+ effect.current_time.get(),
+ effect.timeline_time.get(),
+ );
+
+ // Otherwise, queue a task to dispatch finishEvent at animation. The task source for this task is the DOM
+ // manipulation task source.
+ let task = queue_a_global_task(
+ vm,
+ self.realm.global_object(),
+ TaskSource::DOMManipulation,
+ (self.object(), event),
+ |_, (animation, event)| {
+ animation.event_target.dispatch_event(event.event());
+ },
+ );
+ // NB: The task that dispatches a finish event is the one the record notes as its finish notification task.
+ if r#type == PlaybackEventType::Finish {
+ self.record.set_finish_notification_task(task.host_id());
+ }
+ }
+
// https://www.w3.org/TR/web-animations-1/#dom-animation-cancel
pub(crate) fn cancel(&self, _: &mut CallContext) -> WebIdlResult<()> {
- // NB: Cancelling an animation that is not idle settles its promises and creates its cancel event.
+ // NB: Canceling an animation that is not idle settles its promises and creates its cancel event.
if self.record.is_idle() {
return run(&self.record, AnimationProcedure::Cancel);
}
@@ -866,9 +1007,11 @@ pub(crate) fn parse_timeline_range_edge(
} else {
PROPERTY_ID_ANIMATION_RANGE_START
};
- // A DOMString value is parsed as an 'animation-range-start' (or 'animation-range-end') value to yield a
- // TimelineRangeOffset rangeName and offset or alternatively a CSSKeywordValue with the value of "normal"; a
- // CSSNumericValue is interpreted as a TimelineRangeOffset with that offset and a null rangeName.
+ // A DOMString value is parsed as an 'animation-range-end' value to yield a TimelineRangeOffset rangeName and offset
+ // or alternatively a CSSKeywordValue with the value of "normal"; a CSSNumericValue is interpreted as a
+ // TimelineRangeOffset with that offset and a null rangeName.
+ // NB: The spec says 'animation-range-end' for rangeStart too; a start edge is parsed as an
+ // 'animation-range-start' value.
let parse = |text: &Utf16String| -> WebIdlResult<AttachmentRangeEdgeValue> {
let parsed = parse_property_value(property, text).ok_or_else(invalid_timeline_range)?;
// NB: Arbitrary substitution functions and CSS-wide keywords have nothing to substitute or inherit from here.
@@ -926,21 +1069,6 @@ pub unsafe extern "C" fn web_animation_object_realm(animation: *const c_void) ->
existing_animation_object(&animation).map_or(core::ptr::null_mut(), |object| object.realm.as_ptr().cast())
}
-/// The host's `DOM::EventTarget` of the object of the animation, which a playback event of it is dispatched at.
-///
-/// # Safety
-///
-/// `animation` must be an animation the host holds a reference to, which has an object.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn web_animation_object_event_target(animation: *const c_void) -> *mut c_void {
- // SAFETY: Guaranteed by the caller.
- let animation = unsafe { AnimationRecordRef::retained_from_host(animation) };
- existing_animation_object(&animation)
- .expect("an animation that hears its playback events has an object")
- .event_target
- .as_ptr()
-}
-
/// The bytes of the object of the animation and of the object of its associated effect, or zero where the animation has
/// no object.
///
@@ -954,19 +1082,171 @@ pub unsafe extern "C" fn web_animation_object_memory_size(animation: *const c_vo
existing_animation_object(&animation).map_or(0, Animation::memory_size)
}
-/// Settles a promise of the object of the animation `effect` names, as a procedure asked.
+/// Performs what a procedure asked of the object of the animation `effect` names, where it has one: settles one of its
+/// promises, or queues one of its playback events.
///
/// # Safety
///
/// `vm` must be the live VM, and `effect` an effect the host performs.
#[unsafe(no_mangle)]
-pub unsafe extern "C" fn web_animation_perform_promise_effect(vm: *mut c_void, effect: &HostEffect) {
+pub unsafe extern "C" fn web_animation_perform_object_effect(vm: *mut c_void, effect: &HostEffect) {
// SAFETY: The caller passes the live VM.
let vm = unsafe { &*vm.cast::<Vm>() };
// SAFETY: The effect names an animation the host holds a reference to.
let animation = unsafe { AnimationRecordRef::retained_from_host(effect.animation.as_ptr().cast()) };
- // NB: Only an animation with an object has promises script can observe.
- if let Some(object) = existing_animation_object(&animation) {
- object.perform_promise_effect(vm, effect.kind);
+ // NB: Only an animation with an object has promises script can observe, and hears its playback events.
+ let Some(object) = existing_animation_object(&animation) else {
+ return;
+ };
+ match effect.kind {
+ HostEffectKind::QueuePlaybackEvent => object.queue_playback_event(vm, effect),
+ kind => object.perform_promise_effect(vm, kind),
+ }
+}
+
+/// Dispatches the AnimationPlaybackEvent the pending animation event queue of the host's `DOM::Document` `document`
+/// held for the animation, which the document created with the time stamp `time_stamp` as it was queued.
+fn dispatch_pending_playback_event(
+ vm: &Vm,
+ animation: &AnimationRecordRef,
+ document: NonNull<c_void>,
+ event: &PendingAnimationEvent,
+) {
+ let object = existing_animation_object(animation).expect("only an animation with an object queues playback events");
+ let realm = playback_event_realm(object.realm, event.playback_event_type, Some(document));
+ let playback_event = create_animation_playback_event(
+ vm,
+ realm,
+ event.playback_event_type,
+ event.current_time.get(),
+ event.timeline_time.get(),
+ );
+ // SAFETY: The event is live.
+ unsafe { web_animation_event_set_time_stamp(playback_event.event().as_ptr(), event.time_stamp) };
+ object.event_target.dispatch_event(playback_event.event());
+}
+
+/// Creates the event of a CSS animation or transition the pending animation event queue held, and dispatches it at the
+/// owning element of the animation through `host`.
+fn dispatch_pending_css_event(
+ vm: &Vm,
+ animation: &AnimationRecordRef,
+ event: &PendingAnimationEvent,
+ host: &PendingAnimationEventHost,
+) {
+ use crate::css::animation_event::{AnimationEvent, AnimationEventInit, EventAnimation};
+ use crate::css::transition_event::{TransitionEvent, TransitionEventInit};
+ use libweb_rust::web_animations::{CssEventType, pseudo_element_name};
+
+ let (owning_element, pseudo_element) = animation
+ .owning_element()
+ .expect("a CSS animation or transition with events has an owning element");
+ let pseudo_element = pseudo_element.map_or_else(Utf16String::default, |pseudo_element| {
+ Utf16String::from_utf8(&format!("::{}", pseudo_element_name(pseudo_element)))
+ });
+ let event_name = Utf16String::from_utf8(match event.css_event_type {
+ CssEventType::AnimationStart => "animationstart",
+ CssEventType::AnimationEnd => "animationend",
+ CssEventType::AnimationIteration => "animationiteration",
+ CssEventType::AnimationCancel => "animationcancel",
+ CssEventType::TransitionRun => "transitionrun",
+ CssEventType::TransitionStart => "transitionstart",
+ CssEventType::TransitionEnd => "transitionend",
+ CssEventType::TransitionCancel => "transitioncancel",
+ });
+ let realm = realm_of_element(owning_element);
+ let parent = EventInit {
+ bubbles: true,
+ cancelable: false,
+ composed: false,
+ };
+ let event_animation = Some(EventAnimation::of_record(animation.clone()));
+ let css_event = if animation.kind() == AnimationInterfaceKind::CssTransition {
+ let init = TransitionEventInit {
+ parent,
+ animation: None,
+ elapsed_time: event.elapsed_time,
+ property_name: animation.css_transition_property(),
+ pseudo_element,
+ };
+ TransitionEvent::create_for_animation(vm, realm, &event_name, init, event_animation)
+ .event()
+ .clone()
+ } else {
+ let init = AnimationEventInit {
+ parent,
+ animation: None,
+ animation_name: animation.css_animation_name(),
+ elapsed_time: event.elapsed_time,
+ pseudo_element,
+ };
+ AnimationEvent::create_for_animation(vm, realm, &event_name, init, event_animation)
+ .event()
+ .clone()
+ };
+ // SAFETY: The event is live.
+ unsafe { web_animation_event_set_time_stamp(css_event.as_ptr(), event.time_stamp) };
+ css_event.set_is_trusted(true);
+ // SAFETY: The owning element is live, as the animation keeps it alive, and so is the event.
+ unsafe { (host.dispatch_at_element)(host.context, owning_element, css_event.as_ptr()) };
+}
+
+/// What dispatching the events of the pending animation event queue of a document asks of the host, which hands each
+/// function `context`.
+#[repr(C)]
+pub struct PendingAnimationEventHost {
+ pub context: *mut c_void,
+ /// Keeps the animation, which the host holds a reference to, alive until the call that handed it the function
+ /// returns, since dispatching an event runs script, which can run the GC.
+ pub keep_alive: unsafe extern "C" fn(context: *mut c_void, animation: *const c_void),
+ /// Dispatches the host's `DOM::Event` `event` at the host's `DOM::Element` `element`.
+ pub dispatch_at_element: unsafe extern "C" fn(context: *mut c_void, element: NonNull<c_void>, event: *mut c_void),
+ /// Dispatches the time event of the SMIL animation `animation` the queue held.
+ pub dispatch_time_event:
+ unsafe extern "C" fn(context: *mut c_void, animation: *const c_void, event: &PendingAnimationEvent),
+}
+
+/// https://www.w3.org/TR/web-animations-1/#update-animations-and-send-events
+/// Steps 4 to 7 for the host's `DOM::Document` `document`, whose animations the host's `DocumentAnimations`
+/// `animations` are, comparing elements in tree order with `tree_order`.
+///
+/// # Safety
+///
+/// `vm` must be the live VM, `document` a live document and `animations` what it knows of animations, which only
+/// dispatching an event may reach again.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_animation_dispatch_pending_animation_events(
+ vm: *mut c_void,
+ document: NonNull<c_void>,
+ animations: NonNull<c_void>,
+ tree_order: unsafe extern "C" fn(first: *mut c_void, second: *mut c_void) -> i32,
+ host: &PendingAnimationEventHost,
+) {
+ use libweb_rust::web_animations::{PendingAnimationEventKind, take_pending_animation_events_to_dispatch};
+
+ // SAFETY: The caller passes the live VM.
+ let vm = unsafe { &*vm.cast::<Vm>() };
+ // 4. Let events to dispatch be a copy of doc’s pending animation event queue.
+ // 5. Clear doc’s pending animation event queue.
+ // 6. Perform a stable sort of the animation events in events to dispatch as follows:
+ // SAFETY: Guaranteed by the caller; nothing else reaches the queue until the events are taken.
+ let events_to_dispatch = unsafe { take_pending_animation_events_to_dispatch(animations, tree_order) };
+ // NB: Dispatching an event runs script, which can run the GC, which must not collect the animation of an event yet to
+ // be dispatched.
+ for (animation, _) in &events_to_dispatch {
+ // SAFETY: The host keeps alive an animation it holds a reference to.
+ unsafe { (host.keep_alive)(host.context, animation.as_host_ptr()) };
+ }
+ // 7. Dispatch each of the events in events to dispatch at their corresponding target using the order established in
+ // the previous step.
+ for (animation, event) in &events_to_dispatch {
+ match event.kind {
+ PendingAnimationEventKind::Css => dispatch_pending_css_event(vm, animation, event, host),
+ PendingAnimationEventKind::Playback => dispatch_pending_playback_event(vm, animation, document, event),
+ // SAFETY: The host dispatches the time event of an animation it keeps alive.
+ PendingAnimationEventKind::Time => unsafe {
+ (host.dispatch_time_event)(host.context, animation.as_host_ptr(), event);
+ },
+ }
}
}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/animations/animation_effect.rs b/Libraries/LibWeb/Bindings/Rust/src/animations/animation_effect.rs
index f56a3d5e638..f25386e68d4 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/animations/animation_effect.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/animations/animation_effect.rs
@@ -81,9 +81,9 @@ pub(crate) struct OptionalEffectTiming {
pub(crate) iterations: Option<f64>,
}
-/// Whether the string is the ASCII text.
-pub(crate) fn utf16_string_equals(string: &Utf16String, text: &str) -> bool {
- string.to_utf16().iter().copied().eq(text.encode_utf16())
+/// Whether the UTF-16 code units are the ASCII text.
+pub(crate) fn units_equal(units: &[u16], text: &str) -> bool {
+ units.iter().copied().eq(text.encode_utf16())
}
// https://www.w3.org/TR/web-animations-1/#the-animationeffect-interface
@@ -136,7 +136,7 @@ impl AnimationEffect {
pub(crate) fn get_timing(&self, _cx: &mut CallContext) -> WebIdlResult<EffectTiming> {
self.update_style_if_needed();
- // 1. Returns the specified timing properties for this animation effect.
+ // Returns the specified timing properties for this animation effect.
let specified = self.record.specified_timing();
let timing = self.record.timing();
Ok(EffectTiming {
@@ -168,18 +168,20 @@ impl AnimationEffect {
.associated_animation()
.and_then(|animation| current_time_for_observation(&animation));
- // 1. Returns the calculated timing properties for this animation effect.
+ // Returns the calculated timing properties for this animation effect.
- // Note: Although some of the attributes of the object returned by getTiming() and getComputedTiming() are
- // common, their values may differ in the following ways:
+ // Although some of the attributes of the object returned by getTiming() and getComputedTiming() are common,
+ // their values can differ in the following ways:
- // - duration: while getTiming() may return the string auto, getComputedTiming() must return a number
+ // - duration: while getTiming() can return the string auto, getComputedTiming() must return a number
// corresponding to the calculated value of the iteration duration as defined in the description of the
// duration member of the EffectTiming interface.
//
- // If duration is the string auto, this attribute will return the current calculated value of the
- // intrinsic iteration duration, which may be a expressed as a double representing the duration in
- // milliseconds or a percentage when the effect is associated with a progress-based timeline.
+ // https://drafts.csswg.org/web-animations-2/#dom-animationeffect-getcomputedtiming
+ // The description of the duration attribute of the object needs to indicate that if timing.duration is the
+ // string auto, this attribute will return the current calculated value of the intrinsic iteration duration,
+ // which may be a expressed as a double representing the duration in milliseconds or a percentage when the
+ // effect is associated with a progress-based timeline.
let timing_properties = self.record.timing();
let duration = match time_value_as_css_numberish(vm, timing_properties.iteration_duration) {
CSSNumberish::Double(value) => UnrestrictedDoubleOrCSSNumericValueOrDOMString::UnrestrictedDouble(value),
@@ -188,7 +190,7 @@ impl AnimationEffect {
}
};
- // - fill: likewise, while getTiming() may return the string auto, getComputedTiming() must return the
+ // - fill: likewise, while getTiming() can return the string auto, getComputedTiming() must return the
// specific FillMode used for timing calculations as defined in the description of the fill member of the
// EffectTiming interface.
//
@@ -216,10 +218,10 @@ impl AnimationEffect {
iterations: timing_properties.iteration_count,
},
active_duration: Some(as_css_numberish(timing.active_duration)),
- current_iteration: Some(timing.current_iteration.get()),
+ current_iteration: Some(timing.current_iteration),
end_time: Some(as_css_numberish(timing.end_time)),
local_time: Some(local_time.map(as_css_numberish)),
- progress: Some(timing.transformed_progress.get()),
+ progress: Some(timing.transformed_progress),
})
}
@@ -249,15 +251,14 @@ impl AnimationEffect {
return Err(Exception::type_error("Invalid iteration count value"));
}
- // 3. If the duration member of input exists, and is less than zero or is the value NaN, throw a TypeError and
- // abort this procedure.
- // Note: "auto", the only valid string value, is treated as 0.
+ // 3. If the duration member of input exists, and is less than zero, is the value NaN, or is a string other than
+ // the lowercase auto, throw a TypeError and abort this procedure.
let has_valid_duration_value = match &timing.duration {
None => true,
Some(UnrestrictedDoubleOrDOMString::UnrestrictedDouble(duration)) => {
!(*duration < 0.0 || duration.is_nan())
}
- Some(UnrestrictedDoubleOrDOMString::DOMString(duration)) => utf16_string_equals(duration, "auto"),
+ Some(UnrestrictedDoubleOrDOMString::DOMString(duration)) => units_equal(&duration.to_utf16(), "auto"),
};
if !has_valid_duration_value {
return Err(Exception::type_error("Invalid duration value"));
@@ -402,8 +403,8 @@ impl AnyAnimationEffect {
/// The object of the effect, if it has one.
pub(crate) fn existing_effect_object(effect: &EffectRecordRef) -> Option<AnyAnimationEffect> {
- let cell = effect.facade()?;
- // SAFETY: The facade of an effect is the live cell of its object, a KeyframeEffect, the only AnimationEffect there
+ let cell = effect.object_cell()?;
+ // SAFETY: The object cell of an effect is the live cell of its object, a KeyframeEffect, the only AnimationEffect there
// is.
Some(AnyAnimationEffect::KeyframeEffect(unsafe {
cell_from_abi(cell.as_ptr())
@@ -417,6 +418,6 @@ pub(crate) fn effect_object(vm: &Vm, effect: &EffectRecordRef) -> AnyAnimationEf
return object;
}
let object = KeyframeEffect::create_for_record(vm, effect.clone());
- effect.set_facade(NonNull::new(cell_into_abi(object)));
+ effect.set_object_cell(NonNull::new(cell_into_abi(object)));
AnyAnimationEffect::KeyframeEffect(object)
}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/animations/animation_timeline.rs b/Libraries/LibWeb/Bindings/Rust/src/animations/animation_timeline.rs
index 4a643d7ef81..a1b083448e8 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/animations/animation_timeline.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/animations/animation_timeline.rs
@@ -9,7 +9,6 @@
use core::ffi::c_void;
use core::ptr::NonNull;
-use libcompositing_rust::animation_timing::OptionalTimeValue;
use libjs_rust::api::{Gc, Object, Trace, Visitor, Vm};
use libweb_rust::web_animations::{TimelineInterfaceKind, TimelineRecordRef};
@@ -31,8 +30,6 @@ use crate::css::css_numeric_value::CSSNumberish;
use crate::internals::internal_animation_timeline::InternalAnimationTimeline;
unsafe extern "C" {
- fn web_animation_timeline_did_create(timeline: *mut c_void);
- fn web_animation_timeline_current_time_for_observation(timeline: *mut c_void) -> OptionalTimeValue;
fn web_animation_wrap_element(realm: *mut c_void, element: *mut c_void) -> *mut c_void;
fn web_animation_element_of_wrapper(wrapper: *mut c_void) -> *mut c_void;
}
@@ -65,11 +62,10 @@ impl AnimationTimeline {
pub(crate) fn current_time(&self, cx: &mut CallContext) -> WebIdlResult<Option<CSSNumberish>> {
// Returns the current time for this timeline or null if this timeline is inactive. The value is expressed as a
// percentage for a progress-based timeline, or as a double in milliseconds otherwise.
- // NB: Script observes the current time as the host samples it for observation.
- // SAFETY: The record names the live cell of this timeline.
- let current_time = unsafe { web_animation_timeline_current_time_for_observation(self.cell()) };
- Ok(current_time
- .get()
+ // NB: Script observes the current time as the timeline is sampled for observation.
+ Ok(self
+ .record
+ .current_time_for_observation()
.map(|time| time_value_as_css_numberish(cx.vm(), time)))
}
@@ -81,19 +77,11 @@ impl AnimationTimeline {
.duration()
.map(|time| time_value_as_css_numberish(cx.vm(), time)))
}
-
- /// The cell of the object of this timeline, as the host names it.
- pub(crate) fn cell(&self) -> *mut c_void {
- self.record
- .facade()
- .expect("a timeline script reaches is alive")
- .as_ptr()
- }
}
/// Finalizes a timeline: the record can outlive the timeline until what holds the record is swept.
pub(crate) fn finalize_timeline(timeline: &AnimationTimeline) {
- timeline.record.set_facade(None);
+ timeline.record.set_object_cell(None);
}
impl AnimationTimeline {
@@ -102,19 +90,22 @@ impl AnimationTimeline {
}
}
-/// Has the host note a new timeline, whose cell it then reaches the timeline through.
+/// Notes the cell of a new object of a timeline, which its record then reaches it through.
pub(crate) fn did_create_timeline(cell: *mut c_void) {
// SAFETY: The cell is that of a new timeline.
let timeline = unsafe { timeline_of_cell(cell) }.expect("the cell is that of a timeline");
- timeline.record.set_facade(NonNull::new(cell));
- // SAFETY: The cell is that of a new timeline.
- unsafe { web_animation_timeline_did_create(cell) };
+ timeline.record.set_object_cell(NonNull::new(cell));
}
-/// A new timeline of the record the host describes, which picks its interface by the kind of the record.
-fn create_timeline_from_record(vm: &Vm, record: TimelineRecordRef) -> *mut c_void {
- let timeline = AnimationTimeline::new(record);
- let cell = match timeline.record.kind() {
+/// The object script sees of the timeline of `record`, which is made as script first asks for it, of the interface the
+/// kind of the record picks.
+pub(crate) fn timeline_object_of_record(vm: &Vm, record: &TimelineRecordRef) -> AnyAnimationTimeline {
+ if let Some(cell) = record.object_cell() {
+ // SAFETY: The object cell of a record is the live cell of its object.
+ return unsafe { timeline_object(cell.as_ptr()) };
+ }
+ let timeline = AnimationTimeline::new(record.clone());
+ let cell = match record.kind() {
TimelineInterfaceKind::Document => cell_into_abi(allocate(vm, |_| DocumentTimeline::from_timeline(timeline))),
TimelineInterfaceKind::Scroll => cell_into_abi(allocate(vm, |_| ScrollTimeline::from_timeline(timeline))),
TimelineInterfaceKind::View => cell_into_abi(allocate(vm, |_| ViewTimeline::from_timeline(timeline))),
@@ -123,7 +114,8 @@ fn create_timeline_from_record(vm: &Vm, record: TimelineRecordRef) -> *mut c_voi
}
};
did_create_timeline(cell);
- cell
+ // SAFETY: The cell is that of the new object.
+ unsafe { timeline_object(cell) }
}
/// The part as an AnimationTimeline of the timeline whose cell the host names.
@@ -175,40 +167,6 @@ pub(crate) fn element_of_wrapper(element: CppInterface) -> NonNull<c_void> {
.expect("a wrapper of an Element wraps an element")
}
-/// The record of the timeline whose cell the host names, which lives as long as the timeline.
-///
-/// # Safety
-///
-/// `timeline` must be a live cell of an AnimationTimeline.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn web_animation_timeline_record(timeline: *mut c_void) -> *const c_void {
- // SAFETY: Guaranteed by the caller.
- unsafe { timeline_of_cell(timeline) }
- .expect("the host names the cell of a timeline")
- .record
- .as_host_ptr()
-}
-
-/// A new timeline associated with the host's `DOM::Document` `document`, as `description`, the host's
-/// `FfiTimelineDescription`, describes it.
-///
-/// # Safety
-///
-/// `vm` must be the live VM, `document` a live document and `description` a live description.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn web_animation_timeline_create(
- vm: *mut c_void,
- document: *mut c_void,
- description: *const c_void,
-) -> *mut c_void {
- // SAFETY: The caller passes the live VM.
- let vm = unsafe { &*vm.cast::<Vm>() };
- let document = NonNull::new(document).expect("a timeline is associated with a document");
- // SAFETY: Guaranteed by the caller.
- let record = unsafe { TimelineRecordRef::from_host_description(document, description) };
- create_timeline_from_record(vm, record)
-}
-
/// An object script sees of a timeline, of the interface that inherits from AnimationTimeline it is of.
#[derive(Clone, Copy, PartialEq, Trace)]
#[gc(crate = libjs_rust)]
diff --git a/Libraries/LibWeb/Bindings/Rust/src/animations/exports.rs b/Libraries/LibWeb/Bindings/Rust/src/animations/exports.rs
deleted file mode 100644
index 2a83e216689..00000000000
--- a/Libraries/LibWeb/Bindings/Rust/src/animations/exports.rs
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-//! What the C++ code of LibWeb asks of the interfaces of Web Animations, declared in
-//! Libraries/LibWeb/Animations/RecordHandles.cpp.
-
-use core::ffi::c_void;
-
-use ak::Utf16String;
-use libcompositing_rust::animation_timing::OptionalTimeValue;
-
-use super::animation_playback_event::{
- AnimationPlaybackEvent, AnimationPlaybackEventInit, time_value_as_css_numberish,
-};
-use crate::bindings::interface::realm_arguments;
-use crate::dom::event::EventInit;
-
-/// A new AnimationPlaybackEvent that neither bubbles nor can be canceled, as the Event that C++ dispatches.
-///
-/// # Safety
-///
-/// `vm` must be the live VM, `realm` a live realm, and `event_name` a raw string that C++ hands over.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn web_animation_playback_event_create(
- vm: *mut c_void,
- realm: *mut c_void,
- event_name: usize,
- current_time: OptionalTimeValue,
- timeline_time: OptionalTimeValue,
-) -> *mut c_void {
- // SAFETY: The caller passes the live VM and a live realm.
- let (vm, realm) = unsafe { realm_arguments(vm, realm) };
- // SAFETY: The caller hands over the string.
- let event_name = unsafe { Utf16String::from_raw_owned(event_name) };
- let event_init = AnimationPlaybackEventInit {
- parent: EventInit {
- bubbles: false,
- cancelable: false,
- composed: false,
- },
- current_time: current_time.get().map(|time| time_value_as_css_numberish(vm, time)),
- timeline_time: timeline_time.get().map(|time| time_value_as_css_numberish(vm, time)),
- };
- AnimationPlaybackEvent::create(vm, realm, &event_name, event_init)
- .event()
- .as_ptr()
-}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/animations/keyframe_effect.rs b/Libraries/LibWeb/Bindings/Rust/src/animations/keyframe_effect.rs
index 1a22cc6d214..8a4d71a5a23 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/animations/keyframe_effect.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/animations/keyframe_effect.rs
@@ -25,7 +25,7 @@ use libweb_rust::web_animations::{
use super::animation_effect::{
AnimationEffect, EffectTiming, UnrestrictedDoubleOrCSSNumericValueOrDOMString, to_optional_effect_timing,
- utf16_string_equals,
+ units_equal,
};
use crate::bindings::conversions::{CppInterface, iterator_method};
use crate::bindings::interface::{Inherits, Ref, Wrappable, allocate, cell_into_abi};
@@ -33,8 +33,6 @@ use crate::bindings::{CallContext, Exception, WebIdlResult};
unsafe extern "C" {
fn web_animation_effect_set_target(effect: *const c_void, element: *mut c_void, update: bool);
- fn web_animation_effect_invalidate(effect: *const c_void);
- fn web_animation_effect_set_composite(effect: *const c_void, composite: CompositeOperation);
fn web_animation_effect_set_keyframe_set(effect: *const c_void, keyframe_set: *const c_void);
fn web_animation_element_of_wrapper(wrapper: *mut c_void) -> *mut c_void;
fn web_animation_wrap_element(realm: *mut c_void, element: *mut c_void) -> *mut c_void;
@@ -69,8 +67,8 @@ impl<T> MaybeList<T> {
}
// https://www.w3.org/TR/web-animations-1/#dictdef-basepropertyindexedkeyframe
-// Note: This is an intermediate structure used only when parsing Keyframes provided by the caller in a slightly
-// different format. It is converted to BaseKeyframe, which is why it doesn't need to store the parsed properties
+// NB: This is an intermediate structure used only when parsing Keyframes provided by the caller in a slightly
+// different format. It is converted to BaseKeyframe, which is why it doesn't need to store the parsed properties.
struct BasePropertyIndexedKeyframe {
offset: MaybeList<Option<f64>>,
easing: MaybeList<Utf16String>,
@@ -111,11 +109,11 @@ impl Default for BaseKeyframe {
}
}
-/// A keyframe of a KeyframeEffect, https://www.w3.org/TR/web-animations-1/#keyframe, with its property values and its
-/// easing parsed.
+/// A keyframe of a KeyframeEffect, https://drafts.csswg.org/web-animations-1/#keyframe, with its property values and
+/// its easing parsed.
pub(crate) struct ProcessedKeyframe {
offset: Option<f64>,
- computed_offset: Option<f64>,
+ computed_offset: f64,
easing: ParsedEasing,
composite: CompositeOperationOrAuto,
properties: Vec<(KeyframePropertyName, StyleValue)>,
@@ -125,7 +123,7 @@ impl From<CssKeyframeValues> for ProcessedKeyframe {
fn from(keyframe: CssKeyframeValues) -> Self {
Self {
offset: Some(keyframe.offset),
- computed_offset: Some(keyframe.offset),
+ computed_offset: keyframe.offset,
easing: keyframe.easing,
composite: keyframe.composite,
properties: keyframe.properties,
@@ -149,41 +147,6 @@ impl Clone for ProcessedKeyframe {
}
}
-/// What compute_missing_keyframe_offsets() reads and writes of a keyframe.
-trait KeyframeOffsets {
- fn offset(&self) -> Option<f64>;
- fn computed_offset(&self) -> Option<f64>;
- fn set_computed_offset(&mut self, computed_offset: Option<f64>);
-}
-
-impl KeyframeOffsets for BaseKeyframe {
- fn offset(&self) -> Option<f64> {
- self.offset
- }
-
- fn computed_offset(&self) -> Option<f64> {
- self.computed_offset
- }
-
- fn set_computed_offset(&mut self, computed_offset: Option<f64>) {
- self.computed_offset = computed_offset;
- }
-}
-
-impl KeyframeOffsets for ProcessedKeyframe {
- fn offset(&self) -> Option<f64> {
- self.offset
- }
-
- fn computed_offset(&self) -> Option<f64> {
- self.computed_offset
- }
-
- fn set_computed_offset(&mut self, computed_offset: Option<f64>) {
- self.computed_offset = computed_offset;
- }
-}
-
fn type_error(message: String) -> Exception {
Exception::TypeError(Utf16String::from_utf8(&message))
}
@@ -251,16 +214,17 @@ fn to_composite_operation(vm: &Vm, value: Value) -> WebIdlResult<CompositeOperat
}
let string_value = value.to_utf16_string(vm)?;
- if utf16_string_equals(&string_value, "replace") {
+ let string_value = string_value.to_utf16();
+ if units_equal(&string_value, "replace") {
return Ok(CompositeOperationOrAuto::Replace);
}
- if utf16_string_equals(&string_value, "add") {
+ if units_equal(&string_value, "add") {
return Ok(CompositeOperationOrAuto::Add);
}
- if utf16_string_equals(&string_value, "accumulate") {
+ if units_equal(&string_value, "accumulate") {
return Ok(CompositeOperationOrAuto::Accumulate);
}
- if utf16_string_equals(&string_value, "auto") {
+ if units_equal(&string_value, "auto") {
return Ok(CompositeOperationOrAuto::Auto);
}
@@ -274,24 +238,20 @@ fn is_a_custom_property_name_string(name: &[u16]) -> bool {
name.len() > 2 && name[0] == u16::from(b'-') && name[1] == u16::from(b'-')
}
-fn units_equal(units: &[u16], text: &str) -> bool {
- units.iter().copied().eq(text.encode_utf16())
-}
-
-/// What steps 2 to 5 of the procedure to process a keyframe-like object make of the names of the properties of the
+/// What steps 3 to 6 of the procedure to process a keyframe-like object make of the names of the properties of the
/// keyframe input: its animation properties, sorted.
fn animation_properties(vm: &Vm, keyframe_object: Gc<Object>) -> WebIdlResult<Vec<Utf16String>> {
- // 2. Build up a list of animatable properties as follows:
+ // 3. Build up a list of animatable properties as follows:
//
// 1. Let animatable properties be a list of property names (including shorthand properties that have longhand
- // sub-properties that are animatable) that can be animated by the implementation.
+ // sub-properties that are animatable) that can be animated by the UA.
// 2. Convert each property name in animatable properties to the equivalent IDL attribute by applying the
// animation property name to IDL attribute name algorithm.
- // 3. Let input properties be the result of calling the EnumerableOwnNames operation with keyframe input as the
+ // 4. Let input properties be the result of calling the EnumerableOwnNames operation with keyframe input as the
// object.
- // 4. Make up a new list animation properties that consists of all of the properties that are in both input
+ // 5. Make up a new list animation properties that consists of all of the properties that are in both input
// properties and animatable properties, or which are in input properties and conform to the
// <custom-property-name> production.
let input_properties = keyframe_object.enumerable_own_property_names(vm, PropertyKind::Key)?;
@@ -307,11 +267,11 @@ fn animation_properties(vm: &Vm, keyframe_object: Gc<Object>) -> WebIdlResult<Ve
let name = input_property.as_string().utf16_string();
let units = name.to_utf16();
- // Handle the two special cases
+ // NB: Handle the two special cases.
if units_equal(&units, "cssFloat") || units_equal(&units, "cssOffset") {
animation_properties.push(name.clone());
} else if units_equal(&units, "float") || units_equal(&units, "offset") {
- // Ignore these property names
+ // NB: Ignore these property names.
} else if is_a_custom_property_name_string(&units) {
animation_properties.push(name.clone());
} else if let Some(property) = property_id_from_camel_case(&name)
@@ -321,7 +281,7 @@ fn animation_properties(vm: &Vm, keyframe_object: Gc<Object>) -> WebIdlResult<Ve
}
}
- // 5. Sort animation properties in ascending order by the Unicode codepoints that define each property name.
+ // 6. Sort animation properties in ascending order by the Unicode codepoints that define each property name.
animation_properties.sort_by(|a, b| a.to_utf16().cmp(&b.to_utf16()));
Ok(animation_properties)
@@ -347,14 +307,15 @@ fn process_a_keyframe_like_object_allowing_lists(
vm: &Vm,
keyframe_input: Value,
) -> WebIdlResult<BasePropertyIndexedKeyframe> {
- // 1. Run the procedure to convert an ECMAScript value to a dictionary type with keyframe input as the ECMAScript
- // value, and the dictionary type depending on the value of the allow lists flag as follows:
+ // 1. Run the procedure to convert an ECMAScript value to a dictionary type [WEBIDL] with keyframe input as the
+ // ECMAScript value, and the dictionary type depending on the value of the allow lists flag as follows:
//
// -> If allow lists is true, use the following dictionary type: <BasePropertyIndexedKeyframe>.
// -> Otherwise, use the following dictionary type: <BaseKeyframe>.
//
// Store the result of this procedure as keyframe output.
let mut keyframe_output = BasePropertyIndexedKeyframe::default();
+ // 2. If keyframe input is null or undefined, return keyframe output.
if keyframe_input.is_nullish() {
return Ok(keyframe_output);
}
@@ -375,17 +336,17 @@ fn process_a_keyframe_like_object_allowing_lists(
let offset = keyframe_member(vm, keyframe_object, "offset", None)?;
keyframe_output.offset = convert_value_to_maybe_list(vm, offset, || None, |value| to_offset(vm, value))?;
- // 2. through 5.
+ // 3. through 6.
let animation_properties = animation_properties(vm, keyframe_object)?;
- // 6. For each property name in animation properties,
+ // 7. For each property name in animation properties:
for property_name in animation_properties {
// 1. Let raw value be the result of calling the [[Get]] internal method on keyframe input, with property name
// as the property key and keyframe input as the receiver.
// 2. Check the completion record of raw value.
let raw_value = keyframe_object.get(vm, &PropertyKey::from_utf16_string(&property_name))?;
- // 3. Convert raw value to a DOMString or sequence of DOMStrings property values as follows:
+ // 3. Convert raw value to a DOMString or to a sequence of DOMStrings property values as follows:
// -> If allow lists is true,
// Let property values be the result of converting raw value to IDL type (DOMString or sequence<DOMString>)
@@ -398,8 +359,8 @@ fn process_a_keyframe_like_object_allowing_lists(
// 4. Calculate the normalized property name as the result of applying the IDL attribute name to animation
// property name algorithm to property name.
- // Note: We do not need to do this, since we did not need to do the reverse step (animation property name to IDL
- // attribute name) in the steps above.
+ // NB: We do not need to do this, since we did not need to do the reverse step (animation property name to IDL
+ // attribute name) in the steps above.
// 5. Add a property to keyframe output with normalized property name as the property name, and property values
// as the property value.
@@ -412,14 +373,15 @@ fn process_a_keyframe_like_object_allowing_lists(
// https://www.w3.org/TR/web-animations-1/#process-a-keyframe-like-object
// NB: With the allow lists flag set to false.
fn process_a_keyframe_like_object(vm: &Vm, keyframe_input: Value) -> WebIdlResult<BaseKeyframe> {
- // 1. Run the procedure to convert an ECMAScript value to a dictionary type with keyframe input as the ECMAScript
- // value, and the dictionary type depending on the value of the allow lists flag as follows:
+ // 1. Run the procedure to convert an ECMAScript value to a dictionary type [WEBIDL] with keyframe input as the
+ // ECMAScript value, and the dictionary type depending on the value of the allow lists flag as follows:
//
// -> If allow lists is true, use the following dictionary type: <BasePropertyIndexedKeyframe>.
// -> Otherwise, use the following dictionary type: <BaseKeyframe>.
//
// Store the result of this procedure as keyframe output.
let mut keyframe_output = BaseKeyframe::default();
+ // 2. If keyframe input is null or undefined, return keyframe output.
if keyframe_input.is_nullish() {
return Ok(keyframe_output);
}
@@ -432,17 +394,17 @@ fn process_a_keyframe_like_object(vm: &Vm, keyframe_input: Value) -> WebIdlResul
let offset = keyframe_member(vm, keyframe_object, "offset", None)?;
keyframe_output.offset = to_offset(vm, offset)?;
- // 2. through 5.
+ // 3. through 6.
let animation_properties = animation_properties(vm, keyframe_object)?;
- // 6. For each property name in animation properties,
+ // 7. For each property name in animation properties:
for property_name in animation_properties {
// 1. Let raw value be the result of calling the [[Get]] internal method on keyframe input, with property name
// as the property key and keyframe input as the receiver.
// 2. Check the completion record of raw value.
let raw_value = keyframe_object.get(vm, &PropertyKey::from_utf16_string(&property_name))?;
- // 3. Convert raw value to a DOMString or sequence of DOMStrings property values as follows:
+ // 3. Convert raw value to a DOMString or to a sequence of DOMStrings property values as follows:
// -> Otherwise,
// Let property values be the result of converting raw value to a DOMString using the procedure for
@@ -451,8 +413,8 @@ fn process_a_keyframe_like_object(vm: &Vm, keyframe_input: Value) -> WebIdlResul
// 4. Calculate the normalized property name as the result of applying the IDL attribute name to animation
// property name algorithm to property name.
- // Note: We do not need to do this, since we did not need to do the reverse step (animation property name to IDL
- // attribute name) in the steps above.
+ // NB: We do not need to do this, since we did not need to do the reverse step (animation property name to IDL
+ // attribute name) in the steps above.
// 5. Add a property to keyframe output with normalized property name as the property name, and property values
// as the property value.
@@ -463,33 +425,33 @@ fn process_a_keyframe_like_object(vm: &Vm, keyframe_input: Value) -> WebIdlResul
}
// https://www.w3.org/TR/web-animations-1/#compute-missing-keyframe-offsets
-fn compute_missing_keyframe_offsets<K: KeyframeOffsets>(keyframes: &mut [K]) {
+fn compute_missing_keyframe_offsets(keyframes: &mut [BaseKeyframe]) {
// 1. For each keyframe, in keyframes, let the computed keyframe offset of the keyframe be equal to its keyframe
// offset value.
for keyframe in keyframes.iter_mut() {
- keyframe.set_computed_offset(keyframe.offset());
+ keyframe.computed_offset = keyframe.offset;
}
// 2. If keyframes contains more than one keyframe and the computed keyframe offset of the first keyframe in
// keyframes is null, set the computed keyframe offset of the first keyframe to 0.
- if keyframes.len() > 1 && keyframes[0].computed_offset().is_none() {
- keyframes[0].set_computed_offset(Some(0.0));
+ if keyframes.len() > 1 && keyframes[0].computed_offset.is_none() {
+ keyframes[0].computed_offset = Some(0.0);
}
// 3. If the computed keyframe offset of the last keyframe in keyframes is null, set its computed keyframe offset
// to 1.
if let Some(last) = keyframes.last_mut()
- && last.computed_offset().is_none()
+ && last.computed_offset.is_none()
{
- last.set_computed_offset(Some(1.0));
+ last.computed_offset = Some(1.0);
}
// 4. For each pair of keyframes A and B where:
// - A appears before B in keyframes, and
// - A and B have a computed keyframe offset that is not null, and
// - all keyframes between A and B have a null computed keyframe offset,
- let find_next_index_of_keyframe_with_computed_offset = |keyframes: &[K], starting_index: usize| {
- (starting_index..keyframes.len()).find(|&index| keyframes[index].computed_offset().is_some())
+ let find_next_index_of_keyframe_with_computed_offset = |keyframes: &[BaseKeyframe], starting_index: usize| {
+ (starting_index..keyframes.len()).find(|&index| keyframes[index].computed_offset.is_some())
};
let Some(mut index_a) = find_next_index_of_keyframe_with_computed_offset(keyframes, 0) else {
@@ -502,10 +464,10 @@ fn compute_missing_keyframe_offsets<K: KeyframeOffsets>(keyframes: &mut [K]) {
for keyframe_index in index_a + 1..index_b {
// 1. Let offsetk be the computed keyframe offset of a keyframe k.
let offset_a = keyframes[index_a]
- .computed_offset()
+ .computed_offset
.expect("A has a computed keyframe offset");
let offset_b = keyframes[index_b]
- .computed_offset()
+ .computed_offset
.expect("B has a computed keyframe offset");
// 2. Let n be the number of keyframes between and including A and B minus 1.
@@ -518,7 +480,7 @@ fn compute_missing_keyframe_offsets<K: KeyframeOffsets>(keyframes: &mut [K]) {
let index = (keyframe_index - index_a) as f64;
// 4. Set the computed keyframe offset of keyframe to offsetA + (offsetB − offsetA) × index / n.
- keyframes[keyframe_index].set_computed_offset(Some(offset_a + (offset_b - offset_a) * index / n));
+ keyframes[keyframe_index].computed_offset = Some(offset_a + (offset_b - offset_a) * index / n);
}
index_a = index_b;
@@ -528,9 +490,9 @@ fn compute_missing_keyframe_offsets<K: KeyframeOffsets>(keyframes: &mut [K]) {
// https://www.w3.org/TR/web-animations-1/#loosely-sorted-by-offset
fn is_loosely_sorted_by_offset(keyframes: &[BaseKeyframe]) -> bool {
- // The list of keyframes for a keyframe effect must be loosely sorted by offset which means that for each keyframe
- // in the list that has a keyframe offset that is not null, the offset is greater than or equal to the offset of the
- // previous keyframe in the list with a keyframe offset that is not null, if any.
+ // The list of keyframes for a keyframe effect must be loosely sorted by offset, which means that for each keyframe
+ // in the list that has a keyframe offset that is not null, the offset must be greater than or equal to the offset
+ // of the previous keyframe in the list with a keyframe offset that is not null, if any.
let mut last_offset: Option<f64> = None;
for keyframe in keyframes {
@@ -551,7 +513,7 @@ fn is_loosely_sorted_by_offset(keyframes: &[BaseKeyframe]) -> bool {
/// The property a property name of a keyframe names, or none for a name the keyframe ignores.
fn keyframe_property_of_name(name: &Utf16String) -> Option<(KeyframePropertyName, u16)> {
let units = name.to_utf16();
- // Handle some special cases
+ // NB: Handle some special cases.
if units_equal(&units, "cssFloat") {
return Some((KeyframePropertyName::Id(PROPERTY_ID_FLOAT), PROPERTY_ID_FLOAT));
}
@@ -559,7 +521,7 @@ fn keyframe_property_of_name(name: &Utf16String) -> Option<(KeyframePropertyName
return Some((KeyframePropertyName::Id(PROPERTY_ID_OFFSET), PROPERTY_ID_OFFSET));
}
if units_equal(&units, "float") || units_equal(&units, "offset") {
- // Ignore these properties
+ // NB: Ignore these properties.
return None;
}
if is_a_custom_property_name_string(&units) {
@@ -591,7 +553,7 @@ pub(crate) fn process_a_keyframes_argument(
// 4. Check the completion record of method.
let method = iterator_method(vm, object_value)?;
- // 5. Perform the steps corresponding to the first matching condition from below,
+ // 5. Perform the steps corresponding to the first matching condition below:
// -> If method is not undefined,
if let Some(method) = method {
@@ -613,23 +575,23 @@ pub(crate) fn process_a_keyframes_argument(
}
// 7. Append to processed keyframes the result of running the procedure to process a keyframe-like object
- // passing nextItem as the keyframe input and with the allow lists flag set to false.
+ // passing nextItem as the keyframe input with the allow lists flag set to false.
processed_keyframes.push(process_a_keyframe_like_object(vm, next_item)?);
}
}
// -> Otherwise,
else {
// 1. Let property-indexed keyframe be the result of running the procedure to process a keyframe-like object
- // passing object as the keyframe input and with the allow lists flag set to true.
+ // passing object as the keyframe input with the allow lists flag set to true.
let property_indexed_keyframe = process_a_keyframe_like_object_allowing_lists(vm, object_value)?;
// 2. For each member, m, in property-indexed keyframe, perform the following steps:
for (property_name, property_values) in &property_indexed_keyframe.properties {
// 1. Let property name be the key for m.
- // 2. If property name is "composite", or "easing", or "offset", skip the remaining steps in this loop and
+ // 2. If property name is "composite", "easing", or "offset", skip the remaining steps in this loop and
// continue from the next member in property-indexed keyframe after m.
- // Note: This will never happen, since these fields have dedicated members on BasePropertyIndexedKeyframe
+ // NB: This will never happen, since these fields have dedicated members on BasePropertyIndexedKeyframe.
// 3. Let property values be the value for m.
@@ -663,12 +625,13 @@ pub(crate) fn process_a_keyframes_argument(
let b = b
.computed_offset
.expect("a property keyframe has a computed keyframe offset");
- a.partial_cmp(&b).unwrap_or(core::cmp::Ordering::Equal)
+ // NB: Offsets are never NaN, and adding zero makes -0 and +0 compare equal, as step 4 merges them.
+ (a + 0.0).total_cmp(&(b + 0.0))
});
// 4. Merge adjacent keyframes in processed keyframes when they have equal computed keyframe offsets.
- // Note: The spec doesn't specify how to merge them, but WebKit seems to just override the properties of the
- // earlier keyframe with the properties of the later keyframe.
+ // NB: The spec doesn't specify how to merge them, but WebKit seems to just override the properties of the
+ // earlier keyframe with the properties of the later keyframe.
let mut i = 0;
while i + 1 < processed_keyframes.len() {
if processed_keyframes[i].computed_offset == processed_keyframes[i + 1].computed_offset {
@@ -700,7 +663,7 @@ pub(crate) fn process_a_keyframes_argument(
// A sequence of length one with the value of "offset" as its single item, i.e. « offset »,
let offsets = property_indexed_keyframe.offset.into_list();
- // 6. Assign each value in offsets to the keyframe offset of the keyframe with corresponding position in
+ // 6. Assign each value in offsets to the keyframe offset of the keyframe with the corresponding position in
// processed keyframes until the end of either sequence is reached.
for (keyframe, offset) in processed_keyframes.iter_mut().zip(offsets) {
keyframe.offset = offset;
@@ -793,15 +756,22 @@ pub(crate) fn process_a_keyframes_argument(
}
}
+ // FIXME: After processing the keyframe argument, we need to turn the set of keyframes into a set of computed
+ // keyframes using the procedure outlined in the second half of
+ // https://www.w3.org/TR/web-animations-1/#calculating-computed-keyframes. For now, just compute the
+ // missing keyframe offsets
+ // NB: Step 8 maps the processed keyframes one to one, so their computed keyframe offsets carry over.
+ compute_missing_keyframe_offsets(&mut processed_keyframes);
+
// 8. For each frame in processed keyframes, perform the following steps:
let mut keyframes = Vec::with_capacity(processed_keyframes.len());
for keyframe in processed_keyframes {
// 1. For each property-value pair in frame, parse the property value using the syntax specified for that
// property.
//
- // If the property value is invalid according to the syntax for the property, discard the property-value pair.
- // User agents that provide support for diagnosing errors in content SHOULD produce an appropriate warning
- // highlight
+ // If the property value is invalid according to the syntax for the property, discard the property-value
+ // pair. User agents that provide support for diagnosing errors in content SHOULD produce an appropriate
+ // warning highlighting the invalid property value.
let mut parsed_properties: Vec<(KeyframePropertyName, StyleValue)> = Vec::new();
for (property_string, value_string) in &keyframe.properties {
let Some((property, property_id)) = keyframe_property_of_name(property_string) else {
@@ -813,7 +783,7 @@ pub(crate) fn process_a_keyframes_argument(
}
}
- // 2. Let the timing function of frame be the result of parsing the "easing" property on frame using the CSS
+ // 2. Let the easing function of frame be the result of parsing the "easing" property on frame using the CSS
// syntax defined for the easing member of the EffectTiming dictionary.
//
// If parsing the "easing" property fails, throw a TypeError and abort this procedure.
@@ -821,15 +791,17 @@ pub(crate) fn process_a_keyframes_argument(
keyframes.push(ProcessedKeyframe {
offset: keyframe.offset,
- computed_offset: keyframe.computed_offset,
+ computed_offset: keyframe
+ .computed_offset
+ .expect("a processed keyframe has a computed keyframe offset"),
easing,
composite: keyframe.composite,
properties: parsed_properties,
});
}
- // 9. Parse each of the values in unused easings using the CSS syntax defined for easing member of the EffectTiming
- // interface, and if any of the values fail to parse, throw a TypeError and abort this procedure.
+ // 9. Parse each of the values in unused easings using the CSS syntax defined for the easing member of the
+ // EffectTiming dictionary, and if any of the values fail to parse, throw a TypeError and abort this procedure.
for unused_easing in &unused_easings {
if parse_easing_function(unused_easing).is_none() {
return Err(invalid_easing(unused_easing));
@@ -899,7 +871,7 @@ impl Wrappable for KeyframeEffect {
fn finalize(object: Ref<Self>) {
// NB: The record can outlive the effect until what holds the record is swept.
- object.effect.record().set_facade(None);
+ object.effect.record().set_object_cell(None);
}
}
@@ -907,7 +879,10 @@ impl KeyframeEffect {
/// A new effect with the default timing, no keyframes and no target.
pub(crate) fn create(vm: &Vm) -> Ref<Self> {
let object = Self::create_for_record(vm, EffectRecordRef::new());
- object.effect.record().set_facade(NonNull::new(cell_into_abi(object)));
+ object
+ .effect
+ .record()
+ .set_object_cell(NonNull::new(cell_into_abi(object)));
object
}
@@ -928,8 +903,7 @@ impl KeyframeEffect {
}
fn invalidate(&self) {
- // SAFETY: The effect holds a reference to the record.
- unsafe { web_animation_effect_invalidate(self.record_ptr()) };
+ self.effect.record().invalidate();
}
/// Sets the target element of the effect to the host's `DOM::Element`, or to none, invalidating what that changes
@@ -942,39 +916,27 @@ impl KeyframeEffect {
fn set_target_pseudo_element(&self, pseudo_element: Option<&ParsedPseudoElement>) {
self.effect.record().set_pseudo_element(pseudo_element);
self.invalidate();
- // FIXME: We don't remove the animated style from the old target element as part of normal animated style update and
- // it will remain "stuck" until it's style is fully invalidated for some other reason.
+ // FIXME: We don't remove the animated style from the old target element as part of normal animated style update
+ // and it will remain "stuck" until its style is fully invalidated for some other reason.
}
fn set_composite_operation(&self, composite: CompositeOperation) {
- // SAFETY: The effect holds a reference to the record.
- unsafe { web_animation_effect_set_composite(self.record_ptr(), composite) };
+ self.effect.record().set_composite(composite);
+ self.invalidate();
}
- /// Sets the keyframes of the effect to the processed keyframes, whose missing offsets this computes.
+ /// Sets the keyframes of the effect to the processed keyframes.
pub(crate) fn set_processed_keyframes(&self, keyframes: Vec<ProcessedKeyframe>) {
self.set_processed_keyframes_copied_from(keyframes, None);
}
- /// Sets the keyframes of the effect to the processed keyframes, whose missing offsets this computes, which resolve
- /// what they reference against the style sheet of those of `source` where they are a copy of its keyframes.
- fn set_processed_keyframes_copied_from(
- &self,
- mut keyframes: Vec<ProcessedKeyframe>,
- source: Option<&EffectRecordRef>,
- ) {
- // FIXME: After processing the keyframe argument, we need to turn the set of keyframes into a set of computed
- // keyframes using the procedure outlined in the second half of
- // https://www.w3.org/TR/web-animations-1/#calculating-computed-keyframes. For now, just compute the
- // missing keyframe offsets
- compute_missing_keyframe_offsets(&mut keyframes);
-
+ /// Sets the keyframes of the effect to the processed keyframes, which resolve what they reference against the
+ /// style sheet of those of `source` where they are a copy of its keyframes.
+ fn set_processed_keyframes_copied_from(&self, keyframes: Vec<ProcessedKeyframe>, source: Option<&EffectRecordRef>) {
let inputs = keyframes
.iter()
.map(|keyframe| KeyframeSetInput {
- computed_offset: keyframe
- .computed_offset
- .expect("a keyframe has a computed keyframe offset"),
+ computed_offset: keyframe.computed_offset,
composite: keyframe.composite,
easing: &keyframe.easing,
properties: &keyframe.properties,
@@ -1027,7 +989,7 @@ impl KeyframeEffect {
// 2. Set the target element of effect to target.
effect.set_target_element(target, true);
- // 3. Set the target pseudo-selector to the result corresponding to the first matching condition from below.
+ // 3. Set the target pseudo-selector to the result corresponding to the first matching condition below:
// If options is a KeyframeEffectOptions object with a pseudoElement property,
if let UnrestrictedDoubleOrKeyframeEffectOptions::KeyframeEffectOptions(options) = &options {
@@ -1040,9 +1002,9 @@ impl KeyframeEffect {
}
// Otherwise,
// Set the target pseudo-selector to null.
- // Note: This is the default when constructed
+ // NB: This is the default when constructed.
- // 4. Let timing input be the result corresponding to the first matching condition from below.
+ // 4. Let timing input be the result corresponding to the first matching condition below:
let (timing_input, composite) = match options {
// If options is a KeyframeEffectOptions object,
// Let timing input be options.
@@ -1070,7 +1032,7 @@ impl KeyframeEffect {
// https://drafts.csswg.org/web-animations-2/#the-effecttiming-dictionaries
// Note: In this version of the spec, duration is not settable as a CSSNumericValue; however, duration may be
// returned as a CSSNumericValue when resolving the duration in getComputedTiming(). Future versions of
- // the spec may enable setting the duration as a CSSNumeric value, where the unit is a valid time unit or
+ // the spec may enable setting the duration as a CSSNumericValue, where the unit is a valid time unit or
// percent.
if matches!(
timing_input.duration,
@@ -1156,7 +1118,7 @@ impl KeyframeEffect {
// - iteration count,
// - specified iteration duration,
// - playback direction, and
- // - timing function.
+ // - easing function.
effect
.effect
.record()
@@ -1196,7 +1158,7 @@ impl KeyframeEffect {
pub(crate) fn set_pseudo_element(&self, _cx: &mut CallContext, value: Option<Utf16String>) -> WebIdlResult<()> {
// On setting, sets the target pseudo-selector of the animation effect to the result of
// pseudo-element parsing on the provided value, defined as the following:
- // NOTE: The actual definition is in pseudo_element_parsing().
+ // NB: The actual definition is in pseudo_element_parsing().
let pseudo_element = pseudo_element_parsing(value.as_ref())?;
self.set_target_pseudo_element(pseudo_element.as_ref());
Ok(())
@@ -1245,9 +1207,7 @@ impl KeyframeEffect {
.iter()
.map(|keyframe| ReflectedKeyframe {
offset: keyframe.offset,
- computed_offset: keyframe
- .computed_offset
- .expect("a keyframe has a computed keyframe offset"),
+ computed_offset: keyframe.computed_offset,
easing: keyframe.easing.serialization().clone(),
composite: match keyframe.composite {
CompositeOperationOrAuto::Replace => "replace",
@@ -1280,7 +1240,7 @@ impl KeyframeEffect {
.collect();
drop(script_keyframes);
- // The getKeyframes() algorithm returns a fresh sequence of fresh objects on every invocation.
+ // NB: The getKeyframes() algorithm returns a fresh sequence of fresh objects on every invocation.
let keyframes = MarkedVec::new(vm);
let string = |string: Utf16String| Value::from_string(PrimitiveString::create(vm, string));
for keyframe in reflected_keyframes {
diff --git a/Libraries/LibWeb/Bindings/Rust/src/animations/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/animations/mod.rs
index 42688650b36..666860a6f10 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/animations/mod.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/animations/mod.rs
@@ -13,7 +13,6 @@ pub(crate) mod animation_playback_event;
pub(crate) mod animation_timeline;
pub(crate) mod document_or_shadow_root;
pub(crate) mod document_timeline;
-pub(crate) mod exports;
pub(crate) mod keyframe_effect;
pub(crate) mod scroll_timeline;
pub(crate) mod view_timeline;
diff --git a/Libraries/LibWeb/Bindings/Rust/src/animations/scroll_timeline.rs b/Libraries/LibWeb/Bindings/Rust/src/animations/scroll_timeline.rs
index 6af954f9210..7f4358b6eba 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/animations/scroll_timeline.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/animations/scroll_timeline.rs
@@ -21,7 +21,6 @@ use crate::bindings::interface::{Inherits, Ref, Wrappable, allocate, cell_into_a
use crate::bindings::{CallContext, WebIdlResult};
unsafe extern "C" {
- fn web_scroll_timeline_source(timeline: *mut c_void) -> *mut c_void;
fn web_animation_document_scrolling_element(document: *mut c_void) -> *mut c_void;
}
@@ -126,8 +125,7 @@ impl ScrollTimeline {
pub(crate) fn source(&self, cx: &mut CallContext) -> WebIdlResult<Option<CppInterface>> {
// NB: The host finds the scroll container element an anonymous source names from its target, and the source of a
// view timeline from its subject.
- // SAFETY: The cell is that of this live timeline.
- let source = NonNull::new(unsafe { web_scroll_timeline_source(self.timeline.cell()) });
+ let source = self.timeline.record().source_element();
Ok(source.map(|source| element_wrapper(cx, source)))
}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/animations/view_timeline.rs b/Libraries/LibWeb/Bindings/Rust/src/animations/view_timeline.rs
index ac97df5f892..ffdf2d7dfad 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/animations/view_timeline.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/animations/view_timeline.rs
@@ -216,6 +216,8 @@ impl ViewTimeline {
pub(crate) fn start_offset(&self, cx: &mut CallContext) -> WebIdlResult<AnyCSSNumericValue> {
// Represents the starting (0% progress) scroll position of the view progress timeline as a length offset (in
// px) from the scroll origin.
+ // Null when the timeline is inactive.
+ // AD-HOC: The attribute is not nullable in the IDL, so an inactive timeline gives 0px.
let start = self.record().cover_range().map_or(0.0, |(start, _)| start);
Ok(AnyCSSNumericValue::CSSUnitValue(CSSUnitValue::create(
cx.vm(),
@@ -228,6 +230,8 @@ impl ViewTimeline {
pub(crate) fn end_offset(&self, cx: &mut CallContext) -> WebIdlResult<AnyCSSNumericValue> {
// Represents the ending (100% progress) scroll position of the view progress timeline as a length offset (in
// px) from the scroll origin.
+ // Null when the timeline is inactive.
+ // AD-HOC: The attribute is not nullable in the IDL, so an inactive timeline gives 0px.
let end = self.record().cover_range().map_or(0.0, |(_, end)| end);
Ok(AnyCSSNumericValue::CSSUnitValue(CSSUnitValue::create(
cx.vm(),
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/promise.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/promise.rs
index 39690cdc03b..6fc82ffe2aa 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/promise.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/promise.rs
@@ -103,6 +103,13 @@ unsafe impl Trace for TaskSource {
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) struct TaskId(u64);
+impl TaskId {
+ /// The HTML::TaskID of the task.
+ pub(crate) fn host_id(self) -> u64 {
+ self.0
+ }
+}
+
/// The promise that LibWeb's C++ code returns, a WebIDL::Promise.
///
/// # Safety
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/animation_event.rs b/Libraries/LibWeb/Bindings/Rust/src/css/animation_event.rs
index 9ad46130d05..494381c7fd8 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/css/animation_event.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/animation_event.rs
@@ -6,6 +6,7 @@
//! AnimationEvent, https://drafts.csswg.org/css-animations-2/#interface-animationevent
+use core::cell::RefCell;
use core::ffi::c_void;
use core::ptr::NonNull;
@@ -23,37 +24,45 @@ use crate::dom::event::EventInit;
/// The animation an event names, as its record. The event visits what keeps the record's object, or the elements the
/// record names, alive.
-pub(crate) struct EventAnimation(AnimationRecordRef);
-
-unsafe extern "C" {
- fn web_animation_visit_host_cells(animation: *const c_void, visitor: *mut c_void);
-}
+/// NB: The event lets go of the record as it is finalized rather than as it is swept, after the elements the record
+/// names may be gone, so that the record never outlives them alive.
+pub(crate) struct EventAnimation(RefCell<Option<AnimationRecordRef>>);
impl EventAnimation {
- /// # Safety
- ///
- /// `animation` must be an animation the host holds a reference to.
- pub(crate) unsafe fn retained_from_host(animation: *const c_void) -> Self {
- // SAFETY: Guaranteed by the caller.
- Self(unsafe { AnimationRecordRef::retained_from_host(animation) })
+ /// The animation of a record of it.
+ pub(crate) fn of_record(animation: AnimationRecordRef) -> Self {
+ Self(RefCell::new(Some(animation)))
}
/// The animation of an object of it.
pub(crate) fn of_object(animation: &Animation) -> Self {
- Self(animation.record().clone())
+ Self::of_record(animation.record().clone())
}
/// The object of the animation, which a CSS animation or transition gets as script first asks for it.
pub(crate) fn wrap(&self, cx: &CallContext) -> AnyAnimation {
- animation_object(cx.vm(), &self.0)
+ let animation = self.0.borrow();
+ animation_object(
+ cx.vm(),
+ animation.as_ref().expect("an event that is alive holds its animation"),
+ )
+ }
+
+ /// Lets go of the record, as the event is finalized.
+ pub(crate) fn release(&self) {
+ self.0.borrow_mut().take();
}
}
// SAFETY: Visits the cells of the host that keep the record's object, or the elements the record names, alive.
unsafe impl Trace for EventAnimation {
fn trace(&self, visitor: &mut Visitor) {
- // SAFETY: The event holds a reference to the record, and the visitor is one LibGC passed in.
- unsafe { web_animation_visit_host_cells(self.0.as_host_ptr(), visitor.as_raw().cast()) };
+ if let Some(animation) = self.0.borrow().as_ref() {
+ animation.for_each_host_cell(|cell, _| {
+ // SAFETY: The record names live cells of the host, which the event keeps alive.
+ visitor.visit(unsafe { Gc::from_non_null(cell) });
+ });
+ }
}
}
@@ -83,6 +92,14 @@ impl Wrappable for AnimationEvent {
fn cpp_parent(&self) -> Option<NonNull<c_void>> {
self.event.as_cpp_parent()
}
+
+ const FINALIZES: bool = true;
+
+ fn finalize(object: Ref<Self>) {
+ if let Some(animation) = &object.animation {
+ animation.release();
+ }
+ }
}
impl AnimationEvent {
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_style_value.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_style_value.rs
index 8f5a22885e9..f1c01411f44 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/css/css_style_value.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_style_value.rs
@@ -26,7 +26,7 @@ use super::css_unit_value::CSSUnitValue;
use super::css_unparsed_value::CSSUnparsedValue;
use super::typed_om;
use crate::bindings::conversions::{ToJs, UsvString};
-use crate::bindings::interface::{Inherits, Ref, Wrappable, allocate, cell_into_abi, wrap};
+use crate::bindings::interface::{Inherits, Ref, Wrappable, allocate, wrap};
use crate::bindings::{CallContext, Exception, WebIdlResult};
use libjs_rust::api::{ThrowCompletionOr, Value};
@@ -102,27 +102,6 @@ impl AnyCSSStyleValue {
}
}
- /// The cell of the object, as LibWeb's C++ code holds it.
- pub(crate) fn cell_into_abi(self) -> *mut core::ffi::c_void {
- match self {
- Self::CSSStyleValue(object) => cell_into_abi(object),
- Self::CSSImageValue(object) => cell_into_abi(object),
- Self::CSSKeywordValue(object) => cell_into_abi(object),
- Self::CSSMathClamp(object) => cell_into_abi(object),
- Self::CSSMathInvert(object) => cell_into_abi(object),
- Self::CSSMathMax(object) => cell_into_abi(object),
- Self::CSSMathMin(object) => cell_into_abi(object),
- Self::CSSMathNegate(object) => cell_into_abi(object),
- Self::CSSMathProduct(object) => cell_into_abi(object),
- Self::CSSMathSum(object) => cell_into_abi(object),
- Self::CSSMathValue(object) => cell_into_abi(object),
- Self::CSSNumericValue(object) => cell_into_abi(object),
- Self::CSSTransformValue(object) => cell_into_abi(object),
- Self::CSSUnitValue(object) => cell_into_abi(object),
- Self::CSSUnparsedValue(object) => cell_into_abi(object),
- }
- }
-
// https://drafts.css-houdini.org/css-typed-om-1/#stylevalue-serialization
pub(crate) fn serialize(&self, vm: &Vm) -> WebIdlResult<Utf16String> {
match self {
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/exports.rs b/Libraries/LibWeb/Bindings/Rust/src/css/exports.rs
index cb17d6d9649..8b636db86c0 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/css/exports.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/exports.rs
@@ -4,46 +4,32 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-//! What the C++ code of LibWeb asks of the interfaces of CSS, declared in Libraries/LibWeb/CSS/MediaList.cpp and
-//! Libraries/LibWeb/CSS/TypedOM.cpp.
+//! What the C++ code of LibWeb asks of the interfaces of CSS, declared in Libraries/LibWeb/CSS/MediaList.cpp.
use core::ffi::c_void;
use core::ptr::null_mut;
use std::rc::Rc;
-use std::sync::Arc;
use ak::Utf16String;
use libcompositing_rust::css_pixels::{CssPixelRect, FfiCssPixelPoint, FfiCssPixelRect};
-use libjs_rust::api::{MarkedVec, Vm};
-use libweb_rust::typed_om::{FfiNumericType, RetainedStyleValue};
+use libjs_rust::api::Vm;
use libweb_rust::{NativeMediaList, NativeRule, NativeRuleList};
-use super::animation_event::{AnimationEvent, AnimationEventInit, EventAnimation};
use super::css_container_rule::CSSContainerRule;
use super::css_counter_style_rule::CSSCounterStyleRule;
use super::css_font_face_rule::CSSFontFaceRule;
use super::css_font_feature_values_rule::CSSFontFeatureValuesRule;
use super::css_function_declarations::CSSFunctionDeclarations;
use super::css_function_rule::CSSFunctionRule;
-use super::css_image_value::CSSImageValue;
use super::css_import_rule::CSSImportRule;
use super::css_keyframe_rule::CSSKeyframeRule;
use super::css_keyframes_rule::CSSKeyframesRule;
-use super::css_keyword_value::CSSKeywordValue;
use super::css_layer_block_rule::CSSLayerBlockRule;
use super::css_layer_statement_rule::CSSLayerStatementRule;
use super::css_margin_rule::CSSMarginRule;
-use super::css_math_clamp::CSSMathClamp;
-use super::css_math_invert::CSSMathInvert;
-use super::css_math_max::CSSMathMax;
-use super::css_math_min::CSSMathMin;
-use super::css_math_negate::CSSMathNegate;
-use super::css_math_product::CSSMathProduct;
-use super::css_math_sum::CSSMathSum;
use super::css_media_rule::CSSMediaRule;
use super::css_namespace_rule::CSSNamespaceRule;
use super::css_nested_declarations::CSSNestedDeclarations;
-use super::css_numeric_value::AnyCSSNumericValue;
use super::css_page_rule::CSSPageRule;
use super::css_position_try_rule::CSSPositionTryRule;
use super::css_property_rule::CSSPropertyRule;
@@ -52,11 +38,7 @@ use super::css_rule_list::CSSRuleList;
use super::css_scope_rule::CSSScopeRule;
use super::css_style_rule::CSSStyleRule;
use super::css_style_sheet::CSSStyleSheet;
-use super::css_style_value::{AnyCSSStyleValue, CSSStyleValue};
use super::css_supports_rule::CSSSupportsRule;
-use super::css_transform_value::CSSTransformValue;
-use super::css_unit_value::CSSUnitValue;
-use super::css_unparsed_value::CSSUnparsedValue;
use super::font_face_set::{CppFontFaceState, FontFaceSet};
use super::highlight_registry::HighlightRegistry;
use super::media_list::MediaList;
@@ -65,12 +47,9 @@ use super::screen::Screen;
use super::style_property_map::StylePropertyMap;
use super::style_property_map_read_only::StylePropertyMapReadOnly;
use super::style_sheet_list::StyleSheetList;
-use super::transition_event::{TransitionEvent, TransitionEventInit};
-use super::typed_om;
use super::visual_viewport::VisualViewport;
use crate::bindings::cpp_cell::CppCell;
use crate::bindings::interface::{Ref, allocate, cell_from_abi, cell_if_abi, cell_into_abi, realm_arguments};
-use crate::dom::event::EventInit;
/// # Safety
///
@@ -141,249 +120,6 @@ pub unsafe extern "C" fn web_media_list_share_native_list(list: *mut c_void) ->
Box::into_raw(Box::new(media))
}
-/// The object of the cell of a CSSStyleValue or of an interface that inherits from it.
-///
-/// # Safety
-///
-/// `cell` must be the live cell of such an object.
-unsafe fn style_value_from_abi(cell: *mut c_void) -> AnyCSSStyleValue {
- macro_rules! decode {
- ($($interface:ident),+ $(,)?) => {
- $(
- // SAFETY: The caller passes a live cell.
- if let Some(object) = unsafe { cell_if_abi::<$interface>(cell) } {
- return AnyCSSStyleValue::$interface(object);
- }
- )+
- };
- }
- decode!(
- CSSUnitValue,
- CSSMathSum,
- CSSMathProduct,
- CSSMathNegate,
- CSSMathInvert,
- CSSMathMin,
- CSSMathMax,
- CSSMathClamp,
- CSSKeywordValue,
- CSSUnparsedValue,
- CSSTransformValue,
- CSSImageValue,
- CSSStyleValue,
- );
- unreachable!("C++ passes the cell of a CSSStyleValue")
-}
-
-/// The object of the cell of a CSSNumericValue.
-///
-/// # Safety
-///
-/// `cell` must be the live cell of a CSSNumericValue.
-unsafe fn numeric_value_from_abi(cell: *mut c_void) -> AnyCSSNumericValue {
- // SAFETY: The caller passes a live cell.
- unsafe { style_value_from_abi(cell) }
- .as_numeric()
- .expect("C++ passes the cell of a CSSNumericValue")
-}
-
-/// A new CSSStyleValue, given a raw string and a style value that C++ hands over.
-///
-/// # Safety
-///
-/// `vm` must be the live VM, `associated_property` a raw string and `source_value` a strong reference to a style value
-/// that C++ hands over.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn web_css_style_value_create(
- vm: *mut c_void,
- associated_property: usize,
- source_value: *const c_void,
- serialization_mode: u8,
-) -> *mut c_void {
- // SAFETY: The caller passes the live VM.
- let vm = unsafe { vm_from_abi(vm) };
- // SAFETY: The caller hands over the string and the style value.
- let (associated_property, source_value) = unsafe {
- (
- Utf16String::from_raw_owned(associated_property),
- RetainedStyleValue::from_raw(source_value),
- )
- };
- cell_into_abi(CSSStyleValue::create(
- vm,
- associated_property,
- source_value,
- serialization_mode,
- ))
-}
-
-/// # Safety
-///
-/// `vm` must be the live VM, `value` a strong reference to a style value and `associated_property` a raw string that
-/// C++ hands over.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn web_css_style_value_reify(
- vm: *mut c_void,
- value: *const c_void,
- associated_property: usize,
-) -> *mut c_void {
- // SAFETY: The caller passes the live VM.
- let vm = unsafe { vm_from_abi(vm) };
- // SAFETY: The caller hands over the string and the style value.
- let (value, associated_property) = unsafe {
- (
- RetainedStyleValue::from_raw(value),
- Utf16String::from_raw_owned(associated_property),
- )
- };
- typed_om::reify(vm, &value, &associated_property).cell_into_abi()
-}
-
-/// Whether the value has an associated property, which goes to `associated_property` as a raw string.
-///
-/// # Safety
-///
-/// `value` must be the live cell of a CSSStyleValue, and `associated_property` a place for a raw string.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn web_css_style_value_associated_property(
- value: *mut c_void,
- associated_property: *mut usize,
-) -> bool {
- // SAFETY: The caller passes a live cell.
- let value = unsafe { style_value_from_abi(value) };
- let Some(property) = value.style_value().associated_property() else {
- return false;
- };
- // SAFETY: The caller passes a place for the string.
- unsafe { *associated_property = property.clone().into_raw() };
- true
-}
-
-/// What C++ distinguishes CSSStyleValues by, whose order is that of `enum class StyleValueKind` in
-/// Libraries/LibWeb/CSS/TypedOM.cpp.
-#[repr(u8)]
-enum StyleValueKind {
- Other,
- Numeric,
- Unit,
- Unparsed,
-}
-
-/// # Safety
-///
-/// `value` must be the live cell of a CSSStyleValue.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn web_css_style_value_kind(value: *mut c_void) -> u8 {
- // SAFETY: The caller passes a live cell.
- let value = unsafe { style_value_from_abi(value) };
- let kind = match value {
- AnyCSSStyleValue::CSSUnitValue(_) => StyleValueKind::Unit,
- AnyCSSStyleValue::CSSUnparsedValue(_) => StyleValueKind::Unparsed,
- value if value.as_numeric().is_some() => StyleValueKind::Numeric,
- _ => StyleValueKind::Other,
- };
- kind as u8
-}
-
-/// # Safety
-///
-/// `vm` must be the live VM, and `first` and `second` live cells of CSSNumericValues whose types can be added.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn web_css_numeric_value_create_sum(
- vm: *mut c_void,
- first: *mut c_void,
- second: *mut c_void,
-) -> *mut c_void {
- // SAFETY: The caller passes the live VM.
- let vm = unsafe { vm_from_abi(vm) };
- let values = MarkedVec::new(vm);
- // SAFETY: The caller passes live cells.
- unsafe {
- values.push(numeric_value_from_abi(first));
- values.push(numeric_value_from_abi(second));
- }
- let Ok(sum) = CSSMathSum::add_all_types_into_math_sum(vm, &values) else {
- unreachable!("C++ passes values whose types can be added");
- };
- cell_into_abi(sum)
-}
-
-/// # Safety
-///
-/// `value` must be the live cell of a CSSNumericValue.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn web_css_numeric_value_type(value: *mut c_void) -> FfiNumericType {
- // SAFETY: The caller passes a live cell.
- FfiNumericType::from_calc(Some(unsafe { numeric_value_from_abi(value) }.numeric_type()))
-}
-
-/// The serialization of the value, as a raw string for C++.
-///
-/// # Safety
-///
-/// `value` must be the live cell of a CSSNumericValue.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn web_css_numeric_value_to_string(value: *mut c_void) -> usize {
- // SAFETY: The caller passes a live cell.
- unsafe { numeric_value_from_abi(value) }.to_css_string().into_raw()
-}
-
-/// A strong reference to the calculation of the value, or null if it has none.
-///
-/// # Safety
-///
-/// `value` must be the live cell of a CSSNumericValue.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn web_css_numeric_value_create_calculation_node(value: *mut c_void) -> *const c_void {
- // SAFETY: The caller passes a live cell.
- match unsafe { numeric_value_from_abi(value) }.create_calculation_node() {
- Ok(node) => Arc::into_raw(node).cast(),
- Err(_) => core::ptr::null(),
- }
-}
-
-/// # Safety
-///
-/// `vm` must be the live VM, and `unit` a raw string that C++ hands over.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn web_css_unit_value_create(vm: *mut c_void, value: f64, unit: usize) -> *mut c_void {
- // SAFETY: The caller passes the live VM.
- let vm = unsafe { vm_from_abi(vm) };
- // SAFETY: The caller hands over the string.
- let unit = unsafe { Utf16String::from_raw_owned(unit) };
- cell_into_abi(CSSUnitValue::create(vm, value, &typed_om::to_rust_string(&unit)))
-}
-
-/// # Safety
-///
-/// `value` must be the live cell of a CSSUnitValue.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn web_css_unit_value_value(value: *mut c_void) -> f64 {
- // SAFETY: The caller passes a live cell of a CSSUnitValue.
- let value: Ref<CSSUnitValue> = unsafe { cell_from_abi(value) };
- value.raw_value()
-}
-
-/// # Safety
-///
-/// `value` must be the live cell of a CSSUnitValue.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn web_css_unit_value_unit(value: *mut c_void) -> usize {
- // SAFETY: The caller passes a live cell of a CSSUnitValue.
- let value: Ref<CSSUnitValue> = unsafe { cell_from_abi(value) };
- Utf16String::from_utf8(value.raw_unit()).into_raw()
-}
-
-/// # Safety
-///
-/// `value` must be the live cell of a CSSKeywordValue.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn web_css_keyword_value_value(value: *mut c_void) -> usize {
- // SAFETY: The caller passes a live cell of a CSSKeywordValue.
- let value: Ref<CSSKeywordValue> = unsafe { cell_from_abi(value) };
- value.raw_value().into_raw()
-}
-
/// A new MediaQueryList of the document, whose media query list shares the queries of the one that C++ passes.
///
/// # Safety
@@ -675,92 +411,6 @@ pub unsafe extern "C" fn web_screen_create(vm: *mut c_void, realm: *mut c_void,
cell_into_abi(Screen::create(vm, realm, window))
}
-/// A new AnimationEvent that bubbles, as the Event that C++ dispatches.
-///
-/// # Safety
-///
-/// `vm` must be the live VM, `realm` a live realm, `event_name`, `animation_name` and `pseudo_element` raw strings that
-/// C++ hands over, and `animation` a CSS animation C++ holds a reference to.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn web_animation_event_create(
- vm: *mut c_void,
- realm: *mut c_void,
- event_name: usize,
- animation_name: usize,
- elapsed_time: f64,
- pseudo_element: usize,
- animation: *const c_void,
-) -> *mut c_void {
- // SAFETY: The caller passes the live VM and a live realm.
- let (vm, realm) = unsafe { realm_arguments(vm, realm) };
- // SAFETY: The caller hands over the strings and passes an animation it holds a reference to.
- let (event_name, animation_name, pseudo_element, animation) = unsafe {
- (
- Utf16String::from_raw_owned(event_name),
- Utf16String::from_raw_owned(animation_name),
- Utf16String::from_raw_owned(pseudo_element),
- EventAnimation::retained_from_host(animation),
- )
- };
- let event_init = AnimationEventInit {
- parent: bubbling_event_init(),
- animation: None,
- animation_name,
- elapsed_time,
- pseudo_element,
- };
- let event = AnimationEvent::create_for_animation(vm, realm, &event_name, event_init, Some(animation));
- event.event().set_is_trusted(true);
- event.event().as_ptr()
-}
-
-/// A new TransitionEvent that bubbles, as the Event that C++ dispatches.
-///
-/// # Safety
-///
-/// `vm` must be the live VM, `realm` a live realm, `event_name`, `property_name` and `pseudo_element` raw strings that
-/// C++ hands over, and `animation` a CSS transition C++ holds a reference to.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn web_transition_event_create(
- vm: *mut c_void,
- realm: *mut c_void,
- event_name: usize,
- property_name: usize,
- elapsed_time: f64,
- pseudo_element: usize,
- animation: *const c_void,
-) -> *mut c_void {
- // SAFETY: The caller passes the live VM and a live realm.
- let (vm, realm) = unsafe { realm_arguments(vm, realm) };
- // SAFETY: The caller hands over the strings and passes an animation it holds a reference to.
- let (event_name, property_name, pseudo_element, animation) = unsafe {
- (
- Utf16String::from_raw_owned(event_name),
- Utf16String::from_raw_owned(property_name),
- Utf16String::from_raw_owned(pseudo_element),
- EventAnimation::retained_from_host(animation),
- )
- };
- let event_init = TransitionEventInit {
- parent: bubbling_event_init(),
- animation: None,
- elapsed_time,
- property_name,
- pseudo_element,
- };
- let event = TransitionEvent::create_for_animation(vm, realm, &event_name, event_init, Some(animation));
- event.event().set_is_trusted(true);
- event.event().as_ptr()
-}
-
-fn bubbling_event_init() -> EventInit {
- EventInit {
- bubbles: true,
- cancelable: false,
- composed: false,
- }
-}
-
/// The object of the rule whose cell C++ holds, which C++ names by any of the interfaces it is an object of.
///
/// # Safety
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/transition_event.rs b/Libraries/LibWeb/Bindings/Rust/src/css/transition_event.rs
index 0d3062c2ec9..b62bd447f57 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/css/transition_event.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/transition_event.rs
@@ -47,6 +47,14 @@ impl Wrappable for TransitionEvent {
fn cpp_parent(&self) -> Option<NonNull<c_void>> {
self.event.as_cpp_parent()
}
+
+ const FINALIZES: bool = true;
+
+ fn finalize(object: Ref<Self>) {
+ if let Some(animation) = &object.animation {
+ animation.release();
+ }
+ }
}
impl TransitionEvent {
diff --git a/Libraries/LibWeb/Bindings/Rust/src/dom/document.rs b/Libraries/LibWeb/Bindings/Rust/src/dom/document.rs
index 6821ffb43f6..4c420f7dcba 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/dom/document.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/dom/document.rs
@@ -7,13 +7,16 @@
//! The members of Document that are implemented in Rust, https://dom.spec.whatwg.org/#interface-document
use core::ffi::c_void;
+use core::ptr::NonNull;
use ak::Utf16String;
use libjs_rust::api::{MarkedVec, Trace, Vm};
use liburl_rust::origin::{Host, Origin};
use liburl_rust::{FfiOrigin, FfiUrlHost, Url};
+use libweb_rust::web_animations::TimelineRecordRef;
use crate::animations::animation::AnyAnimation;
+use crate::animations::animation_timeline::{AnyAnimationTimeline, timeline_object_of_record};
use crate::animations::document_or_shadow_root;
use crate::animations::document_timeline::DocumentTimeline;
use crate::bindings::conversions::CppInterface;
@@ -26,7 +29,7 @@ use crate::navigation_timing::performance_navigation_timing::PerformanceNavigati
use crate::permissions_policy::permissions_policy::PolicyControlledFeature;
unsafe extern "C" {
- fn web_animation_document_timeline(document_wrapper: *mut c_void) -> *mut c_void;
+ fn web_animation_document_of_wrapper(document_wrapper: *mut c_void) -> *mut c_void;
fn web_bindings_is_a_registrable_domain_suffix_of_or_is_equal_to(
host_suffix_string: usize,
original_host: *const FfiUrlHost,
@@ -213,12 +216,16 @@ pub(crate) fn is_a_registrable_domain_suffix_of_or_is_equal_to(
}
/// https://drafts.csswg.org/web-animations-1/#dom-document-timeline
-pub(crate) fn timeline(this: &CppInterface, _: &mut CallContext) -> WebIdlResult<Ref<DocumentTimeline>> {
+pub(crate) fn timeline(this: &CppInterface, cx: &mut CallContext) -> WebIdlResult<Ref<DocumentTimeline>> {
// The DocumentTimeline object representing the default document timeline.
- // SAFETY: The wrapper is live, and LibWeb returns the cell of the document's default document timeline.
- let cell = unsafe { web_animation_document_timeline(this.wrapper().as_ptr().cast()) };
- // SAFETY: LibWeb returns the live cell of a DocumentTimeline.
- Ok(unsafe { cell_from_abi::<DocumentTimeline>(cell) })
+ // SAFETY: The wrapper is live, and LibWeb returns the document it wraps.
+ let document = NonNull::new(unsafe { web_animation_document_of_wrapper(this.wrapper().as_ptr().cast()) })
+ .expect("a wrapper of a Document wraps a document");
+ let record = TimelineRecordRef::default_of_document(document);
+ let AnyAnimationTimeline::DocumentTimeline(timeline) = timeline_object_of_record(cx.vm(), &record) else {
+ unreachable!("the default document timeline is a document timeline");
+ };
+ Ok(timeline)
}
/// https://drafts.csswg.org/web-animations-1/#dom-documentorshadowroot-getanimations
diff --git a/Libraries/LibWeb/Bindings/Rust/src/internals/internal_animation_timeline.rs b/Libraries/LibWeb/Bindings/Rust/src/internals/internal_animation_timeline.rs
index 96a0435dd79..42a7bbdf3ce 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/internals/internal_animation_timeline.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/internals/internal_animation_timeline.rs
@@ -6,19 +6,18 @@
//! InternalAnimationTimeline, the timeline whose time tests set.
+use core::cell::RefCell;
use core::ffi::c_void;
+use core::ptr::NonNull;
-use libcompositing_rust::animation_timing::OptionalNumber;
-use libjs_rust::api::{Trace, Visitor};
+use libjs_rust::api::{CellRoot, Gc, Trace, Visitor, Vm};
+use libweb_rust::web_animations::{TimelineDescription, TimelineRecordRef};
-use crate::animations::animation_timeline::{AnimationTimeline, finalize_timeline};
-use crate::bindings::interface::{Inherits, Ref, Wrappable};
+use crate::animations::animation::perform_host_effect;
+use crate::animations::animation_timeline::{AnimationTimeline, finalize_timeline, timeline_object_of_record};
+use crate::bindings::interface::{Inherits, Ref, Wrappable, cell_into_abi};
use crate::bindings::{CallContext, WebIdlResult};
-unsafe extern "C" {
- fn web_internal_animation_timeline_set_time(timeline: *mut c_void, time: OptionalNumber, for_observation: bool);
-}
-
pub(crate) struct InternalAnimationTimeline {
timeline: AnimationTimeline,
}
@@ -53,15 +52,47 @@ impl InternalAnimationTimeline {
&self.timeline
}
+ /// Sets the time of the timeline, or the time a read of it observes, where `for_observation`.
+ fn set_internal_time(&self, time: Option<f64>, for_observation: bool) {
+ // NB: The animations the timeline updates stay alive through it, which can run script.
+ let roots: RefCell<Vec<CellRoot<c_void>>> = RefCell::default();
+ let keep_alive = |cell: NonNull<c_void>| {
+ // SAFETY: The record names a live cell of the host.
+ roots
+ .borrow_mut()
+ .push(CellRoot::new(unsafe { Gc::from_non_null(cell) }));
+ };
+ self.timeline
+ .record()
+ .set_internal_time(time, for_observation, &keep_alive, perform_host_effect);
+ }
+
pub(crate) fn set_time(&self, _: &mut CallContext, time: Option<f64>) -> WebIdlResult<()> {
- // SAFETY: The cell is that of this live timeline.
- unsafe { web_internal_animation_timeline_set_time(self.timeline.cell(), time.into(), false) };
+ self.set_internal_time(time, false);
Ok(())
}
pub(crate) fn set_time_for_observation(&self, _: &mut CallContext, time: f64) -> WebIdlResult<()> {
- // SAFETY: The cell is that of this live timeline.
- unsafe { web_internal_animation_timeline_set_time(self.timeline.cell(), Some(time).into(), true) };
+ self.set_internal_time(Some(time), true);
Ok(())
}
}
+
+/// A new timeline of the Internals interface associated with the host's `DOM::Document` `document`.
+///
+/// # Safety
+///
+/// `vm` must be the live VM, and `document` a live document.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_internal_animation_timeline_create(vm: *mut c_void, document: *mut c_void) -> *mut c_void {
+ // SAFETY: The caller passes the live VM.
+ let vm = unsafe { &*vm.cast::<Vm>() };
+ let document = NonNull::new(document).expect("a timeline is associated with a document");
+ let record = TimelineRecordRef::new(document, TimelineDescription::Internal);
+ let crate::animations::animation_timeline::AnyAnimationTimeline::InternalAnimationTimeline(object) =
+ timeline_object_of_record(vm, &record)
+ else {
+ unreachable!("the record is of an internal timeline");
+ };
+ cell_into_abi(object)
+}
diff --git a/Libraries/LibWeb/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txt
index ded34a4a873..6d5f43b1fc6 100644
--- a/Libraries/LibWeb/CMakeLists.txt
+++ b/Libraries/LibWeb/CMakeLists.txt
@@ -3,8 +3,6 @@ include(libweb_generators)
set(SOURCES
Animations/Animatable.cpp
Animations/AnimationEffect.cpp
- Animations/AnimationTimeline.cpp
- Animations/TimeValue.cpp
Animations/NamedTimelines.cpp
Animations/RecordHandles.cpp
ARIA/AriaData.cpp
@@ -61,7 +59,6 @@ set(SOURCES
CSS/CustomPropertyRegistration.cpp
CSS/GeneratedContent.cpp
CSS/CSS.cpp
- CSS/CSSAnimation.cpp
CSS/CSSDescriptors.cpp
CSS/CSSFontFaceRule.cpp
CSS/CSSFontFeatureValuesRule.cpp
@@ -76,7 +73,6 @@ set(SOURCES
CSS/CSSStyleProperties.cpp
CSS/CSSStyleRule.cpp
CSS/CSSStyleSheet.cpp
- CSS/CSSTransition.cpp
CSS/ColorFunctionDescriptor.cpp
CSS/CustomPropertyData.cpp
CSS/Descriptor.cpp
@@ -171,7 +167,6 @@ set(SOURCES
CSS/Supports.cpp
CSS/SyntaxHighlighter/SyntaxHighlighter.cpp
CSS/Time.cpp
- CSS/TypedOM.cpp
CSS/URL.cpp
CSS/UpdateStyle.cpp
CSS/ValueType.cpp
@@ -703,7 +698,6 @@ set(SOURCES
Painting/DocumentPaintState.cpp
Painting/HitTestQuery.cpp
Painting/HitTestResult.cpp
- Painting/CompositorAnimationEffectState.cpp
Painting/PaintingRustBridge.cpp
Painting/ResizeHandle.cpp
Painting/Scrolling.cpp
diff --git a/Libraries/LibWeb/CSS/CSSAnimation.cpp b/Libraries/LibWeb/CSS/CSSAnimation.cpp
deleted file mode 100644
index 02fdfba2671..00000000000
--- a/Libraries/LibWeb/CSS/CSSAnimation.cpp
+++ /dev/null
@@ -1,213 +0,0 @@
-/*
- * Copyright (c) 2024, Matthew Olsson <[email protected]>.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibGC/Heap.h>
-#include <LibJS/HostClassBuilder.h>
-#include <LibWeb/Animations/AnimationEffect.h>
-#include <LibWeb/Animations/AnimationTimeline.h>
-#include <LibWeb/Animations/NamedTimelines.h>
-#include <LibWeb/Bindings/WrapperWorld.h>
-#include <LibWeb/CSS/CSSAnimation.h>
-#include <LibWeb/CSS/PropertyID.h>
-#include <LibWeb/CSS/PseudoElement.h>
-#include <LibWeb/CSS/StyleValues/StyleValue.h>
-#include <LibWeb/ComputedValuesRustFFI.h>
-#include <LibWeb/DOM/Document.h>
-#include <LibWeb/DOM/Element.h>
-#include <LibWeb/DOM/Event.h>
-#include <LibWeb/HTML/Scripting/Environments.h>
-#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
-
-namespace Web::CSS {
-
-extern "C" {
-
-// Defined in Bindings/Rust/src/css/exports.rs.
-void* web_animation_event_create(JSVM*, void* realm, FlatPtr event_name, FlatPtr name, double elapsed_time, FlatPtr pseudo_element, Animations::RustFFI::AnimationCell const* animation);
-}
-
-GC::Ref<DOM::Event> CSSAnimation::create_event(Animations::AnimationRef const& animation, DOM::Document const& document, Utf16FlyString const& type, double elapsed_time, Utf16String pseudo_element)
-{
- auto& realm = HTML::relevant_realm(document);
- auto* event = web_animation_event_create(JS::HostABI::vm_to_abi(realm.vm()), &realm, type.to_utf16_string().into_raw(), animation_name(animation).to_utf16_string().into_raw(), elapsed_time, move(pseudo_element).into_raw(), &animation.record());
- return GC::Ref { *static_cast<DOM::Event*>(static_cast<GC::Cell*>(event)) };
-}
-
-Animations::AnimationRef CSSAnimation::create(DOM::AbstractElement owner, ComputedValuesFFI::FfiComputedAnimation const& definition, Animations::KeyframeSetHandle keyframe_set, size_t name_index)
-{
- // An animation applies to an element if its name appears as one of the identifiers in the computed value of the
- // animation-name property and the animation uses a valid @keyframes rule
- // FIXME:
- // CSS Animations generated using the markup defined in this specification are not added to the global animation
- // list when they are created. Instead, these animations are appended to the global animation list at the first
- // moment when they transition out of the idle play state after being disassociated from their owning element. CSS
- // Animations that have been disassociated from their owning element but are still idle do not have a defined
- // composite order.
- // NB: Script gets the object of the animation, a CSSAnimation, as it first asks for it.
- auto animation = Animations::AnimationRef::adopt(*Animations::RustFFI::animations_css_animation_create());
- Animations::RustFFI::animations_css_animation_set_name(&animation.record(), css_string_from_rust(definition.name).raw_identity());
- Animations::set_owning_element(animation, owner);
-
- auto effect = Animations::EffectRef::create_keyframe_effect();
- Animations::RustFFI::animations_animation_set_effect(&animation.record(), &effect.record(), true, Animations::perform_host_effect);
-
- apply_css_properties(animation, definition, owner);
- set_animation_name_index(animation, name_index);
-
- effect.set_keyframe_set(move(keyframe_set));
-
- effect.set_target(owner);
- return animation;
-}
-
-Utf16FlyString CSSAnimation::animation_name(Animations::AnimationRef const& animation)
-{
- auto raw = Animations::RustFFI::animations_css_animation_state(&animation.record()).name;
- return raw ? Utf16FlyString::from_raw(raw) : Utf16FlyString {};
-}
-
-void CSSAnimation::set_animation_name_index(Animations::AnimationRef const& animation, size_t index)
-{
- if (!Animations::RustFFI::animations_css_animation_set_name_index(&animation.record(), static_cast<u32>(index)))
- return;
- if (auto effect = animation.effect(); effect.has_value()) {
- if (auto* target = effect->target())
- target->invalidate_associated_animation_composite_order();
- }
-}
-
-using TimelineKind = ComputedValuesFFI::FfiAnimationTimelineKind;
-
-static Animations::ScrollAxis requested_axis(ComputedValuesFFI::FfiComputedAnimation const& definition)
-{
- return Animations::scroll_axis_from_css_axis(static_cast<Axis>(definition.scroll_axis));
-}
-
-static Animations::AnimationTimeline::AnonymousScrollSource anonymous_scroll_source(ComputedValuesFFI::FfiComputedAnimation const& definition, DOM::AbstractElement target)
-{
- return Animations::AnimationTimeline::AnonymousScrollSource {
- .scroller = static_cast<Scroller>(definition.scroll_scroller),
- .target = target,
- };
-}
-
-static Utf16FlyString timeline_name(ComputedValuesFFI::FfiComputedAnimation const& definition)
-{
- return definition.timeline_name ? css_string_from_rust(definition.timeline_name) : Utf16FlyString {};
-}
-
-// NB: Unrelated style changes shouldn't cause us to recreate anonymous timelines, to achieve this we drop updates
-// between two equivalent anonymous timelines. The comparison is made against the description of the requested
-// timeline, so that the timeline a definition names is only ever created when it will replace the one the
-// animation already has.
-static bool should_update_timeline(GC::Ptr<Animations::AnimationTimeline> old_timeline, ComputedValuesFFI::FfiComputedAnimation const& definition, DOM::AbstractElement target)
-{
- switch (definition.timeline_kind) {
- case TimelineKind::None:
- return old_timeline != nullptr;
- case TimelineKind::Document: {
- GC::Ptr<Animations::AnimationTimeline> const document_timeline = target.document().timeline();
- return old_timeline != document_timeline;
- }
- case TimelineKind::Named:
- return old_timeline != target.document().named_timelines().target_timeline(target, timeline_name(definition));
- case TimelineKind::View: {
- return !old_timeline
- || !old_timeline->is_view_timeline()
- || old_timeline->view_subject() != target
- || old_timeline->axis() != requested_axis(definition)
- || old_timeline->view_inset() != Animations::view_timeline_inset_from_ffi(definition.view_inset);
- }
- case TimelineKind::Scroll:
- break;
- }
-
- if (!old_timeline || !old_timeline->is_scroll_timeline() || old_timeline->is_view_timeline())
- return true;
-
- if (old_timeline->axis() != requested_axis(definition))
- return true;
-
- auto old_source = old_timeline->scroll_source();
- if (!old_source.has<Animations::AnimationTimeline::AnonymousScrollSource>())
- return true;
-
- return old_source.get<Animations::AnimationTimeline::AnonymousScrollSource>() != anonymous_scroll_source(definition, target);
-}
-
-static GC::Ptr<Animations::AnimationTimeline> materialize_timeline(ComputedValuesFFI::FfiComputedAnimation const& definition, DOM::AbstractElement target)
-{
- switch (definition.timeline_kind) {
- case TimelineKind::Document:
- return target.document().timeline();
- case TimelineKind::None:
- return {};
- case TimelineKind::Scroll:
- return Animations::AnimationTimeline::create_scroll_timeline(target.document(), anonymous_scroll_source(definition, target), requested_axis(definition));
- case TimelineKind::View:
- return Animations::AnimationTimeline::create_view_timeline(target.document(), target, requested_axis(definition), Animations::view_timeline_inset_from_ffi(definition.view_inset));
- case TimelineKind::Named:
- return target.document().named_timelines().target_timeline(target, timeline_name(definition));
- }
- VERIFY_NOT_REACHED();
-}
-
-void CSSAnimation::apply_css_properties(Animations::AnimationRef const& animation, ComputedValuesFFI::FfiComputedAnimation const& definition, DOM::AbstractElement timeline_target)
-{
- // FIXME: Don't apply overridden properties as defined here: https://drafts.csswg.org/css-animations-2/#animations
-
- VERIFY(animation.effect().has_value());
-
- // NB: Recorded before the early return below, so that the definition always says what the style
- // computation last computed.
- // NB: An animation that names its timeline looks it up again from its owning element as the timelines its
- // document declares change, also while the name finds no timeline. The record notes the name it follows.
- auto const follows_named_timeline = definition.timeline_kind == TimelineKind::Named;
- auto const applies_the_same_properties = Animations::RustFFI::animations_css_animation_apply_definition(&animation.record(), &definition, follows_named_timeline ? timeline_name(definition).raw_identity() : 0);
-
- GC::Ptr<Animations::AnimationTimeline> timeline = static_cast<Animations::AnimationTimeline*>(Animations::RustFFI::animations_animation_timeline(&animation.record()));
- auto const update_timeline = !has_flag(animation, Flag::ScriptSetTimeline)
- && should_update_timeline(timeline, definition, timeline_target);
- if (follows_named_timeline)
- timeline_target.document().named_timelines().track_animation(animation);
-
- // NB: Style feedback can recompute an animation's owning element. Reapplying unchanged
- // properties would invalidate the effect and turn that feedback into an endless cycle.
- if (!update_timeline && applies_the_same_properties)
- return;
-
- HTML::TemporaryExecutionContext context(HTML::relevant_realm(Animations::relevant_global_object_of(animation)));
- if (update_timeline) {
- auto new_timeline = materialize_timeline(definition, timeline_target);
- Animations::RustFFI::animations_animation_set_timeline(&animation.record(), new_timeline ? &new_timeline->record() : nullptr, Animations::perform_host_effect);
- }
- Animations::RustFFI::animations_css_animation_apply_properties(&animation.record(), &definition, Animations::perform_host_effect);
-}
-
-bool CSSAnimation::has_flag(Animations::AnimationRef const& animation, Flag flag)
-{
- return Animations::RustFFI::animations_css_animation_has_flag(&animation.record(), flag);
-}
-
-bool CSSAnimation::update_named_timeline(Animations::AnimationRef const& animation)
-{
- auto state = Animations::RustFFI::animations_css_animation_state(&animation.record());
- if (!state.named_timeline || has_flag(animation, Flag::ScriptSetTimeline))
- return false;
- // NB: The owning element of a CSS animation is the element whose style names the timeline, which the animation
- // keeps alive.
- auto owner = Animations::RustFFI::animations_animation_owning_element(&animation.record());
- VERIFY(owner.element);
- DOM::AbstractElement target { *static_cast<DOM::Element*>(owner.element), owner.has_pseudo_element ? static_cast<PseudoElement>(owner.pseudo_element) : Optional<PseudoElement> {} };
- GC::Ptr<Animations::AnimationTimeline> timeline = target.document().named_timelines().target_timeline(target, Utf16FlyString::from_raw(state.named_timeline));
- if (timeline.ptr() == static_cast<Animations::AnimationTimeline*>(Animations::RustFFI::animations_animation_timeline(&animation.record())))
- return false;
- HTML::TemporaryExecutionContext context { HTML::relevant_realm(Animations::relevant_global_object_of(animation)) };
- Animations::RustFFI::animations_animation_set_timeline(&animation.record(), timeline ? &timeline->record() : nullptr, Animations::perform_host_effect);
- return true;
-}
-
-}
diff --git a/Libraries/LibWeb/CSS/CSSAnimation.h b/Libraries/LibWeb/CSS/CSSAnimation.h
deleted file mode 100644
index 40d49045016..00000000000
--- a/Libraries/LibWeb/CSS/CSSAnimation.h
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * Copyright (c) 2024, Matthew Olsson <[email protected]>.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/Animations/AnimationEffect.h>
-#include <LibWeb/Animations/RecordHandles.h>
-
-namespace Web::CSS::ComputedValuesFFI {
-
-struct FfiComputedAnimation;
-
-}
-
-namespace Web::CSS {
-
-// https://www.w3.org/TR/css-animations-2/#cssanimation
-// What the style engine does with the records of CSS animations, whose objects Bindings/Rust/src/css implements.
-class CSSAnimation {
-public:
- // A new AnimationEvent for `animation`, a CSS animation, that bubbles, which is implemented in Rust.
- static GC::Ref<DOM::Event> create_event(Animations::AnimationRef const& animation, DOM::Document const&, Utf16FlyString const& type, double elapsed_time, Utf16String pseudo_element);
-
- // https://drafts.csswg.org/css-animations-1/#animations
- // Creates the CSS animation `owner` runs for the definition a style computation computed, `definition`, at
- // position `name_index` of its animation-name, running `keyframe_set`.
- static Animations::AnimationRef create(DOM::AbstractElement owner, ComputedValuesFFI::FfiComputedAnimation const& definition, Animations::KeyframeSetHandle keyframe_set, size_t name_index);
-
- static Utf16FlyString animation_name(Animations::AnimationRef const&);
-
- // Applies the definition a style computation computed, `definition`, to the CSS animation `animation`, whose
- // keyframes the caller gives its effect.
- static void apply_css_properties(Animations::AnimationRef const& animation, ComputedValuesFFI::FfiComputedAnimation const& definition, DOM::AbstractElement timeline_target);
-
- static void set_animation_name_index(Animations::AnimationRef const&, size_t index);
-
- // Looks the named timeline the CSS animation follows up again from its owning element, answering whether that
- // changed its timeline.
- static bool update_named_timeline(Animations::AnimationRef const&);
-
-private:
- using Flag = Animations::RustFFI::CssAnimationFlag;
- static bool has_flag(Animations::AnimationRef const&, Flag);
-};
-
-}
diff --git a/Libraries/LibWeb/CSS/CSSKeywordValue.h b/Libraries/LibWeb/CSS/CSSKeywordValue.h
deleted file mode 100644
index 3d2dd103732..00000000000
--- a/Libraries/LibWeb/CSS/CSSKeywordValue.h
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * Copyright (c) 2025, Sam Atkins <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/Utf16String.h>
-#include <LibWeb/Bindings/CSSKeywordValue.h>
-#include <LibWeb/CSS/CSSStyleValue.h>
-
-namespace Web::CSS {
-
-// https://drafts.css-houdini.org/css-typed-om-1/#csskeywordvalue
-class WEB_API CSSKeywordValue final : public CSSStyleValue {
- WEB_RUST_INTERFACE(CSSKeywordValue, css_keyword_value)
-
-public:
- Utf16String value() const;
-};
-
-}
diff --git a/Libraries/LibWeb/CSS/CSSNumericValue.h b/Libraries/LibWeb/CSS/CSSNumericValue.h
deleted file mode 100644
index 47e094e0d0f..00000000000
--- a/Libraries/LibWeb/CSS/CSSNumericValue.h
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * Copyright (c) 2025, Sam Atkins <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/Utf16String.h>
-#include <LibWeb/Bindings/CSSNumericValue.h>
-#include <LibWeb/CSS/CSSStyleValue.h>
-#include <LibWeb/CSS/NumericType.h>
-#include <LibWeb/CSS/StyleValues/CalcNodeRef.h>
-
-namespace Web::CSS {
-
-// https://drafts.css-houdini.org/css-typed-om-1/#cssnumericvalue
-class WEB_API CSSNumericValue : public CSSStyleValue {
- WEB_RUST_INTERFACE(CSSNumericValue, css_numeric_value)
-
-public:
- // A new CSSMathSum of the values, whose types can be added.
- static GC::Ref<CSSNumericValue> create_sum(GC::Ref<CSSNumericValue>, GC::Ref<CSSNumericValue>);
-
- // https://drafts.css-houdini.org/css-typed-om-1/#cssnumericvalue-type
- NumericType type() const;
-
- // https://drafts.css-houdini.org/css-typed-om-1/#numeric-value-serialization
- Utf16String to_string() const;
-
- Optional<CalcNodeRef> create_calculation_node() const;
-};
-
-}
diff --git a/Libraries/LibWeb/CSS/CSSStyleValue.h b/Libraries/LibWeb/CSS/CSSStyleValue.h
deleted file mode 100644
index ea83fca732b..00000000000
--- a/Libraries/LibWeb/CSS/CSSStyleValue.h
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * Copyright (c) 2025, Sam Atkins <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/NonnullRefPtr.h>
-#include <AK/Optional.h>
-#include <AK/Utf16FlyString.h>
-#include <AK/Utf16View.h>
-#include <LibGC/Ptr.h>
-#include <LibWeb/Bindings/CSSStyleValue.h>
-#include <LibWeb/Bindings/RustInterface.h>
-#include <LibWeb/CSS/SerializationMode.h>
-#include <LibWeb/Export.h>
-#include <LibWeb/Forward.h>
-
-namespace Web::CSS {
-
-// https://drafts.css-houdini.org/css-typed-om-1/#cssstylevalue
-// The C++ side of the CSS Typed OM, which is implemented in Rust (Libraries/LibWeb/Bindings/Rust/src/css): what C++
-// creates and reads.
-class WEB_API CSSStyleValue : public Bindings::RustInterfaceCell {
- WEB_RUST_INTERFACE(CSSStyleValue, css_style_value)
-
-public:
- static GC::Ref<CSSStyleValue> create(Utf16FlyString associated_property, StyleValue const&, SerializationMode = SerializationMode::Normal);
-
- // https://drafts.css-houdini.org/css-typed-om-1/#reify-stylevalue
- static GC::Ref<CSSStyleValue> reify(StyleValue const&, Utf16FlyString const& associated_property);
-
- Optional<Utf16FlyString> associated_property() const;
-
- template<typename T>
- bool fast_is() const
- requires(IsSame<T, CSSNumericValue> || IsSame<T, CSSUnitValue>)
- {
- if constexpr (IsSame<T, CSSNumericValue>)
- return is_numeric_value();
- else
- return is_unit_value();
- }
-
-private:
- bool is_numeric_value() const;
- bool is_unit_value() const;
-};
-
-}
diff --git a/Libraries/LibWeb/CSS/CSSTransition.cpp b/Libraries/LibWeb/CSS/CSSTransition.cpp
deleted file mode 100644
index 1ac9508e3f2..00000000000
--- a/Libraries/LibWeb/CSS/CSSTransition.cpp
+++ /dev/null
@@ -1,229 +0,0 @@
-/*
- * Copyright (c) 2024, Matthew Olsson <[email protected]>
- * Copyright (c) 2024, Sam Atkins <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibGC/Heap.h>
-#include <LibJS/HostClassBuilder.h>
-#include <LibWeb/Animations/AnimationTimeline.h>
-#include <LibWeb/CSS/CSSStyleDeclaration.h>
-#include <LibWeb/CSS/CSSTransition.h>
-#include <LibWeb/CSS/PropertyID.h>
-#include <LibWeb/CSS/StyleComputer.h>
-#include <LibWeb/DOM/Document.h>
-#include <LibWeb/DOM/Element.h>
-#include <LibWeb/DOM/Event.h>
-#include <LibWeb/HTML/Scripting/Environments.h>
-#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
-#include <LibWeb/Layout/NodeArena.h>
-#include <LibWeb/StyleEngineRustFFI.h>
-#include <LibWeb/StyleValueRustFFI.h>
-
-namespace Web::CSS {
-
-extern "C" {
-
-// Defined in Bindings/Rust/src/css/exports.rs.
-void* web_transition_event_create(JSVM*, void* realm, FlatPtr event_name, FlatPtr name, double elapsed_time, FlatPtr pseudo_element, Animations::RustFFI::AnimationCell const* animation);
-}
-
-GC::Ref<DOM::Event> CSSTransition::create_event(Animations::AnimationRef const& transition, DOM::Document const& document, Utf16FlyString const& type, double elapsed_time, Utf16String pseudo_element)
-{
- auto& realm = HTML::relevant_realm(document);
- auto* event = web_transition_event_create(JS::HostABI::vm_to_abi(realm.vm()), &realm, type.to_utf16_string().into_raw(), transition_property_name_and_id(transition).name().to_utf16_string().into_raw(), elapsed_time, move(pseudo_element).into_raw(), &transition.record());
- return GC::Ref { *static_cast<DOM::Event*>(static_cast<GC::Cell*>(event)) };
-}
-
-Animations::AnimationRef CSSTransition::start_a_provisional_transition(
- DOM::AbstractElement abstract_element,
- PropertyNameAndID property,
- size_t transition_generation,
- double delay,
- double start_time,
- double end_time,
- NonnullRefPtr<StyleValue const> start_value,
- NonnullRefPtr<StyleValue const> end_value,
- NonnullRefPtr<StyleValue const> reversing_adjusted_start_value,
- double reversing_shortening_factor,
- EasingFunction timing_function)
-{
- Animations::RustFFI::FfiCssTransition description {
- .generation = transition_generation,
- .start_time = start_time + delay,
- .end_time = end_time + delay,
- .reversing_shortening_factor = reversing_shortening_factor,
- .custom_name = property.is_custom_property() ? property.name().raw_identity() : 0,
- .start_value = start_value->rust_style_value_data(),
- .end_value = end_value->rust_style_value_data(),
- .reversing_adjusted_start_value = reversing_adjusted_start_value->rust_style_value_data(),
- .property_id = to_underlying(property.id()),
- };
- // NB: Script gets the object of the transition, a CSSTransition, as it first asks for it.
- auto transition = Animations::AnimationRef::adopt(*Animations::RustFFI::animations_css_transition_create(&description));
-
- // FIXME:
- // Transitions generated using the markup defined in this specification are not added to the global animation list
- // when they are created. Instead, these animations are appended to the global animation list at the first moment
- // when they transition out of the idle play state after being disassociated from their owning element. Transitions
- // that have been disassociated from their owning element but are still idle do not have a defined composite order.
-
- // Construct a KeyframesEffect for our animation
- // NB: The current style computation collects this effect before publishing its result, so scheduling a second
- // animated style update here would evaluate the same transition twice. The record keeps the effect the
- // transition is started with.
- auto keyframe_effect_record = Animations::EffectRef::create_keyframe_effect();
- keyframe_effect_record.set_target(abstract_element, Animations::EffectRef::InvalidateEffect::No);
- keyframe_effect_record.set_keyframe_set(Animations::KeyframeSetHandle::adopt(Animations::RustFFI::animations_keyframe_set_for_transition(
- to_underlying(property.id()),
- property.is_custom_property() ? property.name().raw_identity() : 0,
- start_value->rust_style_value_data(),
- end_value->rust_style_value_data(),
- static_cast<float>(abstract_element.computed_style()->effective_zoom()))));
- Animations::set_owning_element(transition, abstract_element);
- auto* timeline = abstract_element.document().timeline().ptr();
- Animations::RustFFI::animations_animation_set_timeline(&transition.record(), timeline ? &timeline->record() : nullptr, Animations::perform_host_effect);
-
- // NB: The record sets the timing of the effect, sets it as the transition's associated effect and plays the
- // transition, which creates its ready promise.
- Utf16FlyString timing_function_serialization { timing_function.to_utf16_string() };
- Animations::RustFFI::FfiProvisionalTransitionTiming timing {
- .delay = delay,
- .duration = end_time - start_time,
- .timing_function = timing_function.descriptor(),
- .timing_function_serialization = timing_function_serialization.raw_identity(),
- };
- HTML::TemporaryExecutionContext context(abstract_element.document().relevant_settings_object());
- Animations::RustFFI::animations_css_transition_start_provisionally(&transition.record(), &keyframe_effect_record.record(), &timing, Animations::perform_host_effect);
- return transition;
-}
-
-PropertyNameAndID CSSTransition::transition_property_name_and_id(Animations::AnimationRef const& transition)
-{
- auto state = Animations::RustFFI::animations_css_transition(&transition.record());
- if (state.custom_name)
- return PropertyNameAndID::from_name(Utf16FlyString::from_raw(state.custom_name)).release_value();
- return PropertyNameAndID::from_id(static_cast<PropertyID>(state.property_id));
-}
-
-NonnullRefPtr<StyleValue const> CSSTransition::transition_start_value(Animations::AnimationRef const& transition)
-{
- auto state = Animations::RustFFI::animations_css_transition(&transition.record());
- return StyleValue::adopt_rust_style_value_data(StyleValueFFI::rust_style_value_retain(static_cast<StyleValueFFI::StyleValueData const*>(state.start_value)));
-}
-
-void CSSTransition::commit_provisional_transition(Animations::AnimationRef const& transition, Animations::RustFFI::TransitionOrigin origin)
-{
- // NB: The associated effect of a provisional transition is the effect it was started with.
- auto effect = transition.effect();
- VERIFY(effect.has_value());
- auto* target = effect->target();
- VERIFY(target);
- auto owner = Animations::RustFFI::animations_animation_owning_element(&transition.record());
- VERIFY(owner.element);
- Optional<PseudoElement> pseudo_element;
- if (owner.has_pseudo_element)
- pseudo_element = static_cast<PseudoElement>(owner.pseudo_element);
- target->commit_provisional_transition(pseudo_element, transition, origin);
-}
-
-void CSSTransition::discard_provisional_transition(Animations::AnimationRef const& transition)
-{
- Animations::RustFFI::animations_animation_set_timeline(&transition.record(), nullptr, Animations::perform_host_effect);
- // NB: The record lets the transition have no associated effect.
- Animations::RustFFI::animations_css_transition_discard_provisional(&transition.record());
-}
-
-void CSSTransition::adopt_lane_transitions(DOM::Document& document)
-{
- auto* arena = document.layout_node_arena_if_created();
- if (!arena)
- return;
- auto& style_computer = document.style_computer();
- auto adopt_value = [](StyleValueFFI::StyleValueData const* value) {
- return StyleValue::adopt_rust_style_value_data(StyleValueFFI::rust_style_value_retain(value));
- };
- auto adopt = [&](u32 style_node, ReadonlySpan<u64> cancelled, ReadonlySpan<u64> seen, ReadonlySpan<StyleValueFFI::FfiLaneTransition> lane_transitions) {
- auto element = style_computer.element_for_lane_style_node(StyleNodeID { style_node });
- if (!element || !element->is_connected())
- return;
- // A transition the lane started that the host took in already runs from when the lane started it.
- auto runs_as_lane_does = [&](Animations::AnimationRef const& transition) {
- return Animations::RustFFI::animations_css_transition_runs_as_lane_does(&transition.record(), lane_transitions);
- };
- // NB: The record of each running transition decides what becomes of it (see LaneAdoption). One the steps saw
- // end by itself ends as it does, with its events, and so does one script finished meanwhile.
- GC::RootVector<Animations::AnimationRef> ended;
- Vector<PropertyNameAndID> host_decides;
- for (auto const& transition : element->existing_transitions({})) {
- auto timing = transition.timing_state();
- if (timing.play_state == Animations::RustFFI::AnimationPlayState::Idle || timing.playback.is_finished)
- continue;
- switch (Animations::RustFFI::animations_css_transition_lane_adoption(&transition.record(), lane_transitions, cancelled, seen)) {
- case Animations::RustFFI::LaneAdoption::Stands:
- break;
- case Animations::RustFFI::LaneAdoption::Ends:
- ended.append(transition);
- break;
- case Animations::RustFFI::LaneAdoption::HostDecides:
- host_decides.append(transition_property_name_and_id(transition));
- break;
- }
- }
- for (auto const& transition : ended) {
- transition.cancel();
- element->remove_transition({}, transition_property_name_and_id(transition));
- }
- // NB: The start time of a transition is a time of the document timeline, which validating it as script sets
- // it would only read as milliseconds.
- auto set_start_time = [](Animations::AnimationRef const& transition, double start_time) {
- Animations::RustFFI::animations_animation_set_start_time(&transition.record(), Animations::to_ffi(Optional<Animations::TimeValue> { Animations::TimeValue { Animations::TimeValue::Type::Milliseconds, start_time } }), Animations::perform_host_effect);
- };
- // A transition of the host's whose play is still pending runs from when the lane took it to start.
- for (auto const& lane_transition : lane_transitions) {
- if (lane_transition.host_identity == 0)
- continue;
- auto transition = element->property_transition({}, PropertyNameAndID::from_id(static_cast<PropertyID>(lane_transition.property_id)));
- if (!transition.has_value() || !Animations::RustFFI::animations_css_transition_is_host_transition_of(&transition->record(), &lane_transition))
- continue;
- auto timing = transition->timing_state();
- if (!timing.playback.start_time.has_value && (timing.playback.has_pending_play_task || timing.playback.has_pending_pause_task)
- && timing.play_state != Animations::RustFFI::AnimationPlayState::Paused)
- set_start_time(*transition, lane_transition.start_time);
- }
- for (auto const& lane_transition : lane_transitions) {
- if (lane_transition.host_identity != 0)
- continue;
- auto property = PropertyNameAndID::from_id(static_cast<PropertyID>(lane_transition.property_id));
- if (host_decides.contains_slow(property))
- continue;
- if (auto current = element->property_transition({}, property); current.has_value()) {
- if (runs_as_lane_does(*current))
- continue;
- // A completed transition of the property gives way to the one the lane started. One the lane saw end,
- // which the host's timeline has yet to reach, ends now.
- auto timing = current->timing_state();
- if (timing.play_state != Animations::RustFFI::AnimationPlayState::Idle && !timing.playback.is_finished)
- (void)Animations::RustFFI::animations_animation_finish(&current->record(), Animations::perform_host_effect);
- element->remove_transition({}, property);
- }
- auto transition = start_a_provisional_transition(*element, property, document.transition_generation(),
- lane_transition.delay, lane_transition.start_time, lane_transition.start_time + lane_transition.duration,
- adopt_value(lane_transition.start_value), adopt_value(lane_transition.end_value), adopt_value(lane_transition.reversing_adjusted_start_value),
- lane_transition.reversing_shortening_factor, EasingFunction::from_style_value(adopt_value(lane_transition.timing_function)));
- commit_provisional_transition(transition, Animations::RustFFI::TransitionOrigin::Lane);
- set_start_time(transition, lane_transition.start_time);
- }
- };
- // Starting and cancelling transitions settles their promises in the document's realm. The rendering update runs
- // their reactions once every document took in what its lanes did.
- HTML::TemporaryExecutionContext execution_context { document.relevant_settings_object() };
- StyleEngineFFI::style_engine_adopt_lane_transitions(
- arena->host(), &adopt,
- [](void* context, u32 style_node, u64 const* cancelled, size_t cancelled_count, u64 const* seen, size_t seen_count, StyleValueFFI::FfiLaneTransition const* transitions, size_t transition_count) {
- (*static_cast<decltype(adopt)*>(context))(style_node, { cancelled, cancelled_count }, { seen, seen_count }, { transitions, transition_count });
- });
-}
-
-}
diff --git a/Libraries/LibWeb/CSS/CSSTransition.h b/Libraries/LibWeb/CSS/CSSTransition.h
deleted file mode 100644
index c5b198bf639..00000000000
--- a/Libraries/LibWeb/CSS/CSSTransition.h
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * Copyright (c) 2024, Matthew Olsson <[email protected]>
- * Copyright (c) 2024, Sam Atkins <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/Animations/RecordHandles.h>
-#include <LibWeb/CSS/EasingFunction.h>
-#include <LibWeb/CSS/PropertyNameAndID.h>
-#include <LibWeb/CSS/StyleValues/StyleValue.h>
-
-namespace Web::CSS {
-
-// What the style engine does with the records of CSS transitions, whose objects Bindings/Rust/src/css implements.
-class CSSTransition {
-public:
- // A new TransitionEvent for `transition`, a CSS transition, that bubbles, which is implemented in Rust.
- static GC::Ref<DOM::Event> create_event(Animations::AnimationRef const& transition, DOM::Document const&, Utf16FlyString const& type, double elapsed_time, Utf16String pseudo_element);
-
- // A transition is started provisionally, and associated with its target only once committed.
- static Animations::AnimationRef start_a_provisional_transition(
- DOM::AbstractElement,
- PropertyNameAndID,
- size_t transition_generation,
- double delay,
- double start_time,
- double end_time,
- NonnullRefPtr<StyleValue const> start_value,
- NonnullRefPtr<StyleValue const> end_value,
- NonnullRefPtr<StyleValue const> reversing_adjusted_start_value,
- double reversing_shortening_factor,
- EasingFunction timing_function);
-
- static void commit_provisional_transition(Animations::AnimationRef const&, Animations::RustFFI::TransitionOrigin = Animations::RustFFI::TransitionOrigin::StyleChange);
- static void discard_provisional_transition(Animations::AnimationRef const&);
-
- // AD-HOC: Runs the transitions the hover of the document's clock lane left elements running beside a task, which
- // the screen showed, in place of those its steps ended, as the rendering update that takes them in begins.
- static void adopt_lane_transitions(DOM::Document&);
-
- static PropertyNameAndID transition_property_name_and_id(Animations::AnimationRef const&);
-
- static NonnullRefPtr<StyleValue const> transition_start_value(Animations::AnimationRef const&);
-};
-
-}
diff --git a/Libraries/LibWeb/CSS/CSSUnitValue.h b/Libraries/LibWeb/CSS/CSSUnitValue.h
deleted file mode 100644
index 0d735671adc..00000000000
--- a/Libraries/LibWeb/CSS/CSSUnitValue.h
+++ /dev/null
@@ -1,25 +0,0 @@
-/*
- * Copyright (c) 2025, Sam Atkins <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/Bindings/CSSUnitValue.h>
-#include <LibWeb/CSS/CSSNumericValue.h>
-
-namespace Web::CSS {
-
-// https://drafts.css-houdini.org/css-typed-om-1/#cssunitvalue
-class WEB_API CSSUnitValue final : public CSSNumericValue {
- WEB_RUST_INTERFACE(CSSUnitValue, css_unit_value)
-
-public:
- static GC::Ref<CSSUnitValue> create(double value, Utf16FlyString const& unit);
-
- double value() const;
- Utf16FlyString unit() const;
-};
-
-}
diff --git a/Libraries/LibWeb/CSS/DevToolsAppliedStyleRules.cpp b/Libraries/LibWeb/CSS/DevToolsAppliedStyleRules.cpp
index f7b7afb0048..6fcc08b959e 100644
--- a/Libraries/LibWeb/CSS/DevToolsAppliedStyleRules.cpp
+++ b/Libraries/LibWeb/CSS/DevToolsAppliedStyleRules.cpp
@@ -24,14 +24,11 @@
#include <LibGC/Heap.h>
#include <LibGfx/Font/FontDatabase.h>
#include <LibWeb/Animations/AnimationEffect.h>
-#include <LibWeb/Animations/AnimationTimeline.h>
#include <LibWeb/Bindings/PrincipalHostDefined.h>
-#include <LibWeb/CSS/CSSAnimation.h>
#include <LibWeb/CSS/CSSImportRule.h>
#include <LibWeb/CSS/CSSNestedDeclarations.h>
#include <LibWeb/CSS/CSSStyleProperties.h>
#include <LibWeb/CSS/CSSStyleRule.h>
-#include <LibWeb/CSS/CSSTransition.h>
#include <LibWeb/CSS/ComputedStyleWorkingSet.h>
#include <LibWeb/CSS/ContainerQuery.h>
#include <LibWeb/CSS/CustomPropertyData.h>
diff --git a/Libraries/LibWeb/CSS/EasingFunction.h b/Libraries/LibWeb/CSS/EasingFunction.h
index 1f089ed2eaf..ea05203e1da 100644
--- a/Libraries/LibWeb/CSS/EasingFunction.h
+++ b/Libraries/LibWeb/CSS/EasingFunction.h
@@ -32,16 +32,6 @@ public:
return descriptor;
}
- // The descriptor reads its control points from a copy in storage the caller keeps alive.
- Descriptor descriptor_with_points_in(Vector<LinearPoint>& storage) const
- {
- storage.extend(m_linear_points);
- auto descriptor = m_descriptor;
- descriptor.linear_points = storage.data();
- descriptor.linear_point_count = storage.size();
- return descriptor;
- }
-
Utf16String const& to_utf16_string() const { return m_text; }
// NB: The serialization is of the value the function was made from, so it tells functions apart.
diff --git a/Libraries/LibWeb/CSS/NumericType.cpp b/Libraries/LibWeb/CSS/NumericType.cpp
index f246e8e46ba..97ae9fbdd11 100644
--- a/Libraries/LibWeb/CSS/NumericType.cpp
+++ b/Libraries/LibWeb/CSS/NumericType.cpp
@@ -10,29 +10,6 @@
namespace Web::CSS {
-Optional<NumericType::BaseType> NumericType::base_type_from_value_type(ValueType value_type)
-{
- switch (value_type) {
- case ValueType::Angle:
- return BaseType::Angle;
- case ValueType::Flex:
- return BaseType::Flex;
- case ValueType::Frequency:
- return BaseType::Frequency;
- case ValueType::Length:
- return BaseType::Length;
- case ValueType::Percentage:
- return BaseType::Percent;
- case ValueType::Resolution:
- return BaseType::Resolution;
- case ValueType::Time:
- return BaseType::Time;
-
- default:
- return {};
- }
-}
-
static StyleValueFFI::FfiNumericType to_ffi_numeric_type(NumericType const& type)
{
StyleValueFFI::FfiNumericType result {};
@@ -48,20 +25,6 @@ static StyleValueFFI::FfiNumericType to_ffi_numeric_type(NumericType const& type
return result;
}
-Optional<NumericType> NumericType::from_ffi(StyleValueFFI::FfiNumericType const& type)
-{
- if (!type.valid)
- return {};
- NumericType result;
- for (auto i = 0; i < to_underlying(NumericType::BaseType::__Count); ++i) {
- if (type.has_exponent_bits & (1u << i))
- result.set_exponent(static_cast<NumericType::BaseType>(i), type.exponents[i]);
- }
- if (type.has_percent_hint)
- result.set_percent_hint(static_cast<NumericType::BaseType>(type.percent_hint));
- return result;
-}
-
static bool matches(StyleValueFFI::FfiNumericTypeMatch match_kind, NumericType const& type, NumericType::BaseType base_type, Optional<ValueType> percentages_resolve_as)
{
auto ffi_type = to_ffi_numeric_type(type);
diff --git a/Libraries/LibWeb/CSS/NumericType.h b/Libraries/LibWeb/CSS/NumericType.h
index 979ae770044..2caaf4f174b 100644
--- a/Libraries/LibWeb/CSS/NumericType.h
+++ b/Libraries/LibWeb/CSS/NumericType.h
@@ -25,8 +25,6 @@ namespace Web::CSS {
// https://drafts.css-houdini.org/css-typed-om-1/#cssnumericvalue-type
class WEB_API NumericType {
public:
- static Optional<NumericType> from_ffi(StyleValueFFI::FfiNumericType const&);
-
enum class BaseType {
Length,
Angle,
@@ -38,7 +36,6 @@ public:
__Count,
};
- static Optional<BaseType> base_type_from_value_type(ValueType);
NumericType() = default;
NumericType(BaseType type, i32 power)
{
@@ -53,7 +50,6 @@ public:
bool matches_number(Optional<ValueType> percentages_resolve_as) const;
bool matches_percentage() const;
bool matches_resolution(Optional<ValueType> percentages_resolve_as) const { return matches_dimension(BaseType::Resolution, percentages_resolve_as); }
- bool matches_time(Optional<ValueType> percentages_resolve_as) const { return matches_dimension(BaseType::Time, percentages_resolve_as); }
Optional<i32> const& exponent(BaseType type) const { return m_type_exponents[to_underlying(type)]; }
void set_exponent(BaseType type, i32 exponent) { m_type_exponents[to_underlying(type)] = exponent; }
diff --git a/Libraries/LibWeb/CSS/StyleComputer.cpp b/Libraries/LibWeb/CSS/StyleComputer.cpp
index 8dc81121d0b..6b77e60a466 100644
--- a/Libraries/LibWeb/CSS/StyleComputer.cpp
+++ b/Libraries/LibWeb/CSS/StyleComputer.cpp
@@ -27,14 +27,13 @@
#include <LibGC/Heap.h>
#include <LibGfx/Font/FontDatabase.h>
#include <LibWeb/Animations/AnimationEffect.h>
-#include <LibWeb/Animations/AnimationTimeline.h>
+#include <LibWeb/Animations/NamedTimelines.h>
+#include <LibWeb/Animations/RecordHandles.h>
#include <LibWeb/Bindings/PrincipalHostDefined.h>
-#include <LibWeb/CSS/CSSAnimation.h>
#include <LibWeb/CSS/CSSImportRule.h>
#include <LibWeb/CSS/CSSNestedDeclarations.h>
#include <LibWeb/CSS/CSSStyleProperties.h>
#include <LibWeb/CSS/CSSStyleRule.h>
-#include <LibWeb/CSS/CSSTransition.h>
#include <LibWeb/CSS/ComputedStyleWorkingSet.h>
#include <LibWeb/CSS/ContainerQuery.h>
#include <LibWeb/CSS/CustomPropertyData.h>
@@ -90,6 +89,7 @@
#include <LibWeb/HTML/HTMLVideoElement.h>
#include <LibWeb/HTML/Parser/HTMLParser.h>
#include <LibWeb/HTML/Scripting/Environments.h>
+#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
#include <LibWeb/Layout/LayoutRustBridge.h>
#include <LibWeb/Layout/Node.h>
#include <LibWeb/MathML/MathMLElement.h>
@@ -345,22 +345,6 @@ void StyleComputer::visit_edges(Visitor& visitor)
if (entry.value)
entry.value->contents().visit_edges(visitor);
}
-
- for (auto const& state : m_provisional_transition_states) {
- visitor.visit(state.element);
- // NB: An AnimationRef visits the Animation of its record, which keeps the elements the record names alive.
- if (state.committed_transition.has_value())
- state.committed_transition->visit_edges(visitor);
- if (state.proposed_transition.has_value())
- state.proposed_transition->visit_edges(visitor);
- }
-}
-
-void StyleComputer::begin_transition_stabilization_epoch()
-{
- VERIFY(m_provisional_transition_states.is_empty());
- VERIFY(m_provisional_transition_state_indices.is_empty());
- VERIFY(m_provisional_transition_state_indices_by_target.is_empty());
}
void StyleComputer::record_transition_stabilization_baseline(DOM::AbstractElement abstract_element, InstalledStyle const& before_change_style) const
@@ -383,70 +367,9 @@ void StyleComputer::record_transition_baseline_for_later_passes(DOM::AbstractEle
record_transition_stabilization_baseline(abstract_element, before_change_style);
}
-// A provisionally started transition already contributed to the style published by the pass that
-// started it, but it is not associated with its target until the stabilization epoch commits. An
-// animated style update running before that commit has to collect it anyway, or it rebuilds the
-// target's style without the transition's value and clobbers it.
-void StyleComputer::for_each_provisional_transition_effect(DOM::AbstractElement const& abstract_element, Function<void(Animations::EffectRef const&)> const& callback) const
-{
- for (auto const& state : m_provisional_transition_states) {
- if (state.element.ptr() != &abstract_element.element() || state.pseudo_element != abstract_element.pseudo_element())
- continue;
- if (!state.proposed_transition.has_value())
- continue;
- if (auto effect = state.proposed_transition->effect(); effect.has_value())
- callback(*effect);
- }
-}
-
void StyleComputer::commit_transition_stabilization_epoch()
{
- for (auto const& state : m_provisional_transition_states) {
- VERIFY(state.element);
- auto& element = *state.element;
- auto remove_committed_transition = [&] {
- if (element.property_transition(state.pseudo_element, state.property) == state.committed_transition)
- element.remove_transition(state.pseudo_element, state.property);
- };
- auto cancel_and_remove_committed_transition = [&] {
- VERIFY(state.committed_transition.has_value());
- state.committed_transition->cancel();
- remove_committed_transition();
- };
- auto commit_proposed_transition = [&] {
- VERIFY(state.proposed_transition.has_value());
- CSSTransition::commit_provisional_transition(*state.proposed_transition);
- HTML::note_rendering_trace_event("transition started"sv);
- };
-
- switch (state.action) {
- using enum StyleValueFFI::FfiTransitionActionKind;
- case None:
- continue;
- case Remove:
- remove_committed_transition();
- break;
- case Cancel:
- VERIFY(state.committed_transition.has_value());
- state.committed_transition->cancel();
- break;
- case Start:
- commit_proposed_transition();
- break;
- case RemoveAndStart:
- remove_committed_transition();
- commit_proposed_transition();
- break;
- case CancelRemoveAndStart:
- cancel_and_remove_committed_transition();
- commit_proposed_transition();
- break;
- }
- HTML::note_rendering_trace_event("transition action committed"sv);
- }
- m_provisional_transition_states.clear();
- m_provisional_transition_state_indices.clear();
- m_provisional_transition_state_indices_by_target.clear();
+ Animations::RustFFI::animations_document_animations_commit_provisional_transitions(&document().document_animations(), Animations::in_execution_context_of_animation, nullptr, Animations::web_animation_perform_host_effect);
if (exchange(m_transition_baselines_recorded, false))
StyleEngineFFI::style_engine_release_transition_baselines(m_style_engine.host());
}
@@ -808,84 +731,61 @@ void StyleComputer::invalidate_animated_custom_property_readers(DOM::AbstractEle
// itself, as the engine learns of the element's new environment.
}
-void StyleComputer::apply_animation_definitions(DOM::AbstractElement& abstract_element, ReadonlySpan<ComputedValuesFFI::FfiComputedAnimation> animation_definitions, bool in_display_none_subtree) const
+// https://drafts.csswg.org/scroll-animations-1/#target-timeline
+static Animations::RustFFI::TimelineCell const* named_timeline_of_owner(void* owner_pointer, size_t name)
{
- // Only the element and its known pseudo-elements have CSS animations to apply.
- if (!Animations::Animatable::can_own_css_animations_and_transitions(abstract_element.pseudo_element()))
- return;
-
- // https://drafts.csswg.org/css-animations-1/#animations
- // Setting the 'display' property to 'none' will terminate any running animation applied to the element and its
- // descendants. If an element has a 'display' of 'none', updating 'display' to a value other than 'none' will
- // start all animations applied to the element by the 'animation-name' property, as well as all animations
- // applied to descendants with 'display' other than 'none'.
- // NB: We must not start animations on elements that are not rendered due to display:none. Once display becomes
- // something other than none, the resulting style recomputation re-enters this function and starts them.
- // Termination of running animations when display becomes none is handled by
- // Element::play_or_cancel_animations_after_display_property_change(). The style computation answers
- // whether the element is in such a subtree from the records the style engine holds.
-
- // NB: Which existing animation each definition claims is decided by the style computation, from the names of
- // the animations this element holds, which it publishes. See match_existing_animations(). So are the
- // keyframes each definition runs, from the `@keyframes` every style scope publishes.
-
- auto existing_animations = abstract_element.element().css_defined_animations(abstract_element.pseudo_element());
- Vector<bool> existing_animation_was_claimed;
- existing_animation_was_claimed.resize(existing_animations.size());
- GC::RootVector<Animations::AnimationRef> new_animations;
-
- for (size_t i = animation_definitions.size(); i-- > 0;) {
- auto const& definition = animation_definitions[i];
- auto keyframe_set = Animations::KeyframeSetHandle::retained(static_cast<Animations::RustFFI::KeyframeSet const*>(definition.keyframe_set));
-
- auto matched_index = definition.matched_existing_index;
- VERIFY(matched_index < static_cast<i32>(existing_animations.size()));
-
- if (matched_index >= 0) {
- auto const& existing_animation = existing_animations[matched_index];
- VERIFY(CSSAnimation::animation_name(existing_animation) == css_string_from_rust(definition.name));
- VERIFY(!existing_animation_was_claimed[matched_index]);
- existing_animation_was_claimed[matched_index] = true;
-
- if (auto effect = existing_animation.effect(); effect.has_value()) {
- effect->set_keyframe_set(keyframe_set);
- CSSAnimation::apply_css_properties(existing_animation, definition, abstract_element);
- }
- CSSAnimation::set_animation_name_index(existing_animation, i);
- new_animations.append(existing_animation);
- continue;
- }
-
- if (in_display_none_subtree)
- continue;
-
- new_animations.append(CSSAnimation::create(abstract_element, definition, keyframe_set, i));
- }
-
- // Once an animation has started it continues until it ends or the animation-name is removed
- // NB: An animation no definition claimed is one whose animation-name entry has gone.
- for (size_t i = 0; i < existing_animations.size(); ++i) {
- if (!existing_animation_was_claimed[i]) {
- existing_animations[i].cancel(false);
- }
- }
+ if (!name)
+ return nullptr;
+ auto& owner = *static_cast<DOM::AbstractElement*>(owner_pointer);
+ auto timeline = owner.document().named_timelines().target_timeline(owner, Utf16FlyString::from_raw(name));
+ return timeline.has_value() ? &timeline->record() : nullptr;
+}
- // NB: We create animations in reverse definition order so flip it back.
- new_animations.reverse();
+// https://drafts.csswg.org/css-animations-1/#animations
+// Applies the animation definitions a style computation computed for `owner`, which is in a display: none subtree where
+// `in_display_none_subtree`, to the CSS animations it owns.
+static void apply_css_animation_definitions(DOM::AbstractElement owner, ReadonlySpan<ComputedValuesFFI::FfiComputedAnimation> definitions, bool in_display_none_subtree)
+{
+ // NB: Only the element and its known pseudo-elements have CSS animations to apply.
+ auto& element = owner.element();
+ auto pseudo_element = owner.pseudo_element();
+ auto slot = Animations::Animatable::owner_slot(pseudo_element);
+ if (!slot.has_value())
+ return;
- abstract_element.element().set_css_defined_animations(abstract_element.pseudo_element(), new_animations);
+ GC::RootVector<Animations::AnimationRef> animations;
+ struct Context {
+ DOM::AbstractElement owner;
+ GC::RootVector<Animations::AnimationRef>& animations;
+ } context { owner, animations };
+ Animations::RustFFI::FfiCssAnimationHost host {
+ .context = &context,
+ .named_timeline = [](void* context, size_t name) { return named_timeline_of_owner(&static_cast<Context*>(context)->owner, name); },
+ .invalidate_composite_order = [](void*, void* element) { static_cast<DOM::Element*>(element)->invalidate_associated_animation_composite_order(); },
+ .keep_alive = [](void* context, Animations::RustFFI::AnimationCell const* animation) { Animations::keep_animation_alive_in(&static_cast<Context*>(context)->animations, animation); },
+ .in_execution_context = Animations::in_execution_context_of_animation,
+ .perform = Animations::web_animation_perform_host_effect,
+ };
+ Optional<Utf16FlyString> pseudo_element_serialization;
+ if (pseudo_element.has_value())
+ pseudo_element_serialization = Utf16FlyString { Selector::PseudoElementSelector { *pseudo_element }.serialize() };
+ Animations::RustFFI::animations_element_animations_apply_css_animation_definitions(
+ &element.ensure_animations(), *slot,
+ {
+ .element = &element,
+ .pseudo_element = pseudo_element.has_value() ? to_underlying(*pseudo_element) : u8 { 0 },
+ .has_pseudo_element = pseudo_element.has_value(),
+ },
+ pseudo_element_serialization.has_value() ? pseudo_element_serialization->raw_identity() : 0,
+ definitions.data(), definitions.size(), in_display_none_subtree,
+ style_engine_host_for_identified(element), element.style_node_id().value(), &host);
}
void StyleComputer::apply_settled_animation_plan(Layout::BegunRead const& read, DOM::AbstractElement& abstract_element) const
{
- struct Context {
- GC::Ref<StyleComputer const> style_computer;
- DOM::AbstractElement& abstract_element;
- } context { *this, abstract_element };
bool has_animations = abstract_element.element().has_css_defined_animations(abstract_element.pseudo_element());
- ComputedValuesFFI::rust_settled_animation_plan(m_style_engine.host(), &read, abstract_element.element().style_node_id().value(), pseudo_element_to_ffi(abstract_element.pseudo_element()), abstract_element.installed_style().record_pointer(), has_animations, &context, [](void* context_pointer, ComputedValuesFFI::FfiComputedAnimation const* definitions, size_t count, bool in_display_none_subtree) {
- auto& context = *static_cast<Context*>(context_pointer);
- context.style_computer->apply_animation_definitions(context.abstract_element, { definitions, count }, in_display_none_subtree);
+ ComputedValuesFFI::rust_settled_animation_plan(m_style_engine.host(), &read, abstract_element.element().style_node_id().value(), pseudo_element_to_ffi(abstract_element.pseudo_element()), abstract_element.installed_style().record_pointer(), has_animations, &abstract_element, [](void* context, ComputedValuesFFI::FfiComputedAnimation const* definitions, size_t count, bool in_display_none_subtree) {
+ apply_css_animation_definitions(*static_cast<DOM::AbstractElement*>(context), { definitions, count }, in_display_none_subtree);
});
}
@@ -1025,12 +925,38 @@ RequiredInvalidationAfterStyleChange StyleComputer::run_transition_step_for_inst
return decode_style_invalidation(publication.invalidation.invalidation);
}
-// The key of the provisional transition states of an element or pseudo-element, whose element has a style node.
-static u64 transition_target_key(DOM::AbstractElement abstract_element)
+void StyleComputer::adopt_lane_transitions()
{
- auto style_node_id = abstract_element.element().style_node_id();
- VERIFY(style_node_id != 0);
- return (static_cast<u64>(style_node_id.value()) << 8) | pseudo_element_to_ffi(abstract_element.pseudo_element());
+ auto* arena = document().layout_node_arena_if_created();
+ if (!arena)
+ return;
+ auto adopt = [&](u32 style_node, ReadonlySpan<u64> cancelled, ReadonlySpan<u64> seen, ReadonlySpan<StyleValueFFI::FfiLaneTransition> lane_transitions) {
+ auto element = element_for_lane_style_node(StyleNodeID { style_node });
+ if (!element || !element->is_connected())
+ return;
+ GC::RootVector<Animations::AnimationRef> transitions;
+ Animations::RustFFI::animations_element_animations_adopt_lane_transitions(
+ &element->ensure_animations(), element.ptr(), cancelled, seen, lane_transitions, document().transition_generation(),
+ static_cast<float>(effective_zoom(*element)), Animations::keep_animation_alive_in, &transitions, Animations::web_animation_perform_host_effect);
+ };
+ // Starting and canceling transitions settles their promises in the document's realm. The rendering update runs
+ // their reactions once every document took in what its lanes did.
+ HTML::TemporaryExecutionContext execution_context { document().relevant_settings_object() };
+ StyleEngineFFI::style_engine_adopt_lane_transitions(
+ arena->host(), &adopt,
+ [](void* context, u32 style_node, u64 const* cancelled, size_t cancelled_count, u64 const* seen, size_t seen_count, StyleValueFFI::FfiLaneTransition const* transitions, size_t transition_count) {
+ (*static_cast<decltype(adopt)*>(context))(style_node, { cancelled, cancelled_count }, { seen, seen_count }, { transitions, transition_count });
+ });
+}
+
+static Animations::RustFFI::FfiOwningElement transition_owner(DOM::AbstractElement abstract_element)
+{
+ auto pseudo_element = abstract_element.pseudo_element();
+ return {
+ .element = &abstract_element.element(),
+ .pseudo_element = pseudo_element.has_value() ? to_underlying(*pseudo_element) : u8 { 0 },
+ .has_pseudo_element = pseudo_element.has_value(),
+ };
}
// https://drafts.csswg.org/css-transitions/#starting
@@ -1040,156 +966,59 @@ RefPtr<ComputedStyleWorkingSet> StyleComputer::start_needed_transitions(Layout::
auto& element = abstract_element.element();
auto pseudo_element = abstract_element.pseudo_element();
- auto target_key = transition_target_key(abstract_element);
// NB: We know that a DocumentTimeline's current time is always in milliseconds
- auto current_time = m_document->timeline()->current_time();
+ auto current_time = m_document->timeline().current_time();
if (!current_time.has_value())
return {};
- VERIFY(current_time->type == Animations::TimeValue::Type::Milliseconds);
- auto style_change_event_time = current_time->value;
-
- Vector<StyleValueFFI::FfiExistingTransition> existing_transitions;
- Vector<NonnullRefPtr<StyleValue const>> custom_current_values;
- // A running transition of a custom property holds it at what the overlay of the target's environment answers. One
- // not sampled yet holds it at its start value.
- auto custom_current_value = [&](Utf16FlyString const& name, Animations::AnimationRef const& transition) -> StyleValueFFI::StyleValueData const* {
- auto value = CSSTransition::transition_start_value(transition);
- if (auto data = abstract_element.custom_property_data(); data && abstract_element.custom_property_data_is_animation_overlay()) {
- if (auto animated = data->get(name); animated.has_value())
- value = *animated->value;
- }
- custom_current_values.append(value);
- return value->rust_style_value_data();
- };
- // NB: The element holds each transition, which lends what is read of it for as long as the element holds it.
- for (auto const& transition : element.existing_transitions(pseudo_element)) {
- StyleValueFFI::FfiExistingTransition existing;
- Animations::RustFFI::animations_css_transition_existing(&transition.record(), style_change_event_time, &existing);
- if (existing.custom_name && existing.running)
- existing.custom_current_value = custom_current_value(Utf16FlyString::from_raw(existing.custom_name), transition);
- existing_transitions.append(existing);
- }
-
- // A transition action is provisional until the stabilization epoch commits; a later pass of the epoch decides
- // again, superseding the decision of this one.
- auto decide = [&](ProvisionalTransitionState& state, StyleValueFFI::FfiTransitionActionKind action) {
- HTML::note_rendering_trace_event("provisional transition decision"sv);
- if (state.has_decision)
- HTML::note_rendering_trace_event("provisional transition decision superseded"sv);
- state.has_decision = true;
- if (state.proposed_transition.has_value())
- CSSTransition::discard_provisional_transition(*state.proposed_transition);
- state.proposed_transition = {};
- state.action = action;
- };
- auto ensure_state = [&](PropertyNameAndID const& property) -> ProvisionalTransitionState& {
- auto create_state = [&] {
- VERIFY(document().is_in_style_stabilization_epoch());
- m_provisional_transition_state_indices_by_target.ensure(target_key).append(m_provisional_transition_states.size());
- m_provisional_transition_states.append({
- .element = element,
- .pseudo_element = pseudo_element,
- .property = property,
- .committed_transition = element.property_transition(pseudo_element, property),
- .proposed_transition = {},
- .action = StyleValueFFI::FfiTransitionActionKind::None,
- .has_decision = false,
- });
- return m_provisional_transition_states.size() - 1;
- };
- if (property.is_custom_property()) {
- auto indices = m_provisional_transition_state_indices_by_target.get(target_key);
- for (auto index : indices.has_value() ? indices->span() : ReadonlySpan<size_t> {}) {
- if (m_provisional_transition_states[index].property == property)
- return m_provisional_transition_states[index];
- }
- return m_provisional_transition_states[create_state()];
- }
- auto index = m_provisional_transition_state_indices.ensure((target_key << 16) | to_underlying(property.id()), create_state);
- return m_provisional_transition_states[index];
- };
- auto property_of_action = [](StyleValueFFI::FfiTransitionAction const& action) {
- if (action.custom_name != 0)
- return PropertyNameAndID::from_name(Utf16FlyString::from_raw(action.custom_name)).release_value();
- return PropertyNameAndID::from_id(static_cast<PropertyID>(action.property_id));
- };
- auto adopt = [](StyleValueFFI::StyleValueData const* value) {
- return StyleValue::adopt_rust_style_value_data(StyleValueFFI::rust_style_value_retain(value));
- };
-
- // NB: The traced provisional transition states hold each transition started here until it is committed or
- // discarded, and the root vector holds its effect for the update past that.
- GC::RootVector<Animations::EffectRef> newly_started_transition_effects;
- HashTable<Animations::RustFFI::AnimationEffectId> replaced_transition_effects;
- auto on_actions = [&](ReadonlySpan<StyleValueFFI::FfiTransitionAction> actions) {
- for (auto const& action : actions) {
- auto property = property_of_action(action);
- auto& state = ensure_state(property);
- decide(state, action.kind);
- if (action.kind != StyleValueFFI::FfiTransitionActionKind::None && action.kind != StyleValueFFI::FfiTransitionActionKind::Start) {
- VERIFY(state.committed_transition.has_value());
- if (auto effect = state.committed_transition->effect(); effect.has_value())
- replaced_transition_effects.set(effect->id());
- }
- if (!action.start_value)
- continue;
- auto transition = CSSTransition::start_a_provisional_transition(abstract_element, property, document().transition_generation(),
- action.delay, style_change_event_time, style_change_event_time + action.active_duration,
- adopt(action.start_value), adopt(action.end_value), adopt(action.reversing_adjusted_start_value),
- action.reversing_shortening_factor, EasingFunction::from_style_value(adopt(action.timing_function)));
- // NB: The associated effect of a provisional transition is the effect it was started with.
- newly_started_transition_effects.append(*transition.effect());
- state.proposed_transition = move(transition);
- }
- // A property an earlier pass of the epoch decided over that this one does not leaves its transitions as they are.
- auto indices = m_provisional_transition_state_indices_by_target.get(target_key);
- for (auto index : indices.has_value() ? indices->span() : ReadonlySpan<size_t> {}) {
- auto& state = m_provisional_transition_states[index];
- if (!any_of(actions, [&](auto const& action) { return property_of_action(action) == state.property; }))
- decide(state, StyleValueFFI::FfiTransitionActionKind::None);
- }
- };
- StyleValueFFI::FfiTransitionInput input {
- .existing_transitions = existing_transitions.data(),
- .existing_transition_count = existing_transitions.size(),
+ VERIFY(current_time->type == Animations::RustFFI::TimeValueType::Milliseconds);
+
+ Optional<Utf16FlyString> pseudo_element_serialization;
+ if (pseudo_element.has_value())
+ pseudo_element_serialization = Utf16FlyString { Selector::PseudoElementSelector { *pseudo_element }.serialize() };
+ auto slot = Animations::Animatable::owner_slot(pseudo_element);
+ auto overlay = abstract_element.custom_property_data();
+ if (!abstract_element.custom_property_data_is_animation_overlay())
+ overlay = nullptr;
+ Animations::RustFFI::FfiTransitionStep step {
+ .animations = &element.ensure_animations(),
+ .owner = transition_owner(abstract_element),
+ .pseudo_element_serialization = pseudo_element_serialization.has_value() ? pseudo_element_serialization->raw_identity() : 0,
+ .has_slot = slot.has_value(),
+ .slot = slot.value_or(Animations::RustFFI::AnimationOwnerSlot { 0 }),
+ .style_change_event_time = current_time->value,
+ .generation = document().transition_generation(),
+ .overlay_store = overlay ? overlay->rust_store() : nullptr,
+ .host = m_style_engine.host(),
+ .read = &read,
+ .before = before_change_style.record_pointer(),
+ .after = abstract_element.installed_style().record_pointer(),
.target_node = element.style_node_id().value(),
.target_pseudo_kind = pseudo_element_to_ffi(pseudo_element),
.element_box_slot = Layout::Node::slot_id(element.unsafe_layout_node(read)).index,
+ .tree_order = Animations::compare_elements_in_tree_order_for_composite_order,
};
- StyleEngineFFI::style_engine_decide_transitions(m_style_engine.host(), &read, before_change_style.record_pointer(), abstract_element.installed_style().record_pointer(), &input, [](void* context, StyleValueFFI::FfiTransitionAction const* actions, size_t count) { (*static_cast<decltype(on_actions)*>(context))({ actions, count }); }, &on_actions);
-
- // A transition action is provisional until the stabilization epoch commits, but the style
- // published by this pass must already reflect that decision. Rebuild the effect stack without
- // transitions which are being removed, then layer any proposed replacements on top.
- if (replaced_transition_effects.is_empty() && newly_started_transition_effects.is_empty())
+ // NB: Starting and discarding transitions settles their promises in the document's realm.
+ GC::RootVector<Animations::AnimationRef> animations;
+ Animations::RustFFI::FfiTransitionStepOutcome outcome;
+ {
+ HTML::TemporaryExecutionContext execution_context { document().relevant_settings_object() };
+ outcome = Animations::RustFFI::animations_document_animations_run_transition_step(&document().document_animations(), &step, Animations::keep_animation_alive_in, &animations, Animations::web_animation_perform_host_effect);
+ }
+ if (!outcome.changes_effects)
return {};
// OPTIMIZATION: Transition decisions read the installed records directly. Reconstruct a working style only when
// changes to the effect stack require rebuilding the overlay.
auto new_style = reconstruct_computed_properties_for_animation(abstract_element.installed_style());
new_style->clear_animated_properties(Badge<StyleComputer> {});
- // NB: The effects of the relevant animations of the element that target the same element or pseudo-element as
- // this style, beside those of the SVG animation elements, which script does not see.
- GC::RootVector<Animations::EffectRef> remaining_effects;
- for (auto const& animation : abstract_element.element().associated_animations_unordered()) {
- if (animation.timing_state().kind == Animations::RustFFI::FfiAnimationKind::Smil || !animation.is_relevant())
- continue;
- auto effect = animation.effect();
- if (!effect.has_value() || effect->pseudo_element_type() != abstract_element.pseudo_element())
- continue;
- if (replaced_transition_effects.contains(effect->id()))
- continue;
- remaining_effects.append(effect.release_value());
- }
- remaining_effects.extend(newly_started_transition_effects);
- quick_sort(remaining_effects, [](auto const& a, auto const& b) {
- return Animations::AnimationRef::composite_order(*a.associated_animation(), *b.associated_animation()) < 0;
- });
- if (!remaining_effects.is_empty())
- collect_animations_into(read, abstract_element, remaining_effects, *new_style);
+ GC::RootVector<Animations::EffectRef> effects;
+ for (auto const& animation : animations)
+ effects.append(*animation.effect());
+ if (!effects.is_empty())
+ collect_animations_into(read, abstract_element, effects, *new_style);
- if (!newly_started_transition_effects.is_empty()) {
+ if (outcome.started_transitions) {
// NB: Construction does not invalidate animated style because the effects were just evaluated. Request the
// first animation frame directly so timeline updates can schedule subsequent animated style updates.
set_rendering_pending(*m_document, RenderingPendingReason::NeedsRenderingUpdate, 1);
@@ -1202,7 +1031,7 @@ RefPtr<ComputedStyleWorkingSet> StyleComputer::start_needed_transitions(Layout::
bool StyleComputer::has_provisional_transition_states(DOM::AbstractElement abstract_element) const
{
- return m_provisional_transition_state_indices_by_target.contains(transition_target_key(abstract_element));
+ return Animations::RustFFI::animations_document_animations_has_provisional_transitions(&document().document_animations(), transition_owner(abstract_element));
}
// What composes over the record an element or pseudo-element holds: the animations associated with the element, and the
@@ -1210,7 +1039,7 @@ bool StyleComputer::has_provisional_transition_states(DOM::AbstractElement abstr
bool StyleComputer::has_animations_to_compose(DOM::AbstractElement abstract_element) const
{
auto const& element = abstract_element.element();
- return element.has_relevant_animations() || element.has_associated_animations() || has_provisional_transition_states(abstract_element);
+ return element.has_associated_animations() || has_provisional_transition_states(abstract_element);
}
void StyleComputer::register_style_engine_sheet_source(StyleSheetState const& sheet)
diff --git a/Libraries/LibWeb/CSS/StyleComputer.h b/Libraries/LibWeb/CSS/StyleComputer.h
index b7561fb2b20..44d7e7b9d19 100644
--- a/Libraries/LibWeb/CSS/StyleComputer.h
+++ b/Libraries/LibWeb/CSS/StyleComputer.h
@@ -151,7 +151,6 @@ public:
// Refreshes the animations of elements of this document, sampling them all in one call of the style engine.
void refresh_animations_into_each(Layout::BegunRead const& read, ReadonlySpan<AnimationRefreshRequest>) const;
- void apply_animation_definitions(DOM::AbstractElement&, ReadonlySpan<ComputedValuesFFI::FfiComputedAnimation> animation_definitions, bool in_display_none_subtree) const;
// Applies the animation plan the record an element or pseudo-element holds decides, for a record the style engine
// settled, where applying it would change anything.
void apply_settled_animation_plan(Layout::BegunRead const& read, DOM::AbstractElement&) const;
@@ -172,7 +171,6 @@ public:
[[nodiscard]] NonnullRefPtr<ComputedStyleWorkingSet> compute_style_for_animation_commit(Layout::BegunRead const&, DOM::AbstractElement, ReadonlySpan<Animations::EffectRef>) const;
- void begin_transition_stabilization_epoch();
// https://drafts.csswg.org/css-transitions-2/#defining-before-change-style
// Keeps `before_change_style` as the style a later pass of the stabilization epoch decides the element's
// transitions against, unless a pass already kept one.
@@ -184,7 +182,9 @@ public:
// of the style change.
[[nodiscard]] RequiredInvalidationAfterStyleChange run_transition_step_for_installed_record(Layout::BegunRead const& read, DOM::AbstractElement, InstalledStyle const& before_change_style) const;
void commit_transition_stabilization_epoch();
- void for_each_provisional_transition_effect(DOM::AbstractElement const&, Function<void(Animations::EffectRef const&)> const&) const;
+ // AD-HOC: Runs the transitions the hover of the document's clock lane left elements running beside a task, which
+ // the screen showed, in place of those its steps ended, as the rendering update that takes them in begins.
+ void adopt_lane_transitions();
// The media features of the current style update, which the style engine copies with each transaction.
[[nodiscard]] Parser::ValueParserFFI::FfiMediaEnvironment const* ensure_media_environment_for_style_update() const;
@@ -308,18 +308,6 @@ private:
mutable HashMap<u64, InheritableCustomPropertyEnvironment> m_inheritable_custom_property_environments;
mutable u64 m_inheritable_custom_property_environments_generation { 0 };
- struct ProvisionalTransitionState {
- GC::Ptr<DOM::Element> element;
- Optional<PseudoElement> pseudo_element;
- PropertyNameAndID property;
- Optional<Animations::AnimationRef> committed_transition;
- Optional<Animations::AnimationRef> proposed_transition;
- StyleValueFFI::FfiTransitionActionKind action {};
- bool has_decision { false };
- };
- mutable Vector<ProvisionalTransitionState> m_provisional_transition_states;
- mutable HashMap<u64, size_t> m_provisional_transition_state_indices;
- mutable HashMap<u64, Vector<size_t>> m_provisional_transition_state_indices_by_target;
// Whether the engine keeps a before-change style the current stabilization epoch recorded.
mutable bool m_transition_baselines_recorded { false };
diff --git a/Libraries/LibWeb/CSS/StyleEngineInput.cpp b/Libraries/LibWeb/CSS/StyleEngineInput.cpp
index 0a73fd6457c..952c190f084 100644
--- a/Libraries/LibWeb/CSS/StyleEngineInput.cpp
+++ b/Libraries/LibWeb/CSS/StyleEngineInput.cpp
@@ -10,9 +10,7 @@
#include <LibGC/RootHashTable.h>
#include <LibGC/RootVector.h>
#include <LibWeb/Animations/AnimationEffect.h>
-#include <LibWeb/CSS/CSSAnimation.h>
#include <LibWeb/CSS/CSSStyleRule.h>
-#include <LibWeb/CSS/CSSTransition.h>
#include <LibWeb/CSS/ElementBoxKind.h>
#include <LibWeb/CSS/Invalidation/FormControlInvalidator.h>
#include <LibWeb/CSS/Invalidation/LanguageInvalidator.h>
@@ -1811,7 +1809,7 @@ static u32 open_style_adjustment_facts(DOM::Element const& element, ElementOpenF
// Admission facts do not participate in box transformations.
// An animation the element is associated with composes into its style once it is relevant,
// which its timeline can make it after the element's arrival.
- set(element.has_relevant_animations() || element.has_associated_animations(), ElementStyleAdjustmentFact::HasAnimations);
+ set(element.has_associated_animations(), ElementStyleAdjustmentFact::HasAnimations);
set(element.associated_shadow_host_pseudo_element().has_value(), ElementStyleAdjustmentFact::IsShadowHostPseudoElement);
set(element.rendered_in_top_layer(), ElementStyleAdjustmentFact::RenderedInTopLayer);
return facts;
diff --git a/Libraries/LibWeb/CSS/StyleValues/CalcNodeRef.h b/Libraries/LibWeb/CSS/StyleValues/CalcNodeRef.h
deleted file mode 100644
index fdbc1526365..00000000000
--- a/Libraries/LibWeb/CSS/StyleValues/CalcNodeRef.h
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/Noncopyable.h>
-#include <AK/Optional.h>
-#include <AK/StdLibExtras.h>
-#include <LibWeb/CSS/Enums.h>
-#include <LibWeb/CSS/Keyword.h>
-#include <LibWeb/CSS/NumericType.h>
-#include <LibWeb/CSS/StyleValues/CalculatedStyleValue.h>
-#include <LibWeb/StyleValueRustFFI.h>
-
-namespace Web::CSS {
-
-// Move-only owner of one strong reference to a Rust calculation node. This is
-// how C++ builds calculation trees: every factory transfers its argument
-// handles into the new node, mirroring the FFI construction surface, so a
-// fully built tree is always owned by exactly one CalcNodeRef.
-class CalcNodeRef {
- AK_MAKE_NONCOPYABLE(CalcNodeRef);
-
-public:
- CalcNodeRef(CalcNodeRef&& other)
- : m_node(exchange(other.m_node, nullptr))
- {
- }
-
- CalcNodeRef& operator=(CalcNodeRef&& other)
- {
- CalcNodeRef moved(move(other));
- swap(m_node, moved.m_node);
- return *this;
- }
-
- ~CalcNodeRef()
- {
- if (m_node)
- StyleValueFFI::rust_calc_node_release(m_node);
- }
-
- // The borrowed node pointer; ownership stays with this ref.
- StyleValueFFI::CalcNode const* node() const { return m_node; }
-
- // Transfers ownership of the strong reference to the caller.
- StyleValueFFI::CalcNode const* release() { return exchange(m_node, nullptr); }
-
- // Adopts a transferred handle, for example one returned by the Rust
- // simplification entry points.
- static CalcNodeRef adopt(StyleValueFFI::CalcNode const* node) { return CalcNodeRef { node }; }
-
- // https://drafts.csswg.org/css-values-4/#determine-the-type-of-a-calculation
- // The type of the calculation this node roots, determined by the Rust
- // core; nothing when the tree does not type-check.
- Optional<NumericType> determine_type(CalculationContext const&) const;
-
-private:
- explicit CalcNodeRef(StyleValueFFI::CalcNode const* node)
- : m_node(node)
- {
- VERIFY(m_node);
- }
-
- StyleValueFFI::CalcNode const* m_node { nullptr };
-};
-
-}
diff --git a/Libraries/LibWeb/CSS/StyleValues/CalculatedStyleValue.cpp b/Libraries/LibWeb/CSS/StyleValues/CalculatedStyleValue.cpp
index 8d024ca605a..194f8fa4348 100644
--- a/Libraries/LibWeb/CSS/StyleValues/CalculatedStyleValue.cpp
+++ b/Libraries/LibWeb/CSS/StyleValues/CalculatedStyleValue.cpp
@@ -15,7 +15,6 @@
#include <LibWeb/CSS/PropertyNameAndID.h>
#include <LibWeb/CSS/StyleComputeFFI.h>
#include <LibWeb/CSS/StyleValues/AngleStyleValue.h>
-#include <LibWeb/CSS/StyleValues/CalcNodeRef.h>
#include <LibWeb/CSS/StyleValues/FlexStyleValue.h>
#include <LibWeb/CSS/StyleValues/FrequencyStyleValue.h>
#include <LibWeb/CSS/StyleValues/IntegerStyleValue.h>
@@ -27,53 +26,8 @@
namespace Web::CSS {
-// Marshals a numeric type into its FFI mirror.
-static StyleValueFFI::FfiNumericType to_ffi_numeric_type(Optional<NumericType> const& type)
-{
- StyleValueFFI::FfiNumericType result {};
- result.valid = type.has_value();
- if (type.has_value()) {
- type->for_each_type_and_exponent([&](auto base_type, i32 exponent) {
- result.has_exponent_bits |= 1u << to_underlying(base_type);
- result.exponents[to_underlying(base_type)] = exponent;
- });
- if (auto hint = type->percent_hint(); hint.has_value()) {
- result.has_percent_hint = true;
- result.percent_hint = to_underlying(hint.value());
- }
- }
- return result;
-}
-
static Optional<NumericType> from_ffi_numeric_type(StyleValueFFI::FfiNumericType const&);
-// Builds the Rust mirror of a calculation tree, transferring ownership of the
-// returned handle to the caller. The child orders follow each node's members.
-StyleValueFFI::StyleValueData const* CalculatedStyleValue::make_calculated_data_from_rust_root(StyleValueFFI::CalcNode const* rust_root, NumericType const& resolved_type, CalculationContext const& context)
-{
- Vector<StyleValueFFI::RetainedNumericRangeByType> ranges;
- ranges.ensure_capacity(context.accepted_ranges_by_type.size());
- for (auto const& [value_type, range] : context.accepted_ranges_by_type)
- ranges.unchecked_append({ to_underlying(value_type), range.min, range.max });
- auto resolve_as_base = context.percentages_resolve_as.has_value()
- ? NumericType::base_type_from_value_type(*context.percentages_resolve_as)
- : OptionalNone {};
- return StyleValueFFI::rust_style_value_create_calculated(
- rust_root,
- to_ffi_numeric_type(resolved_type),
- context.percentages_resolve_as.has_value(),
- context.percentages_resolve_as == ValueType::Number,
- resolve_as_base.has_value() ? to_underlying(*resolve_as_base) : 0,
- context.percentages_resolve_as.has_value() ? to_underlying(*context.percentages_resolve_as) : 0,
- context.resolve_numbers_as_integers,
- ranges.data(), ranges.size());
-}
-
-ValueComparingNonnullRefPtr<CalculatedStyleValue const> CalculatedStyleValue::create(CalcNodeRef root, NumericType resolved_type, CalculationContext context)
-{
- return adopt_ref(*new (nothrow) CalculatedStyleValue(root.release(), move(resolved_type), move(context)));
-}
-
NumericType CalculatedStyleValue::resolved_type() const
{
return from_ffi_numeric_type(m_value->calculated._0->resolved_type).release_value();
@@ -245,17 +199,6 @@ Optional<Resolution> CalculatedStyleValue::resolve_resolution(CalculationResolut
return {};
}
-Optional<Time> CalculatedStyleValue::resolve_time(CalculationResolutionContext const& context) const
-{
- auto calculation_context = this->calculation_context();
- auto result = resolve_value(context);
-
- if (result.has_value() && result->type.has_value() && result->type->matches_time(calculation_context.percentages_resolve_as))
- return Time::make_seconds(result->value);
-
- return {};
-}
-
Optional<double> CalculatedStyleValue::resolve_number(CalculationResolutionContext const& context) const
{
auto calculation_context = this->calculation_context();
@@ -273,16 +216,4 @@ bool CalculatedStyleValue::contains_percentage() const
return StyleValueFFI::rust_calc_node_contains_percentage(m_value->calculated._0->rust_calculation.node);
}
-Optional<NumericType> CalcNodeRef::determine_type(CalculationContext const& context) const
-{
- auto resolve_as_base = context.percentages_resolve_as.has_value()
- ? NumericType::base_type_from_value_type(*context.percentages_resolve_as)
- : OptionalNone {};
- return from_ffi_numeric_type(StyleValueFFI::rust_calc_node_determine_type(
- m_node,
- context.percentages_resolve_as.has_value(),
- context.percentages_resolve_as == ValueType::Number,
- resolve_as_base.has_value() ? to_underlying(*resolve_as_base) : 0));
-}
-
}
diff --git a/Libraries/LibWeb/CSS/StyleValues/CalculatedStyleValue.h b/Libraries/LibWeb/CSS/StyleValues/CalculatedStyleValue.h
index 51b90eb7dac..e99cda86756 100644
--- a/Libraries/LibWeb/CSS/StyleValues/CalculatedStyleValue.h
+++ b/Libraries/LibWeb/CSS/StyleValues/CalculatedStyleValue.h
@@ -23,8 +23,6 @@
namespace Web::CSS {
-class CalcNodeRef;
-
// https://drafts.csswg.org/css-values-4/#calc-context
// Contains the context available at parse-time.
struct CalculationContext {
@@ -42,7 +40,6 @@ public:
// The numeric value alternatives a calculation leaf can hold.
using NumericValue = Variant<Number, Angle, Flex, Frequency, Length, Percentage, Resolution, Time>;
- static ValueComparingNonnullRefPtr<CalculatedStyleValue const> create(CalcNodeRef root, NumericType resolved_type, CalculationContext context);
bool equals(StyleValue const& other) const;
CalculationContext calculation_context() const;
@@ -56,9 +53,6 @@ public:
Optional<Resolution> resolve_resolution(CalculationResolutionContext const&) const;
- bool resolves_to_time() const { return resolved_type().matches_time(calculation_context().percentages_resolve_as); }
- Optional<Time> resolve_time(CalculationResolutionContext const&) const;
-
bool resolves_to_number() const { return resolved_type().matches_number(calculation_context().percentages_resolve_as); }
Optional<double> resolve_number(CalculationResolutionContext const&) const;
bool contains_percentage() const;
@@ -71,12 +65,6 @@ private:
{
}
- // Takes ownership of a transferred Rust calculation root.
- explicit CalculatedStyleValue(StyleValueFFI::CalcNode const* rust_root, NumericType resolved_type, CalculationContext context)
- : StyleValue(Type::Calculated, make_calculated_data_from_rust_root(rust_root, resolved_type, context))
- {
- }
-
struct ResolvedValue {
double value;
Optional<NumericType> type;
@@ -87,8 +75,6 @@ private:
// StyleValue classes which lack their own absolutized method) which will need to be fixed beforehand.
Optional<ResolvedValue> resolve_value(CalculationResolutionContext const&, bool apply_censoring_and_clamping = true) const;
- static StyleValueFFI::StyleValueData const* make_calculated_data_from_rust_root(StyleValueFFI::CalcNode const*, NumericType const&, CalculationContext const&);
-
NumericType resolved_type() const;
};
diff --git a/Libraries/LibWeb/CSS/TypedOM.cpp b/Libraries/LibWeb/CSS/TypedOM.cpp
deleted file mode 100644
index 958fd1ce33f..00000000000
--- a/Libraries/LibWeb/CSS/TypedOM.cpp
+++ /dev/null
@@ -1,130 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibJS/HostClassBuilder.h>
-#include <LibJS/Runtime/VM.h>
-#include <LibWeb/CSS/CSSKeywordValue.h>
-#include <LibWeb/CSS/CSSNumericValue.h>
-#include <LibWeb/CSS/CSSUnitValue.h>
-
-// What LibWeb's C++ code asks of the Rust implementation of the CSS Typed OM (Libraries/LibWeb/Bindings/Rust/src/css).
-
-namespace Web::CSS {
-
-using StyleValueData = StyleValueFFI::StyleValueData;
-using FfiNumericType = StyleValueFFI::FfiNumericType;
-using FfiCalcNode = StyleValueFFI::CalcNode;
-
-extern "C" {
-
-// Defined in Bindings/Rust/src/css/exports.rs.
-void* web_css_style_value_create(JSVM*, FlatPtr associated_property, StyleValueData const*, u8 serialization_mode);
-void* web_css_style_value_reify(JSVM*, StyleValueData const*, FlatPtr associated_property);
-bool web_css_style_value_associated_property(void* value, FlatPtr* associated_property);
-u8 web_css_style_value_kind(void* value);
-void* web_css_numeric_value_create_sum(JSVM*, void* first, void* second);
-FfiNumericType web_css_numeric_value_type(void* value);
-FlatPtr web_css_numeric_value_to_string(void* value);
-FfiCalcNode const* web_css_numeric_value_create_calculation_node(void* value);
-void* web_css_unit_value_create(JSVM*, double value, FlatPtr unit);
-double web_css_unit_value_value(void* value);
-FlatPtr web_css_unit_value_unit(void* value);
-FlatPtr web_css_keyword_value_value(void* value);
-}
-
-// The order of `enum StyleValueKind` in Bindings/Rust/src/css/exports.rs.
-enum class StyleValueKind : u8 {
- Other,
- Numeric,
- Unit,
- Unparsed,
-};
-
-static JSVM* vm_abi()
-{
- return JS::HostABI::vm_to_abi(JS::VM::the());
-}
-
-static StyleValueKind kind_of(CSSStyleValue const& value)
-{
- return static_cast<StyleValueKind>(web_css_style_value_kind(const_cast<CSSStyleValue*>(&value)));
-}
-
-GC::Ref<CSSStyleValue> CSSStyleValue::create(Utf16FlyString associated_property, StyleValue const& source_value, SerializationMode serialization_mode)
-{
- auto* value = web_css_style_value_create(vm_abi(), associated_property.to_utf16_string().into_raw(), StyleValueFFI::rust_style_value_retain(source_value.rust_style_value_data()), to_underlying(serialization_mode));
- return GC::Ref { *static_cast<CSSStyleValue*>(value) };
-}
-
-GC::Ref<CSSStyleValue> CSSStyleValue::reify(StyleValue const& value, Utf16FlyString const& associated_property)
-{
- auto* reified_value = web_css_style_value_reify(vm_abi(), StyleValueFFI::rust_style_value_retain(value.rust_style_value_data()), associated_property.to_utf16_string().into_raw());
- return GC::Ref { *static_cast<CSSStyleValue*>(reified_value) };
-}
-
-Optional<Utf16FlyString> CSSStyleValue::associated_property() const
-{
- FlatPtr associated_property = 0;
- if (!web_css_style_value_associated_property(const_cast<CSSStyleValue*>(this), &associated_property))
- return {};
- return Utf16FlyString { Utf16String::adopt_raw(associated_property) };
-}
-
-bool CSSStyleValue::is_numeric_value() const
-{
- auto kind = kind_of(*this);
- return kind == StyleValueKind::Numeric || kind == StyleValueKind::Unit;
-}
-
-bool CSSStyleValue::is_unit_value() const
-{
- return kind_of(*this) == StyleValueKind::Unit;
-}
-
-GC::Ref<CSSNumericValue> CSSNumericValue::create_sum(GC::Ref<CSSNumericValue> first, GC::Ref<CSSNumericValue> second)
-{
- return GC::Ref { *static_cast<CSSNumericValue*>(web_css_numeric_value_create_sum(vm_abi(), first.ptr(), second.ptr())) };
-}
-
-NumericType CSSNumericValue::type() const
-{
- return NumericType::from_ffi(web_css_numeric_value_type(const_cast<CSSNumericValue*>(this))).release_value();
-}
-
-Utf16String CSSNumericValue::to_string() const
-{
- return Utf16String::adopt_raw(web_css_numeric_value_to_string(const_cast<CSSNumericValue*>(this)));
-}
-
-Optional<CalcNodeRef> CSSNumericValue::create_calculation_node() const
-{
- auto const* node = web_css_numeric_value_create_calculation_node(const_cast<CSSNumericValue*>(this));
- if (!node)
- return {};
- return CalcNodeRef::adopt(node);
-}
-
-GC::Ref<CSSUnitValue> CSSUnitValue::create(double value, Utf16FlyString const& unit)
-{
- return GC::Ref { *static_cast<CSSUnitValue*>(web_css_unit_value_create(vm_abi(), value, unit.to_utf16_string().into_raw())) };
-}
-
-double CSSUnitValue::value() const
-{
- return web_css_unit_value_value(const_cast<CSSUnitValue*>(this));
-}
-
-Utf16FlyString CSSUnitValue::unit() const
-{
- return Utf16FlyString { Utf16String::adopt_raw(web_css_unit_value_unit(const_cast<CSSUnitValue*>(this))) };
-}
-
-Utf16String CSSKeywordValue::value() const
-{
- return Utf16String::adopt_raw(web_css_keyword_value_value(const_cast<CSSKeywordValue*>(this)));
-}
-
-}
diff --git a/Libraries/LibWeb/DOM/Document.cpp b/Libraries/LibWeb/DOM/Document.cpp
index 09d26cdc1ee..2dc37be78b1 100644
--- a/Libraries/LibWeb/DOM/Document.cpp
+++ b/Libraries/LibWeb/DOM/Document.cpp
@@ -32,24 +32,21 @@
#include <LibHTTP/Cookie/Cookie.h>
#include <LibHTTP/Cookie/ParsedCookie.h>
#include <LibJS/Console.h>
+#include <LibJS/HostClassBuilder.h>
#include <LibJS/Runtime/Iterator.h>
#include <LibTextCodec/Decoder.h>
#include <LibURL/Origin.h>
#include <LibURL/Parser.h>
#include <LibUnicode/Segmenter.h>
#include <LibWeb/ARIA/AttributeNames.h>
-#include <LibWeb/Animations/AnimationTimeline.h>
#include <LibWeb/Animations/NamedTimelines.h>
#include <LibWeb/Animations/RecordHandles.h>
-#include <LibWeb/Animations/TimeValue.h>
#include <LibWeb/Bindings/CSS.h>
#include <LibWeb/Bindings/Document.h>
#include <LibWeb/Bindings/Sanitizer.h>
#include <LibWeb/Bindings/Wrappable.h>
#include <LibWeb/Bindings/WrapperWorld.h>
#include <LibWeb/CSS/Angle.h>
-#include <LibWeb/CSS/CSSAnimation.h>
-#include <LibWeb/CSS/CSSTransition.h>
#include <LibWeb/CSS/ComputedStyleWorkingSet.h>
#include <LibWeb/CSS/ComputedValues.h>
#include <LibWeb/CSS/CustomPropertyRegistration.h>
@@ -80,6 +77,7 @@
#include <LibWeb/CSS/StyleValues/FilterStyleValue.h>
#include <LibWeb/CSS/StyleValues/ImageStyleValue.h>
#include <LibWeb/CSS/StyleValues/OpacityValueStyleValue.h>
+#include <LibWeb/CSS/StyleValues/StyleValue.h>
#include <LibWeb/CSS/StyleValues/StyleValueList.h>
#include <LibWeb/CSS/StyleValues/TransformationStyleValue.h>
#include <LibWeb/CSS/VisualViewport.h>
@@ -228,6 +226,7 @@
#include <LibWeb/Infra/SerializedURL.h>
#include <LibWeb/IntersectionObserver/IntersectionObserver.h>
#include <LibWeb/Layout/LayoutRustBridge.h>
+#include <LibWeb/Layout/LayoutRustFFI.h>
#include <LibWeb/Layout/NodeArena.h>
#include <LibWeb/Layout/RenderDocument.h>
#include <LibWeb/Layout/TextNode.h>
@@ -241,7 +240,6 @@
#include <LibWeb/Page/RenderingStats.h>
#include <LibWeb/Painting/BoxViews.h>
#include <LibWeb/Painting/ChromeWidget.h>
-#include <LibWeb/Painting/CompositorAnimationEffectState.h>
#include <LibWeb/Painting/DocumentPaintState.h>
#include <LibWeb/Painting/HitTestQuery.h>
#include <LibWeb/Painting/PaintFacts.h>
@@ -299,6 +297,20 @@
namespace Web::DOM {
+// What dispatching the events of the pending animation event queue of a document asks of the document.
+struct PendingAnimationEventHost {
+ void* context;
+ void (*keep_alive)(void* context, Animations::RustFFI::AnimationCell const*);
+ void (*dispatch_at_element)(void* context, void* element, void* event);
+ void (*dispatch_time_event)(void* context, Animations::RustFFI::AnimationCell const*, Animations::RustFFI::FfiPendingAnimationEvent const*);
+};
+
+extern "C" {
+
+// Defined in Bindings/Rust/src/animations/animation.rs.
+void web_animation_dispatch_pending_animation_events(JSVM*, Document*, Animations::RustFFI::DocumentAnimations*, Animations::RustFFI::FfiTreeOrder, PendingAnimationEventHost const*);
+}
+
void PendingFullscreenEvent::visit_edges(GC::Cell::Visitor& visitor) const
{
visitor.visit(element);
@@ -792,62 +804,6 @@ GC::Ref<Document> Document::create_for_fragment_parsing(Page& page, GC::Ref<Even
return document;
}
-// The animations associated with the elements of the document, which it keeps none of alive.
-static Animations::WeakAnimationSetView associated_animations(Animations::RustFFI::DocumentAnimations* animations)
-{
- return Animations::WeakAnimationSetView { *Animations::RustFFI::animations_document_animations_set(animations, Animations::RustFFI::DocumentAnimationSetKind::Associated) };
-}
-
-// The animations associated with the document during the current style stabilization epoch.
-static Animations::WeakAnimationSetView animations_created_in_stabilization_epoch(Animations::RustFFI::DocumentAnimations* animations)
-{
- return Animations::WeakAnimationSetView { *Animations::RustFFI::animations_document_animations_set(animations, Animations::RustFFI::DocumentAnimationSetKind::CreatedInStabilizationEpoch) };
-}
-
-// A set of the effects the document knows of, which keeps none of them alive.
-class DocumentEffectSet {
-public:
- DocumentEffectSet(Animations::RustFFI::DocumentAnimations* animations, Animations::RustFFI::DocumentEffectSetKind kind)
- : m_animations(animations)
- , m_kind(kind)
- {
- }
-
- bool set(Animations::EffectRef const& effect) { return Animations::RustFFI::animations_document_effect_set_insert(m_animations, m_kind, &effect.record()); }
- bool remove(Animations::RustFFI::AnimationEffectCell const& effect) { return Animations::RustFFI::animations_document_effect_set_remove(m_animations, m_kind, &effect); }
- bool contains(Animations::RustFFI::AnimationEffectCell const& effect) const { return Animations::RustFFI::animations_document_effect_set_contains(m_animations, m_kind, &effect); }
-
- // Empties the set, calling `callback` with each effect alive to it.
- template<typename Callback>
- void take_each(Callback callback)
- {
- Animations::RustFFI::animations_document_effect_set_take_each(m_animations, m_kind, &callback, [](void* context, Animations::RustFFI::AnimationEffectCell const* effect) {
- (*static_cast<Callback*>(context))(Animations::EffectRef { *effect });
- });
- }
-
- void clear()
- {
- take_each([](Animations::EffectRef const&) { });
- }
-
-private:
- Animations::RustFFI::DocumentAnimations* m_animations { nullptr };
- Animations::RustFFI::DocumentEffectSetKind m_kind;
-};
-
-// The effects whose animated style the next animated style update samples.
-static DocumentEffectSet effects_needing_animated_style_update(Animations::RustFFI::DocumentAnimations* animations)
-{
- return { animations, Animations::RustFFI::DocumentEffectSetKind::NeedingAnimatedStyleUpdate };
-}
-
-// The effects to ask for an observation sample as the current animated style update finishes.
-static DocumentEffectSet effects_needing_animated_style_update_after_current_update(Animations::RustFFI::DocumentAnimations* animations)
-{
- return { animations, Animations::RustFFI::DocumentEffectSetKind::NeedingAnimatedStyleUpdateAfterCurrentUpdate };
-}
-
Document::Document(Page& page, GC::Ref<EventTarget> relevant_global_event_target, URL::URL const& url, TemporaryDocumentForFragmentParsing temporary_document_for_fragment_parsing)
: ParentNode(*this, NodeType::DOCUMENT_NODE)
, m_page(page)
@@ -1102,7 +1058,6 @@ void Document::visit_edges(Cell::Visitor& visitor)
visitor.visit(m_parser);
visitor.visit(m_lazy_load_intersection_observer);
visitor.visit(m_visual_viewport);
- visitor.visit(m_default_timeline);
visitor.visit(m_named_timelines);
visitor.visit(m_scripts_to_execute_when_parsing_has_finished);
visitor.visit(m_scripts_to_execute_in_order_as_soon_as_possible);
@@ -1127,7 +1082,6 @@ void Document::visit_edges(Cell::Visitor& visitor)
for (auto& resource : m_css_image_resources_with_request_url_modifiers)
resource.value->visit_edges(visitor);
- visitor.visit(m_associated_animation_timelines);
visitor.visit(m_smil_time_containers_to_begin);
visitor.visit(m_animate_motion_elements_to_update);
visitor.visit(m_list_of_available_images);
@@ -1152,7 +1106,7 @@ void Document::visit_edges(Cell::Visitor& visitor)
if (m_writing_suggestion_controller)
m_writing_suggestion_controller->visit_edges(visitor);
- Animations::RustFFI::animations_document_animations_visit_pending_events(m_animations, &visitor, Animations::visit_host_cell);
+ Animations::RustFFI::animations_document_animations_visit_edges(m_animations, &visitor, Animations::visit_host_cell);
for (auto& event : m_pending_fullscreen_events) {
visitor.visit(event.element);
@@ -2419,7 +2373,6 @@ void Document::begin_style_stabilization_epoch()
HTML::main_thread_event_loop().defer_microtask_checkpoints();
Animations::RustFFI::animations_document_animations_begin_style_stabilization_epoch(m_animations);
- style_computer().begin_transition_stabilization_epoch();
m_style_stabilization_pass_count = 0;
m_style_stabilization_has_style_reactions = false;
m_animated_custom_property_changes_in_stabilization_epoch.clear();
@@ -2879,6 +2832,13 @@ void Document::invalidate_style_for_viewport_change(CSSPixelSize previous_viewpo
}
}
+// What sampling the effects that need an animated style update of a document holds.
+struct AnimatedStyleSample {
+ // NB: The animations of the effects stay alive for as long as the update holds them.
+ GC::RootVector<Animations::AnimationRef> animations;
+ Optional<Animations::AnimationUpdateContext> context;
+};
+
void Document::sample_animation_effects_needing_style_update()
{
if (!m_needs_animated_style_update)
@@ -2890,74 +2850,24 @@ void Document::sample_animation_effects_needing_style_update()
ScopeGuard clear_is_updating_animated_style = [&] {
finish_animated_style_update();
};
-
- // NB: The effects stay alive for as long as the update holds them.
- GC::RootVector<Animations::EffectRef> effects;
- if (m_force_throttled_animation_style_update) {
- for (auto const& animation : associated_animations(m_animations)) {
- auto effect = animation.effect();
- if (!effect.has_value())
- continue;
- // NB: Dirty idle effects still need to remove their last sampled values after cancellation.
- if (animation.timing_state().play_state == Animations::RustFFI::AnimationPlayState::Idle && !effects_needing_animated_style_update(m_animations).contains(effect->record()))
- continue;
- effects.append(effect.release_value());
- }
- effects_needing_animated_style_update(m_animations).clear();
- } else {
- effects_needing_animated_style_update(m_animations).take_each([&](Animations::EffectRef const& effect) {
- // NB: A canceled animation still needs to remove its last sampled values.
- if (!effect.associated_animation().has_value())
- return;
- effects.append(effect);
- });
- }
m_needs_animated_style_update = false;
- if (effects.is_empty()) {
- m_force_throttled_animation_style_update = false;
- // A compositor-driven effect can remain throttled when every dirty effect was cancelled before this sample.
- // Preserve the flag so a later style or geometry read can still request a current main-thread sample.
- return;
- }
-
- bool has_requested_observation_sample = any_of(effects, [](auto const& effect) {
- return effect.has_flag(Animations::RustFFI::EffectFlag::NeedsObservationSample);
- });
-
- // A timeline script observed ahead of its current time in this task is sampled at that time too, so that a style
- // read agrees with the time script read, however many reads the task makes.
- GC::RootVector<GC::Ref<Animations::AnimationTimeline>> timelines_with_current_time_override;
- bool const samples_at_observed_time = m_force_throttled_animation_style_update || has_requested_observation_sample;
- for (auto& timeline : m_associated_animation_timelines) {
- if (samples_at_observed_time || timeline->was_observed_ahead_in_current_task())
- timelines_with_current_time_override.append(timeline);
- }
- for (auto& timeline : timelines_with_current_time_override)
- timeline->set_current_time_override_for_style_sampling(timeline->current_time_for_observation());
- ScopeGuard clear_current_time_overrides = [&] {
- for (auto& timeline : timelines_with_current_time_override)
- timeline->clear_current_time_override_for_style_sampling();
+ AnimatedStyleSample sample { {}, {} };
+ Animations::RustFFI::FfiAnimatedStyleSampleHost host {
+ .context = &sample,
+ .keep_alive = [](void* context, Animations::RustFFI::AnimationCell const* animation) { Animations::keep_animation_alive_in(&static_cast<AnimatedStyleSample*>(context)->animations, animation); },
+ .begin = [](void* context) { static_cast<AnimatedStyleSample*>(context)->context.emplace(); },
+ .update = [](void* context, Animations::RustFFI::AnimationEffectCell const* effect) { Animations::EffectRef { *effect }.update_computed_properties(*static_cast<AnimatedStyleSample*>(context)->context); },
+ .end = [](void* context) { static_cast<AnimatedStyleSample*>(context)->context.clear(); },
};
+ auto outcome = Animations::RustFFI::animations_document_animations_sample_effects_needing_style_update(m_animations, m_force_throttled_animation_style_update, m_has_throttled_animation_style_update, &host);
- Animations::AnimationUpdateContext context;
-
- quick_sort(effects, [](Animations::EffectRef const& a, Animations::EffectRef const& b) {
- return Animations::AnimationRef::composite_order(*a.associated_animation(), *b.associated_animation()) < 0;
- });
-
- bool has_throttled_animation_style_update = m_force_throttled_animation_style_update ? false : m_has_throttled_animation_style_update;
- for (auto const& effect : effects) {
- bool observation_sample_requested = effect.set_flag(Animations::RustFFI::EffectFlag::NeedsObservationSample, false);
- if (effect.can_skip_per_frame_style_update()) {
- has_throttled_animation_style_update = true;
- if (!m_force_throttled_animation_style_update && !observation_sample_requested)
- continue;
- }
- effect.update_computed_properties(context);
+ if (!outcome.sampled) {
+ m_force_throttled_animation_style_update = false;
+ return;
}
- m_has_throttled_animation_style_update = has_throttled_animation_style_update;
+ m_has_throttled_animation_style_update = outcome.has_throttled_animation_style_update;
if (m_force_throttled_animation_style_update)
m_last_forced_throttled_animation_style_update_task_generation = relevant_settings_object().responsible_event_loop().task_generation();
m_force_throttled_animation_style_update = false;
@@ -2968,13 +2878,8 @@ void Document::note_animations_that_can_skip_per_frame_style_updates()
if (!m_needs_throttled_animation_style_update_check || m_has_throttled_animation_style_update || !layout_is_up_to_date())
return;
m_needs_throttled_animation_style_update_check = false;
- for (auto const& animation : associated_animations(m_animations)) {
- auto effect = animation.effect();
- if (effect.has_value() && effect->can_skip_per_frame_style_update()) {
- note_throttled_animation_style_update();
- return;
- }
- }
+ if (Animations::RustFFI::animations_document_animations_query(m_animations, Animations::RustFFI::DocumentAnimationsQuery::AnyCanSkipPerFrameStyleUpdate))
+ note_throttled_animation_style_update();
}
void Document::flush_throttled_animation_style_update()
@@ -3008,26 +2913,8 @@ void Document::flush_throttled_animation_style_update_for_node(Node const& node)
auto const* element = as_if<Element>(target);
if (!element)
return;
- for (auto const& animation : element->associated_animations_unordered()) {
- auto associated_effect = animation.effect();
- if (!associated_effect.has_value())
- continue;
- auto const& effect = *associated_effect;
- // NB: An effect that changed since it was last sampled, such as one script seeked after an earlier read in
- // this task, is sampled for the read whether or not it can skip per-frame style updates now: the sample
- // decides that again, from a layout that may have moved since.
- if (!m_is_updating_animated_style && effects_needing_animated_style_update(m_animations).contains(effect.record())) {
- effect.request_observation_sample();
- continue;
- }
- if (!effect.can_skip_per_frame_style_update())
- continue;
- if (m_is_updating_animated_style) {
- effects_needing_animated_style_update_after_current_update(m_animations).set(effect);
- } else {
- effect.request_element_scoped_observation_sample(task_generation);
- }
- }
+ if (auto const* animations = element->element_animations_if_created())
+ Animations::RustFFI::animations_element_animations_request_observation_samples(animations, m_animations, m_is_updating_animated_style, task_generation);
};
// An animation changes what this read sees only if its target is the node itself, one of its
@@ -3063,7 +2950,7 @@ bool Document::run_empty_animation_style_update_for_testing(Badge<Internals::Int
{
VERIFY(!m_is_updating_animated_style);
m_needs_animated_style_update = true;
- effects_needing_animated_style_update(m_animations).clear();
+ Animations::RustFFI::animations_document_animations_change_effect_sets(m_animations, Animations::RustFFI::EffectSetsChange::Clear);
sample_animation_effects_needing_style_update();
return m_has_throttled_animation_style_update;
}
@@ -3107,36 +2994,25 @@ void Document::throttled_animation_visibility_changed()
page().client().request_frame_for(*this);
}
-// The effects dirtied beside the transaction of a style update that flew, which the next style update samples.
-static DocumentEffectSet effects_needing_animated_style_update_beside_flown_style_update(Animations::RustFFI::DocumentAnimations* animations)
-{
- return { animations, Animations::RustFFI::DocumentEffectSetKind::SetAsideWhileFlownStyleUpdateDrains };
-}
-
void Document::set_aside_effects_needing_animated_style_update()
{
- effects_needing_animated_style_update(m_animations).take_each([&](Animations::EffectRef const& effect) {
- effects_needing_animated_style_update_beside_flown_style_update(m_animations).set(effect);
- });
+ Animations::RustFFI::animations_document_animations_change_effect_sets(m_animations, Animations::RustFFI::EffectSetsChange::SetAside);
}
void Document::restore_effects_needing_animated_style_update()
{
- effects_needing_animated_style_update_beside_flown_style_update(m_animations).take_each([&](Animations::EffectRef const& effect) {
- effects_needing_animated_style_update(m_animations).set(effect);
- });
+ Animations::RustFFI::animations_document_animations_change_effect_sets(m_animations, Animations::RustFFI::EffectSetsChange::Restore);
}
void Document::clear_needs_animated_style_update()
{
m_needs_animated_style_update = false;
- effects_needing_animated_style_update(m_animations).clear();
- effects_needing_animated_style_update_after_current_update(m_animations).clear();
+ Animations::RustFFI::animations_document_animations_change_effect_sets(m_animations, Animations::RustFFI::EffectSetsChange::Clear);
}
void Document::set_needs_animated_style_update(Animations::EffectRef const& effect)
{
- effects_needing_animated_style_update(m_animations).set(effect);
+ Animations::RustFFI::animations_document_effect_set_insert(m_animations, Animations::RustFFI::DocumentEffectSetKind::NeedingAnimatedStyleUpdate, &effect.record());
if (m_needs_animated_style_update)
return;
@@ -3154,14 +3030,7 @@ void Document::finish_animated_style_update()
{
VERIFY(m_is_updating_animated_style);
m_is_updating_animated_style = false;
-
- GC::RootVector<Animations::EffectRef> effects;
- effects_needing_animated_style_update_after_current_update(m_animations).take_each([&](Animations::EffectRef const& effect) {
- effects.append(effect);
- });
-
- for (auto const& effect : effects)
- effect.request_observation_sample();
+ Animations::RustFFI::animations_document_animations_change_effect_sets(m_animations, Animations::RustFFI::EffectSetsChange::FinishUpdate);
}
// What preparing the paint and hit testing properties, which the render state does as they are read, asks of the
@@ -4750,73 +4619,6 @@ Element* Document::find_a_potential_indicated_element(Utf16View fragment) const
// https://drafts.csswg.org/css-transitions-2/#event-dispatch
// https://www.w3.org/TR/css-animations-2/#event-dispatch
-void Document::dispatch_events_for_animation_if_necessary(Animations::AnimationRef const& animation)
-{
- // NB: The core queues the events the animation frame established for a CSS animation or transition. Each takes the
- // time stamp of when it is queued.
- auto queued = Animations::RustFFI::animations_document_animations_queue_css_events(
- m_animations, &animation.record(), m_style_stabilization_epoch_depth > 0, [](void* element) {
- return HighResolutionTime::current_high_resolution_time(HTML::relevant_global_object(*static_cast<DOM::Element*>(element)));
- });
- if (queued.kind == Animations::RustFFI::FfiAnimationKind::Smil) {
- static_cast<SVG::SVGAnimationElement*>(Animations::RustFFI::animations_smil_animation_element(&animation.record()))->queue_time_events_if_necessary();
- return;
- }
- auto provisional = m_style_stabilization_epoch_depth > 0;
- for (auto count = queued.count; count > 0; --count)
- HTML::note_rendering_trace_event(provisional ? "provisional animation events"sv : "animation events committed"sv);
-}
-
-// Creates the event the pending animation event queue of `document` holds of `animation`, and dispatches it at its
-// target.
-static void dispatch_pending_animation_event(Document& document, Animations::AnimationRef const& animation, Animations::RustFFI::FfiPendingAnimationEvent const& pending_event)
-{
- switch (pending_event.kind) {
- case Animations::RustFFI::PendingAnimationEventKind::Css: {
- auto owner = Animations::RustFFI::animations_animation_owning_element(&animation.record());
- auto& owning_element = *static_cast<DOM::Element*>(owner.element);
- auto pseudo_element = owner.has_pseudo_element
- ? Utf16String::formatted("::{}", CSS::pseudo_element_name(static_cast<CSS::PseudoElement>(owner.pseudo_element)))
- : Utf16String {};
- auto const& type = [&] -> Utf16FlyString const& {
- switch (pending_event.css_event_type) {
- case Animations::RustFFI::FfiCssEventType::AnimationStart:
- return HTML::EventNames::animationstart;
- case Animations::RustFFI::FfiCssEventType::AnimationEnd:
- return HTML::EventNames::animationend;
- case Animations::RustFFI::FfiCssEventType::AnimationIteration:
- return HTML::EventNames::animationiteration;
- case Animations::RustFFI::FfiCssEventType::AnimationCancel:
- return HTML::EventNames::animationcancel;
- case Animations::RustFFI::FfiCssEventType::TransitionRun:
- return HTML::EventNames::transitionrun;
- case Animations::RustFFI::FfiCssEventType::TransitionStart:
- return HTML::EventNames::transitionstart;
- case Animations::RustFFI::FfiCssEventType::TransitionEnd:
- return HTML::EventNames::transitionend;
- case Animations::RustFFI::FfiCssEventType::TransitionCancel:
- return HTML::EventNames::transitioncancel;
- }
- VERIFY_NOT_REACHED();
- }();
- auto event = animation.timing_state().kind == Animations::RustFFI::FfiAnimationKind::CssTransition
- ? CSS::CSSTransition::create_event(animation, owning_element.document(), type, pending_event.elapsed_time, pseudo_element)
- : CSS::CSSAnimation::create_event(animation, owning_element.document(), type, pending_event.elapsed_time, pseudo_element);
- event->set_time_stamp(pending_event.time_stamp);
- event->set_is_trusted(true);
- owning_element.dispatch_event(event);
- return;
- }
- case Animations::RustFFI::PendingAnimationEventKind::Playback:
- Animations::dispatch_pending_playback_event(animation, document, pending_event);
- return;
- case Animations::RustFFI::PendingAnimationEventKind::Time:
- static_cast<SVG::SVGAnimationElement*>(Animations::RustFFI::animations_smil_animation_element(&animation.record()))->dispatch_pending_time_event(pending_event);
- return;
- }
- VERIFY_NOT_REACHED();
-}
-
// https://html.spec.whatwg.org/multipage/browsing-the-web.html#scroll-to-the-fragment-identifier
void Document::scroll_to_the_fragment(bool allow_text_directive_scroll)
{
@@ -8666,18 +8468,26 @@ void Document::prune_image_resource_caches()
}
// https://www.w3.org/TR/web-animations-1/#dom-document-timeline
-GC::Ref<Animations::AnimationTimeline> Document::timeline()
+Animations::TimelineView Document::timeline()
+{
+ return Animations::TimelineView { *Animations::RustFFI::animations_document_timeline(this) };
+}
+
+// https://www.w3.org/TR/web-animations-1/#timeline-associated-with-a-document
+Vector<Animations::TimelineView> Document::associated_animation_timelines() const
{
- // The DocumentTimeline object representing the default document timeline. The default document timeline has an
- // origin time of zero.
- if (!m_default_timeline)
- m_default_timeline = Animations::AnimationTimeline::create_document_timeline(*this, 0.0);
- return *m_default_timeline;
+ Vector<Animations::TimelineView> timelines;
+ for (size_t index = 0;; ++index) {
+ auto const* timeline = Animations::RustFFI::animations_document_animations_timeline_at(m_animations, index);
+ if (!timeline)
+ return timelines;
+ timelines.append(Animations::TimelineView { *timeline });
+ }
}
-Animations::WeakAnimationSetView Document::animations_following_named_timelines()
+bool Document::update_named_timelines_of_animations(Animations::RustFFI::FfiNamedTimelinesHost const& host)
{
- return Animations::WeakAnimationSetView { *Animations::RustFFI::animations_document_animations_set(m_animations, Animations::RustFFI::DocumentAnimationSetKind::FollowingNamedTimelines) };
+ return Animations::RustFFI::animations_document_animations_update_named_timelines(m_animations, &host);
}
Animations::NamedTimelines& Document::named_timelines()
@@ -8687,16 +8497,6 @@ Animations::NamedTimelines& Document::named_timelines()
return *m_named_timelines;
}
-void Document::associate_with_timeline(GC::Ref<Animations::AnimationTimeline> timeline)
-{
- m_associated_animation_timelines.set(timeline);
-}
-
-void Document::disassociate_with_timeline(GC::Ref<Animations::AnimationTimeline> timeline)
-{
- m_associated_animation_timelines.remove(timeline);
-}
-
int Document::compare_elements_in_tree_order_for_composite_order(Element& first, Element& second)
{
// NB: Comparisons cost less than a walk of the document until enough of them have gone by at one version of the
@@ -8759,53 +8559,9 @@ void Document::keep_element_tree_positions_across_attribute_change(u64 version_b
m_element_tree_positions_dom_tree_version = dom_tree_version();
}
-void Document::associate_with_animation(Animations::AnimationRef const& animation)
-{
- associated_animations(m_animations).set(animation);
- if (m_style_stabilization_epoch_depth > 0)
- animations_created_in_stabilization_epoch(m_animations).set(animation);
-}
-
-void Document::disassociate_with_animation(Animations::AnimationRef const& animation, Optional<Animations::EffectRef> const& effect)
-{
- if (effect.has_value()) {
- effects_needing_animated_style_update(m_animations).remove(effect->record());
- effects_needing_animated_style_update_after_current_update(m_animations).remove(effect->record());
- }
- associated_animations(m_animations).remove(animation.record());
-}
-
bool Document::has_associated_animations() const
{
- return !associated_animations(m_animations).is_empty();
-}
-
-static bool is_transform_family_property(CSS::PropertyID property_id)
-{
- return first_is_one_of(property_id,
- CSS::PropertyID::Translate,
- CSS::PropertyID::Rotate,
- CSS::PropertyID::Scale,
- CSS::PropertyID::Transform);
-}
-
-// The keyframes the compositor animation builder reads of each effect an update pass asks about, which the pass keeps
-// alive with the elements they resolve against.
-struct CompositorAnimationKeyframesOfEffect {
- NonnullOwnPtr<Painting::CompositorAnimationKeyframes> keyframes;
-
- void visit_edges(GC::Cell::Visitor& visitor) const { keyframes->visit_edges(visitor); }
-};
-using CompositorAnimationKeyframesByEffect = GC::RootHashMap<Animations::RustFFI::AnimationEffectId, CompositorAnimationKeyframesOfEffect>;
-
-// The keyframes of an effect as the compositor animation builder reads them, built once for the
-// update pass however many animations and questions the pass takes from them.
-static Painting::CompositorAnimationKeyframes const& compositor_animation_keyframes(CompositorAnimationKeyframesByEffect& keyframes_by_effect, Animations::EffectRef const& effect, Animations::AnimationRef const& animation, DOM::AbstractElement target)
-{
- return *keyframes_by_effect.ensure(effect.id(), [&] {
- return CompositorAnimationKeyframesOfEffect { make<Painting::CompositorAnimationKeyframes>(effect, animation, target) };
- })
- .keyframes;
+ return Animations::RustFFI::animations_document_animations_query(m_animations, Animations::RustFFI::DocumentAnimationsQuery::AssociatedCount) != 0;
}
// Whether a box inside an SVG paints or places itself by its bounding box, which includes the transforms of the boxes
@@ -8879,878 +8635,576 @@ static bool svg_transform_may_run_on_the_compositor(Element const& target, Layou
return !has_non_scaling_stroke;
}
-// Builds the compositor animation of one target kind for an effect the compositor could drive, and
-// keeps it pending with the effect. The checks here are the ones that read the animation objects; the
-// builder in Rust lowers and validates the keyframes.
-static Painting::CompositorAnimationEffectState::BuildOutcome build_compositor_animation(Layout::BegunRead const& read, Animations::EffectRef const& effect, Compositing::RustFFI::FfiVisualAnimationTargetKind target_kind, CompositorAnimationKeyframesByEffect& keyframes_by_effect)
-{
- auto animation = effect.associated_animation();
- if (!animation.has_value())
- return {};
- // NB: The record decides whether the compositor may run the effect as far as its timing goes, and where its
- // animation is anchored.
- auto const state = animation->timing_state();
- if (state.compositor_anchor == Animations::RustFFI::FfiCompositorAnchorKind::None)
- return {};
- if (effect.target_properties().is_empty())
- return {};
-
- bool targets_opacity = target_kind == Compositing::RustFFI::FfiVisualAnimationTargetKind::Opacity && effect.target_properties().contains(CSS::PropertyNameAndID::from_id(CSS::PropertyID::Opacity));
- bool targets_background_color = target_kind == Compositing::RustFFI::FfiVisualAnimationTargetKind::BackgroundColor && effect.target_properties().contains(CSS::PropertyNameAndID::from_id(CSS::PropertyID::BackgroundColor));
- bool targets_filter = target_kind == Compositing::RustFFI::FfiVisualAnimationTargetKind::Filter && effect.target_properties().contains(CSS::PropertyNameAndID::from_id(CSS::PropertyID::Filter));
- bool targets_transform = target_kind == Compositing::RustFFI::FfiVisualAnimationTargetKind::Transform && any_of(effect.target_properties(), [](auto const& property) { return is_transform_family_property(property.id()); });
- if (!targets_opacity && !targets_background_color && !targets_filter && !targets_transform)
- return {};
- if (any_of(effect.target_properties(), [&](auto const& property) { return !first_is_one_of(property.id(), CSS::PropertyID::Opacity, CSS::PropertyID::BackgroundColor, CSS::PropertyID::Filter) && !is_transform_family_property(property.id()); }))
- return {};
- auto target = effect.target_abstract_element();
- if (!target.has_value())
- return {};
- if (target->element().namespace_uri() == Namespace::SVG) {
- auto const* layout_node = target->unsafe_layout_node(read);
- // NB: The compositor has no animations for the documents of SVG images.
- if (!layout_node || (!targets_transform && !targets_opacity && !targets_filter) || target->document().is_decoded_svg())
- return {};
- if (targets_transform && !svg_transform_may_run_on_the_compositor(target->element(), *layout_node))
- return {};
- }
- auto monotonic_time_at_anchor_ms = [&]() -> Optional<double> {
- if (state.compositor_anchor == Animations::RustFFI::FfiCompositorAnchorKind::OriginRelativeTime)
- return state.compositor_anchor_origin_relative_time + target->document().relevant_settings_object().time_origin();
- auto frame_timestamp = target->document().last_animation_frame_timestamp();
- if (!frame_timestamp.has_value())
- return {};
- return *frame_timestamp + target->document().relevant_settings_object().time_origin();
- }();
- if (!monotonic_time_at_anchor_ms.has_value())
- return {};
- auto const* layout_node = target->unsafe_layout_node(read);
- if (!layout_node)
- return {};
- if (targets_transform) {
- if ((!effect.target_properties().contains(CSS::PropertyNameAndID::from_id(CSS::PropertyID::Translate)) && layout_node->has_translate())
- || (!effect.target_properties().contains(CSS::PropertyNameAndID::from_id(CSS::PropertyID::Rotate)) && layout_node->has_rotate())
- || (!effect.target_properties().contains(CSS::PropertyNameAndID::from_id(CSS::PropertyID::Scale)) && layout_node->has_scale())
- || (!effect.target_properties().contains(CSS::PropertyNameAndID::from_id(CSS::PropertyID::Transform)) && layout_node->has_transformations())
- || layout_node->transform_origin().z.to_px(CSSPixels { 0 }) != CSSPixels { 0 })
- return {};
+// What the document answers and keeps for one compositor animation update, which the animation records in Rust ask it
+// of through their host.
+struct CompositorAnimationUpdatePass {
+ CompositorAnimationUpdatePass(Document& document, Layout::BegunRead const& read)
+ : document(document)
+ , read(read)
+ {
}
- auto row = Painting::committed_row(*layout_node);
- if (!row.has_value())
- return {};
- auto const& keyframe_set = effect.keyframe_set();
- if (!keyframe_set || keyframe_set.keyframe_count() < 2)
- return {};
+ GC::Ref<Document> document;
+ Layout::BegunRead const& read;
+ Layout::RustFFI::FfiViewportMapping viewport_mapping {};
+ GC::RootVector<Animations::AnimationRef> animations;
+ GC::RootHashMap<GC::Ref<Layout::Node>, bool> previous_content_retention;
+ GC::RootHashTable<GC::Ref<Layout::Node>> retained_this_pass;
+ GC::RootHashMap<GC::Ptr<Element>, CSSPixelRect> observation_target_rect_cache;
+ GC::RootHashTable<GC::Ref<Element>> elements_with_intersection_observation_descendants;
+ GC::RootHashTable<GC::Ref<Element>> elements_with_visibility_observation_descendants;
+ Vector<Compositing::RustFFI::NodeSlotId> layout_nodes_with_stale_forced_effects_layer;
+ Vector<Compositing::RustFFI::NodeSlotId> layout_nodes_with_stale_forced_background_color_frame;
+ // The target the keyframes of the compositor animation being built resolve their values against.
+ Optional<AbstractElement> keyframe_target;
- auto const& keyframes = compositor_animation_keyframes(keyframes_by_effect, effect, *animation, *target);
- Painting::CompositorAnimationEffectState::TimingAnchor timing_anchor {
- .monotonic_time_ms = *monotonic_time_at_anchor_ms,
- .local_time_ms = state.compositor_anchor_local_time,
- };
- return effect.compositor_animation_state().build(read, keyframes, *layout_node, target_kind, timing_anchor);
-}
+ static CompositorAnimationUpdatePass& of(void* context) { return *static_cast<CompositorAnimationUpdatePass*>(context); }
-// The local time of the next iteration event of a CSS animation whose ticks are throttled, whose timing is `state`.
-static Optional<double> next_throttled_animation_iteration_event_time(Animations::RustFFI::FfiAnimationTimingState const& state, Animations::EffectRef const& effect)
-{
- // NB: The record decides this as far as the timing goes.
- if (!state.next_throttled_iteration_event_time.has_value
- || !effect.can_skip_per_frame_style_update()
- || state.phase != Animations::RustFFI::AnimationEffectPhase::Active)
- return {};
- return state.next_throttled_iteration_event_time.value;
-}
+ static AbstractElement target_of(Animations::RustFFI::FfiCompositorTarget const& target)
+ {
+ return AbstractElement {
+ *static_cast<Element*>(target.element),
+ target.has_pseudo_element ? Optional<CSS::PseudoElement> { static_cast<CSS::PseudoElement>(target.pseudo_element) } : Optional<CSS::PseudoElement> {},
+ };
+ }
-void Document::schedule_compositor_animation_wakeup(double delay_ms)
-{
- auto timer_delay_ms = static_cast<int>(ceil(clamp(delay_ms, 1.0, static_cast<double>(NumericLimits<int>::max()))));
- auto deadline = MonotonicTime::now() + AK::Duration::from_milliseconds(timer_delay_ms);
- if (m_compositor_animation_wakeup_timer && m_compositor_animation_wakeup_timer->is_active()
- && m_compositor_animation_wakeup_deadline.has_value() && *m_compositor_animation_wakeup_deadline <= deadline)
- return;
+ Layout::Node* node(Compositing::RustFFI::NodeSlotId slot) const { return document->layout_node_arena().node_if_live(read, slot); }
- m_compositor_animation_wakeup_deadline = deadline;
- if (!m_compositor_animation_wakeup_timer) {
- m_compositor_animation_wakeup_timer = Core::Timer::create_single_shot(AK::Duration::from_milliseconds(static_cast<int>(timer_delay_ms)), GC::weak_callback(*this, [](auto& document) {
- // Cancelling a finite effect can leave this deadline armed. The single wake-up is harmless: it finds
- // nothing due and leaves the timer idle unless another effect supplies a deadline.
- document.m_compositor_animation_wakeup_deadline.clear();
- auto timestamp = HighResolutionTime::relative_high_resolution_time(
- HighResolutionTime::unsafe_shared_current_time(), document.relevant_settings_object().global_object());
- document.service_compositor_animation_wakeup(timestamp);
- }));
+ Vector<Compositing::RustFFI::NodeSlotId>& forced_frames(Animations::RustFFI::FfiCompositorFrameKind kind) const
+ {
+ return kind == Animations::RustFFI::FfiCompositorFrameKind::EffectsLayer ? document->m_layout_nodes_with_forced_compositor_effects_layer : document->m_layout_nodes_with_forced_compositor_background_color_frame;
}
- m_compositor_animation_wakeup_timer->restart(AK::Duration::from_milliseconds(static_cast<int>(timer_delay_ms)));
-}
-void Document::service_compositor_animation_wakeup(double timestamp)
-{
- Optional<double> next_wakeup_delay_ms;
- bool reached_wakeup = false;
- bool reached_compositor_active_start = false;
- for (auto const& animation : associated_animations(m_animations)) {
- auto associated_effect = animation.effect();
- if (!associated_effect.has_value())
- continue;
- auto const& effect = *associated_effect;
- auto const state = animation.timing_state_at_timestamp(timestamp);
- auto current_time = Animations::from_ffi(state.current_time_at_timestamp);
- if (!current_time.has_value() || current_time->type != Animations::TimeValue::Type::Milliseconds)
- continue;
- auto const& timing = state.effect;
- auto const playback_rate = state.playback.playback_rate;
- bool is_compositor_handled = effect.is_compositor_driven()
- || effect.is_compositor_replaced()
- || effect.has_retained_compositor_animations();
- if (!state.playback.has_pending_play_task && !state.playback.has_pending_pause_task
- && playback_rate > 0
- && timing.start_delay.type == Animations::TimeValue::Type::Milliseconds
- && state.phase == Animations::RustFFI::AnimationEffectPhase::Before) {
- if (current_time->value < timing.start_delay.value) {
- auto delay = (timing.start_delay.value - current_time->value) / playback_rate;
- if (!next_wakeup_delay_ms.has_value() || delay < *next_wakeup_delay_ms)
- next_wakeup_delay_ms = delay;
- } else {
- effect.request_observation_sample();
- reached_wakeup = true;
- if (is_compositor_handled)
- reached_compositor_active_start = true;
- }
- }
- if (auto iteration_event_time = next_throttled_animation_iteration_event_time(state, effect);
- iteration_event_time.has_value() && !effect.can_skip_per_frame_animation_tick()) {
- if (current_time->value < *iteration_event_time) {
- auto delay = (*iteration_event_time - current_time->value) / playback_rate;
- if (!next_wakeup_delay_ms.has_value() || delay < *next_wakeup_delay_ms)
- next_wakeup_delay_ms = delay;
- } else {
- reached_wakeup = true;
- }
- }
- bool is_offscreen_handled = effect.is_offscreen_throttled() && effect.can_skip_per_frame_style_update();
- if ((!is_compositor_handled && !is_offscreen_handled) || isinf(timing.iteration_count))
- continue;
- auto active_end = timing.start_delay.value + timing.iteration_duration.value * timing.iteration_count;
- if (current_time->value < active_end) {
- auto delay = (active_end - current_time->value) / playback_rate;
- if (!next_wakeup_delay_ms.has_value() || delay < *next_wakeup_delay_ms)
- next_wakeup_delay_ms = delay;
- continue;
- }
- effect.request_observation_sample();
- reached_wakeup = true;
+ Vector<Compositing::RustFFI::NodeSlotId>& stale_forced_frames(Animations::RustFFI::FfiCompositorFrameKind kind)
+ {
+ return kind == Animations::RustFFI::FfiCompositorFrameKind::EffectsLayer ? layout_nodes_with_stale_forced_effects_layer : layout_nodes_with_stale_forced_background_color_frame;
}
- if (next_wakeup_delay_ms.has_value())
- schedule_compositor_animation_wakeup(*next_wakeup_delay_ms);
- if (reached_wakeup) {
- if (reached_compositor_active_start) {
- Layout::ForcedReadScope read { *this };
- paint_state().republish_visual_animations(read);
- }
- HTML::note_rendering_trace_event("animation frame pump request"sv);
- set_rendering_pending(*this, RenderingPendingReason::NeedsRenderingUpdate, 1);
- page().client().request_frame_for(*this);
+
+ bool transform_subtree_is_clipped_outside(Element const& animated_target, CSSPixelRect const& root_bounds) const
+ {
+ auto const* layout_node = animated_target.unsafe_layout_node(read);
+ if (!layout_node)
+ return false;
+ return Layout::RustFFI::layout_script_transform_subtree_is_clipped_outside(
+ layout_node->document_host(), Layout::Node::slot_id(layout_node), root_bounds,
+ viewport_mapping);
}
-}
-void Document::fire_compositor_animation_wakeup_for_testing(Badge<Internals::Internals>, double frame_time_ms)
-{
- if (m_compositor_animation_wakeup_timer)
- m_compositor_animation_wakeup_timer->stop();
- m_compositor_animation_wakeup_deadline.clear();
- service_compositor_animation_wakeup(relevant_settings_object().time_origin() + frame_time_ms);
-}
+ static Compositing::RustFFI::NodeSlotId layout_node(void* context, Animations::RustFFI::FfiCompositorTarget target)
+ {
+ return Layout::Node::slot_id(target_of(target).unsafe_layout_node(of(context).read));
+ }
-void Document::force_visual_context_tree_rebuild_on_next_compositor_animation_update_for_testing(Badge<Internals::Internals>)
-{
- m_force_visual_context_tree_rebuild_on_next_compositor_animation_update_for_testing = true;
-}
+ static void note_target_layout_node(void* context, Compositing::RustFFI::NodeSlotId slot)
+ {
+ auto& pass = of(context);
+ if (auto* layout_node = pass.node(slot))
+ pass.previous_content_retention.ensure(*layout_node, [&] { return layout_node->retains_compositor_animated_content(); });
+ }
-void Document::update_compositor_animations(Layout::BegunRead const& read)
-{
- struct CompetingPropertyEffects {
- Optional<Animations::EffectRef> winner;
- bool all_effects_use_replace { true };
- u32 effect_count { 0 };
+ static void note_retained_layout_node(void* context, Compositing::RustFFI::NodeSlotId slot)
+ {
+ auto& pass = of(context);
+ if (auto* layout_node = pass.node(slot))
+ pass.retained_this_pass.set(*layout_node);
+ }
- void visit_edges(GC::Cell::Visitor& visitor)
- {
- if (winner.has_value())
- winner->visit_edges(visitor);
- }
- };
- struct CompetingEffects {
- CompetingPropertyEffects opacity;
- CompetingPropertyEffects background_color;
- CompetingPropertyEffects filter;
- CompetingPropertyEffects transform;
+ static bool visibility_is_observed(void* context, void* element)
+ {
+ return of(context).elements_with_visibility_observation_descendants.contains(*static_cast<Element*>(element));
+ }
- void visit_edges(GC::Cell::Visitor& visitor)
- {
- opacity.visit_edges(visitor);
- background_color.visit_edges(visitor);
- filter.visit_edges(visitor);
- transform.visit_edges(visitor);
- }
- };
+ static void const* resolved_keyframe_value(void* context, u16 property_id, void const* declared_value);
+ static bool prepare_compositor_animation(void* context, Animations::RustFFI::FfiCompositorAnimationPreparation const* preparation, void* request, void* keyframe_host);
+ static bool paint_is_offscreen(void* context, Animations::RustFFI::FfiCompositorTarget target, Animations::RustFFI::FfiOffscreenPaintQuery const* query);
+ static bool transform_affects_intersection_observation(void* context, void* animated_target, Animations::RustFFI::FfiTransformObservationQuery const* query, bool* requires_main_thread_sampling);
- auto animation_pass_viewport_mapping = Painting::viewport_mapping(*this);
- paint_state().begin_compositor_animation_update();
- GC::RootHashMap<GC::Ref<Layout::Node>, bool> previous_content_retention;
- GC::RootHashTable<GC::Ref<Layout::Node>> retained_this_pass;
- HashTable<Animations::RustFFI::AnimationEffectId> previously_compositor_driven_effects;
- HashTable<Animations::RustFFI::AnimationEffectId> previously_compositor_replaced_effects;
- HashTable<Animations::RustFFI::AnimationEffectId> previously_published_effects;
- HashTable<Animations::RustFFI::AnimationEffectId> previously_offscreen_throttled_effects;
- GC::RootHashMap<DOM::AbstractElement, CompetingEffects> competing_effects;
- CompositorAnimationKeyframesByEffect keyframes_by_effect;
- HashMap<Animations::RustFFI::AnimationEffectId, bool> only_translates_horizontally_cache;
- HashMap<Animations::RustFFI::AnimationEffectId, bool> animated_transform_preserves_axes_cache;
- HashMap<Layout::Node const*, GC::RootVector<Animations::EffectRef>> in_effect_transform_effects_by_layout_node;
- GC::RootHashMap<GC::Ptr<Element>, CSSPixelRect> observation_target_rect_cache;
- GC::RootHashTable<GC::Ref<Element>> elements_with_intersection_observation_descendants;
- GC::RootHashTable<GC::Ref<Element>> elements_with_visibility_observation_descendants;
- auto layout_nodes_with_stale_forced_effects_layer = move(m_layout_nodes_with_forced_compositor_effects_layer);
- auto layout_nodes_with_stale_forced_background_color_frame = move(m_layout_nodes_with_forced_compositor_background_color_frame);
- Optional<double> compositor_animation_wakeup_delay_ms;
+ static bool transform_subtree_is_clipped_outside_viewport(void* context, void* element)
+ {
+ auto& pass = of(context);
+ auto viewport_bounds = CSSPixelRect { { 0, 0 }, pass.document->viewport_rect().size() };
+ return pass.transform_subtree_is_clipped_outside(*static_cast<Element*>(element), viewport_bounds);
+ }
- auto index_shadow_including_element_ancestors = [](Node& node, GC::RootHashTable<GC::Ref<Element>>& index) {
- for (auto* ancestor = &node; ancestor; ancestor = ancestor->parent_or_shadow_host()) {
- if (auto* element = as_if<Element>(*ancestor))
- index.set(*element);
- }
- };
- for (auto const& observer : m_intersection_observers) {
- if (observer.observation_targets().is_empty())
- continue;
- auto root = observer.intersection_root_node();
- if (root->is_element())
- index_shadow_including_element_ancestors(*root, elements_with_intersection_observation_descendants);
- for (auto const& observation : observer.observation_targets()) {
- auto target = observation.target.ptr();
- if (!target)
- continue;
- index_shadow_including_element_ancestors(*target, elements_with_intersection_observation_descendants);
- if (observer.track_visibility())
- index_shadow_including_element_ancestors(*target, elements_with_visibility_observation_descendants);
- }
+ static bool background_color_can_be_compositor_animated(void* context, Compositing::RustFFI::NodeSlotId slot)
+ {
+ auto* layout_node = of(context).node(slot);
+ return layout_node && Painting::rust_background_color_can_be_compositor_animated(*layout_node);
}
- auto transform_preserves_horizontal_axis = [](Layout::NodeWithStyle const& layout_node) {
- if (layout_node.perspective().has_value())
+ static bool request_frame(void* context, Compositing::RustFFI::NodeSlotId slot, Animations::RustFFI::FfiCompositorFrameKind kind)
+ {
+ auto& pass = of(context);
+ auto* layout_node = pass.node(slot);
+ if (!layout_node)
return false;
-
- auto matrix = Gfx::FloatMatrix4x4::identity();
- auto reference_box = Painting::transform_reference_box(layout_node);
- layout_node.for_each_resolved_transform([&](auto const& transform) {
- matrix = matrix * transform.to_matrix(reference_box.width(), reference_box.height());
- });
-
- constexpr auto epsilon = AK::NumericLimits<float>::epsilon();
- return abs(matrix[1, 0]) <= epsilon
- && abs(matrix[2, 0]) <= epsilon
- && abs(matrix[3, 0]) <= epsilon;
- };
-
- auto animated_transform_preserves_axes = [&](Animations::EffectRef const& effect, Layout::Node const& layout_node) {
- return animated_transform_preserves_axes_cache.ensure(effect.id(), [&] {
- if (effect.target_properties().contains(CSS::PropertyNameAndID::from_id(CSS::PropertyID::Rotate)))
+ if (kind == Animations::RustFFI::FfiCompositorFrameKind::EffectsLayer) {
+ if (layout_node->needs_compositor_effects_layer())
return false;
- if (!effect.target_properties().contains(CSS::PropertyNameAndID::from_id(CSS::PropertyID::Transform)))
- return true;
- auto animation = effect.associated_animation();
- auto target = effect.target_abstract_element();
- if (!animation.has_value() || !target.has_value() || !effect.keyframe_set())
+ layout_node->set_needs_compositor_effects_layer(true);
+ } else {
+ if (layout_node->needs_compositor_background_color_frame())
return false;
- return compositor_animation_keyframes(keyframes_by_effect, effect, *animation, *target).transform_preserves_axes(layout_node);
- });
- };
-
- auto ancestor_transform_can_map_horizontal_motion_to_vertical = [&](Element const& animated_target, Node const& observation_root) {
- auto const* layout_node = animated_target.unsafe_layout_node(read);
- if (!layout_node)
- return true;
- for (auto const* ancestor = layout_node->parent(); ancestor; ancestor = ancestor->parent()) {
- if (ancestor->has_css_transform() && !transform_preserves_horizontal_axis(*ancestor))
- return true;
- if (auto effects = in_effect_transform_effects_by_layout_node.find(ancestor); effects != in_effect_transform_effects_by_layout_node.end()) {
- for (auto const& effect : effects->value) {
- if (!animated_transform_preserves_axes(effect, *ancestor))
- return true;
- }
- }
- if (ancestor->dom_node() == &observation_root)
- break;
+ layout_node->set_needs_compositor_background_color_frame(true);
}
- return false;
- };
+ pass.document->schedule_accumulated_visual_context_update(*layout_node, Document::AccumulatedVisualContextUpdateScope::Structure);
+ CSS::RequiredInvalidationAfterStyleChange invalidation;
+ invalidation.ensure_at_least(CSS::InvalidationLevel::Repaint);
+ Painting::repaint_after_style_change(*layout_node, invalidation);
+ return true;
+ }
- auto transform_subtree_is_clipped_outside = [&animation_pass_viewport_mapping, &read](Element const& animated_target, CSSPixelRect const& root_bounds) {
- auto const* layout_node = animated_target.unsafe_layout_node(read);
- if (!layout_node)
- return false;
- return Layout::RustFFI::layout_script_transform_subtree_is_clipped_outside(
- layout_node->document_host(), Layout::Node::slot_id(layout_node), root_bounds,
- animation_pass_viewport_mapping);
+ static void keep_frame(void* context, Compositing::RustFFI::NodeSlotId slot, Animations::RustFFI::FfiCompositorFrameKind kind)
+ {
+ auto& pass = of(context);
+ auto& forced = pass.forced_frames(kind);
+ if (!any_of(forced, [&](auto forced_slot) { return forced_slot.index == slot.index; }))
+ forced.append(slot);
+ pass.stale_forced_frames(kind).remove_first_matching([&](auto stale_slot) {
+ return stale_slot.index == slot.index;
+ });
+ }
+
+ static bool frame_was_kept(void* context, Compositing::RustFFI::NodeSlotId slot, Animations::RustFFI::FfiCompositorFrameKind kind)
+ {
+ return any_of(of(context).stale_forced_frames(kind), [&](auto stale_slot) {
+ return stale_slot.index == slot.index;
+ });
+ }
+
+ static void refresh_viewport_mapping(void* context)
+ {
+ auto& pass = of(context);
+ pass.viewport_mapping = Painting::viewport_mapping(pass.document);
+ }
+
+ static void note_throttled_animation_style_update(void* context)
+ {
+ of(context).document->note_throttled_animation_style_update();
+ }
+
+ static void keep_alive(void* context, Animations::RustFFI::AnimationCell const* animation)
+ {
+ Animations::keep_animation_alive_in(&of(context).animations, animation);
+ }
+};
+
+static RefPtr<CSS::StyleValue const> resolved_compositor_animation_style_value(Layout::BegunRead const& read, CSS::PropertyID property_id, CSS::StyleValueFFI::StyleValueData const* value, AbstractElement target)
+{
+ HTML::note_rendering_trace_event("compositor keyframe values resolved"sv);
+ auto style_value = CSS::StyleValue::adopt_rust_style_value_data(CSS::StyleValueFFI::rust_style_value_retain(value));
+ if (style_value->is_unresolved()) {
+ // The engine substitutes the value as a sample on the main thread would, against the custom properties the
+ // element holds and inherits.
+ auto custom_property_data = target.custom_property_data();
+ auto inheritance_parent = target.element_to_inherit_style_from();
+ auto inheritance_custom_property_data = inheritance_parent.has_value() ? inheritance_parent->custom_property_data() : nullptr;
+ auto const* substituted = CSS::StyleValueFFI::rust_substitute_compositor_keyframe_value(
+ target.document().style_computer().style_engine().host(),
+ &read, target.element().style_node_id().value(),
+ CSS::pseudo_element_to_ffi(target.pseudo_element()),
+ custom_property_data ? custom_property_data->rust_store() : nullptr,
+ inheritance_custom_property_data ? inheritance_custom_property_data->rust_store() : nullptr,
+ to_underlying(property_id),
+ value);
+ if (!substituted)
+ return nullptr;
+ style_value = CSS::StyleValue::adopt_rust_style_value_data(substituted);
+ }
+ if (style_value->is_guaranteed_invalid() || style_value->is_unresolved() || style_value->is_pending_substitution())
+ return nullptr;
+ // Absolutizing against the target's used color-scheme collapses light-dark() as computing the value would, so
+ // the color the builder resolves needs no length context.
+ auto const* inherited_ui_values = target.style_group<CSS::ComputedValues::InheritedUIValues>();
+ CSS::ComputationContext computation_context {
+ .length_resolution_context = CSS::Length::ResolutionContext::for_element(target),
+ .abstract_element = target,
+ .color_scheme = inherited_ui_values ? inherited_ui_values->color_scheme_value() : Optional<CSS::PreferredColorScheme> {},
};
+ return style_value->absolutized(computation_context);
+}
- auto paint_only_effect_is_offscreen = [&](Animations::EffectRef const& effect, AbstractElement abstract_target) {
- auto& target = abstract_target.element();
- bool is_svg_target = target.namespace_uri() == Namespace::SVG;
- if (abstract_target.pseudo_element().has_value()
- && !first_is_one_of(*abstract_target.pseudo_element(), CSS::PseudoElement::Before, CSS::PseudoElement::After))
- return false;
- if ((!is_svg_target && target.namespace_uri() != Namespace::HTML)
- || target.is_document_element() || &target == body())
- return false;
+void const* CompositorAnimationUpdatePass::resolved_keyframe_value(void* context, u16 property_id, void const* declared_value)
+{
+ auto& pass = of(context);
+ auto target = *pass.keyframe_target;
+ auto property = static_cast<CSS::PropertyID>(property_id);
+ RefPtr<CSS::StyleValue const> style_value;
+ if (!declared_value) {
+ // NB: Synthesized endpoints use the underlying style, just as main-thread keyframe sampling does.
+ auto computed_style = target.computed_style();
+ if (!computed_style)
+ return nullptr;
+ style_value = computed_style->computed_style_value(property, CSS::ComputedValues::WithAnimationsApplied::No);
+ } else {
+ style_value = resolved_compositor_animation_style_value(pass.read, property, static_cast<CSS::StyleValueFFI::StyleValueData const*>(declared_value), target);
+ }
+ if (!style_value)
+ return nullptr;
+ return CSS::StyleValueFFI::rust_style_value_retain(style_value->rust_style_value_data());
+}
- // NB: Only properties whose changes are confined to painting are eligible. In particular, color can
- // affect SVG stroke geometry, and transforms can affect layout. Filters require an ancestor clip.
- bool paint_stays_within_border_box = true;
- for (auto const& property : effect.target_properties()) {
- if (is_svg_target && property.id() != CSS::PropertyID::Opacity)
+bool CompositorAnimationUpdatePass::prepare_compositor_animation(void* context, Animations::RustFFI::FfiCompositorAnimationPreparation const* preparation, void* request_pointer, void* keyframe_host)
+{
+ auto& pass = of(context);
+ auto target = target_of(preparation->target);
+ auto* layout_node = as_if<Layout::NodeWithStyle>(pass.node(preparation->layout_node));
+ if (!layout_node)
+ return false;
+ auto target_kind = static_cast<Compositing::RustFFI::FfiVisualAnimationTargetKind>(preparation->target_kind);
+ bool targets_transform = target_kind == Compositing::RustFFI::FfiVisualAnimationTargetKind::Transform;
+ if (preparation->checked) {
+ if (target.element().namespace_uri() == Namespace::SVG) {
+ // NB: The compositor has no animations for the documents of SVG images.
+ if (target_kind == Compositing::RustFFI::FfiVisualAnimationTargetKind::BackgroundColor || target.document().is_decoded_svg())
return false;
- switch (property.id()) {
- case CSS::PropertyID::BackgroundColor:
- // NB: Keyframes containing var() retain the shorthand until substitution.
- case CSS::PropertyID::BackgroundPosition:
- case CSS::PropertyID::BackgroundPositionX:
- case CSS::PropertyID::BackgroundPositionY:
- case CSS::PropertyID::BackgroundSize:
- case CSS::PropertyID::BackgroundRepeat:
- case CSS::PropertyID::BackgroundOrigin:
- case CSS::PropertyID::BackgroundClip:
- case CSS::PropertyID::BackgroundBlendMode:
- case CSS::PropertyID::BorderTopColor:
- case CSS::PropertyID::BorderRightColor:
- case CSS::PropertyID::BorderBottomColor:
- case CSS::PropertyID::BorderLeftColor:
- break;
- case CSS::PropertyID::Opacity:
- if (elements_with_visibility_observation_descendants.contains(target))
- return false;
- paint_stays_within_border_box = false;
- break;
- case CSS::PropertyID::Filter:
- case CSS::PropertyID::BoxShadow:
- case CSS::PropertyID::OutlineColor:
- case CSS::PropertyID::OutlineOffset:
- case CSS::PropertyID::OutlineStyle:
- case CSS::PropertyID::OutlineWidth:
- case CSS::PropertyID::TextDecorationColor:
- case CSS::PropertyID::TextDecorationStyle:
- case CSS::PropertyID::TextDecorationThickness:
- paint_stays_within_border_box = false;
- break;
- default:
+ if (targets_transform && !svg_transform_may_run_on_the_compositor(target.element(), *layout_node))
return false;
- }
}
-
- auto const* layout_node = abstract_target.unsafe_layout_node(read);
- if (!layout_node || !layout_node->is_box())
- return false;
-
- // NB: SVG resources and referenced subtrees can be painted outside their own ancestor clips.
- // Restrict this proof to unreferenced graphics in an ordinary SVG tree.
- auto svg_element_can_be_painted_elsewhere = [](SVG::SVGElement const& element) {
- return element.id().has_value()
- || !element.local_name().is_one_of(SVG::TagNames::svg, SVG::TagNames::g,
- SVG::TagNames::circle, SVG::TagNames::ellipse, SVG::TagNames::rect,
- SVG::TagNames::path, SVG::TagNames::line, SVG::TagNames::polygon, SVG::TagNames::polyline);
- };
- for (auto const* ancestor = static_cast<Node const*>(&target); ancestor; ancestor = ancestor->parent_or_shadow_host()) {
- auto const* element = as_if<SVG::SVGElement>(ancestor);
- if (element && svg_element_can_be_painted_elsewhere(*element))
+ if (targets_transform) {
+ auto targets = [&](u8 property) { return (preparation->targeted_transform_properties & property) != 0; };
+ if ((!targets(Layout::RustFFI::TARGETED_TRANSFORM_PROPERTY_TRANSLATE) && layout_node->has_translate())
+ || (!targets(Layout::RustFFI::TARGETED_TRANSFORM_PROPERTY_ROTATE) && layout_node->has_rotate())
+ || (!targets(Layout::RustFFI::TARGETED_TRANSFORM_PROPERTY_SCALE) && layout_node->has_scale())
+ || (!targets(Layout::RustFFI::TARGETED_TRANSFORM_PROPERTY_TRANSFORM) && layout_node->has_transformations())
+ || layout_node->transform_origin().z.to_px(CSSPixels { 0 }) != CSSPixels { 0 })
return false;
}
- if (is_svg_target && layout_node->has_children())
+ if (!Painting::committed_row(*layout_node).has_value())
return false;
+ }
- // NB: A descendant can explicitly inherit even a normally non-inherited paint property. Reject
- // content that can escape ancestor clips or be rendered elsewhere through SVG references.
- bool can_include_svg_descendants = all_of(effect.target_properties(), [](auto const& property) {
- return first_is_one_of(property.id(), CSS::PropertyID::Opacity, CSS::PropertyID::Filter);
- });
- bool subtree_can_escape = false;
- layout_node->for_each_in_inclusive_subtree_of_type<Layout::NodeWithStyle>([&](auto const& descendant) {
- if (descendant.is_svg_box()) {
- auto const* element = as_if<SVG::SVGElement>(descendant.dom_node());
- if (!can_include_svg_descendants || !element || svg_element_can_be_painted_elsewhere(*element)) {
- subtree_can_escape = true;
- return TraversalDecision::Break;
- }
- }
- if (descendant.is_fixed_position()
- || (&descendant != layout_node && descendant.is_absolutely_positioned())) {
- subtree_can_escape = true;
- return TraversalDecision::Break;
- }
- return TraversalDecision::Continue;
- });
- if (subtree_can_escape)
- return false;
-
- auto viewport_bounds = CSSPixelRect { { 0, 0 }, viewport_rect().size() };
- auto const& viewport_mapping = animation_pass_viewport_mapping;
- auto bounds_in_viewport = [&](Layout::Node const& node) -> CSSPixelRect {
- CSSPixelRect rect;
- Layout::RustFFI::layout_script_bounding_client_rect(
- node.document_host(), Layout::Node::slot_id(&node), viewport_mapping, &rect);
- return rect;
- };
- HashTable<Layout::Node const*> containing_blocks;
- for (auto const* container = layout_node->containing_block(); container; container = container->containing_block())
- containing_blocks.set(container);
-
- auto visible_bounds = viewport_bounds;
- for (auto const* ancestor = layout_node; ancestor; ancestor = ancestor->parent()) {
- bool can_move_or_expand_paint = ancestor->has_css_transform() || ancestor->perspective().has_value()
- || ancestor->is_sticky_position() || ancestor->filter().has_filters()
- || in_effect_transform_effects_by_layout_node.contains(ancestor);
- if (auto const* element = as_if<Element>(ancestor->dom_node())) {
- if (auto effects = competing_effects.get(*element); effects.has_value() && effects->filter.winner.has_value())
- can_move_or_expand_paint = true;
- }
- if (can_move_or_expand_paint) {
- // NB: A transform or filter outside a clip can bring its paint into view. A later, outer clip
- // can still prove that the entire transformed or filtered subtree remains offscreen.
- visible_bounds = viewport_bounds;
- paint_stays_within_border_box = false;
- continue;
- }
- if (!containing_blocks.contains(ancestor) || ancestor->is_svg_box())
- continue;
- if (ancestor->overflow_x() == CSS::Overflow::Visible || ancestor->overflow_y() == CSS::Overflow::Visible)
- continue;
- if (ancestor->overflow_x() == CSS::Overflow::Clip || ancestor->overflow_y() == CSS::Overflow::Clip) {
- auto const& margin = ancestor->style_group<CSS::ComputedValues::MiscLayoutValues>().overflow_clip_margin;
- if (margin.top.offset != 0 || margin.right.offset != 0 || margin.bottom.offset != 0 || margin.left.offset != 0)
- continue;
- }
- visible_bounds = visible_bounds.intersected(bounds_in_viewport(*ancestor));
- }
- if (visible_bounds.is_empty())
- return true;
-
- // NB: Otherwise, only a leaf box with bounded paint can be proven invisible from its own bounds.
- return paint_stays_within_border_box && !layout_node->has_children()
- && !bounds_in_viewport(*layout_node).intersects(visible_bounds);
+ auto& request = *static_cast<Layout::RustFFI::FfiCompositorAnimationRequest*>(request_pointer);
+ auto target_color_resolution_style = CSS::ColorResolutionStyle::for_element(target);
+ request.target_inherited_ui_values = target_color_resolution_style.inherited_ui_values;
+ request.target_inherited_text_values = target_color_resolution_style.inherited_text_values;
+ request.target_style_generation = target.element().animation_style_generation();
+ request.style_environment_version = target.document().style_computer().style_environment_version_for_sharing();
+ if (targets_transform) {
+ auto reference_box_size = Painting::transform_reference_box(*layout_node).size();
+ request.reference_box_width = reference_box_size.width().to_float();
+ request.reference_box_height = reference_box_size.height().to_float();
+ }
+ request.device_pixels_per_css_pixel = static_cast<float>(target.document().page().client().device_pixels_per_css_pixel());
+ pass.keyframe_target = target;
+ *static_cast<Layout::RustFFI::FfiCompositorAnimationHost*>(keyframe_host) = {
+ .context = &pass,
+ .resolved_keyframe_value = resolved_keyframe_value,
};
+ return true;
+}
- auto observation_has_another_transform_animation = [&](Element const& animated_target, Element const& observation_target, Animations::EffectRef const& current_effect) {
- for (auto const& animation : associated_animations(m_animations)) {
- auto effect = animation.effect();
- if (!effect.has_value())
- continue;
- auto const state = animation.timing_state();
- if (state.play_state == Animations::RustFFI::AnimationPlayState::Idle)
- continue;
- if (*effect == current_effect || !state.is_in_effect)
- continue;
- auto* effect_target = effect->target();
- if (!effect_target || !animated_target.is_shadow_including_inclusive_ancestor_of(*effect_target)
- || !effect_target->is_shadow_including_inclusive_ancestor_of(observation_target))
- continue;
- if (any_of(effect->target_properties(), [](auto const& property) { return is_transform_family_property(property.id()); }))
- return true;
- }
+bool CompositorAnimationUpdatePass::paint_is_offscreen(void* context, Animations::RustFFI::FfiCompositorTarget ffi_target, Animations::RustFFI::FfiOffscreenPaintQuery const* query)
+{
+ auto& pass = of(context);
+ auto& document = *pass.document;
+ auto abstract_target = target_of(ffi_target);
+ auto& target = abstract_target.element();
+ bool is_svg_target = target.namespace_uri() == Namespace::SVG;
+ if (abstract_target.pseudo_element().has_value()
+ && !first_is_one_of(*abstract_target.pseudo_element(), CSS::PseudoElement::Before, CSS::PseudoElement::After))
+ return false;
+ if ((!is_svg_target && target.namespace_uri() != Namespace::HTML)
+ || target.is_document_element() || &target == document.body())
+ return false;
+ if (is_svg_target && !query->targets_only_opacity)
+ return false;
+ if (query->targets_opacity && pass.elements_with_visibility_observation_descendants.contains(target))
+ return false;
+ bool paint_stays_within_border_box = query->paint_stays_within_border_box;
+
+ auto const* layout_node = abstract_target.unsafe_layout_node(pass.read);
+ if (!layout_node || !layout_node->is_box())
return false;
- };
- auto transform_affects_intersection_observation = [&](Element& animated_target, Animations::EffectRef const& effect, bool only_translates_horizontally, bool& requires_main_thread_sampling) {
- if (!elements_with_intersection_observation_descendants.contains(animated_target))
+ // NB: SVG resources and referenced subtrees can be painted outside their own ancestor clips.
+ // Restrict this proof to unreferenced graphics in an ordinary SVG tree.
+ auto svg_element_can_be_painted_elsewhere = [](SVG::SVGElement const& element) {
+ return element.id().has_value()
+ || !element.local_name().is_one_of(SVG::TagNames::svg, SVG::TagNames::g,
+ SVG::TagNames::circle, SVG::TagNames::ellipse, SVG::TagNames::rect,
+ SVG::TagNames::path, SVG::TagNames::line, SVG::TagNames::polygon, SVG::TagNames::polyline);
+ };
+ for (auto const* ancestor = static_cast<Node const*>(&target); ancestor; ancestor = ancestor->parent_or_shadow_host()) {
+ auto const* element = as_if<SVG::SVGElement>(ancestor);
+ if (element && svg_element_can_be_painted_elsewhere(*element))
return false;
- for (auto const& observer : m_intersection_observers) {
- if (observer.observation_targets().is_empty())
- continue;
- auto root = observer.intersection_root_node();
- if (root->is_element() && animated_target.is_shadow_including_inclusive_ancestor_of(*root))
- return true;
- bool subtree_is_clipped_outside_root = transform_subtree_is_clipped_outside(animated_target, observer.root_intersection_rectangle(read));
- for (auto const& observation : observer.observation_targets()) {
- auto target = observation.target.ptr();
- if (!target)
- continue;
- if (!animated_target.is_shadow_including_inclusive_ancestor_of(*target) || subtree_is_clipped_outside_root)
- continue;
- if (only_translates_horizontally && ancestor_transform_can_map_horizontal_motion_to_vertical(animated_target, *root)) {
- requires_main_thread_sampling = true;
- return true;
- }
- if (only_translates_horizontally && !observation_has_another_transform_animation(animated_target, *target, effect)) {
- auto const& target_rect = observation_target_rect_cache.ensure(target, [&] {
- return target->bounding_client_rect_assuming_layout_clean();
- });
- auto root_rect = observer.root_intersection_rectangle(read);
- bool vertical_bands_are_disjoint = target_rect.bottom() < root_rect.top() || target_rect.top() > root_rect.bottom();
- if (vertical_bands_are_disjoint)
- continue;
- }
- return true;
+ }
+ if (is_svg_target && layout_node->has_children())
+ return false;
+
+ // NB: A descendant can explicitly inherit even a normally non-inherited paint property. Reject
+ // content that can escape ancestor clips or be rendered elsewhere through SVG references.
+ bool subtree_can_escape = false;
+ layout_node->for_each_in_inclusive_subtree_of_type<Layout::NodeWithStyle>([&](auto const& descendant) {
+ if (descendant.is_svg_box()) {
+ auto const* element = as_if<SVG::SVGElement>(descendant.dom_node());
+ if (!query->can_include_svg_descendants || !element || svg_element_can_be_painted_elsewhere(*element)) {
+ subtree_can_escape = true;
+ return TraversalDecision::Break;
}
}
+ if (descendant.is_fixed_position()
+ || (&descendant != layout_node && descendant.is_absolutely_positioned())) {
+ subtree_can_escape = true;
+ return TraversalDecision::Break;
+ }
+ return TraversalDecision::Continue;
+ });
+ if (subtree_can_escape)
return false;
- };
- auto opacity_affects_visibility_observation = [&](Element& animated_target) {
- return elements_with_visibility_observation_descendants.contains(animated_target);
+ auto viewport_bounds = CSSPixelRect { { 0, 0 }, document.viewport_rect().size() };
+ auto const& viewport_mapping = pass.viewport_mapping;
+ auto bounds_in_viewport = [&](Layout::Node const& node) -> CSSPixelRect {
+ CSSPixelRect rect;
+ Layout::RustFFI::layout_script_bounding_client_rect(
+ node.document_host(), Layout::Node::slot_id(&node), viewport_mapping, &rect);
+ return rect;
};
-
- for (auto const& animation : associated_animations(m_animations)) {
- auto associated_effect = animation.effect();
- if (!associated_effect.has_value())
+ HashTable<Layout::Node const*> containing_blocks;
+ for (auto const* container = layout_node->containing_block(); container; container = container->containing_block())
+ containing_blocks.set(container);
+
+ auto visible_bounds = viewport_bounds;
+ for (auto const* ancestor = layout_node; ancestor; ancestor = ancestor->parent()) {
+ bool can_move_or_expand_paint = ancestor->has_css_transform() || ancestor->perspective().has_value()
+ || ancestor->is_sticky_position() || ancestor->filter().has_filters()
+ || query->ancestor_animation_moves_paint(query->context, Layout::Node::slot_id(ancestor), const_cast<Element*>(as_if<Element>(ancestor->dom_node())));
+ if (can_move_or_expand_paint) {
+ // NB: A transform or filter outside a clip can bring its paint into view. A later, outer clip
+ // can still prove that the entire transformed or filtered subtree remains offscreen.
+ visible_bounds = viewport_bounds;
+ paint_stays_within_border_box = false;
continue;
- auto const& effect = *associated_effect;
- if (effect.is_compositor_driven())
- previously_compositor_driven_effects.set(effect.id());
- if (effect.is_compositor_replaced())
- previously_compositor_replaced_effects.set(effect.id());
- if (effect.has_retained_compositor_animations())
- previously_published_effects.set(effect.id());
- if (effect.is_offscreen_throttled())
- previously_offscreen_throttled_effects.set(effect.id());
- if (auto target = effect.target_abstract_element(); target.has_value()) {
- if (auto* layout_node = target->unsafe_layout_node(read)) {
- previous_content_retention.ensure(*layout_node, [&] { return layout_node->retains_compositor_animated_content(); });
- }
}
- effect.set_flag(Animations::RustFFI::EffectFlag::CompositorDriven, false);
- effect.set_flag(Animations::RustFFI::EffectFlag::CompositorReplaced, false);
- effect.set_flag(Animations::RustFFI::EffectFlag::OffscreenThrottled, false);
- effect.set_flag(Animations::RustFFI::EffectFlag::ObservationRelevantCompositorAnimation, false);
-
- auto const state = animation.timing_state();
- if (state.play_state == Animations::RustFFI::AnimationPlayState::Idle || (!state.is_in_effect && state.phase != Animations::RustFFI::AnimationEffectPhase::Before))
+ if (!containing_blocks.contains(ancestor) || ancestor->is_svg_box())
continue;
- auto target = effect.target_abstract_element();
- if (!target.has_value())
+ if (ancestor->overflow_x() == CSS::Overflow::Visible || ancestor->overflow_y() == CSS::Overflow::Visible)
continue;
- auto& effects = competing_effects.ensure(*target);
- auto add_competing_effect = [&](CompetingPropertyEffects& property_effects) {
- ++property_effects.effect_count;
- bool effect_produces_output = state.is_in_effect;
- if (effect_produces_output && !effect.composite_is_replace())
- property_effects.all_effects_use_replace = false;
- auto winner_animation = property_effects.winner.has_value() ? property_effects.winner->associated_animation() : Optional<Animations::AnimationRef> {};
- bool winner_produces_output = winner_animation.has_value() && winner_animation->timing_state().is_in_effect;
- if (!property_effects.winner.has_value()
- || (effect_produces_output && !winner_produces_output)
- || (effect_produces_output == winner_produces_output && Animations::AnimationRef::composite_order(*winner_animation, animation) < 0))
- property_effects.winner = effect;
- };
- if (effect.target_properties().contains(CSS::PropertyNameAndID::from_id(CSS::PropertyID::Opacity)))
- add_competing_effect(effects.opacity);
- if (effect.target_properties().contains(CSS::PropertyNameAndID::from_id(CSS::PropertyID::BackgroundColor)))
- add_competing_effect(effects.background_color);
- if (effect.target_properties().contains(CSS::PropertyNameAndID::from_id(CSS::PropertyID::Filter)))
- add_competing_effect(effects.filter);
- if (any_of(effect.target_properties(), [](auto const& property) { return is_transform_family_property(property.id()); })) {
- add_competing_effect(effects.transform);
- if (auto const* layout_node = target->unsafe_layout_node(read))
- in_effect_transform_effects_by_layout_node.ensure(layout_node).append(effect);
+ if (ancestor->overflow_x() == CSS::Overflow::Clip || ancestor->overflow_y() == CSS::Overflow::Clip) {
+ auto const& margin = ancestor->style_group<CSS::ComputedValues::MiscLayoutValues>().overflow_clip_margin;
+ if (margin.top.offset != 0 || margin.right.offset != 0 || margin.bottom.offset != 0 || margin.left.offset != 0)
+ continue;
}
+ visible_bounds = visible_bounds.intersected(bounds_in_viewport(*ancestor));
}
+ if (visible_bounds.is_empty())
+ return true;
- auto winner_uses_replace_keyframes = [](Animations::EffectRef const& effect) {
- auto const& keyframe_set = effect.keyframe_set();
- return keyframe_set && !keyframe_set.facts().has_additive_keyframe;
- };
- // A keyframe that leaves a property out takes the underlying value, which is the output of the effects beneath the
- // winner where there are any. The compositor only knows the element's own style.
- auto winner_takes_the_underlying_value = [](Animations::EffectRef const& effect, auto is_property) {
- auto const& keyframe_set = effect.keyframe_set();
- if (!keyframe_set)
- return false;
- for (size_t index = 0; index < keyframe_set.keyframe_count(); ++index) {
- for (auto property : effect.target_properties()) {
- if (is_property(property.id()) && keyframe_set.value(index, to_underlying(property.id())).state == Animations::RustFFI::FfiKeyframeValueState::ElementValue)
- return true;
- }
- }
+ // NB: Otherwise, only a leaf box with bounded paint can be proven invisible from its own bounds.
+ return paint_stays_within_border_box && !layout_node->has_children()
+ && !bounds_in_viewport(*layout_node).intersects(visible_bounds);
+}
+
+static bool transform_preserves_horizontal_axis(Layout::NodeWithStyle const& layout_node)
+{
+ if (layout_node.perspective().has_value())
return false;
- };
- for (auto& [target, effects] : competing_effects) {
- (void)target;
- auto validate_winner = [&](CompetingPropertyEffects& property_effects, auto is_property) {
- if (!property_effects.all_effects_use_replace
- || (property_effects.winner.has_value() && !winner_uses_replace_keyframes(*property_effects.winner))
- || (property_effects.winner.has_value() && property_effects.effect_count > 1 && winner_takes_the_underlying_value(*property_effects.winner, is_property)))
- property_effects.winner.clear();
- };
- auto is = [](CSS::PropertyID property_id) {
- return [property_id](CSS::PropertyID id) { return id == property_id; };
- };
- validate_winner(effects.opacity, is(CSS::PropertyID::Opacity));
- validate_winner(effects.background_color, is(CSS::PropertyID::BackgroundColor));
- validate_winner(effects.filter, is(CSS::PropertyID::Filter));
- validate_winner(effects.transform, is_transform_family_property);
- }
-
- // An opacity of 1 does not otherwise create an effects frame. Give an otherwise publishable opacity
- // animation a target before the normal handoff loop, and retain that target while the effect remains live.
- auto can_force_opacity_effects_layer = [](Animations::EffectRef const& effect) {
- return all_of(effect.target_properties(), [](auto const& property) {
- return first_is_one_of(property.id(), CSS::PropertyID::Opacity, CSS::PropertyID::BackgroundColor)
- || is_transform_family_property(property.id());
- });
- };
- bool forced_opacity_effects_layer = false;
- for (auto& [target, effects] : competing_effects) {
- auto const& effect = effects.opacity.winner;
- if (!effect.has_value() || opacity_affects_visibility_observation(target.element()) || !can_force_opacity_effects_layer(*effect))
- continue;
- bool missing_visual_context_node = build_compositor_animation(read, *effect, Compositing::RustFFI::FfiVisualAnimationTargetKind::Opacity, keyframes_by_effect).missing_visual_context_node;
- auto* layout_node = target.unsafe_layout_node(read);
- if (!layout_node)
- continue;
- auto layout_node_slot = Layout::Node::slot_id(layout_node);
- bool already_forced_effects_layer = any_of(layout_nodes_with_stale_forced_effects_layer, [&](auto stale_slot) {
- return stale_slot.index == layout_node_slot.index;
- });
- if (!missing_visual_context_node && !already_forced_effects_layer)
- continue;
+ auto matrix = Gfx::FloatMatrix4x4::identity();
+ auto reference_box = Painting::transform_reference_box(layout_node);
+ layout_node.for_each_resolved_transform([&](auto const& transform) {
+ matrix = matrix * transform.to_matrix(reference_box.width(), reference_box.height());
+ });
- if (missing_visual_context_node && !layout_node->needs_compositor_effects_layer()) {
- layout_node->set_needs_compositor_effects_layer(true);
- schedule_accumulated_visual_context_update(*layout_node, AccumulatedVisualContextUpdateScope::Structure);
- CSS::RequiredInvalidationAfterStyleChange invalidation;
- invalidation.ensure_at_least(CSS::InvalidationLevel::Repaint);
- Painting::repaint_after_style_change(*layout_node, invalidation);
- forced_opacity_effects_layer = true;
- }
- if (!any_of(m_layout_nodes_with_forced_compositor_effects_layer, [&](auto forced_slot) { return forced_slot.index == layout_node_slot.index; }))
- m_layout_nodes_with_forced_compositor_effects_layer.append(layout_node_slot);
- layout_nodes_with_stale_forced_effects_layer.remove_first_matching([&](auto stale_slot) {
- return stale_slot.index == layout_node_slot.index;
- });
- }
- if (forced_opacity_effects_layer)
- animation_pass_viewport_mapping = Painting::viewport_mapping(*this);
+ constexpr auto epsilon = AK::NumericLimits<float>::epsilon();
+ return abs(matrix[1, 0]) <= epsilon
+ && abs(matrix[2, 0]) <= epsilon
+ && abs(matrix[3, 0]) <= epsilon;
+}
- bool has_observation_relevant_compositor_animation = false;
- bool requested_withdrawn_effect_sample = false;
- auto schedule_next_phase_wakeup = [&](Animations::RustFFI::FfiAnimationTimingState const& state) {
- // NB: The record decides when the effect next changes phase.
- if (!state.next_phase_boundary_delay.has_value)
- return;
- auto delay = state.next_phase_boundary_delay.value;
- if (!compositor_animation_wakeup_delay_ms.has_value() || delay < *compositor_animation_wakeup_delay_ms)
- compositor_animation_wakeup_delay_ms = delay;
- };
- // Force-dark resolves colors when the display list is recorded, on the main thread. A compositor-driven
- // background color is sampled at play time instead, and would paint as authored — so while force-dark applies,
- // background-color animations stay on the main thread, where every tick re-records the darkened color.
- auto navigable = this->navigable();
- bool force_dark_applies = navigable && navigable->force_dark_applies_to_active_document();
- for (auto const& animation : associated_animations(m_animations)) {
- auto associated_effect = animation.effect();
- if (!associated_effect.has_value())
- continue;
- auto const& effect = *associated_effect;
- auto existing_compositor_animation_state = effect.existing_compositor_animation_state();
- if (existing_compositor_animation_state.has_value())
- existing_compositor_animation_state->clear_pending();
- bool published_compositor_animation = false;
- ScopeGuard collect_effect_bookkeeping = [&] {
- if (auto compositor_animation_state = effect.existing_compositor_animation_state(); compositor_animation_state.has_value()) {
- if (!published_compositor_animation)
- compositor_animation_state->clear_retained();
- compositor_animation_state->clear_pending();
- }
- if (effect.is_observation_relevant_compositor_animation())
- has_observation_relevant_compositor_animation = true;
- bool was_throttled = previously_compositor_driven_effects.contains(effect.id())
- || previously_compositor_replaced_effects.contains(effect.id())
- || previously_offscreen_throttled_effects.contains(effect.id());
- if (was_throttled && !effect.is_compositor_driven() && !effect.is_compositor_replaced() && !effect.is_offscreen_throttled()) {
- effect.request_observation_sample();
- requested_withdrawn_effect_sample = true;
- }
- if (!m_has_throttled_animation_style_update && effect.can_skip_per_frame_style_update())
- note_throttled_animation_style_update();
- };
- auto abstract_target = effect.target_abstract_element();
- if (!abstract_target.has_value() || effect.target_properties().is_empty())
- continue;
- auto const state = animation.timing_state();
- if (state.play_state == Animations::RustFFI::AnimationPlayState::Idle || (!state.is_in_effect && state.phase != Animations::RustFFI::AnimationEffectPhase::Before))
- continue;
- auto& target = abstract_target->element();
+bool CompositorAnimationUpdatePass::transform_affects_intersection_observation(void* context, void* animated_target_pointer, Animations::RustFFI::FfiTransformObservationQuery const* query, bool* requires_main_thread_sampling)
+{
+ auto& pass = of(context);
+ auto& animated_target = *static_cast<Element*>(animated_target_pointer);
+ if (!pass.elements_with_intersection_observation_descendants.contains(animated_target))
+ return false;
- // NB: The record decides whether the timing of the effect lets it be throttled.
- if (state.can_throttle_offscreen_effect && paint_only_effect_is_offscreen(effect, *abstract_target)) {
- effect.set_flag(Animations::RustFFI::EffectFlag::OffscreenThrottled, true);
- schedule_next_phase_wakeup(state);
- continue;
+ auto ancestor_transform_can_map_horizontal_motion_to_vertical = [&](Node const& observation_root) {
+ auto const* layout_node = animated_target.unsafe_layout_node(pass.read);
+ if (!layout_node)
+ return true;
+ for (auto const* ancestor = layout_node->parent(); ancestor; ancestor = ancestor->parent()) {
+ if (ancestor->has_css_transform() && !transform_preserves_horizontal_axis(*ancestor))
+ return true;
+ if (!query->transform_animations_preserve_axes(query->context, Layout::Node::slot_id(ancestor)))
+ return true;
+ if (ancestor->dom_node() == &observation_root)
+ break;
+ }
+ return false;
+ };
+ auto observation_has_another_transform_animation = [&](Element const& observation_target) {
+ for (size_t index = 0; index < query->transform_target_count; ++index) {
+ auto const& transform_target = query->transform_targets[index];
+ if (transform_target.effect == query->effect)
+ continue;
+ auto& effect_target = *static_cast<Element*>(transform_target.element);
+ if (animated_target.is_shadow_including_inclusive_ancestor_of(effect_target)
+ && effect_target.is_shadow_including_inclusive_ancestor_of(observation_target))
+ return true;
}
+ return false;
+ };
- bool targets_opacity = effect.target_properties().contains(CSS::PropertyNameAndID::from_id(CSS::PropertyID::Opacity));
- bool targets_background_color = effect.target_properties().contains(CSS::PropertyNameAndID::from_id(CSS::PropertyID::BackgroundColor));
- bool targets_filter = effect.target_properties().contains(CSS::PropertyNameAndID::from_id(CSS::PropertyID::Filter));
- bool targets_transform = any_of(effect.target_properties(), [](auto const& property) { return is_transform_family_property(property.id()); });
- if (!effect.may_run_on_the_compositor())
+ for (auto const& observer : pass.document->m_intersection_observers) {
+ if (observer.observation_targets().is_empty())
continue;
- auto target_effects = competing_effects.get(*abstract_target);
- VERIFY(target_effects.has_value());
- bool opacity_has_replace_winner = !targets_opacity || target_effects->opacity.winner.has_value();
- bool background_color_has_replace_winner = !targets_background_color || target_effects->background_color.winner.has_value();
- bool filter_has_replace_winner = !targets_filter || target_effects->filter.winner.has_value();
- bool transform_has_replace_winner = !targets_transform || target_effects->transform.winner.has_value();
- bool selected_for_opacity = targets_opacity && target_effects->opacity.winner == effect;
- bool selected_for_background_color = targets_background_color && target_effects->background_color.winner == effect;
- bool selected_for_filter = targets_filter && target_effects->filter.winner == effect;
- bool selected_for_transform = targets_transform && target_effects->transform.winner == effect;
- bool all_targeted_properties_have_replace_winners = opacity_has_replace_winner && background_color_has_replace_winner && filter_has_replace_winner && transform_has_replace_winner;
-
- // Background colors are display-list content, so associate their fill commands with a dedicated metadata
- // frame. Validate the descriptor before forcing that frame, which requires one repaint before the animation
- // can move to the compositor.
- Layout::Node* background_color_layout_node = nullptr;
- bool background_color_animation_was_built = false;
- bool background_color_animation_is_valid = false;
- if (selected_for_background_color) {
- if (auto* layout_node = abstract_target->unsafe_layout_node(read)) {
- if (!force_dark_applies && Painting::rust_background_color_can_be_compositor_animated(*layout_node)) {
- background_color_layout_node = layout_node;
- auto build = build_compositor_animation(read, effect, Compositing::RustFFI::FfiVisualAnimationTargetKind::BackgroundColor, keyframes_by_effect);
- background_color_animation_was_built = build.built;
- background_color_animation_is_valid = build.built || build.missing_visual_context_node;
- if (!background_color_animation_is_valid) {
- background_color_layout_node = nullptr;
- } else if (build.missing_visual_context_node && !layout_node->needs_compositor_background_color_frame()) {
- layout_node->set_needs_compositor_background_color_frame(true);
- schedule_accumulated_visual_context_update(*layout_node, AccumulatedVisualContextUpdateScope::Structure);
- CSS::RequiredInvalidationAfterStyleChange invalidation;
- invalidation.ensure_at_least(CSS::InvalidationLevel::Repaint);
- Painting::repaint_after_style_change(*layout_node, invalidation);
- }
- }
+ auto root = observer.intersection_root_node();
+ if (root->is_element() && animated_target.is_shadow_including_inclusive_ancestor_of(*root))
+ return true;
+ bool subtree_is_clipped_outside_root = pass.transform_subtree_is_clipped_outside(animated_target, observer.root_intersection_rectangle(pass.read));
+ for (auto const& observation : observer.observation_targets()) {
+ auto target = observation.target.ptr();
+ if (!target)
+ continue;
+ if (!animated_target.is_shadow_including_inclusive_ancestor_of(*target) || subtree_is_clipped_outside_root)
+ continue;
+ if (query->only_translates_horizontally && ancestor_transform_can_map_horizontal_motion_to_vertical(*root)) {
+ *requires_main_thread_sampling = true;
+ return true;
}
- }
-
- // Filters need an effects frame whose filter payload can be replaced. Validate the descriptor before forcing
- // that frame, which requires one repaint before the animation can move to the compositor.
- Layout::Node* filter_layout_node = nullptr;
- bool filter_animation_was_built = false;
- bool filter_animation_is_valid = false;
- if (selected_for_filter) {
- if (auto* layout_node = abstract_target->unsafe_layout_node(read)) {
- filter_layout_node = layout_node;
- auto build = build_compositor_animation(read, effect, Compositing::RustFFI::FfiVisualAnimationTargetKind::Filter, keyframes_by_effect);
- filter_animation_was_built = build.built;
- filter_animation_is_valid = build.built || build.missing_visual_context_node;
- if (!filter_animation_is_valid) {
- filter_layout_node = nullptr;
- } else if (build.missing_visual_context_node && !layout_node->needs_compositor_effects_layer()) {
- layout_node->set_needs_compositor_effects_layer(true);
- schedule_accumulated_visual_context_update(*layout_node, AccumulatedVisualContextUpdateScope::Structure);
- CSS::RequiredInvalidationAfterStyleChange invalidation;
- invalidation.ensure_at_least(CSS::InvalidationLevel::Repaint);
- Painting::repaint_after_style_change(*layout_node, invalidation);
- }
+ if (query->only_translates_horizontally && !observation_has_another_transform_animation(*target)) {
+ auto const& target_rect = pass.observation_target_rect_cache.ensure(target, [&] {
+ return target->bounding_client_rect_assuming_layout_clean();
+ });
+ auto root_rect = observer.root_intersection_rectangle(pass.read);
+ bool vertical_bands_are_disjoint = target_rect.bottom() < root_rect.top() || target_rect.top() > root_rect.bottom();
+ if (vertical_bands_are_disjoint)
+ continue;
}
+ return true;
}
+ }
+ return false;
+}
- if (!selected_for_opacity && !selected_for_background_color && !selected_for_filter && !selected_for_transform) {
- if (all_targeted_properties_have_replace_winners && state.can_throttle_replaced_effect) {
- effect.set_flag(Animations::RustFFI::EffectFlag::CompositorReplaced, true);
- schedule_next_phase_wakeup(state);
- }
- continue;
- }
+void Document::schedule_compositor_animation_wakeup(double delay_ms)
+{
+ auto timer_delay_ms = static_cast<int>(ceil(clamp(delay_ms, 1.0, static_cast<double>(NumericLimits<int>::max()))));
+ auto deadline = MonotonicTime::now() + AK::Duration::from_milliseconds(timer_delay_ms);
+ if (m_compositor_animation_wakeup_timer && m_compositor_animation_wakeup_timer->is_active()
+ && m_compositor_animation_wakeup_deadline.has_value() && *m_compositor_animation_wakeup_deadline <= deadline)
+ return;
- auto compositor_animation_state = effect.compositor_animation_state();
- bool opacity_was_handed_off = !selected_for_opacity;
- if (selected_for_opacity && build_compositor_animation(read, effect, Compositing::RustFFI::FfiVisualAnimationTargetKind::Opacity, keyframes_by_effect).built)
- opacity_was_handed_off = true;
- bool background_color_was_handed_off = !selected_for_background_color;
- if (background_color_animation_was_built)
- background_color_was_handed_off = true;
- if (background_color_layout_node && background_color_animation_is_valid) {
- auto background_color_layout_node_slot = Layout::Node::slot_id(background_color_layout_node);
- if (!any_of(m_layout_nodes_with_forced_compositor_background_color_frame, [&](auto forced_slot) { return forced_slot.index == background_color_layout_node_slot.index; }))
- m_layout_nodes_with_forced_compositor_background_color_frame.append(background_color_layout_node_slot);
- layout_nodes_with_stale_forced_background_color_frame.remove_first_matching([&](auto stale_slot) {
- return stale_slot.index == background_color_layout_node_slot.index;
- });
- }
- bool filter_was_handed_off = !selected_for_filter;
- if (filter_animation_was_built)
- filter_was_handed_off = true;
- if (filter_layout_node && filter_animation_is_valid) {
- auto filter_layout_node_slot = Layout::Node::slot_id(filter_layout_node);
- if (!any_of(m_layout_nodes_with_forced_compositor_effects_layer, [&](auto forced_slot) { return forced_slot.index == filter_layout_node_slot.index; }))
- m_layout_nodes_with_forced_compositor_effects_layer.append(filter_layout_node_slot);
- layout_nodes_with_stale_forced_effects_layer.remove_first_matching([&](auto stale_slot) {
- return stale_slot.index == filter_layout_node_slot.index;
- });
- }
- bool transform_was_handed_off = !selected_for_transform;
- if (selected_for_transform) {
- auto build = build_compositor_animation(read, effect, Compositing::RustFFI::FfiVisualAnimationTargetKind::Transform, keyframes_by_effect);
- transform_was_handed_off = build.built;
- if (build.only_translates_horizontally.has_value())
- only_translates_horizontally_cache.set(effect.id(), *build.only_translates_horizontally);
- }
+ m_compositor_animation_wakeup_deadline = deadline;
+ if (!m_compositor_animation_wakeup_timer) {
+ m_compositor_animation_wakeup_timer = Core::Timer::create_single_shot(AK::Duration::from_milliseconds(static_cast<int>(timer_delay_ms)), GC::weak_callback(*this, [](auto& document) {
+ // Canceling a finite effect can leave this deadline armed. The single wake-up is harmless: it finds
+ // nothing due and leaves the timer idle unless another effect supplies a deadline.
+ document.m_compositor_animation_wakeup_deadline.clear();
+ auto timestamp = HighResolutionTime::relative_high_resolution_time(
+ HighResolutionTime::unsafe_shared_current_time(), document.relevant_settings_object().global_object());
+ document.service_compositor_animation_wakeup(timestamp);
+ }));
+ }
+ m_compositor_animation_wakeup_timer->restart(AK::Duration::from_milliseconds(static_cast<int>(timer_delay_ms)));
+}
- if (selected_for_opacity && opacity_affects_visibility_observation(target)) {
- compositor_animation_state.discard_pending(Compositing::RustFFI::FfiVisualAnimationTargetKind::Opacity);
- opacity_was_handed_off = false;
+void Document::service_compositor_animation_wakeup(double timestamp)
+{
+ auto outcome = Animations::RustFFI::animations_document_service_compositor_animation_wakeup(m_animations, timestamp);
+ if (outcome.has_next_wakeup_delay)
+ schedule_compositor_animation_wakeup(outcome.next_wakeup_delay);
+ if (outcome.reached_wakeup) {
+ if (outcome.reached_compositor_active_start) {
+ Layout::ForcedReadScope read { *this };
+ paint_state().republish_visual_animations(read);
}
+ HTML::note_rendering_trace_event("animation frame pump request"sv);
+ set_rendering_pending(*this, RenderingPendingReason::NeedsRenderingUpdate, 1);
+ page().client().request_frame_for(*this);
+ }
+}
- bool transform_affects_observation = false;
- bool requires_main_thread_observation_sampling = false;
- if (selected_for_transform) {
- auto only_translates_horizontally = only_translates_horizontally_cache.ensure(effect.id(), [&] {
- auto const* layout_node = abstract_target->unsafe_layout_node(read);
- if (!layout_node || !effect.keyframe_set())
- return false;
- return compositor_animation_keyframes(keyframes_by_effect, effect, animation, *abstract_target).only_translates_horizontally(*layout_node);
- });
- transform_affects_observation = transform_affects_intersection_observation(target, effect, only_translates_horizontally, requires_main_thread_observation_sampling);
- }
- if (requires_main_thread_observation_sampling) {
- compositor_animation_state.discard_pending(Compositing::RustFFI::FfiVisualAnimationTargetKind::Transform);
- transform_was_handed_off = false;
- }
+void Document::fire_compositor_animation_wakeup_for_testing(Badge<Internals::Internals>, double frame_time_ms)
+{
+ if (m_compositor_animation_wakeup_timer)
+ m_compositor_animation_wakeup_timer->stop();
+ m_compositor_animation_wakeup_deadline.clear();
+ service_compositor_animation_wakeup(frame_time_ms);
+}
+
+void Document::force_visual_context_tree_rebuild_on_next_compositor_animation_update_for_testing(Badge<Internals::Internals>)
+{
+ m_force_visual_context_tree_rebuild_on_next_compositor_animation_update_for_testing = true;
+}
+
+void Document::update_compositor_animations(Layout::BegunRead const& read)
+{
+ CompositorAnimationUpdatePass pass { *this, read };
+ pass.viewport_mapping = Painting::viewport_mapping(*this);
+ paint_state().begin_compositor_animation_update();
+ pass.layout_nodes_with_stale_forced_effects_layer = move(m_layout_nodes_with_forced_compositor_effects_layer);
+ pass.layout_nodes_with_stale_forced_background_color_frame = move(m_layout_nodes_with_forced_compositor_background_color_frame);
- if (!compositor_animation_state.has_pending()) {
- auto viewport_bounds = CSSPixelRect { { 0, 0 }, viewport_rect().size() };
- if (selected_for_transform && !transform_affects_observation && transform_subtree_is_clipped_outside(target, viewport_bounds))
- effect.set_flag(Animations::RustFFI::EffectFlag::OffscreenThrottled, true);
+ auto index_shadow_including_element_ancestors = [](Node& node, GC::RootHashTable<GC::Ref<Element>>& index) {
+ for (auto* ancestor = &node; ancestor; ancestor = ancestor->parent_or_shadow_host()) {
+ if (auto* element = as_if<Element>(*ancestor))
+ index.set(*element);
+ }
+ };
+ for (auto const& observer : m_intersection_observers) {
+ if (observer.observation_targets().is_empty())
continue;
+ auto root = observer.intersection_root_node();
+ if (root->is_element())
+ index_shadow_including_element_ancestors(*root, pass.elements_with_intersection_observation_descendants);
+ for (auto const& observation : observer.observation_targets()) {
+ auto target = observation.target.ptr();
+ if (!target)
+ continue;
+ index_shadow_including_element_ancestors(*target, pass.elements_with_intersection_observation_descendants);
+ if (observer.track_visibility())
+ index_shadow_including_element_ancestors(*target, pass.elements_with_visibility_observation_descendants);
}
- if (all_targeted_properties_have_replace_winners && opacity_was_handed_off && background_color_was_handed_off && filter_was_handed_off && transform_was_handed_off)
- effect.set_flag(Animations::RustFFI::EffectFlag::CompositorDriven, true);
- effect.set_flag(Animations::RustFFI::EffectFlag::ObservationRelevantCompositorAnimation, transform_affects_observation);
- schedule_next_phase_wakeup(state);
- // OPTIMIZATION: Ordinary rendering updates advance the WebContent timeline without changing compositor
- // playback. An effect published before keeps the anchors of the animations whose parameters
- // did not change.
- compositor_animation_state.publish_pending(*this,
- previously_published_effects.contains(effect.id())
- ? Painting::CompositorAnimationEffectState::ReuseRetainedTimingAnchors::Yes
- : Painting::CompositorAnimationEffectState::ReuseRetainedTimingAnchors::No);
- if (auto* layout_node = abstract_target->unsafe_layout_node(read))
- retained_this_pass.set(*layout_node);
- published_compositor_animation = true;
}
+ // Force-dark resolves colors when the display list is recorded, on the main thread. A compositor-driven
+ // background color is sampled at play time instead, and would paint as authored. While force-dark applies,
+ // background-color animations stay on the main thread, where every tick re-records the darkened color.
+ auto navigable = this->navigable();
+ auto last_animation_frame_timestamp = this->last_animation_frame_timestamp();
+ Animations::RustFFI::FfiCompositorUpdateHost host {
+ .context = &pass,
+ .document_host = layout_node_arena().host(),
+ .force_dark_applies = navigable && navigable->force_dark_applies_to_active_document(),
+ .has_throttled_animation_style_update = m_has_throttled_animation_style_update,
+ .time_origin = relevant_settings_object().time_origin(),
+ .has_last_animation_frame_timestamp = last_animation_frame_timestamp.has_value(),
+ .last_animation_frame_timestamp = last_animation_frame_timestamp.value_or(0),
+ .keep_alive = CompositorAnimationUpdatePass::keep_alive,
+ .tree_order = Animations::compare_elements_in_tree_order_for_composite_order,
+ .layout_node = CompositorAnimationUpdatePass::layout_node,
+ .note_target_layout_node = CompositorAnimationUpdatePass::note_target_layout_node,
+ .note_retained_layout_node = CompositorAnimationUpdatePass::note_retained_layout_node,
+ .visibility_is_observed = CompositorAnimationUpdatePass::visibility_is_observed,
+ .prepare_compositor_animation = CompositorAnimationUpdatePass::prepare_compositor_animation,
+ .paint_is_offscreen = CompositorAnimationUpdatePass::paint_is_offscreen,
+ .transform_affects_intersection_observation = CompositorAnimationUpdatePass::transform_affects_intersection_observation,
+ .transform_subtree_is_clipped_outside_viewport = CompositorAnimationUpdatePass::transform_subtree_is_clipped_outside_viewport,
+ .background_color_can_be_compositor_animated = CompositorAnimationUpdatePass::background_color_can_be_compositor_animated,
+ .request_frame = CompositorAnimationUpdatePass::request_frame,
+ .keep_frame = CompositorAnimationUpdatePass::keep_frame,
+ .frame_was_kept = CompositorAnimationUpdatePass::frame_was_kept,
+ .refresh_viewport_mapping = CompositorAnimationUpdatePass::refresh_viewport_mapping,
+ .note_throttled_animation_style_update = CompositorAnimationUpdatePass::note_throttled_animation_style_update,
+ };
+ auto outcome = Animations::RustFFI::animations_document_update_compositor_animations(m_animations, &host);
+
// Retention changes whether zero-opacity or singular-transform content is recorded. The
// flag is written once the pass is complete, so an animation that stays on the compositor
// changes nothing.
- for (auto const& [layout_node, retained_before] : previous_content_retention) {
- bool const retained_now = retained_this_pass.contains(layout_node);
+ for (auto const& [layout_node, retained_before] : pass.previous_content_retention) {
+ bool const retained_now = pass.retained_this_pass.contains(layout_node);
if (retained_now == retained_before)
continue;
layout_node->set_retains_compositor_animated_content(retained_now);
Painting::set_needs_repaint(*layout_node, InvalidateDisplayList::PaintCommandsAndHitTestList);
}
- for (auto stale_slot : layout_nodes_with_stale_forced_effects_layer) {
+ for (auto stale_slot : pass.layout_nodes_with_stale_forced_effects_layer) {
auto* layout_node = layout_node_arena().node_if_live(read, stale_slot);
if (!layout_node)
continue;
@@ -9760,7 +9214,7 @@ void Document::update_compositor_animations(Layout::BegunRead const& read)
invalidation.ensure_at_least(CSS::InvalidationLevel::Repaint);
Painting::repaint_after_style_change(*layout_node, invalidation);
}
- for (auto stale_slot : layout_nodes_with_stale_forced_background_color_frame) {
+ for (auto stale_slot : pass.layout_nodes_with_stale_forced_background_color_frame) {
auto* layout_node = layout_node_arena().node_if_live(read, stale_slot);
if (!layout_node)
continue;
@@ -9786,10 +9240,10 @@ void Document::update_compositor_animations(Layout::BegunRead const& read)
paint_state().publish_compositor_animations(read, Painting::DocumentPaintState::PublishPendingCompositorAnimations::Yes);
- if (compositor_animation_wakeup_delay_ms.has_value())
- schedule_compositor_animation_wakeup(*compositor_animation_wakeup_delay_ms);
+ if (outcome.has_wakeup_delay)
+ schedule_compositor_animation_wakeup(outcome.wakeup_delay);
- if (!has_observation_relevant_compositor_animation) {
+ if (!outcome.has_observation_relevant_compositor_animation) {
if (m_compositor_animation_observation_timer)
m_compositor_animation_observation_timer->stop();
} else {
@@ -9806,7 +9260,7 @@ void Document::update_compositor_animations(Layout::BegunRead const& read)
}
}
- if (requested_withdrawn_effect_sample)
+ if (outcome.requested_withdrawn_effect_sample)
HTML::note_rendering_trace_event("animation frame pump request"sv);
}
@@ -9817,32 +9271,27 @@ void Document::append_pending_animation_event(Animations::AnimationRef const& an
HTML::note_rendering_trace_event(provisional ? "provisional animation events"sv : "animation events committed"sv);
}
-void Document::prepare_to_observe_css_animation_events()
-{
- GC::RootVector<Animations::EffectRef> effects_to_synchronize;
- for (auto const& animation : associated_animations(m_animations)) {
- auto effect = animation.effect();
- if (!effect.has_value() || animation.timing_state().kind != Animations::RustFFI::FfiAnimationKind::CssAnimation)
- continue;
- if (effect->per_frame_animation_tick_was_skipped())
- effects_to_synchronize.append(effect.release_value());
- }
- if (effects_to_synchronize.is_empty())
- return;
+// What preparing to observe the CSS animation events of a document asks of it.
+struct PrepareToObserveCssAnimationEventsContext {
+ GC::Ref<Document> document;
+ // NB: The animations stay alive while the timelines update, which can run script.
+ GC::RootVector<Animations::AnimationRef> animations;
+};
- auto timestamp = HighResolutionTime::relative_high_resolution_time(
- HighResolutionTime::unsafe_shared_current_time(), relevant_settings_object().global_object());
- auto timelines_to_update = GC::RootVector { m_associated_animation_timelines.values() };
- for (auto const& timeline : timelines_to_update)
- timeline->update_current_time(timestamp);
+static void keep_animation_alive_to_prepare_to_observe_css_animation_events(void* context, Animations::RustFFI::AnimationCell const* animation)
+{
+ Animations::keep_animation_alive_in(&static_cast<PrepareToObserveCssAnimationEventsContext*>(context)->animations, animation);
+}
- // OPTIMIZATION: Events which occurred while there were no listeners were intentionally not sampled. Establish
- // the current phase as the baseline so a newly added listener only observes future events.
- for (auto const& effect : effects_to_synchronize) {
- auto resolved_timing = effect.resolve_timing();
- effect.set_previous_phase_and_current_iteration(resolved_timing.phase, Animations::from_ffi(resolved_timing.current_iteration).value_or(0.0));
- effect.set_flag(Animations::RustFFI::EffectFlag::PerFrameAnimationTickWasSkipped, false);
- }
+void Document::prepare_to_observe_css_animation_events()
+{
+ PrepareToObserveCssAnimationEventsContext context { *this, {} };
+ Animations::RustFFI::FfiObserveCssAnimationEventsHost host {
+ .context = &context,
+ .keep_alive = keep_animation_alive_to_prepare_to_observe_css_animation_events,
+ .perform = Animations::web_animation_perform_host_effect,
+ };
+ Animations::RustFFI::animations_document_animations_prepare_to_observe_css_animation_events(m_animations, &host);
}
// https://www.w3.org/TR/web-animations-1/#update-animations-and-send-events
@@ -9856,23 +9305,35 @@ void Document::update_animations_and_send_events(double timestamp)
for (auto& element : animate_motion_elements_to_update)
element->update_referenced_motion_path();
- GC::RootVector timelines_to_update = { m_associated_animation_timelines.values() };
-
{
HTML::TemporaryExecutionContext temporary_execution_context { relevant_settings_object() };
// 1. Update the current time of all timelines associated with doc passing now as the timestamp.
- for (auto const& timeline : timelines_to_update)
- timeline->update_current_time(timestamp);
+ {
+ // NB: The animations the timelines update stay alive through it, which can run script.
+ GC::RootVector<Animations::AnimationRef> updated_animations;
+ Animations::RustFFI::FfiTimelineAnimationsHost timelines_host {
+ .context = &updated_animations,
+ .keep_alive = Animations::keep_animation_alive_in,
+ .perform = Animations::web_animation_perform_host_effect,
+ };
+ Animations::RustFFI::animations_document_update_timelines(m_animations, Animations::RustFFI::FfiTimelinesUpdate::All, timestamp, &timelines_host);
+ }
- // NB: We dispatch events for all animations regardless of whether they have a timeline
+ // NB: We dispatch events for all animations regardless of whether they have a timeline. The core queues the events
+ // the animation frame established for each CSS animation or transition, each with the time stamp of when it is
+ // queued.
GC::RootVector<Animations::AnimationRef> animations;
- for (auto const& animation : associated_animations(m_animations))
- animations.append(animation);
-
- for (auto const& animation : animations) {
- dispatch_events_for_animation_if_necessary(animation);
- animation.disassociate_from_target_if_inert();
- }
+ Animations::RustFFI::FfiQueueAnimationEventsHost host {
+ .context = &animations,
+ .keep_alive = Animations::keep_animation_alive_in,
+ .time_stamp = [](void*, void* element) { return HighResolutionTime::current_high_resolution_time(HTML::relevant_global_object(*static_cast<DOM::Element*>(element))); },
+ .queue_time_events = [](void*, void* animation_element) { static_cast<SVG::SVGAnimationElement*>(animation_element)->queue_time_events_if_necessary(); },
+ .perform = Animations::web_animation_perform_host_effect,
+ };
+ auto provisional = m_style_stabilization_epoch_depth > 0;
+ auto queued = Animations::RustFFI::animations_document_animations_queue_events(m_animations, provisional, &host);
+ for (; queued > 0; --queued)
+ HTML::note_rendering_trace_event(provisional ? "provisional animation events"sv : "animation events committed"sv);
// 2. Remove replaced animations for doc.
remove_replaced_animations();
@@ -9886,21 +9347,16 @@ void Document::update_animations_and_send_events(double timestamp)
// 6. Perform a stable sort of the animation events in events to dispatch as follows:
// 7. Dispatch each of the events in events to dispatch at their corresponding target using the order established in
// the previous step.
- // NB: The core runs these steps over the queue it holds, and the document creates each event as it dispatches it.
- // The animation of each event stays rooted until all are dispatched.
- struct DispatchContext {
- GC::Ref<Document> document;
- GC::RootVector<Animations::AnimationRef> animations;
- } dispatch_context { *this, {} };
- Animations::RustFFI::animations_document_animations_dispatch_events(
- m_animations, Animations::compare_elements_in_tree_order_for_composite_order,
- [](void* context, Animations::RustFFI::AnimationCell const* animation) {
- Animations::keep_animation_alive_in(&static_cast<DispatchContext*>(context)->animations, animation);
- },
- [](void* context, Animations::RustFFI::AnimationCell const* animation, Animations::RustFFI::FfiPendingAnimationEvent const* event) {
- dispatch_pending_animation_event(static_cast<DispatchContext*>(context)->document, Animations::AnimationRef { *animation }, *event);
- },
- &dispatch_context);
+ // NB: Bindings/Rust runs these steps over the queue the core holds, creating each event as it dispatches it. The
+ // animation of each event stays rooted until all are dispatched.
+ GC::RootVector<Animations::AnimationRef> animations_of_events;
+ PendingAnimationEventHost host {
+ .context = &animations_of_events,
+ .keep_alive = [](void* context, Animations::RustFFI::AnimationCell const* animation) { Animations::keep_animation_alive_in(context, animation); },
+ .dispatch_at_element = [](void*, void* element, void* event) { static_cast<Element*>(element)->dispatch_event(*static_cast<Event*>(event)); },
+ .dispatch_time_event = [](void*, Animations::RustFFI::AnimationCell const* animation, Animations::RustFFI::FfiPendingAnimationEvent const* event) { static_cast<SVG::SVGAnimationElement*>(Animations::RustFFI::animations_smil_animation_element(animation))->dispatch_pending_time_event(*event); },
+ };
+ web_animation_dispatch_pending_animation_events(JS::HostABI::vm_to_abi(JS::VM::the()), this, m_animations, Animations::compare_elements_in_tree_order_for_composite_order, &host);
// AD-HOC: Nothing else re-requests a rendering update while time-driven animations are running, since
// Document::set_needs_animated_style_update() only requests a frame when its flag flips from
@@ -9908,47 +9364,24 @@ void Document::update_animations_and_send_events(double timestamp)
// Without this, animations only advance when unrelated tasks happen to schedule rendering
// updates. Keep the frame pump going as long as some animation attached to a monotonically
// increasing timeline needs main-thread painting or observable animation events.
- for (auto const& animation : associated_animations(m_animations)) {
- auto const state = animation.timing_state();
- if (state.play_state != Animations::RustFFI::AnimationPlayState::Running)
- continue;
- if (!state.has_monotonically_increasing_timeline)
- continue;
- if (auto effect = animation.effect(); effect.has_value()) {
- if (effect->can_skip_per_frame_animation_tick()) {
- effect->set_flag(Animations::RustFFI::EffectFlag::PerFrameAnimationTickWasSkipped, true);
- continue;
- }
- effect->set_flag(Animations::RustFFI::EffectFlag::PerFrameAnimationTickWasSkipped, false);
- if (auto iteration_event_time = next_throttled_animation_iteration_event_time(state, *effect); iteration_event_time.has_value()) {
- auto current_time = Animations::from_ffi(state.current_time);
- if (current_time.has_value() && current_time->type == Animations::TimeValue::Type::Milliseconds) {
- auto delay = (*iteration_event_time - current_time->value) / state.playback.playback_rate;
- if (delay > 0) {
- schedule_compositor_animation_wakeup(delay);
- continue;
- }
- }
- }
- }
- HTML::note_rendering_trace_event("animation frame pump request"sv);
- set_rendering_pending(*this, RenderingPendingReason::NeedsRenderingUpdate, 1);
- page().client().request_frame_for(*this);
- break;
- }
+ auto pump = Animations::RustFFI::animations_document_animations_frame_pump(m_animations);
+ if (pump.wakeup_delay.has_value)
+ schedule_compositor_animation_wakeup(pump.wakeup_delay.value);
+ if (!pump.request_frame)
+ return;
+ HTML::note_rendering_trace_event("animation frame pump request"sv);
+ set_rendering_pending(*this, RenderingPendingReason::NeedsRenderingUpdate, 1);
+ page().client().request_frame_for(*this);
}
// https://www.w3.org/TR/web-animations-1/#remove-replaced-animations
void Document::remove_replaced_animations()
{
- Vector<Animations::RustFFI::TimelineCell const*, 8> timelines;
- for (auto const& timeline : m_associated_animation_timelines)
- timelines.append(&timeline->record());
// NB: What the procedure performs for an animation it removes can run the GC, which must not collect the animation.
GC::RootVector<Animations::AnimationRef> removed_animations;
Animations::RustFFI::animations_remove_replaced_animations(
- this, timelines.data(), timelines.size(), Animations::compare_elements_in_tree_order_for_composite_order,
- Animations::keep_animation_alive_in, &removed_animations, Animations::perform_host_effect);
+ m_animations, this, Animations::compare_elements_in_tree_order_for_composite_order,
+ Animations::keep_animation_alive_in, &removed_animations, Animations::web_animation_perform_host_effect);
}
// https://html.spec.whatwg.org/multipage/dom.html#dom-document-nameditem-filter
diff --git a/Libraries/LibWeb/DOM/Document.h b/Libraries/LibWeb/DOM/Document.h
index e44b7f742ce..364bef2440a 100644
--- a/Libraries/LibWeb/DOM/Document.h
+++ b/Libraries/LibWeb/DOM/Document.h
@@ -93,16 +93,10 @@ struct RenderingStats;
}
-namespace Web::Animations {
-
-class AnimationRef;
-class EffectRef;
-
-}
-
namespace Web::Animations::RustFFI {
struct DocumentAnimations;
+struct FfiNamedTimelinesHost;
struct FfiPendingAnimationEvent;
}
@@ -129,6 +123,7 @@ enum class TemporaryDocumentForFragmentParsing : u8 {
};
struct AdoptedStyleSheetsAccess;
+struct CompositorAnimationUpdatePass;
enum class QuirksMode {
No,
@@ -1409,24 +1404,22 @@ public:
void restore_the_history_object_state(NonnullRefPtr<HTML::SessionHistoryEntry> entry);
- GC::Ref<Animations::AnimationTimeline> timeline();
+ // https://www.w3.org/TR/web-animations-1/#dom-document-timeline
+ Animations::TimelineView timeline();
// The scroll progress timelines and view progress timelines the elements of the document declare by name.
Animations::NamedTimelines& named_timelines();
- // The CSS animations of the elements of the document that follow a named timeline, which the document keeps none
- // of alive.
- Animations::WeakAnimationSetView animations_following_named_timelines();
+ // Looks the named timeline each CSS animation that follows one looks up again, answering whether that changed the
+ // timeline of any.
+ bool update_named_timelines_of_animations(Animations::RustFFI::FfiNamedTimelinesHost const&);
bool has_named_timelines() const { return m_named_timelines != nullptr; }
// Moves on whenever the timelines an element declares by name, or the timeline names it scopes, may have changed.
u64 timeline_declarations_generation() const { return m_timeline_declarations_generation; }
void did_change_timeline_declarations() { ++m_timeline_declarations_generation; }
auto const& last_animation_frame_timestamp() const { return m_last_animation_frame_timestamp; }
- void associate_with_timeline(GC::Ref<Animations::AnimationTimeline>);
- void disassociate_with_timeline(GC::Ref<Animations::AnimationTimeline>);
- void associate_with_animation(Animations::AnimationRef const&);
- // Disassociates the animation, whose associated effect was `effect`, from the document.
- void disassociate_with_animation(Animations::AnimationRef const&, Optional<Animations::EffectRef> const& effect);
+ // What the document knows of the animations associated with its elements.
+ Animations::RustFFI::DocumentAnimations& document_animations() const { return *m_animations; }
bool has_associated_animations() const;
// Negative where `first` comes before `second` in tree order and positive where it comes after, for sorting
// animations by composite order. Two distinct elements of this document take no walk of their siblings once a tree
@@ -1443,10 +1436,10 @@ public:
void update_animations_and_send_events(double timestamp);
void prepare_to_observe_css_animation_events();
void update_compositor_animations(Layout::BegunRead const& read);
- void dispatch_events_for_animation_if_necessary(Animations::AnimationRef const&);
void remove_replaced_animations();
- HashTable<GC::Ref<Animations::AnimationTimeline>> const& associated_animation_timelines() const { return m_associated_animation_timelines; }
+ // https://www.w3.org/TR/web-animations-1/#timeline-associated-with-a-document
+ Vector<Animations::TimelineView> associated_animation_timelines() const;
void begin_smil_time_container_once_loaded(SVG::SMILTimeContainer&);
void schedule_svg_referenced_motion_path_update(SVG::SVGAnimateMotionElement&);
@@ -1897,6 +1890,7 @@ private:
void did_add_supported_property_name();
friend struct AdoptedStyleSheetsAccess;
+ friend struct CompositorAnimationUpdatePass;
void republish_svg_patterns_inheriting_from(Utf16FlyString const& id, HashTable<SVG::SVGPatternElement const*>& republished);
@@ -1904,8 +1898,6 @@ private:
void service_compositor_animation_wakeup(double timestamp);
void drain_style_update_that_flew(Layout::BegunRead const&);
- // The effects whose animated style the next animated style update samples, taken out of the document's set, and
- // put back.
// Sets the effects whose animated style the next animated style update samples aside, and back again.
void set_aside_effects_needing_animated_style_update();
void restore_effects_needing_animated_style_update();
@@ -2418,8 +2410,6 @@ private:
// most url() values are.
HashMap<CSS::ImageStyleValueResourceKey, OwnPtr<CSS::ImageStyleValueResource>> m_css_image_resources_with_request_url_modifiers;
- // https://www.w3.org/TR/web-animations-1/#timeline-associated-with-a-document
- HashTable<GC::Ref<Animations::AnimationTimeline>> m_associated_animation_timelines;
Vector<GC::Ref<SVG::SMILTimeContainer>> m_smil_time_containers_to_begin;
Vector<GC::Ref<SVG::SVGAnimateMotionElement>> m_animate_motion_elements_to_update;
@@ -2435,8 +2425,6 @@ private:
u32 m_tree_order_compares_at_dom_tree_version { 0 };
u32 m_element_count_at_last_tree_positions_walk { 0 };
- // https://www.w3.org/TR/web-animations-1/#document-default-document-timeline
- GC::Ptr<Animations::AnimationTimeline> m_default_timeline;
GC::Ptr<Animations::NamedTimelines> m_named_timelines;
u64 m_timeline_declarations_generation { 0 };
Optional<double> m_last_animation_frame_timestamp;
diff --git a/Libraries/LibWeb/DOM/Element.cpp b/Libraries/LibWeb/DOM/Element.cpp
index a3809218898..82a3837dc80 100644
--- a/Libraries/LibWeb/DOM/Element.cpp
+++ b/Libraries/LibWeb/DOM/Element.cpp
@@ -31,7 +31,6 @@
#include <LibWeb/Bindings/Window.h>
#include <LibWeb/Bindings/Wrappable.h>
#include <LibWeb/Bindings/WrapperWorld.h>
-#include <LibWeb/CSS/CSSAnimation.h>
#include <LibWeb/CSS/CSSStyleProperties.h>
#include <LibWeb/CSS/ComputedStyleWorkingSet.h>
#include <LibWeb/CSS/ComputedValues.h>
diff --git a/Libraries/LibWeb/Forward.h b/Libraries/LibWeb/Forward.h
index c1a3640db7a..ab32b7b5284 100644
--- a/Libraries/LibWeb/Forward.h
+++ b/Libraries/LibWeb/Forward.h
@@ -97,11 +97,10 @@ namespace Web::Animations {
class Animatable;
class AnimationRef;
-class AnimationTimeline;
class EffectRef;
class KeyframeSetView;
class NamedTimelines;
-class WeakAnimationSetView;
+class TimelineView;
}
@@ -276,7 +275,6 @@ class ContainerQuery;
class ContentStyleValue;
class CounterDefinitionsStyleValue;
class CounterStyleStyleValue;
-class CSSAnimation;
class CSSDescriptors;
class CSSFontFaceRule;
class CSSFontFeatureValuesRule;
@@ -284,9 +282,7 @@ class CSSFunctionRule;
class CSSGroupingRule;
class CSSImportRule;
class CSSKeyframesRule;
-class CSSKeywordValue;
class CSSNestedDeclarations;
-class CSSNumericValue;
class CSSPositionTryDescriptors;
class CSSRule;
class CSSRuleList;
@@ -295,8 +291,6 @@ class CSSStyleProperties;
class CSSStyleRule;
class CSSStyleSheet;
class StyleSheetState;
-class CSSStyleValue;
-class CSSUnitValue;
class CursorStyleValue;
class CustomIdentStyleValue;
class DimensionStyleValue;
@@ -432,8 +426,6 @@ struct CustomPropertyRegistration;
struct LogicalAliasMappingContext;
struct RequiredInvalidationAfterStyleChange;
-// https://drafts.css-houdini.org/css-typed-om-1/#typedefdef-cssnumberish
-using CSSNumberish = Variant<double, GC::Ref<CSSNumericValue>>;
using PaintOrderList = Array<PaintOrder, 3>;
using StyleValueVector = Vector<ValueComparingNonnullRefPtr<StyleValue const>>;
diff --git a/Libraries/LibWeb/HTML/EventLoop/ClockPlan.cpp b/Libraries/LibWeb/HTML/EventLoop/ClockPlan.cpp
index be8f58d427c..14369d98810 100644
--- a/Libraries/LibWeb/HTML/EventLoop/ClockPlan.cpp
+++ b/Libraries/LibWeb/HTML/EventLoop/ClockPlan.cpp
@@ -6,7 +6,6 @@
#include <AK/Math.h>
#include <LibWeb/Animations/AnimationEffect.h>
-#include <LibWeb/Animations/AnimationTimeline.h>
#include <LibWeb/Animations/RecordHandles.h>
#include <LibWeb/CSS/StyleComputer.h>
#include <LibWeb/CSS/StyleEngineBridge.h>
@@ -73,9 +72,9 @@ static bool tick_can_sample(DOM::Document const& document, Animations::EffectRef
}
// NB: An animation of a scroll timeline that finished runs again as the scroll goes back.
-static bool runs_for_clock_plan(Animations::RustFFI::FfiAnimationTimingState const& state, bool on_scroll_timeline)
+static bool runs_for_clock_plan(Animations::RustFFI::AnimationPlayState play_state, bool on_scroll_timeline)
{
- return state.play_state == Animations::RustFFI::AnimationPlayState::Running || (on_scroll_timeline && state.play_state == Animations::RustFFI::AnimationPlayState::Finished);
+ return play_state == Animations::RustFFI::AnimationPlayState::Running || (on_scroll_timeline && play_state == Animations::RustFFI::AnimationPlayState::Finished);
}
// The compositor runs these on its own, so the render clock does not sample them.
@@ -142,10 +141,10 @@ bool seal_clock_plan(DOM::Document& document, bool may_plan, u64 update_serial)
if (!document.is_fully_active() || document.hidden() || !document.window())
return false;
auto timeline = document.timeline();
- auto timeline_time = timeline->current_time();
- if (!timeline_time.has_value() || timeline_time->type != Animations::TimeValue::Type::Milliseconds)
+ auto timeline_time = timeline.current_time();
+ if (!timeline_time.has_value() || timeline_time->type != Animations::RustFFI::TimeValueType::Milliseconds)
return false;
- auto plan_animation = [&](Animations::AnimationRef const& animation, Animations::RustFFI::FfiAnimationTimingState const& state, Animations::AnimationTimeline const* scroll_timeline, Animations::EffectRef const& effect, DOM::Element const& target) {
+ auto plan_animation = [&](Animations::AnimationRef const& animation, Animations::TimelineView const* scroll_timeline, Animations::EffectRef const& effect, DOM::Element const& target) {
// NB: The record decides what the plan makes of the animation as far as its timing goes. One whose play
// is pending holds still, and the ticks sample nothing of its element.
auto planned = Animations::RustFFI::animations_animation_clock_plan(&animation.record());
@@ -169,25 +168,24 @@ bool seal_clock_plan(DOM::Document& document, bool may_plan, u64 update_serial)
if (!tick_samples)
return true;
if (!scroll_timeline)
- last_end = max(last_end, timeline_time->value + (planned.active_end.value - planned.local_time.value) / state.playback.playback_rate);
+ last_end = max(last_end, timeline_time->value + (planned.active_end.value - planned.local_time.value) / animation.playback_rate());
auto element = target.style_node_id().value();
if (!elements.contains_slow(element))
elements.append(element);
return true;
};
for (auto const& associated_timeline : document.associated_animation_timelines()) {
- Animations::AnimationTimeline const* scroll_timeline = associated_timeline->is_scroll_timeline() ? associated_timeline.ptr() : nullptr;
- for (auto const& animation : associated_timeline->associated_animations()) {
- auto const state = animation.timing_state();
- if (!runs_for_clock_plan(state, scroll_timeline != nullptr))
+ Animations::TimelineView const* scroll_timeline = associated_timeline.is_scroll_timeline() ? &associated_timeline : nullptr;
+ for (auto const& animation : Animations::associated_animations_of(associated_timeline)) {
+ if (!runs_for_clock_plan(animation.play_state(), scroll_timeline != nullptr))
continue;
auto effect = animation.effect();
auto* target = effect.has_value() ? effect->target() : nullptr;
if (!target || &target->document() != &document || !target->is_connected())
continue;
// A tick moves the document's timeline and the scroll timelines alone.
- bool const on_a_ticked_timeline = associated_timeline.ptr() == timeline.ptr() || scroll_timeline;
- if (on_a_ticked_timeline && plan_animation(animation, state, scroll_timeline, *effect, *target))
+ bool const on_a_ticked_timeline = associated_timeline == timeline || scroll_timeline;
+ if (on_a_ticked_timeline && plan_animation(animation, scroll_timeline, *effect, *target))
continue;
// The boxes of an element with an animation a tick cannot sample show what the host's frame shows
// of it, while the ticks sample the others on.
@@ -212,7 +210,7 @@ bool seal_clock_plan(DOM::Document& document, bool may_plan, u64 update_serial)
// A hover decides over the transitions the host runs as they run, where the host runs them without
// sampling them, which leaves the timing the engine holds of them behind.
for (auto const& associated_timeline : document.associated_animation_timelines()) {
- for (auto const& animation : associated_timeline->associated_animations()) {
+ for (auto const& animation : Animations::associated_animations_of(associated_timeline)) {
auto effect = animation.effect();
auto* target = effect.has_value() ? effect->target() : nullptr;
if (!target || effect->pseudo_element_type().has_value() || !target->style_node_id()
diff --git a/Libraries/LibWeb/HTML/EventLoop/EventLoop.cpp b/Libraries/LibWeb/HTML/EventLoop/EventLoop.cpp
index 8df6dedf765..6b5c5327157 100644
--- a/Libraries/LibWeb/HTML/EventLoop/EventLoop.cpp
+++ b/Libraries/LibWeb/HTML/EventLoop/EventLoop.cpp
@@ -14,10 +14,9 @@
#include <LibGC/Heap.h>
#include <LibGC/HeapAccess.h>
#include <LibJS/Runtime/VM.h>
-#include <LibWeb/Animations/AnimationTimeline.h>
#include <LibWeb/Animations/NamedTimelines.h>
+#include <LibWeb/Animations/RecordHandles.h>
#include <LibWeb/Bindings/MainThreadVM.h>
-#include <LibWeb/CSS/CSSTransition.h>
#include <LibWeb/CSS/FontFaceSet.h>
#include <LibWeb/CSS/StyleComputer.h>
#include <LibWeb/CSS/StyleScope.h>
@@ -769,27 +768,6 @@ void EventLoop::finish_rendering_update(double update_start_time)
m_last_rendering_update_end_time = update_end_time;
}
-// Whether `animation` is a CSS animation or transition that the style of a rendering update began, which the update
-// makes ready once its style and layout are done.
-static bool rendering_update_makes_ready(Animations::AnimationRef const& animation)
-{
- auto effect = animation.effect();
- if (!effect.has_value())
- return false;
- auto const state = animation.timing_state();
- return (state.playback.has_pending_play_task || state.playback.has_pending_pause_task)
- && (state.kind == Animations::RustFFI::FfiAnimationKind::CssAnimation || state.kind == Animations::RustFFI::FfiAnimationKind::CssTransition)
- && !effect->may_run_on_the_compositor();
-}
-
-// Whether `animation` runs on the compositor, whose animations, the wake-ups they arm and the ones that leave it, a
-// rendering update publishes with its frame.
-static bool runs_on_the_compositor(Animations::AnimationRef const& animation)
-{
- auto effect = animation.effect();
- return effect.has_value() && effect->is_compositor_driven();
-}
-
enum class StyleTakenIn : u8 {
No,
Yes,
@@ -832,12 +810,8 @@ static HeldTasks tasks_rendering_update_holds(Vector<GC::Root<DOM::Document>> co
return HeldTasks::OfLastDocument;
if (lanes_wait(document))
return HeldTasks::OfLastDocument;
- for (auto const& timeline : document.associated_animation_timelines()) {
- for (auto const& animation : timeline->associated_animations()) {
- if (style_taken_in == StyleTakenIn::No || rendering_update_makes_ready(animation) || runs_on_the_compositor(animation))
- return HeldTasks::OfLastDocument;
- }
- }
+ if (Animations::RustFFI::animations_document_timelines_hold_rendering_update_tasks(&document.document_animations(), style_taken_in == StyleTakenIn::Yes))
+ return HeldTasks::OfLastDocument;
if (style_taken_in == StyleTakenIn::No && document.style_computer().style_engine().css_transitions_may_observe_style_changes())
return HeldTasks::OfLastDocument;
return HeldTasks::None;
@@ -929,7 +903,7 @@ Vector<GC::Root<DOM::Document>> EventLoop::take_clock_lanes_and_input_events_in(
// their reactions run once every document took in what its lanes did.
HTML::TemporaryExecutionContext execution_context { documents_with_lanes.first()->relevant_settings_object() };
for (auto& document : documents_with_lanes)
- CSS::CSSTransition::adopt_lane_transitions(*document);
+ document->style_computer().adopt_lane_transitions();
}
process_input_events();
@@ -1339,19 +1313,17 @@ static void update_style_and_layout_for_rendering(DOM::Document& document, u64 u
if (animations_changed_timeline)
requires_style_and_layout_update = true;
- GC::RootVector timelines = { document.associated_animation_timelines().values() };
- for (auto const& timeline : timelines) {
- if (!timeline->is_scroll_timeline())
- continue;
-
- if (animations_changed_timeline) {
- // NB: The passed timestamp is ignored for ScrollTimelines so we can just use 0.
- timeline->update_current_time(0);
- requires_style_and_layout_update = true;
- continue;
- }
-
- if (timeline->update_current_time_if_stale())
+ {
+ // NB: The animations the timelines update stay alive through it, which can run script.
+ GC::RootVector<Animations::AnimationRef> updated_animations;
+ Animations::RustFFI::FfiTimelineAnimationsHost host {
+ .context = &updated_animations,
+ .keep_alive = Animations::keep_animation_alive_in,
+ .perform = Animations::web_animation_perform_host_effect,
+ };
+ // https://drafts.csswg.org/scroll-animations-1/#stale-timelines
+ auto update = animations_changed_timeline ? Animations::RustFFI::FfiTimelinesUpdate::ScrollTimelines : Animations::RustFFI::FfiTimelinesUpdate::StaleScrollTimelines;
+ if (Animations::RustFFI::animations_document_update_timelines(&document.document_animations(), update, 0, &host))
requires_style_and_layout_update = true;
}
@@ -1374,17 +1346,9 @@ void EventLoop::update_the_rendering_after_style_and_layout(Vector<GC::Root<DOM:
for (auto& document : docs) {
// NB: A play task resolves the animation's ready promise.
TemporaryExecutionContext execution_context { document->relevant_settings_object() };
- GC::RootVector timelines = { document->associated_animation_timelines().values() };
- for (auto const& timeline : timelines) {
- // NB: Running a play task can run script, which the animations stay alive through.
- GC::RootVector<Animations::AnimationRef> pending_css_animations;
- for (auto const& animation : timeline->associated_animations()) {
- if (rendering_update_makes_ready(animation))
- pending_css_animations.append(animation);
- }
- for (auto const& animation : pending_css_animations)
- animation.run_pending_play_task_if_ready();
- }
+ // NB: Running a play task can run script, which the animations stay alive through.
+ GC::RootVector<Animations::AnimationRef> pending_css_animations;
+ Animations::RustFFI::animations_document_run_pending_css_play_tasks(&document->document_animations(), &pending_css_animations, Animations::keep_animation_alive_in, Animations::web_animation_perform_host_effect);
}
// 17. For each doc of docs, if the focused area of doc is not a focusable area, then run the focusing steps for doc's viewport, and set doc's relevant global object's navigation API's focus changed during ongoing navigation to false.
@@ -1535,10 +1499,8 @@ Layout::RustFFI::FfiFlightBlocker EventLoop::style_flight_blocker(DOM::Document&
return Blocker::ScrollStateContainer;
if (document.has_boxes_with_auto_content_visibility())
return Blocker::ContentVisibilityAuto;
- for (auto const& timeline : document.associated_animation_timelines()) {
- if (timeline->is_scroll_timeline())
- return Blocker::ScrollTimeline;
- }
+ if (Animations::RustFFI::animations_document_animations_query(&document.document_animations(), Animations::RustFFI::DocumentAnimationsQuery::AnyScrollTimeline))
+ return Blocker::ScrollTimeline;
// The animations that name their timeline look it up again after style and layout.
if (document.has_named_timelines())
return Blocker::ScrollTimeline;
diff --git a/Libraries/LibWeb/Internals/Internals.cpp b/Libraries/LibWeb/Internals/Internals.cpp
index f55a5588deb..8070cc64ea1 100644
--- a/Libraries/LibWeb/Internals/Internals.cpp
+++ b/Libraries/LibWeb/Internals/Internals.cpp
@@ -22,6 +22,7 @@
#include <LibGfx/Cursor.h>
#include <LibHTTP/Cache/Utilities.h>
#include <LibHTTP/HSTS/ParsedHSTSPolicy.h>
+#include <LibJS/HostClassBuilder.h>
#include <LibJS/Runtime/AbstractOperations.h>
#include <LibJS/Runtime/Array.h>
#include <LibJS/Runtime/Date.h>
@@ -33,7 +34,7 @@
#include <LibURL/Parser.h>
#include <LibWeb/ARIA/AriaData.h>
#include <LibWeb/ARIA/StateAndProperties.h>
-#include <LibWeb/Animations/AnimationTimeline.h>
+#include <LibWeb/Animations/RecordHandles.h>
#include <LibWeb/Bindings/Internals.h>
#include <LibWeb/Bindings/Intrinsics.h>
#include <LibWeb/Bindings/MainThreadVM.h>
@@ -1340,9 +1341,13 @@ void Internals::load_url(Utf16String const& url_string)
});
}
+// Defined in Bindings/Rust/src/internals/internal_animation_timeline.rs.
+extern "C" void* web_internal_animation_timeline_create(JSVM*, DOM::Document*);
+
GC::Ref<InternalAnimationTimeline> Internals::create_internal_animation_timeline()
{
- return static_cast<InternalAnimationTimeline&>(static_cast<Bindings::RustInterfaceCell&>(*Animations::AnimationTimeline::create_internal_timeline(window().associated_document())));
+ auto* cell = web_internal_animation_timeline_create(JS::HostABI::vm_to_abi(JS::VM::the()), &window().associated_document());
+ return static_cast<InternalAnimationTimeline&>(*static_cast<Bindings::RustInterfaceCell*>(cell));
}
WebIDL::ExceptionOr<void> Internals::simulate_drag_start(double x, double y, Utf16String const& name, Utf16String const& contents)
@@ -3118,6 +3123,10 @@ void Internals::force_parallel_layout()
Layout::RustFFI::render_state_force_parallel_layout(window().associated_document().layout_node_arena().host());
}
+// The bytes of the objects script sees of an animation and of its associated effect, beside their records. Defined in
+// Bindings/Rust/src/animations/animation.rs.
+extern "C" size_t web_animation_object_memory_size(Animations::RustFFI::AnimationCell const*);
+
// NB: The Animation objects of the animations associated with the document's elements, which a CSS animation or
// transition only has once script asks for it.
static u64 animation_object_bytes(DOM::Document& document)
@@ -3125,29 +3134,23 @@ static u64 animation_object_bytes(DOM::Document& document)
u64 bytes = 0;
document.for_each_in_inclusive_subtree_of_type<DOM::Element>([&](DOM::Element& element) {
for (auto const& animation : element.associated_animations_unordered())
- bytes += Animations::object_memory_size(animation);
+ bytes += web_animation_object_memory_size(&animation.record());
return TraversalDecision::Continue;
});
return bytes;
}
-// The records the C++ animation objects keep their state in, the keyframe sets they run, each counted once however
-// many effects share it, and each element's lists of its animations and transitions.
+// NB: The records animations and their effects keep their state in, the keyframe sets they run, each counted once
+// however many effects share it, and each element's lists of its animations and transitions.
static u64 animation_record_bytes(DOM::Document& document)
{
u64 bytes = 0;
HashTable<Animations::RustFFI::KeyframeSet const*> counted_keyframe_sets;
document.for_each_in_inclusive_subtree_of_type<DOM::Element>([&](DOM::Element& element) {
- bytes += element.animation_lists_memory_size();
- for (auto const& animation : element.associated_animations_unordered()) {
- bytes += Animations::RustFFI::animations_animation_memory_size(&animation.record());
- auto effect = animation.effect();
- if (!effect.has_value())
- continue;
- bytes += Animations::RustFFI::animations_effect_memory_size(&effect->record());
- if (auto const* keyframe_set = effect->keyframe_set().ptr(); keyframe_set && counted_keyframe_sets.set(keyframe_set) == HashSetResult::InsertedNewEntry)
- bytes += Animations::RustFFI::animations_keyframe_set_memory_size(keyframe_set);
- }
+ bytes += element.animation_record_memory_size([](void* context, Animations::RustFFI::KeyframeSet const* keyframe_set) {
+ return static_cast<HashTable<Animations::RustFFI::KeyframeSet const*>*>(context)->set(keyframe_set) == HashSetResult::InsertedNewEntry;
+ },
+ &counted_keyframe_sets);
return TraversalDecision::Continue;
});
return bytes;
diff --git a/Libraries/LibWeb/Painting/CompositorAnimationEffectState.cpp b/Libraries/LibWeb/Painting/CompositorAnimationEffectState.cpp
deleted file mode 100644
index 7486f19fa16..00000000000
--- a/Libraries/LibWeb/Painting/CompositorAnimationEffectState.cpp
+++ /dev/null
@@ -1,251 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibWeb/Animations/RecordHandles.h>
-#include <LibWeb/CSS/ComputedValues.h>
-#include <LibWeb/CSS/EasingFunction.h>
-#include <LibWeb/CSS/StyleComputer.h>
-#include <LibWeb/CSS/StyleValues/ComputationContext.h>
-#include <LibWeb/DOM/AbstractElement.h>
-#include <LibWeb/DOM/Document.h>
-#include <LibWeb/DOM/Element.h>
-#include <LibWeb/HTML/EventLoop/EventLoop.h>
-#include <LibWeb/Layout/LayoutRustFFI.h>
-#include <LibWeb/Layout/Node.h>
-#include <LibWeb/Page/Page.h>
-#include <LibWeb/Painting/BoxViews.h>
-#include <LibWeb/Painting/CompositorAnimationEffectState.h>
-
-namespace Web::Painting {
-
-struct CompositorAnimationKeyframes::Data {
- AK_ALLOC_WITH_KMALLOC;
-
- Data(Animations::EffectRef effect, Animations::AnimationRef animation, DOM::AbstractElement target)
- : effect(move(effect))
- , animation(move(animation))
- , target(target)
- {
- }
-
- Animations::EffectRef effect;
- Animations::AnimationRef animation;
- DOM::AbstractElement target;
- // The keyframes the builder reads, which the build keeps live.
- Animations::KeyframeSetHandle keyframe_set;
- // The easing a keyframe that declares none runs, with the linear easing control points its descriptor borrows.
- Vector<Compositing::RustFFI::FfiLinearEasingPoint> default_easing_points;
- Compositing::RustFFI::FfiEasingDescriptor default_easing {};
-};
-
-CompositorAnimationKeyframes::CompositorAnimationKeyframes(Animations::EffectRef const& effect, Animations::AnimationRef const& animation, DOM::AbstractElement target)
- : m_data(make<Data>(effect, animation, target))
-{
- m_data->keyframe_set = Animations::KeyframeSetHandle::retained(effect.keyframe_set().ptr());
- if (animation.timing_state().kind != Animations::RustFFI::FfiAnimationKind::CssAnimation) {
- m_data->default_easing = CSS::EasingFunction::linear().descriptor_with_points_in(m_data->default_easing_points);
- return;
- }
- auto default_easing = Animations::RustFFI::animations_css_animation_state(&animation.record()).default_easing;
- m_data->default_easing_points.append(default_easing.linear_points, default_easing.linear_point_count);
- default_easing.linear_points = m_data->default_easing_points.data();
- m_data->default_easing = default_easing;
-}
-
-CompositorAnimationKeyframes::~CompositorAnimationKeyframes() = default;
-
-void CompositorAnimationKeyframes::visit_edges(GC::Cell::Visitor& visitor) const
-{
- m_data->effect.visit_edges(visitor);
- m_data->animation.visit_edges(visitor);
- m_data->target.visit_edges(visitor);
-}
-
-static RefPtr<CSS::StyleValue const> resolved_compositor_animation_style_value(Layout::BegunRead const& read, CSS::PropertyID property_id, CSS::StyleValueFFI::StyleValueData const* value, DOM::AbstractElement target)
-{
- HTML::note_rendering_trace_event("compositor keyframe values resolved"sv);
- auto style_value = CSS::StyleValue::adopt_rust_style_value_data(CSS::StyleValueFFI::rust_style_value_retain(value));
- if (style_value->is_unresolved()) {
- // The engine substitutes the value as a sample on the main thread would, against the custom properties the
- // element holds and inherits.
- auto custom_property_data = target.custom_property_data();
- auto inheritance_parent = target.element_to_inherit_style_from();
- auto inheritance_custom_property_data = inheritance_parent.has_value() ? inheritance_parent->custom_property_data() : nullptr;
- auto const* substituted = CSS::StyleValueFFI::rust_substitute_compositor_keyframe_value(
- target.document().style_computer().style_engine().host(),
- &read, target.element().style_node_id().value(),
- CSS::pseudo_element_to_ffi(target.pseudo_element()),
- custom_property_data ? custom_property_data->rust_store() : nullptr,
- inheritance_custom_property_data ? inheritance_custom_property_data->rust_store() : nullptr,
- to_underlying(property_id),
- value);
- if (!substituted)
- return nullptr;
- style_value = CSS::StyleValue::adopt_rust_style_value_data(substituted);
- }
- if (style_value->is_guaranteed_invalid() || style_value->is_unresolved() || style_value->is_pending_substitution())
- return nullptr;
- // Absolutizing against the target's used color-scheme collapses light-dark() as computing the value would, so
- // the color the builder resolves needs no length context.
- auto const* inherited_ui_values = target.style_group<CSS::ComputedValues::InheritedUIValues>();
- CSS::ComputationContext computation_context {
- .length_resolution_context = CSS::Length::ResolutionContext::for_element(target),
- .abstract_element = target,
- .color_scheme = inherited_ui_values ? inherited_ui_values->color_scheme_value() : Optional<CSS::PreferredColorScheme> {},
- };
- return style_value->absolutized(computation_context);
-}
-
-// What a build lends the callbacks the animation's host makes: the keyframes it builds from, in the read it builds in.
-struct CompositorAnimationBuild {
- CompositorAnimationKeyframes::Data& data;
- Layout::BegunRead const& read;
-};
-
-static void const* resolved_compositor_keyframe_value(void* context, u16 property_id, void const* declared_value)
-{
- auto& [data, read] = *static_cast<CompositorAnimationBuild*>(context);
- auto property = static_cast<CSS::PropertyID>(property_id);
- RefPtr<CSS::StyleValue const> style_value;
- if (!declared_value) {
- // NB: Synthesized endpoints use the underlying style, just as main-thread keyframe sampling does.
- auto computed_style = data.target.computed_style();
- if (!computed_style)
- return nullptr;
- style_value = computed_style->computed_style_value(property, CSS::ComputedValues::WithAnimationsApplied::No);
- } else {
- style_value = resolved_compositor_animation_style_value(read, property, static_cast<CSS::StyleValueFFI::StyleValueData const*>(declared_value), data.target);
- }
- if (!style_value)
- return nullptr;
- return CSS::StyleValueFFI::rust_style_value_retain(style_value->rust_style_value_data());
-}
-
-static Layout::RustFFI::FfiCompositorAnimationHost compositor_animation_host(CompositorAnimationBuild& lent)
-{
- return {
- .context = &lent,
- .resolved_keyframe_value = resolved_compositor_keyframe_value,
- };
-}
-
-static Layout::RustFFI::FfiCompositorAnimationRequest compositor_animation_request(CompositorAnimationKeyframes::Data const& data, Layout::Node const& layout_node, Compositing::RustFFI::FfiVisualAnimationTargetKind target_kind)
-{
- auto const& effect = data.effect;
- Layout::RustFFI::FfiCompositorAnimationRequest request {};
- request.target_kind = target_kind;
- request.layout_node = Layout::Node::slot_id(&layout_node);
- auto target_color_resolution_style = CSS::ColorResolutionStyle::for_element(data.target);
- request.target_inherited_ui_values = target_color_resolution_style.inherited_ui_values;
- request.target_inherited_text_values = target_color_resolution_style.inherited_text_values;
- request.keyframe_set = data.keyframe_set.ptr();
- request.effect_composite_is_replace = effect.composite_is_replace();
- request.default_easing = data.default_easing;
- request.target_style_generation = data.target.element().animation_style_generation();
- request.style_environment_version = data.target.document().style_computer().style_environment_version_for_sharing();
- if (target_kind == Compositing::RustFFI::FfiVisualAnimationTargetKind::Transform) {
- auto reference_box_size = transform_reference_box(layout_node).size();
- request.reference_box_width = reference_box_size.width().to_float();
- request.reference_box_height = reference_box_size.height().to_float();
- }
- request.device_pixels_per_css_pixel = static_cast<float>(data.target.document().page().client().device_pixels_per_css_pixel());
- for (auto const& property : effect.target_properties()) {
- switch (property.id()) {
- case CSS::PropertyID::Translate:
- request.targeted_transform_properties |= Layout::RustFFI::TARGETED_TRANSFORM_PROPERTY_TRANSLATE;
- break;
- case CSS::PropertyID::Rotate:
- request.targeted_transform_properties |= Layout::RustFFI::TARGETED_TRANSFORM_PROPERTY_ROTATE;
- break;
- case CSS::PropertyID::Scale:
- request.targeted_transform_properties |= Layout::RustFFI::TARGETED_TRANSFORM_PROPERTY_SCALE;
- break;
- case CSS::PropertyID::Transform:
- request.targeted_transform_properties |= Layout::RustFFI::TARGETED_TRANSFORM_PROPERTY_TRANSFORM;
- break;
- default:
- break;
- }
- }
- request.targets_only_transform = effect.target_properties().size() == 1
- && effect.target_properties().contains(CSS::PropertyNameAndID::from_id(CSS::PropertyID::Transform));
- return request;
-}
-
-bool CompositorAnimationKeyframes::transform_preserves_axes(Layout::Node const& layout_node) const
-{
- CompositorAnimationBuild lent { *m_data, layout_node.held_read() };
- auto request = compositor_animation_request(*m_data, layout_node, Compositing::RustFFI::FfiVisualAnimationTargetKind::Transform);
- auto host = compositor_animation_host(lent);
- return Layout::RustFFI::compositor_animation_effect_transform_preserves_axes(&request, &host);
-}
-
-bool CompositorAnimationKeyframes::only_translates_horizontally(Layout::Node const& layout_node) const
-{
- CompositorAnimationBuild lent { *m_data, layout_node.held_read() };
- auto request = compositor_animation_request(*m_data, layout_node, Compositing::RustFFI::FfiVisualAnimationTargetKind::Transform);
- auto host = compositor_animation_host(lent);
- return Layout::RustFFI::compositor_animation_effect_only_translates_horizontally(&request, &host);
-}
-
-static Layout::RustFFI::DocumentHost* document_host(DOM::Document& document)
-{
- return document.layout_node_arena().host();
-}
-
-CompositorAnimationEffectState::BuildOutcome CompositorAnimationEffectState::build(Layout::BegunRead const& read, CompositorAnimationKeyframes const& keyframes, Layout::Node const& layout_node, Compositing::RustFFI::FfiVisualAnimationTargetKind target_kind, TimingAnchor timing_anchor)
-{
- auto& data = *keyframes.m_data;
- auto const& effect = data.effect;
- auto request = compositor_animation_request(data, layout_node, target_kind);
- Vector<Compositing::RustFFI::FfiLinearEasingPoint> effect_easing_points;
- request.timing.monotonic_time_at_anchor_ns = static_cast<i64>(timing_anchor.monotonic_time_ms * 1'000'000.0);
- request.timing.local_time_at_anchor_ms = timing_anchor.local_time_ms;
- request.timing.playback_rate = Animations::RustFFI::animations_animation_playback(&data.animation.record()).playback_rate;
- request.timing.effect = effect.timing();
- request.timing.easing = effect.timing_function_with_points_in(effect_easing_points);
-
- CompositorAnimationBuild lent { data, read };
- auto host = compositor_animation_host(lent);
- auto outcome = Layout::RustFFI::compositor_animation_effect_build(m_handle, document_host(data.target.document()), &request, &host);
- return {
- .built = outcome.built,
- .missing_visual_context_node = outcome.missing_visual_context_node,
- .only_translates_horizontally = outcome.only_translates_horizontally_is_known ? Optional<bool> { outcome.only_translates_horizontally } : Optional<bool> {},
- };
-}
-
-void CompositorAnimationEffectState::discard_pending(Compositing::RustFFI::FfiVisualAnimationTargetKind target_kind)
-{
- Layout::RustFFI::compositor_animation_effect_discard_pending(m_handle, target_kind);
-}
-
-bool CompositorAnimationEffectState::has_pending() const
-{
- return Layout::RustFFI::compositor_animation_effect_has_pending(m_handle);
-}
-
-void CompositorAnimationEffectState::clear_pending()
-{
- Layout::RustFFI::compositor_animation_effect_clear_pending(m_handle);
-}
-
-void CompositorAnimationEffectState::publish_pending(DOM::Document& document, ReuseRetainedTimingAnchors reuse_retained_timing_anchors)
-{
- Layout::RustFFI::compositor_animation_effect_publish_pending(m_handle, document.layout_node_arena().host(), reuse_retained_timing_anchors == ReuseRetainedTimingAnchors::Yes);
-}
-
-bool CompositorAnimationEffectState::has_retained() const
-{
- return Layout::RustFFI::compositor_animation_effect_has_retained(m_handle);
-}
-
-void CompositorAnimationEffectState::clear_retained()
-{
- Layout::RustFFI::compositor_animation_effect_clear_retained(m_handle);
-}
-
-}
diff --git a/Libraries/LibWeb/Painting/CompositorAnimationEffectState.h b/Libraries/LibWeb/Painting/CompositorAnimationEffectState.h
deleted file mode 100644
index 860cbcf110c..00000000000
--- a/Libraries/LibWeb/Painting/CompositorAnimationEffectState.h
+++ /dev/null
@@ -1,103 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/Noncopyable.h>
-#include <AK/NonnullOwnPtr.h>
-#include <AK/Optional.h>
-#include <AK/Types.h>
-#include <LibGC/Cell.h>
-#include <LibWeb/Export.h>
-#include <LibWeb/Forward.h>
-
-namespace Web::Layout::RustFFI {
-
-enum class FfiVisualAnimationTargetKind : u8;
-
-}
-
-namespace Web::Painting {
-
-// The keyframes of an effect as the compositor animation builder reads them: the effect's keyframe
-// set, with the easing a keyframe that declares none runs, and the target the builder resolves the
-// values they declare against. An update pass builds them once for each effect it asks about.
-class WEB_API CompositorAnimationKeyframes {
- AK_MAKE_NONCOPYABLE(CompositorAnimationKeyframes);
- AK_MAKE_NONMOVABLE(CompositorAnimationKeyframes);
-
-public:
- AK_ALLOC_WITH_KMALLOC;
-
- CompositorAnimationKeyframes(Animations::EffectRef const&, Animations::AnimationRef const&, DOM::AbstractElement target);
- ~CompositorAnimationKeyframes();
-
- // Visits what keeps the effect, its animation and the target alive, which the holder of the keyframes traces.
- void visit_edges(GC::Cell::Visitor&) const;
-
- // Whether the transforms the effect animates keep the axes in place: it does not rotate, and
- // its transform keyframes only translate and scale.
- bool transform_preserves_axes(Layout::Node const&) const;
- // Whether the effect targets only the transform property and only ever translates horizontally.
- bool only_translates_horizontally(Layout::Node const&) const;
-
- struct Data;
-
-private:
- friend class CompositorAnimationEffectState;
-
- NonnullOwnPtr<Data> m_data;
-};
-
-// What a keyframe effect has built for the compositor, which the effect's record keeps in Rust: the values lowered
-// from its keyframes, the animations built in the current update pass, and the ones it published last. This borrows
-// it from the record, which keeps it for as long as the effect lives and forgets it as the effect changes.
-class WEB_API CompositorAnimationEffectState {
-public:
- explicit CompositorAnimationEffectState(void* handle)
- : m_handle(handle)
- {
- }
-
- struct BuildOutcome {
- // The animation is built and waits with the effect's other pending animations.
- bool built { false };
- // The animation was valid but the target owns no node of the kind it drives yet.
- bool missing_visual_context_node { false };
- // Whether a transform animation's keyframes only ever translate horizontally, once known.
- Optional<bool> only_translates_horizontally;
- };
-
- // The instant the animation is anchored at, as the monotonic clock and the animation's own
- // local time; the compositor derives every later local time from it.
- struct TimingAnchor {
- double monotonic_time_ms { 0 };
- double local_time_ms { 0 };
- };
-
- // Builds the animation of one target kind from the effect's keyframes and timing for the nodes
- // of the target's box, and keeps it pending. The builder in Rust lowers and validates the
- // keyframes.
- BuildOutcome build(Layout::BegunRead const&, CompositorAnimationKeyframes const&, Layout::Node const&, Compositing::RustFFI::FfiVisualAnimationTargetKind, TimingAnchor);
- void discard_pending(Compositing::RustFFI::FfiVisualAnimationTargetKind);
- bool has_pending() const;
- void clear_pending();
-
- enum class ReuseRetainedTimingAnchors : u8 {
- No,
- Yes,
- };
- // The pending animations become the retained ones, and copies join the document's list for the
- // current update pass.
- void publish_pending(DOM::Document&, ReuseRetainedTimingAnchors);
- bool has_retained() const;
- void clear_retained();
-
-private:
- void* m_handle { nullptr };
-};
-
-}
diff --git a/Libraries/LibWeb/Painting/PaintingRustBridge.cpp b/Libraries/LibWeb/Painting/PaintingRustBridge.cpp
index dd9d1495fac..971076fa24b 100644
--- a/Libraries/LibWeb/Painting/PaintingRustBridge.cpp
+++ b/Libraries/LibWeb/Painting/PaintingRustBridge.cpp
@@ -12,7 +12,7 @@
#include <LibGfx/GradientInterpolation.h>
#include <LibGfx/Matrix4x4.h>
#include <LibGfx/TextLayout.h>
-#include <LibWeb/Animations/AnimationTimeline.h>
+#include <LibWeb/Animations/RecordHandles.h>
#include <LibWeb/CSS/Enums.h>
#include <LibWeb/CSS/StyleValues/AbstractImageStyleValue.h>
#include <LibWeb/CSS/VisualViewport.h>
@@ -427,7 +427,7 @@ void take_recording_trace_if_pending(Layout::BegunRead const& read, DOM::Documen
// update's never show them before it.
static double rendering_update_timestamp(DOM::Document& document)
{
- if (auto time = document.timeline()->current_time(); time.has_value() && time->type == Animations::TimeValue::Type::Milliseconds)
+ if (auto time = document.timeline().current_time(); time.has_value() && time->type == Animations::RustFFI::TimeValueType::Milliseconds)
return time->value;
return -AK::Infinity<double>;
}
diff --git a/Libraries/LibWeb/Rust/build.rs b/Libraries/LibWeb/Rust/build.rs
index 4b2f58b80d6..83d45ac6275 100644
--- a/Libraries/LibWeb/Rust/build.rs
+++ b/Libraries/LibWeb/Rust/build.rs
@@ -3152,24 +3152,16 @@ fn main() -> Result<(), Box<dyn Error>> {
Path::new("Layout/TreeBuilderRustFFI.h"),
);
- // The Web Animations timing model - namespace Web::Animations::RustFFI. A time value is laid out as the C++
- // Animations::TimeValue, which C++ passes it as, and an easing descriptor is the compositing header's.
+ // The Web Animations timing model - namespace Web::Animations::RustFFI. An easing descriptor is the compositing
+ // header's.
let mut animations_config = base_config.clone();
animations_config.namespaces = Some(vec!["Web".to_string(), "Animations".to_string(), "RustFFI".to_string()]);
- for (rust_name, cpp_name) in [
- ("TimeValue", "Web::Animations::TimeValue"),
- ("TimeValueType", "Web::Animations::TimeValue::Type"),
- ("FfiEasingDescriptor", "Compositing::RustFFI::FfiEasingDescriptor"),
- ] {
- animations_config.export.exclude.push(rust_name.to_string());
- animations_config
- .export
- .rename
- .insert(rust_name.to_string(), cpp_name.to_string());
- }
- animations_config
- .includes
- .extend(["LibCompositing/RustFFI.h", "LibWeb/Animations/TimeValue.h"].map(String::from));
+ animations_config.export.exclude.push("FfiEasingDescriptor".to_string());
+ animations_config.export.rename.insert(
+ "FfiEasingDescriptor".to_string(),
+ "Compositing::RustFFI::FfiEasingDescriptor".to_string(),
+ );
+ animations_config.includes.push("LibCompositing/RustFFI.h".to_string());
// A keyframe set notes the attributes its values read through the document's host, and a scroll timeline measures
// the boxes it follows there.
declare_document_host_of_layout_header(&mut animations_config);
@@ -3178,13 +3170,6 @@ fn main() -> Result<(), Box<dyn Error>> {
.export
.rename
.insert("NodeSlotId".to_string(), "Compositing::RustFFI::NodeSlotId".to_string());
- // The host defines what the reflection of the keyframes of CSS asks of the style of their target.
- for name in [
- "web_animation_compute_css_keyframe_values",
- "web_animation_effective_zoom_of_target",
- ] {
- animations_config.export.exclude.push(name.to_string());
- }
// An effect's composite operation is the style value header's.
animations_config
.export
@@ -3238,12 +3223,52 @@ fn main() -> Result<(), Box<dyn Error>> {
.export
.exclude
.push("ladybird_animations_document_is_active".to_string());
- // The timing the host publishes of an effect it samples, an effect it samples, and a timeline it creates through
- // the bindings, which no function here takes.
animations_config
.export
- .include
- .extend(["EffectTimingSnapshot", "FfiSampledEffect", "FfiTimelineDescription"].map(String::from));
+ .exclude
+ .push("ladybird_animations_element_node_document".to_string());
+ animations_config
+ .export
+ .exclude
+ .push("web_animation_target_facts".to_string());
+ animations_config
+ .export
+ .exclude
+ .push("web_animation_note_rendering_trace_event".to_string());
+ animations_config
+ .export
+ .exclude
+ .push("web_animation_compute_css_keyframe_values".to_string());
+ animations_config
+ .export
+ .exclude
+ .push("web_animation_effective_zoom_of_target".to_string());
+ animations_config
+ .export
+ .exclude
+ .push("web_animation_set_needs_animated_style_update".to_string());
+ // The host defines what the timelines associated with a document ask of it.
+ for name in [
+ "web_animation_document_animations",
+ "web_animation_document_clock",
+ "web_animation_find_scroll_timeline_boxes",
+ "web_animation_scroll_timeline_source",
+ ] {
+ animations_config.export.exclude.push(name.to_string());
+ }
+ // The timing the host publishes of an effect it samples, an effect it samples, and a timeline it creates through
+ // the bindings, which no function here takes.
+ animations_config.export.include.extend(
+ [
+ "EffectTimingSnapshot",
+ "FfiSampledEffect",
+ "FfiTargetFacts",
+ "FfiTimelineDescription",
+ "FfiDocumentClock",
+ "FfiScrollTimelineBoxes",
+ ]
+ .map(String::from),
+ );
let animation_timing_dir = manifest_dir.join("../../LibCompositing/Rust/src/animation_timing");
println!("cargo:rerun-if-changed={}", animation_timing_dir.display());
generate_ffi_header(
@@ -3254,6 +3279,7 @@ fn main() -> Result<(), Box<dyn Error>> {
animation_timing_dir.join("playback.rs"),
manifest_dir.join("src/animations/animation.rs"),
manifest_dir.join("src/animations/effect.rs"),
+ manifest_dir.join("src/animations/compositor_update.rs"),
manifest_dir.join("src/animations/document_animations.rs"),
manifest_dir.join("src/animations/element_animations.rs"),
manifest_dir.join("src/animations/ffi.rs"),
@@ -3262,8 +3288,11 @@ fn main() -> Result<(), Box<dyn Error>> {
manifest_dir.join("src/animations/css_events.rs"),
manifest_dir.join("src/animations/keyframes.rs"),
manifest_dir.join("src/animations/pending_animation_events.rs"),
+ manifest_dir.join("src/animations/rendering_update.rs"),
manifest_dir.join("src/animations/snapshot.rs"),
+ manifest_dir.join("src/animations/throttling.rs"),
manifest_dir.join("src/animations/timeline.rs"),
+ manifest_dir.join("src/animations/timeline_host.rs"),
manifest_dir.join("src/animations/transitions.rs"),
],
&out_dir,
@@ -3351,6 +3380,12 @@ fn main() -> Result<(), Box<dyn Error>> {
layout_config.export.rename.insert(name.to_string(), "void".to_string());
layout_config.export.exclude.push(name.to_string());
}
+ // The host fills in a compositor animation request, and the host its keyframes resolve with, as the animation
+ // records ask it to, which no function here takes.
+ layout_config
+ .export
+ .include
+ .extend(["FfiCompositorAnimationRequest", "FfiCompositorAnimationHost"].map(String::from));
// The effects whose descriptions and samples cross here are named by their identities.
declare_animation_effect_id_of_animations_header(&mut layout_config);
generate_ffi_header(
diff --git a/Libraries/LibWeb/Rust/src/animations/animation.rs b/Libraries/LibWeb/Rust/src/animations/animation.rs
index 4a37dd23dc5..4004ba2705c 100644
--- a/Libraries/LibWeb/Rust/src/animations/animation.rs
+++ b/Libraries/LibWeb/Rust/src/animations/animation.rs
@@ -79,7 +79,6 @@ pub(crate) struct OwningElement {
}
/// What the host's `CSSAnimation` notes of what script did to it and what it is doing, by bit.
-#[repr(u8)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CssAnimationFlag {
/// Script changed the play state, which `animation-play-state` no longer changes.
@@ -117,12 +116,29 @@ pub(crate) struct CssAnimationState {
pub(crate) flags: u8,
}
+impl CssAnimationState {
+ pub(crate) fn has_flag(&self, flag: CssAnimationFlag) -> bool {
+ self.flags & flag as u8 != 0
+ }
+
+ pub(crate) fn set_flag(&mut self, flag: CssAnimationFlag) {
+ self.flags |= flag as u8;
+ }
+}
+
/// The host's `CSS::AnimationPlayState::Paused` and `CSS::AnimationPlayState::Running`.
pub(crate) const CSS_ANIMATION_PLAY_STATE_PAUSED: u8 = 0;
pub(crate) const CSS_ANIMATION_PLAY_STATE_RUNNING: u8 = 1;
-/// The host's `CSSTransition::Phase::Idle`.
-pub(crate) const CSS_TRANSITION_PHASE_IDLE: u8 = 3;
+/// https://drafts.csswg.org/css-transitions-2/#transition-phase
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) enum TransitionPhase {
+ Before,
+ Active,
+ After,
+ Idle,
+ Pending,
+}
/// The state of a CSS transition.
/// https://drafts.csswg.org/css-transitions-2/#the-CSSTransition-interface
@@ -145,8 +161,8 @@ pub(crate) struct CssTransitionState {
pub(crate) reversing_shortening_factor: f64,
/// The host's `PropertyID` of the property the transition runs.
pub(crate) property_id: u16,
- /// The host's `CSSTransition::Phase` the transition was in when the host last dispatched its events.
- pub(crate) previous_phase: u8,
+ /// The phase the transition was in when its events were last established.
+ pub(crate) previous_phase: TransitionPhase,
/// Whether the transition was started provisionally and is neither committed nor discarded yet.
pub(crate) provisional: bool,
/// Whether the transition is one the hover of a clock lane started, which the host took in.
@@ -180,7 +196,7 @@ pub(crate) enum AnimationKind {
/// The host's `SVGAnimationElement` whose animation it is, which whatever the GC traces of the host that holds
/// the record keeps alive.
animation_element: NonNull<c_void>,
- /// The `SmilHolders` that hold the animation.
+ /// The `SmilHolder` bits of what holds the animation.
holders: u8,
},
}
@@ -198,7 +214,6 @@ pub enum HostCellKind {
/// What of the host holds the animation of an SVG animation element, by bit. The animation is alive to the host while
/// one does, as each lets go of it when it is done with it or the host finalizes it.
#[derive(Clone, Copy)]
-#[repr(u8)]
pub(crate) enum SmilHolder {
/// Its animation element, until it lets go of the animation or is finalized.
AnimationElement = 1 << 0,
@@ -225,20 +240,20 @@ pub(crate) struct AnimationRecord {
/// found finished, and the replace state.
playback: AnimationPlayback,
/// https://www.w3.org/TR/web-animations-1/#previous-current-time
- previous_current_time: Option<TimeValue>,
- /// The current time of the associated effect where the animation was last cancelled, until the host takes it.
- saved_cancel_time: Option<TimeValue>,
+ pub(crate) previous_current_time: Option<TimeValue>,
+ /// The current time of the associated effect where the animation was last canceled, until the host takes it.
+ pub(crate) saved_cancel_time: Option<TimeValue>,
/// The attachment interval the effect's timing was last normalized against.
- normalized_attachment_interval: Option<AttachmentInterval>,
+ pub(crate) normalized_attachment_interval: Option<AttachmentInterval>,
/// The play state the animation was in when it was disassociated from its target as inert.
- play_state_when_disassociated_from_target: Option<AnimationPlayState>,
- /// https://drafts.csswg.org/web-animations-2/#auto-align-start-time
- auto_align_start_time: bool,
+ pub(crate) play_state_when_disassociated_from_target: Option<AnimationPlayState>,
+ /// https://drafts.csswg.org/web-animations-2/#auto-aligning-start-time
+ pub(crate) auto_align_start_time: bool,
/// Whether the animation is disassociated from its target once it is inert.
- disassociation_from_target_pending: bool,
+ pub(crate) disassociation_from_target_pending: bool,
/// https://www.w3.org/TR/web-animations-1/#dom-animation-id
/// None where it is the empty string.
- dom_id: RetainedUtf16FlyString,
+ pub(crate) dom_id: RetainedUtf16FlyString,
/// https://www.w3.org/TR/web-animations-1/#global-animation-list
global_animation_list_order: GlobalAnimationListOrder,
/// https://drafts.csswg.org/scroll-animations-1/#animation-attachment-range
@@ -250,9 +265,9 @@ pub(crate) struct AnimationRecord {
owning_pseudo_element: Option<u8>,
/// The task the host last queued to run the finish notification steps of the animation, or to dispatch its finish
/// event, if any.
- /// NB: Nothing forgets the task once it ran or was cancelled, which keeps a later finish notification task from
- /// being queued, as the host's `Animation` did before the record kept it.
- finish_notification_task: Option<HostTaskId>,
+ /// NB: Canceling the task forgets it. Nothing forgets the task once it ran, which keeps a later finish
+ /// notification task from being queued until one is canceled.
+ pub(crate) finish_notification_task: Option<HostTaskId>,
kind: AnimationKind,
}
@@ -360,41 +375,6 @@ impl AnimationRecord {
&mut self.playback
}
- #[must_use]
- pub(crate) fn previous_current_time(&self) -> Option<TimeValue> {
- self.previous_current_time
- }
-
- pub(crate) fn set_previous_current_time(&mut self, time: Option<TimeValue>) {
- self.previous_current_time = time;
- }
-
- pub(crate) fn set_saved_cancel_time(&mut self, time: Option<TimeValue>) {
- self.saved_cancel_time = time;
- }
-
- pub(crate) fn take_saved_cancel_time(&mut self) -> Option<TimeValue> {
- self.saved_cancel_time.take()
- }
-
- #[must_use]
- pub(crate) fn normalized_attachment_interval(&self) -> Option<AttachmentInterval> {
- self.normalized_attachment_interval
- }
-
- pub(crate) fn set_normalized_attachment_interval(&mut self, interval: Option<AttachmentInterval>) {
- self.normalized_attachment_interval = interval;
- }
-
- pub(crate) fn set_play_state_when_disassociated_from_target(&mut self, play_state: Option<AnimationPlayState>) {
- self.play_state_when_disassociated_from_target = play_state;
- }
-
- #[must_use]
- pub(crate) fn play_state_when_disassociated_from_target(&self) -> Option<AnimationPlayState> {
- self.play_state_when_disassociated_from_target
- }
-
/// Notes that the animation was associated with the target of its associated effect again. Joining a target does
/// not make an animation that was disassociated from it as inert relevant, so whether it is inert is checked again.
pub(crate) fn did_associate_with_target(&mut self) {
@@ -403,33 +383,6 @@ impl AnimationRecord {
}
}
- #[must_use]
- pub(crate) fn auto_align_start_time(&self) -> bool {
- self.auto_align_start_time
- }
-
- pub(crate) fn set_auto_align_start_time(&mut self, value: bool) {
- self.auto_align_start_time = value;
- }
-
- #[must_use]
- pub(crate) fn disassociation_from_target_pending(&self) -> bool {
- self.disassociation_from_target_pending
- }
-
- pub(crate) fn set_disassociation_from_target_pending(&mut self, value: bool) {
- self.disassociation_from_target_pending = value;
- }
-
- #[must_use]
- pub(crate) fn dom_id(&self) -> &RetainedUtf16FlyString {
- &self.dom_id
- }
-
- pub(crate) fn set_dom_id(&mut self, id: RetainedUtf16FlyString) {
- self.dom_id = id;
- }
-
#[must_use]
pub(crate) fn global_animation_list_order(&self) -> GlobalAnimationListOrder {
self.global_animation_list_order
@@ -471,15 +424,6 @@ impl AnimationRecord {
self.owning_pseudo_element = owning_element.and_then(|owner| owner.pseudo_element);
}
- #[must_use]
- pub(crate) fn finish_notification_task(&self) -> Option<HostTaskId> {
- self.finish_notification_task
- }
-
- pub(crate) fn set_finish_notification_task(&mut self, task: HostTaskId) {
- self.finish_notification_task = Some(task);
- }
-
#[must_use]
pub(crate) fn kind(&self) -> &AnimationKind {
&self.kind
@@ -547,7 +491,7 @@ pub struct AnimationCell {
record: RefCell<AnimationRecord>,
/// The GC cell of the object script sees of the animation, which holds a reference to the record until it is
/// finalized and clears this as it does.
- facade: Cell<Option<NonNull<c_void>>>,
+ object_cell: Cell<Option<NonNull<c_void>>>,
}
impl AnimationCell {
@@ -560,8 +504,8 @@ impl AnimationCell {
}
/// The host's `Animation` of the animation, while it is alive.
- pub(crate) fn facade(&self) -> Option<NonNull<c_void>> {
- self.facade.get()
+ pub(crate) fn object_cell(&self) -> Option<NonNull<c_void>> {
+ self.object_cell.get()
}
/// Whether the host may reach the animation and the elements its record names. One with an object script sees is
@@ -572,7 +516,7 @@ impl AnimationCell {
/// element never has an object. It is alive while a holder its record notes holds it, each of which keeps the
/// elements the record names alive while it does.
pub(crate) fn is_alive(&self) -> bool {
- if self.facade().is_some() {
+ if self.object_cell().is_some() {
return true;
}
let record = self.borrow();
@@ -597,8 +541,8 @@ impl AnimationCell {
/// Calls `visit` with each GC cell of the host that keeps alive the elements the record names: the animation's
/// object, or, for an animation without one, the cells the record names.
pub(crate) fn for_each_host_cell(&self, mut visit: impl FnMut(NonNull<c_void>, HostCellKind)) {
- if let Some(facade) = self.facade() {
- visit(facade, HostCellKind::Cell);
+ if let Some(object_cell) = self.object_cell() {
+ visit(object_cell, HostCellKind::Cell);
return;
}
let record = self.borrow();
@@ -622,8 +566,8 @@ impl AnimationCell {
visit(owner, HostCellKind::Element);
}
if let Some(effect) = record.effect() {
- match effect.facade() {
- Some(facade) => visit(facade, HostCellKind::Cell),
+ match effect.object_cell() {
+ Some(object_cell) => visit(object_cell, HostCellKind::Cell),
None => {
if let Some(target) = effect.borrow().target_element() {
visit(target, HostCellKind::Element);
@@ -631,13 +575,13 @@ impl AnimationCell {
}
}
}
- if let Some(timeline) = record.timeline().and_then(|timeline| timeline.facade()) {
- visit(timeline, HostCellKind::Cell);
+ if let Some(timeline) = record.timeline() {
+ timeline.for_each_holder_cell(&mut visit);
}
}
- pub(crate) fn set_facade(&self, facade: Option<NonNull<c_void>>) {
- self.facade.set(facade);
+ pub(crate) fn set_object_cell(&self, object_cell: Option<NonNull<c_void>>) {
+ self.object_cell.set(object_cell);
}
/// The bytes of the allocation every handle shares, and those the record holds beyond it.
@@ -684,7 +628,7 @@ impl AnimationHandle {
pub(crate) fn new(kind: AnimationKind) -> Self {
Self(Rc::new(AnimationCell {
record: RefCell::new(AnimationRecord::new(kind)),
- facade: Cell::new(None),
+ object_cell: Cell::new(None),
}))
}
@@ -793,6 +737,17 @@ impl WeakAnimationSet {
self.0.get(index).map(AnimationHandle)
}
+ /// The animations of the set that are alive, in insertion order, as enumerating the entries in place finds them.
+ pub(crate) fn iter(&self) -> impl Iterator<Item = AnimationHandle> + '_ {
+ (0..self.entry_count()).filter_map(|index| self.get(index))
+ }
+
+ /// The animations of the set that are alive.
+ pub(crate) fn alive(&mut self) -> Vec<AnimationHandle> {
+ self.prune();
+ self.iter().collect()
+ }
+
/// Removes every animation.
pub(crate) fn clear(&mut self) {
self.0.clear();
diff --git a/Libraries/LibWeb/Rust/src/animations/bindings_api.rs b/Libraries/LibWeb/Rust/src/animations/bindings_api.rs
index 1320d87f468..cec66b6319d 100644
--- a/Libraries/LibWeb/Rust/src/animations/bindings_api.rs
+++ b/Libraries/LibWeb/Rust/src/animations/bindings_api.rs
@@ -15,10 +15,11 @@ use super::animation::{AnimationCell, AnimationHandle, AnimationKind, AnimationR
use super::composite_order::composite_order;
use super::easing::CompactEasing;
use super::effect::{AnimationEffectCell, EffectHandle};
-use super::ffi::{FfiResolvedEffectTiming, FfiTreeOrder, animations_effect_resolve_timing, host_tree_order};
-use super::ffi::{FfiScrollTimelineSource, FfiTimelineDescription, create_timeline};
-use super::ffi::{invalidate, run_procedure_on};
-use super::keyframes::{KEY_SCALE_FACTOR, KeyframeProperty, KeyframeSet, ProcessedKeyframe};
+use super::effect::{EffectTimingAtLocalTime, resolve_effect_timing};
+use super::ffi::{FfiScrollTimelineSource, SCROLLER_NEAREST, retained_view_inset};
+use super::ffi::{FfiTreeOrder, host_tree_order};
+use super::ffi::{invalidate, run_procedure, run_procedure_on};
+use super::keyframes::{KeyframeProperty, KeyframeSet, ProcessedKeyframe, key_of_offset};
use super::procedures::AnimationError;
use super::timeline::{TimelineHandle, TimelineKind, ViewTimelineInset, ViewTimelineInsetEdge};
use super::timing::{AnimationEffectTiming, FillMode, SpecifiedEffectTiming, TimeValue};
@@ -26,18 +27,16 @@ use crate::css::animation::FfiCompositeOperation;
use crate::css::retained_fly_string::RetainedUtf16FlyString;
use crate::css::style::effect_descriptions::easing_from_computed_timing_function;
use crate::css::style_value::{RetainedStyleValueData, StyleValueData, retain_style_value};
-use crate::css::typed_om::parse_value_for_property;
use libcompositing_rust::easing::{Easing, FfiEasingKind};
-pub use super::ffi::{FfiHostEffect as HostEffect, HostEffectPerformer};
+pub use super::ffi::{
+ FfiHostEffect as HostEffect, HostEffectPerformer, element_node_document,
+ web_animation_compare_elements_in_tree_order,
+};
pub use super::keyframes::CompositeOperationOrAuto;
pub use crate::css::animation::FfiCompositeOperation as CompositeOperation;
pub use libcompositing_rust::animation_timing::{AnimationPlayState, AnimationReplaceState};
-/// The resolved timing of an effect, as https://www.w3.org/TR/web-animations-1/#calculating-the-active-time and the
-/// sections around it define it.
-pub type ResolvedEffectTiming = FfiResolvedEffectTiming;
-
/// An easing function parsed from script, with the serialization the effect reports it as.
#[derive(Clone)]
pub struct ParsedEasing {
@@ -70,15 +69,21 @@ impl ParsedEasing {
/// The easing the computed value of a timing function `value` describes, serialized as a script reads it, or none
/// where it describes none.
pub(crate) fn of_timing_function(value: &RetainedStyleValueData) -> Option<Self> {
- let easing = crate::css::style::effect_descriptions::easing_from_computed_timing_function(value.data())?;
- let mode = if matches!(value.data(), StyleValueData::Easing(_)) && easing.kind() == FfiEasingKind::CubicBezier {
+ Self::of_timing_function_data(value.data(), |mode| value.serialize(mode))
+ }
+
+ /// The easing the computed value of a timing function `value` describes, with `serialize` serializing the value in
+ /// the mode a script reads it in, or none where it describes none.
+ fn of_timing_function_data(value: &StyleValueData, serialize: impl FnOnce(u8) -> ak::Utf16String) -> Option<Self> {
+ let easing = easing_from_computed_timing_function(value)?;
+ let mode = if matches!(value, StyleValueData::Easing(_)) && easing.kind() == FfiEasingKind::CubicBezier {
SERIALIZATION_MODE_NORMAL
} else {
SERIALIZATION_MODE_RESOLVED_VALUE
};
Some(Self {
easing,
- serialization: value.serialize(mode),
+ serialization: serialize(mode),
})
}
}
@@ -91,7 +96,7 @@ const SERIALIZATION_MODE_RESOLVED_VALUE: u8 = 1;
/// <easing-function> production [CSS-EASING-1].
pub fn parse_easing_function(text: &ak::Utf16String) -> Option<ParsedEasing> {
use crate::css::property_metadata::property_id;
- let value = parse_value_for_property(property_id::ANIMATION_TIMING_FUNCTION, text)?;
+ let value = parse_property_value(property_id::ANIMATION_TIMING_FUNCTION, text)?;
if value.is_unresolved() || value.is_css_wide_keyword() {
return None;
}
@@ -100,16 +105,7 @@ pub fn parse_easing_function(text: &ak::Utf16String) -> Option<ParsedEasing> {
return None;
};
// FIXME: We should absolutize the style value to resolve relative lengths within calcs
- let easing = easing_from_computed_timing_function(item.data())?;
- let mode = if matches!(item.data(), StyleValueData::Easing(_)) && easing.kind() == FfiEasingKind::CubicBezier {
- SERIALIZATION_MODE_NORMAL
- } else {
- SERIALIZATION_MODE_RESOLVED_VALUE
- };
- Some(ParsedEasing {
- easing,
- serialization: item.serialize(mode),
- })
+ ParsedEasing::of_timing_function_data(item.data(), |mode| item.serialize(mode))
}
/// A pseudo-element selector parsed from script: the host's `CSS::PseudoElement`, and its serialization.
@@ -152,22 +148,14 @@ pub fn property_id_from_camel_case(name: &ak::Utf16String) -> Option<u16> {
.map(|index| PROPERTY_CAMEL_CASE_LOOKUP[index].1)
}
-/// The IDL attribute name of the property, https://drafts.csswg.org/cssom/#css-property-to-idl-attribute
-pub fn camel_case_property_name(property_id: u16) -> &'static str {
- crate::css::property_metadata::property_idl_name(property_id)
-}
-
-/// Whether the property, by its id, can be animated.
-pub fn is_animatable_property(property_id: u16) -> bool {
- super::keyframes::is_animatable_property(property_id)
-}
-
-/// The id of the float property.
-pub const PROPERTY_ID_FLOAT: u16 = crate::css::property_metadata::property_id::FLOAT;
-/// The id of the offset property.
-pub const PROPERTY_ID_OFFSET: u16 = crate::css::property_metadata::property_id::OFFSET;
-/// The id custom properties share.
-pub const PROPERTY_ID_CUSTOM: u16 = crate::css::property_metadata::property_id::CUSTOM;
+pub use super::keyframes::is_animatable_property;
+pub use crate::css::property_metadata::property_id::{
+ ANIMATION_RANGE_END as PROPERTY_ID_ANIMATION_RANGE_END, ANIMATION_RANGE_START as PROPERTY_ID_ANIMATION_RANGE_START,
+ CUSTOM as PROPERTY_ID_CUSTOM, FLOAT as PROPERTY_ID_FLOAT, OFFSET as PROPERTY_ID_OFFSET,
+ VIEW_TIMELINE_INSET as PROPERTY_ID_VIEW_TIMELINE_INSET,
+};
+pub use crate::css::property_metadata::property_idl_name as camel_case_property_name;
+pub use crate::css::typed_om::parse_value_for_property as parse_property_value;
/// A property a processed keyframe declares: a longhand or shorthand by its id, or a custom property by its name.
#[derive(Clone)]
@@ -179,12 +167,6 @@ pub enum KeyframePropertyName {
/// A value of a property in a processed keyframe.
pub type StyleValue = RetainedStyleValueData;
-/// The value the text parses as for the property, with no document to parse it for, or none where the value is
-/// invalid according to the syntax for the property.
-pub fn parse_property_value(property_id: u16, text: &ak::Utf16String) -> Option<StyleValue> {
- parse_value_for_property(property_id, text)
-}
-
/// Another reference to a value of a property.
#[must_use]
pub fn clone_property_value(value: &StyleValue) -> StyleValue {
@@ -260,8 +242,7 @@ impl KeyframeSetRef {
let keyframes = keyframes
.iter()
.map(|keyframe| ProcessedKeyframe {
- #[expect(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
- key: (keyframe.computed_offset * 100.0 * KEY_SCALE_FACTOR) as u64,
+ key: key_of_offset(keyframe.computed_offset),
composite: keyframe.composite,
easing: Some(keyframe.easing.easing.clone()),
declarations: keyframe
@@ -324,10 +305,16 @@ impl EffectRecordRef {
std::ptr::from_ref::<AnimationEffectCell>(&self.0).cast()
}
+ /// Invalidates the style the effect produces, forgetting what the host concluded of it.
+ pub fn invalidate(&self) {
+ self.0.borrow_mut().forget_what_the_host_concluded();
+ super::compositor_update::set_needs_animated_style_update(&self.0);
+ }
+
/// Notes the cell of the object script sees of the effect, or that it has none, which the host's code reaches it
/// through.
- pub fn set_facade(&self, facade: Option<NonNull<c_void>>) {
- self.0.set_facade(facade);
+ pub fn set_object_cell(&self, object_cell: Option<NonNull<c_void>>) {
+ self.0.set_object_cell(object_cell);
}
#[must_use]
@@ -397,11 +384,11 @@ impl EffectRecordRef {
local_time: Option<TimeValue>,
fill_mode: FillMode,
with_transformed_progress: bool,
- ) -> ResolvedEffectTiming {
+ ) -> EffectTimingAtLocalTime {
let animation = self.0.borrow().associated_animation();
- animations_effect_resolve_timing(
+ resolve_effect_timing(
&self.0,
- local_time.into(),
+ local_time,
fill_mode,
animation.as_deref().map(|animation: &AnimationCell| animation),
with_transformed_progress,
@@ -453,6 +440,41 @@ impl EffectRecordRef {
pub fn composite(&self) -> FfiCompositeOperation {
self.0.borrow().composite()
}
+
+ pub fn set_composite(&self, composite: FfiCompositeOperation) {
+ self.0.borrow_mut().set_composite(composite);
+ }
+
+ /// Whether the effect's keyframes come from CSS: from a `@keyframes` rule, or a CSS transition.
+ #[must_use]
+ pub fn keyframes_from_css(&self) -> bool {
+ self.0.borrow().keyframes_from_css()
+ }
+
+ /// Notes that script is about to set the effect's keyframes, which keeps those it replaces of CSS from coming back.
+ pub fn note_keyframes_set_by_script(&self) {
+ self.0.borrow_mut().note_keyframes_set_by_script();
+ }
+
+ /// The keyframes of CSS the effect runs as `getKeyframes()` returns them.
+ #[must_use]
+ pub fn computed_css_keyframes(&self) -> Vec<CssKeyframeValues> {
+ let effect = super::keyframe_reflection::ReflectedEffect::of(&self.0.borrow());
+ super::keyframe_reflection::computed_css_keyframes(&effect)
+ .into_iter()
+ .map(Into::into)
+ .collect()
+ }
+
+ /// The keyframes of CSS a copy of the effect takes.
+ #[must_use]
+ pub fn css_keyframes_of_copy(&self) -> Vec<CssKeyframeValues> {
+ let effect = super::keyframe_reflection::ReflectedEffect::of(&self.0.borrow());
+ super::keyframe_reflection::css_keyframes_of_copy(&effect)
+ .into_iter()
+ .map(Into::into)
+ .collect()
+ }
}
/// https://www.w3.org/TR/web-animations-1/#animation-composite-order
@@ -498,11 +520,8 @@ pub enum TimelineInterfaceKind {
#[derive(Clone)]
pub struct TimelineRecordRef(TimelineHandle);
-/// The host's `CSS::Scroller::Nearest`, which a view timeline finds its source from its subject with.
-const SCROLLER_NEAREST: u8 = 1;
-
impl TimelineRecordRef {
- /// A new timeline associated with the host's `DOM::Document` `document`.
+ /// A new timeline associated with the host's `DOM::Document` `document`, which keeps it alive.
#[must_use]
pub fn new(document: NonNull<c_void>, description: TimelineDescription) -> Self {
let scroll = |source, axis| super::timeline::ScrollTimelineState {
@@ -538,17 +557,44 @@ impl TimelineRecordRef {
time_for_observation: None,
},
};
- Self(TimelineHandle::new(document, kind))
+ Self(super::timeline_host::create_timeline(document, kind))
}
- /// A new timeline associated with the host's `DOM::Document` `document`, as the host describes it.
- ///
- /// # Safety
- /// The calculations of a view timeline's inset must be null or live style values.
+ /// https://www.w3.org/TR/web-animations-1/#document-default-document-timeline
+ /// The default document timeline of the host's `DOM::Document` `document`.
#[must_use]
- pub unsafe fn from_host_description(document: NonNull<c_void>, description: *const c_void) -> Self {
- // SAFETY: Guaranteed by the caller.
- Self(unsafe { create_timeline(document, &*description.cast::<FfiTimelineDescription>()) })
+ pub fn default_of_document(document: NonNull<c_void>) -> Self {
+ Self(super::timeline_host::default_document_timeline(document))
+ }
+
+ /// https://drafts.csswg.org/web-animations-1/#dom-animationtimeline-currenttime
+ /// As script observes it.
+ #[must_use]
+ pub fn current_time_for_observation(&self) -> Option<TimeValue> {
+ super::timeline_host::current_time_for_observation(&self.0)
+ }
+
+ /// https://drafts.csswg.org/scroll-animations-1/#dom-scrolltimeline-source
+ /// The host's `DOM::Element` that is the source of a scroll timeline as script observes it, or none.
+ #[must_use]
+ pub fn source_element(&self) -> Option<NonNull<c_void>> {
+ super::timeline_host::scroll_timeline_source(&self.0)
+ }
+
+ /// Sets the current time of the Internals interface's timeline to `time`, in milliseconds, or where
+ /// `for_observation`, the time a read of it observes, keeping alive each animation it updates with `keep_alive`,
+ /// which is handed the cells that keep it alive, and performing what they ask for through `perform`.
+ pub fn set_internal_time(
+ &self,
+ time: Option<f64>,
+ for_observation: bool,
+ keep_alive: &dyn Fn(NonNull<c_void>),
+ perform: HostEffectPerformer,
+ ) {
+ let keep_alive = |animation: &super::animation::AnimationCell| {
+ animation.for_each_host_cell(|cell, _| keep_alive(cell));
+ };
+ super::timeline_host::set_internal_time(&self.0, time, for_observation, &keep_alive, perform);
}
/// The timeline, as the host names it.
@@ -559,19 +605,19 @@ impl TimelineRecordRef {
/// The cell of the object script sees of the timeline, while it is alive.
#[must_use]
- pub fn facade(&self) -> Option<NonNull<c_void>> {
- self.0.facade()
+ pub fn object_cell(&self) -> Option<NonNull<c_void>> {
+ self.0.object_cell()
}
/// Notes the cell of the object script sees of the timeline, or that it has none, which the host's code reaches it
/// through.
- pub fn set_facade(&self, facade: Option<NonNull<c_void>>) {
- self.0.set_facade(facade);
+ pub fn set_object_cell(&self, object_cell: Option<NonNull<c_void>>) {
+ self.0.set_object_cell(object_cell);
}
/// Calls `visit` with each GC cell of the host the record names.
- pub fn for_each_host_cell(&self, visit: impl FnMut(NonNull<c_void>)) {
- self.0.for_each_host_cell(visit);
+ pub fn for_each_host_cell(&self, mut visit: impl FnMut(NonNull<c_void>)) {
+ self.0.for_each_host_cell(|cell, _| visit(cell));
}
/// The host's `DOM::Document` the timeline is associated with.
@@ -663,31 +709,7 @@ impl ViewTimelineInsetValue {
pub fn from_computed_value(value: &StyleValue) -> Self {
let inset = crate::css::style_compute::script_view_timeline_inset(value.data());
// SAFETY: The calculations are null or style values that the value holds.
- let edge = |is_auto, px, percentage, calculated: *const c_void| ViewTimelineInsetEdge {
- is_auto,
- px,
- percentage,
- calculated: if calculated.is_null() {
- RetainedStyleValueData::none()
- } else {
- // SAFETY: The value holds the calculation.
- unsafe { RetainedStyleValueData::from_retained_pointer(retain_style_value(calculated.cast())) }
- },
- };
- Self(ViewTimelineInset {
- start: edge(
- inset.start_is_auto,
- inset.start_px,
- inset.start_percentage,
- inset.start_calculated,
- ),
- end: edge(
- inset.end_is_auto,
- inset.end_px,
- inset.end_percentage,
- inset.end_calculated,
- ),
- })
+ Self(unsafe { retained_view_inset(&inset) })
}
}
@@ -697,9 +719,6 @@ pub fn view_timeline_inset_has_relative_length(value: &StyleValue) -> bool {
crate::css::style_compute::view_timeline_inset_has_relative_length(value.data())
}
-/// The id of the `view-timeline-inset` property.
-pub const PROPERTY_ID_VIEW_TIMELINE_INSET: u16 = crate::css::property_metadata::property_id::VIEW_TIMELINE_INSET;
-
/// Takes over one reference to a style value the host hands over.
///
/// # Safety
@@ -776,22 +795,47 @@ impl AnimationRecordRef {
.map_err(AnimationException::from)
}
+ /// Whether getAnimations() reports the animation: whether it is relevant, on its timeline, if it has one, with its
+ /// associated effect, if any.
+ /// https://www.w3.org/TR/web-animations-1/#animation-relevant
+ #[must_use]
+ pub fn is_exposed_relevant(&self) -> bool {
+ let animation = self.cell().borrow();
+ // AD-HOC: SVG animation elements drive their animations with their own timing model, which script must not
+ // be able to play, pause or cancel. Like other engines, do not expose them.
+ if matches!(animation.kind(), AnimationKind::Smil { .. }) {
+ return false;
+ }
+ let timeline = animation.timeline().map(|timeline| timeline.sample());
+ let timeline = timeline.as_ref();
+ let effect_timing = animation.effect().map(|effect| effect.borrow().timing());
+ // NB: The local time of the associated effect is the current time of the animation.
+ let local_time = effect_timing
+ .is_some()
+ .then(|| {
+ super::timing::current_time_at(
+ animation.playback(),
+ timeline.and_then(|timeline| timeline.current_time.get()),
+ )
+ })
+ .flatten();
+ super::timing::is_relevant(animation.playback(), timeline, effect_timing.as_ref(), local_time)
+ }
+
/// Whether the animation is idle. A cancel of one that is not settles its promises and creates its cancel event.
#[must_use]
pub fn is_idle(&self) -> bool {
- self.cell().borrow().timing_state(None).play_state == AnimationPlayState::Idle
+ self.cell().borrow().play_state() == AnimationPlayState::Idle
}
/// https://www.w3.org/TR/web-animations-1/#dom-animation-id
#[must_use]
pub fn dom_id(&self) -> ak::Utf16String {
- ak::Utf16String::from_utf16(&self.cell().borrow().dom_id().to_utf16())
+ ak::Utf16String::from_utf16(&self.cell().borrow().dom_id.to_utf16())
}
pub fn set_dom_id(&self, id: &ak::Utf16String) {
- self.cell()
- .borrow_mut()
- .set_dom_id(RetainedUtf16FlyString::from_utf16(&id.to_utf16()));
+ self.cell().borrow_mut().dom_id = RetainedUtf16FlyString::from_utf16(&id.to_utf16());
}
/// https://www.w3.org/TR/web-animations-1/#playback-rate
@@ -810,23 +854,7 @@ impl AnimationRecordRef {
/// At `current_time`, the current time of the animation.
#[must_use]
pub fn play_state_at(&self, current_time: Option<TimeValue>) -> AnimationPlayState {
- let record = self.cell().borrow();
- // The associated effect end of an animation is equal to the end time of the animation’s associated effect. If
- // the animation has no associated effect, the associated effect end is zero.
- let associated_effect_end = match record.effect() {
- Some(effect) => super::timing::end_time(&effect.borrow().timing()),
- None => {
- let progress_based = record
- .timeline()
- .is_some_and(|timeline| timeline.borrow().is_progress_based());
- TimeValue::zero(if progress_based {
- super::timing::TimeValueType::Percentage
- } else {
- super::timing::TimeValueType::Milliseconds
- })
- }
- };
- super::timing::play_state_at(record.playback(), current_time, associated_effect_end)
+ self.cell().borrow().play_state_at(current_time)
}
/// https://drafts.csswg.org/css-animations-2/#dom-cssanimation-animationname
@@ -931,12 +959,6 @@ impl AnimationRecordRef {
Self::from_handle(AnimationHandle::new(AnimationKind::Script))
}
- /// Whether both references are to the same animation.
- #[must_use]
- pub fn ptr_eq(&self, other: &Self) -> bool {
- std::ptr::eq(self.cell(), other.cell())
- }
-
/// Which interface the object script sees of the animation is an object of.
#[must_use]
pub fn kind(&self) -> AnimationInterfaceKind {
@@ -950,13 +972,22 @@ impl AnimationRecordRef {
/// The cell of the object script sees of the animation, while it has one.
#[must_use]
- pub fn facade(&self) -> Option<NonNull<c_void>> {
- self.cell().facade()
+ pub fn object_cell(&self) -> Option<NonNull<c_void>> {
+ self.cell().object_cell()
}
/// Notes the cell of the object script sees of the animation, or that it has none.
- pub fn set_facade(&self, facade: Option<NonNull<c_void>>) {
- self.cell().set_facade(facade);
+ pub fn set_object_cell(&self, object_cell: Option<NonNull<c_void>>) {
+ self.cell().set_object_cell(object_cell);
+ }
+
+ /// Notes that the host finalized the object script sees of the animation. Whatever holds the record and is alive
+ /// to the host keeps that object alive, so the animation is dead to the host now, though the record may outlive
+ /// the object until what holds it is swept, after the elements it names may be gone. It no longer names its owning
+ /// element then, so that no set of animations finds it alive.
+ pub fn did_finalize_object(&self) {
+ self.cell().set_object_cell(None);
+ self.cell().borrow_mut().set_owning_element(None);
}
/// Calls `visit` with each GC cell of the host that keeps alive the elements the record names.
@@ -1028,27 +1059,22 @@ impl AnimationRecordRef {
/// https://www.w3.org/TR/web-animations-1/#animation-set-the-associated-effect-of-an-animation
pub fn set_effect(&self, effect: Option<&EffectRecordRef>, perform: HostEffectPerformer) {
let effect = effect.map(|effect| effect.0.clone());
- let _ = run_procedure_on(self.cell(), perform, |procedures| {
+ run_procedure(self.cell(), perform, |procedures| {
procedures.set_the_associated_effect(effect.as_ref(), invalidate(true));
- Ok(())
});
}
/// https://www.w3.org/TR/web-animations-1/#animation-set-the-timeline-of-an-animation
pub fn set_timeline(&self, timeline: Option<&TimelineRecordRef>, perform: HostEffectPerformer) {
let timeline = timeline.map(|timeline| timeline.0.clone());
- let _ = run_procedure_on(self.cell(), perform, |procedures| {
- procedures.set_timeline(timeline);
- Ok(())
- });
+ run_procedure(self.cell(), perform, |procedures| procedures.set_timeline(timeline));
}
/// https://www.w3.org/TR/web-animations-1/#set-the-start-time
/// To the validated `start_time`.
pub fn set_start_time(&self, start_time: Option<TimeValue>, perform: HostEffectPerformer) {
- let _ = run_procedure_on(self.cell(), perform, |procedures| {
+ run_procedure(self.cell(), perform, |procedures| {
procedures.set_start_time_for_bindings(start_time);
- Ok(())
});
}
@@ -1083,30 +1109,20 @@ impl AnimationRecordRef {
observed_current_time: Option<TimeValue>,
perform: HostEffectPerformer,
) {
- let _ = run_procedure_on(self.cell(), perform, |procedures| {
+ run_procedure(self.cell(), perform, |procedures| {
procedures.update_finished_state(
super::procedures::DidSeek::No,
super::procedures::SynchronouslyNotify::Yes,
invalidate(should_invalidate),
observed_current_time,
);
- Ok(())
- });
- }
-
- /// Runs the finish notification steps of the animation from the task the host queued.
- pub fn run_finish_notification_steps(&self, perform: HostEffectPerformer) {
- let _ = run_procedure_on(self.cell(), perform, |procedures| {
- procedures.finish_notification_steps();
- Ok(())
});
}
/// Notes `task`, the host's identity of the task it queued to run the finish notification steps of the animation,
/// or to dispatch its finish event.
pub fn set_finish_notification_task(&self, task: u64) {
- let task = super::animation::HostTaskId(std::num::NonZeroU64::new(task).expect("tasks have nonzero ids"));
- self.cell().borrow_mut().set_finish_notification_task(task);
+ super::ffi::animations_animation_set_finish_notification_task(self.cell(), task);
}
/// https://drafts.csswg.org/scroll-animations-1/#animation-attachment-range
@@ -1140,15 +1156,12 @@ impl AnimationRecordRef {
if !self.cell().borrow_mut().set_range(range) {
return;
}
- let _ = run_procedure_on(self.cell(), perform, |procedures| {
- procedures.attachment_range_changed();
- Ok(())
- });
+ run_procedure(self.cell(), perform, |procedures| procedures.attachment_range_changed());
}
/// Notes that script overrode what `flag` names of the CSS animation.
pub fn set_css_animation_flag(&self, flag: super::animation::CssAnimationFlag) {
- self.cell().borrow_mut().css_animation_mut().flags |= flag as u8;
+ self.cell().borrow_mut().css_animation_mut().set_flag(flag);
}
/// The bytes of the allocation every handle shares, and those the record holds beyond it.
@@ -1161,61 +1174,12 @@ impl AnimationRecordRef {
impl EffectRecordRef {
/// The cell of the object script sees of the effect, while it has one.
#[must_use]
- pub fn facade(&self) -> Option<NonNull<c_void>> {
- self.0.facade()
- }
-
- /// Whether both references are to the same effect.
- #[must_use]
- pub fn ptr_eq(&self, other: &Self) -> bool {
- std::ptr::eq(self.as_host_ptr(), other.as_host_ptr())
- }
-
- /// Whether the effect's keyframes come from CSS: from a `@keyframes` rule, or a CSS transition.
- #[must_use]
- pub fn keyframes_from_css(&self) -> bool {
- self.0.borrow().keyframes_from_css()
- }
-
- /// Notes that script is about to set the effect's keyframes, which keeps those it replaces of CSS from coming back.
- pub fn note_keyframes_set_by_script(&self) {
- self.0.borrow_mut().note_keyframes_set_by_script();
- }
-
- /// The keyframes of CSS the effect runs as `getKeyframes()` returns them.
- #[must_use]
- pub fn computed_css_keyframes(&self) -> Vec<CssKeyframeValues> {
- let effect = super::keyframe_reflection::ReflectedEffect::of(&self.0.borrow());
- super::keyframe_reflection::computed_css_keyframes(&effect)
- .into_iter()
- .map(Into::into)
- .collect()
- }
-
- /// The keyframes of CSS a copy of the effect takes.
- #[must_use]
- pub fn css_keyframes_of_copy(&self) -> Vec<CssKeyframeValues> {
- let effect = super::keyframe_reflection::ReflectedEffect::of(&self.0.borrow());
- super::keyframe_reflection::css_keyframes_of_copy(&effect)
- .into_iter()
- .map(Into::into)
- .collect()
+ pub fn object_cell(&self) -> Option<NonNull<c_void>> {
+ self.0.object_cell()
}
}
impl TimelineRecordRef {
- /// Whether both references are to the same timeline.
- #[must_use]
- pub fn ptr_eq(&self, other: &Self) -> bool {
- std::ptr::eq(self.as_host_ptr(), other.as_host_ptr())
- }
-
- /// Whether the timeline is a progress-based timeline.
- #[must_use]
- pub fn is_progress_based(&self) -> bool {
- self.0.borrow().is_progress_based()
- }
-
/// The current time of the timeline, or none where it is inactive.
#[must_use]
pub fn current_time(&self) -> Option<TimeValue> {
@@ -1232,12 +1196,6 @@ impl TimelineRecordRef {
self.0.borrow_mut().set_style_sampling_override(current_time);
}
- /// Whether the timeline is inactive.
- #[must_use]
- pub fn is_inactive(&self) -> bool {
- self.0.is_inactive()
- }
-
/// https://www.w3.org/TR/web-animations-1/#timeline-time-to-origin-relative-time
/// Where the timeline can convert one, which only a document timeline can.
#[must_use]
@@ -1250,12 +1208,9 @@ impl TimelineRecordRef {
}
}
-/// The ids of the `animation-range-start` and `animation-range-end` properties.
-pub const PROPERTY_ID_ANIMATION_RANGE_START: u16 = crate::css::property_metadata::property_id::ANIMATION_RANGE_START;
-pub const PROPERTY_ID_ANIMATION_RANGE_END: u16 = crate::css::property_metadata::property_id::ANIMATION_RANGE_END;
-
pub use super::animation::CssAnimationFlag;
pub use super::ffi::FfiHostEffectKind as HostEffectKind;
+pub use super::host_effects::PlaybackEventType;
/// The time a calculation of the numeric type gives: milliseconds of a number or a time, or a percentage, where it gives
/// one of those.
@@ -1312,3 +1267,39 @@ pub fn timeline_range_name_to_string(name: u8) -> Option<&'static str> {
_ => unreachable!("the host names a timeline range it knows"),
})
}
+
+pub use super::css_events::FfiCssEventType as CssEventType;
+pub use super::pending_animation_events::{
+ FfiPendingAnimationEvent as PendingAnimationEvent, PendingAnimationEventKind,
+};
+
+/// https://www.w3.org/TR/web-animations-1/#update-animations-and-send-events
+/// Takes the events of the pending animation event queue of a document, whose animations the host's
+/// `DocumentAnimations` `animations` are, in the order to dispatch them in, comparing elements in tree order with
+/// `tree_order`, each with the animation it is of.
+///
+/// # Safety
+/// `animations` must be what a live document knows of animations, which nothing else reaches for the call.
+pub unsafe fn take_pending_animation_events_to_dispatch(
+ animations: NonNull<c_void>,
+ tree_order: FfiTreeOrder,
+) -> Vec<(AnimationRecordRef, PendingAnimationEvent)> {
+ // SAFETY: Guaranteed by the caller.
+ let animations = unsafe {
+ animations
+ .cast::<super::document_animations::DocumentAnimations>()
+ .as_mut()
+ };
+ // NB: Steps 4 to 6 take and sort the events.
+ animations
+ .pending_events
+ .take_events_to_dispatch(&mut host_tree_order(tree_order))
+ .into_iter()
+ .map(|event| (AnimationRecordRef::from_handle(event.animation), event.event))
+ .collect()
+}
+
+/// The name of the host's `CSS::PseudoElement` `kind`, without its colons.
+pub fn pseudo_element_name(kind: u8) -> &'static str {
+ crate::css::selector::pseudo_element_from_ffi(kind).name()
+}
diff --git a/Libraries/LibWeb/Rust/src/animations/clock_plan.rs b/Libraries/LibWeb/Rust/src/animations/clock_plan.rs
index 987dbd87994..cd0e84016f2 100644
--- a/Libraries/LibWeb/Rust/src/animations/clock_plan.rs
+++ b/Libraries/LibWeb/Rust/src/animations/clock_plan.rs
@@ -114,63 +114,3 @@ impl AnimationRecord {
}
}
}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use crate::animations::animation::AnimationHandle;
- use crate::animations::effect::EffectHandle;
- use timing::{SpecifiedEffectTiming, SpecifiedIterationDuration};
-
- /// A script animation of a one second effect on a document timeline, started at `start_time`, or pending.
- fn animation_started_at(start_time: Option<f64>) -> AnimationHandle {
- let effect = EffectHandle::new();
- effect.borrow_mut().set_specified_timing(SpecifiedEffectTiming {
- iteration_duration: SpecifiedIterationDuration {
- is_auto: false,
- milliseconds: 1000.0,
- },
- ..SpecifiedEffectTiming::default()
- });
- effect.borrow_mut().normalize_specified_timing(None);
- let animation = AnimationHandle::new(AnimationKind::Script);
- animation.borrow_mut().set_effect(Some(effect));
- let mut record = animation.borrow_mut();
- let playback = record.playback_mut();
- match start_time {
- Some(start_time) => playback.start_time = Some(TimeValue::milliseconds(start_time)).into(),
- None => {
- playback.hold_time = Some(TimeValue::milliseconds(0.0)).into();
- playback.has_pending_play_task = true;
- }
- }
- drop(record);
- animation
- }
-
- #[test]
- fn a_tick_moves_a_running_animation_until_its_active_interval_ends() {
- let animation = animation_started_at(Some(100.0));
- let plan = animation
- .borrow()
- .clock_plan(Some(TimeValue::milliseconds(600.0)), false);
- assert_eq!(
- plan,
- ClockPlanAnimation::Ticked {
- local_time: TimeValue::milliseconds(500.0),
- active_end: TimeValue::milliseconds(1000.0),
- }
- );
- let plan = animation
- .borrow()
- .clock_plan(Some(TimeValue::milliseconds(1100.0)), false);
- assert_eq!(plan, ClockPlanAnimation::NotTicked);
- }
-
- #[test]
- fn a_pending_animation_holds_still() {
- let animation = animation_started_at(None);
- let plan = animation.borrow().clock_plan(Some(TimeValue::milliseconds(0.0)), false);
- assert_eq!(plan, ClockPlanAnimation::Held);
- }
-}
diff --git a/Libraries/LibWeb/Rust/src/animations/composite_order.rs b/Libraries/LibWeb/Rust/src/animations/composite_order.rs
index 2c00a6414e7..5f2241f39bc 100644
--- a/Libraries/LibWeb/Rust/src/animations/composite_order.rs
+++ b/Libraries/LibWeb/Rust/src/animations/composite_order.rs
@@ -57,8 +57,8 @@ pub(crate) fn composite_order(a: &AnimationRecord, b: &AnimationRecord, tree_ord
// 1. Sort A and B by applying the following conditions in turn until the order is resolved,
- // 1. If A and B’s associated animations differ by class, sort by any inter-class composite order defined for
- // the corresponding classes.
+ // 1. If A and B’s associated animations differ by class, sort by any inter-class composite order as defined
+ // for the corresponding classes.
// From https://www.w3.org/TR/css-animations-2/#animation-composite-order:
// "CSS Animations with an owning element have a later composite order than CSS Transitions but an earlier
// composite order than animations without a specific animation class."
@@ -214,7 +214,7 @@ fn pseudo_element_rank(pseudo_element: Option<PseudoElementType>) -> u8 {
#[cfg(test)]
mod tests {
use super::*;
- use crate::animations::animation::{AnimationHandle, CssTransitionState};
+ use crate::animations::animation::{AnimationHandle, CssTransitionState, TransitionPhase};
use crate::css::retained_fly_string::RetainedUtf16FlyString;
use crate::css::style_value::RetainedStyleValueData;
@@ -237,7 +237,7 @@ mod tests {
reversing_adjusted_start_value: RetainedStyleValueData::none(),
reversing_shortening_factor: 1.0,
property_id,
- previous_phase: 0,
+ previous_phase: TransitionPhase::Before,
provisional: false,
adopted_from_lane: false,
effect_started_with: None,
diff --git a/Libraries/LibWeb/Rust/src/animations/compositor_update.rs b/Libraries/LibWeb/Rust/src/animations/compositor_update.rs
new file mode 100644
index 00000000000..dc10aeca3c4
--- /dev/null
+++ b/Libraries/LibWeb/Rust/src/animations/compositor_update.rs
@@ -0,0 +1,1283 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! Which animations of a document the compositor runs, which it replaces, and which are throttled, as a rendering
+//! update decides it, and the wakeups that keep the main thread's view of them current. The host answers what the
+//! layout, paint and observer state of the document says of their targets.
+
+use super::animation::{AnimationCell, AnimationHandle};
+use super::composite_order::composite_order;
+use super::document_animations::{DocumentAnimationSetKind, DocumentAnimations};
+use super::effect::{AnimationEffectCell, AnimationEffectId, CompositorAnimationStateAccess, EffectFlag, EffectHandle};
+use super::ffi::{FfiKeepAlive, FfiTreeOrder, host_tree_order};
+use super::host_timing::{FfiAnimationKind, FfiAnimationTimingState, FfiCompositorAnchorKind};
+use super::keyframes::{KeyframeSet, KeyframeValue};
+use super::throttling::{can_skip_per_frame_animation_tick, can_skip_per_frame_style_update};
+use super::timing::{AnimationEffectPhase, AnimationPlayState, TimeValueType};
+use crate::css::property_metadata::property_id;
+use crate::layout::node_data::NodeSlotId;
+use crate::painting::host::{
+ FfiCompositorAnimationBuildOutcome, FfiCompositorAnimationHost, FfiCompositorAnimationRequest,
+ FfiCompositorAnimationTiming, FfiVisualAnimationTargetKind, TARGETED_TRANSFORM_PROPERTY_ROTATE,
+ TARGETED_TRANSFORM_PROPERTY_SCALE, TARGETED_TRANSFORM_PROPERTY_TRANSFORM, TARGETED_TRANSFORM_PROPERTY_TRANSLATE,
+};
+use crate::painting::visual_animation_builder::{
+ CompositorAnimationEffectState, Host, Request, effect_only_translates_horizontally, effect_transform_preserves_axes,
+};
+use crate::render_state::DocumentHost;
+use libcompositing_rust::easing::Easing;
+use std::cell::RefCell;
+use std::collections::HashMap;
+use std::ffi::c_void;
+use std::ptr::NonNull;
+use std::sync::Arc;
+
+/// The target of an effect as the host's `DOM::AbstractElement`: the host's `DOM::Element`, and the host's
+/// `PseudoElement` where `has_pseudo_element`.
+#[repr(C)]
+#[derive(Clone, Copy, PartialEq, Eq, Hash)]
+pub struct FfiCompositorTarget {
+ pub element: NonNull<c_void>,
+ pub has_pseudo_element: bool,
+ pub pseudo_element: u8,
+}
+
+/// A visual context node the host forces on a box for a compositor animation.
+#[repr(u8)]
+#[derive(Clone, Copy, PartialEq, Eq)]
+pub enum FfiCompositorFrameKind {
+ EffectsLayer,
+ BackgroundColor,
+}
+
+/// What the host prepares a compositor animation of an effect for: the target kind, the target and its box, the
+/// properties the effect targets, and the instant it is anchored at. `checked` asks the host to check that the
+/// compositor can run the animation for the box too.
+#[repr(C)]
+pub struct FfiCompositorAnimationPreparation {
+ pub target_kind: u8,
+ pub target: FfiCompositorTarget,
+ pub layout_node: NodeSlotId,
+ pub targeted_transform_properties: u8,
+ pub checked: bool,
+}
+
+/// What the host proves of a paint-only effect, as far as its properties go.
+#[repr(C)]
+pub struct FfiOffscreenPaintQuery {
+ pub targets_only_opacity: bool,
+ pub targets_opacity: bool,
+ /// Whether nothing the effect animates paints outside the border box of the target.
+ pub paint_stays_within_border_box: bool,
+ /// Whether the effect animates only properties that SVG descendants of the target cannot paint elsewhere.
+ pub can_include_svg_descendants: bool,
+ /// Whether the box `layout_node` or the element `element` of an ancestor of the target has an animation that can
+ /// move or expand its paint, with `context`.
+ pub context: *const c_void,
+ pub ancestor_animation_moves_paint:
+ unsafe extern "C" fn(context: *const c_void, layout_node: NodeSlotId, element: *mut c_void) -> bool,
+}
+
+/// A target of an in-effect transform animation, which an observation of a transformed subtree tells apart.
+#[repr(C)]
+pub struct FfiTransformAnimationTarget {
+ pub element: NonNull<c_void>,
+ pub effect: AnimationEffectId,
+}
+
+/// What the host reads of the transform animations of a pass as it finds whether a transform animation affects an
+/// intersection observation.
+#[repr(C)]
+pub struct FfiTransformObservationQuery {
+ pub effect: AnimationEffectId,
+ pub only_translates_horizontally: bool,
+ pub transform_targets: *const FfiTransformAnimationTarget,
+ pub transform_target_count: usize,
+ /// Whether the transform animations of the box `layout_node` keep its axes in place, with `context`.
+ pub context: *const c_void,
+ pub transform_animations_preserve_axes:
+ unsafe extern "C" fn(context: *const c_void, layout_node: NodeSlotId) -> bool,
+}
+
+/// What the host answers and does for an update of a document's compositor animations, with `context`.
+#[repr(C)]
+pub struct FfiCompositorUpdateHost {
+ pub context: *mut c_void,
+ pub document_host: *const DocumentHost,
+ pub force_dark_applies: bool,
+ pub has_throttled_animation_style_update: bool,
+ pub time_origin: f64,
+ pub has_last_animation_frame_timestamp: bool,
+ pub last_animation_frame_timestamp: f64,
+ pub keep_alive: FfiKeepAlive,
+ pub tree_order: FfiTreeOrder,
+ pub layout_node: unsafe extern "C" fn(context: *mut c_void, target: FfiCompositorTarget) -> NodeSlotId,
+ /// Notes the box of a target before the pass changes what it retains, and that the pass retains it.
+ pub note_target_layout_node: unsafe extern "C" fn(context: *mut c_void, layout_node: NodeSlotId),
+ pub note_retained_layout_node: unsafe extern "C" fn(context: *mut c_void, layout_node: NodeSlotId),
+ /// Whether an observer tracks the visibility of the element or of something in it.
+ pub visibility_is_observed: unsafe extern "C" fn(context: *mut c_void, element: NonNull<c_void>) -> bool,
+ /// Fills in what the host knows of the request and the host the keyframes' values resolve with, answering whether
+ /// the compositor can run the animation.
+ pub prepare_compositor_animation: unsafe extern "C" fn(
+ context: *mut c_void,
+ preparation: &FfiCompositorAnimationPreparation,
+ request: *mut c_void,
+ keyframe_host: *mut c_void,
+ ) -> bool,
+ pub paint_is_offscreen:
+ unsafe extern "C" fn(context: *mut c_void, target: FfiCompositorTarget, query: &FfiOffscreenPaintQuery) -> bool,
+ pub transform_affects_intersection_observation: unsafe extern "C" fn(
+ context: *mut c_void,
+ animated_target: NonNull<c_void>,
+ query: &FfiTransformObservationQuery,
+ requires_main_thread_sampling: &mut bool,
+ ) -> bool,
+ pub transform_subtree_is_clipped_outside_viewport:
+ unsafe extern "C" fn(context: *mut c_void, element: NonNull<c_void>) -> bool,
+ pub background_color_can_be_compositor_animated:
+ unsafe extern "C" fn(context: *mut c_void, layout_node: NodeSlotId) -> bool,
+ /// Forces the node on the box where it has none yet, answering whether it did.
+ pub request_frame:
+ unsafe extern "C" fn(context: *mut c_void, layout_node: NodeSlotId, kind: FfiCompositorFrameKind) -> bool,
+ /// Keeps the node the pass forced on the box, and whether the last pass kept it.
+ pub keep_frame: unsafe extern "C" fn(context: *mut c_void, layout_node: NodeSlotId, kind: FfiCompositorFrameKind),
+ pub frame_was_kept:
+ unsafe extern "C" fn(context: *mut c_void, layout_node: NodeSlotId, kind: FfiCompositorFrameKind) -> bool,
+ /// Maps the viewport again, through the visual contexts forcing a node changed.
+ pub refresh_viewport_mapping: unsafe extern "C" fn(context: *mut c_void),
+ pub note_throttled_animation_style_update: unsafe extern "C" fn(context: *mut c_void),
+}
+
+/// What an update of a document's compositor animations leaves the host to do.
+#[repr(C)]
+#[derive(Default)]
+pub struct FfiCompositorUpdateOutcome {
+ pub has_observation_relevant_compositor_animation: bool,
+ pub requested_withdrawn_effect_sample: bool,
+ pub has_wakeup_delay: bool,
+ pub wakeup_delay: f64,
+}
+
+/// What a wakeup of the compositor animations of a document leaves the host to do.
+#[repr(C)]
+#[derive(Default)]
+pub struct FfiCompositorWakeupOutcome {
+ pub has_next_wakeup_delay: bool,
+ pub next_wakeup_delay: f64,
+ pub reached_wakeup: bool,
+ pub reached_compositor_active_start: bool,
+}
+
+unsafe extern "C" {
+ fn web_animation_set_needs_animated_style_update(effect: *const c_void, target: NonNull<c_void>);
+}
+
+/// Asks the next style update for an observation sample of `effect`.
+pub(crate) fn request_observation_sample(effect: &AnimationEffectCell) {
+ if effect.borrow_mut().set_flag(EffectFlag::NeedsObservationSample, true) {
+ set_needs_animated_style_update(effect);
+ }
+}
+
+/// Has the next animated style update of the document of the target of `effect` sample it.
+pub(crate) fn set_needs_animated_style_update(effect: &AnimationEffectCell) {
+ let target = effect.borrow().target_element();
+ if let Some(target) = target {
+ // SAFETY: The effect keeps its target alive.
+ unsafe { web_animation_set_needs_animated_style_update(std::ptr::from_ref(effect).cast(), target) };
+ }
+}
+
+pub(crate) fn is_transform_family(property: u16) -> bool {
+ matches!(
+ property,
+ property_id::TRANSFORM | property_id::TRANSLATE | property_id::ROTATE | property_id::SCALE
+ )
+}
+
+fn minimum(delay: &mut Option<f64>, candidate: f64) {
+ if delay.is_none_or(|delay| candidate < delay) {
+ *delay = Some(candidate);
+ }
+}
+
+/// What the pass reads of an effect's record once.
+struct EffectFacts {
+ id: AnimationEffectId,
+ target: Option<FfiCompositorTarget>,
+ keyframes: Option<Arc<KeyframeSet>>,
+ composite_is_replace: bool,
+ may_run_on_the_compositor: bool,
+}
+
+impl EffectFacts {
+ fn of(effect: &AnimationEffectCell) -> Self {
+ let record = effect.borrow();
+ Self {
+ id: record.id(),
+ target: record.target_element().map(|element| {
+ let pseudo_element = record.pseudo_element();
+ FfiCompositorTarget {
+ element,
+ has_pseudo_element: pseudo_element.is_some(),
+ pseudo_element: pseudo_element.map_or(0, |pseudo_element| pseudo_element.kind),
+ }
+ }),
+ keyframes: record.keyframes().cloned(),
+ composite_is_replace: record.composite() == crate::css::animation::FfiCompositeOperation::Replace,
+ may_run_on_the_compositor: record.may_run_on_the_compositor(),
+ }
+ }
+
+ fn properties(&self) -> &[u16] {
+ self.keyframes
+ .as_ref()
+ .map_or(&[][..], |keyframes| keyframes.target_properties())
+ }
+
+ fn has_custom_properties(&self) -> bool {
+ self.keyframes
+ .as_ref()
+ .is_some_and(|keyframes| !keyframes.target_custom_properties().is_empty())
+ }
+
+ fn has_target_properties(&self) -> bool {
+ !self.properties().is_empty() || self.has_custom_properties()
+ }
+
+ fn targets(&self, property: u16) -> bool {
+ self.properties().contains(&property)
+ }
+
+ fn targets_transform(&self) -> bool {
+ self.properties().iter().copied().any(is_transform_family)
+ }
+
+ fn targeted_transform_properties(&self) -> u8 {
+ let mut properties = 0;
+ for (property, flag) in [
+ (property_id::TRANSLATE, TARGETED_TRANSFORM_PROPERTY_TRANSLATE),
+ (property_id::ROTATE, TARGETED_TRANSFORM_PROPERTY_ROTATE),
+ (property_id::SCALE, TARGETED_TRANSFORM_PROPERTY_SCALE),
+ (property_id::TRANSFORM, TARGETED_TRANSFORM_PROPERTY_TRANSFORM),
+ ] {
+ if self.targets(property) {
+ properties |= flag;
+ }
+ }
+ properties
+ }
+}
+
+/// The effects competing for one property group of a target, and the one whose output the compositor could run.
+struct CompetingPropertyEffects {
+ winner: Option<(EffectHandle, AnimationHandle)>,
+ all_effects_use_replace: bool,
+ effect_count: u32,
+}
+
+impl Default for CompetingPropertyEffects {
+ fn default() -> Self {
+ Self {
+ winner: None,
+ all_effects_use_replace: true,
+ effect_count: 0,
+ }
+ }
+}
+
+impl CompetingPropertyEffects {
+ fn is_won_by(&self, effect: &EffectHandle) -> bool {
+ self.winner.as_ref().is_some_and(|(winner, _)| winner.ptr_eq(effect))
+ }
+}
+
+#[derive(Default)]
+struct CompetingEffects {
+ opacity: CompetingPropertyEffects,
+ background_color: CompetingPropertyEffects,
+ filter: CompetingPropertyEffects,
+ transform: CompetingPropertyEffects,
+}
+
+/// One associated animation of the pass with its associated effect.
+struct Candidate {
+ animation: AnimationHandle,
+ effect: EffectHandle,
+ facts: EffectFacts,
+ was_throttled: bool,
+ was_published: bool,
+}
+
+/// The compositor animation of `kind` of an effect for the box `layout_node` of `target` the pass asks the host to
+/// prepare, anchored at `timing_anchor` as the monotonic time and the local time there, where the host is `checked`
+/// it can run it.
+#[derive(Clone, Copy)]
+struct CompositorAnimationAsk {
+ target: FfiCompositorTarget,
+ layout_node: NodeSlotId,
+ kind: FfiVisualAnimationTargetKind,
+ checked: bool,
+ timing_anchor: (f64, f64),
+}
+
+/// What a pass knows as it goes, which the host's queries read back through its callbacks.
+struct Pass<'a> {
+ host: &'a FfiCompositorUpdateHost,
+ competing_effects: Vec<(FfiCompositorTarget, CompetingEffects)>,
+ competing_index: HashMap<FfiCompositorTarget, usize>,
+ in_effect_transform_effects_by_layout_node: HashMap<NodeSlotId, Vec<(EffectHandle, AnimationHandle)>>,
+ animated_transform_preserves_axes: RefCell<HashMap<AnimationEffectId, bool>>,
+}
+
+fn existing_state(effect: &AnimationEffectCell) -> Option<*mut CompositorAnimationEffectState> {
+ effect
+ .borrow_mut()
+ .compositor_animation_state(CompositorAnimationStateAccess::Existing)
+ .map(std::ptr::from_mut)
+}
+
+fn state_of(effect: &AnimationEffectCell) -> *mut CompositorAnimationEffectState {
+ std::ptr::from_mut(
+ effect
+ .borrow_mut()
+ .compositor_animation_state(CompositorAnimationStateAccess::CreateIfMissing)
+ .expect("the state is made where missing"),
+ )
+}
+
+fn has_retained_compositor_animations(effect: &AnimationEffectCell) -> bool {
+ // SAFETY: The effect keeps its state for as long as it lives.
+ existing_state(effect).is_some_and(|state| unsafe { (*state).has_retained() })
+}
+
+impl Pass<'_> {
+ fn layout_node(&self, target: FfiCompositorTarget) -> Option<NodeSlotId> {
+ // SAFETY: The host answers synchronously.
+ let slot = unsafe { (self.host.layout_node)(self.host.context, target) };
+ (slot != NodeSlotId::INVALID).then_some(slot)
+ }
+
+ fn competing(&self, target: &FfiCompositorTarget) -> Option<&CompetingEffects> {
+ self.competing_index
+ .get(target)
+ .map(|&index| &self.competing_effects[index].1)
+ }
+
+ fn composite_order_is_before(&self, a: &AnimationCell, b: &AnimationCell) -> bool {
+ if std::ptr::eq(a, b) {
+ return false;
+ }
+ composite_order(&a.borrow(), &b.borrow(), &mut host_tree_order(self.host.tree_order)).is_lt()
+ }
+
+ /// Prepares the request for a compositor animation of `kind` of the effect for the box `layout_node`, answering it
+ /// with the host its keyframes resolve with, where the host finds the compositor can run it.
+ fn prepare(
+ &self,
+ effect: &AnimationEffectCell,
+ animation: &AnimationCell,
+ facts: &EffectFacts,
+ ask: CompositorAnimationAsk,
+ default_easing: &Easing,
+ ) -> Option<(FfiCompositorAnimationRequest, FfiCompositorAnimationHost)> {
+ let CompositorAnimationAsk {
+ target,
+ layout_node,
+ kind,
+ checked,
+ timing_anchor,
+ } = ask;
+ let effect_timing = effect.borrow().timing();
+ let mut request = FfiCompositorAnimationRequest {
+ target_kind: kind,
+ layout_node,
+ target_inherited_ui_values: std::ptr::null(),
+ target_inherited_text_values: std::ptr::null(),
+ timing: FfiCompositorAnimationTiming {
+ monotonic_time_at_anchor_ns: (timing_anchor.0 * 1_000_000.0) as i64,
+ local_time_at_anchor_ms: timing_anchor.1,
+ playback_rate: animation.borrow().playback().playback_rate,
+ effect: effect_timing,
+ easing: default_easing.descriptor(),
+ },
+ keyframe_set: facts
+ .keyframes
+ .as_ref()
+ .map_or(std::ptr::null(), |keyframes| Arc::as_ptr(keyframes).cast()),
+ effect_composite_is_replace: facts.composite_is_replace,
+ default_easing: default_easing.descriptor(),
+ target_style_generation: 0,
+ style_environment_version: 0,
+ reference_box_width: 0.0,
+ reference_box_height: 0.0,
+ device_pixels_per_css_pixel: 1.0,
+ targeted_transform_properties: facts.targeted_transform_properties(),
+ targets_only_transform: facts.properties() == [property_id::TRANSFORM] && !facts.has_custom_properties(),
+ };
+ let mut keyframe_host = std::mem::MaybeUninit::<FfiCompositorAnimationHost>::uninit();
+ let preparation = FfiCompositorAnimationPreparation {
+ target_kind: kind as u8,
+ target,
+ layout_node,
+ targeted_transform_properties: request.targeted_transform_properties,
+ checked,
+ };
+ // SAFETY: The host answers synchronously, and fills in the keyframe host where it answers true.
+ unsafe {
+ (self.host.prepare_compositor_animation)(
+ self.host.context,
+ &preparation,
+ std::ptr::from_mut(&mut request).cast(),
+ keyframe_host.as_mut_ptr().cast(),
+ )
+ .then(|| (request, keyframe_host.assume_init()))
+ }
+ }
+
+ /// Builds the compositor animation of `kind` for the effect, which it keeps pending, where the compositor can run
+ /// it.
+ fn build(
+ &self,
+ effect: &EffectHandle,
+ facts: &EffectFacts,
+ kind: FfiVisualAnimationTargetKind,
+ ) -> FfiCompositorAnimationBuildOutcome {
+ let Some(animation) = effect.borrow().associated_animation() else {
+ return FfiCompositorAnimationBuildOutcome::default();
+ };
+ // NB: The record decides whether the compositor may run the effect as far as its timing goes, and where its
+ // animation is anchored.
+ let state = animation.borrow().timing_state(None);
+ if state.compositor_anchor == FfiCompositorAnchorKind::None || !facts.has_target_properties() {
+ return FfiCompositorAnimationBuildOutcome::default();
+ }
+ let targets_kind = match kind {
+ FfiVisualAnimationTargetKind::Opacity => facts.targets(property_id::OPACITY),
+ FfiVisualAnimationTargetKind::BackgroundColor => facts.targets(property_id::BACKGROUND_COLOR),
+ FfiVisualAnimationTargetKind::Filter => facts.targets(property_id::FILTER),
+ FfiVisualAnimationTargetKind::Transform => facts.targets_transform(),
+ };
+ if !targets_kind || !facts.may_run_on_the_compositor {
+ return FfiCompositorAnimationBuildOutcome::default();
+ }
+ let Some(target) = facts.target else {
+ return FfiCompositorAnimationBuildOutcome::default();
+ };
+ let monotonic_time_at_anchor = if state.compositor_anchor == FfiCompositorAnchorKind::OriginRelativeTime {
+ state.compositor_anchor_origin_relative_time + self.host.time_origin
+ } else if self.host.has_last_animation_frame_timestamp {
+ self.host.last_animation_frame_timestamp + self.host.time_origin
+ } else {
+ return FfiCompositorAnimationBuildOutcome::default();
+ };
+ let Some(layout_node) = self.layout_node(target) else {
+ return FfiCompositorAnimationBuildOutcome::default();
+ };
+ if facts
+ .keyframes
+ .as_ref()
+ .is_none_or(|keyframes| keyframes.keyframes().len() < 2)
+ {
+ return FfiCompositorAnimationBuildOutcome::default();
+ }
+ let default_easing = default_easing_of(&animation, &state);
+ let Some((request, keyframe_host)) = self.prepare(
+ effect,
+ &animation,
+ facts,
+ CompositorAnimationAsk {
+ target,
+ layout_node,
+ kind,
+ checked: true,
+ timing_anchor: (monotonic_time_at_anchor, state.compositor_anchor_local_time),
+ },
+ &default_easing,
+ ) else {
+ return FfiCompositorAnimationBuildOutcome::default();
+ };
+ let state = state_of(effect);
+ // SAFETY: The effect keeps its state for as long as it lives, the document host is live for the pass, and the
+ // request and the keyframe host live for the call.
+ unsafe {
+ crate::painting::ffi::build_compositor_animation_effect(
+ &mut *state,
+ &*self.host.document_host,
+ request,
+ effect,
+ &animation,
+ &keyframe_host,
+ )
+ }
+ }
+
+ /// Answers `question` of the transform keyframes of the effect for the box `layout_node`.
+ fn ask_transform_keyframes(
+ &self,
+ effect: &EffectHandle,
+ facts: &EffectFacts,
+ layout_node: NodeSlotId,
+ question: fn(&Request, &Host) -> bool,
+ ) -> bool {
+ let Some(animation) = effect.borrow().associated_animation() else {
+ return false;
+ };
+ let Some(target) = facts.target else {
+ return false;
+ };
+ if facts.keyframes.is_none() {
+ return false;
+ }
+ let state = animation.borrow().timing_state(None);
+ let default_easing = default_easing_of(&animation, &state);
+ let Some((request, keyframe_host)) = self.prepare(
+ effect,
+ &animation,
+ facts,
+ CompositorAnimationAsk {
+ target,
+ layout_node,
+ kind: FfiVisualAnimationTargetKind::Transform,
+ checked: false,
+ timing_anchor: (0.0, 0.0),
+ },
+ &default_easing,
+ ) else {
+ return false;
+ };
+ // SAFETY: The request lives for the call.
+ let request = unsafe { Request::new(&request) };
+ question(&request, &Host::new(&keyframe_host))
+ }
+
+ fn animated_transform_preserves_axes(&self, effect: &EffectHandle, layout_node: NodeSlotId) -> bool {
+ let facts = EffectFacts::of(effect);
+ if let Some(&cached) = self.animated_transform_preserves_axes.borrow().get(&facts.id) {
+ return cached;
+ }
+ let preserves_axes = if facts.targets(property_id::ROTATE) {
+ false
+ } else if !facts.targets(property_id::TRANSFORM) {
+ true
+ } else {
+ self.ask_transform_keyframes(effect, &facts, layout_node, effect_transform_preserves_axes)
+ };
+ self.animated_transform_preserves_axes
+ .borrow_mut()
+ .insert(facts.id, preserves_axes);
+ preserves_axes
+ }
+
+ /// Whether a paint-only effect cannot show, as its target is offscreen.
+ fn paint_only_effect_is_offscreen(&self, facts: &EffectFacts, target: FfiCompositorTarget) -> bool {
+ // NB: Only properties whose changes are confined to painting are eligible. In particular, color can
+ // affect SVG stroke geometry, and transforms can affect layout. Filters require an ancestor clip.
+ if facts.has_custom_properties() {
+ return false;
+ }
+ let mut paint_stays_within_border_box = true;
+ for &property in facts.properties() {
+ match property {
+ property_id::BACKGROUND_COLOR
+ // NB: Keyframes containing var() retain the shorthand until substitution.
+ | property_id::BACKGROUND_POSITION
+ | property_id::BACKGROUND_POSITION_X
+ | property_id::BACKGROUND_POSITION_Y
+ | property_id::BACKGROUND_SIZE
+ | property_id::BACKGROUND_REPEAT
+ | property_id::BACKGROUND_ORIGIN
+ | property_id::BACKGROUND_CLIP
+ | property_id::BACKGROUND_BLEND_MODE
+ | property_id::BORDER_TOP_COLOR
+ | property_id::BORDER_RIGHT_COLOR
+ | property_id::BORDER_BOTTOM_COLOR
+ | property_id::BORDER_LEFT_COLOR => {}
+ property_id::OPACITY
+ | property_id::FILTER
+ | property_id::BOX_SHADOW
+ | property_id::OUTLINE_COLOR
+ | property_id::OUTLINE_OFFSET
+ | property_id::OUTLINE_STYLE
+ | property_id::OUTLINE_WIDTH
+ | property_id::TEXT_DECORATION_COLOR
+ | property_id::TEXT_DECORATION_STYLE
+ | property_id::TEXT_DECORATION_THICKNESS => paint_stays_within_border_box = false,
+ _ => return false,
+ }
+ }
+ let query = FfiOffscreenPaintQuery {
+ targets_only_opacity: facts
+ .properties()
+ .iter()
+ .all(|&property| property == property_id::OPACITY),
+ targets_opacity: facts.targets(property_id::OPACITY),
+ paint_stays_within_border_box,
+ can_include_svg_descendants: facts
+ .properties()
+ .iter()
+ .all(|&property| matches!(property, property_id::OPACITY | property_id::FILTER)),
+ context: std::ptr::from_ref(self).cast(),
+ ancestor_animation_moves_paint,
+ };
+ // SAFETY: The host answers synchronously.
+ unsafe { (self.host.paint_is_offscreen)(self.host.context, target, &query) }
+ }
+}
+
+unsafe extern "C" fn ancestor_animation_moves_paint(
+ context: *const c_void,
+ layout_node: NodeSlotId,
+ element: *mut c_void,
+) -> bool {
+ // SAFETY: The pass hands the host itself as the context, for the call it makes.
+ let pass = unsafe { &*context.cast::<Pass>() };
+ if pass
+ .in_effect_transform_effects_by_layout_node
+ .contains_key(&layout_node)
+ {
+ return true;
+ }
+ let Some(element) = NonNull::new(element) else {
+ return false;
+ };
+ let target = FfiCompositorTarget {
+ element,
+ has_pseudo_element: false,
+ pseudo_element: 0,
+ };
+ pass.competing(&target)
+ .is_some_and(|effects| effects.filter.winner.is_some())
+}
+
+unsafe extern "C" fn transform_animations_preserve_axes(context: *const c_void, layout_node: NodeSlotId) -> bool {
+ // SAFETY: The pass hands the host itself as the context, for the call it makes.
+ let pass = unsafe { &*context.cast::<Pass>() };
+ let Some(effects) = pass.in_effect_transform_effects_by_layout_node.get(&layout_node) else {
+ return true;
+ };
+ effects
+ .iter()
+ .all(|(effect, _)| pass.animated_transform_preserves_axes(effect, layout_node))
+}
+
+/// The easing a keyframe of the effect of `animation` that declares none runs: a CSS animation's, or linear.
+fn default_easing_of(animation: &AnimationCell, state: &FfiAnimationTimingState) -> Easing {
+ if state.kind != FfiAnimationKind::CssAnimation {
+ return Easing::default();
+ }
+ animation.borrow().css_animation().default_easing.easing()
+}
+
+/// Whether the effect uses only replace keyframes.
+fn uses_replace_keyframes(keyframes: Option<&Arc<KeyframeSet>>) -> bool {
+ keyframes.is_some_and(|keyframes| !keyframes.has_additive_keyframe())
+}
+
+/// Whether a keyframe of the effect leaves a property `is_property` names out, taking the underlying value, which is
+/// the output of the effects beneath the winner where there are any. The compositor only knows the element's own style.
+fn takes_the_underlying_value(keyframes: Option<&Arc<KeyframeSet>>, is_property: impl Fn(u16) -> bool) -> bool {
+ let Some(keyframes) = keyframes else {
+ return false;
+ };
+ keyframes.keyframes().iter().any(|keyframe| {
+ keyframes.target_properties().iter().any(|&property| {
+ is_property(property)
+ && keyframes
+ .declarations_of(keyframe)
+ .iter()
+ .find(|declaration| declaration.property_id == property)
+ .is_some_and(|declaration| declaration.value == KeyframeValue::ElementValue)
+ })
+ })
+}
+
+/// The candidates of a pass: the associated animations of the document with associated effects, which the host keeps
+/// alive through `keep_alive` with `context` for the pass.
+fn candidates_of(
+ animations: &mut DocumentAnimations,
+ keep_alive: Option<(FfiKeepAlive, *mut c_void)>,
+) -> Vec<(AnimationHandle, EffectHandle)> {
+ animations
+ .set_mut(DocumentAnimationSetKind::Associated)
+ .alive()
+ .into_iter()
+ .filter_map(|animation| {
+ if let Some((keep_alive, context)) = keep_alive {
+ // SAFETY: The host keeps the animation alive for the pass.
+ unsafe { keep_alive(context, &animation) };
+ }
+ let effect = animation.borrow().effect().cloned()?;
+ Some((animation, effect))
+ })
+ .collect()
+}
+
+/// https://www.w3.org/TR/web-animations-1/#animation-composite-order
+/// Updates which of the associated animations of a document whose animations are `animations` the compositor runs,
+/// replaces or throttles, through `host`.
+///
+/// # Safety
+/// `animations` must be what a live document knows of animations, which asking for a sample reaches, and `host` must
+/// hold live callbacks and a live document host for the call.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn animations_document_update_compositor_animations(
+ animations: *mut DocumentAnimations,
+ host: &FfiCompositorUpdateHost,
+) -> FfiCompositorUpdateOutcome {
+ let call = |function: unsafe extern "C" fn(*mut c_void)| {
+ // SAFETY: The host answers synchronously.
+ unsafe { function(host.context) }
+ };
+ let mut pass = Pass {
+ host,
+ competing_effects: Vec::new(),
+ competing_index: HashMap::new(),
+ in_effect_transform_effects_by_layout_node: HashMap::new(),
+ animated_transform_preserves_axes: RefCell::new(HashMap::new()),
+ };
+ let mut candidates = Vec::new();
+ let mut transform_targets = Vec::new();
+ // SAFETY: Guaranteed by the caller, and the borrow ends before any sample is asked for.
+ let alive_candidates = candidates_of(unsafe { &mut *animations }, Some((host.keep_alive, host.context)));
+ for (animation, effect) in alive_candidates {
+ let facts = EffectFacts::of(&effect);
+ let was_throttled = {
+ let record = effect.borrow();
+ record.has_flag(EffectFlag::CompositorDriven)
+ || record.has_flag(EffectFlag::CompositorReplaced)
+ || record.has_flag(EffectFlag::OffscreenThrottled)
+ };
+ let was_published = has_retained_compositor_animations(&effect);
+ if let Some(target) = facts.target
+ && let Some(layout_node) = pass.layout_node(target)
+ {
+ // SAFETY: The host answers synchronously.
+ unsafe { (host.note_target_layout_node)(host.context, layout_node) };
+ }
+ {
+ let mut record = effect.borrow_mut();
+ record.set_flag(EffectFlag::CompositorDriven, false);
+ record.set_flag(EffectFlag::CompositorReplaced, false);
+ record.set_flag(EffectFlag::OffscreenThrottled, false);
+ record.set_flag(EffectFlag::ObservationRelevantCompositorAnimation, false);
+ }
+
+ let state = animation.borrow().timing_state(None);
+ let candidate = Candidate {
+ animation: animation.clone(),
+ effect: effect.clone(),
+ facts,
+ was_throttled,
+ was_published,
+ };
+ let facts = &candidate.facts;
+ if state.play_state == AnimationPlayState::Idle
+ || (!state.is_in_effect && state.phase != AnimationEffectPhase::Before)
+ {
+ candidates.push(candidate);
+ continue;
+ }
+ let Some(target) = facts.target else {
+ candidates.push(candidate);
+ continue;
+ };
+ if state.is_in_effect && facts.targets_transform() {
+ transform_targets.push(FfiTransformAnimationTarget {
+ element: target.element,
+ effect: facts.id,
+ });
+ }
+ let index = *pass.competing_index.entry(target).or_insert_with(|| {
+ pass.competing_effects.push((target, CompetingEffects::default()));
+ pass.competing_effects.len() - 1
+ });
+ let add_competing_effect =
+ |pass: &mut Pass, select: fn(&mut CompetingEffects) -> &mut CompetingPropertyEffects| {
+ let winner_animation = select(&mut pass.competing_effects[index].1)
+ .winner
+ .as_ref()
+ .map(|(_, animation)| animation.clone());
+ let effect_produces_output = state.is_in_effect;
+ let winner_produces_output = winner_animation
+ .as_ref()
+ .is_some_and(|animation| animation.borrow().timing_state(None).is_in_effect);
+ let replaces_winner = match &winner_animation {
+ None => true,
+ Some(winner_animation) => {
+ (effect_produces_output && !winner_produces_output)
+ || (effect_produces_output == winner_produces_output
+ && pass.composite_order_is_before(winner_animation, &animation))
+ }
+ };
+ let property_effects = select(&mut pass.competing_effects[index].1);
+ property_effects.effect_count += 1;
+ if effect_produces_output && !facts.composite_is_replace {
+ property_effects.all_effects_use_replace = false;
+ }
+ if replaces_winner {
+ property_effects.winner = Some((effect.clone(), animation.clone()));
+ }
+ };
+ if facts.targets(property_id::OPACITY) {
+ add_competing_effect(&mut pass, |effects| &mut effects.opacity);
+ }
+ if facts.targets(property_id::BACKGROUND_COLOR) {
+ add_competing_effect(&mut pass, |effects| &mut effects.background_color);
+ }
+ if facts.targets(property_id::FILTER) {
+ add_competing_effect(&mut pass, |effects| &mut effects.filter);
+ }
+ if facts.targets_transform() {
+ add_competing_effect(&mut pass, |effects| &mut effects.transform);
+ if let Some(layout_node) = pass.layout_node(target) {
+ pass.in_effect_transform_effects_by_layout_node
+ .entry(layout_node)
+ .or_default()
+ .push((effect.clone(), animation.clone()));
+ }
+ }
+ candidates.push(candidate);
+ }
+
+ for (_, effects) in &mut pass.competing_effects {
+ let validate_winner = |property_effects: &mut CompetingPropertyEffects, is_property: fn(u16) -> bool| {
+ let keyframes = property_effects
+ .winner
+ .as_ref()
+ .and_then(|(winner, _)| winner.borrow().keyframes().cloned());
+ if !property_effects.all_effects_use_replace
+ || (property_effects.winner.is_some() && !uses_replace_keyframes(keyframes.as_ref()))
+ || (property_effects.winner.is_some()
+ && property_effects.effect_count > 1
+ && takes_the_underlying_value(keyframes.as_ref(), is_property))
+ {
+ property_effects.winner = None;
+ }
+ };
+ validate_winner(&mut effects.opacity, |property| property == property_id::OPACITY);
+ validate_winner(&mut effects.background_color, |property| {
+ property == property_id::BACKGROUND_COLOR
+ });
+ validate_winner(&mut effects.filter, |property| property == property_id::FILTER);
+ validate_winner(&mut effects.transform, is_transform_family);
+ }
+
+ // NB: An opacity of 1 does not otherwise create an effects frame. Give an otherwise publishable opacity
+ // animation a target before the normal handoff loop, and retain that target while the effect remains live.
+ let mut forced_opacity_effects_layer = false;
+ for index in 0..pass.competing_effects.len() {
+ let target = pass.competing_effects[index].0;
+ let Some((effect, _)) = pass.competing_effects[index].1.opacity.winner.clone() else {
+ continue;
+ };
+ let facts = EffectFacts::of(&effect);
+ let can_force_opacity_effects_layer = !facts.has_custom_properties()
+ && facts.properties().iter().all(|&property| {
+ matches!(property, property_id::OPACITY | property_id::BACKGROUND_COLOR)
+ || is_transform_family(property)
+ });
+ // SAFETY: The host answers synchronously.
+ if unsafe { (host.visibility_is_observed)(host.context, target.element) } || !can_force_opacity_effects_layer {
+ continue;
+ }
+
+ let missing_visual_context_node = pass
+ .build(&effect, &facts, FfiVisualAnimationTargetKind::Opacity)
+ .missing_visual_context_node;
+ let Some(layout_node) = pass.layout_node(target) else {
+ continue;
+ };
+ // SAFETY: The host answers synchronously.
+ unsafe {
+ let already_forced_effects_layer =
+ (host.frame_was_kept)(host.context, layout_node, FfiCompositorFrameKind::EffectsLayer);
+ if !missing_visual_context_node && !already_forced_effects_layer {
+ continue;
+ }
+ if missing_visual_context_node
+ && (host.request_frame)(host.context, layout_node, FfiCompositorFrameKind::EffectsLayer)
+ {
+ forced_opacity_effects_layer = true;
+ }
+ (host.keep_frame)(host.context, layout_node, FfiCompositorFrameKind::EffectsLayer);
+ }
+ }
+ if forced_opacity_effects_layer {
+ call(host.refresh_viewport_mapping);
+ }
+
+ let mut outcome = FfiCompositorUpdateOutcome::default();
+ let mut wakeup_delay = None;
+ let mut has_throttled_animation_style_update = host.has_throttled_animation_style_update;
+ let mut only_translates_horizontally_cache: HashMap<AnimationEffectId, bool> = HashMap::new();
+ for candidate in &candidates {
+ let effect = &candidate.effect;
+ if let Some(state) = existing_state(effect) {
+ // SAFETY: The effect keeps its state for as long as it lives.
+ unsafe { (*state).clear_pending() };
+ }
+ let published_compositor_animation = update_candidate(
+ &pass,
+ candidate,
+ &transform_targets,
+ &mut wakeup_delay,
+ &mut only_translates_horizontally_cache,
+ );
+
+ if let Some(state) = existing_state(effect) {
+ // SAFETY: The effect keeps its state for as long as it lives.
+ unsafe {
+ if !published_compositor_animation {
+ (*state).clear_retained();
+ }
+ (*state).clear_pending();
+ }
+ }
+ let (is_throttled, is_observation_relevant) = {
+ let record = effect.borrow();
+ (
+ record.has_flag(EffectFlag::CompositorDriven)
+ || record.has_flag(EffectFlag::CompositorReplaced)
+ || record.has_flag(EffectFlag::OffscreenThrottled),
+ record.has_flag(EffectFlag::ObservationRelevantCompositorAnimation),
+ )
+ };
+ if is_observation_relevant {
+ outcome.has_observation_relevant_compositor_animation = true;
+ }
+ if candidate.was_throttled && !is_throttled {
+ request_observation_sample(effect);
+ outcome.requested_withdrawn_effect_sample = true;
+ }
+ if !has_throttled_animation_style_update && can_skip_per_frame_style_update(effect) {
+ call(host.note_throttled_animation_style_update);
+ has_throttled_animation_style_update = true;
+ }
+ }
+ if let Some(delay) = wakeup_delay {
+ outcome.has_wakeup_delay = true;
+ outcome.wakeup_delay = delay;
+ }
+ outcome
+}
+
+/// Decides how the compositor handles the effect of `candidate`, answering whether it published compositor animations
+/// of it.
+fn update_candidate(
+ pass: &Pass,
+ candidate: &Candidate,
+ transform_targets: &[FfiTransformAnimationTarget],
+ wakeup_delay: &mut Option<f64>,
+ only_translates_horizontally_cache: &mut HashMap<AnimationEffectId, bool>,
+) -> bool {
+ let host = pass.host;
+ let effect = &candidate.effect;
+ let facts = &candidate.facts;
+ let Some(target) = facts.target else {
+ return false;
+ };
+ if !facts.has_target_properties() {
+ return false;
+ }
+ let state = candidate.animation.borrow().timing_state(None);
+ if state.play_state == AnimationPlayState::Idle
+ || (!state.is_in_effect && state.phase != AnimationEffectPhase::Before)
+ {
+ return false;
+ }
+ let set_flag = |flag: EffectFlag, value: bool| {
+ effect.borrow_mut().set_flag(flag, value);
+ };
+ let mut schedule_next_phase_wakeup = |state: &FfiAnimationTimingState| {
+ // NB: The record decides when the effect next changes phase.
+ if let Some(delay) = state.next_phase_boundary_delay.get() {
+ minimum(wakeup_delay, delay);
+ }
+ };
+
+ // NB: The record decides whether the timing of the effect lets it be throttled.
+ if state.can_throttle_offscreen_effect && pass.paint_only_effect_is_offscreen(facts, target) {
+ set_flag(EffectFlag::OffscreenThrottled, true);
+ schedule_next_phase_wakeup(&state);
+ return false;
+ }
+
+ let targets_opacity = facts.targets(property_id::OPACITY);
+ let targets_background_color = facts.targets(property_id::BACKGROUND_COLOR);
+ let targets_filter = facts.targets(property_id::FILTER);
+ let targets_transform = facts.targets_transform();
+ if !facts.may_run_on_the_compositor {
+ return false;
+ }
+ let target_effects = pass
+ .competing(&target)
+ .expect("an effect in effect competes for its target");
+ let all_targeted_properties_have_replace_winners = (!targets_opacity || target_effects.opacity.winner.is_some())
+ && (!targets_background_color || target_effects.background_color.winner.is_some())
+ && (!targets_filter || target_effects.filter.winner.is_some())
+ && (!targets_transform || target_effects.transform.winner.is_some());
+ let selected_for_opacity = targets_opacity && target_effects.opacity.is_won_by(effect);
+ let selected_for_background_color = targets_background_color && target_effects.background_color.is_won_by(effect);
+ let selected_for_filter = targets_filter && target_effects.filter.is_won_by(effect);
+ let selected_for_transform = targets_transform && target_effects.transform.is_won_by(effect);
+
+ // Background colors are display-list content, so associate their fill commands with a dedicated metadata
+ // frame. Validate the descriptor before forcing that frame, which requires one repaint before the animation
+ // can move to the compositor.
+ let mut background_color_layout_node = None;
+ let mut background_color_animation_was_built = false;
+ if selected_for_background_color
+ && let Some(layout_node) = pass.layout_node(target)
+ // SAFETY: The host answers synchronously.
+ && !host.force_dark_applies
+ && unsafe { (host.background_color_can_be_compositor_animated)(host.context, layout_node) }
+ {
+ let build = pass.build(effect, facts, FfiVisualAnimationTargetKind::BackgroundColor);
+ background_color_animation_was_built = build.built;
+ if build.built || build.missing_visual_context_node {
+ background_color_layout_node = Some(layout_node);
+ if build.missing_visual_context_node {
+ // SAFETY: The host answers synchronously.
+ unsafe { (host.request_frame)(host.context, layout_node, FfiCompositorFrameKind::BackgroundColor) };
+ }
+ }
+ }
+
+ // Filters need an effects frame whose filter payload can be replaced. Validate the descriptor before forcing
+ // that frame, which requires one repaint before the animation can move to the compositor.
+ let mut filter_layout_node = None;
+ let mut filter_animation_was_built = false;
+ if selected_for_filter && let Some(layout_node) = pass.layout_node(target) {
+ let build = pass.build(effect, facts, FfiVisualAnimationTargetKind::Filter);
+ filter_animation_was_built = build.built;
+ if build.built || build.missing_visual_context_node {
+ filter_layout_node = Some(layout_node);
+ if build.missing_visual_context_node {
+ // SAFETY: The host answers synchronously.
+ unsafe { (host.request_frame)(host.context, layout_node, FfiCompositorFrameKind::EffectsLayer) };
+ }
+ }
+ }
+
+ if !selected_for_opacity && !selected_for_background_color && !selected_for_filter && !selected_for_transform {
+ if all_targeted_properties_have_replace_winners && state.can_throttle_replaced_effect {
+ set_flag(EffectFlag::CompositorReplaced, true);
+ schedule_next_phase_wakeup(&state);
+ }
+ return false;
+ }
+
+ let compositor_animation_state = state_of(effect);
+ let mut opacity_was_handed_off = !selected_for_opacity;
+ if selected_for_opacity && pass.build(effect, facts, FfiVisualAnimationTargetKind::Opacity).built {
+ opacity_was_handed_off = true;
+ }
+ let background_color_was_handed_off = !selected_for_background_color || background_color_animation_was_built;
+ // SAFETY: The host answers synchronously.
+ unsafe {
+ if let Some(layout_node) = background_color_layout_node {
+ (host.keep_frame)(host.context, layout_node, FfiCompositorFrameKind::BackgroundColor);
+ }
+ if let Some(layout_node) = filter_layout_node {
+ (host.keep_frame)(host.context, layout_node, FfiCompositorFrameKind::EffectsLayer);
+ }
+ }
+ let filter_was_handed_off = !selected_for_filter || filter_animation_was_built;
+ let mut transform_was_handed_off = !selected_for_transform;
+ if selected_for_transform {
+ let build = pass.build(effect, facts, FfiVisualAnimationTargetKind::Transform);
+ transform_was_handed_off = build.built;
+ if build.only_translates_horizontally_is_known {
+ only_translates_horizontally_cache.insert(facts.id, build.only_translates_horizontally);
+ }
+ }
+
+ // SAFETY: The host answers synchronously, and the effect keeps its state for as long as it lives.
+ unsafe {
+ if selected_for_opacity && (host.visibility_is_observed)(host.context, target.element) {
+ (*compositor_animation_state).discard_pending(FfiVisualAnimationTargetKind::Opacity);
+ opacity_was_handed_off = false;
+ }
+ }
+
+ let mut transform_affects_observation = false;
+ let mut requires_main_thread_observation_sampling = false;
+ if selected_for_transform {
+ let only_translates_horizontally = *only_translates_horizontally_cache.entry(facts.id).or_insert_with(|| {
+ pass.layout_node(target).is_some_and(|layout_node| {
+ pass.ask_transform_keyframes(effect, facts, layout_node, effect_only_translates_horizontally)
+ })
+ });
+ let query = FfiTransformObservationQuery {
+ effect: facts.id,
+ only_translates_horizontally,
+ transform_targets: transform_targets.as_ptr(),
+ transform_target_count: transform_targets.len(),
+ context: std::ptr::from_ref(pass).cast(),
+ transform_animations_preserve_axes,
+ };
+ // SAFETY: The host answers synchronously.
+ transform_affects_observation = unsafe {
+ (host.transform_affects_intersection_observation)(
+ host.context,
+ target.element,
+ &query,
+ &mut requires_main_thread_observation_sampling,
+ )
+ };
+ }
+ // SAFETY: The effect keeps its state for as long as it lives.
+ let compositor_animation_state = unsafe { &mut *compositor_animation_state };
+ if requires_main_thread_observation_sampling {
+ compositor_animation_state.discard_pending(FfiVisualAnimationTargetKind::Transform);
+ transform_was_handed_off = false;
+ }
+
+ if !compositor_animation_state.has_pending() {
+ // SAFETY: The host answers synchronously.
+ if selected_for_transform
+ && !transform_affects_observation
+ && unsafe { (host.transform_subtree_is_clipped_outside_viewport)(host.context, target.element) }
+ {
+ set_flag(EffectFlag::OffscreenThrottled, true);
+ }
+ return false;
+ }
+ if all_targeted_properties_have_replace_winners
+ && opacity_was_handed_off
+ && background_color_was_handed_off
+ && filter_was_handed_off
+ && transform_was_handed_off
+ {
+ set_flag(EffectFlag::CompositorDriven, true);
+ }
+ set_flag(
+ EffectFlag::ObservationRelevantCompositorAnimation,
+ transform_affects_observation,
+ );
+ schedule_next_phase_wakeup(&state);
+ // OPTIMIZATION: Ordinary rendering updates advance the WebContent timeline without changing compositor
+ // playback. An effect published before keeps the anchors of the animations whose parameters
+ // did not change.
+ let published = compositor_animation_state.publish_pending(candidate.was_published);
+ // SAFETY: The document host is live for the pass.
+ unsafe { &*host.document_host }.publish_compositor_animations(published);
+ if let Some(layout_node) = pass.layout_node(target) {
+ // SAFETY: The host answers synchronously.
+ unsafe { (host.note_retained_layout_node)(host.context, layout_node) };
+ }
+ true
+}
+
+/// The local time of the next iteration event of a CSS animation whose ticks are throttled, whose timing is `state`.
+pub(crate) fn next_throttled_animation_iteration_event_time(
+ state: &FfiAnimationTimingState,
+ effect: &AnimationEffectCell,
+) -> Option<f64> {
+ // NB: The record decides this as far as the timing goes.
+ let time = state.next_throttled_iteration_event_time.get()?;
+ if !can_skip_per_frame_style_update(effect) || state.phase != AnimationEffectPhase::Active {
+ return None;
+ }
+ Some(time)
+}
+
+/// Wakes the throttled and compositor-driven animations of a document whose animations are `animations` at
+/// `timestamp`: asks for the samples of those that reached an instant the main thread must see, and answers when the
+/// next is due.
+///
+/// # Safety
+/// `animations` must be what a live document knows of animations, which asking for a sample reaches.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn animations_document_service_compositor_animation_wakeup(
+ animations: *mut DocumentAnimations,
+ timestamp: f64,
+) -> FfiCompositorWakeupOutcome {
+ let mut next_wakeup_delay = None;
+ let mut outcome = FfiCompositorWakeupOutcome::default();
+ // SAFETY: Guaranteed by the caller, and the borrow ends before any sample is asked for.
+ let candidates = candidates_of(unsafe { &mut *animations }, None);
+ for (animation, effect) in candidates {
+ let state = animation.borrow().timing_state(Some(timestamp));
+ let Some(current_time) = state.current_time_at_timestamp.get() else {
+ continue;
+ };
+ if current_time.r#type != TimeValueType::Milliseconds {
+ continue;
+ }
+ let current_time = current_time.value;
+ let timing = state.effect;
+ let playback_rate = state.playback.playback_rate;
+ let (is_compositor_driven_or_replaced, is_offscreen_throttled) = {
+ let record = effect.borrow();
+ (
+ record.has_flag(EffectFlag::CompositorDriven) || record.has_flag(EffectFlag::CompositorReplaced),
+ record.has_flag(EffectFlag::OffscreenThrottled),
+ )
+ };
+ let is_compositor_handled = is_compositor_driven_or_replaced || has_retained_compositor_animations(&effect);
+ if !state.playback.has_pending_play_task
+ && !state.playback.has_pending_pause_task
+ && playback_rate > 0.0
+ && timing.start_delay.r#type == TimeValueType::Milliseconds
+ && state.phase == AnimationEffectPhase::Before
+ {
+ if current_time < timing.start_delay.value {
+ minimum(
+ &mut next_wakeup_delay,
+ (timing.start_delay.value - current_time) / playback_rate,
+ );
+ } else {
+ request_observation_sample(&effect);
+ outcome.reached_wakeup = true;
+ if is_compositor_handled {
+ outcome.reached_compositor_active_start = true;
+ }
+ }
+ }
+ if let Some(iteration_event_time) = next_throttled_animation_iteration_event_time(&state, &effect)
+ && !can_skip_per_frame_animation_tick(&effect)
+ {
+ if current_time < iteration_event_time {
+ minimum(
+ &mut next_wakeup_delay,
+ (iteration_event_time - current_time) / playback_rate,
+ );
+ } else {
+ outcome.reached_wakeup = true;
+ }
+ }
+ let is_offscreen_handled = is_offscreen_throttled && can_skip_per_frame_style_update(&effect);
+ if (!is_compositor_handled && !is_offscreen_handled) || timing.iteration_count.is_infinite() {
+ continue;
+ }
+ let active_end = timing.start_delay.value + timing.iteration_duration.value * timing.iteration_count;
+ if current_time < active_end {
+ minimum(&mut next_wakeup_delay, (active_end - current_time) / playback_rate);
+ continue;
+ }
+ request_observation_sample(&effect);
+ outcome.reached_wakeup = true;
+ }
+ if let Some(delay) = next_wakeup_delay {
+ outcome.has_next_wakeup_delay = true;
+ outcome.next_wakeup_delay = delay;
+ }
+ outcome
+}
+
+#[cfg(test)]
+mod ffi_test_stubs {
+ #[unsafe(no_mangle)]
+ extern "C" fn web_animation_set_needs_animated_style_update(
+ _effect: *const std::ffi::c_void,
+ _target: std::ptr::NonNull<std::ffi::c_void>,
+ ) {
+ unreachable!("the tests update no compositor animations")
+ }
+}
diff --git a/Libraries/LibWeb/Rust/src/animations/css_events.rs b/Libraries/LibWeb/Rust/src/animations/css_events.rs
index c4ed7b3865a..6129012c31d 100644
--- a/Libraries/LibWeb/Rust/src/animations/css_events.rs
+++ b/Libraries/LibWeb/Rust/src/animations/css_events.rs
@@ -7,8 +7,7 @@
//! The events of a CSS animation or a CSS transition that a new animation frame establishes, which the record decides
//! from the phases its animation and associated effect go through.
-use super::animation::{AnimationKind, AnimationRecord};
-use super::host_timing::FfiAnimationKind;
+use super::animation::{AnimationKind, AnimationRecord, TransitionPhase};
use super::timing::time_value::{max, min};
use super::timing::{self, AnimationEffectPhase, OptionalNumber, TimeValue, TimeValueType};
@@ -27,9 +26,8 @@ pub enum FfiCssEventType {
}
/// An event to dispatch, with its elapsed time in seconds.
-#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq)]
-pub struct FfiCssEvent {
+pub struct CssEvent {
pub r#type: FfiCssEventType,
pub elapsed_time: f64,
}
@@ -37,23 +35,19 @@ pub struct FfiCssEvent {
/// The events an animation frame establishes for an animation, in the order they are dispatched, and the time they
/// were scheduled at. A frame establishes at most three, the run, start and end events of a transition that went from
/// idle to after.
-#[repr(C)]
#[derive(Clone, Copy, Debug)]
-pub struct FfiCssEvents {
- /// What made the animation, which only has events where it is a CSS animation or a CSS transition.
- pub kind: FfiAnimationKind,
+pub struct CssEvents {
pub count: u8,
- pub events: [FfiCssEvent; 3],
+ pub events: [CssEvent; 3],
/// The origin-relative time of the current time of the timeline, where it has one.
pub scheduled_event_time: OptionalNumber,
}
-impl FfiCssEvents {
- fn new(kind: FfiAnimationKind) -> Self {
+impl CssEvents {
+ fn new() -> Self {
Self {
- kind,
count: 0,
- events: [FfiCssEvent {
+ events: [CssEvent {
r#type: FfiCssEventType::AnimationStart,
elapsed_time: 0.0,
}; 3],
@@ -67,39 +61,16 @@ impl FfiCssEvents {
// FIXME: The spec doesn't specify how to handle this case
TimeValueType::Percentage => 0.0,
};
- self.events[usize::from(self.count)] = FfiCssEvent { r#type, elapsed_time };
+ self.events[usize::from(self.count)] = CssEvent { r#type, elapsed_time };
self.count += 1;
}
- #[cfg(test)]
- fn as_slice(&self) -> &[FfiCssEvent] {
+ pub(crate) fn as_slice(&self) -> &[CssEvent] {
&self.events[..usize::from(self.count)]
}
}
-/// https://drafts.csswg.org/css-transitions-2/#transition-phase
-#[repr(u8)]
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-enum TransitionPhase {
- Before,
- Active,
- After,
- Idle,
- Pending,
-}
-
impl TransitionPhase {
- fn from_stored(phase: u8) -> Self {
- match phase {
- 0 => Self::Before,
- 1 => Self::Active,
- 2 => Self::After,
- 3 => Self::Idle,
- 4 => Self::Pending,
- _ => unreachable!("a stored transition phase"),
- }
- }
-
fn of_effect(phase: AnimationEffectPhase) -> Self {
match phase {
AnimationEffectPhase::Before => Self::Before,
@@ -121,8 +92,8 @@ enum Interval {
impl AnimationRecord {
/// The events of a CSS animation or a CSS transition that the animation frame just established, recording the
/// phases they were decided from for the next frame. Other animations have none.
- pub(crate) fn take_css_events(&mut self) -> FfiCssEvents {
- let mut events = FfiCssEvents::new(self.ffi_kind());
+ pub(crate) fn take_css_events(&mut self) -> CssEvents {
+ let mut events = CssEvents::new();
match self.kind() {
AnimationKind::CssTransition(_) => self.establish_transition_events(&mut events),
AnimationKind::CssAnimation(_) => self.establish_css_animation_events(&mut events),
@@ -139,21 +110,9 @@ impl AnimationRecord {
events
}
- /// A zero time in the unit of the times of the timeline of the animation.
- fn zero_time(&self) -> TimeValue {
- let progress_based = self
- .timeline()
- .is_some_and(|timeline| timeline.borrow().is_progress_based());
- TimeValue::zero(if progress_based {
- TimeValueType::Percentage
- } else {
- TimeValueType::Milliseconds
- })
- }
-
// https://drafts.csswg.org/css-transitions-2/#event-dispatch
- fn establish_transition_events(&mut self, events: &mut FfiCssEvents) {
- let previous_phase = TransitionPhase::from_stored(self.css_transition().previous_phase);
+ fn establish_transition_events(&mut self, events: &mut CssEvents) {
+ let previous_phase = self.css_transition().previous_phase;
let playback = *self.playback();
let timeline = self.timeline();
let current_time = timing::current_time_at(&playback, timeline.and_then(|timeline| timeline.current_time()));
@@ -247,11 +206,11 @@ impl AnimationRecord {
dispatch_event(TransitionCancel, Interval::ActiveTime);
}
- self.css_transition_mut().previous_phase = transition_phase as u8;
+ self.css_transition_mut().previous_phase = transition_phase;
}
// https://www.w3.org/TR/css-animations-2/#event-dispatch
- fn establish_css_animation_events(&mut self, events: &mut FfiCssEvents) {
+ fn establish_css_animation_events(&mut self, events: &mut CssEvents) {
// Each time a new animation frame is established and the animation does not have a pending play task or pending
// pause task, the events to dispatch are determined by comparing the animation’s phase before and after
// establishing the new animation frame as follows:
@@ -269,8 +228,8 @@ impl AnimationRecord {
let effect = effect.borrow();
(
effect.timing(),
- effect.previous_phase(),
- effect.previous_current_iteration(),
+ effect.previous_phase,
+ effect.previous_current_iteration,
)
};
let resolved = timing::resolve_timing(&effect_timing, current_time, Some(&playback), sample.as_ref());
@@ -331,14 +290,14 @@ impl AnimationRecord {
}
if current_phase == Idle && previous_phase != Idle && previous_phase != After {
- // FIXME: Calculate a non-zero time when the animation is cancelled by means other than calling cancel()
- let cancel_time = self.take_saved_cancel_time().unwrap_or(zero);
+ // FIXME: Calculate a non-zero time when the animation is canceled by means other than calling cancel()
+ let cancel_time = self.saved_cancel_time.take().unwrap_or(zero);
events.push(AnimationCancel, cancel_time);
}
let mut effect = effect.borrow_mut();
- effect.set_previous_phase(current_phase);
- effect.set_previous_current_iteration(current_iteration);
+ effect.previous_phase = current_phase;
+ effect.previous_current_iteration = current_iteration;
}
}
@@ -348,7 +307,7 @@ mod tests {
use core::ptr::NonNull;
use super::*;
- use crate::animations::animation::{AnimationHandle, CSS_TRANSITION_PHASE_IDLE, CssTransitionState, OwningElement};
+ use crate::animations::animation::{AnimationHandle, CssTransitionState, OwningElement, TransitionPhase};
use crate::animations::effect::EffectHandle;
use crate::css::retained_fly_string::RetainedUtf16FlyString;
use crate::css::style_value::RetainedStyleValueData;
@@ -376,7 +335,7 @@ mod tests {
reversing_adjusted_start_value: RetainedStyleValueData::none(),
reversing_shortening_factor: 1.0,
property_id: 1,
- previous_phase: CSS_TRANSITION_PHASE_IDLE,
+ previous_phase: TransitionPhase::Idle,
provisional: false,
adopted_from_lane: false,
effect_started_with: None,
@@ -390,15 +349,14 @@ mod tests {
animation
}
- fn event(r#type: FfiCssEventType, elapsed_time: f64) -> FfiCssEvent {
- FfiCssEvent { r#type, elapsed_time }
+ fn event(r#type: FfiCssEventType, elapsed_time: f64) -> CssEvent {
+ CssEvent { r#type, elapsed_time }
}
#[test]
fn a_transition_that_finished_within_a_frame_runs_starts_and_ends() {
let animation = transition_held_at(2000.0);
let events = animation.borrow_mut().take_css_events();
- assert_eq!(events.kind, FfiAnimationKind::CssTransition);
assert_eq!(
events.as_slice(),
[
@@ -438,12 +396,4 @@ mod tests {
}));
assert_eq!(animation.borrow_mut().take_css_events().count, 0);
}
-
- #[test]
- fn script_animations_have_no_events() {
- let animation = AnimationHandle::new(AnimationKind::Script);
- let events = animation.borrow_mut().take_css_events();
- assert_eq!(events.kind, FfiAnimationKind::Script);
- assert_eq!(events.count, 0);
- }
}
diff --git a/Libraries/LibWeb/Rust/src/animations/document_animations.rs b/Libraries/LibWeb/Rust/src/animations/document_animations.rs
index 1e79ece3cbe..c92103e01b0 100644
--- a/Libraries/LibWeb/Rust/src/animations/document_animations.rs
+++ b/Libraries/LibWeb/Rust/src/animations/document_animations.rs
@@ -6,11 +6,14 @@
//! What a document knows of the animations associated with it.
-use super::animation::WeakAnimationSet;
-use super::effect::WeakEffectSet;
+use super::animation::{AnimationCell, AnimationHandle, WeakAnimationSet};
+use super::effect::{AnimationEffectCell, EffectHandle, WeakEffectSet};
use super::pending_animation_events::PendingAnimationEvents;
+use super::provisional_transitions::ProvisionalTransitions;
+use super::timeline::TimelineHandle;
-/// The animations a document knows of, none of which it keeps alive.
+/// The animations a document knows of, none of which it keeps alive, and the timelines associated with it, which it
+/// does.
#[derive(Default)]
pub struct DocumentAnimations {
/// The animations associated with the elements of the document, those of its shadow trees included.
@@ -30,17 +33,20 @@ pub struct DocumentAnimations {
needing_animated_style_update_beside_flown_style_update: WeakEffectSet,
/// https://www.w3.org/TR/web-animations-1/#pending-animation-event-queue
pub(crate) pending_events: PendingAnimationEvents,
+ /// https://www.w3.org/TR/web-animations-1/#timeline-associated-with-a-document
+ /// In the order they were associated with the document.
+ pub(crate) timelines: Vec<TimelineHandle>,
+ /// https://www.w3.org/TR/web-animations-1/#document-default-document-timeline
+ pub(crate) default_timeline: Option<TimelineHandle>,
+ /// The transition actions the outermost style stabilization epoch decided, which it commits as it ends.
+ pub(crate) provisional_transitions: ProvisionalTransitions,
}
/// One of the sets of animations a document knows of.
-#[expect(dead_code, reason = "C++ constructs the variants")]
-#[repr(u8)]
#[derive(Clone, Copy)]
pub enum DocumentAnimationSetKind {
/// The animations associated with the elements of the document.
Associated,
- /// The animations associated with the document during the current style stabilization epoch.
- CreatedInStabilizationEpoch,
/// The CSS animations of the elements of the document that follow a named timeline.
FollowingNamedTimelines,
}
@@ -83,26 +89,84 @@ impl DocumentAnimations {
self.created_in_stabilization_epoch.entry_count() == 0,
"no animations are created in a style stabilization epoch before it begins"
);
+ assert!(
+ self.provisional_transitions.is_empty(),
+ "no transition actions are provisional outside a style stabilization epoch"
+ );
}
/// Commits the events queued during the outermost style stabilization epoch to the pending animation event queue,
/// as the epoch commits, and forgets which animations it created, answering how many events it committed.
pub(crate) fn commit_provisional_events(&mut self) -> usize {
let created_in_epoch = &self.created_in_stabilization_epoch;
- // An animation created and cancelled inside this epoch was never part of an externally committed style. Its
+ // An animation created and canceled inside this epoch was never part of an externally committed style. Its
// cancellation is provisional too, so no observer may receive it.
let committed = self.pending_events.commit_provisional_events(|animation| {
created_in_epoch.contains(animation)
- && animation.borrow().timing_state(None).play_state == super::timing::AnimationPlayState::Idle
+ && animation.borrow().play_state() == super::timing::AnimationPlayState::Idle
});
self.created_in_stabilization_epoch.clear();
committed
}
+ /// Associates `animation` with the document, as one created during its style stabilization epoch where
+ /// `in_style_stabilization_epoch`.
+ pub(crate) fn associate(&mut self, animation: &AnimationHandle, in_style_stabilization_epoch: bool) {
+ self.associated.insert(animation);
+ if in_style_stabilization_epoch {
+ self.created_in_stabilization_epoch.insert(animation);
+ }
+ }
+
+ /// Disassociates `animation` from the document, whose associated effect `effect` was, which no animated style
+ /// update of the document samples anymore.
+ pub(crate) fn disassociate(&mut self, animation: &AnimationCell, effect: Option<&AnimationEffectCell>) {
+ if let Some(effect) = effect {
+ self.needing_animated_style_update.remove(effect);
+ self.needing_animated_style_update_after_current_update.remove(effect);
+ self.needing_animated_style_update_beside_flown_style_update
+ .remove(effect);
+ }
+ self.associated.remove(animation);
+ }
+
+ /// The animations associated with the elements of the document that are alive.
+ pub(crate) fn associated_animations(&mut self) -> Vec<AnimationHandle> {
+ self.associated.alive()
+ }
+
+ /// The effects whose animated style the next animated style update samples.
+ pub(crate) fn needing_animated_style_update(&mut self) -> &mut WeakEffectSet {
+ &mut self.needing_animated_style_update
+ }
+
+ /// The effects asked for an observation sample while an animated style update ran.
+ pub(crate) fn needing_animated_style_update_after_current_update(&mut self) -> &mut WeakEffectSet {
+ &mut self.needing_animated_style_update_after_current_update
+ }
+
+ /// Sets aside the effects the next animated style update samples while the transaction of a style update that
+ /// flew drains, or restores those set aside, where `restore`.
+ pub(crate) fn set_aside_effects_needing_animated_style_update(&mut self, restore: bool) {
+ let (from, to) = if restore {
+ (
+ &mut self.needing_animated_style_update_beside_flown_style_update,
+ &mut self.needing_animated_style_update,
+ )
+ } else {
+ (
+ &mut self.needing_animated_style_update,
+ &mut self.needing_animated_style_update_beside_flown_style_update,
+ )
+ };
+ from.take_each(|effect: &EffectHandle| {
+ to.insert(effect);
+ });
+ }
+
pub(crate) fn set_mut(&mut self, kind: DocumentAnimationSetKind) -> &mut WeakAnimationSet {
match kind {
DocumentAnimationSetKind::Associated => &mut self.associated,
- DocumentAnimationSetKind::CreatedInStabilizationEpoch => &mut self.created_in_stabilization_epoch,
DocumentAnimationSetKind::FollowingNamedTimelines => &mut self.following_named_timelines,
}
}
diff --git a/Libraries/LibWeb/Rust/src/animations/effect.rs b/Libraries/LibWeb/Rust/src/animations/effect.rs
index 74dde96f271..53482989de8 100644
--- a/Libraries/LibWeb/Rust/src/animations/effect.rs
+++ b/Libraries/LibWeb/Rust/src/animations/effect.rs
@@ -7,11 +7,11 @@
//! Animation effects.
//! https://www.w3.org/TR/web-animations-1/#animation-effects
-use super::animation::{AnimationHandle, WeakAnimationHandle};
+use super::animation::{AnimationCell, AnimationHandle, WeakAnimationHandle};
use super::easing::CompactEasing;
use super::keyframes::{KeyframeOrigin, KeyframeSet};
use super::timeline_state::{TimelineState, time_unit};
-use super::timing::{self, AnimationEffectPhase, AnimationEffectTiming, SpecifiedEffectTiming, TimeValue};
+use super::timing::{self, AnimationEffectPhase, AnimationEffectTiming, FillMode, SpecifiedEffectTiming, TimeValue};
use super::weak_record_set::WeakRecordSet;
use crate::css::animation::FfiCompositeOperation;
use crate::css::retained_fly_string::RetainedUtf16FlyString;
@@ -37,7 +37,6 @@ impl AnimationEffectId {
}
/// What the host notes of an effect as it runs it on the compositor, throttles it, or samples it for script, by bit.
-#[expect(dead_code, reason = "C++ constructs the variants")]
#[repr(u8)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum EffectFlag {
@@ -100,7 +99,6 @@ impl RememberedPerFrameStyleUpdateSkipDecision {
}
/// What an effect remembers of whether a frame can skip its style update, for a key.
-#[repr(u8)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PerFrameStyleUpdateSkipDecision {
/// The effect remembers no decision.
@@ -115,7 +113,6 @@ pub enum PerFrameStyleUpdateSkipDecision {
/// What became of a request that the next style update take an observation sample of an effect, at most once in a
/// task.
-#[repr(u8)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ObservationSampleRequest {
/// The effect was already asked for a sample in the task.
@@ -127,8 +124,6 @@ pub enum ObservationSampleRequest {
}
/// How to reach the compositor animations of an effect.
-#[expect(dead_code, reason = "C++ constructs the variants")]
-#[repr(u8)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CompositorAnimationStateAccess {
/// Only where the effect built any before.
@@ -172,11 +167,11 @@ pub(crate) struct AnimationEffectRecord {
/// https://www.w3.org/TR/web-animations-1/#dom-keyframeeffect-pseudoelement
pseudo_element_serialization: RetainedUtf16FlyString,
/// The current iteration the effect was at when the host last dispatched its style events.
- previous_current_iteration: f64,
+ pub(crate) previous_current_iteration: f64,
/// The host's `PseudoElement` of the target pseudo-selector.
pseudo_element_kind: u8,
/// The phase the effect was in when the host last dispatched its style events.
- previous_phase: AnimationEffectPhase,
+ pub(crate) previous_phase: AnimationEffectPhase,
/// The `EffectFlag`s set.
flags: u8,
/// Whether script replaced keyframes the effect took from CSS, after which it takes no more from CSS.
@@ -394,24 +389,6 @@ impl AnimationEffectRecord {
self.describe_anew();
}
- #[must_use]
- pub(crate) fn previous_phase(&self) -> AnimationEffectPhase {
- self.previous_phase
- }
-
- #[must_use]
- pub(crate) fn previous_current_iteration(&self) -> f64 {
- self.previous_current_iteration
- }
-
- pub(crate) fn set_previous_phase(&mut self, phase: AnimationEffectPhase) {
- self.previous_phase = phase;
- }
-
- pub(crate) fn set_previous_current_iteration(&mut self, current_iteration: f64) {
- self.previous_current_iteration = current_iteration;
- }
-
#[must_use]
pub(crate) fn has_flag(&self, flag: EffectFlag) -> bool {
self.flags & flag as u8 != 0
@@ -508,7 +485,7 @@ pub struct AnimationEffectCell {
record: RefCell<AnimationEffectRecord>,
/// The host's `AnimationEffect`, which holds a reference to the record until it is finalized and clears this as it
/// does.
- facade: Cell<Option<NonNull<c_void>>>,
+ object_cell: Cell<Option<NonNull<c_void>>>,
}
impl AnimationEffectCell {
@@ -521,18 +498,18 @@ impl AnimationEffectCell {
}
/// The host's `AnimationEffect` of the effect, while it is alive.
- pub(crate) fn facade(&self) -> Option<NonNull<c_void>> {
- self.facade.get()
+ pub(crate) fn object_cell(&self) -> Option<NonNull<c_void>> {
+ self.object_cell.get()
}
- pub(crate) fn set_facade(&self, facade: Option<NonNull<c_void>>) {
- self.facade.set(facade);
+ pub(crate) fn set_object_cell(&self, object_cell: Option<NonNull<c_void>>) {
+ self.object_cell.set(object_cell);
}
/// Whether the host may reach the effect and the element it targets: while the object script sees of it is, or,
/// for an effect without one, while its associated animation is.
pub(crate) fn is_alive(&self) -> bool {
- if self.facade().is_some() {
+ if self.object_cell().is_some() {
return true;
}
let animation = self.borrow().associated_animation();
@@ -555,7 +532,7 @@ impl EffectHandle {
pub(crate) fn new() -> Self {
Self(Rc::new(AnimationEffectCell {
record: RefCell::new(AnimationEffectRecord::new()),
- facade: Cell::new(None),
+ object_cell: Cell::new(None),
}))
}
@@ -647,3 +624,44 @@ impl std::ops::Deref for EffectHandle {
&self.0
}
}
+
+/// The timing of an effect at one local time, and what follows from its timing alone.
+pub struct EffectTimingAtLocalTime {
+ pub phase: AnimationEffectPhase,
+ pub current_iteration: Option<f64>,
+ /// Unresolved where it was not asked for.
+ pub transformed_progress: Option<f64>,
+ pub active_duration: TimeValue,
+ pub end_time: TimeValue,
+}
+
+/// The timing of `effect` at `local_time` with `fill_mode` as its fill mode, associated with `animation`, if any, on
+/// its timeline, if it has one, and with its transformed progress through its timing function where
+/// `with_transformed_progress`.
+pub(crate) fn resolve_effect_timing(
+ effect: &AnimationEffectCell,
+ local_time: Option<TimeValue>,
+ fill_mode: FillMode,
+ animation: Option<&AnimationCell>,
+ with_transformed_progress: bool,
+) -> EffectTimingAtLocalTime {
+ let timeline = animation.and_then(|animation| animation.borrow().timeline().map(|timeline| timeline.sample()));
+ let timeline = timeline.as_ref();
+ let animation = animation.map(|animation| *animation.borrow().playback());
+ let effect = effect.borrow();
+ let timing = AnimationEffectTiming {
+ fill_mode,
+ ..effect.timing()
+ };
+ let resolved = timing::resolve_timing(&timing, local_time, animation.as_ref(), timeline);
+ let transformed_progress = with_transformed_progress
+ .then(|| timing::transformed_progress(&timing, &resolved, effect.timing_function().as_easing()))
+ .flatten();
+ EffectTimingAtLocalTime {
+ phase: resolved.phase,
+ current_iteration: timing::current_iteration(&timing, &resolved),
+ transformed_progress,
+ active_duration: timing::active_duration(&timing),
+ end_time: timing::end_time(&timing),
+ }
+}
diff --git a/Libraries/LibWeb/Rust/src/animations/element_animations.rs b/Libraries/LibWeb/Rust/src/animations/element_animations.rs
index f63f8d13d4b..2f2e24bdad7 100644
--- a/Libraries/LibWeb/Rust/src/animations/element_animations.rs
+++ b/Libraries/LibWeb/Rust/src/animations/element_animations.rs
@@ -41,14 +41,14 @@ pub(crate) struct StyleEngineTarget<'a> {
/// The property a CSS transition runs: the host's `PropertyID` of a longhand, or the raw fly string of a custom
/// property's name where it is not zero.
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub(crate) struct TransitionProperty {
pub(crate) property_id: u16,
pub(crate) custom_name: usize,
}
impl TransitionProperty {
- fn of(animation: &AnimationRecord) -> Self {
+ pub(crate) fn of(animation: &AnimationRecord) -> Self {
let state = animation.css_transition();
Self {
property_id: state.property_id,
@@ -84,14 +84,26 @@ pub struct ElementAnimations {
owners: SmallVec<[OwnedAnimations; 1]>,
/// Whether `associated` is in composite order.
is_sorted_by_composite_order: bool,
- /// Whether any owner has had a CSS animation since the element last cancelled them all.
+ /// Whether any owner has had a CSS animation since the element last canceled them all.
has_css_defined_animations: bool,
}
impl Drop for ElementAnimations {
fn drop(&mut self) {
+ // NB: The element is finalized, and what else holds the records of its animations may only let go of them as
+ // the host sweeps it, after the element itself may be gone. So that no record names the element by then,
+ // nor is alive to the sets of animations by it, the records forget it here.
for animation in &self.associated {
animation.note_smil_holder(SmilHolder::TargetList, false);
+ let effect = animation.borrow().effect().cloned();
+ if let Some(effect) = effect {
+ effect.borrow_mut().set_target_element(None);
+ }
+ }
+ for owner in &self.owners {
+ for animation in owner.css_animations.iter().chain(&owner.transitions) {
+ animation.borrow_mut().set_owning_element(None);
+ }
}
}
}
@@ -261,7 +273,7 @@ impl ElementAnimations {
.expect("the owner has a transition of the property");
let transition = owner.transitions.remove(index);
self.remove_empty_owners();
- transition.borrow_mut().set_disassociation_from_target_pending(true);
+ transition.borrow_mut().disassociation_from_target_pending = true;
}
/// Takes the CSS animations and transitions of every owner, answering them, and publishes to `engine`, if any, that
@@ -367,53 +379,3 @@ fn publish_css_defined_animations(
.collect(),
}));
}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use crate::animations::animation::AnimationKind;
-
- fn by_address(first: NonNull<c_void>, second: NonNull<c_void>) -> Ordering {
- first.cmp(&second)
- }
-
- #[test]
- fn an_animation_is_associated_once() {
- let mut animations = ElementAnimations::default();
- let animation = AnimationHandle::new(AnimationKind::Script);
- assert!(animations.associate(animation.clone()));
- assert!(!animations.associate(animation.clone()));
- assert_eq!(animations.associated().len(), 1);
- assert!(animations.disassociate(&animation));
- assert!(!animations.disassociate(&animation));
- assert!(animations.associated().is_empty());
- }
-
- #[test]
- fn animations_without_an_effect_sort_first_in_creation_order() {
- let mut animations = ElementAnimations::default();
- let first = AnimationHandle::new(AnimationKind::Script);
- let second = AnimationHandle::new(AnimationKind::Script);
- animations.associate(second.clone());
- animations.associate(first.clone());
- animations.sort_in_composite_order(&mut by_address);
- assert!(animations.associated()[0].ptr_eq(&first));
- assert!(animations.associated()[1].ptr_eq(&second));
- }
-
- #[test]
- fn cancelling_css_animations_clears_what_the_element_had() {
- let mut animations = ElementAnimations::default();
- let slot = AnimationOwnerSlot(3);
- // SAFETY: The test takes over the one reference to the new animation.
- let animation = unsafe { AnimationHandle::from_raw(super::super::ffi::animations_css_animation_create()) };
- animations.set_css_animations(slot, [animation].into_iter(), None);
- assert_eq!(animations.css_animations(slot).len(), 1);
- assert!(animations.css_animations(AnimationOwnerSlot(0)).is_empty());
- animations.set_css_animations(slot, std::iter::empty(), None);
- assert!(animations.css_animations(slot).is_empty());
- assert!(animations.has_css_animations_or_transitions());
- assert!(animations.take_css_animations_and_transitions(None).is_empty());
- assert!(!animations.has_css_animations_or_transitions());
- }
-}
diff --git a/Libraries/LibWeb/Rust/src/animations/ffi.rs b/Libraries/LibWeb/Rust/src/animations/ffi.rs
index 6dcc891d3e2..234500f64fa 100644
--- a/Libraries/LibWeb/Rust/src/animations/ffi.rs
+++ b/Libraries/LibWeb/Rust/src/animations/ffi.rs
@@ -4,170 +4,53 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-//! The C ABI through which the C++ animation classes reach the timing model, until they move to Rust.
+//! The C ABI through which LibWeb's C++ (the DOM, style computation, SVG and the event loop) reaches the animation
+//! records, and the host functions the records call back into.
use super::animation::{
AnimationCell, AnimationHandle, AnimationKind, AttachmentRangeEdge, AttachmentRangeEdgeOffset,
- CSS_ANIMATION_PLAY_STATE_PAUSED, CSS_ANIMATION_PLAY_STATE_RUNNING, CSS_TRANSITION_PHASE_IDLE, CssAnimationFlag,
- CssAnimationState, CssTransitionState, HostCellKind, HostTaskId, OwningElement, SmilHolder, WeakAnimationSet,
+ CSS_ANIMATION_PLAY_STATE_PAUSED, CSS_ANIMATION_PLAY_STATE_RUNNING, CssAnimationFlag, CssAnimationState,
+ CssTransitionState, HostCellKind, HostTaskId, OwningElement, SmilHolder, TransitionPhase, WeakAnimationSet,
};
use super::clock_plan::ClockPlanAnimation;
use super::composite_order::composite_order;
use super::document_animations::{DocumentAnimationSetKind, DocumentAnimations, DocumentEffectSetKind};
use super::easing::CompactEasing;
-use super::effect::{
- AnimationEffectCell, AnimationEffectId, CompositorAnimationStateAccess, EffectFlag, EffectHandle,
- ObservationSampleRequest, PerFrameStyleUpdateSkipDecision, PerFrameStyleUpdateSkipKey,
-};
+use super::effect::{AnimationEffectCell, AnimationEffectId, EffectFlag, EffectHandle, resolve_effect_timing};
use super::element_animations::{AnimationOwnerSlot, ElementAnimations, StyleEngineTarget, TransitionProperty};
use super::host_effects::{HostEffectKind, HostEffects, PlaybackEventType};
-use super::host_timing::{FfiAnimationKind, FfiAnimationTimingState};
+use super::host_timing::FfiAnimationKind;
use super::keyframes::{
- CompositeOperationOrAuto, KeyframeOrigin, KeyframeProperty, KeyframeSet, KeyframeValue, ProcessedKeyframe,
- ResourceContext,
+ CompositeOperationOrAuto, KeyframeProperty, KeyframeSet, ProcessedKeyframe, ResourceContext, key_of_offset,
};
use super::pending_animation_events::{
FfiPendingAnimationEvent, PendingAnimationEvent, PendingAnimationEventKind, TimeEventType,
};
use super::procedures::{self, AnimationError, DidSeek, Invalidate, Procedures, SynchronouslyNotify};
-use super::snapshot::TimelineClock;
+use super::provisional_transitions::TransitionTarget;
+use super::rendering_trace::note_rendering_trace_event;
use super::timeline::{
- AnimationTimelineId, ScrollNodeStableId, ScrollTimelineBoxes, ScrollTimelineSource, ScrollTimelineState,
- TimelineCell, TimelineHandle, TimelineKind, TimelineUpdate, ViewTimelineInset, ViewTimelineInsetEdge,
- ViewTimelineState,
-};
-use super::timing::{
- self, AnimationEffectPhase, AnimationEffectTiming, AnimationPlayState, AnimationPlayback, FillMode, OptionalNumber,
- OptionalTimeValue, SpecifiedEffectTiming, TimeValue, TimelineSample,
+ ScrollTimelineSource, ScrollTimelineState, TimelineCell, TimelineHandle, TimelineKind, ViewTimelineInset,
+ ViewTimelineInsetEdge, ViewTimelineState,
};
+use super::timeline_host::{create_timeline, default_document_timeline};
+use super::timing::{AnimationPlayState, OptionalTimeValue, SpecifiedEffectTiming, TimeValue};
use super::transitions::{self, LaneAdoption, ProvisionalTransitionTiming, TransitionOrigin};
use crate::css::animation::FfiCompositeOperation;
use crate::css::retained_fly_string::RetainedUtf16FlyString;
use crate::css::style::animations::AppliedAnimationDefinition;
use crate::css::style::tree::StyleNodeID;
use crate::css::style_value::{RetainedStyleValueData, StyleValueData, retain_style_value};
-use crate::css::transition::{FfiExistingTransition, FfiLaneTransition};
-use crate::layout::node_data::NodeSlotId;
-use crate::painting::visual_animation_builder::CompositorAnimationEffectState;
-use crate::render_state::{BegunRead, DocumentHost};
-use libcompositing_rust::easing::{Easing, FfiEasingDescriptor, evaluate_easing_descriptor};
+use crate::css::transition::{FfiExistingTransition, FfiLaneTransition, FfiTransitionAction, FfiTransitionActionKind};
+use crate::render_state::DocumentHost;
+use libcompositing_rust::easing::{Easing, FfiEasingDescriptor};
+use smallvec::SmallVec;
use std::cmp::Ordering;
use std::ffi::c_void;
use std::num::NonZeroU64;
use std::ptr::NonNull;
use std::sync::Arc;
-/// The timing of an effect at one local time, and what follows from its timing alone.
-#[repr(C)]
-pub struct FfiResolvedEffectTiming {
- pub phase: AnimationEffectPhase,
- pub local_time: OptionalTimeValue,
- pub active_time: OptionalTimeValue,
- pub overall_progress: OptionalNumber,
- pub current_iteration: OptionalNumber,
- /// Unresolved where it was not asked for.
- pub transformed_progress: OptionalNumber,
- pub is_current: bool,
- pub is_in_effect: bool,
- pub active_duration: TimeValue,
- pub end_time: TimeValue,
- pub before_active_boundary_time: TimeValue,
- pub after_active_boundary_time: TimeValue,
-}
-
-/// The timing of `effect` at `local_time` with `fill_mode` as its fill mode, associated with `animation`, if any, on
-/// its timeline, if it has one, and with its transformed progress through its timing function where
-/// `with_transformed_progress`.
-#[unsafe(no_mangle)]
-pub extern "C" fn animations_effect_resolve_timing(
- effect: &AnimationEffectCell,
- local_time: OptionalTimeValue,
- fill_mode: FillMode,
- animation: Option<&AnimationCell>,
- with_transformed_progress: bool,
-) -> FfiResolvedEffectTiming {
- let timeline = animation.and_then(timeline_sample_of);
- let timeline = timeline.as_ref();
- let animation = animation.map(|animation| *animation.borrow().playback());
- let animation = animation.as_ref();
- let effect = effect.borrow();
- let timing = AnimationEffectTiming {
- fill_mode,
- ..effect.timing()
- };
- let resolved = timing::resolve_timing(&timing, local_time.get(), animation, timeline);
- let transformed_progress = with_transformed_progress
- .then(|| {
- let timing_function = effect.timing_function().descriptor();
- timing::transformed_progress_with(&timing, &resolved, |input_progress, before_flag| {
- evaluate_easing_descriptor(&timing_function, input_progress, before_flag)
- })
- })
- .flatten();
- FfiResolvedEffectTiming {
- phase: resolved.phase,
- local_time: resolved.local_time.into(),
- active_time: resolved.active_time.into(),
- overall_progress: resolved.overall_progress.into(),
- current_iteration: timing::current_iteration(&timing, &resolved).into(),
- transformed_progress: transformed_progress.into(),
- is_current: timing::is_current(&timing, resolved.phase, animation, timeline),
- is_in_effect: timing::is_in_effect(&resolved),
- active_duration: timing::active_duration(&timing),
- end_time: timing::end_time(&timing),
- before_active_boundary_time: timing::before_active_boundary_time(&timing),
- after_active_boundary_time: timing::after_active_boundary_time(&timing),
- }
-}
-
-/// What the timing model reads of the timeline of `animation` now, if it has one.
-fn timeline_sample_of(animation: &AnimationCell) -> Option<TimelineSample> {
- animation.borrow().timeline().map(|timeline| timeline.sample())
-}
-
-/// Whether `animation`, on its timeline, if it has one, is relevant, with its associated effect, if any, at the local
-/// time `local_time`.
-#[unsafe(no_mangle)]
-pub extern "C" fn animations_is_relevant(animation: &AnimationCell, local_time: OptionalTimeValue) -> bool {
- let timeline = timeline_sample_of(animation);
- let timeline = timeline.as_ref();
- let animation = animation.borrow();
- let effect_timing = animation.effect().map(|effect| effect.borrow().timing());
- timing::is_relevant(animation.playback(), timeline, effect_timing.as_ref(), local_time.get())
-}
-
-/// What a procedure threw, as the host throws it: nothing, an "InvalidStateError" DOMException, or a TypeError, with
-/// its message.
-#[repr(C)]
-pub struct FfiAnimationError {
- pub kind: FfiAnimationErrorKind,
- pub message: *const u8,
- pub message_length: usize,
-}
-
-#[repr(u8)]
-#[derive(Clone, Copy, PartialEq, Eq)]
-pub enum FfiAnimationErrorKind {
- None,
- InvalidState,
- TypeError,
-}
-
-impl From<Result<(), AnimationError>> for FfiAnimationError {
- fn from(result: Result<(), AnimationError>) -> Self {
- let (kind, message) = match result {
- Ok(()) => (FfiAnimationErrorKind::None, ""),
- Err(AnimationError::InvalidState(message)) => (FfiAnimationErrorKind::InvalidState, message),
- Err(AnimationError::TypeError(message)) => (FfiAnimationErrorKind::TypeError, message),
- };
- Self {
- kind,
- message: message.as_ptr(),
- message_length: message.len(),
- }
- }
-}
-
/// One thing a procedure asks the host to do for the animation `animation`, and what it needs to do it.
#[repr(C)]
pub struct FfiHostEffect {
@@ -292,14 +175,18 @@ impl FfiHostEffect {
/// The host's function that performs what a procedure asks of it.
pub type HostEffectPerformer = extern "C" fn(effect: &FfiHostEffect);
-/// Runs `procedure` on `animation` and then has the host perform what it asked for through `perform`, in order, holding
-/// no borrow of any record.
-fn run_procedure(
+/// Runs `procedure`, which does not throw, on `animation` and then has the host perform what it asked for through
+/// `perform`, in order, holding no borrow of any record.
+pub(crate) fn run_procedure(
animation: &AnimationCell,
perform: HostEffectPerformer,
- procedure: impl FnOnce(&mut Procedures<'_>) -> Result<(), AnimationError>,
-) -> FfiAnimationError {
- run_procedure_on(animation, perform, procedure).into()
+ procedure: impl FnOnce(&mut Procedures<'_>),
+) {
+ run_procedure_on(animation, perform, |procedures| {
+ procedure(procedures);
+ Ok(())
+ })
+ .expect("the procedure does not throw");
}
/// Runs `procedure` on `animation` and then has the host perform what it asked for through `perform`, in order, holding
@@ -325,13 +212,17 @@ fn perform_host_effects(effects: HostEffects, perform: HostEffectPerformer) {
continue;
}
// NB: The record keeps the task the host queued, which the host then neither queues again nor cancels without.
- let task = animation.borrow().finish_notification_task();
+ let task = animation.borrow().finish_notification_task;
match kind {
HostEffectKind::QueueFinishNotificationTask if task.is_some() => continue,
HostEffectKind::CancelFinishNotificationTask if task.is_none() => continue,
_ => {}
}
perform(&FfiHostEffect::new(&animation, &kind, task));
+ // NB: A canceled task is no longer queued, so a later finish notification task can be queued again.
+ if matches!(kind, HostEffectKind::CancelFinishNotificationTask) {
+ animation.borrow_mut().finish_notification_task = None;
+ }
}
}
@@ -340,7 +231,7 @@ fn perform_host_effects(effects: HostEffects, perform: HostEffectPerformer) {
#[unsafe(no_mangle)]
pub extern "C" fn animations_animation_set_finish_notification_task(animation: &AnimationCell, task: u64) {
let task = HostTaskId(NonZeroU64::new(task).expect("the host's tasks have nonzero identities"));
- animation.borrow_mut().set_finish_notification_task(task);
+ animation.borrow_mut().finish_notification_task = Some(task);
}
pub(crate) fn invalidate(invalidate: bool) -> Invalidate {
@@ -353,10 +244,7 @@ pub extern "C" fn animations_animation_run_finish_notification_steps(
animation: &AnimationCell,
perform: HostEffectPerformer,
) {
- run_procedure(animation, perform, |procedures| {
- procedures.finish_notification_steps();
- Ok(())
- });
+ run_procedure(animation, perform, |procedures| procedures.finish_notification_steps());
}
/// https://www.w3.org/TR/web-animations-1/#dom-animation-cancel
@@ -368,78 +256,6 @@ pub extern "C" fn animations_animation_cancel(
) {
run_procedure(animation, perform, |procedures| {
procedures.cancel(invalidate(should_invalidate));
- Ok(())
- });
-}
-
-/// https://www.w3.org/TR/web-animations-1/#dom-animation-finish
-#[unsafe(no_mangle)]
-pub extern "C" fn animations_animation_finish(
- animation: &AnimationCell,
- perform: HostEffectPerformer,
-) -> FfiAnimationError {
- run_procedure(animation, perform, |procedures| procedures.finish_an_animation())
-}
-
-/// https://www.w3.org/TR/web-animations-1/#dom-animation-starttime
-/// To the validated `start_time`.
-#[unsafe(no_mangle)]
-pub extern "C" fn animations_animation_set_start_time(
- animation: &AnimationCell,
- start_time: OptionalTimeValue,
- perform: HostEffectPerformer,
-) {
- run_procedure(animation, perform, |procedures| {
- procedures.set_start_time_for_bindings(start_time.get());
- Ok(())
- });
-}
-
-/// https://www.w3.org/TR/web-animations-1/#animation-set-the-timeline-of-an-animation
-/// Of `animation` to `timeline`, or to none where it is null.
-#[unsafe(no_mangle)]
-pub extern "C" fn animations_animation_set_timeline(
- animation: &AnimationCell,
- timeline: Option<&TimelineCell>,
- perform: HostEffectPerformer,
-) {
- // SAFETY: The host holds a reference to the timeline it passes.
- let timeline = timeline.map(|timeline| unsafe { TimelineHandle::retained_from_host(timeline) });
- run_procedure(animation, perform, |procedures| {
- procedures.set_timeline(timeline);
- Ok(())
- });
-}
-
-/// The host's timeline of `animation`, or null where it has none.
-/// https://www.w3.org/TR/web-animations-1/#animation-timeline
-#[unsafe(no_mangle)]
-pub extern "C" fn animations_animation_timeline(animation: &AnimationCell) -> *mut c_void {
- animation
- .borrow()
- .timeline()
- .and_then(|timeline| timeline.facade())
- .map_or(std::ptr::null_mut(), NonNull::as_ptr)
-}
-
-/// Updates `animation` as its timeline updated its current time.
-#[unsafe(no_mangle)]
-pub extern "C" fn animations_animation_update(animation: &AnimationCell, perform: HostEffectPerformer) {
- run_procedure(animation, perform, |procedures| {
- procedures.update();
- Ok(())
- });
-}
-
-/// Runs the pending play task of `animation` where it has one and is ready.
-#[unsafe(no_mangle)]
-pub extern "C" fn animations_animation_run_pending_play_task_if_ready(
- animation: &AnimationCell,
- perform: HostEffectPerformer,
-) {
- run_procedure(animation, perform, |procedures| {
- procedures.run_pending_play_task_if_ready();
- Ok(())
});
}
@@ -505,12 +321,12 @@ pub unsafe extern "C" fn animations_keyframe_set_from_keyframes_rule(
))
}
-/// One keyframe script gave a `KeyframeEffect`, as processing the keyframes argument made it: its computed offset,
-/// scaled to a key, its composite operation, its easing where it has one, and the range of the properties it
+/// One keyframe script gave a `KeyframeEffect`, as processing the keyframes argument made it: its computed offset, its
+/// composite operation, its easing where it has one, and the range of the properties it
/// declares.
#[repr(C)]
pub struct FfiProcessedKeyframe {
- pub key: u64,
+ pub offset: f64,
pub composite: CompositeOperationOrAuto,
pub has_easing: bool,
pub easing: FfiEasingDescriptor,
@@ -573,7 +389,7 @@ pub unsafe extern "C" fn animations_keyframe_set_from_processed_keyframes(
.map(|keyframe| {
let first = keyframe.first_property as usize;
ProcessedKeyframe {
- key: keyframe.key,
+ key: key_of_offset(keyframe.offset),
composite: keyframe.composite,
// SAFETY: Guaranteed by the caller.
easing: keyframe
@@ -595,92 +411,16 @@ pub unsafe extern "C" fn animations_keyframe_set_from_processed_keyframes(
into_host(KeyframeSet::from_processed_keyframes(keyframes, None))
}
-/// The keyframe set of a CSS transition of the property `property_id`, or of the custom property whose name is the
-/// raw fly string `custom_name` where that is not zero, from `start` to `end`, computed at the effective zoom
-/// `computed_value_zoom`, with the reference to it the host takes over.
-///
-/// # Safety
-/// `custom_name` must be zero or a live raw fly string, and `start` and `end` live style values.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn animations_keyframe_set_for_transition(
- property_id: u16,
- custom_name: usize,
- start: *const c_void,
- end: *const c_void,
- computed_value_zoom: f32,
-) -> *const KeyframeSet {
- // SAFETY: Guaranteed by the caller.
- unsafe {
- into_host(KeyframeSet::for_transition(
- keyframe_property(property_id, custom_name),
- retained_value(start),
- retained_value(end),
- computed_value_zoom,
- ))
- }
-}
-
-/// What a keyframe declares for a property, as the host reads it.
-#[repr(u8)]
-#[derive(Clone, Copy)]
-pub enum FfiKeyframeValueState {
- Absent,
- /// The element's own value, which a generated initial or final keyframe holds.
- ElementValue,
- Declared,
-}
-
-/// What a keyframe declares for a property, with the value it declares, borrowed from the set, where it declares one.
-#[repr(C)]
-pub struct FfiKeyframeValue {
- pub state: FfiKeyframeValueState,
- pub value: *const c_void,
-}
-
-/// What the keyframe of a set at `index` declares for the property `property_id`.
-///
-/// # Safety
-/// `set` must be a keyframe set the host holds a reference to, and `index` one of its keyframes.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn animations_keyframe_set_value(
- set: *const KeyframeSet,
- index: usize,
- property_id: u16,
-) -> FfiKeyframeValue {
- // SAFETY: Guaranteed by the caller.
- let set = unsafe { borrowed_keyframe_set(set) };
- let declaration = set
- .declarations_of(&set.keyframes()[index])
- .iter()
- .find(|declaration| declaration.property_id == property_id);
- match declaration.map(|declaration| &declaration.value) {
- None => FfiKeyframeValue {
- state: FfiKeyframeValueState::Absent,
- value: std::ptr::null(),
- },
- Some(KeyframeValue::ElementValue) => FfiKeyframeValue {
- state: FfiKeyframeValueState::ElementValue,
- value: std::ptr::null(),
- },
- Some(KeyframeValue::Declared(value)) => FfiKeyframeValue {
- state: FfiKeyframeValueState::Declared,
- value: value.pointer().cast(),
- },
- }
-}
-
-/// What follows from a set's keyframes alone, borrowed from the set: how many there are, the longhands they animate,
-/// sorted, the raw fly strings of the names of the custom properties they animate, and what the set answers of them.
+/// What follows from a set's keyframes alone, borrowed from the set: the longhands they animate, sorted, the raw fly
+/// strings of the names of the custom properties they animate, and what the set answers of them.
#[repr(C)]
pub struct FfiKeyframeSetFacts {
- pub keyframe_count: usize,
pub target_properties: *const u16,
pub target_property_count: usize,
pub target_custom_properties: *const usize,
pub target_custom_property_count: usize,
pub animates_what_a_tick_cannot: bool,
pub animates_an_inherited_property: bool,
- pub has_additive_keyframe: bool,
}
/// What follows from the keyframes of a set alone.
@@ -692,28 +432,15 @@ pub unsafe extern "C" fn animations_keyframe_set_facts(set: *const KeyframeSet)
// SAFETY: Guaranteed by the caller.
let set = unsafe { borrowed_keyframe_set(set) };
FfiKeyframeSetFacts {
- keyframe_count: set.keyframes().len(),
target_properties: set.target_properties().as_ptr(),
target_property_count: set.target_properties().len(),
- target_custom_properties: set.target_custom_properties().as_ptr().cast::<usize>(),
+ target_custom_properties: set.target_custom_properties().as_ptr().cast(),
target_custom_property_count: set.target_custom_properties().len(),
animates_what_a_tick_cannot: set.animates_what_a_tick_cannot(),
animates_an_inherited_property: set.animates_an_inherited_property(),
- has_additive_keyframe: set.has_additive_keyframe(),
}
}
-/// The bytes a keyframe set holds, with the allocation the host's references share.
-///
-/// # Safety
-/// `set` must be a keyframe set the host holds a reference to.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn animations_keyframe_set_memory_size(set: *const KeyframeSet) -> usize {
- // SAFETY: Guaranteed by the caller.
- let set = unsafe { borrowed_keyframe_set(set) };
- crate::heap_size::ARC_HEADER_BYTES + size_of::<KeyframeSet>() + set.heap_size()
-}
-
/// Notes what the `attr()`s of the values a keyframe set declares can read, answering whether they can read a name
/// none could before.
///
@@ -743,8 +470,8 @@ pub unsafe extern "C" fn animations_effect_retain(effect: *const AnimationEffect
/// The host's `AnimationEffect` of `effect`, while it is alive.
#[unsafe(no_mangle)]
-pub extern "C" fn animations_effect_facade(effect: &AnimationEffectCell) -> *mut c_void {
- effect.facade().map_or(std::ptr::null_mut(), NonNull::as_ptr)
+pub extern "C" fn animations_effect_object_cell(effect: &AnimationEffectCell) -> *mut c_void {
+ effect.object_cell().map_or(std::ptr::null_mut(), NonNull::as_ptr)
}
/// Gives up a reference the host holds to an effect.
@@ -762,74 +489,22 @@ pub extern "C" fn animations_effect_id(effect: &AnimationEffectCell) -> Animatio
effect.borrow().id()
}
-/// The normalized timing the timing model reads of `effect`.
-#[unsafe(no_mangle)]
-pub extern "C" fn animations_effect_timing(effect: &AnimationEffectCell) -> AnimationEffectTiming {
- effect.borrow().timing()
-}
-
-/// The timing function of an effect, whose control points it borrows, and the raw fly string of its serialization,
-/// which it borrows, until the timing function changes.
-#[repr(C)]
-pub struct FfiEffectTimingFunction {
- pub descriptor: FfiEasingDescriptor,
- pub serialization: usize,
-}
-
-/// The timing function of `effect`.
-#[unsafe(no_mangle)]
-pub extern "C" fn animations_effect_timing_function(effect: &AnimationEffectCell) -> FfiEffectTimingFunction {
- let effect = effect.borrow();
- FfiEffectTimingFunction {
- descriptor: effect.timing_function().descriptor(),
- serialization: effect.timing_function_serialization().raw(),
- }
-}
-
/// The keyframe set `effect` runs, borrowed until its keyframes change, or null where it has none.
#[unsafe(no_mangle)]
pub extern "C" fn animations_effect_keyframe_set(effect: &AnimationEffectCell) -> *const KeyframeSet {
effect.borrow().keyframes().map_or(std::ptr::null(), Arc::as_ptr)
}
-/// Whether the compositor may run all `effect` animates.
-#[unsafe(no_mangle)]
-pub extern "C" fn animations_effect_may_run_on_the_compositor(effect: &AnimationEffectCell) -> bool {
- effect.borrow().may_run_on_the_compositor()
-}
-
/// Sets the keyframe set `effect` runs to `set`, which it takes a reference of its own to, or to none where `set` is
-/// null, answering whether it did. An effect whose keyframes from CSS script replaced takes no keyframes of CSS.
+/// null.
///
/// # Safety
/// `set` must be null or a keyframe set the host holds a reference to.
#[unsafe(no_mangle)]
-pub unsafe extern "C" fn animations_effect_set_keyframe_set(
- effect: &AnimationEffectCell,
- set: *const KeyframeSet,
-) -> bool {
+pub unsafe extern "C" fn animations_effect_set_keyframe_set(effect: &AnimationEffectCell, set: *const KeyframeSet) {
// SAFETY: Guaranteed by the caller.
let keyframes = (!set.is_null()).then(|| unsafe { KeyframeSet::retained_from_host(set) });
- let mut effect = effect.borrow_mut();
- if effect.ignores_css_keyframes()
- && keyframes
- .as_ref()
- .is_some_and(|keyframes| keyframes.origin() != KeyframeOrigin::Script)
- {
- return false;
- }
- effect.set_keyframes(keyframes);
- true
-}
-
-#[unsafe(no_mangle)]
-pub extern "C" fn animations_effect_composite(effect: &AnimationEffectCell) -> FfiCompositeOperation {
- effect.borrow().composite()
-}
-
-#[unsafe(no_mangle)]
-pub extern "C" fn animations_effect_set_composite(effect: &AnimationEffectCell, composite: FfiCompositeOperation) {
- effect.borrow_mut().set_composite(composite);
+ effect.borrow_mut().set_keyframes(keyframes);
}
/// Sets the host's `DOM::Element` that `effect` targets, which the host keeps alive while the effect targets it, or
@@ -895,45 +570,11 @@ pub extern "C" fn animations_effect_target(effect: &AnimationEffectCell) -> FfiE
}
}
-/// Sets the target pseudo-selector of `effect`.
-///
-/// # Safety
-/// The serialization of `pseudo_element` must be zero or a live raw fly string.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn animations_effect_set_pseudo_element(
- effect: &AnimationEffectCell,
- pseudo_element: FfiEffectPseudoElement,
-) {
- // SAFETY: Guaranteed by the caller.
- let serialization = unsafe { RetainedUtf16FlyString::from_borrowed_raw(pseudo_element.serialization) };
- effect
- .borrow_mut()
- .set_pseudo_element(pseudo_element.kind, serialization);
-}
-
-/// Sets the phase and the current iteration `effect` had when the host last dispatched its events.
-#[unsafe(no_mangle)]
-pub extern "C" fn animations_effect_set_previous_phase_and_current_iteration(
- effect: &AnimationEffectCell,
- phase: AnimationEffectPhase,
- current_iteration: f64,
-) {
- let mut effect = effect.borrow_mut();
- effect.set_previous_phase(phase);
- effect.set_previous_current_iteration(current_iteration);
-}
-
#[unsafe(no_mangle)]
pub extern "C" fn animations_effect_has_flag(effect: &AnimationEffectCell, flag: EffectFlag) -> bool {
effect.borrow().has_flag(flag)
}
-/// Sets or clears `flag` of `effect`, answering whether that changed it.
-#[unsafe(no_mangle)]
-pub extern "C" fn animations_effect_set_flag(effect: &AnimationEffectCell, flag: EffectFlag, value: bool) -> bool {
- effect.borrow_mut().set_flag(flag, value)
-}
-
/// Has `effect` forget what the host concluded of it as it was, since it changed: what the host built of it for the
/// compositor, how the host ran or throttled it, and whether a frame can skip its style update.
#[unsafe(no_mangle)]
@@ -941,63 +582,18 @@ pub extern "C" fn animations_effect_forget_what_the_host_concluded(effect: &Anim
effect.borrow_mut().forget_what_the_host_concluded();
}
-/// What `effect` remembers of whether a frame can skip its style update, for `key`.
-#[unsafe(no_mangle)]
-pub extern "C" fn animations_effect_per_frame_style_update_skip_decision(
- effect: &AnimationEffectCell,
- key: &PerFrameStyleUpdateSkipKey,
-) -> PerFrameStyleUpdateSkipDecision {
- effect.borrow().per_frame_style_update_skip_decision(key)
-}
-
-/// Has `effect` remember whether a frame can skip its style update, as the host found it from `key`.
-#[unsafe(no_mangle)]
-pub extern "C" fn animations_effect_note_per_frame_style_update_skip_decision(
- effect: &AnimationEffectCell,
- key: &PerFrameStyleUpdateSkipKey,
- can_skip: bool,
-) {
- effect
- .borrow_mut()
- .note_per_frame_style_update_skip_decision(*key, can_skip);
-}
-
-/// Asks the next style update for an observation sample of `effect` on behalf of a read of an element in the task of
-/// generation `task_generation`, unless it was already asked for one in that task.
-#[unsafe(no_mangle)]
-pub extern "C" fn animations_effect_request_observation_sample_in_task(
- effect: &AnimationEffectCell,
- task_generation: u64,
-) -> ObservationSampleRequest {
- effect.borrow_mut().request_observation_sample_in_task(task_generation)
-}
-
-/// What the host built of `effect` for the compositor, reached as `access` says, or null where it built nothing and
-/// `access` makes nothing. The state lives as long as the effect.
-#[unsafe(no_mangle)]
-pub extern "C" fn animations_effect_compositor_animation_state(
- effect: &AnimationEffectCell,
- access: CompositorAnimationStateAccess,
-) -> *mut CompositorAnimationEffectState {
- effect
- .borrow_mut()
- .compositor_animation_state(access)
- .map_or(std::ptr::null_mut(), std::ptr::from_mut)
-}
-
-/// The bytes the record of `effect` holds, without the keyframe set, which others share.
+/// Whether a frame can skip the style update of `effect`.
#[unsafe(no_mangle)]
-pub extern "C" fn animations_effect_memory_size(effect: &AnimationEffectCell) -> usize {
- effect.memory_size()
+pub extern "C" fn animations_effect_can_skip_per_frame_style_update(effect: &AnimationEffectCell) -> bool {
+ super::throttling::can_skip_per_frame_style_update(effect)
}
-/// A new idle CSS animation with no associated effect, with the one reference to it the host takes over.
-#[unsafe(no_mangle)]
-pub extern "C" fn animations_css_animation_create() -> *const AnimationCell {
+/// A new idle CSS animation named `name` with no associated effect.
+pub(crate) fn new_css_animation(name: RetainedUtf16FlyString) -> AnimationHandle {
AnimationHandle::new(AnimationKind::CssAnimation(CssAnimationState {
- name: RetainedUtf16FlyString::none(),
+ name,
// https://drafts.csswg.org/css-animations-1/#animation-timing-function
- // The initial value of animation-timing-function is ease.
+ // NB: The initial value of animation-timing-function is ease.
default_easing: CompactEasing::of(super::easing::keyword_cubic_bezier(0)),
applied_definition: None,
named_timeline: RetainedUtf16FlyString::none(),
@@ -1005,14 +601,12 @@ pub extern "C" fn animations_css_animation_create() -> *const AnimationCell {
last_css_play_state: None,
flags: 0,
}))
- .into_raw()
}
/// What a CSS transition is of and runs between, as the host starts one and reads it: the longhand by its id, or, where
/// `custom_name` is not zero, the custom property of that raw fly string, and the values, which a transition the host
/// reads lends it for as long as it holds the transition.
-#[repr(C)]
-pub struct FfiCssTransition {
+pub struct TransitionDescription {
pub generation: u64,
pub start_time: f64,
pub end_time: f64,
@@ -1024,34 +618,6 @@ pub struct FfiCssTransition {
pub property_id: u16,
}
-/// A new idle CSS transition `transition` describes, with no associated effect, with the one reference to it the host
-/// takes over. It is provisional until the host commits or discards it.
-///
-/// # Safety
-/// `transition` must name live style values and a live raw fly string or zero.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn animations_css_transition_create(transition: &FfiCssTransition) -> *const AnimationCell {
- // SAFETY: Guaranteed by the caller.
- let state = unsafe {
- CssTransitionState {
- custom_property_name: RetainedUtf16FlyString::from_borrowed_raw(transition.custom_name),
- generation: transition.generation,
- start_time: transition.start_time,
- end_time: transition.end_time,
- start_value: retained_value(transition.start_value),
- end_value: retained_value(transition.end_value),
- reversing_adjusted_start_value: retained_value(transition.reversing_adjusted_start_value),
- reversing_shortening_factor: transition.reversing_shortening_factor,
- property_id: transition.property_id,
- previous_phase: CSS_TRANSITION_PHASE_IDLE,
- provisional: true,
- adopted_from_lane: false,
- effect_started_with: None,
- }
- };
- AnimationHandle::new(AnimationKind::CssTransition(state)).into_raw()
-}
-
/// What the host describes of the animation of an SVG animation element as it creates it.
#[repr(C)]
pub struct FfiSmilAnimation {
@@ -1069,17 +635,15 @@ pub struct FfiSmilAnimation {
pub begin_time: f64,
}
-/// A new animation of an SVG animation element on `timeline`, whose associated effect is a new keyframe effect as
+/// A new animation of an SVG animation element on the default document timeline of its document, whose associated effect is a new keyframe effect as
/// `description` describes, with the one reference to it the host takes over. The host makes no `Animation` of it, and
/// its animation element holds it until it lets go of it.
///
/// # Safety
-/// `description` must name live host objects and keyframes, `timeline` a timeline the host holds a reference to, and a
-/// timing function, if any, must be live.
+/// `description` must name live host objects and keyframes, and a timing function, if any, must be live.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn animations_smil_animation_create(
description: &FfiSmilAnimation,
- timeline: &TimelineCell,
perform: HostEffectPerformer,
) -> *const AnimationCell {
let effect = EffectHandle::new();
@@ -1111,15 +675,12 @@ pub unsafe extern "C" fn animations_smil_animation_create(
animation_element: description.animation_element,
holders: SmilHolder::AnimationElement as u8,
});
- // SAFETY: The host holds a reference to the timeline it passes.
- let timeline = unsafe { TimelineHandle::retained_from_host(timeline) };
+ let timeline = default_document_timeline(element_node_document(description.animation_element));
run_procedure(&animation, perform, |procedures| {
procedures.set_timeline(Some(timeline));
- Ok(())
});
run_procedure(&animation, perform, |procedures| {
procedures.set_the_associated_effect(Some(&effect), Invalidate::Yes);
- Ok(())
});
animation.into_raw()
}
@@ -1145,56 +706,6 @@ pub extern "C" fn animations_animation_visit_host_cells(
});
}
-/// Calls `visit` with `context` and each GC cell of the host the record of `animation` names, which the object of the
-/// animation visits.
-#[unsafe(no_mangle)]
-pub extern "C" fn animations_animation_visit_named_cells(
- animation: &AnimationCell,
- context: *mut c_void,
- visit: unsafe extern "C" fn(context: *mut c_void, cell: *mut c_void, kind: HostCellKind),
-) {
- animation.for_each_named_cell(|cell, kind| {
- // SAFETY: The host visits a cell of an animation its object holds.
- unsafe { visit(context, cell.as_ptr(), kind) }
- });
-}
-
-/// A new effect with the default timing, no keyframes and no target, with the one reference to it the host takes over,
-/// as a CSS animation or transition creates its associated effect.
-#[unsafe(no_mangle)]
-pub extern "C" fn animations_effect_create() -> *const AnimationEffectCell {
- EffectHandle::new().into_raw()
-}
-
-/// The host's effect of an effect the host passes, which is null or one it holds a reference to.
-///
-/// # Safety
-/// `effect` must be null or an effect the host holds a reference to.
-unsafe fn effect_from_host(effect: *const AnimationEffectCell) -> Option<EffectHandle> {
- // SAFETY: Guaranteed by the caller.
- (!effect.is_null()).then(|| unsafe { EffectHandle::retained_from_host(effect) })
-}
-
-/// https://www.w3.org/TR/web-animations-1/#setting-the-associated-effect
-/// Sets the associated effect of `animation` to `effect`, or to none where it is null.
-///
-/// # Safety
-/// `effect` must be null or an effect the host holds a reference to.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn animations_animation_set_effect(
- animation: &AnimationCell,
- effect: *const AnimationEffectCell,
- should_invalidate: bool,
- perform: HostEffectPerformer,
-) {
- // SAFETY: Guaranteed by the caller.
- let effect = unsafe { effect_from_host(effect) };
- run_procedure(animation, perform, |procedures| {
- procedures.set_the_associated_effect(effect.as_ref(), invalidate(should_invalidate));
- Ok(())
- });
-}
-
/// The associated effect of `animation`, which it borrows for as long as the animation holds it, or null where it has
/// none.
#[unsafe(no_mangle)]
@@ -1204,21 +715,16 @@ pub extern "C" fn animations_animation_effect(animation: &AnimationCell) -> *con
})
}
-/// What the host's per-frame decisions read of `animation` now, with its current time at `timestamp` where
-/// `has_timestamp`.
+/// https://www.w3.org/TR/web-animations-1/#play-states
#[unsafe(no_mangle)]
-pub extern "C" fn animations_animation_timing_state(
- animation: &AnimationCell,
- has_timestamp: bool,
- timestamp: f64,
-) -> FfiAnimationTimingState {
- animation.borrow().timing_state(has_timestamp.then_some(timestamp))
+pub extern "C" fn animations_animation_play_state(animation: &AnimationCell) -> AnimationPlayState {
+ animation.borrow().play_state()
}
-/// The playback state of `animation`, which the timing model reads.
+/// https://www.w3.org/TR/web-animations-1/#playback-rate
#[unsafe(no_mangle)]
-pub extern "C" fn animations_animation_playback(animation: &AnimationCell) -> AnimationPlayback {
- *animation.borrow().playback()
+pub extern "C" fn animations_animation_playback_rate(animation: &AnimationCell) -> f64 {
+ animation.borrow().playback().playback_rate
}
/// The host's function that keeps `animation`, which it holds a reference to, alive to it with `context` until the call
@@ -1239,26 +745,21 @@ fn keep_alive_for_host_effects(effects: &HostEffects, keep_alive: FfiKeepAlive,
}
/// https://www.w3.org/TR/web-animations-1/#remove-replaced-animations
-/// For the host's `DOM::Document` `document`, whose associated timelines are the `timeline_count` of `timelines`,
-/// comparing elements in tree order with `tree_order`, and has the host keep each animation it removes alive through
-/// `keep_alive` with `context` and perform what that asks of it through `perform`.
-///
-/// # Safety
-/// `timelines` must point to `timeline_count` timelines the host holds references to.
+/// For the host's `DOM::Document` `document`, whose animations are `animations`, comparing elements in tree order with
+/// `tree_order`, and has the host keep each animation it removes alive through `keep_alive` with `context` and perform
+/// what that asks of it through `perform`.
#[unsafe(no_mangle)]
-pub unsafe extern "C" fn animations_remove_replaced_animations(
+pub extern "C" fn animations_remove_replaced_animations(
+ animations: &DocumentAnimations,
document: NonNull<c_void>,
- timelines: *const &TimelineCell,
- timeline_count: usize,
tree_order: FfiTreeOrder,
keep_alive: FfiKeepAlive,
context: *mut c_void,
perform: HostEffectPerformer,
) {
- // SAFETY: Guaranteed by the caller.
- let timelines = unsafe { ak::slice_from_raw_parts(timelines, timeline_count) };
+ let timelines = animations.timelines.clone();
let effects = procedures::remove_replaced_animations(
- timelines.iter().copied(),
+ timelines.iter().map(|timeline| &**timeline),
|element| element_node_document(element) == document,
&mut host_tree_order(tree_order),
);
@@ -1266,22 +767,6 @@ pub unsafe extern "C" fn animations_remove_replaced_animations(
perform_host_effects(effects, perform);
}
-/// Disassociates `animation`, on its timeline, if it has one, from the target of its associated effect where it is
-/// inert, where a procedure scheduled that.
-#[unsafe(no_mangle)]
-pub extern "C" fn animations_animation_disassociate_from_target_if_inert(
- animation: &AnimationCell,
- perform: HostEffectPerformer,
-) {
- if !animation.borrow().disassociation_from_target_pending() {
- return;
- }
- run_procedure(animation, perform, |procedures| {
- procedures.disassociate_from_target_if_inert();
- Ok(())
- });
-}
-
/// Keeps the animation of an SVG animation element, on its timeline, if it has one, at the time of its time container,
/// which began at `zero_time` of the document timeline and, where `is_paused`, is paused at `paused_time`, in
/// milliseconds.
@@ -1295,7 +780,6 @@ pub extern "C" fn animations_smil_animation_synchronize(
) {
run_procedure(animation, perform, |procedures| {
procedures.synchronize_with_smil_time_container(zero_time, is_paused.then_some(paused_time));
- Ok(())
});
}
@@ -1364,6 +848,7 @@ pub extern "C" fn animations_animation_hover_timing(
/// The owning element of a CSS animation or transition: the host's `DOM::Element`, or null where it has none, and the
/// host's `PseudoElement`, where `has_pseudo_element`.
#[repr(C)]
+#[derive(Clone, Copy)]
pub struct FfiOwningElement {
pub element: *mut c_void,
pub pseudo_element: u8,
@@ -1387,51 +872,14 @@ pub extern "C" fn animations_animation_owning_element(animation: &AnimationCell)
}
}
-/// Sets the owning element of `animation`, which the host keeps alive while the animation holds it, or to none where
-/// its element is null.
-#[unsafe(no_mangle)]
-pub extern "C" fn animations_animation_set_owning_element(animation: &AnimationCell, owner: FfiOwningElement) {
- animation
- .borrow_mut()
- .set_owning_element(std::ptr::NonNull::new(owner.element).map(|element| OwningElement {
- element,
- pseudo_element: owner.has_pseudo_element.then_some(owner.pseudo_element),
- }));
-}
-
-/// The state of a CSS animation as the host reads it: the raw fly string of its name, borrowed until it changes, or
-/// zero.
-#[repr(C)]
-pub struct FfiCssAnimationState {
- pub name: usize,
- /// The raw fly string of the name of the named timeline the animation follows, or zero.
- pub named_timeline: usize,
- /// The easing a keyframe of the animation that declares none of its own runs, whose control points it borrows
- /// until the easing changes.
- pub default_easing: FfiEasingDescriptor,
-}
-
-/// The state of the CSS animation `animation`.
-#[unsafe(no_mangle)]
-pub extern "C" fn animations_css_animation_state(animation: &AnimationCell) -> FfiCssAnimationState {
- let animation = animation.borrow();
- let state = animation.css_animation();
- FfiCssAnimationState {
- name: state.name.raw(),
- named_timeline: state.named_timeline.raw(),
- default_easing: state.default_easing.descriptor(),
- }
-}
-
/// Applies the timing, attachment range, easing, composite operation and play state the style computation computed in
-/// `definition` to the CSS animation `animation`, whose timeline the host updated, having the host perform what that
-/// asks for through `perform`.
+/// `definition` to the CSS animation `animation`, whose timeline is updated, having the host perform what that asks for
+/// through `perform`.
/// https://drafts.csswg.org/css-animations-2/#animations
///
/// # Safety
/// The values `definition` names must be null or live style values.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn animations_css_animation_apply_properties(
+unsafe fn apply_css_animation_properties(
animation: &AnimationCell,
definition: &crate::css::style_compute::FfiComputedAnimation,
perform: HostEffectPerformer,
@@ -1441,7 +889,7 @@ pub unsafe extern "C" fn animations_css_animation_apply_properties(
FillMode as SpecifiedFillMode, PlaybackDirection, SpecifiedIterationDuration,
};
- let has_flag = |flag: CssAnimationFlag| animation.borrow().css_animation().flags & flag as u8 != 0;
+ let has_flag = |flag: CssAnimationFlag| animation.borrow().css_animation().has_flag(flag);
// NB: An edge of the range that script set is no longer the style's to change.
let [current_start, current_end] = animation.borrow().range();
@@ -1475,10 +923,7 @@ pub unsafe extern "C" fn animations_css_animation_apply_properties(
)
};
if animation.borrow_mut().set_range([start, end]) {
- run_procedure(animation, perform, |procedures| {
- procedures.attachment_range_changed();
- Ok(())
- });
+ run_procedure(animation, perform, |procedures| procedures.attachment_range_changed());
}
let effect = animation
@@ -1537,14 +982,13 @@ pub unsafe extern "C" fn animations_css_animation_apply_properties(
// style it produces.
run_procedure(animation, perform, |procedures| {
procedures.update_finished_state(DidSeek::No, SynchronouslyNotify::No, Invalidate::Yes, None);
- Ok(())
});
if animation.borrow().css_animation().last_css_play_state == Some(definition.play_state) {
return;
}
if !has_flag(CssAnimationFlag::ScriptOverrodePlayState) {
- let play_state = animation.borrow().timing_state(None).play_state;
+ let play_state = animation.borrow().play_state();
// NB: Neither procedure throws for a CSS animation, which has an associated effect.
let result = match definition.play_state {
CSS_ANIMATION_PLAY_STATE_RUNNING if play_state != AnimationPlayState::Running => {
@@ -1560,49 +1004,620 @@ pub unsafe extern "C" fn animations_css_animation_apply_properties(
animation.borrow_mut().css_animation_mut().last_css_play_state = Some(definition.play_state);
}
-/// Whether `flag` of the CSS animation `animation` is set.
-#[unsafe(no_mangle)]
-pub extern "C" fn animations_css_animation_has_flag(animation: &AnimationCell, flag: CssAnimationFlag) -> bool {
- animation.borrow().css_animation().flags & flag as u8 != 0
+/// What applying the definitions of the CSS animations of an element or pseudo-element asks of the host, which hands
+/// each function `context`.
+#[repr(C)]
+pub struct FfiCssAnimationHost {
+ pub context: *mut c_void,
+ /// https://drafts.csswg.org/scroll-animations-1/#target-timeline
+ /// The target timeline of the owner of the animations for the timeline name `name`, a raw fly string, which the
+ /// host holds a reference to until the call returns, or null for none.
+ pub named_timeline: unsafe extern "C" fn(context: *mut c_void, name: usize) -> Option<&'static TimelineCell>,
+ /// Invalidates the composite order of the animations associated with the host's `DOM::Element` `element`.
+ pub invalidate_composite_order: unsafe extern "C" fn(context: *mut c_void, element: NonNull<c_void>),
+ pub keep_alive: FfiKeepAlive,
+ pub in_execution_context: FfiInExecutionContext,
+ pub perform: HostEffectPerformer,
+}
+
+impl FfiCssAnimationHost {
+ /// Has the host invalidate the style the associated effect of `animation` produces.
+ fn invalidate_effect(&self, animation: &AnimationHandle) {
+ let mut effects = HostEffects::default();
+ effects.push(animation, HostEffectKind::InvalidateEffect { changes_plan: false });
+ perform_host_effects(effects, self.perform);
+ }
+
+ /// Runs `run` in the execution context the host opens for `animation`.
+ fn in_execution_context(&self, animation: &AnimationCell, run: impl FnOnce()) {
+ in_host_execution_context(self.in_execution_context, self.context, animation, run);
+ }
+}
+
+/// Sets the keyframes of `effect` to `keyframes` of CSS, answering whether that changed them. An effect whose keyframes
+/// from CSS script replaced takes none.
+///
+/// # Safety
+/// `keyframes` must be null or a keyframe set the host holds a reference to.
+unsafe fn set_effect_keyframes(effect: &EffectHandle, keyframes: *const c_void) -> bool {
+ if effect.borrow().ignores_css_keyframes() {
+ return false;
+ }
+ let keyframes = keyframes.cast::<KeyframeSet>();
+ let current = effect.borrow().keyframes().map_or(std::ptr::null(), Arc::as_ptr);
+ if std::ptr::eq(current, keyframes) {
+ return false;
+ }
+ // SAFETY: Guaranteed by the caller.
+ let keyframes = (!keyframes.is_null()).then(|| unsafe { KeyframeSet::retained_from_host(keyframes) });
+ effect.borrow_mut().set_keyframes(keyframes);
+ effect.borrow_mut().forget_what_the_host_concluded();
+ true
+}
+
+/// The timeline the host finds of the name `definition` names for `owner`, through `host`.
+///
+/// # Safety
+/// The definition must name a live CSS string.
+unsafe fn named_timeline_of(
+ definition: &crate::css::style_compute::FfiComputedAnimation,
+ host: &FfiCssAnimationHost,
+) -> Option<TimelineHandle> {
+ // SAFETY: Guaranteed by the caller.
+ let name = unsafe { definition.timeline_name.as_ref() }
+ .map_or_else(RetainedUtf16FlyString::none, |name| name.to_fly_string());
+ // NB: The timeline is retained before anything can run the GC, and the animation then keeps it alive.
+ // SAFETY: The host hands out a timeline it holds a reference to, or null.
+ unsafe { (host.named_timeline)(host.context, name.raw()) }
+ .map(|timeline| unsafe { TimelineHandle::retained_from_host(timeline) })
+}
+
+/// The anonymous scroll timeline source `definition` describes for `owner`.
+fn anonymous_scroll_source(
+ definition: &crate::css::style_compute::FfiComputedAnimation,
+ owner: OwningElement,
+) -> ScrollTimelineSource {
+ ScrollTimelineSource::Anonymous {
+ scroller: definition.scroll_scroller,
+ target: owner.element,
+ pseudo_element: owner.pseudo_element,
+ }
+}
+
+/// The inset of the view() timeline `definition` describes.
+///
+/// # Safety
+/// The calculations of the inset must be null or live style values.
+pub(crate) unsafe fn retained_view_inset(inset: &crate::css::style_compute::FfiViewTimelineInset) -> ViewTimelineInset {
+ let edge = |is_auto, px, percentage, calculated| ViewTimelineInsetEdge {
+ is_auto,
+ px,
+ percentage,
+ // SAFETY: Guaranteed by the caller.
+ calculated: unsafe { retained_optional_value(calculated) },
+ };
+ ViewTimelineInset {
+ start: edge(
+ inset.start_is_auto,
+ inset.start_px,
+ inset.start_percentage,
+ inset.start_calculated,
+ ),
+ end: edge(
+ inset.end_is_auto,
+ inset.end_px,
+ inset.end_percentage,
+ inset.end_calculated,
+ ),
+ }
+}
+
+/// Whether the CSS animation `animation`, owned by `owner`, takes the timeline `definition` describes in place of the
+/// one it has.
+/// NB: Unrelated style changes shouldn't cause us to recreate anonymous timelines, to achieve this we drop updates
+/// between two equivalent anonymous timelines. The comparison is made against the description of the requested
+/// timeline, so that the timeline a definition names is only ever created when it will replace the one the
+/// animation already has.
+///
+/// # Safety
+/// The values `definition` names must be null or live.
+unsafe fn should_update_timeline(
+ animation: &AnimationHandle,
+ definition: &crate::css::style_compute::FfiComputedAnimation,
+ owner: OwningElement,
+ host: &FfiCssAnimationHost,
+) -> bool {
+ use crate::css::style_compute::FfiAnimationTimelineKind;
+ let old_timeline = animation.borrow().timeline().cloned();
+ let same = |timeline: Option<TimelineHandle>| match (&old_timeline, &timeline) {
+ (Some(old), Some(new)) => old.ptr_eq(new),
+ (None, None) => true,
+ _ => false,
+ };
+ match definition.timeline_kind {
+ FfiAnimationTimelineKind::None => return old_timeline.is_some(),
+ FfiAnimationTimelineKind::Document => {
+ return !same(Some(default_document_timeline(element_node_document(owner.element))));
+ }
+ // SAFETY: Guaranteed by the caller.
+ FfiAnimationTimelineKind::Named => return !same(unsafe { named_timeline_of(definition, host) }),
+ FfiAnimationTimelineKind::View | FfiAnimationTimelineKind::Scroll => {}
+ }
+ let Some(old_timeline) = old_timeline else {
+ return true;
+ };
+ let record = old_timeline.borrow();
+ let Some(scroll) = record.scroll() else {
+ return true;
+ };
+ if scroll.axis != definition.scroll_axis {
+ return true;
+ }
+ if definition.timeline_kind == FfiAnimationTimelineKind::View {
+ let Some(view) = &scroll.view else {
+ return true;
+ };
+ let ScrollTimelineSource::Anonymous {
+ target, pseudo_element, ..
+ } = scroll.source
+ else {
+ return true;
+ };
+ // SAFETY: Guaranteed by the caller.
+ return target != owner.element
+ || pseudo_element != owner.pseudo_element
+ || !view
+ .inset
+ .equals(&unsafe { retained_view_inset(&definition.view_inset) });
+ }
+ if scroll.view.is_some() {
+ return true;
+ }
+ match (scroll.source, anonymous_scroll_source(definition, owner)) {
+ (
+ ScrollTimelineSource::Anonymous {
+ scroller,
+ target,
+ pseudo_element,
+ },
+ ScrollTimelineSource::Anonymous {
+ scroller: new_scroller,
+ target: new_target,
+ pseudo_element: new_pseudo_element,
+ },
+ ) => scroller != new_scroller || target != new_target || pseudo_element != new_pseudo_element,
+ _ => true,
+ }
+}
+
+/// The timeline `definition` describes for the CSS animation owned by `owner`, a new anonymous one for scroll() and
+/// view(), or none.
+///
+/// # Safety
+/// The values `definition` names must be null or live.
+unsafe fn materialize_timeline(
+ definition: &crate::css::style_compute::FfiComputedAnimation,
+ owner: OwningElement,
+ host: &FfiCssAnimationHost,
+) -> Option<TimelineHandle> {
+ use crate::css::style_compute::FfiAnimationTimelineKind;
+ let document = element_node_document(owner.element);
+ let scroll = |source, view| {
+ TimelineKind::Scroll(Box::new(ScrollTimelineState {
+ source,
+ axis: definition.scroll_axis,
+ last_max_scroll_offset: None,
+ followed_scroller: None,
+ view,
+ }))
+ };
+ match definition.timeline_kind {
+ FfiAnimationTimelineKind::Document => Some(default_document_timeline(document)),
+ FfiAnimationTimelineKind::None => None,
+ FfiAnimationTimelineKind::Scroll => Some(create_timeline(
+ document,
+ scroll(anonymous_scroll_source(definition, owner), None),
+ )),
+ FfiAnimationTimelineKind::View => Some(create_timeline(
+ document,
+ scroll(
+ ScrollTimelineSource::Anonymous {
+ scroller: SCROLLER_NEAREST,
+ target: owner.element,
+ pseudo_element: owner.pseudo_element,
+ },
+ Some(ViewTimelineState {
+ // SAFETY: Guaranteed by the caller.
+ inset: unsafe { retained_view_inset(&definition.view_inset) },
+ last_metrics: None,
+ subject_style_node: None,
+ }),
+ ),
+ )),
+ // SAFETY: Guaranteed by the caller.
+ FfiAnimationTimelineKind::Named => unsafe { named_timeline_of(definition, host) },
+ }
+}
+
+/// The host's `CSS::Scroller::Nearest`, which a view timeline finds its source from its subject with.
+pub(crate) const SCROLLER_NEAREST: u8 = 1;
+
+/// Applies `definition` to the CSS animation `animation`, whose associated effect runs the keyframes the caller gave it.
+///
+/// # Safety
+/// The values `definition` names must be null or live style values.
+unsafe fn apply_css_animation_definition(
+ animation: &AnimationHandle,
+ definition: &crate::css::style_compute::FfiComputedAnimation,
+ owner: OwningElement,
+ host: &FfiCssAnimationHost,
+) {
+ use crate::css::style_compute::FfiAnimationTimelineKind;
+
+ // FIXME: Don't apply overridden properties as defined here: https://drafts.csswg.org/css-animations-2/#animations
+
+ // NB: Recorded before the early return below, so that the definition always says what the style computation last
+ // computed.
+ // NB: An animation that names its timeline looks it up again from its owning element as the timelines its document
+ // declares change, also while the name finds no timeline. The record notes the name it follows.
+ let named_timeline =
+ if definition.timeline_kind == FfiAnimationTimelineKind::Named && !definition.timeline_name.is_null() {
+ // SAFETY: The style computation names a live CSS string.
+ unsafe { &*definition.timeline_name }.to_fly_string()
+ } else {
+ RetainedUtf16FlyString::none()
+ };
+ // SAFETY: Guaranteed by the caller.
+ let applies_the_same_properties = unsafe { note_css_animation_definition(animation, definition, named_timeline) };
+
+ let script_set_timeline = animation
+ .borrow()
+ .css_animation()
+ .has_flag(CssAnimationFlag::ScriptSetTimeline);
+ // NB: An animation that names its timeline follows it as the declarations of its document change.
+ if definition.timeline_kind == FfiAnimationTimelineKind::Named {
+ let document = element_node_document(owner.element);
+ // SAFETY: The document of the owner of an animation is live, and the borrow ends here.
+ unsafe { super::timeline_host::document_animations(document) }
+ .set_mut(DocumentAnimationSetKind::FollowingNamedTimelines)
+ .insert(animation);
+ }
+ // SAFETY: The definition lives for the call.
+ let update_timeline = !script_set_timeline && unsafe { should_update_timeline(animation, definition, owner, host) };
+
+ // NB: Style feedback can recompute an animation's owning element. Reapplying unchanged properties would invalidate
+ // the effect and turn that feedback into an endless cycle.
+ if !update_timeline && applies_the_same_properties {
+ return;
+ }
+
+ host.in_execution_context(animation, || {
+ if update_timeline {
+ // SAFETY: The definition lives for the call.
+ let timeline = unsafe { materialize_timeline(definition, owner, host) };
+ run_procedure(animation, host.perform, |procedures| procedures.set_timeline(timeline));
+ }
+ // SAFETY: Guaranteed by the caller.
+ unsafe { apply_css_animation_properties(animation, definition, host.perform) };
+ });
}
-/// Sets the name of the CSS animation `animation` to the raw fly string `name`.
+/// https://drafts.csswg.org/css-animations-1/#animations
+/// Applies the `count` animation definitions `definitions` the style computation computed for the owner at `slot` of
+/// the element whose lists `animations` are, `owner`, which is in a display: none subtree where
+/// `in_display_none_subtree`: claims the CSS animation of each definition that claims one, creates one for each other
+/// definition, cancels each animation no definition claims, and sets the CSS animations of the owner to those of the
+/// definitions, publishing them to the style engine of `style_engine`, which knows the element as `node`, where the
+/// host names one. `pseudo_element_serialization` is the raw fly string of the serialization of the pseudo-element of
+/// `owner`, or zero where it has none.
///
/// # Safety
-/// `name` must be a live raw fly string.
+/// `animations` must be the lists of `owner`, which live for the call, and which the host may change as it performs;
+/// `definitions` must point to `count` definitions whose values are live and whose keyframe sets are null or ones the
+/// host holds references to; a non-null `style_engine` must be live for the call; and `pseudo_element_serialization`
+/// must be zero or a live raw fly string.
#[unsafe(no_mangle)]
-pub unsafe extern "C" fn animations_css_animation_set_name(animation: &AnimationCell, name: usize) {
+pub unsafe extern "C" fn animations_element_animations_apply_css_animation_definitions(
+ animations: *mut ElementAnimations,
+ slot: AnimationOwnerSlot,
+ owner: FfiOwningElement,
+ pseudo_element_serialization: usize,
+ definitions: *const crate::css::style_compute::FfiComputedAnimation,
+ count: usize,
+ in_display_none_subtree: bool,
+ style_engine: *const DocumentHost,
+ node: u32,
+ host: &FfiCssAnimationHost,
+) {
+ let owner_element = NonNull::new(owner.element).expect("CSS animations have an owning element");
+ // SAFETY: Guaranteed by the caller.
+ let definitions = unsafe { ak::slice_from_raw_parts(definitions, count) };
+ // NB: What the host performs can change the lists, so no borrow of them outlives a read.
+ // SAFETY: Guaranteed by the caller.
+ let existing_animations: SmallVec<[AnimationHandle; 1]> =
+ unsafe { &*animations }.css_animations(slot).iter().cloned().collect();
+ for animation in &existing_animations {
+ // SAFETY: The host keeps alive an animation it is handed for as long as this call lasts.
+ unsafe { (host.keep_alive)(host.context, animation) };
+ }
+ let mut existing_animation_was_claimed: SmallVec<[bool; 1]> = smallvec::smallvec![false; existing_animations.len()];
+ let mut new_animations: SmallVec<[AnimationHandle; 1]> = SmallVec::with_capacity(definitions.len());
+
+ // NB: Which existing animation each definition claims is decided by the style computation, from the names of the
+ // animations this element holds, which it publishes. So are the keyframes each definition runs, from the
+ // `@keyframes` every style scope publishes.
+ let owning_element = OwningElement {
+ element: owner_element,
+ pseudo_element: owner.has_pseudo_element.then_some(owner.pseudo_element),
+ };
+ for (name_index, definition) in definitions.iter().enumerate().rev() {
+ let name_index = u32::try_from(name_index).expect("animation-name has fewer than 2^32 entries");
+ let animation = if let Ok(matched_index) = usize::try_from(definition.matched_existing_index) {
+ assert!(
+ !existing_animation_was_claimed[matched_index],
+ "a definition claims an animation only once"
+ );
+ existing_animation_was_claimed[matched_index] = true;
+ let animation = existing_animations[matched_index].clone();
+ let effect = animation.borrow().effect().cloned();
+ if let Some(effect) = effect {
+ // SAFETY: Guaranteed by the caller.
+ if unsafe { set_effect_keyframes(&effect, definition.keyframe_set) } {
+ host.invalidate_effect(&animation);
+ }
+ // SAFETY: Guaranteed by the caller.
+ unsafe { apply_css_animation_definition(&animation, definition, owning_element, host) };
+ }
+ if set_css_animation_name_index(&animation, name_index) {
+ let target = animation
+ .borrow()
+ .effect()
+ .and_then(|effect| effect.borrow().target_element());
+ if let Some(target) = target {
+ // SAFETY: The effect keeps its target alive.
+ unsafe { (host.invalidate_composite_order)(host.context, target) };
+ }
+ }
+ animation
+ } else {
+ if in_display_none_subtree {
+ continue;
+ }
+ // An animation applies to an element if its name appears as one of the identifiers in the computed value
+ // of the animation-name property and the animation uses a valid @keyframes rule
+ // FIXME:
+ // CSS Animations generated using the markup defined in this specification are not added to the global
+ // animation list when they are created. Instead, these animations are appended to the global animation
+ // list at the first moment when they transition out of the idle play state after being disassociated from
+ // their owning element. CSS Animations that have been disassociated from their owning element but are
+ // still idle do not have a defined composite order.
+ // NB: Script gets the object of the animation, a CSSAnimation, as it first asks for it.
+ // SAFETY: The style computation names a live CSS string.
+ let name = unsafe { definition.name.as_ref() }
+ .map_or_else(RetainedUtf16FlyString::none, |name| name.to_fly_string());
+ let animation = new_css_animation(name);
+ // SAFETY: The host keeps alive an animation it is handed for as long as this call lasts.
+ unsafe { (host.keep_alive)(host.context, &animation) };
+ animation.borrow_mut().set_owning_element(Some(owning_element));
+ let effect = EffectHandle::new();
+ // SAFETY: Guaranteed by the caller.
+ unsafe { set_effect_keyframes(&effect, definition.keyframe_set) };
+ run_procedure(&animation, host.perform, |procedures| {
+ procedures.set_the_associated_effect(Some(&effect), Invalidate::Yes);
+ });
+ // SAFETY: Guaranteed by the caller.
+ unsafe { apply_css_animation_definition(&animation, definition, owning_element, host) };
+ set_css_animation_name_index(&animation, name_index);
+ // NB: The effect targets the owning pseudo-element, if any, before it is associated with its target.
+ // SAFETY: Guaranteed by the caller.
+ let serialization = unsafe { RetainedUtf16FlyString::from_borrowed_raw(pseudo_element_serialization) };
+ effect
+ .borrow_mut()
+ .set_pseudo_element(owner.pseudo_element, serialization);
+ // NB: The keyframes of a CSS animation read the attributes their rule read, which the style engine noted
+ // as the rule was published.
+ perform_host_effects(
+ procedures::set_effect_target(&effect, Some(owner_element)),
+ host.perform,
+ );
+ host.invalidate_effect(&animation);
+ animation
+ };
+ new_animations.push(animation);
+ }
+
+ // Once an animation has started it continues until it ends or the animation-name is removed
+ // NB: An animation no definition claimed is one whose animation-name entry has gone. Canceling it from the style
+ // computation needs no invalidation, as the effect stack is computed after this.
+ for (animation, _) in existing_animations
+ .iter()
+ .zip(&existing_animation_was_claimed)
+ .filter(|(_, claimed)| !**claimed)
+ {
+ cancel_animation(
+ animation,
+ Invalidate::No,
+ host.in_execution_context,
+ host.context,
+ host.perform,
+ );
+ }
+
+ // NB: The animations were created in reverse definition order, so flip it back.
+ new_animations.reverse();
// SAFETY: Guaranteed by the caller.
- let name = unsafe { RetainedUtf16FlyString::from_borrowed_raw(name) };
- animation.borrow_mut().css_animation_mut().name = name;
+ unsafe { &mut *animations }.set_css_animations(slot, new_animations.into_iter(), unsafe {
+ style_engine_target(style_engine, node)
+ });
}
-/// Sets the position of the CSS animation `animation` in `animation-name`, answering whether that changed it.
+/// What preparing to observe the CSS animation events of a document asks of the host, which hands each function
+/// `context`.
+#[repr(C)]
+pub struct FfiObserveCssAnimationEventsHost {
+ pub context: *mut c_void,
+ pub keep_alive: FfiKeepAlive,
+ pub perform: HostEffectPerformer,
+}
+
+/// Has the CSS animations of a document whose animations are `animations`, whose effects skipped per-frame animation
+/// ticks, take their current phase and iteration as those they last dispatched events for, as the host updates the
+/// timelines of the document to now first, keeping alive and performing through `host`.
+///
+/// # Safety
+/// `animations` must be what a live document knows of animations, which the host may reach as it performs.
#[unsafe(no_mangle)]
-pub extern "C" fn animations_css_animation_set_name_index(animation: &AnimationCell, name_index: u32) -> bool {
+pub unsafe extern "C" fn animations_document_animations_prepare_to_observe_css_animation_events(
+ animations: *mut DocumentAnimations,
+ host: &FfiObserveCssAnimationEventsHost,
+) {
+ // SAFETY: Guaranteed by the caller, and the borrow ends before the host performs anything.
+ let effects_to_synchronize: Vec<(AnimationHandle, EffectHandle)> = unsafe { &mut *animations }
+ .set_mut(DocumentAnimationSetKind::Associated)
+ .iter()
+ .filter_map(|animation| {
+ let effect = {
+ let record = animation.borrow();
+ if record.ffi_kind() != FfiAnimationKind::CssAnimation {
+ return None;
+ }
+ record.effect()?.clone()
+ };
+ let skipped = effect.borrow().has_flag(EffectFlag::PerFrameAnimationTickWasSkipped);
+ skipped.then_some((animation, effect))
+ })
+ .collect();
+ if effects_to_synchronize.is_empty() {
+ return;
+ }
+ for (animation, _) in &effects_to_synchronize {
+ // SAFETY: The host keeps alive an animation it is handed for as long as this call lasts.
+ unsafe { (host.keep_alive)(host.context, animation) };
+ }
+ // NB: The timelines of the document take their current time as of now first.
+ super::timeline_host::update_timelines_to_now(
+ animations,
+ &super::timeline_host::keep_alive_with(host.keep_alive, host.context),
+ host.perform,
+ );
+
+ // OPTIMIZATION: Events which occurred while there were no listeners were intentionally not sampled. Establish
+ // the current phase as the baseline so a newly added listener only observes future events.
+ for (_, effect) in &effects_to_synchronize {
+ let animation = effect.borrow().associated_animation();
+ let local_time = animation
+ .as_ref()
+ .and_then(|animation| animation.borrow().current_time());
+ let fill_mode = effect.borrow().timing().fill_mode;
+ let resolved = resolve_effect_timing(effect, local_time, fill_mode, animation.as_deref(), false);
+ let mut record = effect.borrow_mut();
+ record.previous_phase = resolved.phase;
+ record.previous_current_iteration = resolved.current_iteration.unwrap_or(0.0);
+ record.set_flag(EffectFlag::PerFrameAnimationTickWasSkipped, false);
+ }
+}
+
+/// What looking up the named timelines of the CSS animations of a document again asks of the host, which hands each
+/// function `context`.
+#[repr(C)]
+pub struct FfiNamedTimelinesHost {
+ pub context: *mut c_void,
+ /// The timeline the host finds of the name `name`, a raw fly string, for the element `owner`, or null.
+ pub target_timeline: unsafe extern "C" fn(
+ context: *mut c_void,
+ owner: FfiOwningElement,
+ name: usize,
+ ) -> Option<&'static TimelineCell>,
+ pub keep_alive: FfiKeepAlive,
+ pub in_execution_context: FfiInExecutionContext,
+ pub perform: HostEffectPerformer,
+}
+
+/// Looks the named timeline each CSS animation of a document whose animations are `animations` follows up again from
+/// its owning element, through `host`, and sets it as the animation's timeline where it changed, answering whether that
+/// changed the timeline of any.
+///
+/// # Safety
+/// `animations` must be what a live document knows of animations, which the host may reach as it performs.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn animations_document_animations_update_named_timelines(
+ animations: *mut DocumentAnimations,
+ host: &FfiNamedTimelinesHost,
+) -> bool {
+ // SAFETY: Guaranteed by the caller, and the borrow ends before the host performs anything.
+ let following = unsafe { &mut *animations }
+ .set_mut(DocumentAnimationSetKind::FollowingNamedTimelines)
+ .alive();
+ for animation in &following {
+ // SAFETY: The host keeps alive an animation it is handed for as long as this call lasts.
+ unsafe { (host.keep_alive)(host.context, animation) };
+ }
+ let mut any_timeline_changed = false;
+ for animation in &following {
+ if update_named_timeline(animation, host) {
+ any_timeline_changed = true;
+ }
+ }
+ any_timeline_changed
+}
+
+/// Looks the named timeline the CSS animation `animation` follows up again from its owning element through `host`, and
+/// sets it as the animation's timeline, answering whether that changed its timeline.
+fn update_named_timeline(animation: &AnimationCell, host: &FfiNamedTimelinesHost) -> bool {
+ let (named_timeline, owner) = {
+ let record = animation.borrow();
+ let state = record.css_animation();
+ if state.named_timeline.raw() == 0 || state.has_flag(CssAnimationFlag::ScriptSetTimeline) {
+ return false;
+ }
+ // NB: The owning element of a CSS animation is the element whose style names the timeline, which the animation
+ // keeps alive.
+ let owner = record
+ .owning_element()
+ .expect("a CSS animation that follows a named timeline has an owning element");
+ (state.named_timeline.clone(), owner)
+ };
+ let owner = FfiOwningElement {
+ element: owner.element.as_ptr(),
+ pseudo_element: owner.pseudo_element.unwrap_or(0),
+ has_pseudo_element: owner.pseudo_element.is_some(),
+ };
+ // SAFETY: The host finds the timeline for a live element and a live raw fly string, which it holds a reference to.
+ let timeline = unsafe { (host.target_timeline)(host.context, owner, named_timeline.raw()) };
+ let current = animation
+ .borrow()
+ .timeline()
+ .map(|timeline| std::ptr::from_ref::<TimelineCell>(timeline));
+ if current == timeline.map(std::ptr::from_ref) {
+ return false;
+ }
+ // SAFETY: As above.
+ let timeline = timeline.map(|timeline| unsafe { TimelineHandle::retained_from_host(timeline) });
+ in_host_execution_context(host.in_execution_context, host.context, animation, || {
+ run_procedure(animation, host.perform, |procedures| procedures.set_timeline(timeline));
+ });
+ true
+}
+
+/// Sets the position of the CSS animation `animation` in `animation-name`, answering whether that changed it.
+fn set_css_animation_name_index(animation: &AnimationCell, name_index: u32) -> bool {
std::mem::replace(&mut animation.borrow_mut().css_animation_mut().name_index, name_index) != name_index
}
/// Notes that the style computation applied `definition` to the CSS animation `animation`, which follows the named
-/// timeline of the raw fly string `named_timeline` where that is not zero, answering whether that sets the same
-/// properties as the definition it last applied, whatever keyframes each gives the animation's effect.
+/// timeline `named_timeline` where that is not none, answering whether that sets the same properties as the definition
+/// it last applied, whatever keyframes each gives the animation's effect.
///
/// # Safety
-/// The values `definition` names must be null or live style values, its keyframe set null or one the host holds a
-/// reference to, and `named_timeline` zero or a live raw fly string.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn animations_css_animation_apply_definition(
+/// The values `definition` names must be null or live style values, and its keyframe set null or one the host holds a
+/// reference to.
+unsafe fn note_css_animation_definition(
animation: &AnimationCell,
definition: &crate::css::style_compute::FfiComputedAnimation,
- named_timeline: usize,
+ named_timeline: RetainedUtf16FlyString,
) -> bool {
// SAFETY: Guaranteed by the caller.
- let (definition, named_timeline) = unsafe {
- (
- Arc::new(AppliedAnimationDefinition::retained(definition)),
- RetainedUtf16FlyString::from_borrowed_raw(named_timeline),
- )
- };
+ let definition = unsafe { Arc::new(AppliedAnimationDefinition::retained(definition)) };
let mut animation = animation.borrow_mut();
let state = animation.css_animation_mut();
state.named_timeline = named_timeline;
@@ -1619,156 +1634,701 @@ pub unsafe extern "C" fn animations_css_animation_apply_definition(
applies_the_same_properties
}
-/// The CSS transition `animation`, which lends the host its values and the name of its custom property for as long as
-/// the host holds it.
-#[unsafe(no_mangle)]
-pub extern "C" fn animations_css_transition(animation: &AnimationCell) -> FfiCssTransition {
- let animation = animation.borrow();
- let state = animation.css_transition();
- FfiCssTransition {
- generation: state.generation,
- start_time: state.start_time,
- end_time: state.end_time,
- reversing_shortening_factor: state.reversing_shortening_factor,
- custom_name: state.custom_property_name.raw(),
- start_value: state.start_value.pointer().cast(),
- end_value: state.end_value.pointer().cast(),
- reversing_adjusted_start_value: state.reversing_adjusted_start_value.pointer().cast(),
- property_id: state.property_id,
- }
-}
-
-/// The timing a CSS transition starts with: its delay and duration, in milliseconds, its timing function, and the raw
-/// fly string of the serialization of the value that was made from.
-#[repr(C)]
-pub struct FfiProvisionalTransitionTiming {
+/// What a CSS transition starts with: its owning element, which its effect targets, the raw fly string of the
+/// serialization of the owner's pseudo-element, or zero where it has none, the transition, whose start and end times
+/// include its delay, the timing its effect runs with: its delay and duration, in milliseconds, and the computed value
+/// of its timing function, and the effective zoom of the owner its values were computed at.
+pub struct TransitionStart {
+ pub owner: FfiOwningElement,
+ pub pseudo_element_serialization: usize,
+ pub transition: TransitionDescription,
pub delay: f64,
pub duration: f64,
- pub timing_function: FfiEasingDescriptor,
- pub timing_function_serialization: usize,
+ pub timing_function: *const c_void,
+ pub computed_value_zoom: f32,
+}
+
+/// The easing of the computed timing function `value`, with its serialization, as `EffectTiming.easing` reads it.
+fn timing_function_and_serialization(value: &StyleValueData) -> (CompactEasing, RetainedUtf16FlyString) {
+ use crate::css::serialize::{SerializationMode, TextSink, serialize_style_value};
+ use libcompositing_rust::easing::FfiEasingKind;
+ let easing = crate::css::style::effect_descriptions::easing_from_computed_timing_function(value)
+ .expect("a computed transition-timing-function describes an easing");
+ let mode = if matches!(value, StyleValueData::Easing(_)) && easing.kind() == FfiEasingKind::CubicBezier {
+ SerializationMode::Normal
+ } else {
+ SerializationMode::ResolvedValue
+ };
+ let mut sink = TextSink::new();
+ serialize_style_value(&mut sink, value, mode);
+ (
+ CompactEasing::of(easing),
+ RetainedUtf16FlyString::from_utf16(&sink.into_utf16()),
+ )
}
/// https://drafts.csswg.org/css-transitions/#starting
-/// Starts the CSS transition `animation`, on its timeline, provisionally, with `effect`, which targets its owning
-/// element and runs its keyframes, and the timing `timing`.
+/// Starts the CSS transition `start` describes on `timeline` provisionally, having the host perform what that asks for
+/// through `perform`. It is associated with its target only once committed.
///
/// # Safety
-/// The serialization `timing` names must be a live raw fly string.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn animations_css_transition_start_provisionally(
- animation: &AnimationCell,
- effect: &AnimationEffectCell,
- timing: &FfiProvisionalTransitionTiming,
+/// `start` must name live host objects, style values and raw fly strings.
+unsafe fn start_a_provisional_transition(
+ start: &TransitionStart,
+ timeline: Option<TimelineHandle>,
perform: HostEffectPerformer,
-) {
- // SAFETY: The host holds a reference to the effect it passes, and the caller guarantees the serialization.
- let (effect, timing) = unsafe {
- (
- EffectHandle::retained_from_host(effect),
- ProvisionalTransitionTiming {
- delay: timing.delay,
- duration: timing.duration,
- timing_function: CompactEasing::of(Easing::from_descriptor(&timing.timing_function)),
- timing_function_serialization: RetainedUtf16FlyString::from_borrowed_raw(
- timing.timing_function_serialization,
- ),
- },
- )
+) -> AnimationHandle {
+ let description = &start.transition;
+ // SAFETY: Guaranteed by the caller.
+ let state = unsafe {
+ CssTransitionState {
+ custom_property_name: RetainedUtf16FlyString::from_borrowed_raw(description.custom_name),
+ generation: description.generation,
+ start_time: description.start_time,
+ end_time: description.end_time,
+ start_value: retained_value(description.start_value),
+ end_value: retained_value(description.end_value),
+ reversing_adjusted_start_value: retained_value(description.reversing_adjusted_start_value),
+ reversing_shortening_factor: description.reversing_shortening_factor,
+ property_id: description.property_id,
+ previous_phase: TransitionPhase::Idle,
+ provisional: true,
+ adopted_from_lane: false,
+ effect_started_with: None,
+ }
};
- run_procedure(animation, perform, |procedures| {
+ // NB: Script gets the object of the transition, a CSSTransition, as it first asks for it.
+ let transition = AnimationHandle::new(AnimationKind::CssTransition(state));
+
+ // FIXME:
+ // Transitions generated using the markup defined in this specification are not added to the global animation list
+ // when they are created. Instead, these animations are appended to the global animation list at the first moment
+ // when they transition out of the idle play state after being disassociated from their owning element. Transitions
+ // that have been disassociated from their owning element but are still idle do not have a defined composite order.
+
+ // NB: The transition's associated effect is a keyframe effect. The current style computation collects this effect
+ // before publishing its result, so scheduling a second animated style update here would evaluate the same
+ // transition twice. The record keeps the effect the transition is started with. The values of a transition are
+ // computed values, which read no attributes.
+ let owner = NonNull::new(start.owner.element).expect("a transition has an owning element");
+ let effect = EffectHandle::new();
+ perform_host_effects(procedures::set_effect_target(&effect, Some(owner)), perform);
+ // SAFETY: Guaranteed by the caller.
+ unsafe {
+ let mut effect = effect.borrow_mut();
+ effect.set_pseudo_element(
+ start.owner.pseudo_element,
+ RetainedUtf16FlyString::from_borrowed_raw(start.pseudo_element_serialization),
+ );
+ effect.set_keyframes(Some(Arc::new(KeyframeSet::for_transition(
+ keyframe_property(description.property_id, description.custom_name),
+ retained_value(description.start_value),
+ retained_value(description.end_value),
+ start.computed_value_zoom,
+ ))));
+ }
+ transition.borrow_mut().set_owning_element(Some(OwningElement {
+ element: owner,
+ pseudo_element: start.owner.has_pseudo_element.then_some(start.owner.pseudo_element),
+ }));
+
+ // NB: The record sets the timing of the effect, sets it as the transition's associated effect and plays the
+ // transition, which creates its ready promise.
+ // SAFETY: Guaranteed by the caller.
+ let timing_function =
+ unsafe { start.timing_function.cast::<StyleValueData>().as_ref() }.expect("a transition has a timing function");
+ let (timing_function, timing_function_serialization) = timing_function_and_serialization(timing_function);
+ let timing = ProvisionalTransitionTiming {
+ delay: start.delay,
+ duration: start.duration,
+ timing_function,
+ timing_function_serialization,
+ };
+ run_procedure(&transition, perform, |procedures| {
+ procedures.set_timeline(timeline);
procedures.start_a_provisional_transition(&effect, timing);
- Ok(())
});
+ transition
}
-/// Discards the CSS transition `animation`, which was started provisionally and has no timeline any more.
-#[unsafe(no_mangle)]
-pub extern "C" fn animations_css_transition_discard_provisional(animation: &AnimationCell) {
- // SAFETY: The host holds a reference to the animation it passes.
- let animation = unsafe { AnimationHandle::retained_from_host(animation) };
- procedures::run(&animation, |procedures| {
+/// Discards the CSS transition `animation`, which was started provisionally, setting its timeline to none, having the
+/// host perform what that asks for through `perform`.
+fn discard_provisional_transition(animation: &AnimationHandle, perform: HostEffectPerformer) {
+ run_procedure(animation, perform, |procedures| procedures.set_timeline(None));
+ procedures::run(animation, |procedures| {
procedures.discard_provisional_transition();
Ok(())
})
.expect("discarding a provisional transition does not throw");
}
-/// Commits the CSS transition `animation`, which was started provisionally, as the running transition of its property
-/// the owner at `slot` of `animations` holds, where `animations` is not null, which `origin` started, and has the host
-/// associate it with its target through `perform`.
+/// Cancels `animation`, invalidating the style of its target as `invalidate` asks, in an execution context the host
+/// opens through `in_execution_context` with `context` where it is not idle, having the host perform what that asks for
+/// through `perform`.
+fn cancel_animation(
+ animation: &AnimationHandle,
+ invalidate: Invalidate,
+ in_execution_context: FfiInExecutionContext,
+ context: *mut c_void,
+ perform: HostEffectPerformer,
+) {
+ let cancel = || {
+ run_procedure(animation, perform, |procedures| procedures.cancel(invalidate));
+ };
+ // NB: Canceling an animation that is not idle settles its promises and creates its cancel event.
+ if animation.borrow().play_state() == AnimationPlayState::Idle {
+ cancel();
+ } else {
+ in_host_execution_context(in_execution_context, context, animation, cancel);
+ }
+}
+
+/// The element or pseudo-element `owner` names, as the target of a transition step.
+fn transition_target(owner: FfiOwningElement) -> TransitionTarget {
+ TransitionTarget {
+ element: NonNull::new(owner.element).expect("a transition step has a target"),
+ pseudo_element: owner.has_pseudo_element.then_some(owner.pseudo_element),
+ }
+}
+
+/// What a transition step decides over: the lists of its target's element, which it can change, the target, with the
+/// raw fly string of the serialization of its pseudo-element, or zero, and its slot in the lists, where it can own
+/// transitions, the time of the style change event on the document timeline, in milliseconds, the generation of the
+/// transitions it starts, the store of the animation overlay of the target's custom properties, or null where it has
+/// none, the style engine of `host`, which `read` reads, the records `before` and `after` the target's style changes
+/// between, the target's style node, its pseudo-element kind, or `u8::MAX`, the slot of the row of the box of its
+/// element, and the tree order of the host's elements.
+#[repr(C)]
+pub struct FfiTransitionStep {
+ pub animations: *mut ElementAnimations,
+ pub owner: FfiOwningElement,
+ pub pseudo_element_serialization: usize,
+ pub has_slot: bool,
+ pub slot: AnimationOwnerSlot,
+ pub style_change_event_time: f64,
+ pub generation: u64,
+ pub overlay_store: *const c_void,
+ pub host: *const DocumentHost,
+ pub read: *const crate::render_state::BegunRead,
+ pub before: *const c_void,
+ pub after: *const c_void,
+ pub target_node: u32,
+ pub target_pseudo_kind: u8,
+ pub element_box_slot: u32,
+ pub tree_order: FfiTreeOrder,
+}
+
+/// What a transition step did: whether it changed the effects that compose over the target's style, and whether it
+/// started any transition.
+#[repr(C)]
+#[derive(Default)]
+pub struct FfiTransitionStepOutcome {
+ pub changes_effects: bool,
+ pub started_transitions: bool,
+}
+
+/// Records the decision `action` for the provisional state at `index` of `document`, which supersedes any an earlier
+/// pass of the epoch made, discarding the transition that one started, if any.
///
/// # Safety
-/// A non-null `animations` must be lists the host holds, which nothing else refers to for the call.
+/// `document` must be live, and no reference to it may be held across the call.
+unsafe fn decide_provisional_transition(
+ document: *mut DocumentAnimations,
+ index: usize,
+ action: FfiTransitionActionKind,
+ perform: HostEffectPerformer,
+) {
+ let discarded = {
+ // SAFETY: Guaranteed by the caller.
+ let state = unsafe { &mut *document }.provisional_transitions.state_mut(index);
+ note_rendering_trace_event("provisional transition decision");
+ if state.has_decision {
+ note_rendering_trace_event("provisional transition decision superseded");
+ }
+ state.has_decision = true;
+ state.action = action;
+ state.proposed.take()
+ };
+ if let Some(discarded) = discarded {
+ discard_provisional_transition(&discarded, perform);
+ }
+}
+
+/// https://drafts.csswg.org/css-transitions/#starting
+/// Runs the transition step `step` describes in the outermost style stabilization epoch of `document`: the style engine
+/// decides what it does to each property's transitions, and the transitions it starts start provisionally, on the
+/// document timeline of the target. A transition action is provisional until the epoch commits; a later pass of the
+/// epoch decides again, superseding the decision of this one. Where the step changes the effects that compose over the
+/// target's style, the host keeps alive through `keep_alive` with `context` the animations of those effects, in
+/// composite order: the relevant animations of the element that target the same element or pseudo-element as the
+/// step, beside those of the SVG animation elements, which script does not see, and those whose transitions the step
+/// replaces, and the transitions it started. The host performs what that asks of it through `perform`.
+///
+/// # Safety
+/// `document` must be live for the call, and `step` must name live host objects, records and lists, which the host may
+/// change as it performs.
#[unsafe(no_mangle)]
-pub unsafe extern "C" fn animations_css_transition_commit_provisional(
- animation: &AnimationCell,
+pub unsafe extern "C" fn animations_document_animations_run_transition_step(
+ document: *mut DocumentAnimations,
+ step: &FfiTransitionStep,
+ keep_alive: FfiKeepAlive,
+ context: *mut c_void,
+ perform: HostEffectPerformer,
+) -> FfiTransitionStepOutcome {
+ let target = transition_target(step.owner);
+ let animations = NonNull::new(step.animations).expect("the target's element has lists");
+ let slot = step.has_slot.then_some(step.slot);
+ let t = step.style_change_event_time;
+
+ // NB: The element holds each transition, which lends what is read of it for as long as the element holds it. A
+ // running transition of a custom property holds it at what the overlay of the target's environment answers.
+ // One not sampled yet holds it at its start value.
+ // SAFETY: Guaranteed by the caller.
+ let overlay = unsafe {
+ step.overlay_store
+ .cast::<crate::css::custom_properties::CustomPropertyStore>()
+ .as_ref()
+ };
+ // SAFETY: Guaranteed by the caller.
+ let held = slot.map_or(&[][..], |slot| unsafe { animations.as_ref() }.transitions(slot));
+ let existing: SmallVec<[FfiExistingTransition; 4]> = held
+ .iter()
+ .map(|transition| {
+ let record = transition.borrow();
+ let mut existing = record.existing_transition(t);
+ if existing.custom_name != 0 && existing.running {
+ existing.custom_current_value = overlay
+ .and_then(|store| store.get(existing.custom_name))
+ .map_or(record.css_transition().start_value.pointer(), |entry| {
+ entry.value.pointer()
+ });
+ }
+ existing
+ })
+ .collect();
+
+ // NB: The values of the transitions the step starts are computed values of the after-change style.
+ // SAFETY: Guaranteed by the caller.
+ let computed_value_zoom = unsafe { crate::css::style::ViewLonghands::of_raw_record(step.after) }.effective_zoom();
+ let mut outcome = FfiTransitionStepOutcome::default();
+ let mut timeline = None;
+ let mut started: SmallVec<[AnimationHandle; 2]> = SmallVec::new();
+ let mut replaced: SmallVec<[AnimationEffectId; 2]> = SmallVec::new();
+ let input = crate::css::transition::FfiTransitionInput {
+ target_node: step.target_node,
+ target_pseudo_kind: step.target_pseudo_kind,
+ element_box_slot: step.element_box_slot,
+ };
+ let on_actions = |actions: &[FfiTransitionAction]| {
+ let mut decided: SmallVec<[usize; 4]> = SmallVec::new();
+ for action in actions {
+ let property = TransitionProperty {
+ property_id: action.property_id,
+ custom_name: action.custom_name,
+ };
+ // SAFETY: Guaranteed by the caller.
+ let index = unsafe {
+ (*document)
+ .provisional_transitions
+ .ensure(target, animations, slot, property)
+ };
+ decided.push(index);
+ // SAFETY: Guaranteed by the caller.
+ unsafe { decide_provisional_transition(document, index, action.kind, perform) };
+ if action.kind != FfiTransitionActionKind::None && action.kind != FfiTransitionActionKind::Start {
+ // SAFETY: Guaranteed by the caller.
+ let state = unsafe { &*document }.provisional_transitions.state(index);
+ let committed = state
+ .committed
+ .as_ref()
+ .expect("an action on a transition has one to act on");
+ if let Some(effect) = committed.borrow().effect() {
+ replaced.push(effect.borrow().id());
+ }
+ }
+ if action.start_value.is_null() {
+ continue;
+ }
+ let start = TransitionStart {
+ owner: step.owner,
+ pseudo_element_serialization: step.pseudo_element_serialization,
+ transition: TransitionDescription {
+ generation: step.generation,
+ start_time: t + action.delay,
+ end_time: t + action.active_duration + action.delay,
+ reversing_shortening_factor: action.reversing_shortening_factor,
+ custom_name: action.custom_name,
+ start_value: action.start_value.cast(),
+ end_value: action.end_value.cast(),
+ reversing_adjusted_start_value: action.reversing_adjusted_start_value.cast(),
+ property_id: action.property_id,
+ },
+ delay: action.delay,
+ duration: action.active_duration,
+ timing_function: action.timing_function.cast(),
+ computed_value_zoom,
+ };
+ let timeline = timeline
+ .get_or_insert_with(|| default_document_timeline(element_node_document(target.element)))
+ .clone();
+ // SAFETY: The action names live style values and raw fly strings, and the step live host objects.
+ let transition = unsafe { start_a_provisional_transition(&start, Some(timeline), perform) };
+ started.push(transition.clone());
+ // SAFETY: Guaranteed by the caller.
+ unsafe { &mut *document }
+ .provisional_transitions
+ .state_mut(index)
+ .proposed = Some(transition);
+ }
+ // NB: A property an earlier pass of the epoch decided over that this one does not leaves its transitions as
+ // they are.
+ // SAFETY: Guaranteed by the caller.
+ let indices = unsafe { &*document }.provisional_transitions.indices_of(target);
+ for index in indices {
+ if !decided.contains(&index) {
+ // SAFETY: Guaranteed by the caller.
+ unsafe {
+ decide_provisional_transition(document, index, FfiTransitionActionKind::None, perform);
+ };
+ }
+ }
+ };
+ // SAFETY: Guaranteed by the caller.
+ unsafe {
+ crate::css::style::engine_calls::decide_transitions(
+ &*step.host,
+ &*step.read,
+ step.before,
+ step.after,
+ &input,
+ &existing,
+ on_actions,
+ );
+ }
+
+ // NB: A transition action is provisional until the stabilization epoch commits, but the style published by this
+ // pass must already reflect that decision. The effect stack is rebuilt without the transitions being removed,
+ // and with any proposed replacements on top.
+ if replaced.is_empty() && started.is_empty() {
+ return outcome;
+ }
+ outcome.changes_effects = true;
+ outcome.started_transitions = !started.is_empty();
+ // SAFETY: Guaranteed by the caller.
+ let mut remaining: Vec<AnimationHandle> = unsafe { animations.as_ref() }
+ .associated()
+ .iter()
+ .filter(|animation| {
+ if matches!(animation.borrow().kind(), AnimationKind::Smil { .. }) {
+ return false;
+ }
+ let Some(effect) = animation.borrow().effect().cloned() else {
+ return false;
+ };
+ let effect = effect.borrow();
+ if effect.pseudo_element().map(|pseudo_element| pseudo_element.kind) != target.pseudo_element
+ || replaced.contains(&effect.id())
+ {
+ return false;
+ }
+ procedures::run(animation, |procedures| Ok(procedures.is_relevant()))
+ .expect("reading relevance does not throw")
+ .0
+ })
+ .cloned()
+ .collect();
+ remaining.extend(started);
+ let mut tree_order = host_tree_order(step.tree_order);
+ remaining.sort_by(|a, b| composite_order(&a.borrow(), &b.borrow(), &mut tree_order));
+ for animation in &remaining {
+ // SAFETY: The host keeps alive an animation it is handed.
+ unsafe { keep_alive(context, animation) };
+ }
+ outcome
+}
+
+/// Commits the transition actions the outermost style stabilization epoch of `document` decided, as the epoch commits:
+/// each removes the transition its property had, cancels it in an execution context the host opens through
+/// `in_execution_context` with `context` where it is not idle, or commits the transition the epoch started, which
+/// associates it with its target. The host performs what that asks of it through `perform`.
+///
+/// # Safety
+/// `document` must be live for the call, which the host may change as it performs.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn animations_document_animations_commit_provisional_transitions(
+ document: *mut DocumentAnimations,
+ in_execution_context: FfiInExecutionContext,
+ context: *mut c_void,
+ perform: HostEffectPerformer,
+) {
+ // NB: The states stay with the document until every action is taken, which keeps what they name alive.
+ let mut index = 0;
+ // SAFETY: Guaranteed by the caller, for each read below; no borrow outlives the read.
+ while index < unsafe { &*document }.provisional_transitions.len() {
+ let (action, animations, slot, property, committed, proposed) = {
+ // SAFETY: As above.
+ let state = unsafe { &*document }.provisional_transitions.state(index);
+ (
+ state.action,
+ state.animations,
+ state.slot,
+ state.property,
+ state.committed.clone(),
+ state.proposed.clone(),
+ )
+ };
+ index += 1;
+ let remove_committed_transition = || {
+ let (Some(slot), Some(committed)) = (slot, committed.as_ref()) else {
+ return;
+ };
+ // SAFETY: The state keeps the element that owns the lists alive, and nothing else refers to them here.
+ let animations = unsafe { &mut *animations.as_ptr() };
+ if animations
+ .transition(slot, property)
+ .is_some_and(|transition| transition.ptr_eq(committed))
+ {
+ animations.remove_transition(slot, property);
+ }
+ };
+ let cancel_committed_transition = || {
+ let committed = committed
+ .as_ref()
+ .expect("a cancelled transition is one the target held");
+ cancel_animation(committed, Invalidate::Yes, in_execution_context, context, perform);
+ };
+ let commit_proposed_transition = || {
+ let proposed = proposed.clone().expect("a started transition was proposed");
+ // SAFETY: The state keeps the element that owns the lists alive. Associating the transition with its
+ // target reaches the lists again, after this borrow ends.
+ let effects = transitions::commit_provisional_transition(
+ slot.map(|slot| (unsafe { &mut *animations.as_ptr() }, slot)),
+ proposed,
+ TransitionOrigin::StyleChange,
+ );
+ perform_host_effects(effects, perform);
+ note_rendering_trace_event("transition started");
+ };
+ match action {
+ FfiTransitionActionKind::None => continue,
+ FfiTransitionActionKind::Remove => remove_committed_transition(),
+ FfiTransitionActionKind::Cancel => cancel_committed_transition(),
+ FfiTransitionActionKind::Start => commit_proposed_transition(),
+ FfiTransitionActionKind::RemoveAndStart => {
+ remove_committed_transition();
+ commit_proposed_transition();
+ }
+ FfiTransitionActionKind::CancelRemoveAndStart => {
+ cancel_committed_transition();
+ remove_committed_transition();
+ commit_proposed_transition();
+ }
+ }
+ note_rendering_trace_event("transition action committed");
+ }
+ // SAFETY: Guaranteed by the caller.
+ drop(unsafe { &mut *document }.provisional_transitions.take());
+}
+
+/// Whether the outermost style stabilization epoch of `document` decided over the transitions of `owner`.
+#[unsafe(no_mangle)]
+pub extern "C" fn animations_document_animations_has_provisional_transitions(
+ document: &DocumentAnimations,
+ owner: FfiOwningElement,
+) -> bool {
+ document.provisional_transitions.has_states(transition_target(owner))
+}
+
+/// The effect of the transition at `index` among those the outermost style stabilization epoch of `document` started
+/// provisionally for `owner`, which the transition borrows for as long as the epoch holds it, or null past the last.
+/// NB: A provisionally started transition already contributed to the style published by the pass that started it,
+/// but it is not associated with its target until the stabilization epoch commits.
+#[unsafe(no_mangle)]
+pub extern "C" fn animations_document_animations_proposed_transition_effect(
+ document: &DocumentAnimations,
+ owner: FfiOwningElement,
+ index: usize,
+) -> *const AnimationEffectCell {
+ document
+ .provisional_transitions
+ .proposed_effect(transition_target(owner), index)
+}
+
+/// AD-HOC: Runs the transitions the hover of a clock lane left the element whose lists `animations` are, `element`,
+/// running beside a task, which the screen showed, in place of those its steps ended, as the rendering update
+/// that takes them in begins: `lane_transitions` are those the lane leaves the element running, and the lane's
+/// steps ended the host's transitions whose effects `cancelled` names and saw those `seen` names. A transition
+/// this starts is of the generation `generation`, on the document timeline, with values computed at the
+/// element's effective zoom `effective_zoom`. The host keeps each transition alive through `keep_alive` with
+/// `context`, and performs what that asks of it through `perform`.
+///
+/// # Safety
+/// `animations` must be the lists of `element`, which live for the call, and which the host may change as it performs,
+/// and `lane_transitions` must name live style values.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn animations_element_animations_adopt_lane_transitions(
animations: *mut ElementAnimations,
- slot: AnimationOwnerSlot,
- origin: TransitionOrigin,
+ element: NonNull<c_void>,
+ cancelled: ak::Span<'_, AnimationEffectId>,
+ seen: ak::Span<'_, AnimationEffectId>,
+ lane_transitions: ak::Span<'_, FfiLaneTransition>,
+ generation: u64,
+ effective_zoom: f32,
+ keep_alive: FfiKeepAlive,
+ context: *mut c_void,
perform: HostEffectPerformer,
) {
- // SAFETY: The host holds a reference to the animation it passes.
- let animation = unsafe { AnimationHandle::retained_from_host(animation) };
- let effects = {
+ let slot = AnimationOwnerSlot(0);
+ let (cancelled, seen, lane_transitions) = (cancelled.as_slice(), seen.as_slice(), lane_transitions.as_slice());
+ let timeline = Some(default_document_timeline(element_node_document(element)));
+ // NB: What the host performs can change the lists, so no borrow of them outlives a read.
+ // SAFETY: Guaranteed by the caller, for each read below.
+ let lists = || unsafe { &mut *animations };
+ let transition_of = |property_id: u16| {
+ lists()
+ .transition(
+ slot,
+ TransitionProperty {
+ property_id,
+ custom_name: 0,
+ },
+ )
+ .cloned()
+ };
+ let run = |transition: &AnimationHandle,
+ procedure: &mut dyn FnMut(&mut Procedures<'_>) -> Result<(), AnimationError>| {
+ if let Ok(((), effects)) = procedures::run(transition, |procedures| procedure(procedures)) {
+ perform_host_effects(effects, perform);
+ }
+ };
+ let is_running = |transition: &AnimationHandle| {
+ let transition = transition.borrow();
+ transition.play_state() != AnimationPlayState::Idle && !transition.playback().is_finished
+ };
+ // NB: The start time of a transition is a time of the document timeline, which validating it as script sets it
+ // would only read as milliseconds.
+ let set_start_time = |transition: &AnimationHandle, start_time: f64| {
+ run(transition, &mut |procedures| {
+ procedures.set_start_time_for_bindings(Some(TimeValue::milliseconds(start_time)));
+ Ok(())
+ });
+ };
+
+ // NB: The record of each running transition decides what becomes of it (see LaneAdoption). One the steps saw end by
+ // itself ends as it does, with its events, and so does one script finished meanwhile.
+ let existing: SmallVec<[AnimationHandle; 4]> = lists().transitions(slot).iter().cloned().collect();
+ let mut ended: SmallVec<[AnimationHandle; 4]> = SmallVec::new();
+ let mut host_decides: SmallVec<[TransitionProperty; 4]> = SmallVec::new();
+ for transition in &existing {
+ // SAFETY: The host keeps alive an animation it is handed for as long as this call lasts.
+ unsafe { keep_alive(context, transition) };
+ if !is_running(transition) {
+ continue;
+ }
+ let adoption = transition.borrow().lane_adoption(lane_transitions, cancelled, seen);
+ match adoption {
+ LaneAdoption::Stands => {}
+ LaneAdoption::Ends => ended.push(transition.clone()),
+ LaneAdoption::HostDecides => host_decides.push(TransitionProperty::of(&transition.borrow())),
+ }
+ }
+ for transition in &ended {
+ run(transition, &mut |procedures| {
+ procedures.cancel(Invalidate::Yes);
+ Ok(())
+ });
+ let property = TransitionProperty::of(&transition.borrow());
+ lists().remove_transition(slot, property);
+ }
+ // NB: A transition of the host's whose play is still pending runs from when the lane took it to start.
+ for lane_transition in lane_transitions
+ .iter()
+ .filter(|lane_transition| lane_transition.host_identity != AnimationEffectId::default())
+ {
+ let Some(transition) = transition_of(lane_transition.property_id) else {
+ continue;
+ };
+ if !transition.borrow().is_host_transition_of(lane_transition) {
+ continue;
+ }
+ let timing = transition.borrow().timing_state(None);
+ if timing.playback.start_time.get().is_none()
+ && (timing.playback.has_pending_play_task || timing.playback.has_pending_pause_task)
+ && timing.play_state != AnimationPlayState::Paused
+ {
+ set_start_time(&transition, lane_transition.start_time);
+ }
+ }
+ for lane_transition in lane_transitions
+ .iter()
+ .filter(|lane_transition| lane_transition.host_identity == AnimationEffectId::default())
+ {
+ let property = TransitionProperty {
+ property_id: lane_transition.property_id,
+ custom_name: 0,
+ };
+ if host_decides.contains(&property) {
+ continue;
+ }
+ if let Some(current) = transition_of(lane_transition.property_id) {
+ if current.borrow().runs_as_lane_does(lane_transitions) {
+ continue;
+ }
+ // NB: A completed transition of the property gives way to the one the lane started. One the lane saw end,
+ // which the host's timeline has yet to reach, ends now.
+ if is_running(&current) {
+ run(&current, &mut |procedures| procedures.finish_an_animation());
+ }
+ lists().remove_transition(slot, property);
+ }
+ let start = TransitionStart {
+ owner: FfiOwningElement {
+ element: element.as_ptr(),
+ pseudo_element: 0,
+ has_pseudo_element: false,
+ },
+ pseudo_element_serialization: 0,
+ transition: TransitionDescription {
+ generation,
+ start_time: lane_transition.start_time + lane_transition.delay,
+ end_time: lane_transition.start_time + lane_transition.duration + lane_transition.delay,
+ reversing_shortening_factor: lane_transition.reversing_shortening_factor,
+ custom_name: 0,
+ start_value: lane_transition.start_value.cast(),
+ end_value: lane_transition.end_value.cast(),
+ reversing_adjusted_start_value: lane_transition.reversing_adjusted_start_value.cast(),
+ property_id: lane_transition.property_id,
+ },
+ delay: lane_transition.delay,
+ duration: lane_transition.duration,
+ timing_function: lane_transition.timing_function.cast(),
+ computed_value_zoom: effective_zoom,
+ };
// SAFETY: Guaranteed by the caller.
- let animations = unsafe { animations.as_mut() };
- transitions::commit_provisional_transition(animations.map(|animations| (animations, slot)), animation, origin)
- };
- // NB: Associating the transition with its target reaches the lists again.
- perform_host_effects(effects, perform);
-}
-
-/// Writes to `existing` what a style change event at time `t` of the document timeline reads of the CSS transition
-/// `animation`, which its target holds, whose values it lends for as long as the host holds the transition. The host
-/// gives the current value of a running transition of a custom property.
-#[unsafe(no_mangle)]
-pub extern "C" fn animations_css_transition_existing(
- animation: &AnimationCell,
- t: f64,
- existing: &mut FfiExistingTransition,
-) {
- *existing = animation.borrow().existing_transition(t);
-}
-
-/// Whether the CSS transition `animation` already runs from when the hover of a clock lane started it, as one of the
-/// `lane_transitions` the lane leaves its element running does.
-#[unsafe(no_mangle)]
-pub extern "C" fn animations_css_transition_runs_as_lane_does(
- animation: &AnimationCell,
- lane_transitions: ak::Span<'_, FfiLaneTransition>,
-) -> bool {
- animation.borrow().runs_as_lane_does(lane_transitions.as_slice())
-}
-
-/// Whether `lane_transition` is the run of the host's CSS transition `animation` by the hover of a clock lane.
-#[unsafe(no_mangle)]
-pub extern "C" fn animations_css_transition_is_host_transition_of(
- animation: &AnimationCell,
- lane_transition: &FfiLaneTransition,
-) -> bool {
- animation.borrow().is_host_transition_of(lane_transition)
-}
-
-/// What becomes of the running CSS transition `animation` as the host takes in `lane_transitions`, which the hover of a
-/// clock lane leaves its element running, where the lane's steps ended the transitions whose effects `cancelled` names
-/// and saw those `seen` names.
-#[unsafe(no_mangle)]
-pub extern "C" fn animations_css_transition_lane_adoption(
- animation: &AnimationCell,
- lane_transitions: ak::Span<'_, FfiLaneTransition>,
- cancelled: ak::Span<'_, AnimationEffectId>,
- seen: ak::Span<'_, AnimationEffectId>,
-) -> LaneAdoption {
- animation
- .borrow()
- .lane_adoption(lane_transitions.as_slice(), cancelled.as_slice(), seen.as_slice())
+ let transition = unsafe { start_a_provisional_transition(&start, timeline.clone(), perform) };
+ // SAFETY: The host keeps alive an animation it is handed for as long as this call lasts.
+ unsafe { keep_alive(context, &transition) };
+ let effects = transitions::commit_provisional_transition(
+ Some((lists(), slot)),
+ transition.clone(),
+ TransitionOrigin::Lane,
+ );
+ // NB: Associating the transition with its target reaches the lists again.
+ perform_host_effects(effects, perform);
+ set_start_time(&transition, lane_transition.start_time);
+ }
}
/// The host's `SVGAnimationElement` whose animation the SMIL animation `animation` is.
#[unsafe(no_mangle)]
pub extern "C" fn animations_smil_animation_element(animation: &AnimationCell) -> *mut c_void {
+ smil_animation_element(animation).as_ptr()
+}
+
+/// The host's `SVGAnimationElement` whose animation `animation` is.
+pub(crate) fn smil_animation_element(animation: &AnimationCell) -> NonNull<c_void> {
match animation.borrow().kind() {
- AnimationKind::Smil { animation_element, .. } => animation_element.as_ptr(),
+ AnimationKind::Smil { animation_element, .. } => *animation_element,
_ => unreachable!("the animation is an SVG animation element's"),
}
}
@@ -1786,14 +2346,23 @@ pub(crate) fn host_tree_order(compare: FfiTreeOrder) -> impl FnMut(NonNull<c_voi
}
/// https://www.w3.org/TR/web-animations-1/#animation-composite-order
-/// The relative composite order of `a` and `b`, as a negative number where `a` sorts first, a positive one where it
-/// sorts last, and zero where they are the same animation, with `tree_order` comparing elements in tree order.
+/// The relative composite order of the animations `first` and `second`: less than zero where `first` comes first, zero
+/// for the same animation, and greater than zero otherwise, with the host's elements in the tree order `tree_order`
+/// gives.
#[unsafe(no_mangle)]
-pub extern "C" fn animations_composite_order(a: &AnimationCell, b: &AnimationCell, tree_order: FfiTreeOrder) -> i32 {
- if std::ptr::eq(a, b) {
+pub extern "C" fn animations_animation_composite_order(
+ first: &AnimationCell,
+ second: &AnimationCell,
+ tree_order: FfiTreeOrder,
+) -> i32 {
+ if std::ptr::eq(first, second) {
return 0;
}
- composite_order(&a.borrow(), &b.borrow(), &mut host_tree_order(tree_order)) as i32
+ match super::composite_order::composite_order(&first.borrow(), &second.borrow(), &mut host_tree_order(tree_order)) {
+ Ordering::Less => -1,
+ Ordering::Equal => 0,
+ Ordering::Greater => 1,
+ }
}
/// Takes a reference of the host's own to `animation`, which the host holds a reference to.
@@ -1832,15 +2401,6 @@ pub unsafe extern "C" fn animations_document_animations_destroy(animations: *mut
drop(unsafe { Box::from_raw(animations) });
}
-/// The set `kind` of the animations a document knows of, which lives as long as `animations`.
-#[unsafe(no_mangle)]
-pub extern "C" fn animations_document_animations_set(
- animations: &mut DocumentAnimations,
- kind: DocumentAnimationSetKind,
-) -> *mut WeakAnimationSet {
- animations.set_mut(kind)
-}
-
/// Begins the outermost style stabilization epoch of a document.
#[unsafe(no_mangle)]
pub extern "C" fn animations_document_animations_begin_style_stabilization_epoch(animations: &mut DocumentAnimations) {
@@ -1871,120 +2431,110 @@ pub unsafe extern "C" fn animations_document_animations_append_event(
) {
// SAFETY: Guaranteed by the caller.
let animation = unsafe { AnimationHandle::retained_from_host(animation) };
- animations.pending_events.append(
- PendingAnimationEvent {
- animation,
- event: *event,
- },
- provisional,
- );
+ let mut event = *event;
+ // NB: A time event is scheduled at the origin-relative time of the current time of a document timeline.
+ if event.kind == PendingAnimationEventKind::Time {
+ let timeline = animation.borrow().timeline().cloned();
+ event.scheduled_event_time = timeline
+ .filter(|timeline| matches!(timeline.borrow().kind, TimelineKind::Document { .. }))
+ .and_then(|timeline| timeline.convert_a_timeline_time_to_an_origin_relative_time(timeline.current_time()))
+ .into();
+ }
+ animations
+ .pending_events
+ .append(PendingAnimationEvent { animation, event }, provisional);
}
-/// What queueing the events an animation frame established for an animation did: what made the animation, which only
-/// has events where it is a CSS animation or a CSS transition, and how many it queued.
+/// What queueing the events of the animations of a document an animation frame established asks of the host, which
+/// hands each function `context`.
#[repr(C)]
-pub struct FfiQueuedCssEvents {
- pub kind: FfiAnimationKind,
- pub count: u8,
+pub struct FfiQueueAnimationEventsHost {
+ pub context: *mut c_void,
+ pub keep_alive: FfiKeepAlive,
+ /// The time stamp of an event queued for the host's `DOM::Element` `element` now.
+ pub time_stamp: unsafe extern "C" fn(context: *mut c_void, element: NonNull<c_void>) -> f64,
+ /// Queues the time events of the host's `SVGAnimationElement` `animation_element` the animation frame established.
+ pub queue_time_events: unsafe extern "C" fn(context: *mut c_void, animation_element: NonNull<c_void>),
+ pub perform: HostEffectPerformer,
}
+/// https://www.w3.org/TR/web-animations-1/#update-animations-and-send-events
/// https://drafts.csswg.org/css-transitions-2/#event-dispatch
/// https://www.w3.org/TR/css-animations-2/#event-dispatch
-/// Appends the events the animation frame just established for `animation` to the pending animation event queue of a
-/// document, or, where `provisional`, to the events it queues during its style stabilization epoch, each with the time
-/// stamp `time_stamp` answers for the owning element of the animation.
-///
-/// # Safety
-/// `animation` must be an animation the host holds a reference to.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn animations_document_animations_queue_css_events(
- animations: &mut DocumentAnimations,
- animation: *const AnimationCell,
- provisional: bool,
- time_stamp: unsafe extern "C" fn(element: NonNull<c_void>) -> f64,
-) -> FfiQueuedCssEvents {
- // SAFETY: Guaranteed by the caller.
- let animation = unsafe { AnimationHandle::retained_from_host(animation) };
- let events = animation.borrow_mut().take_css_events();
- let queued = FfiQueuedCssEvents {
- kind: events.kind,
- count: events.count,
- };
- if events.count == 0 {
- return queued;
- }
- let owner = animation
- .borrow()
- .owning_element()
- .expect("a CSS animation or transition with events has an owning element");
- // SAFETY: The animation keeps its owning element alive, and the host answers the time stamp of a live element.
- let time_stamp = unsafe { time_stamp(owner.element) };
- for css_event in &events.events[..usize::from(events.count)] {
- let event = FfiPendingAnimationEvent {
- kind: PendingAnimationEventKind::Css,
- css_event_type: css_event.r#type,
- playback_event_type: PlaybackEventType::Finish,
- time_event_type: TimeEventType::Begin,
- detail: 0,
- elapsed_time: css_event.elapsed_time,
- current_time: OptionalTimeValue::UNRESOLVED,
- timeline_time: OptionalTimeValue::UNRESOLVED,
- scheduled_event_time: events.scheduled_event_time,
- time_stamp,
- };
- animations.pending_events.append(
- PendingAnimationEvent {
- animation: animation.clone(),
- event,
- },
- provisional,
- );
- }
- queued
-}
-
-/// https://www.w3.org/TR/web-animations-1/#update-animations-and-send-events
-/// Takes the events of the pending animation event queue of a document in the order to dispatch them in, comparing
-/// elements in tree order with `tree_order`, has the host keep the animation of each alive through `keep_alive` with
-/// `context`, and has it dispatch each through `dispatch` with `context`.
+/// For each animation associated with a document whose animations `animations` are, whether or not it has a timeline,
+/// appends the events the animation frame established for a CSS animation or transition to the pending animation event
+/// queue of the document, or, where `provisional`, to the events it queues during its style stabilization epoch, has
+/// the host queue those of the animation of an SVG animation element, and disassociates the animation from the target
+/// of its associated effect where it is inert, as a procedure scheduled. Answers how many CSS events it queued.
///
/// # Safety
-/// `animations` must be what a live document knows of animations, which `dispatch` may reach again, and `context` must
-/// be what `keep_alive` and `dispatch` expect.
+/// `animations` must be what a live document knows of animations, which the host may reach as it performs.
#[unsafe(no_mangle)]
-pub unsafe extern "C" fn animations_document_animations_dispatch_events(
+pub unsafe extern "C" fn animations_document_animations_queue_events(
animations: *mut DocumentAnimations,
- tree_order: FfiTreeOrder,
- keep_alive: FfiKeepAlive,
- dispatch: unsafe extern "C" fn(context: *mut c_void, animation: &AnimationCell, event: &FfiPendingAnimationEvent),
- context: *mut c_void,
-) {
- // NB: Steps 4 to 6 take and sort the events, which dispatching them leaves to the host.
- let events_to_dispatch = {
- // SAFETY: Guaranteed by the caller; nothing else reaches the queue until the events are taken.
- let animations = unsafe { &mut *animations };
- animations
- .pending_events
- .take_events_to_dispatch(&mut host_tree_order(tree_order))
- };
- // NB: Dispatching an event runs script, which can run the GC, which must not collect the animation of an event
- // yet to be dispatched.
- for event in &events_to_dispatch {
- // SAFETY: The host keeps alive an animation it is handed for as long as the call that handed it lasts.
- unsafe { keep_alive(context, &event.animation) };
+ provisional: bool,
+ host: &FfiQueueAnimationEventsHost,
+) -> usize {
+ // SAFETY: Guaranteed by the caller, and the borrow ends before the host performs anything.
+ let associated = unsafe { &mut *animations }
+ .set_mut(DocumentAnimationSetKind::Associated)
+ .alive();
+ for animation in &associated {
+ // SAFETY: The host keeps alive an animation it is handed for as long as this call lasts.
+ unsafe { (host.keep_alive)(host.context, animation) };
}
- // 7. Dispatch each of the events in events to dispatch at their corresponding target using the order established in
- // the previous step.
- for event in &events_to_dispatch {
- // SAFETY: Guaranteed by the caller.
- unsafe { dispatch(context, &event.animation, &event.event) };
+ let mut queued_count = 0;
+ for animation in &associated {
+ let events = animation.borrow_mut().take_css_events();
+ if let AnimationKind::Smil { animation_element, .. } = *animation.borrow().kind() {
+ // SAFETY: The animation keeps its animation element alive.
+ unsafe { (host.queue_time_events)(host.context, animation_element) };
+ } else if !events.as_slice().is_empty() {
+ let owner = animation
+ .borrow()
+ .owning_element()
+ .expect("a CSS animation or transition with events has an owning element");
+ // NB: Each event takes the time stamp of when it is queued.
+ // SAFETY: The animation keeps its owning element alive.
+ let time_stamp = unsafe { (host.time_stamp)(host.context, owner.element) };
+ for css_event in events.as_slice() {
+ let event = FfiPendingAnimationEvent {
+ kind: PendingAnimationEventKind::Css,
+ css_event_type: css_event.r#type,
+ playback_event_type: PlaybackEventType::Finish,
+ time_event_type: TimeEventType::Begin,
+ detail: 0,
+ elapsed_time: css_event.elapsed_time,
+ current_time: OptionalTimeValue::UNRESOLVED,
+ timeline_time: OptionalTimeValue::UNRESOLVED,
+ scheduled_event_time: events.scheduled_event_time,
+ time_stamp,
+ };
+ // SAFETY: Guaranteed by the caller; the borrow ends before the host performs anything.
+ unsafe { &mut *animations }.pending_events.append(
+ PendingAnimationEvent {
+ animation: animation.clone(),
+ event,
+ },
+ provisional,
+ );
+ }
+ queued_count += events.as_slice().len();
+ }
+ if animation.borrow().disassociation_from_target_pending {
+ run_procedure(animation, host.perform, |procedures| {
+ procedures.disassociate_from_target_if_inert();
+ });
+ }
}
+ queued_count
}
/// Calls `visit` with `context` and each GC cell of the host that keeps alive the elements the records of the events a
-/// document queued name, which the document visits as the GC traces it.
+/// document queued name, and the timelines associated with the document, which the document visits as the GC traces
+/// it.
#[unsafe(no_mangle)]
-pub extern "C" fn animations_document_animations_visit_pending_events(
+pub extern "C" fn animations_document_animations_visit_edges(
animations: &DocumentAnimations,
context: *mut c_void,
visit: unsafe extern "C" fn(context: *mut c_void, cell: *mut c_void, kind: HostCellKind),
@@ -1993,6 +2543,18 @@ pub extern "C" fn animations_document_animations_visit_pending_events(
// SAFETY: The host visits a cell of an animation it queued an event of.
unsafe { visit(context, cell.as_ptr(), kind) }
});
+ // NB: The document keeps alive the elements and transitions its provisional transition actions decide over.
+ animations.provisional_transitions.for_each_host_cell(|cell, kind| {
+ // SAFETY: The host visits a cell the document's provisional transition actions keep alive.
+ unsafe { visit(context, cell.as_ptr(), kind) }
+ });
+ // NB: The document keeps the timelines associated with it alive, and the objects script sees of them.
+ for timeline in &animations.timelines {
+ timeline.for_each_holder_cell(|cell, kind| {
+ // SAFETY: The host visits a cell of a timeline associated with the document.
+ unsafe { visit(context, cell.as_ptr(), kind) }
+ });
+ }
}
/// Adds `effect` to the set `kind` of the effects a document knows of, answering whether the set did not hold it yet.
@@ -2010,69 +2572,6 @@ pub unsafe extern "C" fn animations_document_effect_set_insert(
animations.effect_set_mut(kind).insert(&effect)
}
-/// Removes `effect` from the set `kind` of the effects a document knows of, answering whether the set held it.
-#[unsafe(no_mangle)]
-pub extern "C" fn animations_document_effect_set_remove(
- animations: &mut DocumentAnimations,
- kind: DocumentEffectSetKind,
- effect: &AnimationEffectCell,
-) -> bool {
- animations.effect_set_mut(kind).remove(effect)
-}
-
-/// Whether the set `kind` of the effects a document knows of holds `effect`.
-#[unsafe(no_mangle)]
-pub extern "C" fn animations_document_effect_set_contains(
- animations: &mut DocumentAnimations,
- kind: DocumentEffectSetKind,
- effect: &AnimationEffectCell,
-) -> bool {
- animations.effect_set_mut(kind).contains(effect)
-}
-
-/// Empties the set `kind` of the effects a document knows of, calling `callback` with `context` and each effect alive
-/// to it, which the effect stays alive for the call of.
-///
-/// # Safety
-/// `callback` must not reach the effects the document knows of, and `context` must be what it expects.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn animations_document_effect_set_take_each(
- animations: &mut DocumentAnimations,
- kind: DocumentEffectSetKind,
- context: *mut c_void,
- callback: unsafe extern "C" fn(*mut c_void, &AnimationEffectCell),
-) {
- animations.effect_set_mut(kind).take_each(|effect| {
- // SAFETY: Guaranteed by the caller.
- unsafe { callback(context, effect) };
- });
-}
-
-/// Adds `animation` to `set`, answering whether `set` did not hold it yet.
-///
-/// # Safety
-/// `animation` must be an animation the host holds a reference to.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn animations_weak_animation_set_insert(
- set: &mut WeakAnimationSet,
- animation: *const AnimationCell,
-) -> bool {
- // SAFETY: Guaranteed by the caller.
- set.insert(&unsafe { AnimationHandle::retained_from_host(animation) })
-}
-
-/// Removes `animation` from `set`, answering whether `set` held it.
-#[unsafe(no_mangle)]
-pub extern "C" fn animations_weak_animation_set_remove(set: &mut WeakAnimationSet, animation: &AnimationCell) -> bool {
- set.remove(animation)
-}
-
-/// Whether `set` holds `animation`.
-#[unsafe(no_mangle)]
-pub extern "C" fn animations_weak_animation_set_contains(set: &WeakAnimationSet, animation: &AnimationCell) -> bool {
- set.contains(animation)
-}
-
/// Drops the entries of the animations in `set` that died, as the host begins to enumerate it.
#[unsafe(no_mangle)]
pub extern "C" fn animations_weak_animation_set_prune(set: &mut WeakAnimationSet) {
@@ -2091,12 +2590,6 @@ pub extern "C" fn animations_weak_animation_set_get(set: &WeakAnimationSet, inde
set.get(index).map_or(std::ptr::null(), AnimationHandle::into_raw)
}
-/// The bytes the record of `animation` holds, without its associated effect's.
-#[unsafe(no_mangle)]
-pub extern "C" fn animations_animation_memory_size(animation: &AnimationCell) -> usize {
- animation.memory_size()
-}
-
/// New empty lists of the animations of an element, which the element owns.
#[unsafe(no_mangle)]
pub extern "C" fn animations_element_animations_create() -> *mut ElementAnimations {
@@ -2126,14 +2619,18 @@ pub extern "C" fn animations_element_animations_for_each_host_cell(
});
}
-/// Associates `animation` with the element, answering whether it was not associated yet.
+/// Associates `animation` with the element, and, where it was not associated yet, with its document, whose animations
+/// `document` are, as one created during its style stabilization epoch where `in_style_stabilization_epoch`, answering
+/// whether it was not associated yet.
///
/// # Safety
/// `animation` must be an animation the host holds a reference to.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn animations_element_animations_associate(
animations: &mut ElementAnimations,
+ document: &mut DocumentAnimations,
animation: *const AnimationCell,
+ in_style_stabilization_epoch: bool,
) -> bool {
// SAFETY: Guaranteed by the caller.
let animation = unsafe { AnimationHandle::retained_from_host(animation) };
@@ -2141,16 +2638,45 @@ pub unsafe extern "C" fn animations_element_animations_associate(
return false;
}
animation.borrow_mut().did_associate_with_target();
+ document.associate(&animation, in_style_stabilization_epoch);
true
}
-/// Disassociates `animation` from the element, answering whether it was associated.
+/// Disassociates `animation`, whose associated effect `effect` was, if any, from the element, whose lists `animations`
+/// are where it has any, and from its document, whose animations `document` are, answering whether it was associated
+/// with the element.
+///
+/// # Safety
+/// `animations` must be null or the live lists of the element, and `effect` null or a live effect.
#[unsafe(no_mangle)]
-pub extern "C" fn animations_element_animations_disassociate(
- animations: &mut ElementAnimations,
+pub unsafe extern "C" fn animations_element_animations_disassociate(
+ animations: *mut ElementAnimations,
+ document: &mut DocumentAnimations,
animation: &AnimationCell,
+ effect: *const AnimationEffectCell,
) -> bool {
- animations.disassociate(animation)
+ // SAFETY: Guaranteed by the caller.
+ let was_associated = unsafe { animations.as_mut() }.is_some_and(|animations| animations.disassociate(animation));
+ // SAFETY: Guaranteed by the caller.
+ document.disassociate(animation, unsafe { effect.as_ref() });
+ was_associated
+}
+
+/// Moves the animations associated with an element, whose lists `animations` are, from the document whose animations
+/// `old_document` are to the one whose animations `new_document` are, as ones created during its style stabilization
+/// epoch where `in_style_stabilization_epoch`.
+#[unsafe(no_mangle)]
+pub extern "C" fn animations_element_animations_move_to_document(
+ animations: &ElementAnimations,
+ old_document: &mut DocumentAnimations,
+ new_document: &mut DocumentAnimations,
+ in_style_stabilization_epoch: bool,
+) {
+ for animation in animations.associated() {
+ let effect = animation.borrow().effect().cloned();
+ old_document.disassociate(animation, effect.as_deref());
+ new_document.associate(animation, in_style_stabilization_epoch);
+ }
}
#[unsafe(no_mangle)]
@@ -2228,33 +2754,7 @@ unsafe fn style_engine_target<'a>(host: *const DocumentHost, node: u32) -> Optio
})
}
-/// Sets the CSS animations of the owner at `slot` to `records`, which it takes references of its own to, and publishes
-/// them to the style engine of `host`, which knows the element as `node`, where the host names one.
-///
-/// # Safety
-/// Each of `records` must be an animation the host holds a reference to, and a non-null `host` must be live for the
-/// call.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn animations_element_animations_set_css_animations(
- animations: &mut ElementAnimations,
- slot: AnimationOwnerSlot,
- records: ak::Span<'_, *const AnimationCell>,
- host: *const DocumentHost,
- node: u32,
-) {
- animations.set_css_animations(
- slot,
- records
- .as_slice()
- .iter()
- // SAFETY: Guaranteed by the caller.
- .map(|&record| unsafe { AnimationHandle::retained_from_host(record) }),
- // SAFETY: Guaranteed by the caller.
- unsafe { style_engine_target(host, node) },
- );
-}
-
-/// Whether the element has had CSS animations since it last cancelled them, or has transitions.
+/// Whether the element has had CSS animations since it last canceled them, or has transitions.
#[unsafe(no_mangle)]
pub extern "C" fn animations_element_animations_has_css_animations_or_transitions(
animations: &ElementAnimations,
@@ -2262,46 +2762,6 @@ pub extern "C" fn animations_element_animations_has_css_animations_or_transition
animations.has_css_animations_or_transitions()
}
-/// The property a CSS transition runs: the host's `PropertyID`, and the raw fly string of the name of a custom property,
-/// or zero.
-#[repr(C)]
-pub struct FfiTransitionProperty {
- pub property_id: u16,
- pub custom_name: usize,
-}
-
-impl From<FfiTransitionProperty> for TransitionProperty {
- fn from(property: FfiTransitionProperty) -> Self {
- Self {
- property_id: property.property_id,
- custom_name: property.custom_name,
- }
- }
-}
-
-/// The record of the transition of `property` the owner at `slot` has, which the lists hold, or null.
-#[unsafe(no_mangle)]
-pub extern "C" fn animations_element_animations_transition(
- animations: &ElementAnimations,
- slot: AnimationOwnerSlot,
- property: FfiTransitionProperty,
-) -> *const AnimationCell {
- animations
- .transition(slot, property.into())
- .map_or(std::ptr::null(), |transition| &raw const **transition)
-}
-
-/// Removes the transition of `property` the owner at `slot` has, which is disassociated from its target once it is
-/// inert.
-#[unsafe(no_mangle)]
-pub extern "C" fn animations_element_animations_remove_transition(
- animations: &mut ElementAnimations,
- slot: AnimationOwnerSlot,
- property: FfiTransitionProperty,
-) {
- animations.remove_transition(slot, property.into());
-}
-
/// The host's function that runs `run` with `run_context` in an execution context it opens for `animation`, as its
/// caller, which hands it `context`, asks.
pub type FfiInExecutionContext = unsafe extern "C" fn(
@@ -2364,7 +2824,7 @@ pub unsafe extern "C" fn animations_element_animations_play_or_pause_css_animati
_ => unreachable!("a CSS-defined animation has the play state animation-play-state computed for it"),
};
in_host_execution_context(in_execution_context, context, animation, || {
- let ((), effects) = procedures::run(animation, |procedures| {
+ run_procedure_on(animation, perform, |procedures| {
if plays {
procedures.play_from_css()
} else {
@@ -2372,7 +2832,6 @@ pub unsafe extern "C" fn animations_element_animations_play_or_pause_css_animati
}
})
.expect("playing or pausing an animation from CSS does not throw");
- perform_host_effects(effects, perform);
});
}
}
@@ -2408,29 +2867,34 @@ pub unsafe extern "C" fn animations_element_animations_cancel_css_animations_and
unsafe { keep_alive(context, animation) };
}
for animation in &taken {
- let cancel = || {
- let ((), effects) = procedures::run(animation, |procedures| {
- procedures.cancel(Invalidate::No);
- Ok(())
- })
- .expect("cancelling an animation does not throw");
- perform_host_effects(effects, perform);
- };
- // NB: Cancelling an animation that is not idle settles its promises and creates its cancel event.
- let (play_state, _) = procedures::run(animation, |procedures| Ok(procedures.play_state()))
- .expect("reading the play state does not throw");
- if play_state == AnimationPlayState::Idle {
- cancel();
- } else {
- in_host_execution_context(in_execution_context, context, animation, cancel);
- }
+ cancel_animation(animation, Invalidate::No, in_execution_context, context, perform);
}
}
-/// The bytes the lists of the animations of an element hold, without the animations.
+/// The bytes the lists of the animations of an element hold, with the records of the animations associated with it and
+/// of their effects, and the keyframe sets those run that `first_counted` with `context` answers are counted here first.
#[unsafe(no_mangle)]
-pub extern "C" fn animations_element_animations_memory_size(animations: &ElementAnimations) -> usize {
- animations.memory_size()
+pub extern "C" fn animations_element_animations_record_memory_size(
+ animations: &ElementAnimations,
+ first_counted: unsafe extern "C" fn(context: *mut c_void, set: *const KeyframeSet) -> bool,
+ context: *mut c_void,
+) -> usize {
+ let mut bytes = animations.memory_size();
+ for animation in animations.associated() {
+ bytes += animation.memory_size();
+ let Some(effect) = animation.borrow().effect().cloned() else {
+ continue;
+ };
+ bytes += effect.memory_size();
+ let keyframes = effect.borrow().keyframes().cloned();
+ // SAFETY: The host only notes the address of the set.
+ if let Some(keyframes) = keyframes
+ && unsafe { first_counted(context, Arc::as_ptr(&keyframes)) }
+ {
+ bytes += crate::heap_size::ARC_HEADER_BYTES + size_of::<KeyframeSet>() + keyframes.heap_size();
+ }
+ }
+ bytes
}
/// Forgets the descriptions of the effects of the element `animations` belongs to that the host published to the style
@@ -2497,12 +2961,14 @@ pub(crate) unsafe fn describe_sampled_effects(effects: &[FfiSampledEffect]) -> S
unsafe extern "C" {
fn ladybird_animations_document_is_active(document: NonNull<c_void>) -> bool;
fn ladybird_animations_element_node_document(element: NonNull<c_void>) -> NonNull<c_void>;
+ /// Compares the host's `DOM::Element`s `first` and `second` in tree order, as composite order does.
+ pub fn web_animation_compare_elements_in_tree_order(first: *mut c_void, second: *mut c_void) -> i32;
}
/// The host's `DOM::Document` that is the node document of the host's `DOM::Element` `element`, which something the
/// caller holds keeps alive.
/// https://dom.spec.whatwg.org/#concept-node-document
-fn element_node_document(element: NonNull<c_void>) -> NonNull<c_void> {
+pub fn element_node_document(element: NonNull<c_void>) -> NonNull<c_void> {
// SAFETY: Guaranteed by the caller, and the host only reads the element.
unsafe { ladybird_animations_element_node_document(element) }
}
@@ -2574,20 +3040,6 @@ impl FfiViewTimelineInset {
end: edge(&self.end),
}
}
-
- /// The inset `inset` describes, whose calculations it borrows.
- fn borrowing(inset: &ViewTimelineInset) -> Self {
- let edge = |edge: &ViewTimelineInsetEdge| FfiViewTimelineInsetEdge {
- is_auto: edge.is_auto,
- px: edge.px,
- percentage: edge.percentage,
- calculated: edge.calculated.pointer().cast(),
- };
- Self {
- start: edge(&inset.start),
- end: edge(&inset.end),
- }
- }
}
/// https://drafts.csswg.org/scroll-animations-1/#dom-scrolltimeline-source
@@ -2665,7 +3117,7 @@ pub struct FfiTimelineDescription {
///
/// # Safety
/// The calculations of a view timeline's inset must be null or live style values.
-pub(crate) unsafe fn create_timeline(
+pub(crate) unsafe fn timeline_of_description(
document: NonNull<c_void>,
description: &FfiTimelineDescription,
) -> TimelineHandle {
@@ -2696,232 +3148,25 @@ pub(crate) unsafe fn create_timeline(
TimelineHandle::new(document, kind)
}
-/// The host's `DOM::Document` that `timeline` is associated with.
-#[unsafe(no_mangle)]
-pub extern "C" fn animations_timeline_document(timeline: &TimelineCell) -> *mut c_void {
- timeline.document().as_ptr()
-}
-
-/// The scroll offsets at the start and at the end of the cover range of a view timeline, in CSS pixels.
-#[repr(C)]
-#[derive(Clone, Copy, Default)]
-pub struct FfiViewTimelineCoverRange {
- pub start: f64,
- pub end: f64,
-}
-
-/// What the host reads of a timeline: what the timing model reads of it, with its duration and what moves it as a
-/// clock tick samples it, what script observed of it, and the state of a scroll or view timeline.
+/// What the host reads of a timeline: its kind and its current time, which is unresolved where the timeline is
+/// inactive.
#[repr(C)]
pub struct FfiTimeline {
- pub id: AnimationTimelineId,
pub kind: FfiTimelineKind,
- /// Its current time is unresolved where the timeline is inactive.
- pub sample: TimelineSample,
- pub is_inactive: bool,
- pub duration: OptionalTimeValue,
- pub clock: TimelineClock,
- /// The current time a style sampling reads instead, where `has_style_sampling_override`.
- pub has_style_sampling_override: bool,
- pub style_sampling_override: OptionalTimeValue,
- pub can_sample_current_time_at_timestamp: bool,
- /// The task generation of the event loop in which script last observed the timeline, where
- /// `has_observation_task_generation`, and the current time it observed then.
- pub has_observation_task_generation: bool,
- pub observation_task_generation: u64,
- pub observed_current_time: OptionalTimeValue,
- /// The task generation in which script observed the timeline at a time ahead of its current time, where
- /// `was_observed_ahead`.
- pub was_observed_ahead: bool,
- pub observed_ahead_task_generation: u64,
- pub source: FfiScrollTimelineSource,
- pub axis: u8,
- /// The inset of a view timeline, whose calculations it borrows until the inset changes.
- pub inset: FfiViewTimelineInset,
- /// The cover range of a view timeline as its progress was last calculated, where `has_cover_range`.
- pub has_cover_range: bool,
- pub cover_range: FfiViewTimelineCoverRange,
+ pub current_time: OptionalTimeValue,
}
/// What the host reads of `timeline`.
#[unsafe(no_mangle)]
pub extern "C" fn animations_timeline_read(timeline: &TimelineCell) -> FfiTimeline {
- let sample = timeline.sample();
- let is_inactive = timeline.is_inactive();
- let clock = timeline.clock();
- let record = timeline.borrow();
- let observation = record.observed_in_task_generation();
- let observed_ahead = record.observed_ahead_in_task_generation();
- let style_sampling_override = record.style_sampling_override();
- let no_edge = FfiViewTimelineInsetEdge {
- is_auto: true,
- px: 0.0,
- percentage: 0.0,
- calculated: std::ptr::null(),
- };
- let mut read = FfiTimeline {
- id: record.id(),
- kind: match &record.kind {
- TimelineKind::Document { .. } => FfiTimelineKind::Document,
- TimelineKind::Scroll(scroll) if scroll.view.is_some() => FfiTimelineKind::View,
- TimelineKind::Scroll(_) => FfiTimelineKind::Scroll,
- TimelineKind::Internal { .. } => FfiTimelineKind::Internal,
- },
- sample,
- is_inactive,
- duration: record.duration().into(),
- clock,
- has_style_sampling_override: style_sampling_override.is_some(),
- style_sampling_override: style_sampling_override.flatten().into(),
- can_sample_current_time_at_timestamp: record.can_sample_current_time_at_timestamp(),
- has_observation_task_generation: observation.0.is_some(),
- observation_task_generation: observation.0.unwrap_or(0),
- observed_current_time: observation.1.into(),
- was_observed_ahead: observed_ahead.is_some(),
- observed_ahead_task_generation: observed_ahead.unwrap_or(0),
- source: ScrollTimelineSource::Element(None).into(),
- axis: 0,
- inset: FfiViewTimelineInset {
- start: no_edge,
- end: no_edge,
- },
- has_cover_range: false,
- cover_range: FfiViewTimelineCoverRange::default(),
- };
- if let Some(scroll) = record.scroll() {
- read.source = scroll.source.into();
- read.axis = scroll.axis;
- if let Some(view) = &scroll.view {
- read.inset = FfiViewTimelineInset::borrowing(&view.inset);
- if let Some(metrics) = view.last_metrics {
- read.has_cover_range = true;
- read.cover_range = FfiViewTimelineCoverRange {
- start: metrics.cover_start(),
- end: metrics.cover_end(),
- };
- }
- }
- }
- read
-}
-
-/// The boxes a scroll timeline follows, as the host found them from its source in the render state of `host`'s
-/// document, which it reads in `read`: the box of the scroll container, if any, the viewport's where the source is the
-/// root element, its scroll node, where `has_scroll_node`, and the style node of the element whose box scrolls, or 0
-/// for the viewport. For a view timeline, the box of its subject, if any, and the style node by which a clock tick finds
-/// it, or 0 where the subject is a pseudo-element. `host` and `read` are null where the source has no box.
-#[repr(C)]
-pub struct FfiScrollTimelineBoxes {
- pub host: *const DocumentHost,
- pub read: *const BegunRead,
- pub scroller: NodeSlotId,
- pub has_scroll_node: bool,
- pub scroll_node: ScrollNodeStableId,
- pub scroller_style_node: u32,
- pub subject: NodeSlotId,
- pub subject_style_node: u32,
-}
-
-/// The host's function that updates the animations associated with its timeline `facade`.
-pub type TimelineAnimationsUpdater = extern "C" fn(facade: *mut c_void);
-
-/// Updates the current time of `timeline` in the task of `task_generation`: a document timeline's from the now
-/// timestamp `timestamp`, and a scroll timeline's from where the render state lays out the boxes it follows, `boxes`,
-/// unless that leaves it as it was where `only_if_stale`. Has `update_associated_animations` update the animations
-/// associated with the timeline as its current time changes, and answers whether the timeline was updated.
-///
-/// # Safety
-/// The host and the read of `boxes` must be null or a live document host and a read the host began of its render
-/// state, in which the slots of `boxes` name its rows.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn animations_timeline_update_current_time(
- timeline: &TimelineCell,
- timestamp: f64,
- boxes: Option<&FfiScrollTimelineBoxes>,
- task_generation: u64,
- only_if_stale: bool,
- update_associated_animations: TimelineAnimationsUpdater,
-) -> bool {
- let facade = timeline.facade().expect("the host updates a live timeline");
- let update = || update_associated_animations(facade.as_ptr());
- let Some(boxes) = boxes else {
- timeline.update_current_time(TimelineUpdate::Timestamp(timestamp), task_generation, false, update);
- return true;
- };
- let subject_style_node = StyleNodeID::from_raw(boxes.subject_style_node);
- // SAFETY: Guaranteed by the caller.
- let (scroller, subject) = match unsafe { (boxes.host.as_ref(), boxes.read.as_ref()) } {
- (Some(host), Some(read)) => {
- let found = ScrollTimelineBoxes {
- scroller: boxes.scroller,
- scroll_node: boxes.has_scroll_node.then_some(boxes.scroll_node),
- scroller_style_node: boxes.scroller_style_node,
- subject: boxes.subject,
- };
- let record = timeline.borrow();
- let scroll = record.scroll().expect("the host lays out scroll timelines");
- host.ask(read, |state| {
- let arena = state.arena_mut();
- arena.settle_scrollable_overflow();
- scroll.measure(arena, &found)
- })
- }
- _ => (None, None),
+ let current_time = timeline.sample().current_time;
+ let kind = match &timeline.borrow().kind {
+ TimelineKind::Document { .. } => FfiTimelineKind::Document,
+ TimelineKind::Scroll(scroll) if scroll.view.is_some() => FfiTimelineKind::View,
+ TimelineKind::Scroll(_) => FfiTimelineKind::Scroll,
+ TimelineKind::Internal { .. } => FfiTimelineKind::Internal,
};
- timeline.update_current_time(
- TimelineUpdate::Layout {
- scroller: scroller.as_ref(),
- subject: subject.as_ref(),
- subject_style_node,
- },
- task_generation,
- only_if_stale,
- update,
- )
-}
-
-/// Sets the current time of the Internals interface's timeline `timeline` to `time`, in milliseconds, in the task of
-/// `task_generation`, having `update_associated_animations` update its animations, or, where `for_observation`, the
-/// time a read of it observes.
-#[unsafe(no_mangle)]
-pub extern "C" fn animations_internal_timeline_set_time(
- timeline: &TimelineCell,
- time: OptionalNumber,
- for_observation: bool,
- task_generation: u64,
- update_associated_animations: TimelineAnimationsUpdater,
-) {
- let facade = timeline.facade().expect("the host sets the time of a live timeline");
- timeline.set_internal_time(time.get(), for_observation, task_generation, || {
- update_associated_animations(facade.as_ptr());
- });
-}
-
-/// The current time at the timestamp `timestamp` of `timeline`, where it can sample it there, and its current time
-/// otherwise. Where `observed`, script observes it in the task of `task_generation`, which the timeline keeps.
-#[unsafe(no_mangle)]
-pub extern "C" fn animations_timeline_current_time_at_timestamp(
- timeline: &TimelineCell,
- timestamp: f64,
- observed: bool,
- task_generation: u64,
-) -> OptionalTimeValue {
- timeline
- .current_time_at_timestamp(timestamp, observed.then_some(task_generation))
- .into()
-}
-
-/// Has a style sampling read `current_time` as the current time of `timeline` where `has_override`, and its current
-/// time otherwise.
-#[unsafe(no_mangle)]
-pub extern "C" fn animations_timeline_set_style_sampling_override(
- timeline: &TimelineCell,
- has_override: bool,
- current_time: OptionalTimeValue,
-) {
- timeline
- .borrow_mut()
- .set_style_sampling_override(has_override.then(|| current_time.get()));
+ FfiTimeline { kind, current_time }
}
/// The animations associated with `timeline`, which lives as long as the timeline.
@@ -2929,32 +3174,3 @@ pub extern "C" fn animations_timeline_set_style_sampling_override(
pub extern "C" fn animations_timeline_associated_animations(timeline: &TimelineCell) -> *mut WeakAnimationSet {
timeline.associated_animations().as_ptr()
}
-
-/// Sets the axis of the scroll timeline `timeline` to `axis`, the host's `ScrollAxis`, and the inset of a view
-/// timeline to `inset`, answering whether that changed either.
-///
-/// # Safety
-/// The calculations of `inset` must be null or live style values.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn animations_scroll_timeline_set_axis_and_inset(
- timeline: &TimelineCell,
- axis: u8,
- inset: Option<&FfiViewTimelineInset>,
-) -> bool {
- // SAFETY: Guaranteed by the caller.
- let inset = inset.map(|inset| unsafe { inset.retained() });
- timeline.set_axis_and_inset(axis, inset)
-}
-
-/// https://www.w3.org/TR/web-animations-1/#timeline-time-to-origin-relative-time
-/// The origin-relative time of the timeline time `timeline_time` of `timeline`, which is unresolved where the timeline
-/// defines no procedure to convert it.
-#[unsafe(no_mangle)]
-pub extern "C" fn animations_timeline_convert_to_origin_relative_time(
- timeline: &TimelineCell,
- timeline_time: OptionalTimeValue,
-) -> OptionalNumber {
- timeline
- .convert_a_timeline_time_to_an_origin_relative_time(timeline_time.get())
- .into()
-}
diff --git a/Libraries/LibWeb/Rust/src/animations/host_timing.rs b/Libraries/LibWeb/Rust/src/animations/host_timing.rs
index 327228899d1..4a7ed29c10c 100644
--- a/Libraries/LibWeb/Rust/src/animations/host_timing.rs
+++ b/Libraries/LibWeb/Rust/src/animations/host_timing.rs
@@ -8,7 +8,8 @@
//! updates and ticks, the wakeups it arms, and what the compositor update hands the compositor. The record resolves
//! all of it from one current time, and decides what follows from its timing alone.
-use super::animation::{AnimationKind, AnimationRecord, CSS_TRANSITION_PHASE_IDLE};
+use super::animation::{AnimationKind, AnimationRecord, TransitionPhase};
+use super::timeline_state::time_unit_of;
use super::timing::{
self, AnimationEffectPhase, AnimationEffectTiming, AnimationPlayState, AnimationPlayback, OptionalNumber,
OptionalTimeValue, TimeValue, TimeValueType,
@@ -93,18 +94,77 @@ impl AnimationRecord {
}
}
+ /// A zero time in the unit of the times of the timeline of the animation.
+ pub(crate) fn zero_time(&self) -> TimeValue {
+ let progress_based = self
+ .timeline()
+ .is_some_and(|timeline| timeline.borrow().is_progress_based());
+ TimeValue::zero(time_unit_of(progress_based))
+ }
+
+ /// https://www.w3.org/TR/web-animations-1/#associated-effect-end
+ pub(crate) fn associated_effect_end(&self) -> TimeValue {
+ // The associated effect end of an animation is equal to the end time of the animation’s associated effect. If
+ // the animation has no associated effect, the associated effect end is zero.
+ match self.effect() {
+ Some(effect) => timing::end_time(&effect.borrow().timing()),
+ None => self.zero_time(),
+ }
+ }
+
+ /// https://www.w3.org/TR/web-animations-1/#animation-current-time
+ pub(crate) fn current_time(&self) -> Option<TimeValue> {
+ let timeline_time = self.timeline().and_then(|timeline| timeline.current_time());
+ timing::current_time_at(self.playback(), timeline_time)
+ }
+
+ /// https://www.w3.org/TR/web-animations-1/#play-states
+ pub(crate) fn play_state(&self) -> AnimationPlayState {
+ self.play_state_at(self.current_time())
+ }
+
+ /// https://www.w3.org/TR/web-animations-1/#play-states
+ /// At `current_time`, the current time of the animation.
+ pub(crate) fn play_state_at(&self, current_time: Option<TimeValue>) -> AnimationPlayState {
+ timing::play_state_at(self.playback(), current_time, self.associated_effect_end())
+ }
+
+ /// Whether the animation has a monotonically increasing timeline.
+ pub(crate) fn has_monotonically_increasing_timeline(&self) -> bool {
+ self.timeline()
+ .is_some_and(|timeline| timeline.borrow().is_monotonically_increasing())
+ }
+
+ /// https://www.w3.org/TR/web-animations-1/#animation-effect-phases-and-states
+ /// The phase of the associated effect of the animation at the current time of the animation, idle without one.
+ pub(crate) fn effect_phase(&self) -> AnimationEffectPhase {
+ let Some(effect) = self.effect() else {
+ return AnimationEffectPhase::Idle;
+ };
+ let sample = self.timeline().map(|timeline| timeline.sample());
+ let timeline_time = sample.as_ref().and_then(|sample| sample.current_time.get());
+ let current_time = timing::current_time_at(self.playback(), timeline_time);
+ timing::resolve_timing(
+ &effect.borrow().timing(),
+ current_time,
+ Some(self.playback()),
+ sample.as_ref(),
+ )
+ .phase
+ }
+
/// What the host's per-frame decisions read of the animation now, with its current time at `timestamp`, where the
/// host asks about one.
pub(crate) fn timing_state(&self, timestamp: Option<f64>) -> FfiAnimationTimingState {
let playback = *self.playback();
let timeline = self.timeline();
- let timeline_time = timeline.and_then(|timeline| timeline.current_time());
- let current_time = timing::current_time_at(&playback, timeline_time);
+ let sample = timeline.map(|timeline| timeline.sample());
+ let current_time =
+ timing::current_time_at(&playback, sample.as_ref().and_then(|sample| sample.current_time.get()));
let current_time_at_timestamp = timestamp.and_then(|timestamp| {
let timeline_time = timeline.and_then(|timeline| timeline.current_time_at_timestamp(timestamp, None));
timing::current_time_at(&playback, timeline_time)
});
- let sample = timeline.map(|timeline| timeline.sample());
let has_monotonically_increasing_timeline = sample.is_some_and(|sample| sample.is_monotonically_increasing);
let effect = self.effect().map(|effect| effect.borrow());
@@ -112,19 +172,7 @@ impl AnimationRecord {
let resolved = effect_timing
.as_ref()
.map(|effect_timing| timing::resolve_timing(effect_timing, current_time, Some(&playback), sample.as_ref()));
- // https://www.w3.org/TR/web-animations-1/#associated-effect-end
- let associated_effect_end = match &effect_timing {
- Some(effect_timing) => timing::end_time(effect_timing),
- None => {
- let progress_based = timeline.is_some_and(|timeline| timeline.borrow().is_progress_based());
- TimeValue::zero(if progress_based {
- TimeValueType::Percentage
- } else {
- TimeValueType::Milliseconds
- })
- }
- };
-
+ let associated_effect_end = self.associated_effect_end();
let mut state = FfiAnimationTimingState {
kind: self.ffi_kind(),
playback,
@@ -142,12 +190,10 @@ impl AnimationRecord {
.map_or(AnimationEffectPhase::Idle, |resolved| resolved.phase),
is_in_effect: resolved.as_ref().is_some_and(timing::is_in_effect),
end_time: associated_effect_end,
- previous_current_iteration: effect
- .as_ref()
- .map_or(0.0, |effect| effect.previous_current_iteration()),
+ previous_current_iteration: effect.as_ref().map_or(0.0, |effect| effect.previous_current_iteration),
is_initial_pending_css_transition: playback.pending()
&& playback.has_pending_play_task
- && matches!(self.kind(), AnimationKind::CssTransition(state) if state.previous_phase == CSS_TRANSITION_PHASE_IDLE),
+ && matches!(self.kind(), AnimationKind::CssTransition(state) if state.previous_phase == TransitionPhase::Idle),
compositor_anchor: FfiCompositorAnchorKind::None,
compositor_anchor_origin_relative_time: 0.0,
compositor_anchor_local_time: 0.0,
@@ -277,19 +323,6 @@ mod tests {
animation
}
- #[test]
- fn an_animation_without_a_timeline_runs_on_no_clock() {
- let state = animation_held_at(500.0, 1.0).borrow().timing_state(None);
- assert_eq!(state.kind, FfiAnimationKind::Script);
- assert_eq!(state.phase, AnimationEffectPhase::Active);
- assert!(state.is_in_effect);
- assert_eq!(state.current_time.get(), Some(TimeValue::milliseconds(500.0)));
- assert_eq!(state.compositor_anchor, FfiCompositorAnchorKind::None);
- assert!(!state.can_throttle_offscreen_effect);
- assert!(!state.can_throttle_replaced_effect);
- assert_eq!(state.next_throttled_iteration_event_time.get(), None);
- }
-
#[test]
fn the_next_phase_boundary_is_the_start_delay_and_then_the_active_end() {
let state = animation_held_at(50.0, 2.0).borrow().timing_state(None);
@@ -302,14 +335,4 @@ mod tests {
let state = animation_held_at(600.0, f64::INFINITY).borrow().timing_state(None);
assert_eq!(state.next_phase_boundary_delay.get(), None);
}
-
- #[test]
- fn an_animation_without_an_effect_has_no_effect_timing() {
- let animation = AnimationHandle::new(AnimationKind::Script);
- let state = animation.borrow().timing_state(Some(0.0));
- assert!(!state.has_effect);
- assert_eq!(state.play_state, AnimationPlayState::Idle);
- assert_eq!(state.phase, AnimationEffectPhase::Idle);
- assert_eq!(state.next_phase_boundary_delay.get(), None);
- }
}
diff --git a/Libraries/LibWeb/Rust/src/animations/keyframe_reflection.rs b/Libraries/LibWeb/Rust/src/animations/keyframe_reflection.rs
index 532c43bf5d4..44c8ac63450 100644
--- a/Libraries/LibWeb/Rust/src/animations/keyframe_reflection.rs
+++ b/Libraries/LibWeb/Rust/src/animations/keyframe_reflection.rs
@@ -12,7 +12,7 @@ use super::animation::AnimationKind;
use super::bindings_api::ParsedEasing;
use super::effect::AnimationEffectRecord;
use super::keyframes::{
- CompositeOperationOrAuto, KEY_SCALE_FACTOR, KeyframeOrigin, KeyframeProperty, KeyframeSet, ResourceContext,
+ CompositeOperationOrAuto, KeyframeOrigin, KeyframeProperty, KeyframeSet, ResourceContext, offset_of_key,
};
use crate::css::style_compute::{FfiReflectedKeyframeProperty, FfiStyleSheetResourceContext};
use crate::css::style_value::{RetainedStyleValueData, StyleValueData, retain_style_value};
@@ -88,7 +88,7 @@ fn declared_css_keyframes(effect: &ReflectedEffect) -> Vec<CssKeyframe> {
easing: Option<&RetainedStyleValueData>,
composite: CompositeOperationOrAuto,
declarations: &mut dyn Iterator<Item = (KeyframeProperty, &RetainedStyleValueData)>| {
- let offset = key as f64 / (100.0 * KEY_SCALE_FACTOR);
+ let offset = offset_of_key(key as f64);
// AD-HOC: Step 2.2 uses the computed timing function. Substitution-dependent keyframe easings use the
// animation-wide easing for web compatibility.
let easing = easing
diff --git a/Libraries/LibWeb/Rust/src/animations/keyframes.rs b/Libraries/LibWeb/Rust/src/animations/keyframes.rs
index 71d6be1182b..5c26a1a5652 100644
--- a/Libraries/LibWeb/Rust/src/animations/keyframes.rs
+++ b/Libraries/LibWeb/Rust/src/animations/keyframes.rs
@@ -17,8 +17,7 @@ use crate::css::style_value::{RetainedStyleValueData, StyleValueData};
use std::ops::Range;
use std::sync::Arc;
-/// What keyframe offsets are scaled by to key a keyframe: `KeyframeEffect::AnimationKeyFrameKeyScaleFactor`, which
-/// keys an offset of 100% at 100000.
+/// What keyframe offsets, as percentages, are scaled by to key a keyframe, which keys an offset of 100% at 100000.
pub(crate) const KEY_SCALE_FACTOR: f64 = 1000.0;
/// The key of a keyframe at an offset of 0%.
@@ -27,6 +26,25 @@ pub(crate) const INITIAL_KEY: u64 = 0;
/// The key of a keyframe at an offset of 100%.
pub(crate) const FINAL_KEY: u64 = 100 * KEY_SCALE_FACTOR as u64;
+/// The offset `offset`, a fraction of an iteration, scaled as a key, before it is truncated to one.
+pub(crate) fn scaled_offset(offset: f64) -> f64 {
+ offset * 100.0 * KEY_SCALE_FACTOR
+}
+
+/// The key of a keyframe at the offset `offset`, a fraction of an iteration.
+pub(crate) fn key_of_offset(offset: f64) -> u64 {
+ #[expect(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
+ let key = scaled_offset(offset) as u64;
+ key
+}
+
+/// The offset, a fraction of an iteration, that `key` scales.
+pub(crate) fn offset_of_key(key: f64) -> f64 {
+ #[expect(clippy::cast_precision_loss)]
+ let final_key = FINAL_KEY as f64;
+ key / final_key
+}
+
/// https://drafts.csswg.org/web-animations-1/#enumdef-compositeoperationorauto
/// In the order of the host's `Bindings::CompositeOperationOrAuto`.
#[repr(u8)]
@@ -267,7 +285,7 @@ fn key_of_percentage(percentage: f64) -> u64 {
/// Whether a property, by its id, can be animated: a longhand whose animation type is not `none`, or a shorthand
/// with such a longhand.
-pub(crate) fn is_animatable_property(property_id: u16) -> bool {
+pub fn is_animatable_property(property_id: u16) -> bool {
use crate::css::property_metadata::{longhands_for_shorthand, property_animation_type, property_is_shorthand};
if property_is_shorthand(property_id) {
return longhands_for_shorthand(property_id)
@@ -317,7 +335,7 @@ impl KeyframeSet {
let mut declared_keyframes = Vec::new();
let mut declared_declarations = Vec::new();
- // Forwards pass, resolve all the user-specified keyframe properties.
+ // NB: Forwards pass, resolve all the user-specified keyframe properties.
for (keys, block) in blocks {
let mut resolved_keyframe = PendingKeyframe::new(0);
let mut declared_easing = None;
@@ -325,8 +343,8 @@ impl KeyframeSet {
let value = RetainedStyleValueData::from_arc(declaration.value.clone());
match declaration.property_id {
property_id::ANIMATION_TIMING_FUNCTION => {
- // animation-timing-function is a list property, but inside @keyframes only a single value is
- // meaningful.
+ // NB: animation-timing-function is a list property, but inside @keyframes only a single value
+ // is meaningful.
let value = match value.data() {
StyleValueData::ValueList { values, .. } => match values.as_slice().first() {
Some(first) => first.clone_retained(),
@@ -370,7 +388,7 @@ impl KeyframeSet {
}
property if !is_animatable_property(property) => {}
property => {
- // Unresolved properties are resolved when the effect is sampled.
+ // NB: Unresolved properties are resolved when the effect is sampled.
expanded_longhands(property, &value, |longhand, longhand_value| {
animated_properties.insert(KeyframeProperty::Id(longhand));
resolved_keyframe.set(
@@ -922,23 +940,4 @@ mod tests {
);
assert!(set.has_additive_keyframe());
}
-
- #[test]
- fn a_transition_runs_from_its_start_to_its_end_value() {
- use crate::css::css_enums::keyword;
- use crate::css::property_metadata::property_id;
- let set = KeyframeSet::for_transition(
- KeyframeProperty::Id(property_id::OPACITY),
- value(keyword::AUTO),
- value(keyword::NONE),
- 1.0,
- );
- let keys: Vec<_> = set.keyframes().iter().map(|keyframe| keyframe.key).collect();
- assert_eq!(keys, [INITIAL_KEY, FINAL_KEY]);
- for keyframe in set.keyframes() {
- assert_eq!(declared_properties(&set, keyframe), [(property_id::OPACITY, true)]);
- assert_eq!(keyframe.composite, CompositeOperationOrAuto::Auto);
- }
- assert_eq!(set.target_properties(), [property_id::OPACITY]);
- }
}
diff --git a/Libraries/LibWeb/Rust/src/animations/mod.rs b/Libraries/LibWeb/Rust/src/animations/mod.rs
index 3bf29a97db3..db3e82ed425 100644
--- a/Libraries/LibWeb/Rust/src/animations/mod.rs
+++ b/Libraries/LibWeb/Rust/src/animations/mod.rs
@@ -10,6 +10,7 @@ pub(crate) mod animation;
pub mod bindings_api;
pub(crate) mod clock_plan;
pub(crate) mod composite_order;
+pub(crate) mod compositor_update;
pub(crate) mod css_events;
pub(crate) mod document_animations;
pub(crate) mod easing;
@@ -22,8 +23,13 @@ pub(crate) mod keyframe_reflection;
pub(crate) mod keyframes;
pub(crate) mod pending_animation_events;
pub(crate) mod procedures;
+pub(crate) mod provisional_transitions;
+pub(crate) mod rendering_trace;
+pub(crate) mod rendering_update;
pub(crate) mod snapshot;
+pub(crate) mod throttling;
pub(crate) mod timeline;
+pub(crate) mod timeline_host;
pub(crate) mod timeline_state;
pub(crate) mod transitions;
pub(crate) mod weak_record_set;
diff --git a/Libraries/LibWeb/Rust/src/animations/pending_animation_events.rs b/Libraries/LibWeb/Rust/src/animations/pending_animation_events.rs
index 414593ae1ce..e70b38fc595 100644
--- a/Libraries/LibWeb/Rust/src/animations/pending_animation_events.rs
+++ b/Libraries/LibWeb/Rust/src/animations/pending_animation_events.rs
@@ -19,7 +19,6 @@ use std::ptr::NonNull;
/// The type of a `TimeEvent` an SVG animation element dispatches.
/// https://svgwg.org/specs/animations/#InterfaceTimeEvent
-#[expect(dead_code, reason = "C++ constructs the variants")]
#[repr(u8)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TimeEventType {
@@ -29,7 +28,6 @@ pub enum TimeEventType {
}
/// Which interface an event of the pending animation event queue is of.
-#[expect(dead_code, reason = "C++ constructs the variants")]
#[repr(u8)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PendingAnimationEventKind {
@@ -114,10 +112,10 @@ impl PendingAnimationEvents {
let mut events_to_dispatch = std::mem::take(&mut self.pending);
// 6. Perform a stable sort of the animation events in events to dispatch as follows:
- // Sort the events by their scheduled event time such that events that were scheduled to occur earlier, sort
- // before events scheduled to occur later and events whose scheduled event time is unresolved sort before
- // events with a resolved scheduled event time.
- // Within events with equal scheduled event times, sort by their composite order.
+ // 1. Sort the events by their scheduled event time such that events that were scheduled to occur earlier
+ // sort before events scheduled to occur later, and events whose scheduled event time is unresolved sort
+ // before events with a resolved scheduled event time.
+ // 2. Within events with equal scheduled event times, sort by their composite order.
// NB: An event of an animation without an associated effect sorts before those of animations with one.
events_to_dispatch.sort_by(|a, b| {
let (a_time, b_time) = (a.event.scheduled_event_time, b.event.scheduled_event_time);
diff --git a/Libraries/LibWeb/Rust/src/animations/procedures.rs b/Libraries/LibWeb/Rust/src/animations/procedures.rs
index 13b54cf6ee5..00efa547844 100644
--- a/Libraries/LibWeb/Rust/src/animations/procedures.rs
+++ b/Libraries/LibWeb/Rust/src/animations/procedures.rs
@@ -10,7 +10,7 @@
//! A procedure changes the records it runs on and records what it asks the host to do as `HostEffects`, in the order
//! its steps ask for them, which the host performs once it has returned.
-use super::animation::{AnimationHandle, AnimationKind, CSS_TRANSITION_PHASE_IDLE, CssAnimationFlag};
+use super::animation::{AnimationHandle, AnimationKind, CssAnimationFlag, TransitionPhase};
use super::composite_order::{TreeOrder, composite_order};
use super::effect::{EffectFlag, EffectHandle};
use super::host_effects::{HostEffectKind, HostEffects, PlaybackEventType};
@@ -154,7 +154,7 @@ impl Procedures<'_> {
}
fn set_auto_align_start_time(&self, value: bool) {
- self.animation.borrow_mut().set_auto_align_start_time(value);
+ self.animation.borrow_mut().auto_align_start_time = value;
}
/// The current time of the timeline, which is unresolved without one or where it is inactive.
@@ -220,7 +220,7 @@ impl Procedures<'_> {
}
/// https://www.w3.org/TR/web-animations-1/#animation-relevant
- fn is_relevant(&self) -> bool {
+ pub(crate) fn is_relevant(&self) -> bool {
let effect_timing = self.effect_timing();
timing::is_relevant(
&self.playback(),
@@ -335,7 +335,7 @@ impl Procedures<'_> {
}
// 7. Make animation’s previous current time unresolved.
- self.animation.borrow_mut().set_previous_current_time(None);
+ self.animation.borrow_mut().previous_current_time = None;
Ok(())
}
@@ -361,7 +361,7 @@ impl Procedures<'_> {
// 4. Cancel the pending pause task.
self.set_has_pending_pause_task(false);
- // 5 Resolve animation’s current ready promise with animation.
+ // 5. Resolve animation’s current ready promise with animation.
self.emit(HostEffectKind::ResolveReadyPromise);
}
@@ -483,7 +483,7 @@ impl Procedures<'_> {
// unresolved time value for the hold time if did seek is false. If did seek is true, the unconstrained
// current time is equal to the current time.
//
- // Note: This is required to accommodate timelines that may change direction. Without this definition, a once-
+ // Note: This is required to accommodate timelines that can change direction. Without this definition, a once-
// finished animation would remain finished even when its timeline progresses in the opposite direction.
let unconstrained_current_time = observed_current_time.or_else(|| match did_seek {
DidSeek::No => self.current_time_without_hold_time(),
@@ -502,9 +502,9 @@ impl Procedures<'_> {
self.update_hold_time_for_finished_state(did_seek, unconstrained_current_time);
}
- // 3. Set the previous current time of animation be the result of calculating its current time.
+ // 3. Set the previous current time of animation to be the result of calculating its current time.
let current_time = self.current_time();
- self.animation.borrow_mut().set_previous_current_time(current_time);
+ self.animation.borrow_mut().previous_current_time = current_time;
// 4. Let current finished state be true if the play state of animation is finished. Otherwise, let it be false.
let current_finished_state = self.play_state() == AnimationPlayState::Finished;
@@ -536,7 +536,7 @@ impl Procedures<'_> {
}
// AD-HOC: An animation disassociated from its target while inert can only be revived through here.
- if let Some(play_state_when_disassociated) = self.animation.borrow().play_state_when_disassociated_from_target()
+ if let Some(play_state_when_disassociated) = self.animation.borrow().play_state_when_disassociated_from_target
&& (self.pending() || self.is_relevant() || self.play_state() != play_state_when_disassociated)
&& let Some(element) = self.effect_target()
{
@@ -545,7 +545,7 @@ impl Procedures<'_> {
// AD-HOC: An animation that has finished without filling produces nothing more, so it leaves its target's list.
if current_finished_state && !self.pending() && !self.is_relevant() {
- self.animation.borrow_mut().set_disassociation_from_target_pending(true);
+ self.animation.borrow_mut().disassociation_from_target_pending = true;
}
if invalidate == Invalidate::Yes {
@@ -556,7 +556,7 @@ impl Procedures<'_> {
/// Step 2 of https://www.w3.org/TR/web-animations-1/#update-an-animations-finished-state
fn update_hold_time_for_finished_state(&self, did_seek: DidSeek, unconstrained_current_time: TimeValue) {
let playback_rate = self.playback_rate();
- let previous_current_time = self.animation.borrow().previous_current_time();
+ let previous_current_time = self.animation.borrow().previous_current_time;
// -> If playback rate > 0 and unconstrained current time is greater than or equal to associated effect end,
let associated_effect_end = self.associated_effect_end();
@@ -595,7 +595,7 @@ impl Procedures<'_> {
// 1. If did seek is true and the hold time is resolved, let animation’s start time be equal to the result
// of evaluating timeline time - (hold time / playback rate) where timeline time is the current time
- // value of timeline associated with animation.
+ // value of the timeline associated with animation.
if did_seek == DidSeek::Yes
&& let Some(hold_time) = self.hold_time()
{
@@ -733,7 +733,7 @@ impl Procedures<'_> {
// 3. Make animation’s start time unresolved.
self.set_start_time(None);
- // This time is needed for dispatching the animationcancel DOM event
+ // NB: This time is needed for dispatching the animationcancel DOM event.
if let Some(timing) = self.effect_timing() {
let timing = AnimationEffectTiming {
fill_mode: FillMode::Both,
@@ -747,12 +747,12 @@ impl Procedures<'_> {
self.timeline.as_ref().map(|timeline| &timeline.sample),
)
.active_time;
- self.animation.borrow_mut().set_saved_cancel_time(active_time);
+ self.animation.borrow_mut().saved_cancel_time = active_time;
}
// AD-HOC: The target's animation list is our own cache of the animations whose effect targets it, and holding a
- // cancelled animation there keeps it alive and walked every frame. It is reassociated if revived.
- self.animation.borrow_mut().set_disassociation_from_target_pending(true);
+ // canceled animation there keeps it alive and walked every frame. It is reassociated if revived.
+ self.animation.borrow_mut().disassociation_from_target_pending = true;
if invalidate == Invalidate::Yes {
self.invalidate_effect();
@@ -899,9 +899,12 @@ impl Procedures<'_> {
self.set_hold_time(Some(self.zero()));
}
- // 7. If has finite timeline and previous current time is unresolved:
+ // 7. If has finite timeline and auto-rewind is true:
+ // 1. Set the flag auto align start time to true.
+ // 2. Set the animation’s hold time to previous current time.
+ // AD-HOC: The flag is set when previous current time is unresolved, whatever auto-rewind is, and the hold time
+ // is left as it is.
if has_finite_timeline && previous_current_time.is_none() {
- // Set the flag auto align start time to true.
self.set_auto_align_start_time(true);
}
@@ -927,7 +930,7 @@ impl Procedures<'_> {
// AD-HOC: We also don't abort if we have a pending auto-alignment of the start time, see
// https://github.com/w3c/csswg-drafts/issues/13236
let pending_auto_aligned_start_time =
- self.animation.borrow().auto_align_start_time() && self.start_time().is_none();
+ self.animation.borrow().auto_align_start_time && self.start_time().is_none();
if self.hold_time().is_none()
&& !aborted_pause
&& self.pending_playback_rate().is_none()
@@ -945,7 +948,7 @@ impl Procedures<'_> {
// 12. Schedule a task to run as soon as animation is ready. The task shall perform the following steps:
//
- // Note: Steps omitted, see run_pending_play_task()
+ // NB: The steps of the task are in run_pending_play_task().
//
// So long as the above task is scheduled but has yet to run, animation is described as having a pending
// play task. While the task is running, however, animation does not have a pending play task.
@@ -982,7 +985,7 @@ impl Procedures<'_> {
let has_finite_timeline = self.has_finite_timeline();
// 5. If the animation’s current time is unresolved, perform the steps according to the first matching
- // condition from below:
+ // condition below:
if self.current_time().is_none() {
// -> If animation’s playback rate is ≥ 0,
if self.playback_rate() >= 0.0 {
@@ -1037,8 +1040,7 @@ impl Procedures<'_> {
// 10. Schedule a task to be executed at the first possible moment where both of the following conditions are
// true:
- // NB: Criteria has been listed out in is_ready_to_run_pending_pause_task()
- // NB: This is run_pending_pause_task()
+ // NB: is_ready_to_run_pending_pause_task() checks these conditions, and run_pending_pause_task() is the task.
self.set_has_pending_pause_task(true);
// 11. Run the procedure to update an animation’s finished state for animation with the did seek flag set to
@@ -1182,7 +1184,7 @@ impl Procedures<'_> {
return None;
};
let may_run_on_the_compositor = animation.effect()?.borrow().may_run_on_the_compositor();
- if !may_run_on_the_compositor || transition.previous_phase != CSS_TRANSITION_PHASE_IDLE {
+ if !may_run_on_the_compositor || transition.previous_phase != TransitionPhase::Idle {
return None;
}
Some(TimeValue::milliseconds(
@@ -1354,7 +1356,7 @@ impl Procedures<'_> {
let Some(interval) = self.timeline.as_ref().and_then(TimelineState::attachment_interval) else {
return;
};
- if self.animation.borrow().normalized_attachment_interval() == Some(interval) {
+ if self.animation.borrow().normalized_attachment_interval == Some(interval) {
return;
}
self.normalize_effect_timing();
@@ -1366,7 +1368,7 @@ impl Procedures<'_> {
fn normalize_effect_timing(&self) {
let interval = self.timeline.as_ref().and_then(TimelineState::attachment_interval);
let mut animation = self.animation.borrow_mut();
- animation.set_normalized_attachment_interval(interval);
+ animation.normalized_attachment_interval = interval;
if let Some(effect) = animation.effect() {
effect.borrow_mut().normalize_specified_timing(self.timeline.as_ref());
}
@@ -1381,7 +1383,7 @@ impl Procedures<'_> {
);
// 1. If the auto-align start time flag is false, abort this procedure.
- if !self.animation.borrow().auto_align_start_time() {
+ if !self.animation.borrow().auto_align_start_time {
return;
}
@@ -1458,8 +1460,8 @@ impl Procedures<'_> {
let is_monotonically_increasing = timeline.sample.is_monotonically_increasing;
- // Prevent unnecessary work if the animation is already finished and can't exit the finished state due to
- // timeline changes
+ // NB: Prevent unnecessary work if the animation is already finished and can't exit the finished state due to
+ // timeline changes.
let was_finished = self.playback().is_finished;
if !was_finished || !is_monotonically_increasing {
self.update_finished_state(DidSeek::No, SynchronouslyNotify::Yes, Invalidate::No, None);
@@ -1475,7 +1477,7 @@ impl Procedures<'_> {
}
}
- // Act on the pending play or pause task
+ // NB: Act on the pending play or pause task.
self.run_pending_play_task_if_ready();
if self.playback().has_pending_pause_task && self.is_ready_to_run_pending_pause_task() {
@@ -1776,9 +1778,7 @@ impl Procedures<'_> {
/// AD-HOC: The target's animation list is our own cache of the animations whose effect targets it, which an
/// animation that produces nothing leaves until it is revived.
pub(crate) fn disassociate_from_target_if_inert(&mut self) {
- self.animation
- .borrow_mut()
- .set_disassociation_from_target_pending(false);
+ self.animation.borrow_mut().disassociation_from_target_pending = false;
// NB: Script may have revived the animation since the disassociation was scheduled.
let Some(effect) = self.animation.borrow().effect().cloned() else {
return;
@@ -1794,9 +1794,7 @@ impl Procedures<'_> {
effect: effect.clone(),
});
let play_state = self.play_state();
- self.animation
- .borrow_mut()
- .set_play_state_when_disassociated_from_target(Some(play_state));
+ self.animation.borrow_mut().play_state_when_disassociated_from_target = Some(play_state);
// NB: The target's animated style keeps the effect's values until they are recomputed without it.
self.emit(HostEffectKind::RecomputeEffectStyle { effect });
}
@@ -1927,7 +1925,9 @@ impl Procedures<'_> {
fn note_script_play_state_override(&self) {
let mut animation = self.animation.borrow_mut();
if let AnimationKind::CssAnimation(_) = animation.kind() {
- animation.css_animation_mut().flags |= CssAnimationFlag::ScriptOverrodePlayState as u8;
+ animation
+ .css_animation_mut()
+ .set_flag(CssAnimationFlag::ScriptOverrodePlayState);
}
}
@@ -2181,56 +2181,6 @@ mod tests {
.kinds()
}
- fn play_state(animation: &AnimationHandle, timeline: &TimelineState) -> AnimationPlayState {
- run_on(animation, Some(*timeline), |procedures| Ok(procedures.play_state()))
- .unwrap()
- .0
- }
-
- #[test]
- fn playing_waits_for_the_pending_play_task_to_start() {
- let timeline = document_timeline_at(100.0);
- let animation = one_second_animation(AnimationKind::Script, &timeline);
-
- let kinds = kinds_of(&animation, &timeline, |procedures| procedures.play(Invalidate::No));
- assert!(kinds.contains(&HostEffectKind::ReplaceReadyPromise));
- assert!(animation.borrow().playback().has_pending_play_task);
- assert_eq!(play_state(&animation, &timeline), AnimationPlayState::Running);
-
- let timeline = document_timeline_at(250.0);
- let kinds = kinds_of(&animation, &timeline, |procedures| {
- procedures.run_pending_play_task_if_ready();
- Ok(())
- });
- assert!(kinds.contains(&HostEffectKind::ResolveReadyPromise));
- let playback = *animation.borrow().playback();
- assert!(!playback.has_pending_play_task);
- assert_eq!(playback.start_time.get(), Some(TimeValue::milliseconds(250.0)));
- assert_eq!(playback.hold_time.get(), None);
- }
-
- #[test]
- fn finishing_notifies_synchronously() {
- let timeline = document_timeline_at(0.0);
- let animation = one_second_animation(AnimationKind::Script, &timeline);
- kinds_of(&animation, &timeline, |procedures| procedures.play(Invalidate::No));
-
- let kinds = kinds_of(&animation, &timeline, |procedures| procedures.finish_an_animation());
- let resolve = kinds
- .iter()
- .position(|kind| *kind == HostEffectKind::ResolveFinishedPromise)
- .expect("finishing resolves the finished promise");
- assert!(matches!(
- kinds[resolve + 1],
- HostEffectKind::QueuePlaybackEvent {
- r#type: PlaybackEventType::Finish,
- current_time: Some(time),
- ..
- } if time == TimeValue::milliseconds(1000.0)
- ));
- assert_eq!(play_state(&animation, &timeline), AnimationPlayState::Finished);
- }
-
#[test]
fn finishing_an_animation_at_rate_zero_throws() {
let timeline = document_timeline_at(0.0);
@@ -2242,53 +2192,6 @@ mod tests {
assert!(matches!(result, Err(AnimationError::InvalidState(_))));
}
- #[test]
- fn pausing_while_play_pending_keeps_the_ready_promise() {
- let timeline = document_timeline_at(0.0);
- let animation = one_second_animation(AnimationKind::Script, &timeline);
- kinds_of(&animation, &timeline, |procedures| procedures.play(Invalidate::No));
-
- let kinds = kinds_of(&animation, &timeline, |procedures| procedures.pause());
- assert!(!kinds.contains(&HostEffectKind::ReplaceReadyPromise));
- let playback = *animation.borrow().playback();
- assert!(!playback.has_pending_play_task);
- assert!(playback.has_pending_pause_task);
- assert_eq!(play_state(&animation, &timeline), AnimationPlayState::Paused);
- }
-
- #[test]
- fn cancelling_rejects_ready_then_finished_promise_then_queues_cancel() {
- let timeline = document_timeline_at(0.0);
- let animation = one_second_animation(AnimationKind::Script, &timeline);
- kinds_of(&animation, &timeline, |procedures| procedures.play(Invalidate::No));
-
- let kinds = kinds_of(&animation, &timeline, |procedures| {
- procedures.cancel(Invalidate::No);
- Ok(())
- });
- assert_eq!(
- kinds,
- [
- HostEffectKind::RejectReadyPromise,
- HostEffectKind::RejectFinishedPromise,
- HostEffectKind::QueuePlaybackEvent {
- r#type: PlaybackEventType::Cancel,
- current_time: None,
- timeline_time: Some(TimeValue::milliseconds(0.0)),
- scheduled_timeline_time: Some(TimeValue::milliseconds(0.0)),
- },
- ]
- );
- assert_eq!(play_state(&animation, &timeline), AnimationPlayState::Idle);
-
- // Cancelling an idle animation does nothing observable.
- let kinds = kinds_of(&animation, &timeline, |procedures| {
- procedures.cancel(Invalidate::No);
- Ok(())
- });
- assert!(kinds.is_empty());
- }
-
#[test]
fn reversing_without_an_active_timeline_throws() {
let timeline = document_timeline_at(0.0);
@@ -2298,24 +2201,13 @@ mod tests {
}
fn script_overrode_play_state(animation: &AnimationHandle) -> bool {
- let mut animation = animation.borrow_mut();
- animation.css_animation_mut().flags & CssAnimationFlag::ScriptOverrodePlayState as u8 != 0
+ animation
+ .borrow()
+ .css_animation()
+ .has_flag(CssAnimationFlag::ScriptOverrodePlayState)
}
// https://drafts.csswg.org/css-animations-2/#animations
- #[test]
- fn script_changing_the_play_state_overrides_animation_play_state() {
- let timeline = document_timeline_at(0.0);
- let animation = one_second_animation(css_animation(), &timeline);
-
- kinds_of(&animation, &timeline, |procedures| procedures.play_from_css());
- kinds_of(&animation, &timeline, |procedures| procedures.pause_from_css());
- assert!(!script_overrode_play_state(&animation));
-
- // Playing a paused animation changes its play state.
- kinds_of(&animation, &timeline, |procedures| procedures.play(Invalidate::No));
- assert!(script_overrode_play_state(&animation));
- }
#[test]
fn script_playing_a_running_css_animation_does_not_override_animation_play_state() {
@@ -2364,19 +2256,6 @@ mod tests {
assert!(kinds.is_empty());
}
- #[test]
- fn unsetting_the_effect_recomputes_the_style_it_applied() {
- let timeline = document_timeline_at(0.0);
- let animation = one_second_animation(AnimationKind::Script, &timeline);
- let effect = animation.borrow().effect().cloned().unwrap();
- let kinds = kinds_of(&animation, &timeline, |procedures| {
- procedures.set_the_associated_effect(None, Invalidate::No);
- Ok(())
- });
- assert_eq!(kinds, [HostEffectKind::RecomputeEffectStyle { effect }]);
- assert!(animation.borrow().effect().is_none());
- }
-
#[test]
fn removing_an_animation_disassociates_it_from_its_timeline_until_persisted() {
let dangling = NonNull::<u8>::dangling().cast::<c_void>();
@@ -2388,7 +2267,7 @@ mod tests {
);
let animation = one_second_animation(AnimationKind::Script, &document_timeline_at(0.0));
// NB: A set of animations holds only the animations whose host `Animation` is alive.
- animation.set_facade(Some(dangling));
+ animation.set_object_cell(Some(dangling));
let associated = || timeline.associated_animations().borrow().contains(&animation);
run(&animation, |procedures| {
procedures.set_timeline(Some(timeline.clone()));
@@ -2415,48 +2294,6 @@ mod tests {
}
}
- #[test]
- fn an_inert_animation_leaves_its_target_until_it_is_associated_again() {
- let timeline = document_timeline_at(0.0);
- let animation = one_second_animation(AnimationKind::Script, &timeline);
- let effect = animation.borrow().effect().cloned().unwrap();
- let element = NonNull::<u8>::dangling().cast::<c_void>();
- effect.borrow_mut().set_target_element(Some(element));
-
- // An idle animation is not relevant.
- let kinds = kinds_of(&animation, &timeline, |procedures| {
- procedures.disassociate_from_target_if_inert();
- Ok(())
- });
- assert_eq!(
- kinds,
- [
- HostEffectKind::DisassociateFromTarget {
- element,
- effect: effect.clone()
- },
- HostEffectKind::RecomputeEffectStyle { effect }
- ]
- );
- assert_eq!(
- animation.borrow().play_state_when_disassociated_from_target(),
- Some(AnimationPlayState::Idle)
- );
-
- animation.borrow_mut().did_associate_with_target();
- assert_eq!(animation.borrow().play_state_when_disassociated_from_target(), None);
- assert!(animation.borrow().disassociation_from_target_pending());
-
- // A playing animation is relevant, so it stays.
- kinds_of(&animation, &timeline, |procedures| procedures.play(Invalidate::No));
- let kinds = kinds_of(&animation, &timeline, |procedures| {
- procedures.disassociate_from_target_if_inert();
- Ok(())
- });
- assert!(kinds.is_empty());
- assert!(!animation.borrow().disassociation_from_target_pending());
- }
-
/// A finished script animation on `timeline`, which runs from time zero, whose one second effect targets `target`,
/// fills forwards and animates `properties`.
fn finished_animation(timeline: &TimelineHandle, target: NonNull<c_void>, properties: &[u16]) -> AnimationHandle {
@@ -2499,7 +2336,7 @@ mod tests {
None,
))));
// NB: A set of animations holds only the animations whose host `Animation` is alive.
- animation.set_facade(Some(NonNull::<u8>::dangling().cast()));
+ animation.set_object_cell(Some(NonNull::<u8>::dangling().cast()));
animation.borrow_mut().playback_mut().start_time = Some(TimeValue::milliseconds(0.0)).into();
run(&animation, |procedures| {
procedures.set_timeline(Some(timeline.clone()));
diff --git a/Libraries/LibWeb/Rust/src/animations/provisional_transitions.rs b/Libraries/LibWeb/Rust/src/animations/provisional_transitions.rs
new file mode 100644
index 00000000000..20208254a8a
--- /dev/null
+++ b/Libraries/LibWeb/Rust/src/animations/provisional_transitions.rs
@@ -0,0 +1,146 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The transition actions a style stabilization epoch decides, which stay provisional until the epoch commits.
+//! https://drafts.csswg.org/css-transitions/#starting
+
+use super::animation::{AnimationHandle, HostCellKind};
+use super::effect::AnimationEffectCell;
+use super::element_animations::{AnimationOwnerSlot, ElementAnimations, TransitionProperty};
+use crate::css::retained_fly_string::RetainedUtf16FlyString;
+use crate::css::transition::FfiTransitionActionKind;
+use smallvec::SmallVec;
+use std::collections::HashMap;
+use std::ffi::c_void;
+use std::ptr::NonNull;
+
+/// The element, or one of its pseudo-elements, whose transitions a transition step decides.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
+pub(crate) struct TransitionTarget {
+ pub(crate) element: NonNull<c_void>,
+ /// The host's `PseudoElement`, where the target is a pseudo-element.
+ pub(crate) pseudo_element: Option<u8>,
+}
+
+/// What the epoch decided so far for the transitions of one property of one target.
+pub(crate) struct ProvisionalTransitionState {
+ pub(crate) target: TransitionTarget,
+ /// The lists of the target's element, which the element owns for as long as it lives, and the slot of the target
+ /// in them, where it can own transitions.
+ pub(crate) animations: NonNull<ElementAnimations>,
+ pub(crate) slot: Option<AnimationOwnerSlot>,
+ pub(crate) property: TransitionProperty,
+ /// The name of a custom property, which the state keys on by its raw fly string, kept alive with the state.
+ _custom_name: RetainedUtf16FlyString,
+ /// The transition of the property the target held as the epoch first decided over it.
+ pub(crate) committed: Option<AnimationHandle>,
+ /// The transition the latest decision started provisionally, if any.
+ pub(crate) proposed: Option<AnimationHandle>,
+ pub(crate) action: FfiTransitionActionKind,
+ pub(crate) has_decision: bool,
+}
+
+/// The provisional transition states of a document's current style stabilization epoch, in the order the epoch first
+/// decided over each.
+#[derive(Default)]
+pub(crate) struct ProvisionalTransitions {
+ states: Vec<ProvisionalTransitionState>,
+ by_property: HashMap<(TransitionTarget, TransitionProperty), usize>,
+ by_target: HashMap<TransitionTarget, SmallVec<[usize; 2]>>,
+}
+
+impl ProvisionalTransitions {
+ pub(crate) fn is_empty(&self) -> bool {
+ self.states.is_empty()
+ }
+
+ pub(crate) fn has_states(&self, target: TransitionTarget) -> bool {
+ self.by_target.contains_key(&target)
+ }
+
+ /// The indices of the states of `target`.
+ pub(crate) fn indices_of(&self, target: TransitionTarget) -> SmallVec<[usize; 2]> {
+ self.by_target.get(&target).cloned().unwrap_or_default()
+ }
+
+ pub(crate) fn state_mut(&mut self, index: usize) -> &mut ProvisionalTransitionState {
+ &mut self.states[index]
+ }
+
+ pub(crate) fn state(&self, index: usize) -> &ProvisionalTransitionState {
+ &self.states[index]
+ }
+
+ /// The index of the state of `property` of `target`, created with the transition of the property its lists
+ /// `animations` hold at `slot` as the committed one where the epoch did not decide over it yet.
+ ///
+ /// # Safety
+ /// `animations` must be the lists of the target's element.
+ pub(crate) unsafe fn ensure(
+ &mut self,
+ target: TransitionTarget,
+ animations: NonNull<ElementAnimations>,
+ slot: Option<AnimationOwnerSlot>,
+ property: TransitionProperty,
+ ) -> usize {
+ if let Some(&index) = self.by_property.get(&(target, property)) {
+ return index;
+ }
+ let index = self.states.len();
+ // SAFETY: Guaranteed by the caller.
+ let committed = slot.and_then(|slot| unsafe { animations.as_ref() }.transition(slot, property).cloned());
+ self.states.push(ProvisionalTransitionState {
+ target,
+ animations,
+ slot,
+ property,
+ // SAFETY: The name is a live fly string the step decides over, or zero.
+ _custom_name: unsafe { RetainedUtf16FlyString::from_borrowed_raw(property.custom_name) },
+ committed,
+ proposed: None,
+ action: FfiTransitionActionKind::None,
+ has_decision: false,
+ });
+ self.by_property.insert((target, property), index);
+ self.by_target.entry(target).or_default().push(index);
+ index
+ }
+
+ pub(crate) fn len(&self) -> usize {
+ self.states.len()
+ }
+
+ /// The effect of the transition at `index` among those the epoch started provisionally for `target`, which the
+ /// transition holds for as long as the epoch holds it, or null past the last.
+ pub(crate) fn proposed_effect(&self, target: TransitionTarget, index: usize) -> *const AnimationEffectCell {
+ self.by_target
+ .get(&target)
+ .into_iter()
+ .flatten()
+ .filter_map(|&state| self.states[state].proposed.as_ref())
+ .filter_map(|transition| transition.borrow().effect().map(|effect| &raw const **effect))
+ .nth(index)
+ .unwrap_or(std::ptr::null())
+ }
+
+ /// Takes every state, as the epoch commits.
+ pub(crate) fn take(&mut self) -> Vec<ProvisionalTransitionState> {
+ self.by_property.clear();
+ self.by_target.clear();
+ std::mem::take(&mut self.states)
+ }
+
+ /// Calls `visit` with each GC cell of the host the states keep alive: the elements they decide over and what keeps
+ /// alive what their transitions name.
+ pub(crate) fn for_each_host_cell(&self, mut visit: impl FnMut(NonNull<c_void>, HostCellKind)) {
+ for state in &self.states {
+ visit(state.target.element, HostCellKind::Element);
+ for transition in state.committed.iter().chain(state.proposed.iter()) {
+ transition.for_each_host_cell(&mut visit);
+ }
+ }
+ }
+}
diff --git a/Libraries/LibWeb/Rust/src/animations/rendering_trace.rs b/Libraries/LibWeb/Rust/src/animations/rendering_trace.rs
new file mode 100644
index 00000000000..fc7a8edcdcd
--- /dev/null
+++ b/Libraries/LibWeb/Rust/src/animations/rendering_trace.rs
@@ -0,0 +1,23 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The rendering trace of the event loop, which notes the animation work of its documents as it happens.
+
+unsafe extern "C" {
+ fn web_animation_note_rendering_trace_event(event: *const u8, length: usize);
+}
+
+/// Notes `event` in the rendering trace of the event loop, where a trace is being taken.
+pub(crate) fn note_rendering_trace_event(event: &str) {
+ // SAFETY: The event is live for the call.
+ unsafe { web_animation_note_rendering_trace_event(event.as_ptr(), event.len()) };
+}
+
+#[cfg(test)]
+mod ffi_test_stubs {
+ #[unsafe(no_mangle)]
+ extern "C" fn web_animation_note_rendering_trace_event(_event: *const u8, _length: usize) {}
+}
diff --git a/Libraries/LibWeb/Rust/src/animations/rendering_update.rs b/Libraries/LibWeb/Rust/src/animations/rendering_update.rs
new file mode 100644
index 00000000000..44f4d5cf736
--- /dev/null
+++ b/Libraries/LibWeb/Rust/src/animations/rendering_update.rs
@@ -0,0 +1,454 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! What the animated style updates and the rendering updates of a document decide of the animations associated with
+//! it.
+
+use super::animation::{AnimationCell, AnimationHandle};
+use super::composite_order::composite_order;
+use super::compositor_update::{
+ next_throttled_animation_iteration_event_time, request_observation_sample, set_needs_animated_style_update,
+};
+use super::document_animations::{DocumentAnimationSetKind, DocumentAnimations};
+use super::effect::{AnimationEffectCell, EffectFlag, EffectHandle, ObservationSampleRequest};
+use super::element_animations::ElementAnimations;
+use super::ffi::{
+ FfiKeepAlive, HostEffectPerformer, host_tree_order, run_procedure, web_animation_compare_elements_in_tree_order,
+};
+use super::host_timing::FfiAnimationKind;
+use super::throttling::{can_skip_per_frame_animation_tick, can_skip_per_frame_style_update};
+use super::timing::{AnimationPlayState, OptionalNumber, TimeValueType};
+use std::ffi::c_void;
+
+/// What sampling the effects that need an animated style update of a document asks of the host, which hands each
+/// function `context`.
+#[repr(C)]
+pub struct FfiAnimatedStyleSampleHost {
+ pub context: *mut c_void,
+ pub keep_alive: FfiKeepAlive,
+ /// Readies the host to sample the effects.
+ pub begin: unsafe extern "C" fn(context: *mut c_void),
+ /// Samples `effect` into the style of its target.
+ pub update: unsafe extern "C" fn(context: *mut c_void, effect: &AnimationEffectCell),
+ /// Has the host publish what it sampled.
+ pub end: unsafe extern "C" fn(context: *mut c_void),
+}
+
+/// What sampling the effects that need an animated style update of a document found.
+#[repr(C)]
+pub struct FfiAnimatedStyleSampleOutcome {
+ /// Whether there were any effects to sample.
+ pub sampled: bool,
+ /// Whether an effect that can skip its per-frame style update was left unsampled.
+ pub has_throttled_animation_style_update: bool,
+}
+
+/// Samples the effects whose animated style a document's next animated style update samples, in the composite order
+/// of their animations, or, where `force_throttled`, those of every animation associated with it that is not idle,
+/// and the idle ones that need it, skipping those that can skip their per-frame style update and that no observation
+/// asked for unless `force_throttled`. `has_throttled` is whether an earlier update left a throttled effect unsampled.
+///
+/// # Safety
+/// `animations` must be what a live document knows of animations, which the host may reach as it samples.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn animations_document_animations_sample_effects_needing_style_update(
+ animations: *mut DocumentAnimations,
+ force_throttled: bool,
+ has_throttled: bool,
+ host: &FfiAnimatedStyleSampleHost,
+) -> FfiAnimatedStyleSampleOutcome {
+ let mut effects: Vec<(AnimationHandle, EffectHandle)> = Vec::new();
+ {
+ // SAFETY: Guaranteed by the caller, and the borrow ends before the host is called.
+ let animations = unsafe { &mut *animations };
+ if force_throttled {
+ for animation in animations.associated_animations() {
+ let Some(effect) = animation.borrow().effect().cloned() else {
+ continue;
+ };
+ // NB: Dirty idle effects still need to remove their last sampled values after cancellation.
+ if animation.borrow().play_state() == AnimationPlayState::Idle
+ && !animations.needing_animated_style_update().contains(&effect)
+ {
+ continue;
+ }
+ effects.push((animation, effect));
+ }
+ animations.needing_animated_style_update().take_each(|_| {});
+ } else {
+ animations.needing_animated_style_update().take_each(|effect| {
+ // NB: A canceled animation still needs to remove its last sampled values.
+ if let Some(animation) = effect.borrow().associated_animation() {
+ effects.push((animation, effect.clone()));
+ }
+ });
+ }
+ }
+
+ if effects.is_empty() {
+ // A compositor-driven effect can remain throttled when every dirty effect was canceled before this sample.
+ // Preserve the flag so a later style or geometry read can still request a current main-thread sample.
+ return FfiAnimatedStyleSampleOutcome {
+ sampled: false,
+ has_throttled_animation_style_update: has_throttled,
+ };
+ }
+
+ // NB: The effects stay alive for as long as the update holds them.
+ for (animation, _) in &effects {
+ // SAFETY: The host keeps alive an animation it is handed for as long as this call lasts.
+ unsafe { (host.keep_alive)(host.context, animation) };
+ }
+
+ let has_requested_observation_sample = effects
+ .iter()
+ .any(|(_, effect)| effect.borrow().has_flag(EffectFlag::NeedsObservationSample));
+
+ // A timeline script observed ahead of its current time in this task is sampled at that time too, so that a style
+ // read agrees with the time script read, however many reads the task makes. Where an observation asked for the
+ // sample, all of them are.
+ DocumentAnimations::at_observed_times(animations, force_throttled || has_requested_observation_sample, || {
+ // SAFETY: The host answers synchronously.
+ unsafe { (host.begin)(host.context) };
+ // SAFETY: As above.
+ let has_throttled_animation_style_update =
+ unsafe { sample_effects_in_composite_order(effects, force_throttled, has_throttled, host) };
+ // SAFETY: As above.
+ unsafe { (host.end)(host.context) };
+ FfiAnimatedStyleSampleOutcome {
+ sampled: true,
+ has_throttled_animation_style_update,
+ }
+ })
+}
+
+/// Samples `effects` through `host` in the composite order of their animations, answering whether an effect that can
+/// skip its per-frame style update was left unsampled.
+///
+/// # Safety
+/// The host must sample synchronously.
+unsafe fn sample_effects_in_composite_order(
+ mut effects: Vec<(AnimationHandle, EffectHandle)>,
+ force_throttled: bool,
+ has_throttled: bool,
+ host: &FfiAnimatedStyleSampleHost,
+) -> bool {
+ let mut tree_order = host_tree_order(web_animation_compare_elements_in_tree_order);
+ effects.sort_by(|(a, _), (b, _)| {
+ if a.ptr_eq(b) {
+ return std::cmp::Ordering::Equal;
+ }
+ composite_order(&a.borrow(), &b.borrow(), &mut tree_order)
+ });
+
+ let mut has_throttled_animation_style_update = !force_throttled && has_throttled;
+ for (_, effect) in &effects {
+ let observation_sample_requested = effect.borrow_mut().set_flag(EffectFlag::NeedsObservationSample, false);
+ if can_skip_per_frame_style_update(effect) {
+ has_throttled_animation_style_update = true;
+ if !force_throttled && !observation_sample_requested {
+ continue;
+ }
+ }
+ // SAFETY: The host answers synchronously, and the effect stays alive through the call.
+ unsafe { (host.update)(host.context, effect) };
+ }
+ has_throttled_animation_style_update
+}
+
+/// A change of the sets of the effects a document's animated style updates sample.
+#[expect(dead_code, reason = "C++ constructs the variants")]
+#[repr(u8)]
+#[derive(Clone, Copy)]
+pub enum EffectSetsChange {
+ /// Sets aside the effects the next animated style update samples while the transaction of a style update that
+ /// flew drains.
+ SetAside,
+ /// Restores the effects set aside.
+ Restore,
+ /// Forgets the effects the next animated style update samples, and those to ask for an observation sample.
+ Clear,
+ /// Asks for an observation sample of each effect that asked for one while the animated style update that finishes
+ /// ran.
+ FinishUpdate,
+}
+
+/// Makes `change` to the sets of the effects the animated style updates of a document sample.
+///
+/// # Safety
+/// `animations` must be what a live document knows of animations, which the host may reach as it is asked for
+/// samples.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn animations_document_animations_change_effect_sets(
+ animations: *mut DocumentAnimations,
+ change: EffectSetsChange,
+) {
+ // SAFETY: Guaranteed by the caller, and the borrow ends before the host is called.
+ let document = unsafe { &mut *animations };
+ match change {
+ EffectSetsChange::SetAside => document.set_aside_effects_needing_animated_style_update(false),
+ EffectSetsChange::Restore => document.set_aside_effects_needing_animated_style_update(true),
+ EffectSetsChange::Clear => {
+ document.needing_animated_style_update().take_each(|_| {});
+ document
+ .needing_animated_style_update_after_current_update()
+ .take_each(|_| {});
+ }
+ EffectSetsChange::FinishUpdate => {
+ let mut effects = Vec::new();
+ document
+ .needing_animated_style_update_after_current_update()
+ .take_each(|effect| effects.push(effect.clone()));
+ for effect in &effects {
+ request_observation_sample(effect);
+ }
+ }
+ }
+}
+
+/// Asks for an observation sample of each effect of the animations associated with an element, whose lists
+/// `element` are, on behalf of a read of its style or layout in the task of generation `task_generation`: those
+/// the next animated style update of the document samples anyway, unless `is_updating_animated_style`, and those that
+/// can skip their per-frame style update, after the current update where `is_updating_animated_style`, and once per
+/// task otherwise.
+///
+/// # Safety
+/// `document` must be what the live document of the element knows of animations, which the host may reach as it is
+/// asked for samples.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn animations_element_animations_request_observation_samples(
+ element: &ElementAnimations,
+ document: *mut DocumentAnimations,
+ is_updating_animated_style: bool,
+ task_generation: u64,
+) {
+ let effects: Vec<EffectHandle> = element
+ .associated()
+ .iter()
+ .filter_map(|animation| animation.borrow().effect().cloned())
+ .collect();
+ for effect in &effects {
+ // NB: An effect that changed since it was last sampled, such as one script seeked after an earlier read in
+ // this task, is sampled for the read whether or not it can skip per-frame style updates now: the sample
+ // decides that again, from a layout that may have moved since.
+ // SAFETY: Guaranteed by the caller; the borrow ends before the host is called.
+ if !is_updating_animated_style
+ && unsafe { &mut *document }
+ .needing_animated_style_update()
+ .contains(effect)
+ {
+ request_observation_sample(effect);
+ continue;
+ }
+ if !can_skip_per_frame_style_update(effect) {
+ continue;
+ }
+ if is_updating_animated_style {
+ // SAFETY: Guaranteed by the caller.
+ unsafe { &mut *document }
+ .needing_animated_style_update_after_current_update()
+ .insert(effect);
+ continue;
+ }
+ let request = effect.borrow_mut().request_observation_sample_in_task(task_generation);
+ if request == ObservationSampleRequest::NewlyRequested {
+ set_needs_animated_style_update(effect);
+ }
+ }
+}
+
+/// Something a document asks of the animations associated with it.
+#[expect(dead_code, reason = "C++ constructs the variants")]
+#[repr(u8)]
+#[derive(Clone, Copy)]
+pub enum DocumentAnimationsQuery {
+ /// The number of the animations associated with the document.
+ AssociatedCount,
+ /// Whether the associated effect of one of them can skip its per-frame style update, as one or zero.
+ AnyCanSkipPerFrameStyleUpdate,
+ /// Whether a scroll timeline is associated with the document, as one or zero.
+ AnyScrollTimeline,
+}
+
+/// Answers `query` of the animations associated with a document.
+///
+/// # Safety
+/// `animations` must be what a live document knows of animations.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn animations_document_animations_query(
+ animations: *mut DocumentAnimations,
+ query: DocumentAnimationsQuery,
+) -> usize {
+ // SAFETY: Guaranteed by the caller, and the borrow ends before the host is called.
+ let document = unsafe { &mut *animations };
+ match query {
+ DocumentAnimationsQuery::AssociatedCount => {
+ document.set_mut(DocumentAnimationSetKind::Associated).iter().count()
+ }
+ DocumentAnimationsQuery::AnyCanSkipPerFrameStyleUpdate => usize::from(
+ document
+ .set_mut(DocumentAnimationSetKind::Associated)
+ .iter()
+ .any(|animation| {
+ let effect = animation.borrow().effect().cloned();
+ effect.is_some_and(|effect| can_skip_per_frame_style_update(&effect))
+ }),
+ ),
+ DocumentAnimationsQuery::AnyScrollTimeline => usize::from(
+ document
+ .timelines
+ .iter()
+ .any(|timeline| timeline.borrow().scroll().is_some()),
+ ),
+ }
+}
+
+/// What keeps the rendering updates of a document coming while its animations run.
+#[repr(C)]
+pub struct FfiAnimationFramePump {
+ /// The delay after which the next iteration event of a throttled CSS animation is due, where one is.
+ pub wakeup_delay: OptionalNumber,
+ /// Whether an animation needs the next rendering update.
+ pub request_frame: bool,
+}
+
+/// Decides how the running animations associated with a document of a monotonically increasing timeline keep its
+/// rendering updates coming: by asking for the next where one needs main-thread painting or observable animation
+/// events, or by waking up as the next iteration event of a throttled CSS animation is due, noting of each effect
+/// whether a frame skipped its tick.
+///
+/// # Safety
+/// `animations` must be what a live document knows of animations.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn animations_document_animations_frame_pump(
+ animations: *mut DocumentAnimations,
+) -> FfiAnimationFramePump {
+ // SAFETY: Guaranteed by the caller, and the borrow ends before the host is called.
+ let associated = unsafe { &mut *animations }.associated_animations();
+ let mut wakeup_delay: Option<f64> = None;
+ for animation in &associated {
+ let effect = {
+ let record = animation.borrow();
+ if !record.has_monotonically_increasing_timeline() || record.play_state() != AnimationPlayState::Running {
+ continue;
+ }
+ record.effect().cloned()
+ };
+ if let Some(effect) = effect {
+ if can_skip_per_frame_animation_tick(&effect) {
+ effect
+ .borrow_mut()
+ .set_flag(EffectFlag::PerFrameAnimationTickWasSkipped, true);
+ continue;
+ }
+ effect
+ .borrow_mut()
+ .set_flag(EffectFlag::PerFrameAnimationTickWasSkipped, false);
+ let state = animation.borrow().timing_state(None);
+ if let Some(iteration_event_time) = next_throttled_animation_iteration_event_time(&state, &effect)
+ && let Some(current_time) = state.current_time.get()
+ && current_time.r#type == TimeValueType::Milliseconds
+ {
+ let delay = (iteration_event_time - current_time.value) / state.playback.playback_rate;
+ if delay > 0.0 {
+ wakeup_delay = Some(wakeup_delay.map_or(delay, |earliest| earliest.min(delay)));
+ continue;
+ }
+ }
+ }
+ return FfiAnimationFramePump {
+ wakeup_delay: wakeup_delay.into(),
+ request_frame: true,
+ };
+ }
+ FfiAnimationFramePump {
+ wakeup_delay: wakeup_delay.into(),
+ request_frame: false,
+ }
+}
+
+/// Whether `animation` is a CSS animation or transition that the style of a rendering update began, which the update
+/// makes ready once its style and layout are done.
+fn rendering_update_makes_ready(animation: &AnimationCell) -> bool {
+ let record = animation.borrow();
+ let Some(effect) = record.effect() else {
+ return false;
+ };
+ let playback = record.playback();
+ (playback.has_pending_play_task || playback.has_pending_pause_task)
+ && matches!(
+ record.ffi_kind(),
+ FfiAnimationKind::CssAnimation | FfiAnimationKind::CssTransition
+ )
+ && !effect.borrow().may_run_on_the_compositor()
+}
+
+/// Runs the pending play tasks of the CSS animations and transitions associated with the timelines of a document whose
+/// animations are `animations` that the style of a rendering update began, which the update makes ready once its style
+/// and layout are done, having the host keep each alive through `keep_alive` with `context`.
+///
+/// # Safety
+/// `animations` must be what a live document knows of animations, and `keep_alive` must keep alive an animation it is
+/// handed with `context` for as long as the call lasts.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn animations_document_run_pending_css_play_tasks(
+ animations: *mut DocumentAnimations,
+ context: *mut c_void,
+ keep_alive: FfiKeepAlive,
+ perform: HostEffectPerformer,
+) {
+ // SAFETY: Guaranteed by the caller, and the borrow ends here.
+ let timelines = unsafe { &*animations }.timelines.clone();
+ let mut pending: Vec<AnimationHandle> = Vec::new();
+ for timeline in &timelines {
+ let associated = timeline.associated_animations().borrow();
+ pending.extend(
+ associated
+ .iter()
+ .filter(|animation| rendering_update_makes_ready(animation)),
+ );
+ }
+ for animation in &pending {
+ // SAFETY: Guaranteed by the caller.
+ unsafe { keep_alive(context, animation) };
+ }
+ for animation in &pending {
+ run_procedure(animation, perform, |procedures| {
+ procedures.run_pending_play_task_if_ready();
+ });
+ }
+}
+
+/// Whether an animation associated with a timeline of a document whose animations are `animations` has a rendering
+/// update hold the tasks of the document until the whole of it has run: any, where the update did not take in the style
+/// of the document, or else one the update makes ready or one the compositor runs, which the update's frame publishes.
+#[unsafe(no_mangle)]
+pub extern "C" fn animations_document_timelines_hold_rendering_update_tasks(
+ animations: &DocumentAnimations,
+ style_taken_in: bool,
+) -> bool {
+ animations.timelines.iter().any(|timeline| {
+ timeline.associated_animations().borrow().iter().any(|animation| {
+ !style_taken_in
+ || rendering_update_makes_ready(&animation)
+ || animation
+ .borrow()
+ .effect()
+ .is_some_and(|effect| effect.borrow().has_flag(EffectFlag::CompositorDriven))
+ })
+ })
+}
+
+#[cfg(test)]
+mod ffi_test_stubs {
+ #[unsafe(no_mangle)]
+ extern "C" fn web_animation_compare_elements_in_tree_order(
+ _first: *mut std::ffi::c_void,
+ _second: *mut std::ffi::c_void,
+ ) -> i32 {
+ unreachable!("the tests sample no animated style")
+ }
+}
diff --git a/Libraries/LibWeb/Rust/src/animations/snapshot.rs b/Libraries/LibWeb/Rust/src/animations/snapshot.rs
index 769047796b6..5271cd1c760 100644
--- a/Libraries/LibWeb/Rust/src/animations/snapshot.rs
+++ b/Libraries/LibWeb/Rust/src/animations/snapshot.rs
@@ -355,23 +355,9 @@ mod tests {
Some(TimeValue::percentage(time)).into()
}
- fn round_trip(snapshot: EffectTimingSnapshot) {
- let compact = CompactEffectTiming::from(&snapshot);
- assert_eq!(compact.snapshot(), snapshot);
- assert_eq!(compact.effect(), snapshot.effect);
- assert_eq!(compact.playback(), snapshot.playback);
- let timeline = snapshot.has_timeline.then_some(snapshot.timeline);
- assert_eq!(compact.timeline(), timeline);
- assert_eq!(
- compact.timeline_time(),
- timeline.and_then(|timeline| timeline.current_time.get())
- );
- assert_eq!(compact.clock(), snapshot.clock);
- }
-
#[test]
- fn a_document_timeline_timing_round_trips() {
- round_trip(EffectTimingSnapshot {
+ fn the_packed_timing_round_trips() {
+ let document_timeline = EffectTimingSnapshot {
effect: AnimationEffectTiming {
start_delay: TimeValue::milliseconds(-250.0),
end_delay: TimeValue::milliseconds(125.0),
@@ -402,12 +388,8 @@ mod tests {
origin_time: 16.75,
scroll_timeline: AnimationTimelineId::default(),
},
- });
- }
-
- #[test]
- fn a_scroll_timeline_timing_round_trips() {
- round_trip(EffectTimingSnapshot {
+ };
+ let scroll_timeline = EffectTimingSnapshot {
effect: AnimationEffectTiming {
start_delay: TimeValue::percentage(10.0),
end_delay: TimeValue::percentage(5.0),
@@ -422,7 +404,7 @@ mod tests {
..AnimationPlayback::default()
},
timeline: TimelineSample {
- current_time: percent(62.5),
+ current_time: OptionalTimeValue::from(None),
minimum_timeline_time: percent(0.0),
maximum_timeline_time: percent(100.0),
is_monotonically_increasing: false,
@@ -433,32 +415,11 @@ mod tests {
origin_time: 0.0,
scroll_timeline: AnimationTimelineId(u64::MAX - 3),
},
- });
- }
-
- #[test]
- fn unresolved_times_round_trip() {
- round_trip(EffectTimingSnapshot::default());
- round_trip(EffectTimingSnapshot {
- timeline: TimelineSample {
- current_time: OptionalTimeValue::from(None),
- minimum_timeline_time: percent(0.0),
- maximum_timeline_time: percent(100.0),
- is_monotonically_increasing: false,
- },
- has_timeline: true,
- ..EffectTimingSnapshot::default()
- });
- let mut compact = CompactEffectTiming::from(&EffectTimingSnapshot {
- playback: AnimationPlayback {
- hold_time: percent(30.0),
- ..AnimationPlayback::default()
- },
- ..EffectTimingSnapshot::default()
- });
- compact.set_hold_time(Some(TimeValue::milliseconds(12.0)));
- assert_eq!(compact.playback().hold_time.get(), Some(TimeValue::milliseconds(12.0)));
- compact.set_hold_time(None);
- assert_eq!(compact.playback().hold_time.get(), None);
+ };
+ for snapshot in [document_timeline, scroll_timeline, EffectTimingSnapshot::default()] {
+ let compact = CompactEffectTiming::from(&snapshot);
+ assert_eq!(compact.snapshot(), snapshot);
+ assert_eq!(compact.timeline(), snapshot.has_timeline.then_some(snapshot.timeline));
+ }
}
}
diff --git a/Libraries/LibWeb/Rust/src/animations/throttling.rs b/Libraries/LibWeb/Rust/src/animations/throttling.rs
new file mode 100644
index 00000000000..3e609817dc0
--- /dev/null
+++ b/Libraries/LibWeb/Rust/src/animations/throttling.rs
@@ -0,0 +1,302 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! Whether a frame can skip the style update or the tick of an effect, from its record and what the host knows of its
+//! target.
+
+use super::animation::AnimationHandle;
+use super::compositor_update::is_transform_family;
+use super::effect::{AnimationEffectCell, EffectFlag, PerFrameStyleUpdateSkipDecision, PerFrameStyleUpdateSkipKey};
+use super::host_timing::FfiAnimationKind;
+use super::rendering_trace::note_rendering_trace_event;
+use super::timing::{self, AnimationEffectPhase, AnimationPlayState};
+use crate::css::property_metadata::property_id;
+use std::cell::OnceCell;
+use std::ffi::c_void;
+use std::ptr::NonNull;
+
+// NB: What the host is asked of, or told about, an element, by bit: the facts it answers, and the counters it bumps.
+
+/// The node document of the element has its layout up to date.
+pub const TARGET_FACT_LAYOUT_IS_UP_TO_DATE: u32 = 1 << 0;
+/// The element is connected.
+pub const TARGET_FACT_IS_CONNECTED: u32 = 1 << 1;
+/// The element has a layout box.
+pub const TARGET_FACT_HAS_LAYOUT_BOX: u32 = 1 << 2;
+/// The element is in the SVG namespace.
+pub const TARGET_FACT_IS_SVG: u32 = 1 << 3;
+/// A navigable container the element's document is nested through has an up to date layout and no box.
+pub const TARGET_FACT_INSIDE_BOXLESS_CONTAINER: u32 = 1 << 4;
+/// Nothing shows the style of the element, as a display: none ancestor leaves it without a box, and no SVG
+/// element in its subtree can be referenced from elsewhere.
+pub const TARGET_FACT_UNSEEN_IN_DISPLAY_NONE_SUBTREE: u32 = 1 << 5;
+/// The element has a box with hidden visibility, and nothing in its box's subtree is visible.
+pub const TARGET_FACT_HIDDEN_WITHOUT_VISIBLE_DESCENDANT: u32 = 1 << 6;
+/// A listener on the element, the nodes its events bubble to or its window hears a CSS animation event that needs
+/// a tick.
+pub const TARGET_FACT_HEARS_CSS_ANIMATION_EVENTS: u32 = 1 << 7;
+/// The same, for the iteration events alone.
+pub const TARGET_FACT_HEARS_CSS_ANIMATION_ITERATION_EVENTS: u32 = 1 << 8;
+/// A listener on the element, an SVG animation element, hears its beginEvent, endEvent or repeatEvent.
+pub const TARGET_FACT_HEARS_TIME_EVENTS: u32 = 1 << 9;
+/// The same, for its repeatEvent alone.
+pub const TARGET_FACT_HEARS_REPEAT_EVENT: u32 = 1 << 10;
+/// What the host found whether a frame can skip a style update from, for the key it answers.
+pub const TARGET_FACT_SKIP_KEY: u32 = 1 << 11;
+
+/// What the host answers of an element: the facts it was asked of that hold, and the skip key where it was asked for
+/// one.
+#[repr(C)]
+#[derive(Clone, Copy)]
+pub struct FfiTargetFacts {
+ pub facts: u32,
+ pub key: PerFrameStyleUpdateSkipKey,
+}
+
+unsafe extern "C" {
+ fn web_animation_target_facts(element: NonNull<c_void>, wanted: u32) -> FfiTargetFacts;
+}
+
+/// What the host answers of `wanted` of the host's `DOM::Element` `element`, which something the caller holds keeps
+/// alive.
+pub(crate) fn target_facts(element: NonNull<c_void>, wanted: u32) -> FfiTargetFacts {
+ // SAFETY: Guaranteed by the caller.
+ unsafe { web_animation_target_facts(element, wanted) }
+}
+
+/// Whether `fact` holds of `element`.
+pub(crate) fn target_fact_holds(element: NonNull<c_void>, fact: u32) -> bool {
+ target_facts(element, fact).facts & fact != 0
+}
+
+/// Whether a frame can skip the style update of `effect`.
+pub(crate) fn can_skip_per_frame_style_update(effect: &AnimationEffectCell) -> bool {
+ let record = effect.borrow();
+ if record.has_flag(EffectFlag::CompositorDriven) || record.has_flag(EffectFlag::CompositorReplaced) {
+ return true;
+ }
+ let offscreen_throttled = record.has_flag(EffectFlag::OffscreenThrottled);
+ let keyframes = record.keyframes().cloned();
+ let target_properties = keyframes
+ .as_ref()
+ .map_or(&[][..], |keyframes| keyframes.target_properties());
+ if offscreen_throttled && !target_properties.iter().copied().any(is_transform_family) {
+ return true;
+ }
+
+ let Some(target) = record.target_element() else {
+ return false;
+ };
+ let has_pseudo_element = record.pseudo_element().is_some();
+ let timing = record.timing();
+ let animation = record.associated_animation();
+ drop(record);
+
+ // An animation inside a box-less iframe can't affect its embedding document's rendering. Check the containers
+ // before the target-local cache, since their layout can change without changing the target's style or layout box.
+ // Reverse playback and effects with a finite end time need ticks to finish, even with an infinite iteration count.
+ if let Some(animation) = &animation
+ && timing.iteration_count.is_infinite()
+ && {
+ let animation = animation.borrow();
+ animation.playback().playback_rate > 0.0 && animation.associated_effect_end().value.is_infinite()
+ }
+ && target_fact_holds(target, TARGET_FACT_INSIDE_BOXLESS_CONTAINER)
+ {
+ return true;
+ }
+
+ let facts = target_facts(
+ target,
+ TARGET_FACT_LAYOUT_IS_UP_TO_DATE | TARGET_FACT_IS_CONNECTED | TARGET_FACT_SKIP_KEY,
+ );
+ let layout_is_up_to_date = facts.facts & TARGET_FACT_LAYOUT_IS_UP_TO_DATE != 0;
+ let is_connected = facts.facts & TARGET_FACT_IS_CONNECTED != 0;
+ let key = facts.key;
+ let cache_result = |result: bool| {
+ if layout_is_up_to_date {
+ effect
+ .borrow_mut()
+ .note_per_frame_style_update_skip_decision(key, result);
+ }
+ result
+ };
+ if layout_is_up_to_date {
+ let decision = effect.borrow().per_frame_style_update_skip_decision(&key);
+ match decision {
+ PerFrameStyleUpdateSkipDecision::CanSkip | PerFrameStyleUpdateSkipDecision::CannotSkip => {
+ note_rendering_trace_event("animation style skip cache hit");
+ return decision == PerFrameStyleUpdateSkipDecision::CanSkip;
+ }
+ PerFrameStyleUpdateSkipDecision::Stale => {
+ note_rendering_trace_event("animation style skip cache miss");
+ }
+ PerFrameStyleUpdateSkipDecision::Unknown => {}
+ }
+ }
+
+ // Restrict throttling within a rendered document to infinite transform-only effects until animation overflow
+ // updates can also be throttled safely.
+ if !timing.iteration_count.is_infinite() || has_pseudo_element {
+ return cache_result(false);
+ }
+
+ if !is_connected {
+ return cache_result(true);
+ }
+ // NB: A custom property can feed the display of the target through var().
+ let may_animate_display = keyframes.as_ref().is_some_and(|keyframes| {
+ keyframes.target_properties().contains(&property_id::DISPLAY)
+ || !keyframes.target_custom_properties().is_empty()
+ });
+ if layout_is_up_to_date
+ && !may_animate_display
+ && target_fact_holds(target, TARGET_FACT_UNSEEN_IN_DISPLAY_NONE_SUBTREE)
+ {
+ return cache_result(true);
+ }
+ let Some(keyframes) = keyframes else {
+ return false;
+ };
+ if (keyframes.target_properties().is_empty() && keyframes.target_custom_properties().is_empty())
+ || !keyframes.target_custom_properties().is_empty()
+ || !keyframes.target_properties().iter().copied().all(is_transform_family)
+ {
+ return cache_result(false);
+ }
+
+ let facts = target_facts(target, TARGET_FACT_HAS_LAYOUT_BOX | TARGET_FACT_IS_SVG).facts;
+ // NB: Transforms cannot affect rendering without a layout box. This also covers SVG content inside
+ // display-none subtrees and closed details elements.
+ if layout_is_up_to_date && facts & TARGET_FACT_HAS_LAYOUT_BOX == 0 {
+ return cache_result(true);
+ }
+ if facts & TARGET_FACT_IS_SVG != 0 {
+ return cache_result(false);
+ }
+
+ if offscreen_throttled {
+ return cache_result(true);
+ }
+
+ if !layout_is_up_to_date {
+ return false;
+ }
+ cache_result(target_fact_holds(target, TARGET_FACT_HIDDEN_WITHOUT_VISIBLE_DESCENDANT))
+}
+
+/// Whether a frame can skip the tick of `effect`.
+pub(crate) fn can_skip_per_frame_animation_tick(effect: &AnimationEffectCell) -> bool {
+ let record = effect.borrow();
+ let animation = record.associated_animation();
+ let timing = record.timing();
+ let target = record.target_element();
+ let compositor_handled =
+ record.has_flag(EffectFlag::CompositorDriven) || record.has_flag(EffectFlag::CompositorReplaced);
+ let observation_relevant = record.has_flag(EffectFlag::ObservationRelevantCompositorAnimation);
+ drop(record);
+ // NB: The phase of the effect is at the current time of its associated animation. Resolve it once, where needed.
+ let phase_cell = OnceCell::new();
+ let phase = || {
+ *phase_cell.get_or_init(|| match &animation {
+ Some(animation) => animation.borrow().effect_phase(),
+ None => timing::resolve_timing(&timing, None, None, None).phase,
+ })
+ };
+
+ if let Some(animation) = &animation
+ && {
+ let animation = animation.borrow();
+ let playback = animation.playback();
+ !playback.has_pending_play_task
+ && !playback.has_pending_pause_task
+ && animation.play_state() == AnimationPlayState::Running
+ && playback.playback_rate > 0.0
+ && animation.has_monotonically_increasing_timeline()
+ }
+ && phase() == AnimationEffectPhase::Before
+ {
+ return true;
+ }
+
+ if !compositor_handled && !can_skip_per_frame_style_update(effect) {
+ return false;
+ }
+
+ // NB: Playing backward, an effect with an infinite iteration count finishes at time zero, and with a zero iteration
+ // duration it finishes at its end time. No timer wakes the main thread for either.
+ if let Some(animation) = &animation
+ && timing.iteration_count.is_infinite()
+ && {
+ let animation = animation.borrow();
+ animation.playback().playback_rate < 0.0 || !animation.associated_effect_end().value.is_infinite()
+ }
+ {
+ return false;
+ }
+
+ // A compositor-handled one-iteration effect has a document timer that wakes the main thread at its active end.
+ if compositor_handled && (!timing.iteration_count.is_infinite() || observation_relevant) {
+ return true;
+ }
+
+ // NB: Infinite effects cannot reach their natural end, and finite offscreen paint effects have an end timer.
+ // Neither needs a continuous tick for animationend listeners.
+ // NB: Starting or canceling an active animation requests an update independently of playback.
+ // Only iteration events require future updates while a visually throttled effect runs.
+ !css_animation_events_are_heard(
+ animation.as_ref(),
+ animation.as_ref().map(|animation| animation.borrow().ffi_kind()),
+ target,
+ phase() == AnimationEffectPhase::Active,
+ )
+}
+
+/// Whether a listener hears the CSS animation events of an effect targeting `target`, associated with `animation` of
+/// `kind`, that need a tick: only its iteration events if `only_iteration_events`.
+fn css_animation_events_are_heard(
+ animation: Option<&AnimationHandle>,
+ kind: Option<FfiAnimationKind>,
+ target: Option<NonNull<c_void>>,
+ only_iteration_events: bool,
+) -> bool {
+ // NB: SMIL animations raise time events at their animation element instead, which do not bubble.
+ if let Some(animation) = animation
+ && kind == Some(FfiAnimationKind::Smil)
+ {
+ let animation_element = super::ffi::smil_animation_element(animation);
+ let fact = if only_iteration_events {
+ TARGET_FACT_HEARS_REPEAT_EVENT
+ } else {
+ TARGET_FACT_HEARS_TIME_EVENTS
+ };
+ return target_fact_holds(animation_element, fact);
+ }
+
+ // Script animations do not dispatch CSS animation events, even when an ancestor listens for them.
+ if animation.is_some() && kind != Some(FfiAnimationKind::CssAnimation) {
+ return false;
+ }
+
+ let target = target.expect("an effect whose events are heard has a target");
+ let fact = if only_iteration_events {
+ TARGET_FACT_HEARS_CSS_ANIMATION_ITERATION_EVENTS
+ } else {
+ TARGET_FACT_HEARS_CSS_ANIMATION_EVENTS
+ };
+ target_fact_holds(target, fact)
+}
+
+#[cfg(test)]
+mod ffi_test_stubs {
+ #[unsafe(no_mangle)]
+ extern "C" fn web_animation_target_facts(
+ _element: std::ptr::NonNull<std::ffi::c_void>,
+ _wanted: u32,
+ ) -> super::FfiTargetFacts {
+ unreachable!("the tests ask the host nothing of elements")
+ }
+}
diff --git a/Libraries/LibWeb/Rust/src/animations/timeline.rs b/Libraries/LibWeb/Rust/src/animations/timeline.rs
index 327d14769fc..d36663525c2 100644
--- a/Libraries/LibWeb/Rust/src/animations/timeline.rs
+++ b/Libraries/LibWeb/Rust/src/animations/timeline.rs
@@ -7,7 +7,9 @@
//! Timelines.
//! https://www.w3.org/TR/web-animations-1/#timelines
-use super::animation::{AttachmentInterval, AttachmentRangeEdge, AttachmentRangeEdgeOffset, WeakAnimationSet};
+use super::animation::{
+ AttachmentInterval, AttachmentRangeEdge, AttachmentRangeEdgeOffset, HostCellKind, WeakAnimationSet,
+};
use super::snapshot::{TimelineClock, TimelineClockSource};
use super::timeline_state::TimelineState;
use super::timing::{TimeValue, TimelineSample};
@@ -595,8 +597,8 @@ impl ScrollTimelineState {
if let Some(metrics) = self.view.as_ref().and_then(|view| view.last_metrics)
&& metrics.time_at(0.0).is_some()
{
- // Each edge is measured from the start of its named timeline range, along that range, and is then placed
- // as a proportion of the cover range, which spans the entire timeline.
+ // NB: Each edge is measured from the start of its named timeline range, along that range, and is then
+ // placed as a proportion of the cover range, which spans the entire timeline.
let time_of = |edge: &AttachmentRangeEdge| {
let named_range = metrics.interval_for_range_name(TimelineRangeName::from_host(edge.name));
let position = named_range.start + edge.offset.offset_along(named_range.end - named_range.start);
@@ -739,11 +741,6 @@ pub(crate) struct TimelineRecord {
}
impl TimelineRecord {
- #[must_use]
- pub(crate) fn id(&self) -> AnimationTimelineId {
- self.id
- }
-
#[must_use]
pub(crate) fn scroll(&self) -> Option<&ScrollTimelineState> {
match &self.kind {
@@ -761,6 +758,12 @@ impl TimelineRecord {
}
}
+ /// https://drafts.csswg.org/web-animations-1/#monotonically-increasing-timeline
+ #[must_use]
+ pub(crate) fn is_monotonically_increasing(&self) -> bool {
+ self.is_monotonically_increasing
+ }
+
/// The current time a style sampling reads instead of the current time, where it is set.
#[must_use]
pub(crate) fn style_sampling_override(&self) -> Option<Option<TimeValue>> {
@@ -881,10 +884,10 @@ pub struct TimelineCell {
record: RefCell<TimelineRecord>,
/// NB: The animations associated with the timeline, none of which it keeps alive.
associated_animations: RefCell<WeakAnimationSet>,
- /// The host's `AnimationTimeline`, which holds a reference to the record until it is finalized and clears this as
- /// it does. It keeps the document and the elements the record names alive, so the record does not reach them
- /// without it.
- facade: Cell<Option<NonNull<c_void>>>,
+ /// The cell of the object script sees of the timeline, which holds a reference to the record until it is finalized
+ /// and clears this as it does, if script has asked for it yet. Each holder of the record keeps it alive, or the
+ /// cells the record names where it has none.
+ object_cell: Cell<Option<NonNull<c_void>>>,
}
/// How a timeline came to have its current time.
@@ -910,24 +913,35 @@ impl TimelineCell {
self.record.borrow_mut()
}
- /// The host's `AnimationTimeline` of the timeline, while it is alive.
- pub(crate) fn facade(&self) -> Option<NonNull<c_void>> {
- self.facade.get()
+ /// The cell of the object script sees of the timeline, while it has one.
+ pub(crate) fn object_cell(&self) -> Option<NonNull<c_void>> {
+ self.object_cell.get()
}
/// Calls `visit` with each GC cell of the host the record names: the document the timeline is associated with, and
- /// the element a scroll timeline finds its scroller from, if any, which a holder of the record the GC traces
+ /// the element a scroll timeline finds its scroller from, if any, which the object script sees of the timeline
/// visits.
- pub(crate) fn for_each_host_cell(&self, mut visit: impl FnMut(NonNull<c_void>)) {
+ pub(crate) fn for_each_host_cell(&self, mut visit: impl FnMut(NonNull<c_void>, HostCellKind)) {
let record = self.borrow();
- visit(record.document);
+ visit(record.document, HostCellKind::Cell);
match record.scroll().map(|scroll| scroll.source) {
- Some(ScrollTimelineSource::Element(Some(element))) => visit(element),
- Some(ScrollTimelineSource::Anonymous { target, .. }) => visit(target),
+ Some(ScrollTimelineSource::Element(Some(element))) => visit(element, HostCellKind::Element),
+ Some(ScrollTimelineSource::Anonymous { target, .. }) => visit(target, HostCellKind::Element),
Some(ScrollTimelineSource::Element(None)) | None => {}
}
}
+ /// Calls `visit` with each GC cell of the host that keeps alive what the record names: the object script sees of
+ /// the timeline, or, for a timeline that has none, the cells the record names. A holder of the record the GC traces
+ /// visits these.
+ pub(crate) fn for_each_holder_cell(&self, mut visit: impl FnMut(NonNull<c_void>, HostCellKind)) {
+ if let Some(object_cell) = self.object_cell() {
+ visit(object_cell, HostCellKind::Cell);
+ return;
+ }
+ self.for_each_host_cell(visit);
+ }
+
/// The host's `DOM::Document` the timeline is associated with.
pub(crate) fn document(&self) -> NonNull<c_void> {
self.borrow().document
@@ -947,10 +961,9 @@ impl TimelineCell {
}
if let TimelineKind::Document { .. } = record.kind {
// https://www.w3.org/TR/web-animations-1/#document-timelines
- // A document timeline that is associated with a Document which is not an active document is also
- // considered to be inactive.
- // NB: A timeline whose host timeline was finalized reaches no document.
- return self.facade().is_none() || !super::ffi::document_is_active(record.document);
+ // A document timeline that is associated with a Document that is not an active document is also considered
+ // to be inactive.
+ return !super::ffi::document_is_active(record.document);
}
false
}
@@ -981,7 +994,7 @@ impl TimelineCell {
/// What moves the timeline as a clock tick samples it.
#[must_use]
pub(crate) fn clock(&self) -> TimelineClock {
- // A document timeline's time is a timestamp less its origin time, which is what lets a clock tick sample it.
+ // NB: A document timeline's time is a timestamp less its origin time, which lets a clock tick sample it.
if let Some(origin_time) =
self.convert_a_timeline_time_to_an_origin_relative_time(Some(TimeValue::milliseconds(0.0)))
{
@@ -993,8 +1006,8 @@ impl TimelineCell {
}
let record = self.borrow();
match &record.kind {
- // A scroll timeline's time is the progress of the scroller it follows, which is what lets a clock tick
- // sample it where the compositor has scrolled to.
+ // NB: A scroll timeline's time is the progress of the scroller it follows, which is what lets a clock tick
+ // sample it where the compositor has scrolled to.
TimelineKind::Scroll(scroll) if scroll.followed_scroller.is_some() => TimelineClock {
source: TimelineClockSource::Scroll,
origin_time: 0.0,
@@ -1214,7 +1227,7 @@ impl ScrollTimelineState {
// AD-HOC: The spec only lists two criteria for a scroll timeline to be considered stale: a) it was newly
// created within the current frame or; b) style update and layout within the current frame changed
- // it's associated named timeline ranges. However, WPT expects us to also consider the source element
+ // its associated named timeline ranges. However, WPT expects us to also consider the source element
// resizing as a cause for staleness, so we use a more broad definition of staleness and consider any
// timeline whose max scroll offset has changed since the last call to `update_current_time` to be
// stale. This matches the (admittedly narrow) tests in WPT and is the same behavior as is implemented
@@ -1247,7 +1260,7 @@ impl ScrollTimelineState {
self.last_max_scroll_offset = scroller.map(|scroller| scroller.max_scroll_offset);
// If the source of a ScrollTimeline is an element whose principal box does not exist or is not a scroll
- // container, or if there is no scrollable overflow, then the ScrollTimeline is inactive.
+ // container in the timeline's axis, or if there is no scrollable overflow, then the ScrollTimeline is inactive.
let scroller = scroller?;
// https://drafts.csswg.org/scroll-animations-1/#scroll-timeline-progress
@@ -1294,7 +1307,7 @@ pub(crate) struct TimelineHandle(Rc<TimelineCell>);
impl TimelineHandle {
/// A new timeline of `kind`, associated with the host's `DOM::Document` `document`, whose host timeline is
- /// `facade`. Its current time is unresolved, and a document timeline is not monotonically increasing until it
+ /// `object_cell`. Its current time is unresolved, and a document timeline is not monotonically increasing until it
/// becomes active.
pub(crate) fn new(document: NonNull<c_void>, kind: TimelineKind) -> Self {
// NB: The Internals interface's timeline starts at zero and only moves forward.
@@ -1313,7 +1326,7 @@ impl TimelineHandle {
kind,
}),
associated_animations: RefCell::default(),
- facade: Cell::new(None),
+ object_cell: Cell::new(None),
}))
}
@@ -1337,8 +1350,8 @@ impl TimelineHandle {
}
/// Notes the cell of the object script sees of the timeline, or that it was finalized.
- pub(crate) fn set_facade(&self, facade: Option<NonNull<c_void>>) {
- self.0.facade.set(facade);
+ pub(crate) fn set_object_cell(&self, object_cell: Option<NonNull<c_void>>) {
+ self.0.object_cell.set(object_cell);
}
}
@@ -1354,7 +1367,7 @@ impl std::ops::Deref for TimelineHandle {
mod tests {
use super::*;
- fn facade() -> NonNull<c_void> {
+ fn object_cell() -> NonNull<c_void> {
NonNull::<u8>::dangling().cast()
}
@@ -1384,7 +1397,7 @@ mod tests {
fn scroll_timeline(view: Option<ViewTimelineInset>) -> TimelineHandle {
TimelineHandle::new(
- facade(),
+ object_cell(),
TimelineKind::Scroll(Box::new(ScrollTimelineState {
source: ScrollTimelineSource::Element(None),
axis: 0,
@@ -1443,36 +1456,6 @@ mod tests {
assert_eq!(timeline.clock().source, TimelineClockSource::Unticked);
}
- #[test]
- fn a_scroll_timeline_is_stale_where_its_maximum_scroll_offset_moved() {
- let timeline = scroll_timeline(None);
- update(&timeline, Some(&scroller(50.0, 200.0)), None);
- let mut updated = false;
- timeline.update_current_time(
- TimelineUpdate::Layout {
- scroller: Some(&scroller(80.0, 200.0)),
- subject: None,
- subject_style_node: None,
- },
- 1,
- true,
- || updated = true,
- );
- assert!(!updated);
- timeline.update_current_time(
- TimelineUpdate::Layout {
- scroller: Some(&scroller(80.0, 400.0)),
- subject: None,
- subject_style_node: None,
- },
- 1,
- true,
- || updated = true,
- );
- assert!(updated);
- assert_eq!(timeline.current_time(), Some(TimeValue::percentage(20.0)));
- }
-
#[test]
fn an_attachment_range_on_a_scroll_timeline_spans_the_scroll_range() {
let timeline = scroll_timeline(None);
@@ -1528,42 +1511,6 @@ mod tests {
assert_eq!(timeline.current_time(), None);
}
- #[test]
- fn a_clock_tick_finds_the_progress_the_record_has() {
- let timeline = scroll_timeline(None);
- update(&timeline, Some(&scroller(50.0, 200.0)), None);
- let snapshot = timeline.clock_snapshot().unwrap();
- assert_eq!(
- Some(TimeValue::percentage(snapshot.progress_at(50.0))),
- timeline.current_time()
- );
-
- // A tick does not follow a view timeline whose subject it cannot find.
- let timeline = scroll_timeline(Some(auto_inset()));
- let subject = SubjectMetrics {
- start: 300.0,
- size: 50.0,
- };
- update(&timeline, Some(&scroller(250.0, 1000.0)), Some(&subject));
- assert!(timeline.current_time().is_some());
- assert!(timeline.clock_snapshot().is_none());
- assert!(timeline.update_current_time(
- TimelineUpdate::Layout {
- scroller: Some(&scroller(250.0, 1000.0)),
- subject: Some(&subject),
- subject_style_node: StyleNodeID::from_raw(3),
- },
- 1,
- false,
- || {}
- ));
- let snapshot = timeline.clock_snapshot().unwrap();
- assert_eq!(
- Some(TimeValue::percentage(snapshot.progress_at(250.0))),
- timeline.current_time()
- );
- }
-
#[test]
fn the_block_axis_of_a_vertical_writing_mode_is_horizontal() {
assert_eq!(
@@ -1583,20 +1530,4 @@ mod tests {
(true, false)
);
}
-
- #[test]
- fn a_monotonically_increasing_timeline_only_moves_forward() {
- let timeline = TimelineHandle::new(
- facade(),
- TimelineKind::Internal {
- time_for_observation: None,
- },
- );
- let mut updates = 0;
- timeline.set_internal_time(Some(10.0), false, 1, || updates += 1);
- timeline.set_internal_time(Some(5.0), false, 1, || updates += 1);
- timeline.set_internal_time(None, false, 1, || updates += 1);
- assert_eq!(updates, 1);
- assert_eq!(timeline.current_time(), Some(TimeValue::milliseconds(10.0)));
- }
}
diff --git a/Libraries/LibWeb/Rust/src/animations/timeline_host.rs b/Libraries/LibWeb/Rust/src/animations/timeline_host.rs
new file mode 100644
index 00000000000..6a6984cb544
--- /dev/null
+++ b/Libraries/LibWeb/Rust/src/animations/timeline_host.rs
@@ -0,0 +1,551 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The timelines associated with a document: what the document keeps of them, what moves them, and what they ask of
+//! the document and its layout.
+
+use super::animation::AnimationCell;
+use super::document_animations::DocumentAnimations;
+use super::effect::EffectFlag;
+use super::ffi::{FfiKeepAlive, FfiScrollTimelineSource, FfiTimelineDescription, HostEffectPerformer, run_procedure};
+use super::rendering_trace::note_rendering_trace_event;
+use super::throttling::can_skip_per_frame_animation_tick;
+use super::timeline::{ScrollTimelineBoxes, TimelineCell, TimelineHandle, TimelineKind, TimelineUpdate};
+use super::timing::TimeValue;
+use crate::css::style::tree::StyleNodeID;
+use crate::layout::node_data::NodeSlotId;
+use crate::render_state::{BegunRead, DocumentHost};
+use std::ffi::c_void;
+use std::ptr::NonNull;
+
+/// The now timestamp of a document, the task generation of its event loop, and the time a new document timeline of
+/// the document starts at: the timestamp of its last animation frame, or before it has one, the time navigation to it
+/// started.
+#[repr(C)]
+#[derive(Clone, Copy)]
+pub struct FfiDocumentClock {
+ pub now: f64,
+ pub task_generation: u64,
+ pub timeline_start_time: f64,
+}
+
+/// The boxes a scroll timeline follows, as the host found them from its source in the render state of `host`'s
+/// document, which it reads in `read`: the box of the scroll container, if any, the viewport's where the source is the
+/// root element, its scroll node, where `has_scroll_node`, and the style node of the element whose box scrolls, or 0
+/// for the viewport. For a view timeline, the box of its subject, if any, and the style node by which a clock tick finds
+/// it, or 0 where the subject is a pseudo-element. `host` and `read` are null where the source has no box.
+#[repr(C)]
+pub struct FfiScrollTimelineBoxes {
+ pub host: *const DocumentHost,
+ pub read: *const BegunRead,
+ pub scroller: NodeSlotId,
+ pub has_scroll_node: bool,
+ pub scroll_node: super::timeline::ScrollNodeStableId,
+ pub scroller_style_node: u32,
+ pub subject: NodeSlotId,
+ pub subject_style_node: u32,
+}
+
+unsafe extern "C" {
+ /// What the host's `DOM::Document` `document` knows of animations.
+ fn web_animation_document_animations(document: NonNull<c_void>) -> NonNull<c_void>;
+ /// The clock of the host's `DOM::Document` `document`.
+ fn web_animation_document_clock(document: NonNull<c_void>) -> FfiDocumentClock;
+ /// Finds the boxes the scroll timeline of `source`, a view timeline's where `is_view`, follows, and calls `measure`
+ /// with `context` and them, while it reads the render state they are in.
+ fn web_animation_find_scroll_timeline_boxes(
+ source: &FfiScrollTimelineSource,
+ is_view: bool,
+ context: *mut c_void,
+ measure: unsafe extern "C" fn(context: *mut c_void, boxes: &FfiScrollTimelineBoxes),
+ );
+ /// The host's `DOM::Element` that is the source of the scroll timeline of `source`, as script observes it, a view
+ /// timeline's where `is_view`, or null.
+ fn web_animation_scroll_timeline_source(source: &FfiScrollTimelineSource, is_view: bool) -> *mut c_void;
+}
+
+/// What the host's `DOM::Document` `document` knows of animations, which lives as long as the document.
+///
+/// # Safety
+/// The document must be live, and the caller must not hold the reference across anything that reaches it again.
+pub(crate) unsafe fn document_animations<'a>(document: NonNull<c_void>) -> &'a mut DocumentAnimations {
+ // SAFETY: Guaranteed by the caller.
+ unsafe {
+ web_animation_document_animations(document)
+ .cast::<DocumentAnimations>()
+ .as_mut()
+ }
+}
+
+fn document_clock(document: NonNull<c_void>) -> FfiDocumentClock {
+ // SAFETY: The document of a timeline that is updated or observed is live.
+ unsafe { web_animation_document_clock(document) }
+}
+
+/// What updating the animations associated with a timeline asks of the host: to keep each animation alive while the
+/// update lasts, and to perform what the procedures that update it ask for.
+pub(crate) struct TimelineUpdateHost<'a> {
+ pub(crate) keep_alive: &'a dyn Fn(&AnimationCell),
+ pub(crate) perform: HostEffectPerformer,
+}
+
+/// The host's side of an update of the animations associated with a timeline, which hands `keep_alive` `context`.
+#[repr(C)]
+pub struct FfiTimelineAnimationsHost {
+ pub context: *mut c_void,
+ pub keep_alive: FfiKeepAlive,
+ pub perform: HostEffectPerformer,
+}
+
+impl FfiTimelineAnimationsHost {
+ fn with<R>(&self, run: impl FnOnce(&TimelineUpdateHost<'_>) -> R) -> R {
+ let keep_alive = |animation: &AnimationCell| {
+ // SAFETY: The host keeps alive an animation it is handed for as long as the call that handed it lasts.
+ unsafe { (self.keep_alive)(self.context, animation) };
+ };
+ run(&TimelineUpdateHost {
+ keep_alive: &keep_alive,
+ perform: self.perform,
+ })
+ }
+}
+
+extern "C" fn perform_nothing(_: &super::ffi::FfiHostEffect) {
+ unreachable!("a new timeline has no associated animations to update");
+}
+
+/// https://drafts.csswg.org/web-animations-1/#animation-frame-loop
+/// Updates the animations associated with `timeline` as its current time changed.
+fn update_associated_animations(timeline: &TimelineCell, host: &TimelineUpdateHost<'_>) {
+ // Note: Due to the hierarchical nature of the timing model, updating the current time of a timeline also involves:
+ // - Updating the current time of any animations associated with the timeline.
+ // - Running the update an animation's finished state procedure for any animations whose current time has been
+ // updated.
+ // - Queueing animation events for any such animations.
+ // NB: Since we dispatch events for all animations regardless of whether they have a timeline we handle them all
+ // together in the host's update of the animations of its document.
+ note_rendering_trace_event("animation timeline updated its animations");
+ // NB: Updating an animation can run script that changes which animations are associated with this timeline. Skip
+ // the ones it disassociates. The host keeps the animations alive through it.
+ let animations = timeline.associated_animations().borrow_mut().alive();
+ for animation in &animations {
+ (host.keep_alive)(animation);
+ }
+ for animation in &animations {
+ if timeline.associated_animations().borrow().contains(animation) {
+ run_procedure(animation, host.perform, |procedures| procedures.update());
+ }
+ }
+}
+
+/// What measuring the boxes a scroll timeline follows hands back.
+struct LayoutUpdate<'a> {
+ timeline: &'a TimelineCell,
+ task_generation: u64,
+ only_if_stale: bool,
+ host: &'a TimelineUpdateHost<'a>,
+ updated: bool,
+}
+
+unsafe extern "C" fn update_from_boxes(context: *mut c_void, boxes: &FfiScrollTimelineBoxes) {
+ // SAFETY: The context is the update that asked the host to find the boxes.
+ let update = unsafe { &mut *context.cast::<LayoutUpdate<'_>>() };
+ let timeline = update.timeline;
+ let subject_style_node = StyleNodeID::from_raw(boxes.subject_style_node);
+ // SAFETY: The host hands a live document host and a read it began of its render state, or nulls.
+ let (scroller, subject) = match unsafe { (boxes.host.as_ref(), boxes.read.as_ref()) } {
+ (Some(host), Some(read)) => {
+ let found = ScrollTimelineBoxes {
+ scroller: boxes.scroller,
+ scroll_node: boxes.has_scroll_node.then_some(boxes.scroll_node),
+ scroller_style_node: boxes.scroller_style_node,
+ subject: boxes.subject,
+ };
+ let record = timeline.borrow();
+ let scroll = record.scroll().expect("the host lays out scroll timelines");
+ host.ask(read, |state| {
+ let arena = state.arena_mut();
+ arena.settle_scrollable_overflow();
+ scroll.measure(arena, &found)
+ })
+ }
+ _ => (None, None),
+ };
+ update.updated = timeline.update_current_time(
+ TimelineUpdate::Layout {
+ scroller: scroller.as_ref(),
+ subject: subject.as_ref(),
+ subject_style_node,
+ },
+ update.task_generation,
+ update.only_if_stale,
+ || update_associated_animations(timeline, update.host),
+ );
+}
+
+/// The source of the scroll timeline `timeline` as the host names it, and whether it is a view timeline.
+fn host_source(timeline: &TimelineCell) -> (FfiScrollTimelineSource, bool) {
+ let record = timeline.borrow();
+ let scroll = record.scroll().expect("a scroll timeline has a source");
+ (scroll.source.into(), scroll.view.is_some())
+}
+
+/// Updates the current time of the scroll timeline `timeline` from where the render state lays out the boxes it
+/// follows, unless that leaves it as it was where `only_if_stale`, answering whether it updated it.
+fn update_current_time_from_layout(
+ timeline: &TimelineCell,
+ only_if_stale: bool,
+ host: &TimelineUpdateHost<'_>,
+) -> bool {
+ let task_generation = document_clock(timeline.document()).task_generation;
+ let (source, is_view) = host_source(timeline);
+ let mut update = LayoutUpdate {
+ timeline,
+ task_generation,
+ only_if_stale,
+ host,
+ updated: false,
+ };
+ // NB: The host measures the boxes the timeline follows where the render state of the document whose viewport or
+ // element the source propagates to lays them out.
+ // SAFETY: The host calls back synchronously with the update.
+ unsafe {
+ web_animation_find_scroll_timeline_boxes(&source, is_view, (&raw mut update).cast(), update_from_boxes);
+ }
+ update.updated
+}
+
+/// Updates the current time of `timeline`: a document timeline's from the now timestamp `timestamp`, and a scroll
+/// timeline's from the layout of its scroller, which ignores the timestamp, unless that leaves it as it was where
+/// `only_if_stale`. Answers whether the timeline was updated.
+pub(crate) fn update_current_time(
+ timeline: &TimelineCell,
+ timestamp: f64,
+ only_if_stale: bool,
+ host: &TimelineUpdateHost<'_>,
+) -> bool {
+ // https://drafts.csswg.org/scroll-animations-1/#ref-for-dom-animationtimeline-currenttime
+ // NB: The scroll progress is calculated from the layout of the scroller. The passed timestamp is ignored.
+ if timeline.borrow().scroll().is_some() {
+ return update_current_time_from_layout(timeline, only_if_stale, host);
+ }
+ let task_generation = document_clock(timeline.document()).task_generation;
+ timeline.update_current_time(TimelineUpdate::Timestamp(timestamp), task_generation, false, || {
+ update_associated_animations(timeline, host);
+ })
+}
+
+/// Whether the associated effect of an animation associated with `timeline` goes without a per-frame tick.
+fn has_animation_without_per_frame_tick(timeline: &TimelineCell) -> bool {
+ // NB: Script reads the current time often, so stop at the first one.
+ timeline.associated_animations().borrow().iter().any(|animation| {
+ let effect = animation.borrow().effect().cloned();
+ effect.is_some_and(|effect| {
+ effect.borrow().has_flag(EffectFlag::PerFrameAnimationTickWasSkipped)
+ || can_skip_per_frame_animation_tick(&effect)
+ })
+ })
+}
+
+/// https://drafts.csswg.org/web-animations-1/#dom-animationtimeline-currenttime
+/// The current time of `timeline` as script observes it.
+pub(crate) fn current_time_for_observation(timeline: &TimelineCell) -> Option<TimeValue> {
+ let can_sample = {
+ let record = timeline.borrow();
+ record.is_monotonically_increasing() && record.can_sample_current_time_at_timestamp()
+ };
+ if !can_sample || !has_animation_without_per_frame_tick(timeline) {
+ return timeline.current_time();
+ }
+ let clock = document_clock(timeline.document());
+ let (observed_in, observed_current_time) = timeline.borrow().observed_in_task_generation();
+ if observed_in == Some(clock.task_generation) {
+ return observed_current_time;
+ }
+
+ // OPTIMIZATION: An animation skipped by the per-frame sampler does not keep the rendering update loop alive.
+ // Sample document timelines only when script observes them, and at most once per event-loop task
+ // so all reads within a stable state agree.
+ let current_time = timeline.current_time_at_timestamp(clock.now, Some(clock.task_generation));
+ note_rendering_trace_event("animation timeline synchronized");
+ current_time
+}
+
+/// The host's `DOM::Element` that is the source of the scroll timeline `timeline` as script observes it, or none.
+pub(crate) fn scroll_timeline_source(timeline: &TimelineCell) -> Option<NonNull<c_void>> {
+ let (source, is_view) = host_source(timeline);
+ // SAFETY: The elements the source names are live while the timeline's object is.
+ NonNull::new(unsafe { web_animation_scroll_timeline_source(&source, is_view) })
+}
+
+/// Associates the new timeline `timeline` with its document, and gives it its first current time.
+pub(crate) fn associate_new_timeline(timeline: &TimelineHandle) {
+ // SAFETY: The document of a new timeline is live, and the borrow ends here.
+ unsafe { document_animations(timeline.document()) }
+ .timelines
+ .push(timeline.clone());
+ let keep_alive = |_: &AnimationCell| {};
+ let host = TimelineUpdateHost {
+ keep_alive: &keep_alive,
+ perform: perform_nothing,
+ };
+ let timestamp = match timeline.borrow().kind {
+ // NB: The document hasn't processed an animation frame yet, we use the navigation start time, which is either
+ // the time that the previous document started to be unloaded or the creation time of the current document.
+ TimelineKind::Document { .. } => document_clock(timeline.document()).timeline_start_time,
+ // NB: The passed timestamp is ignored for ScrollTimelines so we can just pass 0 here.
+ TimelineKind::Scroll(_) => 0.0,
+ TimelineKind::Internal { .. } => return,
+ };
+ update_current_time(timeline, timestamp, false, &host);
+}
+
+/// Sets the current time of the Internals interface's timeline `timeline` to `time`, in milliseconds, or, where
+/// `for_observation`, the time a read of it observes, updating its associated animations, which `keep_alive` keeps
+/// alive.
+pub(crate) fn set_internal_time(
+ timeline: &TimelineCell,
+ time: Option<f64>,
+ for_observation: bool,
+ keep_alive: &dyn Fn(&AnimationCell),
+ perform: HostEffectPerformer,
+) {
+ let task_generation = document_clock(timeline.document()).task_generation;
+ let host = TimelineUpdateHost { keep_alive, perform };
+ timeline.set_internal_time(time, for_observation, task_generation, || {
+ update_associated_animations(timeline, &host);
+ });
+}
+
+/// https://www.w3.org/TR/web-animations-1/#document-default-document-timeline
+/// The default document timeline of the host's `DOM::Document` `document`.
+pub(crate) fn default_document_timeline(document: NonNull<c_void>) -> TimelineHandle {
+ // SAFETY: The document is live, and the borrow ends before the timeline is associated with it.
+ if let Some(timeline) = &unsafe { document_animations(document) }.default_timeline {
+ return timeline.clone();
+ }
+ // The DocumentTimeline object representing the default document timeline. The default document timeline has an
+ // origin time of zero.
+ let timeline = TimelineHandle::new(document, TimelineKind::Document { origin_time: 0.0 });
+ // SAFETY: As above.
+ unsafe { document_animations(document) }.default_timeline = Some(timeline.clone());
+ associate_new_timeline(&timeline);
+ timeline
+}
+
+/// A new timeline associated with the host's `DOM::Document` `document`, of `kind`.
+pub(crate) fn create_timeline(document: NonNull<c_void>, kind: TimelineKind) -> TimelineHandle {
+ let timeline = TimelineHandle::new(document, kind);
+ associate_new_timeline(&timeline);
+ timeline
+}
+
+impl DocumentAnimations {
+ /// Runs `run` with the timelines associated with the document at the times script observed of them: all of them
+ /// where `all`, or else those script observed ahead of their current time in this task.
+ pub(crate) fn at_observed_times<R>(this: *mut Self, all: bool, run: impl FnOnce() -> R) -> R {
+ // SAFETY: The caller passes what a live document knows of animations, and the borrow ends here.
+ let timelines = unsafe { &*this }.timelines.clone();
+ let Some(first) = timelines.first() else {
+ return run();
+ };
+ let task_generation = document_clock(first.document()).task_generation;
+ let mut overridden = Vec::new();
+ for timeline in &timelines {
+ if !all && timeline.borrow().observed_ahead_in_task_generation() != Some(task_generation) {
+ continue;
+ }
+ let previous = timeline.borrow().style_sampling_override();
+ let current_time = current_time_for_observation(timeline);
+ timeline.borrow_mut().set_style_sampling_override(Some(current_time));
+ overridden.push((timeline, previous));
+ }
+ let result = run();
+ for (timeline, previous) in overridden.into_iter().rev() {
+ timeline.borrow_mut().set_style_sampling_override(previous);
+ }
+ result
+ }
+}
+
+/// Which of the timelines of a document an update moves.
+#[expect(dead_code, reason = "C++ constructs the variants")]
+#[repr(u8)]
+#[derive(Clone, Copy, PartialEq, Eq)]
+pub enum FfiTimelinesUpdate {
+ /// All of them, to the timestamp.
+ All,
+ /// The scroll timelines, from the layout of their scrollers.
+ ScrollTimelines,
+ /// The scroll timelines whose scrollers' layout changed them since their last update.
+ StaleScrollTimelines,
+}
+
+/// Updates the current time of the timelines associated with a document whose animations are `animations`, as `update`
+/// has it, a document timeline's to the now timestamp `timestamp`, updating their associated animations through
+/// `host`, and answers whether that updated any.
+///
+/// # Safety
+/// `animations` must be what a live document knows of animations, which the update may reach.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn animations_document_update_timelines(
+ animations: *mut DocumentAnimations,
+ update: FfiTimelinesUpdate,
+ timestamp: f64,
+ host: &FfiTimelineAnimationsHost,
+) -> bool {
+ // NB: Updating a timeline can run script, which can associate new timelines with the document.
+ // SAFETY: Guaranteed by the caller, and the borrow ends here.
+ let timelines = unsafe { &*animations }.timelines.clone();
+ host.with(|host| {
+ let mut updated = false;
+ for timeline in &timelines {
+ let is_scroll = timeline.borrow().scroll().is_some();
+ updated |= match update {
+ FfiTimelinesUpdate::All => update_current_time(timeline, timestamp, false, host),
+ FfiTimelinesUpdate::ScrollTimelines if is_scroll => {
+ update_current_time_from_layout(timeline, false, host)
+ }
+ FfiTimelinesUpdate::StaleScrollTimelines if is_scroll => {
+ update_current_time_from_layout(timeline, true, host)
+ }
+ FfiTimelinesUpdate::ScrollTimelines | FfiTimelinesUpdate::StaleScrollTimelines => false,
+ };
+ }
+ updated
+ })
+}
+
+/// Updates the current time of every timeline associated with the host's `DOM::Document` `document` to now, keeping
+/// the animations it updates alive through `keep_alive` and performing what they ask for through `perform`.
+pub(crate) fn update_timelines_to_now(
+ animations: *mut DocumentAnimations,
+ keep_alive: &dyn Fn(&AnimationCell),
+ perform: HostEffectPerformer,
+) {
+ // SAFETY: The caller passes what a live document knows of animations, and the borrow ends here.
+ let timelines = unsafe { &*animations }.timelines.clone();
+ let Some(first) = timelines.first() else {
+ return;
+ };
+ let now = document_clock(first.document()).now;
+ let host = TimelineUpdateHost { keep_alive, perform };
+ for timeline in &timelines {
+ update_current_time(timeline, now, false, &host);
+ }
+}
+
+/// The default document timeline of the host's `DOM::Document` `document`, which the document keeps alive.
+#[unsafe(no_mangle)]
+pub extern "C" fn animations_document_timeline(document: NonNull<c_void>) -> *const TimelineCell {
+ // NB: The document keeps the timeline alive.
+ let timeline = default_document_timeline(document);
+ std::ptr::from_ref::<TimelineCell>(&*timeline)
+}
+
+/// The timeline associated with a document whose animations are `animations` at `index`, in the order they were
+/// associated with it, or null past the last. The document keeps each alive.
+#[unsafe(no_mangle)]
+pub extern "C" fn animations_document_animations_timeline_at(
+ animations: &DocumentAnimations,
+ index: usize,
+) -> *const TimelineCell {
+ animations.timelines.get(index).map_or(std::ptr::null(), |timeline| {
+ std::ptr::from_ref::<TimelineCell>(timeline)
+ })
+}
+
+/// A new timeline associated with the host's `DOM::Document` `document`, as `description` describes it, which the
+/// document keeps alive.
+///
+/// # Safety
+/// The calculations of a view timeline's inset must be null or live style values.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn animations_document_create_timeline(
+ document: NonNull<c_void>,
+ description: &FfiTimelineDescription,
+) -> *const TimelineCell {
+ // SAFETY: Guaranteed by the caller.
+ let timeline = unsafe { super::ffi::timeline_of_description(document, description) };
+ associate_new_timeline(&timeline);
+ // NB: The document keeps the timeline alive.
+ std::ptr::from_ref::<TimelineCell>(&*timeline)
+}
+
+/// Sets the axis of the scroll timeline `timeline` to `axis`, the host's `ScrollAxis`, and the inset of a view
+/// timeline to `inset`, updating its current time through `host` where that changed either.
+///
+/// # Safety
+/// The calculations of `inset` must be null or live style values.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn animations_scroll_timeline_set_axis_and_inset(
+ timeline: &TimelineCell,
+ axis: u8,
+ inset: Option<&super::ffi::FfiViewTimelineInset>,
+ host: &FfiTimelineAnimationsHost,
+) {
+ // SAFETY: Guaranteed by the caller.
+ let inset = inset.map(|inset| unsafe { inset.retained() });
+ if timeline.set_axis_and_inset(axis, inset) {
+ host.with(|host| update_current_time_from_layout(timeline, false, host));
+ }
+}
+
+/// Runs `run` with `context`, with the timelines associated with a document whose animations are `animations` that
+/// script observed ahead of their current time in this task at the times it observed.
+///
+/// # Safety
+/// `animations` must be what a live document knows of animations.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn animations_document_animations_at_times_observed_ahead(
+ animations: *mut DocumentAnimations,
+ context: *mut c_void,
+ run: unsafe extern "C" fn(context: *mut c_void),
+) {
+ // SAFETY: The host runs synchronously.
+ DocumentAnimations::at_observed_times(animations, false, || unsafe { run(context) });
+}
+
+/// Keeps alive the animations a procedure hands the host, which `keep_alive` keeps with `context`.
+pub(crate) fn keep_alive_with(keep_alive: FfiKeepAlive, context: *mut c_void) -> impl Fn(&AnimationCell) {
+ move |animation| {
+ // SAFETY: The host keeps alive an animation it is handed for as long as the call that handed it lasts.
+ unsafe { keep_alive(context, animation) };
+ }
+}
+
+#[cfg(test)]
+mod ffi_test_stubs {
+ use super::*;
+
+ #[unsafe(no_mangle)]
+ extern "C" fn web_animation_document_animations(_document: NonNull<c_void>) -> NonNull<c_void> {
+ unreachable!("the tests associate no timelines with documents")
+ }
+
+ #[unsafe(no_mangle)]
+ extern "C" fn web_animation_document_clock(_document: NonNull<c_void>) -> FfiDocumentClock {
+ unreachable!("the tests observe no document clocks")
+ }
+
+ #[unsafe(no_mangle)]
+ extern "C" fn web_animation_find_scroll_timeline_boxes(
+ _source: &FfiScrollTimelineSource,
+ _is_view: bool,
+ _context: *mut c_void,
+ _measure: unsafe extern "C" fn(context: *mut c_void, boxes: &FfiScrollTimelineBoxes),
+ ) {
+ unreachable!("the tests lay out no scroll timelines")
+ }
+
+ #[unsafe(no_mangle)]
+ extern "C" fn web_animation_scroll_timeline_source(
+ _source: &FfiScrollTimelineSource,
+ _is_view: bool,
+ ) -> *mut c_void {
+ unreachable!("the tests observe no scroll timeline sources")
+ }
+}
diff --git a/Libraries/LibWeb/Rust/src/animations/timeline_state.rs b/Libraries/LibWeb/Rust/src/animations/timeline_state.rs
index b1404c8db5c..bcc7788ed77 100644
--- a/Libraries/LibWeb/Rust/src/animations/timeline_state.rs
+++ b/Libraries/LibWeb/Rust/src/animations/timeline_state.rs
@@ -61,7 +61,13 @@ impl TimelineState {
/// The unit of the times of `timeline`, which is milliseconds without one.
#[must_use]
pub(crate) fn time_unit(timeline: Option<&TimelineState>) -> TimeValueType {
- if timeline.is_some_and(|timeline| timeline.is_progress_based) {
+ time_unit_of(timeline.is_some_and(|timeline| timeline.is_progress_based))
+}
+
+/// The unit of the times of a timeline that is progress-based or not.
+#[must_use]
+pub(crate) fn time_unit_of(is_progress_based: bool) -> TimeValueType {
+ if is_progress_based {
return TimeValueType::Percentage;
}
TimeValueType::Milliseconds
diff --git a/Libraries/LibWeb/Rust/src/animations/transitions.rs b/Libraries/LibWeb/Rust/src/animations/transitions.rs
index 9f403eb5012..690e65c6b4f 100644
--- a/Libraries/LibWeb/Rust/src/animations/transitions.rs
+++ b/Libraries/LibWeb/Rust/src/animations/transitions.rs
@@ -19,8 +19,6 @@ use crate::css::retained_fly_string::RetainedUtf16FlyString;
use crate::css::transition::{FfiExistingTransition, FfiLaneTransition};
/// Who started a transition the element comes to hold.
-#[expect(dead_code, reason = "C++ constructs the variants")]
-#[repr(u8)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TransitionOrigin {
/// A style change event of the host's.
@@ -31,7 +29,6 @@ pub enum TransitionOrigin {
/// What becomes of a running transition of the host's as it takes in what the hover of a clock lane left the element
/// running.
-#[repr(u8)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LaneAdoption {
/// The transition stands: the lane runs it as the host does, or the lane's steps saw it without ending it.
@@ -106,7 +103,7 @@ impl AnimationRecord {
/// a custom property.
pub(crate) fn existing_transition(&self, t: f64) -> FfiExistingTransition {
let state = self.css_transition();
- let running = !self.playback().is_finished && self.timing_state(None).play_state != AnimationPlayState::Idle;
+ let running = !self.playback().is_finished && self.play_state() != AnimationPlayState::Idle;
FfiExistingTransition {
property_id: state.property_id,
custom_name: state.custom_property_name.raw(),
diff --git a/Libraries/LibWeb/Rust/src/animations/weak_record_set.rs b/Libraries/LibWeb/Rust/src/animations/weak_record_set.rs
index 94329150402..1019b00df14 100644
--- a/Libraries/LibWeb/Rust/src/animations/weak_record_set.rs
+++ b/Libraries/LibWeb/Rust/src/animations/weak_record_set.rs
@@ -171,22 +171,6 @@ mod tests {
assert!(set.contains(Rc::as_ptr(&second)));
}
- #[test]
- fn removing_an_entry_keeps_the_others_findable() {
- let mut set = WeakRecordSet::new(|_| true);
- let records: Vec<_> = (0..5).map(Rc::new).collect();
- for record in &records {
- set.insert(record);
- }
- set.remove(Rc::as_ptr(&records[1]));
- assert_eq!(live(&set), [0, 4, 2, 3]);
- for record in [&records[0], &records[2], &records[3], &records[4]] {
- assert!(set.contains(Rc::as_ptr(record)));
- assert!(set.remove(Rc::as_ptr(record)));
- }
- assert_eq!(set.entry_count(), 0);
- }
-
#[test]
fn taking_each_record_yields_the_live_ones_and_empties_the_set() {
let mut set = WeakRecordSet::new(|&record| record != 2);
diff --git a/Libraries/LibWeb/Rust/src/css/calc.rs b/Libraries/LibWeb/Rust/src/css/calc.rs
index a3586e1e685..4dac4cf4fdc 100644
--- a/Libraries/LibWeb/Rust/src/css/calc.rs
+++ b/Libraries/LibWeb/Rust/src/css/calc.rs
@@ -13,7 +13,6 @@
//! Nothing constructs these yet; the FFI construction surface follows with
//! the C++ staging.
-use crate::css::ffi_support::OwnedArc;
use crate::css::style_value::{
AnchorPayload, AnchorSizePayload, CalculatedPayload, RandomValueSharingPayload, StyleValueBox,
};
@@ -941,12 +940,6 @@ unsafe impl Send for CalcNodeHandle where CalcNode: Send + Sync {}
unsafe impl Sync for CalcNodeHandle where CalcNode: Send + Sync {}
impl CalcNodeHandle {
- /// # Safety
- /// `raw` must be a handle from one of the construction functions below.
- pub(crate) unsafe fn from_raw(raw: *const CalcNode) -> Self {
- Self { node: raw }
- }
-
pub(crate) fn from_arc(node: Arc<CalcNode>) -> Self {
Self {
node: Arc::into_raw(node),
@@ -1266,27 +1259,6 @@ pub(crate) fn calc_node_create_numeric_dimension(kind: u8, value: f64, unit: u8)
handle(CalcNode::Numeric(numeric))
}
-#[unsafe(no_mangle)]
-pub extern "C" fn rust_calc_node_release(node: OwnedArc<CalcNode>) {
- drop(node);
-}
-
-/// https://drafts.csswg.org/css-values-4/#determine-the-type-of-a-calculation
-/// Determines the type of the calculation rooted at `node` under the given
-/// resolve-as target. The result's valid flag is false when the tree does not
-/// type-check.
-#[unsafe(no_mangle)]
-pub extern "C" fn rust_calc_node_determine_type(
- node: &CalcNode,
- has_percentages_resolve_as: bool,
- resolve_as_is_number: bool,
- resolve_as_base: u8,
-) -> FfiNumericType {
- let resolve_as = resolve_as_from_fields(has_percentages_resolve_as, resolve_as_is_number, resolve_as_base);
- let percentage_leaf_type = percentage_leaf_type_for(resolve_as);
- FfiNumericType::from_calc(node.numeric_type(&percentage_leaf_type))
-}
-
/// Whether any leaf of the calculation is a percentage.
#[unsafe(no_mangle)]
pub extern "C" fn rust_calc_node_contains_percentage(node: &CalcNode) -> bool {
diff --git a/Libraries/LibWeb/Rust/src/css/property_metadata.rs b/Libraries/LibWeb/Rust/src/css/property_metadata.rs
index 8b9f3b41bff..3b4f8dd90fc 100644
--- a/Libraries/LibWeb/Rust/src/css/property_metadata.rs
+++ b/Libraries/LibWeb/Rust/src/css/property_metadata.rs
@@ -353,7 +353,7 @@ fn property_index(property_id: u16) -> usize {
}
/// The IDL attribute name of the property, https://drafts.csswg.org/cssom/#css-property-to-idl-attribute
-pub(crate) fn property_idl_name(property_id: u16) -> &'static str {
+pub fn property_idl_name(property_id: u16) -> &'static str {
PROPERTY_IDL_NAMES[property_index(property_id)]
}
diff --git a/Libraries/LibWeb/Rust/src/css/style/animations.rs b/Libraries/LibWeb/Rust/src/css/style/animations.rs
index 4ecc4fe6131..0a29430ca78 100644
--- a/Libraries/LibWeb/Rust/src/css/style/animations.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/animations.rs
@@ -591,9 +591,9 @@ impl CompactEffectTiming {
Some((sampled.effect, resolved))
}
- /// The key the effect's keyframes are sampled at with its timeline at `samples`, eased by `easing`, which is
- /// `AnimationEffect::transformed_progress()` scaled the way the host scales it. The outer `None` is
- /// a timeline the samples do not move; the inner one is an unresolved progress, which samples nothing.
+ /// The key the effect's keyframes are sampled at with its timeline at `samples`, eased by `easing`, which is the
+ /// transformed progress as a percentage scaled by `keyframes::KEY_SCALE_FACTOR`. The outer `None` is a timeline the
+ /// samples do not move; the inner one is an unresolved progress, which samples nothing.
#[must_use]
pub(crate) fn key_at(
&self,
@@ -628,8 +628,8 @@ impl CompactEffectTiming {
return Some(None);
};
- // `KeyframeEffect::AnimationKeyFrameKeyScaleFactor`, and the host's clamp to what a key can hold.
- let key = output_progress * 100.0 * 1000.0;
+ // NB: The transformed progress, scaled as a key, and clamped to what a key can hold.
+ let key = crate::animations::keyframes::scaled_offset(output_progress);
Some(Some(key.clamp(i64::MIN as f64, i64::MAX as f64)))
}
@@ -689,7 +689,7 @@ mod tests {
use crate::animations::snapshot::{EffectTimingSnapshot, TimelineClock, TimelineClockSource};
use crate::animations::timeline::AnimationTimelineId;
- use crate::animations::timing::{AnimationEffectTiming, AnimationReplaceState, FillMode, PlaybackDirection};
+ use crate::animations::timing::{AnimationEffectTiming, AnimationReplaceState, FillMode};
impl EffectTiming {
/// Changes the timing as the host would publish it.
@@ -828,53 +828,6 @@ mod tests {
assert_eq!(animation.key_at(AnimationTimelineSamples::at_tick(5000.0, &[])), None);
}
- #[test]
- fn a_key_follows_the_timeline_through_the_active_phase() {
- assert_eq!(key(&timing_at(250.0)), Some(Some(25_000.0)));
- assert_eq!(key(&timing_at(0.0)), Some(Some(0.0)));
- assert_eq!(key(&timing_at(1500.0)), Some(None), "no fill after the end");
- assert_eq!(key(&timing_at(-1.0)), Some(None), "no fill before the start");
- }
-
- #[test]
- fn a_key_fills_and_holds() {
- let mut timing = timing_at(1500.0);
- timing.change(|timing| timing.effect.fill_mode = FillMode::Both);
- assert_eq!(key(&timing), Some(Some(100_000.0)));
- timing.change(|timing| timing.timeline.current_time = ms(-500.0));
- assert_eq!(key(&timing), Some(Some(0.0)));
- timing.change(|timing| timing.playback.hold_time = ms(500.0));
- assert_eq!(key(&timing), Some(Some(50_000.0)), "a hold time wins over the timeline");
- }
-
- #[test]
- fn a_key_runs_each_iteration_in_its_direction() {
- let mut timing = timing_at(1250.0);
- timing.change(|timing| timing.effect.iteration_count = f64::INFINITY);
- assert_eq!(key(&timing), Some(Some(25_000.0)));
- timing.change(|timing| timing.effect.playback_direction = PlaybackDirection::Alternate);
- assert_eq!(
- key(&timing),
- Some(Some(75_000.0)),
- "an alternate second iteration runs backwards"
- );
- timing.change(|timing| timing.effect.playback_direction = PlaybackDirection::Reverse);
- assert_eq!(key(&timing), Some(Some(75_000.0)));
- timing.change(|timing| timing.effect.playback_direction = PlaybackDirection::Normal);
- timing.change(|timing| timing.playback.playback_rate = 2.0);
- assert_eq!(key(&timing), Some(Some(50_000.0)));
- }
-
- #[test]
- fn a_key_is_eased_by_the_effect() {
- let mut timing = timing_at(500.0);
- timing.easing = crate::css::easing::Easing::Steps {
- interval_count: 2,
- position: crate::css::easing::STEP_POSITION_JUMP_START,
- };
- assert_eq!(key(&timing), Some(Some(100_000.0)));
- }
-
#[test]
fn a_key_is_where_the_host_sampled_the_timeline() {
let timing = timing_at(500.0);
diff --git a/Libraries/LibWeb/Rust/src/css/style/engine_calls.rs b/Libraries/LibWeb/Rust/src/css/style/engine_calls.rs
index 6fca05c3d5e..ab958f9e928 100644
--- a/Libraries/LibWeb/Rust/src/css/style/engine_calls.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/engine_calls.rs
@@ -1592,31 +1592,26 @@ pub extern "C" fn style_engine_counter(
name.as_ptr()
}
-/// Decides what the transition step of `input`'s target does to its transitions, as the target's style changes from the
-/// record `before` to the record `after` it installed, and hands `on_actions` one action per property it decided over.
-/// The style update the host drains decided the step beside the row of an element whose step nothing but the
-/// engine's records decides; any other the render owner decides, reading the transform reference box of the target's
-/// element's box as it does.
+/// Decides what the transition step of the target `input` names, which holds the transitions `existing`, does to its
+/// transitions, as the target's style changes from the record `before` to the record `after` it installed, and hands
+/// `on_actions` one action per property it decided over. The style update the host drains decided the step beside the
+/// row of an element whose step nothing but the engine's records decides; any other the render owner decides, reading
+/// the transform reference box of the target's element's box as it does.
///
/// # Safety
///
-/// `host` must be a live document host, on its document's thread, `before` and `after` records the host holds, and
-/// `input` must be valid. The values the actions point at live until `on_actions` returns.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn style_engine_decide_transitions(
+/// `before` and `after` must be records the host holds. The values the actions point at live until `on_actions`
+/// returns.
+pub(crate) unsafe fn decide_transitions(
host: &DocumentHost,
read: &crate::render_state::BegunRead,
before: *const c_void,
after: *const c_void,
input: &FfiTransitionInput,
- on_actions: unsafe extern "C" fn(*mut c_void, *const FfiTransitionAction, usize),
- context: *mut c_void,
+ existing: &[crate::css::transition::FfiExistingTransition],
+ mut on_actions: impl FnMut(&[FfiTransitionAction]),
) {
// SAFETY: Guaranteed by the caller.
- let existing = unsafe { ak::slice_from_raw_parts(input.existing_transitions, input.existing_transition_count) };
- // SAFETY: As above.
- let hand_over = |actions: &[FfiTransitionAction]| unsafe { on_actions(context, actions.as_ptr(), actions.len()) };
- // SAFETY: As above.
let (Some(before), Some(after)) = (unsafe { super::bridge::retain_host_record(before) }, unsafe {
super::bridge::retain_host_record(after)
}) else {
@@ -1631,7 +1626,7 @@ pub unsafe extern "C" fn style_engine_decide_transitions(
.flatten(),
};
if decision.element.is_some()
- && host.answer_decided_transition_step(input.target_node, &decision, existing, hand_over)
+ && host.answer_decided_transition_step(input.target_node, &decision, existing, &mut on_actions)
{
return;
}
@@ -1647,7 +1642,7 @@ pub unsafe extern "C" fn style_engine_decide_transitions(
)
});
actions.extend_from_slice(&custom_properties.actions);
- hand_over(&actions);
+ on_actions(&actions);
}
#[cfg(test)]
diff --git a/Libraries/LibWeb/Rust/src/css/style_compute.rs b/Libraries/LibWeb/Rust/src/css/style_compute.rs
index 2eb123f606c..e06d56e95d6 100644
--- a/Libraries/LibWeb/Rust/src/css/style_compute.rs
+++ b/Libraries/LibWeb/Rust/src/css/style_compute.rs
@@ -2213,7 +2213,7 @@ struct ComputedStoreEntry<'a> {
computed: NativeValue,
}
-#[derive(Clone, Copy)]
+#[derive(Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum FfiAnimationTimelineKind {
Document,
@@ -5894,6 +5894,19 @@ pub unsafe extern "C" fn rust_settled_animation_plan(
}) else {
return;
};
+ // https://drafts.csswg.org/css-animations-1/#animations
+ // Setting the 'display' property to 'none' will terminate any running animation applied to the element and its
+ // descendants. If an element has a 'display' of 'none', updating 'display' to a value other than 'none' will
+ // start all animations applied to the element by the 'animation-name' property, as well as all animations
+ // applied to descendants with 'display' other than 'none'.
+ // NB: We must not start animations on elements that are not rendered due to display:none. Once display becomes
+ // something other than none, the resulting style recomputation applies the plan again and starts them.
+ // Termination of running animations when display becomes none is handled by
+ // Element::play_or_cancel_animations_after_display_property_change(). An element that has no animations and
+ // starts none has nothing to hold or publish.
+ if !has_animations && (plan.definitions.is_empty() || in_display_none_subtree) {
+ return;
+ }
unsafe {
apply(
context,
diff --git a/Libraries/LibWeb/Rust/src/css/style_value.rs b/Libraries/LibWeb/Rust/src/css/style_value.rs
index 5603f2bd2d3..15be75e4186 100644
--- a/Libraries/LibWeb/Rust/src/css/style_value.rs
+++ b/Libraries/LibWeb/Rust/src/css/style_value.rs
@@ -4383,36 +4383,6 @@ pub unsafe extern "C" fn rust_style_value_create_color_function(
))))
}
-/// Takes ownership of one strong reference to the calculation node; the byte blob and ranges
-/// are copied.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn rust_style_value_create_calculated(
- rust_calculation: *const crate::css::calc::CalcNode,
- resolved_type: crate::css::calc::FfiNumericType,
- has_percentages_resolve_as: bool,
- resolve_as_is_number: bool,
- resolve_as_base: u8,
- percentages_resolve_as: u8,
- resolve_numbers_as_integers: bool,
- accepted_ranges: *const RetainedNumericRangeByType,
- accepted_range_count: usize,
-) -> *const StyleValueData {
- StyleValueArc::into_raw(StyleValueArc::new(StyleValueData::Calculated(StyleValueBox::new(
- CalculatedPayload {
- rust_calculation: unsafe { crate::css::calc::CalcNodeHandle::from_raw(rust_calculation) },
- resolve_as_is_number,
- resolve_as_base,
- resolved_type,
- has_percentages_resolve_as,
- percentages_resolve_as,
- resolve_numbers_as_integers,
- accepted_ranges: RetainedNumericRangeList::from_vec(unsafe {
- read_elements(accepted_ranges, accepted_range_count)
- }),
- },
- ))))
-}
-
/// Copies the borrowed native URL text and takes ownership of each modifier string.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rust_style_value_create_image(
diff --git a/Libraries/LibWeb/Rust/src/css/transition.rs b/Libraries/LibWeb/Rust/src/css/transition.rs
index 164df2dead5..245d5914bcd 100644
--- a/Libraries/LibWeb/Rust/src/css/transition.rs
+++ b/Libraries/LibWeb/Rust/src/css/transition.rs
@@ -37,11 +37,8 @@ pub struct FfiExistingTransition {
pub reversing_shortening_factor: f64,
}
-#[repr(C)]
+/// The target of a transition step.
pub struct FfiTransitionInput {
- /// The transitions the target holds, each for a different property.
- pub existing_transitions: *const FfiExistingTransition,
- pub existing_transition_count: usize,
/// The target's style node.
pub target_node: u32,
/// The target's pseudo-element kind, or `u8::MAX` for an element.
@@ -754,9 +751,6 @@ struct RunningTransitionAt {
started_at: f64,
}
-/// The key a published keyframe at 100% sits at: `KeyframeEffect::AnimationKeyFrameKeyScaleFactor` times 100.
-const FULL_KEY: f64 = 100.0 * 1000.0;
-
/// The transitions the host runs on the element `node` names, as they stand at `at`, the time a step decides at, in
/// the document timeline's milliseconds. The CSS animations the host runs on it are not among them: the ticks sample
/// those as they are.
@@ -979,7 +973,7 @@ impl RowTransitions {
end_value: transition.end_value,
reversing_adjusted_start_value: transition.reversing_adjusted_start_value,
// The output of the timing function of a running transition at the time of the style change event.
- timing_function_output: transition.key.map_or(0.0, |key| key / FULL_KEY),
+ timing_function_output: transition.key.map_or(0.0, crate::animations::keyframes::offset_of_key),
reversing_shortening_factor: transition.reversing_shortening_factor,
})
.collect();
diff --git a/Libraries/LibWeb/Rust/src/css/typed_om.rs b/Libraries/LibWeb/Rust/src/css/typed_om.rs
index 6b429025ff9..1ed4c2b30cc 100644
--- a/Libraries/LibWeb/Rust/src/css/typed_om.rs
+++ b/Libraries/LibWeb/Rust/src/css/typed_om.rs
@@ -12,7 +12,9 @@ use std::collections::BTreeMap;
use std::sync::Arc;
pub use crate::css::calc::{CalcNode, CalcNumericType as NumericType, FfiNumericType};
-use crate::css::calc::{CalcNumericValue, base_type_from_value_type, canonical_unit_code, resolve_as_for_value_type};
+use crate::css::calc::{
+ CalcNodeHandle, CalcNumericValue, base_type_from_value_type, canonical_unit_code, resolve_as_for_value_type,
+};
use crate::css::css_enums::{keyword, keyword_from_ascii_case_insensitive};
use crate::css::css_string::CssString;
use crate::css::dimension_units::{
@@ -40,10 +42,11 @@ use crate::css::style_compute::{
LENGTH_UNIT_CANONICAL_PX_RATIOS, LENGTH_UNIT_NAMES, rust_style_value_is_computationally_independent,
};
use crate::css::style_value::style_value_create_grid_track_size_list;
-pub use crate::css::style_value::{ReifiedUnresolvedSegment, RetainedStyleValueData as RetainedStyleValue};
use crate::css::style_value::{
- RetainedNumericRangeByType, StyleValueData, rust_style_value_create_calculated, rust_style_value_create_value_list,
+ CalculatedPayload, RetainedNumericRangeByType, RetainedNumericRangeList, StyleValueBox, StyleValueData,
+ rust_style_value_create_value_list,
};
+pub use crate::css::style_value::{ReifiedUnresolvedSegment, RetainedStyleValueData as RetainedStyleValue};
use crate::css::style_value_arc::StyleValueArc;
use crate::css::value_codes::{
VALUE_TYPE_ANGLE, VALUE_TYPE_FLEX, VALUE_TYPE_FREQUENCY, VALUE_TYPE_IMAGE, VALUE_TYPE_INTEGER, VALUE_TYPE_LENGTH,
@@ -787,23 +790,18 @@ pub(crate) fn calculated_value(
.map(|range| RetainedNumericRangeByType::new(range.value_type, range.min, range.max))
.collect()
};
- let calculation = Arc::into_raw(calculation);
- // SAFETY: This hands over one strong reference to the calculation, and the ranges are readable for their length.
- let value = unsafe {
- rust_style_value_create_calculated(
- calculation,
- FfiNumericType::from_calc(Some(numeric_type)),
- resolve_as.is_some(),
- resolve_as == Some(VALUE_TYPE_NUMBER),
- resolve_as.and_then(base_type_from_value_type).unwrap_or(0),
- resolve_as.unwrap_or(0),
- property_accepts_value_type(property_id, VALUE_TYPE_INTEGER),
- ranges.as_ptr(),
- ranges.len(),
- )
- };
- // SAFETY: The call hands over a strong reference to a new value.
- unsafe { RetainedStyleValue::from_raw(value.cast()) }
+ RetainedStyleValue::from_arc(StyleValueArc::new(StyleValueData::Calculated(StyleValueBox::new(
+ CalculatedPayload {
+ rust_calculation: CalcNodeHandle::from_arc(calculation),
+ resolve_as_is_number: resolve_as == Some(VALUE_TYPE_NUMBER),
+ resolve_as_base: resolve_as.and_then(base_type_from_value_type).unwrap_or(0),
+ resolved_type: FfiNumericType::from_calc(Some(numeric_type)),
+ has_percentages_resolve_as: resolve_as.is_some(),
+ percentages_resolve_as: resolve_as.unwrap_or(0),
+ resolve_numbers_as_integers: property_accepts_value_type(property_id, VALUE_TYPE_INTEGER),
+ accepted_ranges: RetainedNumericRangeList::from_vec(ranges),
+ },
+ ))))
}
fn opacity_value(value: RetainedStyleValue) -> RetainedStyleValue {
diff --git a/Libraries/LibWeb/Rust/src/painting/ffi.rs b/Libraries/LibWeb/Rust/src/painting/ffi.rs
index 93ad7bd37d9..64215a0121d 100644
--- a/Libraries/LibWeb/Rust/src/painting/ffi.rs
+++ b/Libraries/LibWeb/Rust/src/painting/ffi.rs
@@ -1338,22 +1338,32 @@ pub unsafe extern "C" fn render_state_background_color_animation_keyframe_colors
}
/// Builds the animation of the request's target kind for the effect and keeps it pending with the
-/// effect. The target's nodes come from the arena's main tree.
+/// effect, which runs with the timing of the effect record `effect` and of the record of its associated animation
+/// `animation`. The target's nodes come from the arena's main tree.
///
/// # Safety
///
/// `document_host` must be a live document host on its document's thread, and the request and host, with every range
-/// they address, live for the call. The host's callbacks run synchronously and may not touch the arena.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn compositor_animation_effect_build(
+/// they address, live for the call. The host's callbacks run synchronously and may not touch the arena or the records.
+pub(crate) unsafe fn build_compositor_animation_effect(
state: &mut CompositorAnimationEffectState,
document_host: &DocumentHost,
- request: *const crate::painting::host::FfiCompositorAnimationRequest,
+ mut ffi_request: crate::painting::host::FfiCompositorAnimationRequest,
+ effect: &crate::animations::effect::AnimationEffectCell,
+ animation: &crate::animations::animation::AnimationCell,
host: &crate::painting::host::FfiCompositorAnimationHost,
) -> crate::painting::host::FfiCompositorAnimationBuildOutcome {
use crate::painting::visual_animation_builder::{Host, Request};
+ // NB: The easing descriptor borrows the control points of the effect's timing function, which the build leaves as
+ // they are.
+ ffi_request.timing.playback_rate = animation.borrow().playback().playback_rate;
+ {
+ let effect = effect.borrow();
+ ffi_request.timing.effect = effect.timing();
+ ffi_request.timing.easing = effect.timing_function().descriptor();
+ }
// SAFETY: Guaranteed by the caller.
- let mut request = unsafe { Request::new(&*request) };
+ let mut request = unsafe { Request::new(&ffi_request) };
let host = Host::new(host);
let layout_node = request.layout_node();
if request.target_kind() == crate::painting::host::FfiVisualAnimationTargetKind::Transform {
@@ -1377,60 +1387,6 @@ pub unsafe extern "C" fn compositor_animation_effect_build(
})
}
-#[unsafe(no_mangle)]
-pub extern "C" fn compositor_animation_effect_discard_pending(
- state: &mut CompositorAnimationEffectState,
- kind: crate::painting::host::FfiVisualAnimationTargetKind,
-) {
- state.discard_pending(kind);
-}
-
-#[unsafe(no_mangle)]
-pub extern "C" fn compositor_animation_effect_has_pending(state: &CompositorAnimationEffectState) -> bool {
- state.has_pending()
-}
-
-#[unsafe(no_mangle)]
-pub extern "C" fn compositor_animation_effect_clear_pending(state: &mut CompositorAnimationEffectState) {
- state.clear_pending();
-}
-
-#[unsafe(no_mangle)]
-pub extern "C" fn compositor_animation_effect_has_retained(state: &CompositorAnimationEffectState) -> bool {
- state.has_retained()
-}
-
-#[unsafe(no_mangle)]
-pub extern "C" fn compositor_animation_effect_clear_retained(state: &mut CompositorAnimationEffectState) {
- state.clear_retained();
-}
-
-/// # Safety
-///
-/// The request and host, with every range they address, must be live for the call.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn compositor_animation_effect_only_translates_horizontally(
- request: *const crate::painting::host::FfiCompositorAnimationRequest,
- host: &crate::painting::host::FfiCompositorAnimationHost,
-) -> bool {
- use crate::painting::visual_animation_builder::{Host, Request, effect_only_translates_horizontally};
- let request = unsafe { Request::new(&*request) };
- effect_only_translates_horizontally(&request, &Host::new(host))
-}
-
-/// # Safety
-///
-/// The request and host, with every range they address, must be live for the call.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn compositor_animation_effect_transform_preserves_axes(
- request: *const crate::painting::host::FfiCompositorAnimationRequest,
- host: &crate::painting::host::FfiCompositorAnimationHost,
-) -> bool {
- use crate::painting::visual_animation_builder::{Host, Request, effect_transform_preserves_axes};
- let request = unsafe { Request::new(&*request) };
- effect_transform_preserves_axes(&request, &Host::new(host))
-}
-
/// Starts an update pass: the effects publish into an empty document list.
///
/// # Safety
diff --git a/Libraries/LibWeb/Rust/src/painting/ffi/main_thread_entries.rs b/Libraries/LibWeb/Rust/src/painting/ffi/main_thread_entries.rs
index 9a4dc1eec58..7089a3f8aa9 100644
--- a/Libraries/LibWeb/Rust/src/painting/ffi/main_thread_entries.rs
+++ b/Libraries/LibWeb/Rust/src/painting/ffi/main_thread_entries.rs
@@ -369,19 +369,6 @@ pub extern "C" fn render_state_begin_compositor_animation_update(host: &crate::r
host.begin_compositor_animation_update();
}
-/// Publishes the effect's pending animations: they become the ones it retains, and copies join the compositor
-/// animations of the current update pass of `host`'s document.
-///
-#[unsafe(no_mangle)]
-pub extern "C" fn compositor_animation_effect_publish_pending(
- state: &mut crate::painting::visual_animation_builder::CompositorAnimationEffectState,
- host: &crate::render_state::DocumentHost,
- reuse_retained_timing_anchors: bool,
-) {
- let animations = state.publish_pending(reuse_retained_timing_anchors);
- host.publish_compositor_animations(animations);
-}
-
/// Ends the current update pass of the compositor animations of `host`'s document, and gives the visual context tree,
/// prepared up to date, what its effects published where `publish_pending`, or none.
///
diff --git a/Libraries/LibWeb/Rust/src/painting/visual_animation_builder.rs b/Libraries/LibWeb/Rust/src/painting/visual_animation_builder.rs
index b5ba6d60444..adcafd0028e 100644
--- a/Libraries/LibWeb/Rust/src/painting/visual_animation_builder.rs
+++ b/Libraries/LibWeb/Rust/src/painting/visual_animation_builder.rs
@@ -10,7 +10,7 @@
//! context tree receives.
use crate::animations::keyframes::{
- CompositeOperationOrAuto, FINAL_KEY, Keyframe, KeyframeEasing, KeyframeSet, KeyframeValue,
+ CompositeOperationOrAuto, Keyframe, KeyframeEasing, KeyframeSet, KeyframeValue, offset_of_key,
};
use crate::css::absolutize::number_from_value;
use crate::css::color_resolution::{ColorResolutionInput, FfiColorResolutionStyle, to_color};
@@ -851,7 +851,7 @@ impl CompositorAnimationEffectState {
let value = value.as_ref()?.clone();
Some(VisualAnimationKeyframe {
#[expect(clippy::cast_precision_loss)]
- offset: keyframe.key as f64 / FINAL_KEY as f64,
+ offset: offset_of_key(keyframe.key as f64),
easing: request.easing_of(keyframe)?,
value,
})
@@ -1172,8 +1172,7 @@ mod tests {
})),
)],
};
- #[expect(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
- let key = (keyframe.offset * FINAL_KEY as f64) as u64;
+ let key = crate::animations::keyframes::key_of_offset(keyframe.offset);
(key, keyframe.composite, keyframe.easing.clone(), declarations)
})
.collect(),
diff --git a/Libraries/LibWeb/SVG/SMILTimeContainer.cpp b/Libraries/LibWeb/SVG/SMILTimeContainer.cpp
index 6df989fceaf..782ad455800 100644
--- a/Libraries/LibWeb/SVG/SMILTimeContainer.cpp
+++ b/Libraries/LibWeb/SVG/SMILTimeContainer.cpp
@@ -4,7 +4,7 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-#include <LibWeb/Animations/AnimationTimeline.h>
+#include <LibWeb/Animations/RecordHandles.h>
#include <LibWeb/DOM/Document.h>
#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
#include <LibWeb/SVG/SMILTimeContainer.h>
@@ -40,7 +40,7 @@ void SMILTimeContainer::visit_edges(GC::Cell::Visitor& visitor)
double SMILTimeContainer::document_timeline_time() const
{
- auto time = m_document->timeline()->current_time();
+ auto time = m_document->timeline().current_time();
return time.has_value() ? time->value : 0.;
}
@@ -151,7 +151,7 @@ void SMILTimeContainer::synchronize_animation(Animations::AnimationRef const& an
// NB: The record sets the start time or the current time of the animation. The animation has no promises to
// settle, but the microtask checkpoint as the execution context ends stays where it was.
HTML::TemporaryExecutionContext execution_context { m_document->relevant_settings_object() };
- Animations::RustFFI::animations_smil_animation_synchronize(&animation.record(), m_zero_time, m_is_paused, m_paused_time, Animations::perform_host_effect);
+ Animations::RustFFI::animations_smil_animation_synchronize(&animation.record(), m_zero_time, m_is_paused, m_paused_time, Animations::web_animation_perform_host_effect);
}
}
diff --git a/Libraries/LibWeb/SVG/SVGAnimateElement.cpp b/Libraries/LibWeb/SVG/SVGAnimateElement.cpp
index 70d6a0620c4..9d76078d866 100644
--- a/Libraries/LibWeb/SVG/SVGAnimateElement.cpp
+++ b/Libraries/LibWeb/SVG/SVGAnimateElement.cpp
@@ -4,7 +4,6 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-#include <LibWeb/Animations/AnimationEffect.h>
#include <LibWeb/CSS/StyleValues/StyleValue.h>
#include <LibWeb/SVG/AttributeNames.h>
#include <LibWeb/SVG/AttributeParsing.h>
diff --git a/Libraries/LibWeb/SVG/SVGAnimationElement.cpp b/Libraries/LibWeb/SVG/SVGAnimationElement.cpp
index e93b732b812..19a38f21a60 100644
--- a/Libraries/LibWeb/SVG/SVGAnimationElement.cpp
+++ b/Libraries/LibWeb/SVG/SVGAnimationElement.cpp
@@ -7,7 +7,6 @@
#include <LibWeb/SVG/SVGAnimationElement.h>
#include <AK/Math.h>
-#include <LibWeb/Animations/AnimationTimeline.h>
#include <LibWeb/CSS/PropertyNameAndID.h>
#include <LibWeb/CSS/StyleEngineInput.h>
#include <LibWeb/CSS/StyleValues/StyleValue.h>
@@ -283,7 +282,7 @@ static Animations::KeyframeSetHandle keyframe_set_of(Vector<SVGKeyframe> const&
processed_keyframes.ensure_capacity(keyframes.size());
for (auto const& keyframe : keyframes) {
Animations::RustFFI::FfiProcessedKeyframe processed_keyframe {};
- processed_keyframe.key = static_cast<u64>(keyframe.offset * 100 * 1000.0);
+ processed_keyframe.offset = keyframe.offset;
processed_keyframe.composite = Animations::RustFFI::CompositeOperationOrAuto::Auto;
if (keyframe.easing.has_value()) {
processed_keyframe.has_easing = true;
@@ -307,11 +306,11 @@ void SVGAnimationElement::update_animation()
{
if (auto animation = exchange(m_animation, {}); animation.has_value()) {
exchange(m_animation_time_container, nullptr)->remove_animation(*animation);
- // NB: Cancelling an animation that is not idle runs in an execution context, as an Animation's does.
+ // NB: Canceling an animation that is not idle runs in an execution context, as an Animation's does.
Optional<HTML::TemporaryExecutionContext> execution_context;
- if (animation->timing_state().play_state != Animations::RustFFI::AnimationPlayState::Idle)
+ if (animation->play_state() != Animations::RustFFI::AnimationPlayState::Idle)
execution_context.emplace(document().relevant_settings_object());
- Animations::RustFFI::animations_animation_cancel(&animation->record(), true, Animations::perform_host_effect);
+ Animations::RustFFI::animations_animation_cancel(&animation->record(), true, Animations::web_animation_perform_host_effect);
execution_context.clear();
Animations::RustFFI::animations_smil_animation_let_go(&animation->record());
}
@@ -375,7 +374,7 @@ void SVGAnimationElement::update_animation()
.timing_function_serialization = timing_function_serialization.raw_identity(),
.begin_time = *begin_time,
};
- m_animation = Animations::AnimationRef::adopt(*Animations::RustFFI::animations_smil_animation_create(&description, &document().timeline()->record(), Animations::perform_host_effect));
+ m_animation = Animations::AnimationRef::adopt(*Animations::RustFFI::animations_smil_animation_create(&description, Animations::web_animation_perform_host_effect));
CSS::record_attr_names_read_by_keyframes(*target, keyframe_set);
m_animation_time_container = time_container;
time_container->add_animation(*m_animation);
@@ -543,11 +542,7 @@ void SVGAnimationElement::end_element_at(float offset)
void SVGAnimationElement::queue_time_event(Animations::RustFFI::TimeEventType type, i32 detail)
{
// NB: Time events are dispatched along with the other animation events of the document, which creates each as it
- // dispatches it, with the time stamp of now.
- auto* timeline = static_cast<Animations::AnimationTimeline*>(Animations::RustFFI::animations_animation_timeline(&m_animation->record()));
- auto scheduled_event_time = timeline && timeline->can_convert_a_timeline_time_to_an_origin_relative_time()
- ? timeline->convert_a_timeline_time_to_an_origin_relative_time(timeline->current_time())
- : Optional<double> {};
+ // dispatches it, with the time stamp of now, and schedules each at the time of the animation's timeline.
document().append_pending_animation_event(*m_animation, {
.kind = Animations::RustFFI::PendingAnimationEventKind::Time,
.css_event_type = {},
@@ -557,7 +552,7 @@ void SVGAnimationElement::queue_time_event(Animations::RustFFI::TimeEventType ty
.elapsed_time = 0,
.current_time = {},
.timeline_time = {},
- .scheduled_event_time = Animations::to_ffi(scheduled_event_time),
+ .scheduled_event_time = {},
.time_stamp = HighResolutionTime::current_high_resolution_time(HTML::relevant_global_object(*this)),
});
}
diff --git a/Meta/Linters/check_libweb_realm_mentions.py b/Meta/Linters/check_libweb_realm_mentions.py
index 7e854cce6fc..cd484ed2c6e 100755
--- a/Meta/Linters/check_libweb_realm_mentions.py
+++ b/Meta/Linters/check_libweb_realm_mentions.py
@@ -37,8 +37,9 @@ CHECKED_SUFFIXES = {
ALLOWED_REALM_MENTIONS = {
"Animations": (
2,
- 8,
- "animation playback events, promise settling and CSS value materialization still pass spec-selected realms",
+ 4,
+ "host callbacks of the Rust animation code take the realm it selects to read the current high resolution time, "
+ "find an animation's relevant global object and wrap elements",
),
"CSS": (
7,
diff --git a/Tests/LibWeb/Text/expected/WebAnimations/animate-target-adopted-by-keyframes.txt b/Tests/LibWeb/Text/expected/WebAnimations/animate-target-adopted-by-keyframes.txt
new file mode 100644
index 00000000000..04b486f849e
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/WebAnimations/animate-target-adopted-by-keyframes.txt
@@ -0,0 +1 @@
+timeline of the other document: true
diff --git a/Tests/LibWeb/Text/expected/WebAnimations/playback-events-are-trusted.txt b/Tests/LibWeb/Text/expected/WebAnimations/playback-events-are-trusted.txt
new file mode 100644
index 00000000000..a444a23e422
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/WebAnimations/playback-events-are-trusted.txt
@@ -0,0 +1,3 @@
+finish isTrusted: true
+cancel isTrusted: true
+constructed isTrusted: false
diff --git a/Tests/LibWeb/Text/expected/WebAnimations/ready-promise-read-while-resolving.txt b/Tests/LibWeb/Text/expected/WebAnimations/ready-promise-read-while-resolving.txt
new file mode 100644
index 00000000000..6a89623d591
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/WebAnimations/ready-promise-read-while-resolving.txt
@@ -0,0 +1 @@
+ready: read while resolving is the same promise: true, later read too: true
diff --git a/Tests/LibWeb/Text/expected/WebAnimations/scroll-timeline-nearest-source-through-shadow-root.txt b/Tests/LibWeb/Text/expected/WebAnimations/scroll-timeline-nearest-source-through-shadow-root.txt
new file mode 100644
index 00000000000..097d0c12f99
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/WebAnimations/scroll-timeline-nearest-source-through-shadow-root.txt
@@ -0,0 +1,2 @@
+shadow root child: host
+slotted: slot-scroller
diff --git a/Tests/LibWeb/Text/input/WebAnimations/animate-target-adopted-by-keyframes.html b/Tests/LibWeb/Text/input/WebAnimations/animate-target-adopted-by-keyframes.html
new file mode 100644
index 00000000000..f25d58a6630
--- /dev/null
+++ b/Tests/LibWeb/Text/input/WebAnimations/animate-target-adopted-by-keyframes.html
@@ -0,0 +1,18 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<iframe id="frame"></iframe>
+<script>
+ test(() => {
+ // The animation gets the default timeline of the document the target is in after its keyframes are processed.
+ const otherDocument = frame.contentDocument;
+ const target = document.createElement("div");
+ document.body.appendChild(target);
+ const animation = target.animate({
+ get opacity() {
+ otherDocument.adoptNode(target);
+ return [0, 1];
+ },
+ }, 1000);
+ println(`timeline of the other document: ${animation.timeline === otherDocument.timeline}`);
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/WebAnimations/playback-events-are-trusted.html b/Tests/LibWeb/Text/input/WebAnimations/playback-events-are-trusted.html
new file mode 100644
index 00000000000..cdc7c43b589
--- /dev/null
+++ b/Tests/LibWeb/Text/input/WebAnimations/playback-events-are-trusted.html
@@ -0,0 +1,19 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<div id="target"></div>
+<script>
+ asyncTest(async done => {
+ const finishing = target.animate({ opacity: [0, 1] }, 1000);
+ const finishEvent = new Promise(resolve => { finishing.onfinish = resolve; });
+ finishing.finish();
+ println(`finish isTrusted: ${(await finishEvent).isTrusted}`);
+
+ const canceling = target.animate({ opacity: [0, 1] }, 1000);
+ const cancelEvent = new Promise(resolve => { canceling.oncancel = resolve; });
+ canceling.cancel();
+ println(`cancel isTrusted: ${(await cancelEvent).isTrusted}`);
+
+ println(`constructed isTrusted: ${new AnimationPlaybackEvent("finish").isTrusted}`);
+ done();
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/WebAnimations/ready-promise-read-while-resolving.html b/Tests/LibWeb/Text/input/WebAnimations/ready-promise-read-while-resolving.html
new file mode 100644
index 00000000000..bcea745e027
--- /dev/null
+++ b/Tests/LibWeb/Text/input/WebAnimations/ready-promise-read-while-resolving.html
@@ -0,0 +1,21 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ function readWhileResolving(animation, name) {
+ let inner;
+ Object.defineProperty(animation, "then", {
+ configurable: true,
+ get() {
+ delete animation.then;
+ inner = animation[name];
+ return undefined;
+ },
+ });
+ const outer = animation[name];
+ println(`${name}: read while resolving is the same promise: ${inner === outer}, later read too: ${animation[name] === outer}`);
+ }
+
+ test(() => {
+ readWhileResolving(new Animation(), "ready");
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/WebAnimations/scroll-timeline-nearest-source-through-shadow-root.html b/Tests/LibWeb/Text/input/WebAnimations/scroll-timeline-nearest-source-through-shadow-root.html
new file mode 100644
index 00000000000..e229da17112
--- /dev/null
+++ b/Tests/LibWeb/Text/input/WebAnimations/scroll-timeline-nearest-source-through-shadow-root.html
@@ -0,0 +1,38 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<style>
+ @keyframes grow {
+ from { width: 10px; }
+ to { width: 20px; }
+ }
+ #host {
+ height: 100px;
+ overflow: scroll;
+ }
+ #slotted {
+ height: 200px;
+ animation: grow 1s linear;
+ animation-timeline: scroll(nearest);
+ }
+</style>
+<div id="host"></div>
+<div id="slotted-host"><div id="slotted"></div></div>
+<script>
+ test(() => {
+ // The nearest scroll container of a direct child of a shadow root is found through the flat tree: the shadow
+ // host here.
+ const shadow = host.attachShadow({ mode: "open" });
+ shadow.innerHTML = `<style>
+ @keyframes grow { from { width: 10px; } to { width: 20px; } }
+ #target { height: 200px; animation: grow 1s linear; animation-timeline: scroll(nearest); }
+ </style><div id="target"></div>`;
+ const target = shadow.getElementById("target");
+ println(`shadow root child: ${target.getAnimations()[0].timeline.source?.id}`);
+
+ // The nearest scroll container of a slotted element is the one around its slot.
+ document.getElementById("slotted-host").attachShadow({ mode: "open" }).innerHTML =
+ `<div id="slot-scroller" style="height: 100px; overflow: scroll"><slot></slot></div>`;
+ const source = document.getElementById("slotted").getAnimations()[0].timeline.source;
+ println(`slotted: ${source?.id || source?.tagName}`);
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/css/style-memory/bytes-per-animated-element.html b/Tests/LibWeb/Text/input/css/style-memory/bytes-per-animated-element.html
index 068a3d27641..4ec4271a2c8 100644
--- a/Tests/LibWeb/Text/input/css/style-memory/bytes-per-animated-element.html
+++ b/Tests/LibWeb/Text/input/css/style-memory/bytes-per-animated-element.html
@@ -47,7 +47,6 @@
// with every element running the same @keyframes rule).
// - cssAnimations: each CSS animation's name and applied definition.
// - styleValues: the animated value of the longhand the payload of its group holds.
- // - animationObjects: the Animation objects, which a CSS animation or transition only has once script asks for it.
// - animationRecords: the records the animation and its effect keep their state in, a transition's keyframes, and
// the element's lists of its animations and of the effect descriptions it published to the engine.
const animationBudgets = {
@@ -64,7 +63,6 @@
animationEffects: 416,
cssAnimations: 240,
cppInstalledStyles: 8,
- animationObjects: 0,
animationRecords: 856,
};
const transitionBudgets = {
@@ -79,7 +77,6 @@
layoutStyleColumns: 28,
animationEffects: 348,
cppInstalledStyles: 8,
- animationObjects: 0,
animationRecords: 1058,
};