1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
use glycin::{Frame, Image};
use gtk::{gdk, glib, glib::clone, graphene, prelude::*, subclass::prelude::*};
use tracing::error;

use crate::{spawn, spawn_tokio, utils::CountedRef};

mod imp {
    use std::{
        cell::{OnceCell, RefCell},
        sync::Arc,
    };

    use super::*;

    #[derive(Default)]
    pub struct AnimatedImagePaintable {
        /// The source image.
        image: OnceCell<Arc<Image<'static>>>,
        /// The current frame that is displayed.
        pub current_frame: RefCell<Option<Frame>>,
        /// The next frame of the animation, if any.
        next_frame: RefCell<Option<Frame>>,
        /// The source ID of the timeout to load the next frame, if any.
        timeout_source_id: RefCell<Option<glib::SourceId>>,
        /// The counted reference for the animation.
        ///
        /// When the count is 0, the animation is paused.
        animation_ref: OnceCell<CountedRef>,
    }

    #[glib::object_subclass]
    impl ObjectSubclass for AnimatedImagePaintable {
        const NAME: &'static str = "AnimatedImagePaintable";
        type Type = super::AnimatedImagePaintable;
        type Interfaces = (gdk::Paintable,);
    }

    impl ObjectImpl for AnimatedImagePaintable {}

    impl PaintableImpl for AnimatedImagePaintable {
        fn intrinsic_height(&self) -> i32 {
            self.current_frame
                .borrow()
                .as_ref()
                .map(|f| f.height())
                .unwrap_or_else(|| self.image().info().height) as i32
        }

        fn intrinsic_width(&self) -> i32 {
            self.current_frame
                .borrow()
                .as_ref()
                .map(|f| f.width())
                .unwrap_or_else(|| self.image().info().width) as i32
        }

        fn snapshot(&self, snapshot: &gdk::Snapshot, width: f64, height: f64) {
            if let Some(frame) = &*self.current_frame.borrow() {
                frame.texture().snapshot(snapshot, width, height);
            } else {
                let snapshot = snapshot.downcast_ref::<gtk::Snapshot>().unwrap();
                snapshot.append_color(
                    &gdk::RGBA::BLACK,
                    &graphene::Rect::new(0., 0., width as f32, height as f32),
                );
            }
        }

        fn flags(&self) -> gdk::PaintableFlags {
            gdk::PaintableFlags::SIZE
        }

        fn current_image(&self) -> gdk::Paintable {
            let snapshot = gtk::Snapshot::new();
            self.snapshot(
                snapshot.upcast_ref(),
                self.intrinsic_width() as f64,
                self.intrinsic_height() as f64,
            );

            snapshot
                .to_paintable(None)
                .expect("snapshot should always work")
        }
    }

    impl AnimatedImagePaintable {
        /// The source image.
        fn image(&self) -> &Arc<Image<'static>> {
            self.image.get().unwrap()
        }

        /// Initialize the image.
        pub(super) fn init(&self, image: Image<'static>, first_frame: Frame) {
            self.image.set(Arc::new(image)).unwrap();
            self.current_frame.replace(Some(first_frame));

            self.update_animation();
        }

        /// Show the next frame of the animation.
        fn show_next_frame(&self) {
            // Drop the timeout source ID so we know we are not waiting for it.
            self.timeout_source_id.take();

            let Some(next_frame) = self.next_frame.take() else {
                // Wait for the next frame to be loaded.
                return;
            };

            self.current_frame.replace(Some(next_frame));

            // Invalidate the contents so that the new frame will be rendered.
            self.obj().invalidate_contents();

            self.update_animation();
        }

        /// The counted reference of the animation.
        pub(super) fn animation_ref(&self) -> &CountedRef {
            self.animation_ref.get_or_init(|| {
                CountedRef::new(
                    clone!(
                        #[weak(rename_to = imp)]
                        self,
                        move || {
                            imp.update_animation();
                        }
                    ),
                    clone!(
                        #[weak(rename_to = imp)]
                        self,
                        move || {
                            imp.update_animation();
                        }
                    ),
                )
            })
        }

        /// Prepare the next frame of the animation or stop the animation,
        /// depending on the refcount.
        fn update_animation(&self) {
            if self.animation_ref().count() == 0 {
                // We should not animate, remove the timeout if it exists.
                if let Some(source) = self.timeout_source_id.take() {
                    source.remove();
                }
                return;
            } else if self.timeout_source_id.borrow().is_some() {
                // We are already waiting for the next update.
                return;
            }

            let Some(delay) = self.current_frame.borrow().as_ref().and_then(|f| f.delay()) else {
                return;
            };

            // Set the timeout to update the animation.
            let source_id = glib::timeout_add_local_once(
                delay,
                clone!(
                    #[weak(rename_to = imp)]
                    self,
                    move || {
                        imp.show_next_frame();
                    }
                ),
            );
            self.timeout_source_id.replace(Some(source_id));

            spawn!(clone!(
                #[weak(rename_to = imp)]
                self,
                async move {
                    imp.load_next_frame_inner().await;
                }
            ));
        }

        async fn load_next_frame_inner(&self) {
            let image = self.image().clone();

            let result = spawn_tokio!(async move { image.next_frame().await })
                .await
                .unwrap();

            match result {
                Ok(next_frame) => {
                    self.next_frame.replace(Some(next_frame));

                    // In case loading the frame took longer than the delay between frames.
                    if self.timeout_source_id.borrow().is_none() {
                        self.show_next_frame();
                    }
                }
                Err(error) => {
                    error!("Failed to load next frame: {error}");
                    // Do nothing, the animation will stop.
                }
            }
        }
    }
}

glib::wrapper! {
    /// A paintable to display an animated image.
    pub struct AnimatedImagePaintable(ObjectSubclass<imp::AnimatedImagePaintable>)
        @implements gdk::Paintable;
}

impl AnimatedImagePaintable {
    /// Load an image from the given file.
    pub fn new(image: Image<'static>, first_frame: Frame) -> Self {
        let obj = glib::Object::new::<Self>();

        obj.imp().init(image, first_frame);

        obj
    }

    /// Get the current `GdkTexture` of this paintable, if any.
    pub fn current_texture(&self) -> Option<gdk::Texture> {
        Some(self.imp().current_frame.borrow().as_ref()?.texture())
    }

    /// Get an animation ref.
    pub fn animation_ref(&self) -> CountedRef {
        self.imp().animation_ref().clone()
    }
}