root/src/gif_paintable/imp.rs

// adapted from (previous MIT version, now GPL3):
// https://github.com/gtk-rs/gtk4-rs/blob/main/examples/gif_paintable/gif_paintable/imp.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::cell::{Cell, RefCell};

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

use super::Frame;

#[derive(Default)]
pub struct GifPaintable {
    pub frames: RefCell<Option<Vec<Frame>>>,
    pub next_frame: RefCell<Option<gdk::Texture>>,
    pub timeout_source_id: RefCell<Option<glib::SourceId>>,
    pub current_idx: Cell<usize>,
}

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

impl ObjectImpl for GifPaintable {}

impl PaintableImpl for GifPaintable {
    fn intrinsic_height(&self) -> i32 {
        self.next_frame
            .borrow()
            .as_ref()
            .map(|texture| texture.height())
            .unwrap_or(-1)
    }

    fn intrinsic_width(&self) -> i32 {
        self.next_frame
            .borrow()
            .as_ref()
            .map(|texture| texture.width())
            .unwrap_or(-1)
    }

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