Skip to main content

brep_app/ui_kit/
chrome_toolbar.rs

1//! The toolbar's own controls on the refreshed look (ui-refresh-spec section 5,
2//! "Icon buttons"), for `panels/toolbar_button.rs`, the one place every
3//! toolbar, ribbon, context and sketch button is drawn: a square tool button,
4//! the ribbon's Large button (artwork over a label) and an icon row for menus
5//! and the workbench switcher. Owned by the UI-CHROME lane.
6//!
7//! Unlike [`super::IconButton`], these keep the toolbar's own metrics (the
8//! caller passes the square's size, which already includes the touch target)
9//! and attach no tooltip: the caller does, with the command's detail and its
10//! disabled reason. They are `egui::Widget`s that read `ui.is_enabled()`, so
11//! `ui.add_enabled(false, ...)` disables them exactly as it did the
12//! `egui::Button` each replaces, `on_disabled_hover_text` included.
13use super::paint;
14use crate::theme::{radius, space, Text, Theme, RING};
15use eframe::egui::{self, Color32, Rect, Stroke, Vec2};
16
17/// Painted edge of a tool button's artwork (and a menu row's icon slot).
18pub const GLYPH_SIZE: f32 = 17.0;
19/// Side of a Large button's artwork square.
20pub const LARGE_ART: f32 = 28.0;
21
22/// The text colour of a control in its state: primary, or disabled.
23fn ink(theme: &Theme, enabled: bool) -> Color32 {
24    if enabled { theme.colors.text_primary } else { theme.colors.text_disabled }
25}
26
27/// Paint `glyph`'s catalogued cropped artwork in `rect`: monochrome artwork
28/// in `color`, colour artwork in its own colours (dimmed when disabled).
29/// Returns whether the glyph is catalogued.
30fn paint_artwork(ui: &egui::Ui, glyph: &str, rect: Rect, color: Color32, enabled: bool) -> bool {
31    let Some(icon) = crate::icons::artwork(glyph) else { return false };
32    egui_extras::install_image_loaders(ui.ctx());
33    let tint = if icon.mono {
34        color
35    } else if enabled {
36        Color32::WHITE
37    } else {
38        Color32::WHITE.gamma_multiply(0.4)
39    };
40    egui::Image::new(egui::ImageSource::Bytes {
41        uri: format!("bytes://brep-toolbar/{}.svg", icon.name).into(),
42        bytes: egui::load::Bytes::Static(icon.artwork_svg.as_bytes()),
43    })
44    .fit_to_exact_size(rect.size())
45    .tint(tint)
46    .paint_at(ui, rect);
47    true
48}
49
50/// The hover / pressed / selected background and the focus ring every
51/// toolbar control shares. `bar` draws the 2 px accent bar under a selected
52/// control (the ribbon and toolbars); rows leave it off.
53fn paint_state(ui: &egui::Ui, rect: Rect, response: &egui::Response, selected: bool, bar: bool, theme: &Theme) {
54    let c = &theme.colors;
55    let enabled = ui.is_enabled();
56    let hover = ui.ctx().animate_bool_with_time(response.id.with("hover"), enabled && response.hovered(), theme.motion_fast());
57    let on = ui.ctx().animate_bool_with_time(response.id.with("on"), selected, theme.motion_base());
58    let body = rect.shrink(1.0);
59    if on > 0.0 {
60        ui.painter().rect_filled(body, radius::BUTTON, paint::lerp_color(Color32::TRANSPARENT, c.accent_muted, on));
61    }
62    let overlay = if enabled && response.is_pointer_button_down_on() { c.pressed } else { paint::lerp_color(Color32::TRANSPARENT, c.hover, hover) };
63    ui.painter().rect_filled(body, radius::BUTTON, overlay);
64    if bar && on > 0.0 {
65        let strip = Rect::from_min_max(egui::pos2(rect.left() + 6.0, rect.bottom() - RING - 1.0), egui::pos2(rect.right() - 6.0, rect.bottom() - 1.0));
66        ui.painter().rect_filled(strip, 1.0, paint::lerp_color(Color32::TRANSPARENT, c.accent_ring, on));
67    }
68    if response.has_focus() {
69        paint::focus_ring(ui, body, radius::BUTTON, theme);
70    }
71}
72
73/// A square toolbar button: `glyph`'s artwork centred, or the characters
74/// themselves when it has none.
75#[must_use = "a tool button does nothing until it is added to a Ui"]
76pub struct ToolButton<'a> {
77    glyph: &'a str,
78    size: Vec2,
79    selected: bool,
80}
81
82impl<'a> ToolButton<'a> {
83    pub fn new(glyph: &'a str, size: Vec2) -> Self {
84        Self { glyph, size, selected: false }
85    }
86    /// A toggle that is on, or the tool in use.
87    pub fn selected(mut self, selected: bool) -> Self {
88        self.selected = selected;
89        self
90    }
91}
92
93impl egui::Widget for ToolButton<'_> {
94    fn ui(self, ui: &mut egui::Ui) -> egui::Response {
95        let theme = Theme::of(ui);
96        // A glyph with no catalogued artwork is drawn as its text ("Faces", "Planes"):
97        // widen the button to fit it, as the egui button it replaced did, or a row of
98        // text toggles paints each label over its neighbours.
99        let mut size = self.size;
100        if crate::icons::artwork(self.glyph).is_none() {
101            let text_width = paint::galley(ui, self.glyph, theme.font(Text::Body)).size().x;
102            size.x = size.x.max(text_width + 2.0 * space::MD);
103        }
104        let (rect, response) = ui.allocate_exact_size(size, egui::Sense::click());
105        let enabled = ui.is_enabled();
106        response.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::Button, enabled, self.selected, self.glyph));
107        if ui.is_rect_visible(rect) {
108            paint_state(ui, rect, &response, self.selected, true, &theme);
109            let nudge = Vec2::new(0.0, if enabled && response.is_pointer_button_down_on() { 1.0 } else { 0.0 });
110            let slot = Rect::from_center_size(rect.center() + nudge, Vec2::splat(GLYPH_SIZE));
111            let color = ink(&theme, enabled);
112            if !paint_artwork(ui, self.glyph, slot, color, enabled) {
113                let g = paint::galley(ui, self.glyph, theme.font(Text::Body));
114                ui.painter().galley(rect.center() + nudge - g.size() / 2.0, g, color);
115            }
116        }
117        response
118    }
119}
120
121/// The ribbon's Large button: artwork over its label, [`crate::panels::toolbar_button::LARGE_BTN`] tall.
122#[must_use = "a large button does nothing until it is added to a Ui"]
123pub struct LargeButton<'a> {
124    glyph: &'a str,
125    label: &'a str,
126    height: f32,
127    selected: bool,
128}
129
130impl<'a> LargeButton<'a> {
131    pub fn new(glyph: &'a str, label: &'a str, height: f32) -> Self {
132        Self { glyph, label, height, selected: false }
133    }
134    pub fn selected(mut self, selected: bool) -> Self {
135        self.selected = selected;
136        self
137    }
138    /// The width the button takes: its label (at least 32 pt) and the
139    /// control padding either side.
140    pub fn width(ui: &egui::Ui, label: &str) -> f32 {
141        let theme = Theme::of(ui);
142        paint::galley(ui, label, large_font(&theme)).size().x.max(32.0) + 2.0 * space::XS
143    }
144}
145
146/// A Large button's label font: the caption size, so a 1600 pt Modeling
147/// ribbon keeps its Large buttons.
148fn large_font(theme: &Theme) -> egui::FontId {
149    theme.font(Text::Caption)
150}
151
152impl egui::Widget for LargeButton<'_> {
153    fn ui(self, ui: &mut egui::Ui) -> egui::Response {
154        let theme = Theme::of(ui);
155        let width = LargeButton::width(ui, self.label);
156        let (rect, response) = ui.allocate_exact_size(Vec2::new(width, self.height), egui::Sense::click());
157        let enabled = ui.is_enabled();
158        response.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::Button, enabled, self.selected, self.label));
159        if ui.is_rect_visible(rect) {
160            paint_state(ui, rect, &response, self.selected, true, &theme);
161            let color = ink(&theme, enabled);
162            let art = Rect::from_center_size(egui::pos2(rect.center().x, rect.top() + 22.0), Vec2::splat(LARGE_ART));
163            if !paint_artwork(ui, self.glyph, art, color, enabled) {
164                let g = paint::galley(ui, self.glyph, theme.font(Text::Body));
165                ui.painter().galley(art.center() - g.size() / 2.0, g, color);
166            }
167            let g = paint::galley(ui, self.label, large_font(&theme));
168            ui.painter().galley(egui::pos2(rect.center().x - g.size().x / 2.0, rect.bottom() - 6.0 - g.size().y), g, color);
169        }
170        response
171    }
172}
173
174/// The icon at the start of a [`ToolRow`].
175#[derive(Debug, Clone, Copy)]
176pub enum RowIcon<'a> {
177    /// A toolbar glyph's cropped artwork in a `GLYPH_SIZE` square, so every
178    /// row's label starts at one x whatever the icon.
179    Glyph(&'a str),
180    /// A workbench icon's padded artwork at its own proportions, `height` tall.
181    Workbench(&'a str, f32),
182    None,
183}
184
185impl RowIcon<'_> {
186    fn width(&self) -> f32 {
187        match self {
188            RowIcon::Glyph(g) => if crate::icons::artwork(g).is_some() { GLYPH_SIZE } else { 0.0 },
189            RowIcon::Workbench(g, h) => crate::icons::artwork(g).map_or(0.0, |i| h * i.aspect),
190            RowIcon::None => 0.0,
191        }
192    }
193}
194
195/// Edge of a row's trailing marker (the switcher's chevron and tick).
196pub const ROW_MARKER: f32 = 12.0;
197/// A row's inner padding either side, and the gap between its icon, label and
198/// marker: as tight as the egui button it replaced, so the 1400 pt automation
199/// window still holds every workbench's toolbar on one line.
200pub const ROW_PAD: f32 = space::SM;
201pub const ROW_GAP: f32 = space::XS;
202
203/// A menu row: an icon, the label and an optional trailing marker slot, on
204/// the selected fill when selected. `ToolRow::width` is what it measures to.
205#[must_use = "a tool row does nothing until it is shown"]
206pub struct ToolRow<'a> {
207    icon: RowIcon<'a>,
208    label: &'a str,
209    size: Vec2,
210    selected: bool,
211    marker: Option<&'a str>,
212    reserve_marker: bool,
213}
214
215impl<'a> ToolRow<'a> {
216    /// A row at least `size`: wider when its contents need it.
217    pub fn new(icon: RowIcon<'a>, label: &'a str, size: Vec2) -> Self {
218        Self { icon, label, size, selected: false, marker: None, reserve_marker: false }
219    }
220    pub fn selected(mut self, selected: bool) -> Self {
221        self.selected = selected;
222        self
223    }
224    /// Reserve the trailing marker slot, and paint `marker`'s artwork in it
225    /// when there is one.
226    pub fn marker(mut self, marker: Option<&'a str>) -> Self {
227        self.reserve_marker = true;
228        self.marker = marker;
229        self
230    }
231    /// The natural width of a row: padding, icon, gap, label, the marker
232    /// slot when reserved, padding.
233    pub fn width(ui: &egui::Ui, icon: RowIcon<'_>, label: &str, marker: bool) -> f32 {
234        let theme = Theme::of(ui);
235        let iw = icon.width();
236        let gap = if iw > 0.0 { ROW_GAP } else { 0.0 };
237        let label_w = paint::galley(ui, label, theme.font(Text::Body)).size().x;
238        let marker_w = if marker { ROW_GAP + ROW_MARKER } else { 0.0 };
239        2.0 * ROW_PAD + iw + gap + label_w + marker_w
240    }
241
242    /// Draw the row; returns its response and the marker slot's rect when reserved.
243    pub fn show(self, ui: &mut egui::Ui) -> (egui::Response, Option<Rect>) {
244        let theme = Theme::of(ui);
245        let natural = ToolRow::width(ui, self.icon, self.label, self.reserve_marker);
246        // At least the interact height, as the egui button rows this replaces
247        // were: 44 pt on a touch screen (viewport::touch raises it).
248        let height = self.size.y.max(ui.spacing().interact_size.y);
249        let (rect, response) = ui.allocate_exact_size(Vec2::new(self.size.x.max(natural), height), egui::Sense::click());
250        let enabled = ui.is_enabled();
251        response.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::SelectableLabel, enabled, self.selected, self.label));
252        let slot = self.reserve_marker.then(|| Rect::from_center_size(egui::pos2(rect.right() - ROW_PAD - ROW_MARKER / 2.0, rect.center().y), Vec2::splat(ROW_MARKER)));
253        if ui.is_rect_visible(rect) {
254            paint_state(ui, rect, &response, self.selected, false, &theme);
255            let color = ink(&theme, enabled);
256            let mut x = rect.left() + ROW_PAD;
257            let iw = self.icon.width();
258            match self.icon {
259                RowIcon::Glyph(g) => {
260                    paint_artwork(ui, g, Rect::from_min_size(egui::pos2(x, rect.center().y - GLYPH_SIZE / 2.0), Vec2::splat(GLYPH_SIZE)), color, enabled);
261                }
262                RowIcon::Workbench(g, h) => {
263                    if let Some(icon) = crate::icons::artwork(g) {
264                        egui_extras::install_image_loaders(ui.ctx());
265                        let tint = if icon.mono { color } else if enabled { Color32::WHITE } else { Color32::WHITE.gamma_multiply(0.4) };
266                        egui::Image::new(egui::ImageSource::Bytes { uri: icon.uri.into(), bytes: egui::load::Bytes::Static(icon.svg.as_bytes()) })
267                            .fit_to_exact_size(Vec2::new(iw, h))
268                            .tint(tint)
269                            .paint_at(ui, Rect::from_min_size(egui::pos2(x, rect.center().y - h / 2.0), Vec2::new(iw, h)));
270                    }
271                }
272                RowIcon::None => {}
273            }
274            if iw > 0.0 {
275                x += iw + ROW_GAP;
276            }
277            let g = paint::galley(ui, self.label, theme.font(Text::Body));
278            ui.painter().galley(egui::pos2(x, rect.center().y - g.size().y / 2.0), g, color);
279            if let (Some(marker), Some(slot)) = (self.marker, slot) {
280                let tint = if self.selected { theme.colors.accent_text } else { theme.colors.text_secondary };
281                paint_artwork(ui, marker, slot, tint, enabled);
282            }
283        }
284        (response, slot)
285    }
286}
287
288/// A ribbon tab's height on the desktop in every density (the compact
289/// control height).
290pub const TAB_HEIGHT: f32 = 24.0;
291
292/// A tab of a tab row that wraps with its neighbours (the ribbon's tabs share
293/// a wrapping row with the switcher and the File menu): its text, a hover
294/// overlay, and the active tab in `text.primary` over a 2 px accent underline.
295pub fn wrapping_tab(ui: &mut egui::Ui, label: &str, selected: bool) -> egui::Response {
296    let theme = Theme::of(ui);
297    let c = &theme.colors;
298    let g = paint::galley(ui, label, theme.font(Text::Body));
299    // The top bar never moves with the density setting (step 2 keeps it on
300    // the classic metrics): the compact control height, or the touch target.
301    let size = Vec2::new(g.size().x + 2.0 * space::MD, TAB_HEIGHT.max(ui.spacing().interact_size.y));
302    let (rect, response) = ui.allocate_exact_size(size, egui::Sense::click());
303    response.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::SelectableLabel, ui.is_enabled(), selected, label));
304    if ui.is_rect_visible(rect) {
305        if response.hovered() {
306            let overlay = if response.is_pointer_button_down_on() { c.pressed } else { c.hover };
307            ui.painter().rect_filled(rect.shrink2(Vec2::new(0.0, 1.0)), radius::BUTTON, overlay);
308        }
309        if response.has_focus() {
310            paint::focus_ring(ui, rect.shrink(1.0), radius::BUTTON, &theme);
311        }
312        let ink = if selected { c.text_primary } else { c.text_secondary };
313        ui.painter().galley(rect.center() - g.size() / 2.0, g, ink);
314        if selected {
315            let line = Rect::from_min_max(egui::pos2(rect.left() + space::SM, rect.bottom() - RING), egui::pos2(rect.right() - space::SM, rect.bottom()));
316            ui.painter().rect_filled(line, 1.0, c.accent_ring);
317        }
318    }
319    response.on_hover_cursor(egui::CursorIcon::PointingHand)
320}
321
322/// The frame of a ribbon group: a 1 px `border.subtle` outline, no fill.
323pub fn group_frame(ui: &egui::Ui) -> egui::Frame {
324    let theme = Theme::of(ui);
325    egui::Frame::new()
326        .inner_margin(egui::Margin::same(space::SM as i8))
327        .corner_radius(radius::BUTTON)
328        .stroke(Stroke::new(crate::theme::BORDER, theme.colors.border_subtle))
329}
330
331/// A thin `border.subtle` rule, for separating toolbar groups.
332pub fn rule(ui: &egui::Ui, x: f32, y: egui::Rangef) {
333    ui.painter().vline(x, y, Stroke::new(1.0, Theme::of(ui).colors.border_subtle));
334}