root/src/gif_paintable/frame.rs

// adapted from (previous MIT version, now GPL3):
// https://github.com/gtk-rs/gtk4-rs/blob/main/examples/gif_paintable/gif_paintable/frame.rs
//
// Copyright 2026 nee <nee-git@hidamari.blue>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
// SPDX-License-Identifier: GPL-3.0-or-later

use std::time::Duration;

use gtk::{gdk, glib, prelude::*};

#[derive(Debug)]
pub struct Frame {
    pub texture: gdk::Texture,
    pub frame_duration: Duration,
}

impl From<image::Frame> for Frame {
    fn from(f: image::Frame) -> Self {
        let mut frame_duration = Duration::from(f.delay());

        // convention is to use 100 milliseconds duration if it is defined as 0.
        if frame_duration.is_zero() {
            frame_duration = Duration::from_millis(100);
        }

        let samples = f.into_buffer().into_flat_samples();

        let bytes = glib::Bytes::from(samples.as_slice());
        let layout = samples.layout;

        let texture = gdk::MemoryTexture::new(
            layout.width as i32,
            layout.height as i32,
            gdk::MemoryFormat::R8g8b8a8,
            &bytes,
            layout.height_stride,
        );

        Frame {
            texture: texture.upcast(),
            frame_duration,
        }
    }
}