Skip to main content

brep_app/panels/
toolbar_button.rs

1//! The SINGLE source of truth for toolbar-button styling — shared by the main
2//! toolbar (`toolbar.rs`), the context bar (`context_bar.rs`), and the 2D sketcher
3//! toolbar (`sketch.rs`). Every toolbar button goes through here, so sizing/style
4//! changes land in ONE place. The human label is in the hover TOOLTIP, and every
5//! button is SQUARE (min-width == height).
6//!
7//! Artwork is ALWAYS the catalogued SVG ([`crate::icons`]) — colour icons paint
8//! their own colours, monochrome ones are tinted to the button's live text
9//! colour. There is no font path: this app ships no icon font, and a glyph
10//! character is only ever a KEY into the catalog.
11//!
12//! There used to be two other routes. Several private-use font glyphs painted at
13//! one origin in different colours was the only way to get multi-colour artwork
14//! out of a monochrome TrueType face; that went when each became a single colour
15//! SVG. Then monochrome glyphs were left to `BrepIcons.ttf` on the reasoning that
16//! a rasterised image "would buy nothing" — true in isolation, but it was the
17//! last thing keeping a whole font in the binary, so it went too.
18use eframe::egui;
19
20/// The catalogued artwork for a button glyph — what lets a plain
21/// `button`/`button_enabled`/`toggle` call site render its icon with no per-site
22/// plumbing, so the toolbar, the workbench registry and the sketch tool row all
23/// light up from the glyph alone. Shared with the tree and palette rows so all
24/// three agree on what is an icon.
25use crate::icons::artwork;
26
27/// Square edge length of a single-glyph toolbar button (min-width == height).
28pub const TOOLBAR_BTN: f32 = 28.0;
29
30/// Height of a Ribbon Large button; the row height every ribbon group reserves.
31pub const LARGE_BTN: f32 = 64.0;
32
33/// Shared flow layout for toolbar controls in every workbench. Individual
34/// controls wrap at the available width; nested non-wrapping groups would hide
35/// their buttons on narrow windows. The parent panel grows to contain each row.
36pub fn wrapped<R>(ui: &mut egui::Ui, contents: impl FnOnce(&mut egui::Ui) -> R) -> egui::InnerResponse<R> {
37    ui.horizontal_wrapped(contents)
38}
39
40/// Maximum painted edge length, independent of legacy SVG canvas padding.
41const GLYPH_SIZE: f32 = 17.0;
42
43fn square(ui: &egui::Ui) -> egui::Vec2 {
44    crate::viewport::touch::target_size(ui.ctx(), egui::vec2(TOOLBAR_BTN, TOOLBAR_BTN))
45}
46
47/// The button for one glyph: its catalogued artwork if it has any, else the
48/// characters themselves as text.
49///
50/// Monochrome artwork is white in the catalog, so `image_tint_follows_text_color`
51/// multiplies it by the button's LIVE text colour — which is what keeps hover,
52/// pressed and disabled states looking exactly as they did when the font drew
53/// the glyph. Colour artwork must never be tinted, so it opts out.
54pub(crate) fn glyph_button<'a>(ui: &egui::Ui, glyph: &'a str) -> egui::Button<'a> {
55    match artwork(glyph) {
56        Some(icon) => {
57            // Idempotent, and the only place a toolbar button needs it: a button
58            // can be the first thing on screen to draw an SVG.
59            egui_extras::install_image_loaders(ui.ctx());
60            let image = egui::Image::new(egui::ImageSource::Bytes {
61                uri: format!("bytes://brep-toolbar/{}.svg", icon.name).into(),
62                bytes: egui::load::Bytes::Static(icon.artwork_svg.as_bytes()),
63            })
64            .fit_to_exact_size(egui::Vec2::splat(GLYPH_SIZE));
65            egui::Button::new(image)
66                .image_tint_follows_text_color(icon.mono)
67                .min_size(square(ui))
68        }
69        None => egui::Button::new(glyph).min_size(square(ui)),
70    }
71}
72
73/// A plain action toolbar button: `glyph` shown, `tooltip` on hover. Square.
74pub fn button(ui: &mut egui::Ui, glyph: &str, tooltip: &str) -> egui::Response {
75    let button = glyph_button(ui, glyph);
76    ui.add(button).on_hover_text(tooltip)
77}
78
79/// Side of a Large button's artwork square.
80const LARGE_ART: f32 = 28.0;
81
82/// Ribbon's Large presentation: catalogue artwork above the canonical label.
83pub fn large_button(ui: &mut egui::Ui, glyph: &str, label: &str, selected: bool, toggle: bool, enabled: bool) -> egui::Response {
84    let font = egui::TextStyle::Button.resolve(ui.style());
85    let text =
86        ui.fonts_mut(|f| f.layout_no_wrap(label.to_owned(), font.clone(), egui::Color32::WHITE));
87    let width = text.size().x.max(32.0) + 2.0 * ui.spacing().button_padding.x;
88    let button = egui::Button::new("").min_size(egui::vec2(width, LARGE_BTN));
89    let response = ui.add_enabled(enabled, if toggle { button.selected(selected) } else { button });
90    let color = ui
91        .style()
92        .interact_selectable(&response, selected)
93        .text_color();
94    let image_center = egui::pos2(response.rect.center().x, response.rect.top() + 22.0);
95    if let Some(icon) = artwork(glyph) {
96        let image_rect = egui::Rect::from_center_size(
97            image_center,
98            egui::Vec2::splat(LARGE_ART),
99        );
100        egui_extras::install_image_loaders(ui.ctx());
101        let tint = if icon.mono {
102            color
103        } else if enabled && ui.is_enabled() {
104            egui::Color32::WHITE
105        } else {
106            egui::Color32::WHITE.gamma_multiply(0.4)
107        };
108        egui::Image::new(egui::ImageSource::Bytes {
109            uri: format!("bytes://brep-toolbar/{}.svg", icon.name).into(),
110            bytes: egui::load::Bytes::Static(icon.artwork_svg.as_bytes()),
111        })
112        .fit_to_exact_size(image_rect.size())
113        .tint(tint)
114        .paint_at(ui, image_rect);
115    } else {
116        ui.painter().text(
117            image_center,
118            egui::Align2::CENTER_CENTER,
119            glyph,
120            font.clone(),
121            color,
122        );
123    }
124    ui.painter().text(
125        egui::pos2(response.rect.center().x, response.rect.bottom() - 6.0),
126        egui::Align2::CENTER_BOTTOM,
127        label,
128        font,
129        color,
130    );
131    response
132}
133/// A toolbar button enabled only when `enabled` (undo/redo, selection actions).
134pub fn button_enabled(
135    ui: &mut egui::Ui,
136    enabled: bool,
137    glyph: &str,
138    tooltip: &str,
139) -> egui::Response {
140    let button = glyph_button(ui, glyph);
141    ui.add_enabled(enabled, button).on_hover_text(tooltip)
142}
143
144/// A toolbar TOGGLE button (draw-tool selection, wireframe): pressed when `selected`.
145pub fn toggle(ui: &mut egui::Ui, selected: bool, glyph: &str, tooltip: &str) -> egui::Response {
146    let button = glyph_button(ui, glyph).selected(selected);
147    ui.add(button).on_hover_text(tooltip)
148}
149
150/// Disable a toggle as one atomic widget, preserving the wrapping row's layout.
151pub fn toggle_enabled(ui: &mut egui::Ui, enabled: bool, selected: bool, glyph: &str, tooltip: &str) -> egui::Response {
152    ui.add_enabled(enabled, glyph_button(ui, glyph).selected(selected)).on_hover_text(tooltip)
153}
154
155/// The outcome of a toolbar [`select`] combo for one frame.
156pub struct SelectResult {
157    /// The option `id` the user picked THIS frame — `Some` only on a real change
158    /// (differs from `current`); `None` otherwise.
159    pub changed: Option<String>,
160    /// The combo HEADER's screen rect (the verifier clicks this to open the menu).
161    pub header_rect: egui::Rect,
162    /// `(id, rect)` per menu item while the menu is OPEN (empty when closed) — the
163    /// verifier clicks an item rect to drive a SELECTION.
164    pub item_rects: Vec<(String, egui::Rect)>,
165}
166
167/// Painted edge of the workbench icon on one switcher row.
168const SELECT_ICON: f32 = 18.0;
169
170/// Painted edge of a switcher row's trailing marker. Both markers are square
171/// artwork drawn at this size, so the header and every menu item reserve the
172/// SAME right-hand slot and their labels sit at the same x.
173const SELECT_MARKER: f32 = 12.0;
174
175/// The switcher header's "there is a menu here" chevron (U+25BE) and the tick
176/// beside the ACTIVE workbench (U+2713). Both are catalogued artwork, like every
177/// other picture in this module: nothing here renders a character as text, so no
178/// font has to have it. They used to be `right_text("▾")` / `right_text("✓")`,
179/// which drew correctly only where the OS monospace happened to carry them —
180/// on wasm, where `fonts::install` falls back to egui's four bundled faces,
181/// NEITHER codepoint is covered (`Ubuntu-Light`/`NotoEmoji`/`emoji-icon-font`
182/// have no U+25BE, and nothing bundled has U+2713 at all), so both rendered as
183/// a tofu box in the browser build.
184const SELECT_CHEVRON: &str = "\u{25BE}";
185const SELECT_TICK: &str = "\u{2713}";
186
187/// One switcher row: the workbench's own icon, its label, and a right-aligned
188/// SLOT for the trailing marker.
189///
190/// The slot is an empty custom atom, and the marker is painted into the rect it
191/// reports, because [`egui::Button::image_tint_follows_text_color`] is a
192/// per-BUTTON switch: the workbench icons carry their own colours and must not
193/// be tinted, so a monochrome marker sharing the button could not be tinted
194/// either. Painting it separately also gets it the row's LIVE text colour —
195/// including the selected row's, which is the one place a tick ever appears.
196fn switcher_row(label: &str, glyph: &str, marker_slot: egui::Id) -> egui::Button<'static> {
197    let icon = artwork(glyph).expect("workbench icon must be catalogued");
198    let image = egui::Image::new(egui::ImageSource::Bytes {
199        uri: icon.uri.into(),
200        bytes: egui::load::Bytes::Static(icon.svg.as_bytes()),
201    })
202    // At the canvas's own proportions, so no workbench icon can be stretched.
203    .fit_to_exact_size(egui::vec2(SELECT_ICON * icon.aspect, SELECT_ICON));
204    egui::Button::new((
205        image,
206        label.to_owned(),
207        egui::Atom::grow(),
208        egui::Atom::custom(marker_slot, egui::Vec2::splat(SELECT_MARKER)),
209    ))
210    .image_tint_follows_text_color(icon.mono)
211    .wrap_mode(egui::TextWrapMode::Extend)
212}
213
214/// Draw one switcher row `width` wide and paint `marker` (if any) into its slot.
215fn switcher_row_ui(
216    ui: &mut egui::Ui,
217    label: &str,
218    glyph: &str,
219    width: f32,
220    selected: bool,
221    marker: Option<&str>,
222) -> egui::Response {
223    let slot = ui.id().with(("switcher-marker", label));
224    let out = switcher_row(label, glyph, slot)
225        .selected(selected)
226        .min_size(egui::vec2(width, TOOLBAR_BTN))
227        .atom_ui(ui);
228    if let (Some(marker), Some(rect)) = (marker, out.rect(slot)) {
229        let icon = artwork(marker).expect("switcher marker must be catalogued");
230        let tint = ui.style().interact_selectable(&out.response, selected).text_color();
231        egui::Image::new(egui::ImageSource::Bytes {
232            uri: icon.uri.into(),
233            bytes: egui::load::Bytes::Static(icon.svg.as_bytes()),
234        })
235        .tint(tint)
236        .paint_at(ui, rect);
237    }
238    out.response
239}
240
241/// The width the switcher is drawn at: the NATURAL width of its widest option,
242/// so the longest label fits exactly and nothing carries dead space.
243///
244/// egui measures it, in a throwaway invisible sizing-pass `Ui`, rather than this
245/// module re-deriving egui's button padding and atom-gap arithmetic — a copy of
246/// that arithmetic would go quietly loose or tight the next time either changes.
247/// Every row is measured with its marker slot present, so the header's chevron
248/// and an item's tick are both accounted for whichever row is widest.
249fn switcher_width(ui: &egui::Ui, options: &[(&str, &str, &str)]) -> f32 {
250    switcher_width_salted(ui, "options", options)
251}
252
253fn switcher_width_salted(ui: &egui::Ui, salt: &str, options: &[(&str, &str, &str)]) -> f32 {
254    let mut probe = egui::Ui::new(
255        ui.ctx().clone(),
256        ui.id().with(("switcher-measure", salt)),
257        egui::UiBuilder::new()
258            .sizing_pass()
259            .invisible()
260            .style(ui.style().clone())
261            .layer_id(ui.layer_id())
262            // Far OFF SCREEN, deliberately. The probe still registers its rows
263            // as widgets in this layer, and at the origin those six rects would
264            // land on the toolbar, the workbench strip and the top of the dock —
265            // over widgets drawn BEFORE the switcher, which the switcher's own
266            // click cannot mask. Layout is arithmetic and `fit_to_exact_size` is
267            // deterministic, so the measurement is the same wherever it happens.
268            .max_rect(egui::Rect::from_min_size(
269                egui::pos2(1.0e5, 1.0e5),
270                egui::Vec2::splat(1.0e4),
271            )),
272    );
273    options.iter().fold(0.0_f32, |widest, (label, _, glyph)| {
274        let slot = probe.id().with(("switcher-marker", *label));
275        let row = switcher_row(label, glyph, slot).min_size(egui::vec2(0.0, TOOLBAR_BTN));
276        widest.max(row.atom_ui(&mut probe).response.rect.width())
277    })
278}
279
280/// An icon-and-label toolbar dropdown, as tall as the surrounding buttons and
281/// sized to its current label; the menu fits its widest option.
282/// Options are `(label, id, glyph)` entries from the workbench registry.
283pub fn select(
284    ui: &mut egui::Ui,
285    id_source: &str,
286    current: &str,
287    options: &[(&str, &str, &str)],
288) -> SelectResult {
289    egui_extras::install_image_loaders(ui.ctx());
290    let width = switcher_width(ui, options);
291    let current_option = options.iter().find(|(_, id, _)| *id == current)
292        .expect("selected workbench must be registered");
293    let header_width = switcher_width_salted(ui, "header", &[*current_option]);
294    let mut changed = None;
295    let mut item_rects = Vec::new();
296    let header = ui
297        .push_id(("toolbar-select", id_source), |ui| {
298            let (label, _, glyph) = options
299                .iter()
300                .find(|(_, id, _)| *id == current)
301                .expect("selected workbench must be registered");
302            let phone = crate::viewport::touch::enabled(ui.ctx())
303                && ui.ctx().content_rect().width() < crate::viewport::touch::NARROW_WIDTH;
304            let response = if phone {
305                button(ui, glyph, &format!("{label} — Switch workbench"))
306            } else {
307                switcher_row_ui(ui, label, glyph, header_width, false, Some(SELECT_CHEVRON))
308                    .on_hover_text("Switch workbench")
309            };
310            egui::Popup::menu(&response).width(width).show(|ui| {
311                let height = (ui.ctx().content_rect().height() - 80.0).max(80.0);
312                ui.set_max_height(height);
313                egui::ScrollArea::vertical()
314                    .max_height(height)
315                    .show(ui, |ui| {
316                        for (label, id, glyph) in options {
317                            let selected = *id == current;
318                            let marker = selected.then_some(SELECT_TICK);
319                            let resp = switcher_row_ui(ui, label, glyph, width, selected, marker);
320                            item_rects.push(((*id).to_string(), resp.rect));
321                            if resp.clicked() {
322                                if !selected {
323                                    changed = Some((*id).to_string());
324                                }
325                                ui.close();
326                            }
327                        }
328                    });
329            });
330            response
331        })
332        .inner;
333    SelectResult {
334        changed,
335        header_rect: header.rect,
336        item_rects,
337    }
338}
339
340/// One MENU row: a toolbar button's own artwork and its human label, as a
341/// selectable row inside a popup. This is what a toolbar menu entry
342/// looks like — the same glyph it draws in the row, plus the label that is only
343/// a tooltip while it is on the strip.
344///
345/// `selected` is the entry's live PRESSED state, so menus and toolbar buttons
346/// communicate their current state with the same selected fill.
347///
348/// No marker slot, unlike [`switcher_row`]: a menu of toolbar buttons has no
349/// "which one is active" tick to reserve room for — several can be pressed at
350/// once (the three display toggles), and the pressed FILL says so.
351pub(crate) fn menu_row_button(glyph: &str, label: &str) -> egui::Button<'static> {
352    let Some(icon) = artwork(glyph) else { return egui::Button::new(format!("{glyph} {label}")).wrap_mode(egui::TextWrapMode::Extend); };
353    // The CROPPED artwork at the strip's own painted size and URI, exactly as
354    // [`glyph_button`] draws it — not the switcher's padded `svg`, which paints
355    // the same glyph visibly smaller. Menu and toolbar artwork share a size.
356    let image = egui::Image::new(egui::ImageSource::Bytes {
357        uri: format!("bytes://brep-toolbar/{}.svg", icon.name).into(),
358        bytes: egui::load::Bytes::Static(icon.artwork_svg.as_bytes()),
359    })
360    .fit_to_exact_size(egui::Vec2::splat(GLYPH_SIZE));
361    // Every icon's artwork is square, so every row's icon takes the same slot
362    // and the labels of a menu start at one x (lane U audit item 6).
363    egui::Button::new((image, label.to_owned()))
364        .image_tint_follows_text_color(icon.mono)
365        .wrap_mode(egui::TextWrapMode::Extend)
366}
367
368/// Draw one overflow-menu row `width` wide. Returns its response, so the caller
369/// publishes the hit-rect and reads the click.
370pub fn menu_row(
371    ui: &mut egui::Ui,
372    glyph: &str,
373    label: &str,
374    selected: bool,
375    width: f32,
376) -> egui::Response {
377    ui.add(
378        menu_row_button(glyph, label)
379            .selected(selected)
380            .min_size(egui::vec2(width, TOOLBAR_BTN)),
381    )
382}
383
384/// The width an overflow menu of `rows` — `(glyph, label)` pairs — is drawn at:
385/// the NATURAL width of its widest row, measured by egui in a throwaway
386/// invisible sizing pass, exactly the way `switcher_width` measures the
387/// switcher. Re-deriving egui's button padding and atom-gap arithmetic here
388/// would go quietly loose or tight the next time either changes.
389pub fn menu_width(ui: &egui::Ui, rows: &[(&str, &str)]) -> f32 {
390    menu_width_salted(ui, "menu-measure", rows)
391}
392
393/// [`menu_width`] under its own probe id, for a menu that measures two
394/// column's rows in one frame (the File menu's workbench and document
395/// columns): two probes under one id would register the same widget ids
396/// at different rects.
397pub fn menu_width_salted(ui: &egui::Ui, salt: &str, rows: &[(&str, &str)]) -> f32 {
398    let mut probe = egui::Ui::new(
399        ui.ctx().clone(),
400        ui.id().with(salt),
401        egui::UiBuilder::new()
402            .sizing_pass()
403            .invisible()
404            .style(ui.style().clone())
405            .layer_id(ui.layer_id())
406            // Far OFF SCREEN, for the reason `switcher_width` explains: the
407            // probe still registers its rows as widgets in this layer, and at
408            // the origin they would land on the toolbar it is measuring FOR.
409            .max_rect(egui::Rect::from_min_size(
410                egui::pos2(1.0e5, 1.0e5),
411                egui::Vec2::splat(1.0e4),
412            )),
413    );
414    rows.iter().fold(0.0_f32, |widest, (glyph, label)| {
415        let row = menu_row_button(glyph, label).min_size(egui::vec2(0.0, TOOLBAR_BTN));
416        widest.max(probe.add(row).rect.width())
417    })
418}
419