Truly independent web browser
LibWeb: Update only the animations a timeline update may change
Andreas Klingc804f056bda8
diff --git a/Libraries/LibWeb/Animations/RecordHandles.h b/Libraries/LibWeb/Animations/RecordHandles.hindex 0cc2952d51c..170009cd1f5 100644--- a/Libraries/LibWeb/Animations/RecordHandles.h+++ b/Libraries/LibWeb/Animations/RecordHandles.h@@ -268,6 +268,8 @@ public:}EndIterator end() const { return {}; }+ bool contains(AnimationRef const& animation) const { return RustFFI::animations_weak_animation_set_contains(m_set, &animation.record()); }+protected:RustFFI::WeakAnimationSet* m_set { nullptr };};@@ -278,4 +280,19 @@ inline WeakAnimationSetView associated_animations_of(TimelineView timeline)return WeakAnimationSetView { *RustFFI::animations_timeline_associated_animations(&timeline.record()) };}+// NB: The animations associated with a timeline that an update of its current time may change, none of which it keeps+// alive. The others have finished on a monotonically increasing timeline and have no pending task. This includes+// every running animation of the timeline, and may include some that are no longer associated with it, until the+// timeline next updates.+inline WeakAnimationSetView animations_needing_update_of(TimelineView timeline)+{+ return WeakAnimationSetView { *RustFFI::animations_timeline_animations_needing_update(&timeline.record()) };+}++// NB: The animations associated with the elements of a document, none of which it keeps alive.+inline WeakAnimationSetView associated_animations_of(RustFFI::DocumentAnimations& animations)+{+ return WeakAnimationSetView { *RustFFI::animations_document_associated_animations(&animations) };+}+}diff --git a/Libraries/LibWeb/HTML/EventLoop/ClockPlan.cpp b/Libraries/LibWeb/HTML/EventLoop/ClockPlan.cppindex 14369d98810..895d5d244b8 100644--- a/Libraries/LibWeb/HTML/EventLoop/ClockPlan.cpp+++ b/Libraries/LibWeb/HTML/EventLoop/ClockPlan.cpp@@ -4,6 +4,7 @@* SPDX-License-Identifier: BSD-2-Clause*/+#include <AK/HashTable.h>#include <AK/Math.h>#include <LibWeb/Animations/AnimationEffect.h>#include <LibWeb/Animations/RecordHandles.h>@@ -176,7 +177,11 @@ bool seal_clock_plan(DOM::Document& document, bool may_plan, u64 update_serial)};for (auto const& associated_timeline : document.associated_animation_timelines()) {Animations::TimelineView const* scroll_timeline = associated_timeline.is_scroll_timeline() ? &associated_timeline : nullptr;- for (auto const& animation : Animations::associated_animations_of(associated_timeline)) {+ // OPTIMIZATION: Every animation the plan runs is one an update of its timeline may change.+ auto associated_animations = Animations::associated_animations_of(associated_timeline);+ for (auto const& animation : Animations::animations_needing_update_of(associated_timeline)) {+ if (!associated_animations.contains(animation))+ continue;if (!runs_for_clock_plan(animation.play_state(), scroll_timeline != nullptr))continue;auto effect = animation.effect();@@ -209,17 +214,35 @@ bool seal_clock_plan(DOM::Document& document, bool may_plan, u64 update_serial)if (hover_lane_is_enabled() && document.is_fully_active() && !document.hidden() && document.window()) {// 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 : 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()- || !effect->can_skip_per_frame_style_update())- continue;- // NB: The record decides the timing the hover runs the animation with.- effect_timing_nodes.append(target->style_node_id().value());- effect_timing_identities.append(effect->id());- effect_timings.append(Animations::RustFFI::animations_animation_hover_timing(&animation.record()));+ // OPTIMIZATION: An animation whose effect produces nothing leaves the animations associated with its+ // target, and one an update of its timeline may change is among those its timeline keeps,+ // so look only at those, not at every animation associated with a timeline. Those of+ // timelines the document is not associated with, or of none, are left out as before.+ auto const associated_timelines = document.associated_animation_timelines();+ HashTable<Animations::RustFFI::TimelineCell const*> timelines;+ for (auto const& timeline : associated_timelines)+ timelines.set(&timeline.record());+ auto add_effect_timing = [&](Animations::AnimationRef const& animation) {+ auto effect = animation.effect();+ auto* target = effect.has_value() ? effect->target() : nullptr;+ if (!target || effect->pseudo_element_type().has_value() || !target->style_node_id()+ || !effect->can_skip_per_frame_style_update()+ || !timelines.contains(Animations::RustFFI::animations_animation_timeline(&animation.record())))+ return;+ // NB: The record decides the timing the hover runs the animation with.+ effect_timing_nodes.append(target->style_node_id().value());+ effect_timing_identities.append(effect->id());+ effect_timings.append(Animations::RustFFI::animations_animation_hover_timing(&animation.record()));+ };+ auto target_associated_animations = Animations::associated_animations_of(document.document_animations());+ for (auto const& animation : target_associated_animations)+ add_effect_timing(animation);+ // NB: A transition started provisionally runs on its timeline before its target observes it.+ for (auto const& timeline : associated_timelines) {+ auto associated_animations = Animations::associated_animations_of(timeline);+ for (auto const& animation : Animations::animations_needing_update_of(timeline)) {+ if (associated_animations.contains(animation) && !target_associated_animations.contains(animation))+ add_effect_timing(animation);}}Optional<Web::EventHandler::SelectionDragForLanes> selection_drag;diff --git a/Libraries/LibWeb/Rust/src/animations/animation.rs b/Libraries/LibWeb/Rust/src/animations/animation.rsindex 4004ba2705c..d40d5f7fcd9 100644--- a/Libraries/LibWeb/Rust/src/animations/animation.rs+++ b/Libraries/LibWeb/Rust/src/animations/animation.rs@@ -722,6 +722,11 @@ impl WeakAnimationSet {self.0.contains(animation)}+ /// The index of the entry of `animation` in the set's order, if the set holds it.+ pub(crate) fn position(&self, animation: &AnimationCell) -> Option<u32> {+ self.0.position(animation)+ }+/// Drops the entries of animations that died.pub(crate) fn prune(&mut self) {self.0.prune();diff --git a/Libraries/LibWeb/Rust/src/animations/ffi.rs b/Libraries/LibWeb/Rust/src/animations/ffi.rsindex 26998e3de94..2381173dcf7 100644--- a/Libraries/LibWeb/Rust/src/animations/ffi.rs+++ b/Libraries/LibWeb/Rust/src/animations/ffi.rs@@ -715,6 +715,17 @@ pub extern "C" fn animations_animation_effect(animation: &AnimationCell) -> *con})}+/// https://www.w3.org/TR/web-animations-1/#animation-timeline+/// The record of the timeline of `animation`, or null where it has none. The pointer stays valid while the animation+/// keeps that timeline.+#[unsafe(no_mangle)]+pub extern "C" fn animations_animation_timeline(animation: &AnimationCell) -> *const TimelineCell {+ animation+ .borrow()+ .timeline()+ .map_or(std::ptr::null(), |timeline| &raw const **timeline)+}+/// https://www.w3.org/TR/web-animations-1/#play-states#[unsafe(no_mangle)]pub extern "C" fn animations_animation_play_state(animation: &AnimationCell) -> AnimationPlayState {@@ -2031,9 +2042,7 @@ pub unsafe extern "C" fn animations_document_animations_run_transition_step({return false;}- procedures::run(animation, |procedures| Ok(procedures.is_relevant()))- .expect("reading relevance does not throw")- .0+ procedures::query(animation, |procedures| procedures.is_relevant())}).cloned().collect();@@ -2590,6 +2599,12 @@ pub extern "C" fn animations_weak_animation_set_get(set: &WeakAnimationSet, indeset.get(index).map_or(std::ptr::null(), AnimationHandle::into_raw)}+/// Whether `set` holds `animation`.+#[unsafe(no_mangle)]+pub extern "C" fn animations_weak_animation_set_contains(set: &WeakAnimationSet, animation: &AnimationCell) -> bool {+ set.contains(animation)+}+/// 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 {@@ -3215,3 +3230,19 @@ pub extern "C" fn animations_timeline_read(timeline: &TimelineCell) -> FfiTimelipub extern "C" fn animations_timeline_associated_animations(timeline: &TimelineCell) -> *mut WeakAnimationSet {timeline.associated_animations().as_ptr()}++/// The animations associated with `timeline` that an update of its current time may change, which lives as long as the+/// timeline. The others have finished on a monotonically increasing timeline and have no pending task.+#[unsafe(no_mangle)]+pub extern "C" fn animations_timeline_animations_needing_update(timeline: &TimelineCell) -> *mut WeakAnimationSet {+ timeline.animations_needing_update().as_ptr()+}++/// The animations associated with the elements of a document whose animations are `animations`, which lives as long as+/// the document.+#[unsafe(no_mangle)]+pub extern "C" fn animations_document_associated_animations(+ animations: &mut DocumentAnimations,+) -> *mut WeakAnimationSet {+ animations.set_mut(DocumentAnimationSetKind::Associated)+}diff --git a/Libraries/LibWeb/Rust/src/animations/procedures.rs b/Libraries/LibWeb/Rust/src/animations/procedures.rsindex c1d210a5f22..a2b82eee20f 100644--- a/Libraries/LibWeb/Rust/src/animations/procedures.rs+++ b/Libraries/LibWeb/Rust/src/animations/procedures.rs@@ -10,7 +10,9 @@//! 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, AnimationRecord, CssAnimationFlag, TransitionPhase};+use super::animation::{+ AnimationCell, AnimationHandle, AnimationKind, AnimationRecord, CssAnimationFlag, TransitionPhase,+};use super::composite_order::{TreeOrder, composite_order};use super::effect::{EffectFlag, EffectHandle};use super::host_effects::{HostEffectKind, HostEffects, PlaybackEventType};@@ -71,6 +73,18 @@ pub(crate) fn run<T>(run_on(animation, timeline, procedure)}+/// Answers what `procedure`, which only reads, finds of `animation`. Unlike `run`, this does not note that the+/// animation may need updates.+pub(crate) fn query<T>(animation: &AnimationHandle, procedure: impl FnOnce(&Procedures<'_>) -> T) -> T {+ let timeline = animation.borrow().timeline_state();+ let mut effects = HostEffects::default();+ procedure(&Procedures {+ animation,+ timeline,+ effects: &mut effects,+ })+}+/// Runs `procedure` on `animation`, whose timeline reads `timeline` now, if it has one, and hands back what it asks/// the host to do.fn run_on<T>(@@ -83,8 +97,33 @@ fn run_on<T>(animation,timeline,effects: &mut effects,- })?;- Ok((value, effects))+ });+ note_animation_may_need_update(animation);+ Ok((value?, effects))+}++/// OPTIMIZATION: Notes that an update of the current time of the timeline of `animation`, if any, may change it, as a+/// procedure ran on it. The timeline updates only those of its animations.+pub(crate) fn note_animation_may_need_update(animation: &AnimationHandle) {+ let timeline = animation.borrow().timeline().cloned();+ if let Some(timeline) = timeline {+ timeline.animations_needing_update().borrow_mut().insert(animation);+ }+}++/// Whether an update of the current time of its timeline leaves `animation` as it is until a procedure runs on it: it+/// has finished on a monotonically increasing timeline that is not progress-based, and has no pending task, which is+/// what the update of an animation as its timeline updates skips.+pub(crate) fn update_leaves_animation_as_it_is(animation: &AnimationCell) -> bool {+ let record = animation.borrow();+ let playback = record.playback();+ if !playback.is_finished || playback.pending() {+ return false;+ }+ record+ .timeline_state()+ .is_some_and(|timeline| timeline.sample.is_monotonically_increasing && !timeline.is_progress_based)+ && record.play_state() == AnimationPlayState::Finished}/// An animation and its timeline as it is now, on which the procedures run, and what they ask the host to do so far.@@ -1561,6 +1600,11 @@ impl Procedures<'_> {// 8. Let the timeline of animation be new timeline.if let Some(old_timeline) = &old_timeline {old_timeline.associated_animations().borrow_mut().remove(self.animation);+ // NB: Nothing the old timeline updates is left of the animation for it to update.+ old_timeline+ .animations_needing_update()+ .borrow_mut()+ .remove(self.animation);}if let Some(new_timeline) = &new_timeline {new_timeline.associated_animations().borrow_mut().insert(self.animation);@@ -1682,6 +1726,7 @@ impl Procedures<'_> {effects: &mut *self.effects,}.set_the_associated_effect(None, Invalidate::Yes);+ note_animation_may_need_update(&previous_animation);}// 6. Let the associated effect of animation be new effect.@@ -2068,11 +2113,11 @@ pub(crate) fn remove_replaced_animations<'a>(if !target.is_some_and(&is_descendant_of_document) {continue;}- let Ok((true, _)) = run(&animation, |procedures| {- Ok(procedures.is_replaceable() && procedures.playback().replace_state == AnimationReplaceState::Active)- }) else {+ if !query(&animation, |procedures| {+ procedures.is_replaceable() && procedures.playback().replace_state == AnimationReplaceState::Active+ }) {continue;- };+ }// NB: Every animation effect is a keyframe effect, whose composite order is defined.replaceable_animations.push(animation);}diff --git a/Libraries/LibWeb/Rust/src/animations/rendering_update.rs b/Libraries/LibWeb/Rust/src/animations/rendering_update.rsindex 44f4d5cf736..0933086b75f 100644--- a/Libraries/LibWeb/Rust/src/animations/rendering_update.rs+++ b/Libraries/LibWeb/Rust/src/animations/rendering_update.rs@@ -403,11 +403,12 @@ pub unsafe extern "C" fn animations_document_run_pending_css_play_tasks(// SAFETY: Guaranteed by the caller, and the borrow ends here.let timelines = unsafe { &*animations }.timelines.clone();let mut pending: Vec<AnimationHandle> = Vec::new();+ // NB: An animation with a pending task needs updates, so only those are looked at.for timeline in &timelines {- let associated = timeline.associated_animations().borrow();pending.extend(- associated- .iter()+ timeline+ .associated_animations_needing_update()+ .into_iter().filter(|animation| rendering_update_makes_ready(animation)),);}diff --git a/Libraries/LibWeb/Rust/src/animations/timeline.rs b/Libraries/LibWeb/Rust/src/animations/timeline.rsindex d36663525c2..76bf022c58e 100644--- a/Libraries/LibWeb/Rust/src/animations/timeline.rs+++ b/Libraries/LibWeb/Rust/src/animations/timeline.rs@@ -8,7 +8,7 @@//! https://www.w3.org/TR/web-animations-1/#timelinesuse super::animation::{- AttachmentInterval, AttachmentRangeEdge, AttachmentRangeEdgeOffset, HostCellKind, WeakAnimationSet,+ AnimationHandle, AttachmentInterval, AttachmentRangeEdge, AttachmentRangeEdgeOffset, HostCellKind, WeakAnimationSet,};use super::snapshot::{TimelineClock, TimelineClockSource};use super::timeline_state::TimelineState;@@ -884,6 +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>,+ /// OPTIMIZATION: The animations associated with the timeline that an update of its current time may change, none of+ /// which it keeps alive. An animation that has finished on a monotonically increasing timeline, with+ /// no pending task, stays as it is until a procedure runs on it, which adds it back.+ animations_needing_update: RefCell<WeakAnimationSet>,/// 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.@@ -951,6 +955,28 @@ impl TimelineCell {&self.associated_animations}+ pub(crate) fn animations_needing_update(&self) -> &RefCell<WeakAnimationSet> {+ &self.animations_needing_update+ }++ /// The animations associated with the timeline that an update of its current time may change, in the order of the+ /// animations associated with it, forgetting that the others need updates.+ pub(crate) fn associated_animations_needing_update(&self) -> Vec<AnimationHandle> {+ let associated = self.associated_animations.borrow();+ let mut needing_update = self.animations_needing_update.borrow_mut();+ let mut animations = Vec::new();+ for animation in needing_update.alive() {+ match associated.position(&animation) {+ Some(position) => animations.push((position, animation)),+ None => {+ needing_update.remove(&animation);+ }+ }+ }+ animations.sort_unstable_by_key(|(position, _)| *position);+ animations.into_iter().map(|(_, animation)| animation).collect()+ }+/// https://drafts.csswg.org/web-animations-1/#timeline#[must_use]pub(crate) fn is_inactive(&self) -> bool {@@ -1326,6 +1352,7 @@ impl TimelineHandle {kind,}),associated_animations: RefCell::default(),+ animations_needing_update: RefCell::default(),object_cell: Cell::new(None),}))}diff --git a/Libraries/LibWeb/Rust/src/animations/timeline_host.rs b/Libraries/LibWeb/Rust/src/animations/timeline_host.rsindex 6a6984cb544..eda8f65bec9 100644--- a/Libraries/LibWeb/Rust/src/animations/timeline_host.rs+++ b/Libraries/LibWeb/Rust/src/animations/timeline_host.rs@@ -11,6 +11,7 @@ use super::animation::AnimationCell;use super::document_animations::DocumentAnimations;use super::effect::EffectFlag;use super::ffi::{FfiKeepAlive, FfiScrollTimelineSource, FfiTimelineDescription, HostEffectPerformer, run_procedure};+use super::procedures::update_leaves_animation_as_it_is;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};@@ -130,14 +131,21 @@ fn update_associated_animations(timeline: &TimelineCell, host: &TimelineUpdateHonote_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();+ // OPTIMIZATION: Only the animations an update may change are updated, in the order they are associated with the+ // timeline. The others stay as they are until a procedure runs on them, which notes that they need+ // updates again.+ let animations = timeline.associated_animations_needing_update();for animation in &animations {(host.keep_alive)(animation);}for animation in &animations {- if timeline.associated_animations().borrow().contains(animation) {+ let is_associated = timeline.associated_animations().borrow().contains(animation);+ if is_associated {run_procedure(animation, host.perform, |procedures| procedures.update());}+ if !is_associated || update_leaves_animation_as_it_is(animation) {+ timeline.animations_needing_update().borrow_mut().remove(animation);+ }}}diff --git a/Libraries/LibWeb/Rust/src/animations/weak_record_set.rs b/Libraries/LibWeb/Rust/src/animations/weak_record_set.rsindex 1019b00df14..e9774e77458 100644--- a/Libraries/LibWeb/Rust/src/animations/weak_record_set.rs+++ b/Libraries/LibWeb/Rust/src/animations/weak_record_set.rs@@ -51,6 +51,11 @@ impl<T> WeakRecordSet<T> {.copied()}+ /// The index of the entry of `record` in the set's order, if the set holds it.+ pub(crate) fn position(&self, record: *const T) -> Option<u32> {+ self.find(record)+ }+/// Whether the set holds `record`.pub(crate) fn contains(&self, record: *const T) -> bool {self.find(record).is_some()diff --git a/Tests/LibWeb/Text/expected/WebAnimations/animations-finishing-together-resolve-in-association-order.txt b/Tests/LibWeb/Text/expected/WebAnimations/animations-finishing-together-resolve-in-association-order.txtnew file mode 100644index 00000000000..ceb8fe7c70c--- /dev/null+++ b/Tests/LibWeb/Text/expected/WebAnimations/animations-finishing-together-resolve-in-association-order.txt@@ -0,0 +1 @@+first, seconddiff --git a/Tests/LibWeb/Text/expected/WebAnimations/finished-animation-runs-again-after-update-timing.txt b/Tests/LibWeb/Text/expected/WebAnimations/finished-animation-runs-again-after-update-timing.txtnew file mode 100644index 00000000000..76ec5a78517--- /dev/null+++ b/Tests/LibWeb/Text/expected/WebAnimations/finished-animation-runs-again-after-update-timing.txt@@ -0,0 +1,3 @@+Before: finished+After updateTiming: running+Finished again: finished, moved on: truediff --git a/Tests/LibWeb/Text/input/WebAnimations/animations-finishing-together-resolve-in-association-order.html b/Tests/LibWeb/Text/input/WebAnimations/animations-finishing-together-resolve-in-association-order.htmlnew file mode 100644index 00000000000..3104ae73045--- /dev/null+++ b/Tests/LibWeb/Text/input/WebAnimations/animations-finishing-together-resolve-in-association-order.html@@ -0,0 +1,29 @@+<!DOCTYPE html>+<div id="first"></div>+<div id="second"></div>+<script src="../include.js"></script>+<script>+ const nextFrame = () => new Promise(resolve => requestAnimationFrame(resolve));++ asyncTest(async done => {+ const duration = 100000;+ const a = document.getElementById("first").animate({ opacity: [0, 1] }, duration);+ const b = document.getElementById("second").animate({ opacity: [0, 1] }, duration);+ await Promise.all([a.ready, b.ready]);++ // Finish the first animation and let the timeline update it, so that it settles as finished.+ a.finish();+ await nextFrame();+ await nextFrame();++ // Seek the first animation, then the second, so that both end on the same timeline update.+ a.currentTime = duration - 1;+ b.currentTime = duration - 1;++ const order = [];+ const finished = [a.finished.then(() => order.push("first")), b.finished.then(() => order.push("second"))];+ await Promise.all(finished);+ println(order.join(", "));+ done();+ });+</script>diff --git a/Tests/LibWeb/Text/input/WebAnimations/finished-animation-runs-again-after-update-timing.html b/Tests/LibWeb/Text/input/WebAnimations/finished-animation-runs-again-after-update-timing.htmlnew file mode 100644index 00000000000..4d4e35934e4--- /dev/null+++ b/Tests/LibWeb/Text/input/WebAnimations/finished-animation-runs-again-after-update-timing.html@@ -0,0 +1,26 @@+<!DOCTYPE html>+<div id="target"></div>+<script src="../include.js"></script>+<script>+ const nextFrame = () => new Promise(resolve => requestAnimationFrame(resolve));++ asyncTest(async done => {+ const animation = document.getElementById("target").animate({ opacity: [0, 1] }, 100000);+ await animation.ready;++ // Finish the animation and let the timeline update it, so that it settles as finished.+ animation.finish();+ await animation.finished;+ await nextFrame();+ await nextFrame();+ println(`Before: ${animation.playState}`);++ // A longer duration makes it run again, and the timeline must update it on to its new end.+ const time = animation.currentTime;+ animation.effect.updateTiming({ duration: time + 20 });+ println(`After updateTiming: ${animation.playState}`);+ await animation.finished;+ println(`Finished again: ${animation.playState}, moved on: ${animation.currentTime > time}`);+ done();+ });+</script>