Skip to main content

egui_pop_core/kit/
window.rs

1//! What a window drawn by the application takes from the kit beside its
2//! components' boxes: where its title bar puts the window buttons, which
3//! of them show the hover state, the corners the system is asked for and
4//! the outline drawn around it.
5//! Compiled with the kit, read as plain fields.
6
7use super::{Tokens, string};
8
9/// Where the window buttons go on the title bar (`title-bar.buttons-side`).
10#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
11pub enum ButtonsSide {
12    /// Before the leading items, close at the start edge, then minimize
13    /// and maximize (macOS).
14    Start,
15    /// After the trailing items, minimize, maximize, then close at the
16    /// end edge (Windows, most Linux desktops). The default.
17    #[default]
18    End,
19}
20
21/// Which window buttons are drawn `hover` (`title-bar.buttons-hover`).
22#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
23pub enum ButtonsHover {
24    /// The one under the pointer. The default.
25    #[default]
26    Own,
27    /// All three while the pointer is over any of them (macOS shows every
28    /// glyph then).
29    Group,
30}
31
32/// The corners asked of the system for a window drawn by the application
33/// (`window.corners`), where it can round them (Windows 11).
34#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
35pub enum WindowCorners {
36    /// The system's rounded corners. The default.
37    #[default]
38    Round,
39    /// The system's small rounded corners.
40    Small,
41    /// Square corners.
42    Square,
43}
44
45impl WindowCorners {
46    /// The token's value.
47    pub fn name(self) -> &'static str {
48        match self {
49            WindowCorners::Round => "round",
50            WindowCorners::Small => "small",
51            WindowCorners::Square => "square",
52        }
53    }
54}
55
56/// Where a section's count goes on its band (`section-count.placement`).
57#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
58pub enum CountPlacement {
59    /// At the band's end, the title clipped before it. The default.
60    #[default]
61    End,
62    /// Right after the title, `space.inline` from it; the title still
63    /// clips to the band's room, the count after what shows of it.
64    AfterTitle,
65}
66
67/// The sections' terms of a kit beside their components' boxes.
68#[derive(Clone, Copy, Debug, Default, PartialEq)]
69pub struct SectionsKit {
70    pub count_placement: CountPlacement,
71}
72
73impl SectionsKit {
74    pub(super) fn compile(t: &Tokens, problems: &mut Vec<String>) -> SectionsKit {
75        SectionsKit {
76            count_placement: choice(
77                t,
78                "section-count.placement",
79                &[
80                    ("end", CountPlacement::End),
81                    ("after-title", CountPlacement::AfterTitle),
82                ],
83                problems,
84            ),
85        }
86    }
87}
88
89/// The window's terms of a kit.
90#[derive(Clone, Copy, Debug, Default, PartialEq)]
91pub struct WindowKit {
92    pub buttons_side: ButtonsSide,
93    pub buttons_hover: ButtonsHover,
94    pub corners: WindowCorners,
95    /// The line around a window drawn by the application, inside its
96    /// edges (`window.rest.border-width` and `border-color`); none when
97    /// the width is 0.
98    pub outline: egui::Stroke,
99}
100
101/// The rest of a window's edge, beside [`WindowKit::outline`]: the line
102/// while another window has the focus and the corners rounded while the
103/// window floats free.
104#[derive(Clone, Copy, Debug, Default, PartialEq)]
105#[non_exhaustive]
106pub struct WindowEdgeKit {
107    /// The line around the window while another window has the focus
108    /// (`window.inactive.border-color`, dimmer).
109    pub inactive: egui::Stroke,
110    /// The corners the application rounds on its own floating window
111    /// (`window.radius`), in points; 0 for square.
112    pub radius: f32,
113}
114
115impl WindowEdgeKit {
116    pub(super) fn compile(t: &Tokens) -> WindowEdgeKit {
117        WindowEdgeKit {
118            inactive: outline(t, "window.inactive.border-color"),
119            radius: t
120                .resolved()
121                .dimension("window.radius")
122                .unwrap_or(0.0)
123                .max(0.0),
124        }
125    }
126}
127
128/// Reads a string token among `choices`; what is not one of them is a
129/// problem and gives the default.
130pub(super) fn choice<T: Copy + Default>(
131    t: &Tokens,
132    path: &str,
133    choices: &[(&str, T)],
134    problems: &mut Vec<String>,
135) -> T {
136    let Some(asked) = string(t, path) else {
137        return T::default();
138    };
139    match choices.iter().find(|(name, _)| *name == asked) {
140        Some((_, v)) => *v,
141        None => {
142            let names: Vec<&str> = choices.iter().map(|(n, _)| *n).collect();
143            let (last, first) = names.split_last().unwrap_or((&"", &[]));
144            problems.push(format!(
145                "{path}: `{asked}` is not {} or {last}",
146                first.join(", ")
147            ));
148            T::default()
149        }
150    }
151}
152
153impl WindowKit {
154    pub(super) fn compile(t: &Tokens, problems: &mut Vec<String>) -> WindowKit {
155        WindowKit {
156            buttons_side: choice(
157                t,
158                "title-bar.buttons-side",
159                &[("start", ButtonsSide::Start), ("end", ButtonsSide::End)],
160                problems,
161            ),
162            buttons_hover: choice(
163                t,
164                "title-bar.buttons-hover",
165                &[("own", ButtonsHover::Own), ("group", ButtonsHover::Group)],
166                problems,
167            ),
168            corners: choice(
169                t,
170                "window.corners",
171                &[
172                    ("round", WindowCorners::Round),
173                    ("small", WindowCorners::Small),
174                    ("square", WindowCorners::Square),
175                ],
176                problems,
177            ),
178            outline: outline(t, "window.rest.border-color"),
179        }
180    }
181}
182
183/// The window's line in the colour at `color`, `window.rest.border-width`
184/// wide; none when that is 0.
185fn outline(t: &Tokens, color: &str) -> egui::Stroke {
186    match t.resolved().dimension("window.rest.border-width") {
187        Some(w) if w > 0.0 => egui::Stroke::new(
188            w,
189            t.color(color)
190                .or_else(|| t.color("window.rest.border-color"))
191                .unwrap_or(egui::Color32::TRANSPARENT),
192        ),
193        _ => egui::Stroke::NONE,
194    }
195}
196
197#[cfg(test)]
198mod tests {
199    use super::*;
200    use egui_pop_tokens::{ThemeSpec, Themes};
201
202    fn kit(json: &str) -> crate::kit::Kit {
203        let mut themes = Themes::default();
204        themes
205            .add_text("window-test", json)
206            .expect("test theme reads");
207        let t = Tokens::new(themes.resolve(&ThemeSpec::new("window-test")));
208        crate::kit::Kit::compile(&t, &crate::kit::Shapes::default())
209    }
210
211    #[test]
212    fn corners_are_round_by_default_and_read_from_the_theme() {
213        let default = kit(r#"
214                          $extends: "pop-dark"
215                          "#);
216        assert_eq!(default.window.corners, WindowCorners::Round);
217        // A 1 px line, dimmer while another window has the focus, and
218        // the window's radius.
219        let (w, e) = (default.window, default.window_edge);
220        assert_eq!(w.outline.width, 1.0);
221        assert_eq!(e.inactive.width, 1.0);
222        assert!(e.inactive.color.a() < w.outline.color.a(), "{e:?}");
223        assert_eq!(e.radius, 8.0);
224        let square = kit(r#"
225                         $extends: "pop-dark"
226                         window:
227                           corners: {$type: "string", $value: "square"}
228                         "#);
229        assert_eq!(square.window.corners, WindowCorners::Square);
230        assert!(square.problems.is_empty(), "{:?}", square.problems);
231        let bad = kit(r#"
232                      $extends: "pop-dark"
233                      window:
234                        corners: {$type: "string", $value: "oval"}
235                      "#);
236        assert_eq!(bad.window.corners, WindowCorners::Round);
237        assert_eq!(
238            bad.problems,
239            ["window.corners: `oval` is not round, small or square"]
240        );
241    }
242}