gdk_pixbuf/subclass/
pixbuf_animation_iter.rs

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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
// Take a look at the license at the top of the repository in the LICENSE file.

// rustdoc-stripper-ignore-next
//! Traits intended for subclassing [`PixbufAnimationIter`].

use std::{
    sync::OnceLock,
    time::{Duration, SystemTime},
};

use glib::{prelude::*, subclass::prelude::*, translate::*};

use crate::{ffi, Pixbuf, PixbufAnimationIter};

pub trait PixbufAnimationIterImpl: ObjectImpl {
    // rustdoc-stripper-ignore-next
    /// Time in milliseconds, returning `None` implies showing the same pixbuf forever.
    // rustdoc-stripper-ignore-next-stop
    /// Gets the number of milliseconds the current pixbuf should be displayed,
    /// or -1 if the current pixbuf should be displayed forever.
    ///
    /// The `g_timeout_add()` function conveniently takes a timeout in milliseconds,
    /// so you can use a timeout to schedule the next update.
    ///
    /// Note that some formats, like GIF, might clamp the timeout values in the
    /// image file to avoid updates that are just too quick. The minimum timeout
    /// for GIF images is currently 20 milliseconds.
    ///
    /// # Returns
    ///
    /// delay time in milliseconds (thousandths of a second)
    fn delay_time(&self) -> Option<Duration> {
        self.parent_delay_time()
    }

    /// Gets the current pixbuf which should be displayed.
    ///
    /// The pixbuf might not be the same size as the animation itself
    /// (gdk_pixbuf_animation_get_width(), gdk_pixbuf_animation_get_height()).
    ///
    /// This pixbuf should be displayed for gdk_pixbuf_animation_iter_get_delay_time()
    /// milliseconds.
    ///
    /// The caller of this function does not own a reference to the returned
    /// pixbuf; the returned pixbuf will become invalid when the iterator
    /// advances to the next frame, which may happen anytime you call
    /// gdk_pixbuf_animation_iter_advance().
    ///
    /// Copy the pixbuf to keep it (don't just add a reference), as it may get
    /// recycled as you advance the iterator.
    ///
    /// # Returns
    ///
    /// the pixbuf to be displayed
    fn pixbuf(&self) -> Pixbuf {
        self.parent_pixbuf()
    }

    /// Used to determine how to respond to the area_updated signal on
    /// #GdkPixbufLoader when loading an animation.
    ///
    /// The `::area_updated` signal is emitted for an area of the frame currently
    /// streaming in to the loader. So if you're on the currently loading frame,
    /// you will need to redraw the screen for the updated area.
    ///
    /// # Returns
    ///
    /// `TRUE` if the frame we're on is partially loaded, or the last frame
    fn on_currently_loading_frame(&self) -> bool {
        self.parent_on_currently_loading_frame()
    }

    /// Possibly advances an animation to a new frame.
    ///
    /// Chooses the frame based on the start time passed to
    /// gdk_pixbuf_animation_get_iter().
    ///
    /// @current_time would normally come from g_get_current_time(), and
    /// must be greater than or equal to the time passed to
    /// gdk_pixbuf_animation_get_iter(), and must increase or remain
    /// unchanged each time gdk_pixbuf_animation_iter_get_pixbuf() is
    /// called. That is, you can't go backward in time; animations only
    /// play forward.
    ///
    /// As a shortcut, pass `NULL` for the current time and g_get_current_time()
    /// will be invoked on your behalf. So you only need to explicitly pass
    /// @current_time if you're doing something odd like playing the animation
    /// at double speed.
    ///
    /// If this function returns `FALSE`, there's no need to update the animation
    /// display, assuming the display had been rendered prior to advancing;
    /// if `TRUE`, you need to call gdk_pixbuf_animation_iter_get_pixbuf()
    /// and update the display with the new pixbuf.
    /// ## `current_time`
    /// current time
    ///
    /// # Returns
    ///
    /// `TRUE` if the image may need updating
    fn advance(&self, current_time: SystemTime) -> bool {
        self.parent_advance(current_time)
    }
}

mod sealed {
    pub trait Sealed {}
    impl<T: super::PixbufAnimationIterImplExt> Sealed for T {}
}

pub trait PixbufAnimationIterImplExt: sealed::Sealed + ObjectSubclass {
    fn parent_delay_time(&self) -> Option<Duration> {
        unsafe {
            let data = Self::type_data();
            let parent_class =
                data.as_ref().parent_class() as *mut ffi::GdkPixbufAnimationIterClass;
            let f = (*parent_class)
                .get_delay_time
                .expect("No parent class implementation for \"get_delay_time\"");

            let time = f(self
                .obj()
                .unsafe_cast_ref::<PixbufAnimationIter>()
                .to_glib_none()
                .0);
            if time < 0 {
                None
            } else {
                Some(Duration::from_millis(time as u64))
            }
        }
    }

    fn parent_pixbuf(&self) -> Pixbuf {
        unsafe {
            let data = Self::type_data();
            let parent_class =
                data.as_ref().parent_class() as *mut ffi::GdkPixbufAnimationIterClass;
            let f = (*parent_class)
                .get_pixbuf
                .expect("No parent class implementation for \"get_pixbuf\"");

            from_glib_none(f(self
                .obj()
                .unsafe_cast_ref::<PixbufAnimationIter>()
                .to_glib_none()
                .0))
        }
    }

    fn parent_on_currently_loading_frame(&self) -> bool {
        unsafe {
            let data = Self::type_data();
            let parent_class =
                data.as_ref().parent_class() as *mut ffi::GdkPixbufAnimationIterClass;
            let f = (*parent_class)
                .on_currently_loading_frame
                .expect("No parent class implementation for \"on_currently_loading_frame\"");

            from_glib(f(self
                .obj()
                .unsafe_cast_ref::<PixbufAnimationIter>()
                .to_glib_none()
                .0))
        }
    }

    fn parent_advance(&self, current_time: SystemTime) -> bool {
        unsafe {
            let data = Self::type_data();
            let parent_class =
                data.as_ref().parent_class() as *mut ffi::GdkPixbufAnimationIterClass;
            let f = (*parent_class)
                .advance
                .expect("No parent class implementation for \"advance\"");

            let diff = current_time
                .duration_since(SystemTime::UNIX_EPOCH)
                .expect("failed to convert time");
            let time = glib::ffi::GTimeVal {
                tv_sec: diff.as_secs() as _,
                tv_usec: diff.subsec_micros() as _,
            };
            from_glib(f(
                self.obj()
                    .unsafe_cast_ref::<PixbufAnimationIter>()
                    .to_glib_none()
                    .0,
                &time,
            ))
        }
    }
}

impl<T: PixbufAnimationIterImpl> PixbufAnimationIterImplExt for T {}

unsafe impl<T: PixbufAnimationIterImpl> IsSubclassable<T> for PixbufAnimationIter {
    fn class_init(class: &mut ::glib::Class<Self>) {
        Self::parent_class_init::<T>(class);

        let klass = class.as_mut();
        klass.get_delay_time = Some(animation_iter_get_delay_time::<T>);
        klass.get_pixbuf = Some(animation_iter_get_pixbuf::<T>);
        klass.on_currently_loading_frame = Some(animation_iter_on_currently_loading_frame::<T>);
        klass.advance = Some(animation_iter_advance::<T>);
    }
}

unsafe extern "C" fn animation_iter_get_delay_time<T: PixbufAnimationIterImpl>(
    ptr: *mut ffi::GdkPixbufAnimationIter,
) -> i32 {
    let instance = &*(ptr as *mut T::Instance);
    let imp = instance.imp();

    imp.delay_time().map(|t| t.as_millis() as i32).unwrap_or(-1)
}

unsafe extern "C" fn animation_iter_get_pixbuf<T: PixbufAnimationIterImpl>(
    ptr: *mut ffi::GdkPixbufAnimationIter,
) -> *mut ffi::GdkPixbuf {
    let instance = &*(ptr as *mut T::Instance);
    let imp = instance.imp();

    let pixbuf = imp.pixbuf();
    // Ensure that the pixbuf stays alive until the next call
    let pixbuf_quark = {
        static QUARK: OnceLock<glib::Quark> = OnceLock::new();
        *QUARK.get_or_init(|| glib::Quark::from_str("gtk-rs-subclass-pixbuf"))
    };
    imp.obj().set_qdata(pixbuf_quark, pixbuf.clone());
    pixbuf.to_glib_none().0
}

unsafe extern "C" fn animation_iter_on_currently_loading_frame<T: PixbufAnimationIterImpl>(
    ptr: *mut ffi::GdkPixbufAnimationIter,
) -> glib::ffi::gboolean {
    let instance = &*(ptr as *mut T::Instance);
    let imp = instance.imp();

    imp.on_currently_loading_frame().into_glib()
}

unsafe extern "C" fn animation_iter_advance<T: PixbufAnimationIterImpl>(
    ptr: *mut ffi::GdkPixbufAnimationIter,
    current_time_ptr: *const glib::ffi::GTimeVal,
) -> glib::ffi::gboolean {
    let instance = &*(ptr as *mut T::Instance);
    let imp = instance.imp();

    let current_time = SystemTime::UNIX_EPOCH
        + Duration::from_secs((*current_time_ptr).tv_sec.try_into().unwrap())
        + Duration::from_micros((*current_time_ptr).tv_usec.try_into().unwrap());

    imp.advance(current_time).into_glib()
}