Skip to main content

egui_pop_core/kit/
source.rs

1//! A kit to install (`docs/kit-packages.md`): its data (tokens, faces,
2//! licence: `egui_pop_tokens::kit::KitData`) and, for a kit with code,
3//! the handlers its `shape` tokens name.
4//!
5//! A data-only kit is a folder or a `kit!`; a kit with code is a crate
6//! exposing a function giving its source:
7//!
8//! ```
9//! use std::sync::Arc;
10//! use egui_pop_core::kit::{ComponentKit, KitCx, KitSource, Part, Primitive};
11//!
12//! struct Notch;
13//! impl Primitive<ComponentKit> for Notch {
14//!     fn measure(&self, data: &ComponentKit, label: egui::Vec2) -> egui::Vec2 {
15//!         egui::vec2(label.x + 2.0 * data.padding_x, data.height)
16//!     }
17//!     fn paint(&self, cx: &KitCx<'_>, data: &ComponentKit, part: &Part<'_>) {
18//!         let b = data.states.get(part.state);
19//!         cx.painter.rect_filled(part.rect, b.radius, b.fill);
20//!     }
21//!     fn paint_label(&self, cx: &KitCx<'_>, data: &ComponentKit, part: &Part<'_>) {
22//!         egui_pop_core::kit::paint_label(cx, data, part);
23//!     }
24//! }
25//!
26//! /// The kit's crate: `pub fn kit() -> KitSource`.
27//! pub fn kit() -> KitSource {
28//!     let data = egui_pop_tokens::kit::KitData::from_text(
29//!         "notched",
30//!         r#"
31//!         tab:
32//!           shape: {$type: "string", $value: "notch"}
33//!         "#,
34//!     );
35//!     KitSource::new(data).shape("tab", "notch", Arc::new(Notch))
36//! }
37//!
38//! let ctx = egui::Context::default();
39//! let source = kit();
40//! source.register(&ctx);
41//! let mut themes = egui_pop_tokens::Themes::default();
42//! themes.add_kit(&source.data);
43//! egui_pop_core::theme::install_with(&ctx, &themes, &egui_pop_tokens::ThemeSpec::new("notched"));
44//! assert_eq!(egui_pop_core::kit::Kit::of(&ctx).tab.shape, "notch");
45//! ```
46//!
47//! `AppBuilder::kit` does those three steps in an application.
48
49use std::sync::Arc;
50
51use egui::Context;
52use egui_pop_tokens::kit::{Bytes, KitData};
53
54use super::{COMPONENTS, ComponentKit, Primitive, register_shape};
55use crate::fonts::{self, Face, Weight};
56
57type Handler = Arc<dyn Primitive<ComponentKit>>;
58
59/// A kit to install: its data and its handlers.
60#[derive(Clone)]
61pub struct KitSource {
62    pub data: KitData,
63    shapes: Vec<(String, String, Handler)>,
64    problems: Vec<String>,
65}
66
67impl From<KitData> for KitSource {
68    fn from(data: KitData) -> Self {
69        KitSource::new(data)
70    }
71}
72
73impl KitSource {
74    /// A kit with no handlers of its own (data only).
75    pub fn new(data: KitData) -> KitSource {
76        KitSource {
77            data,
78            shapes: Vec::new(),
79            problems: Vec::new(),
80        }
81    }
82
83    /// Adds a handler its tokens can name (`tab.shape`), for a component
84    /// of [`COMPONENTS`]; one for another component is reported and not
85    /// registered.
86    #[must_use]
87    pub fn shape(mut self, component: &str, name: &str, handler: Handler) -> KitSource {
88        if COMPONENTS.iter().any(|(c, _)| *c == component) {
89            self.shapes.push((component.into(), name.into(), handler));
90        } else {
91            self.problems.push(format!(
92                "handler `{name}`: no kit component is named `{component}` (known: {}); not registered",
93                COMPONENTS
94                    .iter()
95                    .map(|(c, _)| *c)
96                    .collect::<Vec<_>>()
97                    .join(", ")
98            ));
99        }
100        self
101    }
102
103    /// The kit's theme name.
104    pub fn name(&self) -> &str {
105        &self.data.name
106    }
107
108    /// The handlers it adds: component and name.
109    pub fn handlers(&self) -> impl Iterator<Item = (&str, &str)> {
110        self.shapes.iter().map(|(c, n, _)| (c.as_str(), n.as_str()))
111    }
112
113    /// Its faces, for `fonts::register`.
114    pub fn faces(&self) -> Vec<Face> {
115        self.data
116            .fonts
117            .iter()
118            .map(|f| match &f.bytes {
119                Bytes::Borrowed(b) => Face::from_static(&f.family, Weight(f.weight), b),
120                Bytes::Owned(b) => Face::from_owned(&f.family, Weight(f.weight), b.clone()),
121            })
122            .collect()
123    }
124
125    /// What was wrong reading the kit and adding its handlers, as text.
126    pub fn problems(&self) -> Vec<String> {
127        self.data
128            .problems()
129            .iter()
130            .map(ToString::to_string)
131            .chain(self.problems.iter().cloned())
132            .collect()
133    }
134
135    /// Registers its faces and handlers in a context, in use from the next
136    /// theme install (its theme is added to the `Themes` the application
137    /// resolves: `Themes::add_kit`). Called at start-up or in a "change
138    /// kit" step, never per frame.
139    pub fn register(&self, ctx: &Context) {
140        for face in self.faces() {
141            fonts::register(ctx, face);
142        }
143        for (component, name, handler) in &self.shapes {
144            register_shape(ctx, component, name, handler.clone());
145        }
146    }
147}
148
149impl std::fmt::Debug for KitSource {
150    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
151        f.debug_struct("KitSource")
152            .field("name", &self.data.name)
153            .field("handlers", &self.handlers().collect::<Vec<_>>())
154            .field("fonts", &self.data.fonts)
155            .finish_non_exhaustive()
156    }
157}
158
159#[cfg(test)]
160mod tests {
161    use super::*;
162    use egui_pop_tokens::kit::KitFont;
163    use egui_pop_tokens::{ThemeSpec, Themes};
164
165    static INTER_VAR: &[u8] = include_bytes!("../../tests/fonts/InterVariable-subset.ttf");
166
167    #[test]
168    fn a_kit_registers_its_faces_and_its_theme_names_them() {
169        let mut data = KitData::from_text(
170            "inter",
171            r#"
172            font:
173              family:
174                ui: {$type: "fontFamily", $value: ["Inter", "sans-serif"]}
175            "#,
176        );
177        data.fonts.push(KitFont {
178            file: "Inter.ttf".into(),
179            family: "Inter".into(),
180            weight: 400,
181            bytes: Bytes::Borrowed(INTER_VAR),
182        });
183        let source = KitSource::from(data);
184        let ctx = Context::default();
185        source.register(&ctx);
186        let mut themes = Themes::default();
187        themes.add_kit(&source.data);
188        crate::theme::install_with(&ctx, &themes, &ThemeSpec::new("inter"));
189        let report = fonts::report(&ctx).expect("installed");
190        assert!(report.problems.is_empty(), "{report:?}");
191        assert!(
192            report
193                .primary
194                .iter()
195                .any(|(_, p)| p.as_deref().is_some_and(|p| p.contains("Inter"))),
196            "{report:?}"
197        );
198    }
199
200    #[test]
201    fn a_handler_for_no_component_is_reported() {
202        let source = KitSource::new(KitData::from_text("k", "{}")).shape(
203            "tabz",
204            "x",
205            Arc::new(super::super::shapes::Plain),
206        );
207        assert_eq!(source.handlers().count(), 0);
208        assert!(
209            source.problems()[0].contains("`tabz`"),
210            "{:?}",
211            source.problems()
212        );
213    }
214}