Skip to main content

egui_pop_core/icon/
registry.rs

1//! The icon vocabulary: every name an icon can be declared by, resolved
2//! once, and the names that did not resolve.
3//!
4//! A name is one of three kinds:
5//!
6//! - **egui-pop's**, bare and in kebab case (`settings`, `chevron-right`):
7//!   [`Icon::name`] of every icon in [`Icon::ALL`];
8//! - **a Phosphor glyph's**, prefixed (`phosphor:export`,
9//!   `phosphor:grid-four`): every glyph of the regular Phosphor font, with
10//!   the `phosphor` feature; without it these names do not resolve;
11//! - **an application's or a plugin's**, registered as an SVG
12//!   (`crate::icon_set::register`); a plugin's are prefixed by its id
13//!   (`my-plugin:mask-circle`, `crate::icon_set::register_for`).
14//!
15//! [`lookup`] resolves a name, once: the answer is kept, and forgotten
16//! only when a registration changes what the name means. [`resolve`] does
17//! the same and reports a name that does not resolve: a warning in the
18//! log the first time, and a line in [`unknown`] that the debug bridge's
19//! `icons` collector shows (ADR 0003: never a silent no-op). A surface
20//! that cannot draw the icon of an unknown name draws a neutral
21//! placeholder ([`PLACEHOLDER`], or the title's first letter where there
22//! is one).
23//!
24//! What a surface drew by name can be recorded each pass ([`record`]),
25//! so agents read which icon a row or a field shows without pixels
26//! ([`drawn`]).
27
28use std::borrow::Cow;
29use std::collections::{BTreeMap, BTreeSet, HashMap};
30use std::sync::{LazyLock, Mutex, RwLock};
31
32use egui::Context;
33use serde::Serialize;
34
35use super::Icon;
36use crate::state::{lock, pass, shared};
37
38/// The prefix of the Phosphor glyphs' names (`phosphor:export`).
39pub const PHOSPHOR_PREFIX: &str = "phosphor:";
40
41/// What a surface without a title draws for a name that does not
42/// resolve: a hollow ring, so the place is visibly taken.
43pub const PLACEHOLDER: Icon = Icon::Circle;
44
45/// A glyph of the Phosphor font, by its index in the font's list (with
46/// the `phosphor` feature; without it, none exists).
47#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
48pub struct PhosphorIcon(u16);
49
50impl PhosphorIcon {
51    /// Its name, prefixed (`phosphor:grid-four`).
52    pub fn name(self) -> &'static str {
53        phosphor::names()
54            .get(usize::from(self.0))
55            .map_or(PHOSPHOR_PREFIX, String::as_str)
56    }
57
58    /// Its glyph in the icon font.
59    pub fn glyph(self) -> Option<&'static str> {
60        phosphor::glyph(self.0)
61    }
62}
63
64#[cfg(feature = "phosphor")]
65mod phosphor {
66    use std::sync::LazyLock;
67
68    use egui_phosphor::regular::ICONS;
69
70    static NAMES: LazyLock<Vec<String>> = LazyLock::new(|| {
71        ICONS
72            .iter()
73            .map(|(n, _)| {
74                format!(
75                    "{}{}",
76                    super::PHOSPHOR_PREFIX,
77                    n.to_ascii_lowercase().replace('_', "-")
78                )
79            })
80            .collect()
81    });
82
83    pub(super) fn names() -> &'static [String] {
84        &NAMES
85    }
86
87    pub(super) fn find(name: &str) -> Option<u16> {
88        names()
89            .iter()
90            .position(|n| n == name)
91            .and_then(|i| u16::try_from(i).ok())
92    }
93
94    pub(super) fn glyph(i: u16) -> Option<&'static str> {
95        ICONS.get(usize::from(i)).map(|(_, g)| *g)
96    }
97}
98
99#[cfg(not(feature = "phosphor"))]
100mod phosphor {
101    pub(super) fn names() -> &'static [String] {
102        &[]
103    }
104
105    pub(super) fn find(_name: &str) -> Option<u16> {
106        None
107    }
108
109    pub(super) fn glyph(_i: u16) -> Option<&'static str> {
110        None
111    }
112}
113
114/// Whether the Phosphor names resolve (the `phosphor` feature).
115pub fn phosphor_available() -> bool {
116    cfg!(feature = "phosphor")
117}
118
119/// Every Phosphor glyph's name, prefixed, in the font's order; empty
120/// without the `phosphor` feature.
121pub fn phosphor_names() -> &'static [String] {
122    phosphor::names()
123}
124
125/// egui-pop's own names, in [`Icon::ALL`]'s order.
126pub fn builtin_names() -> impl Iterator<Item = &'static str> {
127    Icon::ALL.iter().map(|i| i.name())
128}
129
130/// The names resolved so far, and what each gave.
131static CACHE: LazyLock<RwLock<HashMap<String, Option<Icon>>>> =
132    LazyLock::new(|| RwLock::new(HashMap::new()));
133
134/// The names that did not resolve, with the surfaces that asked.
135static UNKNOWN: LazyLock<Mutex<BTreeMap<String, BTreeSet<String>>>> =
136    LazyLock::new(|| Mutex::new(BTreeMap::new()));
137
138fn find(name: &str) -> Option<Icon> {
139    if name.starts_with(PHOSPHOR_PREFIX) {
140        return phosphor::find(name).map(|i| Icon::Phosphor(PhosphorIcon(i)));
141    }
142    Icon::ALL
143        .iter()
144        .copied()
145        .find(|i| i.name() == name)
146        .or_else(|| crate::icon_set::by_name(name))
147}
148
149/// The icon of a name, silently: egui-pop's names, then the Phosphor
150/// glyphs' (`phosphor:<name>`), then the registered ones. Each name is
151/// looked up once; the answer is kept.
152pub fn lookup(name: &str) -> Option<Icon> {
153    if let Some(hit) = CACHE.read().unwrap_or_else(|e| e.into_inner()).get(name) {
154        return *hit;
155    }
156    let found = find(name);
157    CACHE
158        .write()
159        .unwrap_or_else(|e| e.into_inner())
160        .insert(name.to_string(), found);
161    found
162}
163
164/// Whether a name resolves.
165pub fn is_known(name: &str) -> bool {
166    lookup(name).is_some()
167}
168
169/// The icon of a name, as [`lookup`], reporting a name that does not
170/// resolve: logged once, and listed by [`unknown`] with `surface` (what
171/// declared or drew it: `indicator`, `menu list item`, `panel
172/// egui_pop.jobs`).
173pub fn resolve(name: &str, surface: &str) -> Option<Icon> {
174    let found = lookup(name);
175    if found.is_none() {
176        note_unknown(name, surface);
177    }
178    found
179}
180
181/// Why a name may not resolve, for the warning.
182pub fn hint(name: &str) -> &'static str {
183    if name.starts_with(PHOSPHOR_PREFIX) && !phosphor_available() {
184        "egui-pop was built without the `phosphor` feature"
185    } else if name.starts_with(PHOSPHOR_PREFIX) {
186        "the Phosphor set has no glyph of that name"
187    } else if name.contains(':') {
188        "no icon is registered under that name"
189    } else {
190        "not one of egui-pop's names (a Phosphor glyph is `phosphor:<name>`, a plugin's `<plugin-id>:<name>`)"
191    }
192}
193
194fn note_unknown(name: &str, surface: &str) {
195    let mut u = lock(&UNKNOWN);
196    match u.get_mut(name) {
197        Some(s) if s.contains(surface) => {}
198        Some(s) => {
199            s.insert(surface.to_string());
200        }
201        None => {
202            log::warn!(
203                target: "egui_pop",
204                "unknown icon `{name}` ({surface}): {}; a placeholder is drawn",
205                hint(name)
206            );
207            u.insert(name.to_string(), BTreeSet::from([surface.to_string()]));
208        }
209    }
210}
211
212/// Forgets what a name resolved to, and that it was unknown: a
213/// registration changed it.
214pub(crate) fn forget(name: &str) {
215    CACHE
216        .write()
217        .unwrap_or_else(|e| e.into_inner())
218        .remove(name);
219    lock(&UNKNOWN).remove(name);
220}
221
222/// A name that did not resolve, and who asked for it.
223#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
224pub struct Unknown {
225    pub name: String,
226    /// The surfaces that declared or drew it.
227    pub surfaces: Vec<String>,
228    /// Why it may not resolve.
229    pub hint: &'static str,
230}
231
232/// The names asked of [`resolve`] that did not resolve, by name.
233pub fn unknown() -> Vec<Unknown> {
234    lock(&UNKNOWN)
235        .iter()
236        .map(|(name, s)| Unknown {
237            name: name.clone(),
238            surfaces: s.iter().cloned().collect(),
239            hint: hint(name),
240        })
241        .collect()
242}
243
244/// Names of the vocabulary containing `query` (egui-pop's, the
245/// registered ones, the Phosphor glyphs'), at most `limit`.
246pub fn search(query: &str, limit: usize) -> Vec<String> {
247    let q = query.to_ascii_lowercase();
248    builtin_names()
249        .map(str::to_string)
250        .chain(crate::icon_set::names().into_iter().map(str::to_string))
251        .chain(phosphor_names().iter().cloned())
252        .filter(|n| n.contains(&q))
253        .take(limit)
254        .collect()
255}
256
257/// An icon given by value or by name: what a widget taking an icon
258/// accepts (`Icon::Search`, `"search"`, `"phosphor:export"`).
259#[derive(Clone, Debug, PartialEq, Eq, Hash)]
260pub enum IconRef {
261    Icon(Icon),
262    /// A name of the vocabulary, resolved when used.
263    Name(String),
264}
265
266impl IconRef {
267    /// The icon, or `None` for a name that does not resolve (reported,
268    /// see [`resolve`]).
269    pub fn resolve(&self, surface: &str) -> Option<Icon> {
270        match self {
271            IconRef::Icon(i) => Some(*i),
272            IconRef::Name(n) => resolve(n, surface),
273        }
274    }
275
276    /// The icon, or [`PLACEHOLDER`] for a name that does not resolve
277    /// (reported).
278    pub fn or_placeholder(&self, surface: &str) -> Icon {
279        self.resolve(surface).unwrap_or(PLACEHOLDER)
280    }
281
282    /// Its name, as declared.
283    pub fn name(&self) -> Cow<'_, str> {
284        match self {
285            IconRef::Icon(i) => Cow::Borrowed(i.name()),
286            IconRef::Name(n) => Cow::Borrowed(n),
287        }
288    }
289}
290
291impl From<Icon> for IconRef {
292    fn from(icon: Icon) -> Self {
293        IconRef::Icon(icon)
294    }
295}
296
297impl From<&str> for IconRef {
298    fn from(name: &str) -> Self {
299        IconRef::Name(name.to_string())
300    }
301}
302
303impl From<String> for IconRef {
304    fn from(name: String) -> Self {
305        IconRef::Name(name)
306    }
307}
308
309impl From<&String> for IconRef {
310    fn from(name: &String) -> Self {
311        IconRef::Name(name.clone())
312    }
313}
314
315/// An icon a surface drew, as agents read it.
316#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
317pub struct Drawn {
318    /// What drew it: `tree`, `input`, `breadcrumb`...
319    pub surface: String,
320    /// The text it stands beside (a row's label, a field's).
321    pub label: String,
322    /// The icon's name.
323    pub icon: String,
324}
325
326/// The most icons recorded in one pass.
327const DRAWN_MAX: usize = 1024;
328
329#[derive(Debug, Default)]
330struct DrawnState {
331    pass: u64,
332    building: Vec<Drawn>,
333    last: Vec<Drawn>,
334}
335
336fn rotate(ctx: &Context, s: &mut DrawnState) {
337    let now = pass(ctx);
338    if s.pass != now {
339        s.last = if s.pass + 1 == now {
340            std::mem::take(&mut s.building)
341        } else {
342            s.building.clear();
343            Vec::new()
344        };
345        s.pass = now;
346    }
347}
348
349/// Records an icon drawn this pass beside `label` on `surface`, so agents
350/// see it in [`drawn`] from the next pass.
351pub fn record(ctx: &Context, surface: &str, label: &str, icon: &str) {
352    let st = shared::<DrawnState>(ctx, "core.icons.drawn");
353    let mut s = lock(&st);
354    rotate(ctx, &mut s);
355    if s.building.len() < DRAWN_MAX {
356        s.building.push(Drawn {
357            surface: surface.into(),
358            label: label.into(),
359            icon: icon.into(),
360        });
361    }
362}
363
364/// The icons recorded in the last complete pass.
365pub fn drawn(ctx: &Context) -> Vec<Drawn> {
366    let st = shared::<DrawnState>(ctx, "core.icons.drawn");
367    let mut s = lock(&st);
368    rotate(ctx, &mut s);
369    s.last.clone()
370}
371
372#[cfg(test)]
373mod tests {
374    use super::*;
375
376    #[test]
377    fn a_built_in_name_resolves_and_is_kept() {
378        assert_eq!(lookup("settings"), Some(Icon::Settings));
379        assert_eq!(lookup("settings"), Some(Icon::Settings));
380        assert!(is_known("chevron-right"));
381    }
382
383    #[test]
384    fn an_unknown_name_is_reported_once_with_every_surface() {
385        assert_eq!(resolve("test-no-such-icon", "indicator"), None);
386        assert_eq!(resolve("test-no-such-icon", "indicator"), None);
387        assert_eq!(resolve("test-no-such-icon", "panel demo.p"), None);
388        let u = unknown();
389        let found = u.iter().find(|u| u.name == "test-no-such-icon").unwrap();
390        assert_eq!(found.surfaces, ["indicator", "panel demo.p"]);
391    }
392
393    #[test]
394    fn a_name_given_as_text_resolves_through_the_registry() {
395        let r = IconRef::from("search");
396        assert_eq!(r.resolve("test"), Some(Icon::Search));
397        assert_eq!(IconRef::from(Icon::Close).name(), "close");
398        assert_eq!(
399            IconRef::from("test-missing-ref").or_placeholder("test"),
400            PLACEHOLDER
401        );
402    }
403
404    #[cfg(feature = "phosphor")]
405    #[test]
406    fn phosphor_glyphs_are_named_with_their_prefix() {
407        let grid = lookup("phosphor:grid-four").expect("a Phosphor glyph");
408        assert_eq!(grid.name(), "phosphor:grid-four");
409        assert_eq!(grid.glyph(), Some(egui_phosphor::regular::GRID_FOUR));
410        assert_eq!(lookup("phosphor:no-such-glyph"), None);
411        // Bare, a Phosphor name is not egui-pop's.
412        assert_eq!(lookup("grid-four"), None);
413        assert_eq!(phosphor_names().len(), egui_phosphor::regular::ICONS.len());
414        assert!(search("grid-f", 10).contains(&"phosphor:grid-four".to_string()));
415    }
416
417    #[cfg(not(feature = "phosphor"))]
418    #[test]
419    fn without_the_feature_a_phosphor_name_is_unknown() {
420        assert_eq!(resolve("phosphor:export", "test"), None);
421        assert!(hint("phosphor:export").contains("feature"));
422    }
423
424    #[test]
425    fn drawn_icons_are_read_from_the_pass_before() {
426        let ctx = Context::default();
427        let photos = [Drawn {
428            surface: "tree".into(),
429            label: "Photos".into(),
430            icon: "folder".into(),
431        }];
432        let mut out = ctx.run_ui(Default::default(), |ui| {
433            record(ui.ctx(), "tree", "Photos", "folder");
434        });
435        out.textures_delta.clear();
436        // Between the passes, and all through the next one, the pass
437        // before is the one that drew.
438        assert_eq!(drawn(&ctx), photos);
439        let mut seen = Vec::new();
440        let mut out = ctx.run_ui(Default::default(), |ui| seen = drawn(ui.ctx()));
441        out.textures_delta.clear();
442        assert_eq!(seen, photos);
443        // Once that pass is complete, it drew nothing.
444        assert!(drawn(&ctx).is_empty());
445    }
446}