Skip to main content

egui_pop_core/
icon_set.rs

1//! An application's own icons: SVG files registered by name, drawn like
2//! egui-pop's own ([`Icon::Custom`]) and nameable by a kit's glyphs
3//! (`glyph.<role>: "<name>"`).
4//!
5//! An icon is single-colour ([`Paint::Mono`], tinted at draw with the
6//! colour a widget gives, like the built-in icons) or full-colour
7//! ([`Paint::Colour`], an application's logo, drawn as it is).
8//!
9//! An application's names may stay bare (`play-circle`); a plugin's are
10//! prefixed by its id (`my-plugin:mask-circle`, [`register_for`]) so two
11//! plugins never clash. `phosphor:` names belong to the Phosphor set.
12//! A contributor's removal cleans its icons: [`unregister_owner`] (the
13//! application calls it when a plugin is disconnected) or [`unregister`]
14//! for one name.
15//!
16//! [`install`] (run with the theme, `theme::install_tokens`) rasterises
17//! every registered icon at the icon sizes of the theme (`size.icon.*`)
18//! and the window's pixels per point, as textures; drawing paints one
19//! image. An icon drawn at another size (a kit's `indicator-size`, an
20//! application's 15 points) is rasterised at that size the first time it
21//! is drawn, then kept: scaling a texture would blur it.
22//! A single-colour icon is a white mask, so one texture serves every
23//! colour. Rasterising needs the `svg` feature (resvg); without it,
24//! [`register`] refuses.
25
26use std::collections::HashMap;
27use std::sync::{Arc, Mutex, RwLock};
28
29use egui::{Color32, Context, Painter, Rect, TextureHandle};
30
31use crate::icon::Icon;
32use crate::state::Slot;
33use crate::theme::Tokens;
34
35/// How an icon is coloured.
36#[derive(Clone, Copy, Debug, PartialEq, Eq)]
37pub enum Paint {
38    /// One colour, given at draw (its shape is the SVG's alpha).
39    Mono,
40    /// Its own colours.
41    Colour,
42}
43
44/// An icon an application registered.
45#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
46pub struct CustomIcon(u16);
47
48/// Why an icon could not be registered.
49#[derive(Clone, Debug, PartialEq, Eq)]
50pub enum IconError {
51    /// The name is one of egui-pop's icons.
52    Taken(String),
53    /// The file is not an SVG resvg can read.
54    Svg(String),
55    /// Built without the `svg` feature.
56    Unsupported,
57}
58
59impl std::fmt::Display for IconError {
60    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
61        match self {
62            IconError::Taken(n) if n.starts_with(crate::icon::registry::PHOSPHOR_PREFIX) => {
63                write!(f, "`{n}` is in the Phosphor set's name space")
64            }
65            IconError::Taken(n) => write!(f, "`{n}` is one of egui-pop's icons"),
66            IconError::Svg(e) => write!(f, "not a readable SVG: {e}"),
67            IconError::Unsupported => write!(f, "egui-pop was built without the `svg` feature"),
68        }
69    }
70}
71
72impl std::error::Error for IconError {}
73
74struct Entry {
75    name: &'static str,
76    svg: Arc<[u8]>,
77    paint: Paint,
78    /// Unregistered: the name no longer resolves; its slot (an icon's id
79    /// is its index) is reused if the name is registered again.
80    removed: bool,
81}
82
83/// The registered icons, for the whole process: an icon's name and id
84/// are the same in every window.
85static SET: RwLock<Vec<Entry>> = RwLock::new(Vec::new());
86
87/// Registers an SVG icon under a name (kebab case, like `play-circle`),
88/// or replaces the one registered under it. In use from the next theme
89/// install. A name keeps its id for the whole process, even unregistered
90/// ([`unregister`]) and registered again. A name
91/// `<owner>:<name>` is owned by `owner` (see [`register_for`]); egui-pop's
92/// names and the `phosphor:` ones are refused.
93pub fn register(name: &str, svg: impl Into<Arc<[u8]>>, paint: Paint) -> Result<Icon, IconError> {
94    if Icon::ALL.iter().any(|i| i.name() == name)
95        || name.starts_with(crate::icon::registry::PHOSPHOR_PREFIX)
96    {
97        return Err(IconError::Taken(name.into()));
98    }
99    let svg = svg.into();
100    check(&svg)?;
101    let icon = {
102        let mut set = SET.write().unwrap_or_else(|e| e.into_inner());
103        if let Some(i) = set.iter().position(|e| e.name == name) {
104            set[i].svg = svg;
105            set[i].paint = paint;
106            set[i].removed = false;
107            Icon::Custom(CustomIcon(i as u16))
108        } else {
109            let id = u16::try_from(set.len()).expect("fewer than 65536 icons");
110            set.push(Entry {
111                name: Box::leak(name.to_string().into_boxed_str()),
112                svg,
113                paint,
114                removed: false,
115            });
116            Icon::Custom(CustomIcon(id))
117        }
118    };
119    // The name may have been looked up, and found unknown, before.
120    crate::icon::registry::forget(name);
121    Ok(icon)
122}
123
124/// Registers a plugin's SVG icon under `<owner>:<name>` (the plugin's id
125/// as `owner`: `my-plugin:mask-circle`), as [`register`] does.
126pub fn register_for(
127    owner: &str,
128    name: &str,
129    svg: impl Into<Arc<[u8]>>,
130    paint: Paint,
131) -> Result<Icon, IconError> {
132    register(&format!("{owner}:{name}"), svg, paint)
133}
134
135/// Unregisters the icon registered under `name`: the name stops
136/// resolving at once, and its textures go at the next theme install.
137/// Returns whether it was registered.
138pub fn unregister(name: &str) -> bool {
139    let found = {
140        let mut set = SET.write().unwrap_or_else(|e| e.into_inner());
141        match set.iter_mut().find(|e| e.name == name && !e.removed) {
142            Some(e) => {
143                e.removed = true;
144                e.svg = Arc::from(&[][..]);
145                true
146            }
147            None => false,
148        }
149    };
150    if found {
151        crate::icon::registry::forget(name);
152    }
153    found
154}
155
156/// Unregisters every icon of an owner (`<owner>:<name>`, see
157/// [`register_for`]), as [`unregister`] does: a contributor's removal
158/// cleans its registrations. The application API calls it when a plugin
159/// is disconnected or fails to connect. Returns how many were removed.
160///
161/// The set is the process's: an owner's icons go for every window and
162/// every application in it.
163pub fn unregister_owner(owner: &str) -> usize {
164    let prefix = format!("{owner}:");
165    let names: Vec<&'static str> = {
166        let set = SET.read().unwrap_or_else(|e| e.into_inner());
167        set.iter()
168            .filter(|e| !e.removed && e.name.starts_with(&prefix))
169            .map(|e| e.name)
170            .collect()
171    };
172    names.into_iter().filter(|n| unregister(n)).count()
173}
174
175/// A registered icon, as agents read it.
176#[derive(Clone, Debug, PartialEq, Eq)]
177pub struct Registered {
178    pub name: &'static str,
179    /// The plugin owning it (the part before `:`), `None` for an
180    /// application's bare name.
181    pub owner: Option<&'static str>,
182    pub paint: Paint,
183}
184
185/// Every registered icon, in registration order.
186pub fn registered() -> Vec<Registered> {
187    let set = SET.read().unwrap_or_else(|e| e.into_inner());
188    set.iter()
189        .filter(|e| !e.removed)
190        .map(|e| Registered {
191            name: e.name,
192            owner: e.name.split_once(':').map(|(o, _)| o),
193            paint: e.paint,
194        })
195        .collect()
196}
197
198/// A registered icon by name.
199pub fn by_name(name: &str) -> Option<Icon> {
200    let set = SET.read().unwrap_or_else(|e| e.into_inner());
201    set.iter()
202        .position(|e| e.name == name && !e.removed)
203        .map(|i| Icon::Custom(CustomIcon(i as u16)))
204}
205
206/// Every registered icon's name, in registration order.
207pub fn names() -> Vec<&'static str> {
208    let set = SET.read().unwrap_or_else(|e| e.into_inner());
209    set.iter().filter(|e| !e.removed).map(|e| e.name).collect()
210}
211
212pub(crate) fn name(icon: CustomIcon) -> &'static str {
213    let set = SET.read().unwrap_or_else(|e| e.into_inner());
214    set.get(usize::from(icon.0)).map_or("custom", |e| e.name)
215}
216
217#[cfg(feature = "svg")]
218fn check(svg: &[u8]) -> Result<(), IconError> {
219    resvg::usvg::Tree::from_data(svg, &resvg::usvg::Options::default())
220        .map(|_| ())
221        .map_err(|e| IconError::Svg(e.to_string()))
222}
223
224#[cfg(not(feature = "svg"))]
225fn check(_svg: &[u8]) -> Result<(), IconError> {
226    Err(IconError::Unsupported)
227}
228
229/// One icon's textures, smallest first.
230#[derive(Clone)]
231struct Rasters {
232    paint: Paint,
233    /// (side in physical pixels, texture).
234    sizes: Vec<(u32, TextureHandle)>,
235}
236
237#[derive(Clone, Default)]
238struct Installed {
239    ppp: f32,
240    icons: Vec<Rasters>,
241}
242
243/// Textures made while drawing, for sizes [`install`] did not make: by
244/// icon and side in physical pixels (`None`: the SVG did not rasterise).
245type Textures = HashMap<(u16, u32), Option<TextureHandle>>;
246
247#[derive(Clone, Default)]
248struct Extra(Arc<Mutex<Textures>>);
249
250const EXTRA: Slot<Extra> = Slot::opaque("core.icon_set.extra");
251
252/// The texture of an icon at a side no install made, made on first use.
253fn extra(ctx: &Context, icon: CustomIcon, px: u32, paint: Paint) -> Option<TextureHandle> {
254    let cache = EXTRA.update(ctx, |e| e.clone());
255    let mut map = cache.0.lock().unwrap_or_else(|e| e.into_inner());
256    map.entry((icon.0, px))
257        .or_insert_with(|| {
258            let set = SET.read().unwrap_or_else(|e| e.into_inner());
259            let e = set.get(usize::from(icon.0)).filter(|e| !e.removed)?;
260            let image = rasterise(&e.svg, px, paint)?;
261            let name = format!("egui_pop.icon.{}.{px}", e.name);
262            Some(ctx.load_texture(name, image, egui::TextureOptions::LINEAR))
263        })
264        .clone()
265}
266
267const INSTALLED: Slot<Arc<Installed>> = Slot::opaque("core.icon_set.installed");
268
269/// Rasterises every registered icon at the theme's icon sizes and the
270/// context's pixels per point. Called by `theme::install_tokens`, between
271/// frames; a no-op when nothing is registered.
272pub fn install(ctx: &Context, tokens: &Tokens) {
273    let set = SET.read().unwrap_or_else(|e| e.into_inner());
274    if set.is_empty() {
275        return;
276    }
277    let ppp = ctx.pixels_per_point();
278    let mut sides: Vec<u32> = [
279        tokens.size.icon_inline,
280        tokens.size.icon_toolbar,
281        tokens.size.icon_panel,
282    ]
283    .iter()
284    .map(|s| (s * ppp).round().max(1.0) as u32)
285    .collect();
286    sides.sort_unstable();
287    sides.dedup();
288    let icons = set
289        .iter()
290        .map(|e| Rasters {
291            paint: e.paint,
292            sizes: sides
293                .iter()
294                .filter(|_| !e.removed)
295                .filter_map(|&px| {
296                    let image = rasterise(&e.svg, px, e.paint)?;
297                    let name = format!("egui_pop.icon.{}.{px}", e.name);
298                    Some((
299                        px,
300                        ctx.load_texture(name, image, egui::TextureOptions::LINEAR),
301                    ))
302                })
303                .collect(),
304        })
305        .collect();
306    INSTALLED.set(ctx, Arc::new(Installed { ppp, icons }));
307}
308
309#[cfg(feature = "svg")]
310fn rasterise(svg: &[u8], px: u32, paint: Paint) -> Option<egui::ColorImage> {
311    use resvg::{tiny_skia, usvg};
312    let tree = usvg::Tree::from_data(svg, &usvg::Options::default()).ok()?;
313    let size = tree.size();
314    let scale = px as f32 / size.width().max(size.height());
315    let (dx, dy) = (
316        (px as f32 - size.width() * scale) / 2.0,
317        (px as f32 - size.height() * scale) / 2.0,
318    );
319    let mut pixmap = tiny_skia::Pixmap::new(px, px)?;
320    resvg::render(
321        &tree,
322        tiny_skia::Transform::from_row(scale, 0.0, 0.0, scale, dx, dy),
323        &mut pixmap.as_mut(),
324    );
325    let mut rgba = pixmap.take();
326    if paint == Paint::Mono {
327        // A white mask: premultiplied, white at alpha a is (a, a, a, a).
328        for p in rgba.chunks_exact_mut(4) {
329            let a = p[3];
330            p.copy_from_slice(&[a, a, a, a]);
331        }
332    }
333    Some(egui::ColorImage::from_rgba_premultiplied(
334        [px as usize, px as usize],
335        &rgba,
336    ))
337}
338
339#[cfg(not(feature = "svg"))]
340fn rasterise(_svg: &[u8], _px: u32, _paint: Paint) -> Option<egui::ColorImage> {
341    None
342}
343
344/// Paints a registered icon in a square: the texture of the nearest
345/// size at or above the square's, tinted with `color` when single-colour.
346/// Nothing is drawn before the first install that saw it.
347pub(crate) fn paint(painter: &Painter, icon: CustomIcon, rect: Rect, color: Color32) {
348    let Some(installed) = INSTALLED.get(painter.ctx()) else {
349        return;
350    };
351    let Some(r) = installed.icons.get(usize::from(icon.0)) else {
352        return;
353    };
354    let want = (rect.width().min(rect.height()) * installed.ppp)
355        .round()
356        .max(1.0) as u32;
357    // Its texture at that side: an installed one, or one made now.
358    let made;
359    let texture = match r.sizes.iter().find(|(px, _)| *px == want) {
360        Some((_, t)) => t,
361        None => match extra(painter.ctx(), icon, want, r.paint) {
362            Some(t) => {
363                made = t;
364                &made
365            }
366            None => return,
367        },
368    };
369    // Drawn at its own pixel size, on the pixel grid: crisp.
370    let side = want as f32 / installed.ppp;
371    let min = rect.center() - egui::Vec2::splat(side / 2.0);
372    let min = egui::pos2(
373        (min.x * installed.ppp).round() / installed.ppp,
374        (min.y * installed.ppp).round() / installed.ppp,
375    );
376    let tint = match r.paint {
377        Paint::Mono => color,
378        Paint::Colour => Color32::WHITE.gamma_multiply(f32::from(color.a()) / 255.0),
379    };
380    painter.image(
381        texture.id(),
382        Rect::from_min_size(min, egui::Vec2::splat(side)),
383        Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(1.0, 1.0)),
384        tint,
385    );
386}
387
388#[cfg(all(test, feature = "svg"))]
389mod tests {
390    use super::*;
391
392    const RING: &[u8] = br#"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><circle cx="12" cy="12" r="9" fill="none" stroke="black" stroke-width="2"/></svg>"#;
393
394    #[test]
395    fn a_registered_icon_has_a_name_and_an_id_and_is_rasterised_as_a_mask() {
396        let icon = register("test-ring", RING, Paint::Mono).unwrap();
397        assert_eq!(by_name("test-ring"), Some(icon));
398        assert_eq!(icon.name(), "test-ring");
399        assert_eq!(Icon::by_name("test-ring"), Some(icon));
400        let image = rasterise(RING, 24, Paint::Mono).unwrap();
401        // The ring's top edge is drawn, white at some alpha; the centre
402        // is empty.
403        let top = image[(12, 3)];
404        assert!(top.a() > 100 && top.r() == top.a(), "{top:?}");
405        assert_eq!(image[(12, 12)].a(), 0);
406    }
407
408    #[test]
409    fn a_plugin_icon_is_prefixed_by_its_owner_and_resolves_once_registered() {
410        assert_eq!(Icon::by_name("test-plugin:ring"), None);
411        let ring = register_for("test-plugin", "ring", RING, Paint::Mono).unwrap();
412        assert_eq!(ring.name(), "test-plugin:ring");
413        assert_eq!(Icon::by_name("test-plugin:ring"), Some(ring));
414        let r = registered();
415        let entry = r.iter().find(|e| e.name == "test-plugin:ring").unwrap();
416        assert_eq!(entry.owner, Some("test-plugin"));
417        assert!(matches!(
418            register("phosphor:ring", RING, Paint::Mono),
419            Err(IconError::Taken(_))
420        ));
421    }
422
423    #[test]
424    fn a_contributor_removal_unregisters_its_icons_and_keeps_others() {
425        let a = register_for("test-gone", "a", RING, Paint::Mono).unwrap();
426        register_for("test-gone", "b", RING, Paint::Colour).unwrap();
427        let kept = register_for("test-gone-not", "a", RING, Paint::Mono).unwrap();
428        assert_eq!(Icon::by_name("test-gone:a"), Some(a), "looked up, cached");
429        assert_eq!(unregister_owner("test-gone"), 2);
430        assert_eq!(Icon::by_name("test-gone:a"), None);
431        assert_eq!(by_name("test-gone:b"), None);
432        assert!(!names().contains(&"test-gone:a"));
433        assert!(registered().iter().all(|e| e.owner != Some("test-gone")));
434        assert_eq!(Icon::by_name("test-gone-not:a"), Some(kept));
435        assert_eq!(unregister_owner("test-gone"), 0, "nothing left");
436        // Registered again, it takes its old id back.
437        assert_eq!(register_for("test-gone", "a", RING, Paint::Mono), Ok(a));
438        assert_eq!(Icon::by_name("test-gone:a"), Some(a));
439        assert!(unregister("test-gone:a"));
440        assert!(!unregister("test-gone:a"));
441    }
442
443    #[test]
444    fn a_built_in_name_or_a_broken_file_is_refused() {
445        assert_eq!(
446            register("check", RING, Paint::Mono),
447            Err(IconError::Taken("check".into()))
448        );
449        assert!(matches!(
450            register("broken", &b"<svg"[..], Paint::Mono),
451            Err(IconError::Svg(_))
452        ));
453    }
454
455    #[test]
456    fn a_kit_glyph_can_name_an_application_icon() {
457        let ring = register("test-kit-ring", RING, Paint::Mono).unwrap();
458        let mut themes = egui_pop_tokens::Themes::default();
459        themes
460            .add_text(
461                "ring-check",
462                r#"
463                $extends: "pop-dark"
464                glyph:
465                  check: {$type: "string", $value: "test-kit-ring"}
466                "#,
467            )
468            .unwrap();
469        let t = Tokens::new(themes.resolve(&egui_pop_tokens::ThemeSpec::new("ring-check")));
470        let kit = crate::kit::Kit::compile(&t, &crate::kit::Shapes::default());
471        assert_eq!(kit.glyph(crate::kit::Glyph::Check), ring);
472        assert!(kit.problems.is_empty(), "{:?}", kit.problems);
473    }
474
475    #[test]
476    fn install_makes_one_texture_per_icon_size() {
477        register("test-dot", RING, Paint::Colour).unwrap();
478        let ctx = Context::default();
479        install(&ctx, &Tokens::default());
480        let installed = INSTALLED.get(&ctx).unwrap();
481        let t = Tokens::default();
482        let mut sides = vec![t.size.icon_inline, t.size.icon_toolbar, t.size.icon_panel];
483        sides.dedup();
484        let at = names().iter().position(|n| *n == "test-dot").unwrap();
485        assert_eq!(installed.icons[at].sizes.len(), sides.len());
486    }
487
488    #[test]
489    fn a_size_no_install_made_is_rasterised_once_at_that_size() {
490        let ring = register("test-odd-ring", RING, Paint::Mono).unwrap();
491        let Icon::Custom(c) = ring else {
492            panic!("an application icon")
493        };
494        let ctx = Context::default();
495        install(&ctx, &Tokens::default());
496        let painter = Painter::new(ctx.clone(), egui::LayerId::background(), Rect::EVERYTHING);
497        let square = Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(15.0, 15.0));
498        ring.paint(&painter, square, Color32::WHITE);
499        ring.paint(&painter, square, Color32::WHITE);
500        let cache = EXTRA.update(&ctx, |e| e.clone());
501        let map = cache.0.lock().unwrap();
502        let made: Vec<_> = map.keys().filter(|(i, _)| *i == c.0).collect();
503        assert_eq!(made, [&(c.0, 15)]);
504        assert_eq!(map[&(c.0, 15)].as_ref().unwrap().size(), [15, 15]);
505    }
506}