Skip to main content

cosmic/widget/icon/
handle.rs

1// Copyright 2023 System76 <info@system76.com>
2// SPDX-License-Identifier: MPL-2.0
3
4use super::Icon;
5use crate::widget::{image, svg};
6use std::borrow::Cow;
7use std::ffi::OsStr;
8use std::fs::File;
9use std::hash::Hash;
10use std::io::Read;
11use std::path::{Path, PathBuf};
12
13#[must_use]
14#[derive(Clone, Debug, Hash, derive_setters::Setters)]
15pub struct Handle {
16    pub symbolic: bool,
17    #[setters(skip)]
18    pub data: Data,
19    /// Set for handles made from an icon name, so they can follow icon theme changes.
20    #[setters(skip)]
21    pub(super) source: Option<Source>,
22}
23
24impl Handle {
25    /// Wrap an image or SVG handle. Use [`from_name`](super::from_name) for themed icons.
26    #[inline]
27    pub fn new(symbolic: bool, data: Data) -> Self {
28        Self {
29            symbolic,
30            data,
31            source: None,
32        }
33    }
34
35    #[inline]
36    pub fn icon(self) -> Icon {
37        super::icon(self)
38    }
39
40    /// The same handle, re-resolved if the icon theme changed since it was created.
41    #[must_use]
42    pub fn refreshed(self) -> Self {
43        match &self.source {
44            Some(source) if source.theme != crate::icon_theme::default() => {
45                source.named.clone().handle()
46            }
47            _ => self,
48        }
49    }
50}
51
52#[derive(Clone, Debug, Hash)]
53pub(super) struct Source {
54    pub named: super::named::Named,
55    pub theme: String,
56}
57
58#[must_use]
59#[derive(Clone, Debug, Hash)]
60pub enum Data {
61    // Name(Named),
62    Image(image::Handle),
63    Svg(svg::Handle),
64}
65
66enum SvgSource {
67    Path,
68    Bytes(Vec<u8>),
69}
70
71fn svg_source(path: &Path) -> Option<SvgSource> {
72    if path
73        .extension()
74        .and_then(OsStr::to_str)
75        .is_some_and(|extension| extension.eq_ignore_ascii_case("svg"))
76    {
77        return Some(SvgSource::Path);
78    }
79
80    let Ok(mut file) = File::open(path) else {
81        return None;
82    };
83
84    let Ok(metadata) = file.metadata() else {
85        return None;
86    };
87    const MAX_SVG_SIZE: u64 = 16 * 1024 * 1024;
88    if !metadata.file_type().is_file() || metadata.len() > MAX_SVG_SIZE {
89        return None;
90    }
91
92    let mut prefix = [0; 32];
93    let Ok(length) = file.read(&mut prefix) else {
94        return None;
95    };
96    let prefix = &prefix[..length];
97
98    if ::image::guess_format(prefix).is_ok() {
99        return None;
100    }
101
102    let mut bytes = Vec::with_capacity(metadata.len() as usize);
103    bytes.extend_from_slice(prefix);
104    if file.read_to_end(&mut bytes).is_err() {
105        return None;
106    }
107
108    let document = roxmltree::Document::parse(std::str::from_utf8(&bytes).ok()?).ok()?;
109    (document.root_element().tag_name().name() == "svg").then_some(SvgSource::Bytes(bytes))
110}
111
112/// Create an icon handle from its path.
113pub fn from_path(path: PathBuf) -> Handle {
114    Handle {
115        symbolic: path
116            .file_stem()
117            .and_then(OsStr::to_str)
118            .is_some_and(|name| name.ends_with("-symbolic")),
119        data: match svg_source(&path) {
120            Some(SvgSource::Path) => Data::Svg(svg::Handle::from_path(path)),
121            Some(SvgSource::Bytes(bytes)) => Data::Svg(svg::Handle::from_memory(bytes)),
122            None => Data::Image(image::Handle::from_path(path)),
123        },
124        source: None,
125    }
126}
127
128/// Create an image handle from memory.
129pub fn from_raster_bytes(
130    bytes: impl Into<Cow<'static, [u8]>>
131    + std::convert::AsRef<[u8]>
132    + std::marker::Send
133    + std::marker::Sync
134    + 'static,
135) -> Handle {
136    fn inner(bytes: Cow<'static, [u8]>) -> Handle {
137        Handle {
138            symbolic: false,
139            data: match bytes {
140                Cow::Owned(b) => Data::Image(image::Handle::from_bytes(b)),
141                Cow::Borrowed(b) => Data::Image(image::Handle::from_bytes(b)),
142            },
143            source: None,
144        }
145    }
146
147    inner(bytes.into())
148}
149
150/// Create an image handle from RGBA data, where you must define the width and height.
151pub fn from_raster_pixels(
152    width: u32,
153    height: u32,
154    pixels: impl Into<Cow<'static, [u8]>>
155    + std::convert::AsRef<[u8]>
156    + std::marker::Send
157    + std::marker::Sync,
158) -> Handle {
159    fn inner(width: u32, height: u32, pixels: Cow<'static, [u8]>) -> Handle {
160        Handle {
161            symbolic: false,
162            data: match pixels {
163                Cow::Owned(pixels) => Data::Image(image::Handle::from_rgba(width, height, pixels)),
164                Cow::Borrowed(pixels) => {
165                    Data::Image(image::Handle::from_rgba(width, height, pixels))
166                }
167            },
168            source: None,
169        }
170    }
171
172    inner(width, height, pixels.into())
173}
174
175/// Create a SVG handle from memory.
176pub fn from_svg_bytes(bytes: impl Into<Cow<'static, [u8]>>) -> Handle {
177    Handle {
178        symbolic: false,
179        data: Data::Svg(svg::Handle::from_memory(bytes)),
180        source: None,
181    }
182}