Skip to main content

crisol_ui_kit/foundation/
icons.rs

1//! Monochrome UI icons, rasterized from SVG once and tinted at draw time.
2//!
3//! Every glyph is a 24×24 SVG drawn in white (`#fff`) strokes or fills, so a single
4//! texture can be tinted with any token color. Applications add their own glyphs with
5//! [`Icons::register`] (the product `logo` is the usual one); a registered name
6//! replaces a bundled glyph of the same name.
7
8use std::collections::HashMap;
9
10use egui::{Color32, Context, Image, Pos2, Rect, TextureHandle, TextureOptions, Ui, Vec2};
11#[cfg(feature = "svg")]
12use resvg::tiny_skia::{Pixmap, Transform};
13use rust_embed::RustEmbed;
14
15#[derive(RustEmbed)]
16#[folder = "assets/ui-icons"]
17struct UiAssets;
18
19/// Pixel size of every UI glyph texture: crisp up to 2× at 16 pt.
20const GLYPH_PIXELS: u32 = 48;
21
22/// The UV rectangle of a whole texture.
23pub const FULL_UV: Rect = Rect::from_min_max(Pos2::ZERO, Pos2::new(1.0, 1.0));
24
25/// UI glyph cache, plus the Material file icons when that feature is on.
26pub struct Icons {
27    custom: HashMap<String, Vec<u8>>,
28    textures: HashMap<String, TextureHandle>,
29    /// File and folder icons from the VS Code Material Icon Theme.
30    #[cfg(feature = "material-icons")]
31    pub material: crate::MaterialIcons,
32}
33
34impl Default for Icons {
35    fn default() -> Self {
36        Self::new()
37    }
38}
39
40impl Icons {
41    /// An empty cache over the bundled glyphs.
42    pub fn new() -> Self {
43        Self {
44            custom: HashMap::new(),
45            textures: HashMap::new(),
46            #[cfg(feature = "material-icons")]
47            material: crate::MaterialIcons::new(),
48        }
49    }
50
51    /// The names of the bundled UI glyphs, sorted.
52    pub fn bundled() -> Vec<String> {
53        let mut names: Vec<String> = UiAssets::iter()
54            .filter_map(|path| path.strip_suffix(".svg").map(str::to_owned))
55            .collect();
56        names.sort();
57        names
58    }
59
60    /// Add or replace a glyph. Draw it in white so tinting works.
61    pub fn register(&mut self, name: &str, svg: impl Into<Vec<u8>>) {
62        self.custom.insert(name.to_owned(), svg.into());
63        let sized = format!("{name}@");
64        self.textures.retain(|key, _| key != name && !key.starts_with(&sized));
65    }
66
67    /// The names of the bundled Lucide icons, sorted.
68    ///
69    /// Lucide names are resolved after the UI glyphs, so `save` keeps the workbench
70    /// glyph and `lucide-save` forces Lucide. `trash-2` (a name only Lucide has) also
71    /// resolves. Both are drawn through the same white-tint pipeline.
72    #[cfg(feature = "lucide-icons")]
73    pub fn lucide_names() -> Vec<String> {
74        crate::foundation::lucide::names()
75    }
76
77    /// Lucide icons matching `query`, best match first. Exact substring matches rank
78    /// before subsequence matches; an empty query returns every name.
79    #[cfg(feature = "lucide-icons")]
80    pub fn lucide_search(query: &str) -> Vec<String> {
81        crate::foundation::lucide::search(query)
82    }
83
84    /// The texture of a glyph, rasterized on first use.
85    ///
86    /// Resolution order: registered custom SVG, bundled UI glyph, Lucide icon. Prefix a
87    /// name with `lucide-` to skip the UI set when both have it.
88    pub fn texture(&mut self, ctx: &Context, name: &str) -> Option<TextureHandle> {
89        self.texture_px(ctx, name, GLYPH_PIXELS)
90    }
91
92    /// The texture of a glyph that stays crisp at `size` points on the current display.
93    ///
94    /// Small glyphs share the 48 px texture; larger ones (gallery previews, empty
95    /// states, toasts on HiDPI screens) are rasterized again at 96, 192, or 384 px.
96    pub fn texture_sized(&mut self, ctx: &Context, name: &str, size: f32) -> Option<TextureHandle> {
97        let needed = size * ctx.pixels_per_point();
98        let pixels = [GLYPH_PIXELS, GLYPH_PIXELS * 2, GLYPH_PIXELS * 4, GLYPH_PIXELS * 8]
99            .into_iter()
100            .find(|&pixels| pixels as f32 >= needed)
101            .unwrap_or(GLYPH_PIXELS * 8);
102        self.texture_px(ctx, name, pixels)
103    }
104
105    fn texture_px(&mut self, ctx: &Context, name: &str, pixels: u32) -> Option<TextureHandle> {
106        let key = if pixels == GLYPH_PIXELS {
107            name.to_owned()
108        } else {
109            format!("{name}@{pixels}")
110        };
111        if let Some(texture) = self.textures.get(&key) {
112            return Some(texture.clone());
113        }
114        let bytes = match self.custom.get(name) {
115            Some(bytes) => bytes.clone(),
116            None => bundled_svg(name)?,
117        };
118        let image = rasterize(&bytes, pixels)?;
119        let texture = ctx.load_texture(format!("workbench-icon-{key}"), image, TextureOptions::LINEAR);
120        self.textures.insert(key, texture.clone());
121        Some(texture)
122    }
123
124    /// Paint a glyph centered in `rect` at `size`, tinted with `color`.
125    pub fn paint(&mut self, ui: &Ui, name: &str, center: Pos2, size: f32, color: Color32) -> bool {
126        let Some(texture) = self.texture_sized(ui.ctx(), name, size) else {
127            return false;
128        };
129        let rect = Rect::from_center_size(center, Vec2::splat(size));
130        ui.painter().image(texture.id(), rect, FULL_UV, color);
131        true
132    }
133
134    /// Place a glyph as a widget at `center` with `ui.put`, like the workbench's title-bar and
135    /// tab-strip buttons. Unlike [`Self::paint`], this moves the layout cursor to the
136    /// glyph's edge, so the next button in the row starts there and overlaps the previous
137    /// cell. That gives the workbench its compact button pitch (see `metrics`).
138    pub fn put(&mut self, ui: &mut Ui, name: &str, center: Pos2, size: f32, color: Color32) -> bool {
139        let Some(texture) = self.texture_sized(ui.ctx(), name, size) else {
140            return false;
141        };
142        let rect = Rect::from_center_size(center, Vec2::splat(size));
143        ui.put(
144            rect,
145            Image::new(&texture).fit_to_exact_size(Vec2::splat(size)).tint(color),
146        );
147        true
148    }
149
150    /// Add a glyph at the cursor, tinted with the text color. Reserves the slot even
151    /// when the glyph is missing, so rows never shift.
152    pub fn show(&mut self, ui: &mut Ui, name: &str, size: f32) {
153        self.show_tinted(ui, name, size, ui.visuals().text_color());
154    }
155
156    /// Add a glyph at the cursor with an explicit tint.
157    pub fn show_tinted(&mut self, ui: &mut Ui, name: &str, size: f32, color: Color32) {
158        if let Some(texture) = self.texture_sized(ui.ctx(), name, size) {
159            ui.add(Image::new(&texture).fit_to_exact_size(Vec2::splat(size)).tint(color));
160        } else {
161            ui.allocate_exact_size(Vec2::splat(size), egui::Sense::hover());
162        }
163    }
164}
165
166fn bundled_svg(name: &str) -> Option<Vec<u8>> {
167    if let Some(name) = name.strip_prefix("lucide-").or_else(|| name.strip_prefix("lucide/")) {
168        return lucide_svg(name);
169    }
170    if let Some(file) = UiAssets::get(&format!("{name}.svg")) {
171        return Some(file.data.into_owned());
172    }
173    lucide_svg(name)
174}
175
176#[cfg(feature = "lucide-icons")]
177fn lucide_svg(name: &str) -> Option<Vec<u8>> {
178    crate::foundation::lucide::svg(name)
179}
180
181#[cfg(not(feature = "lucide-icons"))]
182fn lucide_svg(_name: &str) -> Option<Vec<u8>> {
183    None
184}
185
186/// Rasterize an SVG to fit a `pixels`-square box, keeping its aspect ratio.
187///
188/// Without the `svg` feature there is no rasterizer; icon packs and plots enable it, so
189/// this only returns `None` in a deliberately minimal build.
190#[doc(hidden)]
191pub fn rasterize(bytes: &[u8], pixels: u32) -> Option<egui::ColorImage> {
192    #[cfg(not(feature = "svg"))]
193    {
194        let _ = (bytes, pixels);
195        None
196    }
197    #[cfg(feature = "svg")]
198    {
199        // Parsing and rendering are both linear in the input; refuse an oversized file
200        // before allocating the tree.
201        const MAX_SVG_BYTES: usize = 4 * 1024 * 1024;
202        if bytes.len() > MAX_SVG_BYTES {
203            return None;
204        }
205        // An SVG opened in the viewer is untrusted: never resolve `href`s that name files
206        // (`<image href="/etc/...">`). Inline `data:` images still work.
207        let mut options = usvg::Options::default();
208        options.image_href_resolver.resolve_string = Box::new(|_, _| None);
209        let tree = usvg::Tree::from_data(bytes, &options).ok()?;
210        let size = tree.size();
211        let scale = (pixels as f32 / size.width().max(1.0)).min(pixels as f32 / size.height().max(1.0));
212        let width = (size.width() * scale).round().max(1.0) as u32;
213        let height = (size.height() * scale).round().max(1.0) as u32;
214        let mut pixmap = Pixmap::new(width, height)?;
215        resvg::render(&tree, Transform::from_scale(scale, scale), &mut pixmap.as_mut());
216        let mut rgba = pixmap.take();
217        for pixel in rgba.chunks_exact_mut(4) {
218            let alpha = u16::from(pixel[3]);
219            if alpha > 0 && alpha < 255 {
220                for channel in &mut pixel[..3] {
221                    *channel = ((u16::from(*channel) * 255 + alpha / 2) / alpha).min(255) as u8;
222                }
223            }
224        }
225        Some(egui::ColorImage::from_rgba_unmultiplied(
226            [width as usize, height as usize],
227            &rgba,
228        ))
229    }
230}
231
232#[cfg(test)]
233mod tests {
234    use super::*;
235
236    #[test]
237    #[cfg(feature = "lucide-icons")]
238    fn lucide_is_available_through_the_same_cache() {
239        let names = Icons::lucide_names();
240        assert!(names.len() > 2000, "{}", names.len());
241        assert!(names.iter().any(|name| name == "trash-2"));
242        let mut icons = Icons::new();
243        let ctx = Context::default();
244        for name in ["save", "lucide-save", "trash-2", "heart", "circle-help"] {
245            let texture = icons.texture(&ctx, name).unwrap_or_else(|| panic!("{name}"));
246            assert!(texture.size()[0] > 0, "{name}");
247        }
248    }
249
250    #[test]
251    #[cfg(feature = "svg")]
252    fn every_bundled_glyph_rasterizes() {
253        let names = Icons::bundled();
254        assert!(names.len() >= 40, "{names:?}");
255        for name in names {
256            let file = UiAssets::get(&format!("{name}.svg")).expect("asset");
257            let image = rasterize(&file.data, GLYPH_PIXELS).unwrap_or_else(|| panic!("{name}"));
258            assert_eq!(image.size, [48, 48], "{name}");
259            assert!(image.pixels.iter().any(|pixel| pixel.a() > 0), "{name} is empty");
260        }
261    }
262}