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, 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    /// Rasterized at exactly the painted size in device pixels ([`icon_pixels`]), so
95    /// it is drawn one texel per pixel at every zoom. A larger bitmap shrunk by the GPU
96    /// (no mipmaps) skips texels and reads pixelated below 100%, and a smaller one
97    /// stretched reads blurry at fractional scales.
98    pub fn texture_sized(&mut self, ctx: &Context, name: &str, size: f32) -> Option<TextureHandle> {
99        self.texture_px(ctx, name, icon_pixels(ctx, size))
100    }
101
102    fn texture_px(&mut self, ctx: &Context, name: &str, pixels: u32) -> Option<TextureHandle> {
103        let key = if pixels == GLYPH_PIXELS {
104            name.to_owned()
105        } else {
106            format!("{name}@{pixels}")
107        };
108        if let Some(texture) = self.textures.get(&key) {
109            return Some(texture.clone());
110        }
111        let bytes = match self.custom.get(name) {
112            Some(bytes) => bytes.clone(),
113            None => bundled_svg(name)?,
114        };
115        let image = rasterize(&bytes, pixels)?;
116        let texture = ctx.load_texture(format!("workbench-icon-{key}"), image, TextureOptions::LINEAR);
117        self.textures.insert(key, texture.clone());
118        Some(texture)
119    }
120
121    /// Paint a glyph centered in `rect` at `size`, tinted with `color`.
122    pub fn paint(&mut self, ui: &Ui, name: &str, center: Pos2, size: f32, color: Color32) -> bool {
123        let Some(texture) = self.texture_sized(ui.ctx(), name, size) else {
124            return false;
125        };
126        let rect = pixel_rect(ui.ctx(), center, size);
127        ui.painter().image(texture.id(), rect, FULL_UV, color);
128        true
129    }
130
131    /// Place a glyph as a widget at `center` with `ui.put`, like the workbench's title-bar and
132    /// tab-strip buttons. Unlike [`Self::paint`], this moves the layout cursor to the
133    /// glyph's edge, so the next button in the row starts there and overlaps the previous
134    /// cell. That gives the workbench its compact button pitch (see `metrics`).
135    pub fn put(&mut self, ui: &mut Ui, name: &str, center: Pos2, size: f32, color: Color32) -> bool {
136        let Some(texture) = self.texture_sized(ui.ctx(), name, size) else {
137            return false;
138        };
139        let rect = Rect::from_center_size(center, Vec2::splat(size));
140        let response = ui.allocate_rect(rect, egui::Sense::hover());
141        ui.painter().image(
142            texture.id(),
143            pixel_rect(ui.ctx(), response.rect.center(), size),
144            FULL_UV,
145            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        let (rect, _) = ui.allocate_exact_size(Vec2::splat(size), egui::Sense::hover());
159        if let Some(texture) = self.texture_sized(ui.ctx(), name, size) {
160            ui.painter()
161                .image(texture.id(), pixel_rect(ui.ctx(), rect.center(), size), FULL_UV, color);
162        }
163    }
164}
165
166/// The device-pixel size an icon painted at `size` points occupies on this display.
167///
168/// Rasterize at this size and paint into [`pixel_rect`] for one texel per pixel.
169pub fn icon_pixels(ctx: &Context, size: f32) -> u32 {
170    (size * ctx.pixels_per_point()).round().clamp(8.0, 512.0) as u32
171}
172
173/// A `size`-point square centered near `center`, moved onto whole device pixels and
174/// sized to [`icon_pixels`], so a texture rasterized at that size is not resampled.
175///
176/// Layout positions are fractional at zooms like 110% or a 1.25 desktop factor;
177/// painting a texture there samples between texels and smears every edge.
178pub fn pixel_rect(ctx: &Context, center: Pos2, size: f32) -> Rect {
179    let ppp = ctx.pixels_per_point();
180    let side = icon_pixels(ctx, size) as f32;
181    let min = (center.to_vec2() * ppp - Vec2::splat(side * 0.5)).round();
182    Rect::from_min_size((min / ppp).to_pos2(), Vec2::splat(side / ppp))
183}
184
185fn bundled_svg(name: &str) -> Option<Vec<u8>> {
186    if let Some(name) = name.strip_prefix("lucide-").or_else(|| name.strip_prefix("lucide/")) {
187        return lucide_svg(name);
188    }
189    if let Some(file) = UiAssets::get(&format!("{name}.svg")) {
190        return Some(file.data.into_owned());
191    }
192    lucide_svg(name)
193}
194
195#[cfg(feature = "lucide-icons")]
196fn lucide_svg(name: &str) -> Option<Vec<u8>> {
197    crate::foundation::lucide::svg(name)
198}
199
200#[cfg(not(feature = "lucide-icons"))]
201fn lucide_svg(_name: &str) -> Option<Vec<u8>> {
202    None
203}
204
205/// Rasterize an SVG to fit a `pixels`-square box, keeping its aspect ratio.
206///
207/// Without the `svg` feature there is no rasterizer; icon packs and plots enable it, so
208/// this only returns `None` in a deliberately minimal build.
209#[doc(hidden)]
210pub fn rasterize(bytes: &[u8], pixels: u32) -> Option<egui::ColorImage> {
211    #[cfg(not(feature = "svg"))]
212    {
213        let _ = (bytes, pixels);
214        None
215    }
216    #[cfg(feature = "svg")]
217    {
218        // Parsing and rendering are both linear in the input; refuse an oversized file
219        // before allocating the tree.
220        const MAX_SVG_BYTES: usize = 4 * 1024 * 1024;
221        if bytes.len() > MAX_SVG_BYTES {
222            return None;
223        }
224        // An SVG opened in the viewer is untrusted: never resolve `href`s that name files
225        // (`<image href="/etc/...">`). Inline `data:` images still work.
226        let mut options = usvg::Options::default();
227        options.image_href_resolver.resolve_string = Box::new(|_, _| None);
228        let tree = usvg::Tree::from_data(bytes, &options).ok()?;
229        let size = tree.size();
230        let scale = (pixels as f32 / size.width().max(1.0)).min(pixels as f32 / size.height().max(1.0));
231        let width = (size.width() * scale).round().max(1.0) as u32;
232        let height = (size.height() * scale).round().max(1.0) as u32;
233        let mut pixmap = Pixmap::new(width, height)?;
234        resvg::render(&tree, Transform::from_scale(scale, scale), &mut pixmap.as_mut());
235        let mut rgba = pixmap.take();
236        for pixel in rgba.chunks_exact_mut(4) {
237            let alpha = u16::from(pixel[3]);
238            if alpha > 0 && alpha < 255 {
239                for channel in &mut pixel[..3] {
240                    *channel = ((u16::from(*channel) * 255 + alpha / 2) / alpha).min(255) as u8;
241                }
242            }
243        }
244        Some(egui::ColorImage::from_rgba_unmultiplied(
245            [width as usize, height as usize],
246            &rgba,
247        ))
248    }
249}
250
251#[cfg(test)]
252mod tests {
253    use super::*;
254
255    #[test]
256    #[cfg(feature = "lucide-icons")]
257    fn lucide_is_available_through_the_same_cache() {
258        let names = Icons::lucide_names();
259        assert!(names.len() > 2000, "{}", names.len());
260        assert!(names.iter().any(|name| name == "trash-2"));
261        let mut icons = Icons::new();
262        let ctx = Context::default();
263        for name in ["save", "lucide-save", "trash-2", "heart", "circle-help"] {
264            let texture = icons.texture(&ctx, name).unwrap_or_else(|| panic!("{name}"));
265            assert!(texture.size()[0] > 0, "{name}");
266        }
267    }
268
269    #[test]
270    #[cfg(feature = "svg")]
271    fn every_bundled_glyph_rasterizes() {
272        let names = Icons::bundled();
273        assert!(names.len() >= 40, "{names:?}");
274        for name in names {
275            let file = UiAssets::get(&format!("{name}.svg")).expect("asset");
276            let image = rasterize(&file.data, GLYPH_PIXELS).unwrap_or_else(|| panic!("{name}"));
277            assert_eq!(image.size, [48, 48], "{name}");
278            assert!(image.pixels.iter().any(|pixel| pixel.a() > 0), "{name} is empty");
279        }
280    }
281
282    #[test]
283    fn pixel_rects_cover_whole_device_pixels_at_every_zoom() {
284        for zoom in [0.8_f32, 0.9, 1.0, 1.1, 1.25, 1.3, 1.5, 2.0] {
285            let ctx = Context::default();
286            ctx.set_pixels_per_point(zoom);
287            let rect = pixel_rect(&ctx, Pos2::new(37.37, 11.81), 16.0);
288            let ppp = ctx.pixels_per_point();
289            for value in [rect.min.x, rect.min.y, rect.max.x, rect.max.y] {
290                let px = value * ppp;
291                assert!((px - px.round()).abs() < 1e-3, "{value} at {zoom}");
292            }
293            assert_eq!(
294                (rect.width() * ppp).round() as u32,
295                icon_pixels(&ctx, 16.0),
296                "at {zoom}"
297            );
298        }
299    }
300}