Debian Codegraph @

src/image.rs

raw symbols SCIP
1 /*
2 * Copyright 2022-2026 Andrey Kutejko <[email protected]>
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, see <http://www.gnu.org/licenses/>.
16 *
17 * For more details see the file COPYING.
18 */
19
20 use gtk::{gdk, gio, graphene, gsk, prelude::*};
21 use std::cell::RefCell;
22 use std::error::Error;
23 use std::path::Path;
24 use std::rc::Rc;
25
26 #[derive(Clone)]
27 pub struct Image(Rc<ImageInner>);
28
29 struct ImageInner {
30 image: gly::Image,
31 texture: gdk::Texture,
32 scaled: RefCell<Option<gdk::Texture>>,
33 }
34
35 impl Image {
36 pub fn from_file(filename: &Path) -> Result<Self, Box<dyn Error>> {
37 let file = gio::File::for_path(filename);
38 let loader = gly::Loader::new(&file);
39 let image = loader.load()?;
40 let frame = image.next_frame()?;
41 let texture = gly_gtk::frame_get_texture(&frame);
42 Ok(Self(Rc::new(ImageInner {
43 image,
44 texture,
45 scaled: Default::default(),
46 })))
47 }
48
49 fn is_svg(&self) -> bool {
50 const SVG_CONTENT_TYPE: &str = "image/svg+xml";
51 self.0.image.mime_type() == SVG_CONTENT_TYPE
52 }
53
54 pub fn to_paintable(&self) -> gdk::Paintable {
55 self.0.texture.clone().upcast()
56 }
57
58 pub fn scaled(
59 &self,
60 width: i32,
61 height: i32,
62 renderer: &gsk::Renderer,
63 ) -> Result<gdk::Texture, Box<dyn Error>> {
64 if let Some(texture) = self.0.scaled.borrow().as_ref()
65 && texture.width() == width
66 && texture.height() == height
67 {
68 return Ok(texture.clone());
69 }
70
71 let texture = if self.is_svg() {
72 let request = gly::FrameRequest::new();
73 request.set_scale(width as u32, height as u32);
74 let frame = self.0.image.specific_frame(&request)?;
75 gly_gtk::frame_get_texture(&frame)
76 } else {
77 let snapshot = gtk::Snapshot::new();
78 let bounds = graphene::Rect::new(0.0, 0.0, width as f32, height as f32);
79 snapshot.append_texture(&self.0.texture, &bounds);
80 let node = snapshot.to_node().ok_or("No node")?;
81 renderer.render_texture(node, None)
82 };
83
84 self.0.scaled.replace(Some(texture.clone()));
85
86 Ok(texture)
87 }
88 }