1use 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
38pub const PHOSPHOR_PREFIX: &str = "phosphor:";
40
41pub const PLACEHOLDER: Icon = Icon::Circle;
44
45#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
48pub struct PhosphorIcon(u16);
49
50impl PhosphorIcon {
51 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 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
114pub fn phosphor_available() -> bool {
116 cfg!(feature = "phosphor")
117}
118
119pub fn phosphor_names() -> &'static [String] {
122 phosphor::names()
123}
124
125pub fn builtin_names() -> impl Iterator<Item = &'static str> {
127 Icon::ALL.iter().map(|i| i.name())
128}
129
130static CACHE: LazyLock<RwLock<HashMap<String, Option<Icon>>>> =
132 LazyLock::new(|| RwLock::new(HashMap::new()));
133
134static 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
149pub 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
164pub fn is_known(name: &str) -> bool {
166 lookup(name).is_some()
167}
168
169pub 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
181pub 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
212pub(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#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
224pub struct Unknown {
225 pub name: String,
226 pub surfaces: Vec<String>,
228 pub hint: &'static str,
230}
231
232pub 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
244pub 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#[derive(Clone, Debug, PartialEq, Eq, Hash)]
260pub enum IconRef {
261 Icon(Icon),
262 Name(String),
264}
265
266impl IconRef {
267 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 pub fn or_placeholder(&self, surface: &str) -> Icon {
279 self.resolve(surface).unwrap_or(PLACEHOLDER)
280 }
281
282 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#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
317pub struct Drawn {
318 pub surface: String,
320 pub label: String,
322 pub icon: String,
324}
325
326const 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
349pub 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
364pub 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 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 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 assert!(drawn(&ctx).is_empty());
445 }
446}