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::sync::Arc;
7use std::time::Duration;
8
9use layout_api::AnimatingImages;
10use paint_api::ImageUpdate;
11use parking_lot::RwLock;
12use script_bindings::codegen::GenericBindings::WindowBinding::WindowMethods;
13use timers::{TimerEventRequest, TimerId};
14
15use crate::dom::bindings::refcounted::Trusted;
16use crate::dom::node::Node;
17use crate::dom::window::Window;
18use crate::script_thread::with_script_thread;
19
20#[derive(Clone, Default, JSTraceable, MallocSizeOf)]
21#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
22pub struct ImageAnimationManager {
23    /// The set of [`AnimatingImages`] which is used to communicate the addition
24    /// and removal of animating images from layout.
25    #[no_trace]
26    #[conditional_malloc_size_of]
27    animating_images: Arc<RwLock<AnimatingImages>>,
28
29    /// The [`TimerId`] of the currently scheduled animated image update callback.
30    #[no_trace]
31    callback_timer_id: Cell<Option<TimerId>>,
32}
33
34impl ImageAnimationManager {
35    pub(crate) fn animating_images(&self) -> Arc<RwLock<AnimatingImages>> {
36        self.animating_images.clone()
37    }
38
39    fn duration_to_next_frame(&self, now: f64) -> Option<Duration> {
40        self.animating_images
41            .read()
42            .node_to_state_map
43            .values()
44            .map(|state| state.duration_to_next_frame(now))
45            .min()
46    }
47
48    pub(crate) fn update_active_frames(&self, window: &Window, now: f64) {
49        if self.animating_images.read().is_empty() {
50            return;
51        }
52
53        let updates = self
54            .animating_images
55            .write()
56            .node_to_state_map
57            .values_mut()
58            .filter_map(|state| {
59                if !state.update_frame_for_animation_timeline_value(now) {
60                    return None;
61                }
62
63                let image = &state.image;
64                let frame = image
65                    .frame_data(state.active_frame)
66                    .expect("No frame found")
67                    .clone();
68                if let Some(mut descriptor) =
69                    image.webrender_image_descriptor_and_offset_for_frame()
70                {
71                    descriptor.offset = frame.byte_range.start as i32;
72                    Some(ImageUpdate::UpdateImageForAnimation(
73                        image.id.unwrap(),
74                        descriptor,
75                    ))
76                } else {
77                    error!("Doing normal image update which will be slow!");
78                    None
79                }
80            })
81            .collect();
82        window
83            .paint_api()
84            .update_images(window.webview_id().into(), updates);
85
86        self.maybe_schedule_update(window, now);
87    }
88
89    /// After doing a layout, if the set of animating images was updated in some way,
90    /// schedule a new animation update.
91    pub(crate) fn maybe_schedule_update_after_layout(&self, window: &Window, now: f64) {
92        if self.animating_images().write().clear_dirty() {
93            self.maybe_schedule_update(window, now);
94        }
95    }
96
97    fn maybe_schedule_update(&self, window: &Window, now: f64) {
98        with_script_thread(|script_thread| {
99            if let Some(current_timer_id) = self.callback_timer_id.take() {
100                self.callback_timer_id.set(None);
101                script_thread.cancel_timer(current_timer_id);
102            }
103
104            if let Some(duration) = self.duration_to_next_frame(now) {
105                let trusted_window = Trusted::new(window);
106                let timer_id = script_thread.schedule_timer(TimerEventRequest {
107                    callback: Box::new(move || {
108                        let window = trusted_window.root();
109                        window.Document().set_has_pending_animated_image_update();
110                    }),
111                    duration,
112                });
113                self.callback_timer_id.set(Some(timer_id));
114            }
115        })
116    }
117
118    pub(crate) fn cancel_animations_for_node(&self, node: &Node) {
119        self.animating_images().write().remove(node.to_opaque());
120    }
121}