Skip to main content

egui_pop_core/kit/
glyph.rs

1//! Glyphs by role: the small marks widgets draw (a branch's disclosure, a
2//! sort direction, a menu's check...) named by what they mean, each mapped
3//! by the kit to an icon of its set (`glyph.<role>` tokens). Widgets ask
4//! for a role, never draw a shape: a kit turns the tree's triangles into
5//! chevrons, or a check into a dot, with data only.
6
7use crate::icon::Icon;
8use crate::theme::Tokens;
9
10macro_rules! glyphs {
11    ($($(#[$doc:meta])* $role:ident: $name:literal => $default:ident,)*) => {
12        /// What a small mark means. The vocabulary is fixed: a widget
13        /// needing a new mark adds a role here, never a shape of its own.
14        ///
15        /// Need (icon): a small mark by meaning (disclosure, sort, check, close).
16        #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
17        pub enum Glyph {
18            $($(#[$doc])* $role,)*
19        }
20
21        impl Glyph {
22            /// Every role, in declaration order.
23            pub const ALL: &'static [Glyph] = &[$(Glyph::$role,)*];
24
25            /// Its token name (`glyph.<name>`).
26            pub fn name(self) -> &'static str {
27                match self {
28                    $(Glyph::$role => $name,)*
29                }
30            }
31
32            /// The icon drawn when a kit names none it knows.
33            pub fn default_icon(self) -> Icon {
34                match self {
35                    $(Glyph::$role => Icon::$default,)*
36                }
37            }
38        }
39    };
40}
41
42glyphs! {
43    /// An open branch, an expanded section.
44    DisclosureOpen: "disclosure-open" => TriangleDown,
45    /// A closed branch, a collapsed section.
46    DisclosureClosed: "disclosure-closed" => TriangleRight,
47    /// A column sorted ascending.
48    SortAscending: "sort-ascending" => TriangleUp,
49    /// A column sorted descending.
50    SortDescending: "sort-descending" => TriangleDown,
51    /// A checked item.
52    Check: "check" => Check,
53    /// The chosen item of a group.
54    Radio: "radio" => Dot,
55    /// A partly checked item.
56    Indeterminate: "indeterminate" => Minus,
57    /// An item of a list.
58    Bullet: "bullet" => Dot,
59    /// An item opening a submenu.
60    Submenu: "submenu" => ChevronRight,
61    /// Back, towards the start.
62    ChevronStart: "chevron-start" => ChevronLeft,
63    /// Forward, towards the end.
64    ChevronEnd: "chevron-end" => ChevronRight,
65    /// Closes or removes.
66    Close: "close" => Close,
67    /// More actions.
68    More: "more" => More,
69    /// Something to grab or to open: a folded area's strip.
70    DragHandle: "drag-handle" => Grip,
71    /// Opens a list of choices: a combo box's arrow.
72    Dropdown: "dropdown" => TriangleDown,
73    /// Expands, adds a level.
74    Expand: "expand" => Plus,
75    /// Collapses, removes a level.
76    Collapse: "collapse" => Minus,
77    /// A window's minimize button (drawn by the application).
78    WindowMinimize: "window-minimize" => WindowMinimize,
79    /// A window's maximize button.
80    WindowMaximize: "window-maximize" => WindowMaximize,
81    /// A maximized window's restore button.
82    WindowRestore: "window-restore" => WindowRestore,
83    /// A window's close button.
84    WindowClose: "window-close" => WindowClose,
85    /// A full screen window's button leaving full screen (where maximize
86    /// was).
87    WindowExitFullscreen: "window-exit-fullscreen" => ExitFullscreen,
88    /// An LED that is off.
89    LedOff: "led-off" => Circle,
90    /// An LED that is on.
91    LedOn: "led-on" => Disc,
92    /// A busy LED (it pulses too, a still ring under reduced motion, so it may share the on LED's shape).
93    LedBusy: "led-busy" => Disc,
94    /// An LED warning.
95    LedWarning: "led-warning" => Triangle,
96    /// An LED in error.
97    LedError: "led-error" => Square,
98    /// A modified flag (`corner` fills the corner it sits in).
99    FlagModified: "flag-modified" => Corner,
100    /// A pinned flag.
101    FlagPinned: "flag-pinned" => Diamond,
102    /// A required flag.
103    FlagRequired: "flag-required" => Asterisk,
104    /// An invalid flag.
105    FlagInvalid: "flag-invalid" => Triangle,
106}
107
108/// The icon of each role, compiled from the kit's tokens: read by index
109/// while drawing.
110#[derive(Clone, Debug, PartialEq)]
111pub struct Glyphs(Vec<Icon>);
112
113impl Default for Glyphs {
114    /// Every role's default icon.
115    fn default() -> Self {
116        Glyphs(Glyph::ALL.iter().map(|g| g.default_icon()).collect())
117    }
118}
119
120impl Glyphs {
121    pub(super) fn compile(t: &Tokens, problems: &mut Vec<String>) -> Glyphs {
122        let mut glyphs = Glyphs::read(t, problems);
123        glyphs.keep_shapes_distinct(problems);
124        glyphs
125    }
126
127    /// Two roles that must differ (`egui_pop_tokens::kit::DISTINCT_GLYPHS`)
128    /// and draw the same icon go back to their defaults, which differ, so
129    /// colour never carries a state alone; a problem says so.
130    fn keep_shapes_distinct(&mut self, problems: &mut Vec<String>) {
131        let role = |name: &str| Glyph::ALL.iter().copied().find(|g| g.name() == name);
132        loop {
133            let clash = egui_pop_tokens::kit::DISTINCT_GLYPHS
134                .iter()
135                .filter_map(|(a, b)| Some((role(a)?, role(b)?)))
136                .find(|(a, b)| {
137                    self.get(*a) == self.get(*b)
138                        && (self.get(*a) != a.default_icon() || self.get(*b) != b.default_icon())
139                });
140            let Some((a, b)) = clash else { break };
141            problems.push(format!(
142                "glyph.{} and glyph.{} both draw `{}`: their states would differ by colour alone; `{}` and `{}` are drawn",
143                a.name(),
144                b.name(),
145                self.get(a).name(),
146                a.default_icon().name(),
147                b.default_icon().name()
148            ));
149            self.0[a as usize] = a.default_icon();
150            self.0[b as usize] = b.default_icon();
151        }
152    }
153
154    fn read(t: &Tokens, problems: &mut Vec<String>) -> Glyphs {
155        Glyphs(
156            Glyph::ALL
157                .iter()
158                .map(|g| {
159                    let path = format!("glyph.{}", g.name());
160                    match super::string(t, &path) {
161                        None => g.default_icon(),
162                        Some(name) => Icon::by_name(&name).unwrap_or_else(|| {
163                            problems.push(format!(
164                                "{path}: no icon named `{name}`, `{}` is drawn",
165                                g.default_icon().name()
166                            ));
167                            g.default_icon()
168                        }),
169                    }
170                })
171                .collect(),
172        )
173    }
174
175    /// The icon of a role.
176    pub fn get(&self, glyph: Glyph) -> Icon {
177        self.0[glyph as usize]
178    }
179}