script/
image_animation.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use std::cell::Cell;
6use std::ffi::c_void;
7use std::sync::Arc;
8use std::time::Duration;
9
10use embedder_traits::UntrustedNodeAddress;
11use layout_api::AnimatingImages;
12use paint_api::ImageUpdate;
13use parking_lot::RwLock;
14use rustc_hash::FxHashMap;
15use script_bindings::codegen::GenericBindings::WindowBinding::WindowMethods;
16use script_bindings::root::Dom;
17use style::dom::OpaqueNode;
18use timers::{TimerEventRequest, TimerId};
19
20use crate::dom::bindings::refcounted::Trusted;
21use crate::dom::bindings::trace::NoTrace;
22use crate::dom::from_untrusted_node_address;
23use crate::dom::node::Node;
24use crate::dom::window::Window;
25use crate::script_thread::with_script_thread;
26
27#[derive(Clone, Default, JSTraceable, MallocSizeOf)]
28#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
29pub struct ImageAnimationManager {
30    /// The set of [`AnimatingImages`] which is used to communicate the addition
31    /// and removal of animating images from layout.
32    #[no_trace]
33    #[conditional_malloc_size_of]
34    animating_images: Arc<RwLock<AnimatingImages>>,
35
36    /// The [`TimerId`] of the currently scheduled animated image update callback.
37    #[no_trace]
38    callback_timer_id: Cell<Option<TimerId>>,
39
40    /// A map of nodes with in-progress image animations. This is kept outside
41    /// of [`Self::animating_images`] as that data structure is shared with layout.
42    rooted_nodes: FxHashMap<NoTrace<OpaqueNode>, Dom<Node>>,
43}
44
45impl ImageAnimationManager {
46    pub(crate) fn animating_images(&self) -> Arc<RwLock<AnimatingImages>> {
47        self.animating_images.clone()
48    }
49
50    fn duration_to_next_frame(&self, now: f64) -> Option<Duration> {
51        self.animating_images
52            .read()
53            .node_to_state_map
54            .values()
55            .map(|state| state.duration_to_next_frame(now))
56            .min()
57    }
58
59    pub(crate) fn update_active_frames(&self, window: &Window, now: f64) {
60        if self.animating_images.read().is_empty() {
61            return;
62        }
63
64        let updates = self
65            .animating_images
66            .write()
67            .node_to_state_map
68            .values_mut()
69            .filter_map(|state| {
70                if !state.update_frame_for_animation_timeline_value(now) {
71                    return None;
72                }
73
74                let image = &state.image;
75                let frame = image
76                    .frame_data(state.active_frame)
77                    .expect("No frame found")
78                    .clone();
79                if let Some(mut descriptor) =
80                    image.webrender_image_descriptor_and_offset_for_frame()
81                {
82                    descriptor.offset = frame.byte_range.start as i32;
83                    Some(ImageUpdate::UpdateImageForAnimation(
84                        image.id.unwrap(),
85                        descriptor,
86                    ))
87                } else {
88                    error!("Doing normal image update which will be slow!");
89                    None
90                }
91            })
92            .collect();
93        window
94            .paint_api()
95            .update_images(window.webview_id().into(), updates);
96
97        self.maybe_schedule_update(window, now);
98    }
99
100    /// This does three things:
101    ///  - Root any nodes with newly animating images
102    ///  - Schedule an image update for newly animating images
103    ///  - Cancel animations for any nodes that no longer have layout boxes.
104    pub(crate) fn do_post_reflow_update(&mut self, window: &Window, now: f64) {
105        // Cancel animations for any images that are no longer rendering.
106        self.rooted_nodes.retain(|opaque_node, node| {
107            if node.is_being_rendered(None) {
108                return true;
109            }
110            self.animating_images.write().remove(opaque_node.0);
111            false
112        });
113
114        if self.animating_images().write().clear_dirty() {
115            self.root_nodes_with_newly_animating_images();
116            self.maybe_schedule_update(window, now);
117        }
118    }
119
120    fn root_nodes_with_newly_animating_images(&mut self) {
121        for opaque_node in self.animating_images().read().node_to_state_map.keys() {
122            #[expect(unsafe_code)]
123            self.rooted_nodes
124                .entry(NoTrace(*opaque_node))
125                .or_insert_with(|| {
126                    // SAFETY: This should be safe as this method is run directly after layout,
127                    // which should not remove any nodes.
128                    let address = UntrustedNodeAddress(opaque_node.0 as *const c_void);
129                    unsafe { Dom::from_ref(&*from_untrusted_node_address(address)) }
130                });
131        }
132    }
133
134    fn maybe_schedule_update(&self, window: &Window, now: f64) {
135        with_script_thread(|script_thread| {
136            if let Some(current_timer_id) = self.callback_timer_id.take() {
137                self.callback_timer_id.set(None);
138                script_thread.cancel_timer(current_timer_id);
139            }
140
141            if let Some(duration) = self.duration_to_next_frame(now) {
142                let trusted_window = Trusted::new(window);
143                let timer_id = script_thread.schedule_timer(TimerEventRequest {
144                    callback: Box::new(move || {
145                        let window = trusted_window.root();
146                        window.Document().set_has_pending_animated_image_update();
147                    }),
148                    duration,
149                });
150                self.callback_timer_id.set(Some(timer_id));
151            }
152        })
153    }
154
155    pub(crate) fn cancel_animations_for_node(&mut self, node: &Node) {
156        let opaque_node = node.to_opaque();
157        self.animating_images().write().remove(opaque_node);
158        self.rooted_nodes.remove(&NoTrace(opaque_node));
159    }
160}