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