1use egui::style::WidgetVisuals;
15use egui::{Color32, CornerRadius, Stroke, Visuals};
16
17use super::{BoxStyle, Component, Kit, State, Tone};
18
19#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
22pub enum Stock {
23 Button,
28 ComboBox,
31 Field,
35 ToggleButton,
39 ScrollBar,
46}
47
48impl Stock {
49 pub const ALL: [Stock; 5] = [
50 Stock::Button,
51 Stock::ComboBox,
52 Stock::Field,
53 Stock::ToggleButton,
54 Stock::ScrollBar,
55 ];
56
57 pub fn component(self) -> &'static str {
59 match self {
60 Stock::Button => "button",
61 Stock::ComboBox => "combo-box",
62 Stock::Field => "field",
63 Stock::ToggleButton => "toggle-button",
64 Stock::ScrollBar => "scroll-bar",
65 }
66 }
67
68 fn of(self, kit: &Kit) -> &Component {
69 match self {
70 Stock::Button => &kit.button,
71 Stock::ComboBox => &kit.combo_box,
72 Stock::Field => &kit.field,
73 Stock::ToggleButton => &kit.toggle_button,
74 Stock::ScrollBar => &kit.scroll_bar,
75 }
76 }
77
78 fn index(self) -> usize {
79 self as usize
80 }
81}
82
83#[derive(Clone, Copy, Debug, PartialEq)]
87pub struct ScopedVisuals {
88 pub widgets: [WidgetVisuals; 4],
91 pub disabled: Option<WidgetVisuals>,
95 pub selection_fill: Option<Color32>,
97 pub selection_stroke: Option<Stroke>,
100 pub text_edit_bg: Option<Color32>,
102 pub extreme_bg: Option<Color32>,
104}
105
106const NONE: ScopedVisuals = ScopedVisuals {
109 widgets: [WIDGET_NONE; 4],
110 disabled: None,
111 selection_fill: None,
112 selection_stroke: None,
113 text_edit_bg: None,
114 extreme_bg: None,
115};
116
117const WIDGET_NONE: WidgetVisuals = WidgetVisuals {
118 bg_fill: Color32::PLACEHOLDER,
119 weak_bg_fill: Color32::PLACEHOLDER,
120 bg_stroke: Stroke::NONE,
121 corner_radius: CornerRadius::ZERO,
122 fg_stroke: Stroke::NONE,
123 expansion: 0.0,
124};
125
126pub(crate) fn widget_visuals(b: &BoxStyle) -> WidgetVisuals {
129 WidgetVisuals {
130 bg_fill: b.fill,
131 weak_bg_fill: b.fill,
132 bg_stroke: Stroke::new(b.border_width, b.border_color),
133 corner_radius: CornerRadius::same(b.radius.round().clamp(0.0, 255.0) as u8),
134 fg_stroke: Stroke::new(1.0, b.text),
135 expansion: 0.0,
136 }
137}
138
139fn set(dst: &mut WidgetVisuals, src: &WidgetVisuals, ppp: f32) {
142 let expansion = dst.expansion;
143 *dst = *src;
144 dst.expansion = expansion;
145 dst.bg_stroke.width = crate::scale::snap(dst.bg_stroke.width, ppp);
146}
147
148impl ScopedVisuals {
149 fn compile(stock: Stock, kit: &Kit, tone: Tone) -> ScopedVisuals {
150 let c = stock.of(kit);
151 let b = |state: State| c.style_toned(tone, state);
152 let rest = b(State::REST);
153 let disabled = b(State::DISABLED);
154 let mut s = ScopedVisuals {
155 widgets: [
156 widget_visuals(rest),
157 widget_visuals(b(State::HOVER)),
158 widget_visuals(b(State::ACTIVE)),
159 widget_visuals(b(State::SELECTED)),
160 ],
161 disabled: (disabled != rest).then(|| widget_visuals(disabled)),
162 ..NONE
163 };
164 match stock {
165 Stock::Button | Stock::ComboBox => {}
166 Stock::ToggleButton => {
167 let on = b(State::SELECTED);
168 s.selection_fill = Some(on.fill);
169 s.selection_stroke = Some(Stroke::new(1.0, on.text));
170 }
171 Stock::Field => {
172 let focus = b(State::FOCUS);
175 s.widgets[2] = widget_visuals(focus);
176 s.widgets[3] = widget_visuals(rest);
177 s.selection_stroke = Some(Stroke::new(focus.border_width, focus.border_color));
178 s.text_edit_bg = Some(rest.fill);
179 }
180 Stock::ScrollBar => {
181 for (i, state) in [State::REST, State::HOVER, State::ACTIVE]
186 .into_iter()
187 .enumerate()
188 {
189 s.widgets[i].fg_stroke.color = b(state).fill;
190 }
191 s.widgets[3] = s.widgets[0];
192 s.extreme_bg = Some(kit.scroll.track);
193 }
194 }
195 s
196 }
197
198 pub fn apply(&self, v: &mut Visuals, enabled: bool, ppp: f32) {
203 let w = &mut v.widgets;
204 for (dst, src) in [&mut w.inactive, &mut w.hovered, &mut w.active, &mut w.open]
205 .into_iter()
206 .zip(&self.widgets)
207 {
208 let src = match (&self.disabled, enabled) {
209 (Some(d), false) => d,
210 _ => src,
211 };
212 set(dst, src, ppp);
213 }
214 if let Some(fill) = self.selection_fill {
215 v.selection.bg_fill = fill;
216 }
217 if let Some(mut stroke) = self.selection_stroke {
218 stroke.width = crate::scale::snap(stroke.width, ppp);
219 v.selection.stroke = stroke;
220 }
221 if let Some(bg) = self.text_edit_bg {
222 v.text_edit_bg_color = Some(bg);
223 }
224 if let Some(bg) = self.extreme_bg {
225 v.extreme_bg_color = bg;
226 }
227 }
228
229 pub(crate) fn apply_widgets(&self, v: &mut Visuals) {
232 let w = &mut v.widgets;
233 for (dst, src) in [&mut w.inactive, &mut w.hovered, &mut w.active, &mut w.open]
234 .into_iter()
235 .zip(&self.widgets)
236 {
237 let expansion = dst.expansion;
238 *dst = *src;
239 dst.expansion = expansion;
240 }
241 }
242}
243
244#[derive(Clone, Debug, Default, PartialEq)]
247pub struct ScopedKit([Box<[ScopedVisuals]>; Stock::ALL.len()]);
248
249impl ScopedKit {
250 pub(super) fn compile(kit: &Kit) -> ScopedKit {
251 ScopedKit(Stock::ALL.map(|stock| {
252 if stock.of(kit).data.states.toned() {
253 let mut all = vec![ScopedVisuals::compile(stock, kit, Tone::Neutral)];
254 all.extend(
255 Tone::NAMED
256 .iter()
257 .map(|(tone, _)| ScopedVisuals::compile(stock, kit, *tone)),
258 );
259 all.into_boxed_slice()
260 } else {
261 Box::new([ScopedVisuals::compile(stock, kit, Tone::Neutral)])
262 }
263 }))
264 }
265
266 pub fn get(&self, stock: Stock, tone: Tone) -> &ScopedVisuals {
269 let table = &self.0[stock.index()];
270 table
271 .get(tone as usize)
272 .or_else(|| table.first())
273 .unwrap_or(&NONE)
274 }
275}
276
277pub(super) fn losses(kit: &Kit) -> Vec<String> {
281 let mut lost = Vec::new();
282 if kit.scroll_bar.shape != "scoped" {
283 lost.push(format!(
284 "scroll-bar.shape: egui draws it, so `{}` is not used (only `scoped`)",
285 kit.scroll_bar.shape
286 ));
287 }
288 for stock in [Stock::ComboBox, Stock::ToggleButton] {
289 let c = stock.of(kit);
290 let name = stock.component();
291 if c.shape != "scoped" {
292 lost.push(format!(
293 "{name}.shape: egui draws it, so `{}` is not used (only `scoped`)",
294 c.shape
295 ));
296 }
297 for (state, sname) in [
298 (State::REST, "rest"),
299 (State::HOVER, "hover"),
300 (State::ACTIVE, "active"),
301 (State::SELECTED, "selected"),
302 ] {
303 let (b, base) = (c.style(state), kit.button.style(state));
305 let indicator = |b: &BoxStyle| (b.indicator_size, b.indicator_color);
306 let ring = |b: &BoxStyle| (b.ring_width, b.ring_color);
307 if b.indicator_size > 0.0
308 && b.indicator_color.a() > 0
309 && indicator(b) != indicator(base)
310 {
311 lost.push(format!("{name}.{sname}: egui draws no indicator"));
312 }
313 if b.ring_width > 0.0 && b.ring_color.a() > 0 && ring(b) != ring(base) {
314 lost.push(format!("{name}.{sname}: egui draws no focus ring"));
315 }
316 }
317 }
318 let toggle = &kit.toggle_button;
319 let (rest, on) = (toggle.style(State::REST), toggle.style(State::SELECTED));
320 if (on.border_color, on.border_width, on.radius)
321 != (rest.border_color, rest.border_width, rest.radius)
322 {
323 lost.push(
324 "toggle-button.selected: egui keeps the state's outline and corners on a selected button"
325 .into(),
326 );
327 }
328 let field = &kit.field;
329 let (rest, focus) = (field.style(State::REST), field.style(State::FOCUS));
330 if focus.ring_width > 0.0 && focus.ring_color.a() > 0 {
331 lost.push("field.focus: egui's text fields draw no focus ring".into());
332 }
333 for (state, sname) in [(State::HOVER, "hover"), (State::FOCUS, "focus")] {
334 if field.style(state).fill != rest.fill {
335 lost.push(format!(
336 "field.{sname}.fill: egui's text fields keep their resting background"
337 ));
338 }
339 }
340 lost
341}
342
343#[cfg(test)]
344mod tests {
345 use super::*;
346 use crate::kit::Shapes;
347 use crate::theme::{self, Tokens};
348 use egui_pop_tokens::{ThemeSpec, Themes};
349
350 fn tokens_with(yaml: &str) -> Tokens {
351 let mut themes = Themes::default();
352 themes
353 .add_text("scoped-test", yaml)
354 .expect("test theme reads");
355 Tokens::new(themes.resolve(&ThemeSpec::new("scoped-test")))
356 }
357
358 const RESTYLED: &str = r##"
359 $extends: "pop-dark"
360 combo-box:
361 rest:
362 fill: {$type: "color", $value: "#102030"}
363 radius: {$type: "dimension", $value: {value: 9, unit: "px"}}
364 selected:
365 fill: {$type: "color", $value: "#203040"}
366 toggle-button:
367 selected:
368 fill: {$type: "color", $value: "#405060"}
369 text: {$type: "color", $value: "#ffeedd"}
370 field:
371 focus:
372 border-color: {$type: "color", $value: "#00ff00"}
373 border-width: {$type: "dimension", $value: {value: 2, unit: "px"}}
374 button:
375 disabled:
376 fill: {$type: "color", $value: "#333333"}
377 "##;
378
379 fn pass(ctx: &egui::Context, add: impl FnMut(&mut egui::Ui)) {
380 let mut out = ctx.run_ui(egui::RawInput::default(), add);
381 out.textures_delta.clear();
382 }
383
384 #[test]
385 fn egui_s_global_widgets_are_the_button_s_scope() {
386 let t = Tokens::default();
387 let kit = Kit::compile(&t, &Shapes::default());
388 let v = theme::visuals_with(&t, &kit);
389 let s = kit.scoped.get(Stock::Button, Tone::Neutral);
390 assert_eq!(v.widgets.inactive.weak_bg_fill, s.widgets[0].weak_bg_fill);
391 assert_eq!(v.widgets.hovered.bg_stroke, s.widgets[1].bg_stroke);
392 assert_eq!(v.widgets.open.fg_stroke, s.widgets[3].fg_stroke);
393 let combo = kit.scoped.get(Stock::ComboBox, Tone::Neutral);
395 assert_eq!(combo.widgets, s.widgets);
396 let toggle = kit.scoped.get(Stock::ToggleButton, Tone::Neutral);
397 assert_eq!(toggle.selection_fill, Some(v.selection.bg_fill));
398 assert_eq!(toggle.selection_stroke, Some(v.selection.stroke));
399 let field = kit.scoped.get(Stock::Field, Tone::Neutral);
400 assert_eq!(field.selection_stroke, Some(v.selection.stroke));
401 assert_eq!(field.text_edit_bg, v.text_edit_bg_color);
402 let danger = kit.scoped.get(Stock::Button, Tone::Danger);
404 assert_ne!(danger, s);
405 assert_eq!(
406 kit.scoped.get(Stock::ComboBox, Tone::Danger).widgets,
407 danger.widgets
408 );
409 }
410
411 #[test]
412 fn a_scope_draws_egui_s_widgets_from_the_kit_and_stays_in_its_scope() {
413 let ctx = egui::Context::default();
414 theme::install_tokens(&ctx, tokens_with(RESTYLED));
415 let kit = Kit::of(&ctx);
416 assert!(kit.problems.is_empty(), "{:?}", kit.problems);
417 pass(&ctx, |ui| {
418 let before = ui.visuals().clone();
419 kit.scope(ui, Stock::ComboBox, Tone::Neutral, |ui| {
420 let w = &ui.visuals().widgets;
421 assert_eq!(w.inactive.weak_bg_fill, Color32::from_rgb(0x10, 0x20, 0x30));
422 assert_eq!(w.inactive.corner_radius, CornerRadius::same(9));
423 assert_eq!(w.open.weak_bg_fill, Color32::from_rgb(0x20, 0x30, 0x40));
424 assert_eq!(w.hovered.expansion, before.widgets.hovered.expansion);
426 });
427 kit.scope(ui, Stock::ToggleButton, Tone::Neutral, |ui| {
428 let s = ui.visuals().selection;
429 assert_eq!(s.bg_fill, Color32::from_rgb(0x40, 0x50, 0x60));
430 assert_eq!(s.stroke.color, Color32::from_rgb(0xff, 0xee, 0xdd));
431 });
432 kit.scope(ui, Stock::Field, Tone::Danger, |ui| {
433 let v = ui.visuals();
434 assert_eq!(v.selection.stroke.color, Color32::from_rgb(0, 0xff, 0));
435 assert_eq!(v.selection.stroke.width, 2.0);
436 let danger = kit.field.style_toned(Tone::Danger, State::REST);
437 assert_eq!(v.widgets.inactive.bg_stroke.color, danger.border_color);
438 });
439 ui.add_enabled_ui(false, |ui| {
440 kit.scope(ui, Stock::Button, Tone::Neutral, |ui| {
441 let grey = Color32::from_rgb(0x33, 0x33, 0x33);
442 let w = &ui.visuals().widgets;
443 assert_eq!(w.inactive.bg_fill, grey);
444 assert_eq!(w.hovered.bg_fill, grey);
445 });
446 });
447 assert_eq!(*ui.visuals(), before);
448 let r = kit.scope(ui, Stock::Button, Tone::Accent, |ui| ui.button("Go"));
449 assert!(r.inner.rect.width() > 0.0);
450 });
451 }
452
453 #[test]
454 fn what_egui_cannot_draw_of_a_scoped_component_is_a_problem() {
455 let t = tokens_with(
456 r##"
457 $extends: "pop-dark"
458 combo-box:
459 shape: {$type: "string", $value: "box"}
460 hover:
461 ring-color: {$type: "color", $value: "#ff0000"}
462 ring-width: {$type: "dimension", $value: {value: 1, unit: "px"}}
463 toggle-button:
464 selected:
465 border-color: {$type: "color", $value: "#ff0000"}
466 field:
467 focus:
468 fill: {$type: "color", $value: "#ff0000"}
469 "##,
470 );
471 let kit = Kit::compile(&t, &Shapes::default());
472 let p = kit.problems.join("\n");
473 assert!(p.contains("combo-box.shape"), "{p}");
474 assert!(
475 p.contains("combo-box.hover: egui draws no focus ring"),
476 "{p}"
477 );
478 assert!(p.contains("toggle-button.selected"), "{p}");
479 assert!(p.contains("field.focus.fill"), "{p}");
480 }
481}