BREP_app 0.36.0

The next.BREP.io CAD application on the Rust B-rep kernel: an eframe (egui + wgpu) host that draws the brep-render 3D engine into an egui frame, native + wasm from one codebase.
Documentation
//! The SINGLE source of truth for toolbar-button styling — shared by the main
//! toolbar (`toolbar.rs`), the context bar (`context_bar.rs`), and the 2D sketcher
//! toolbar (`sketch.rs`). Every toolbar button goes through here, so sizing/style
//! changes land in ONE place. The human label is in the hover TOOLTIP, and every
//! button is SQUARE (min-width == height).
//!
//! Artwork is ALWAYS the catalogued SVG ([`crate::icons`]) — colour icons paint
//! their own colours, monochrome ones are tinted to the button's live text
//! colour. There is no font path: this app ships no icon font, and a glyph
//! character is only ever a KEY into the catalog.
//!
//! There used to be two other routes. Several private-use font glyphs painted at
//! one origin in different colours was the only way to get multi-colour artwork
//! out of a monochrome TrueType face; that went when each became a single colour
//! SVG. Then monochrome glyphs were left to `BrepIcons.ttf` on the reasoning that
//! a rasterised image "would buy nothing" — true in isolation, but it was the
//! last thing keeping a whole font in the binary, so it went too.
use crate::ui_kit::chrome_toolbar::{LargeButton, RowIcon, ToolButton, ToolRow};
use eframe::egui;

/// The catalogued artwork for a button glyph — what lets a plain
/// `button`/`button_enabled`/`toggle` call site render its icon with no per-site
/// plumbing, so the toolbar, the workbench registry and the sketch tool row all
/// light up from the glyph alone. Shared with the tree and palette rows so all
/// three agree on what is an icon.
use crate::icons::artwork;

/// Square edge length of a single-glyph toolbar button (min-width == height).
pub const TOOLBAR_BTN: f32 = 28.0;

/// Height of a Ribbon Large button; the row height every ribbon group reserves.
pub const LARGE_BTN: f32 = 64.0;

/// Shared flow layout for toolbar controls in every workbench. Individual
/// controls wrap at the available width; nested non-wrapping groups would hide
/// their buttons on narrow windows. The parent panel grows to contain each row.
pub fn wrapped<R>(ui: &mut egui::Ui, contents: impl FnOnce(&mut egui::Ui) -> R) -> egui::InnerResponse<R> {
    ui.horizontal_wrapped(contents)
}

fn square(ui: &egui::Ui) -> egui::Vec2 {
    crate::viewport::touch::target_size(ui.ctx(), egui::vec2(TOOLBAR_BTN, TOOLBAR_BTN))
}

/// The button for one glyph: its catalogued artwork if it has any, else the
/// characters themselves as text, on a touch-sized square.
///
/// Monochrome artwork is drawn in the button's live text colour (primary, or
/// disabled), so hover, pressed and disabled states read as they did; colour
/// artwork keeps its own colours and is only dimmed when disabled.
pub(crate) fn glyph_button<'a>(ui: &egui::Ui, glyph: &'a str) -> ToolButton<'a> {
    ToolButton::new(glyph, square(ui))
}

/// A plain action toolbar button: `glyph` shown, `tooltip` on hover. Square.
pub fn button(ui: &mut egui::Ui, glyph: &str, tooltip: &str) -> egui::Response {
    let button = glyph_button(ui, glyph);
    ui.add(button).on_hover_text(tooltip)
}

/// Ribbon's Large presentation: catalogue artwork above the canonical label.
pub fn large_button(ui: &mut egui::Ui, glyph: &str, label: &str, selected: bool, toggle: bool, enabled: bool) -> egui::Response {
    ui.add_enabled(enabled, LargeButton::new(glyph, label, LARGE_BTN).selected(toggle && selected))
}

/// A toolbar button enabled only when `enabled` (undo/redo, selection actions).
pub fn button_enabled(
    ui: &mut egui::Ui,
    enabled: bool,
    glyph: &str,
    tooltip: &str,
) -> egui::Response {
    let button = glyph_button(ui, glyph);
    ui.add_enabled(enabled, button).on_hover_text(tooltip)
}

/// A toolbar TOGGLE button (draw-tool selection, wireframe): pressed when `selected`.
pub fn toggle(ui: &mut egui::Ui, selected: bool, glyph: &str, tooltip: &str) -> egui::Response {
    let button = glyph_button(ui, glyph).selected(selected);
    ui.add(button).on_hover_text(tooltip)
}

/// Disable a toggle as one atomic widget, preserving the wrapping row's layout.
pub fn toggle_enabled(ui: &mut egui::Ui, enabled: bool, selected: bool, glyph: &str, tooltip: &str) -> egui::Response {
    ui.add_enabled(enabled, glyph_button(ui, glyph).selected(selected)).on_hover_text(tooltip)
}

/// The outcome of a toolbar [`select`] combo for one frame.
pub struct SelectResult {
    /// The option `id` the user picked THIS frame — `Some` only on a real change
    /// (differs from `current`); `None` otherwise.
    pub changed: Option<String>,
    /// The combo HEADER's screen rect (the verifier clicks this to open the menu).
    pub header_rect: egui::Rect,
    /// `(id, rect)` per menu item while the menu is OPEN (empty when closed) — the
    /// verifier clicks an item rect to drive a SELECTION.
    pub item_rects: Vec<(String, egui::Rect)>,
}

/// Painted edge of the workbench icon on one switcher row.
const SELECT_ICON: f32 = 18.0;

/// The switcher header's "there is a menu here" chevron (U+25BE) and the tick
/// beside the ACTIVE workbench (U+2713). Both are catalogued artwork, like every
/// other picture in this module: nothing here renders a character as text, so no
/// font has to have it. They used to be `right_text("▾")` / `right_text("✓")`,
/// which drew correctly only where the OS monospace happened to carry them —
/// on wasm, where `fonts::install` falls back to egui's four bundled faces,
/// NEITHER codepoint is covered (`Ubuntu-Light`/`NotoEmoji`/`emoji-icon-font`
/// have no U+25BE, and nothing bundled has U+2713 at all), so both rendered as
/// a tofu box in the browser build.
const SELECT_CHEVRON: &str = "\u{25BE}";
const SELECT_TICK: &str = "\u{2713}";

/// One switcher row: the workbench's own icon at its canvas proportions, its
/// label, and a right-aligned marker SLOT (the chevron on the closed header,
/// the tick on the active item). Every row reserves the slot, so the header and
/// every item put their labels at the same x and their markers in one column.
fn switcher_row<'a>(label: &'a str, glyph: &'a str, width: f32) -> ToolRow<'a> {
    assert!(artwork(glyph).is_some(), "workbench icon must be catalogued");
    ToolRow::new(RowIcon::Workbench(glyph, SELECT_ICON), label, egui::vec2(width, TOOLBAR_BTN))
}

/// Draw one switcher row `width` wide with `marker` (if any) in its slot.
fn switcher_row_ui(
    ui: &mut egui::Ui,
    label: &str,
    glyph: &str,
    width: f32,
    selected: bool,
    marker: Option<&str>,
) -> egui::Response {
    if let Some(marker) = marker {
        assert!(artwork(marker).is_some(), "switcher marker must be catalogued");
    }
    switcher_row(label, glyph, width).selected(selected).marker(marker).show(ui).0
}

/// The width the switcher is drawn at: the NATURAL width of its widest option,
/// so the longest label fits exactly and nothing carries dead space. Every row
/// is measured with its marker slot, so the header's chevron and an item's
/// tick are both accounted for whichever row is widest.
fn switcher_width(ui: &egui::Ui, options: &[(&str, &str, &str)]) -> f32 {
    options
        .iter()
        .fold(0.0_f32, |widest, (label, _, glyph)| widest.max(ToolRow::width(ui, RowIcon::Workbench(glyph, SELECT_ICON), label, true)))
}

/// An icon-and-label toolbar dropdown, as tall as the surrounding buttons and
/// sized to its current label; the menu fits its widest option.
/// Options are `(label, id, glyph)` entries from the workbench registry.
pub fn select(
    ui: &mut egui::Ui,
    id_source: &str,
    current: &str,
    options: &[(&str, &str, &str)],
) -> SelectResult {
    egui_extras::install_image_loaders(ui.ctx());
    let width = switcher_width(ui, options);
    let current_option = options.iter().find(|(_, id, _)| *id == current)
        .expect("selected workbench must be registered");
    let header_width = switcher_width(ui, &[*current_option]);
    let mut changed = None;
    let mut item_rects = Vec::new();
    let header = ui
        .push_id(("toolbar-select", id_source), |ui| {
            let (label, _, glyph) = current_option;
            let phone = crate::viewport::touch::enabled(ui.ctx())
                && ui.ctx().content_rect().width() < crate::viewport::touch::NARROW_WIDTH;
            let response = if phone {
                button(ui, glyph, &format!("{label} — Switch workbench"))
            } else {
                switcher_row_ui(ui, label, glyph, header_width, false, Some(SELECT_CHEVRON))
                    .on_hover_text("Switch workbench")
            };
            egui::Popup::menu(&response).width(width).show(|ui| {
                let height = (ui.ctx().content_rect().height() - 80.0).max(80.0);
                ui.set_max_height(height);
                egui::ScrollArea::vertical()
                    .max_height(height)
                    .show(ui, |ui| {
                        for (label, id, glyph) in options {
                            let selected = *id == current;
                            let marker = selected.then_some(SELECT_TICK);
                            let resp = switcher_row_ui(ui, label, glyph, width, selected, marker);
                            item_rects.push(((*id).to_string(), resp.rect));
                            if resp.clicked() {
                                if !selected {
                                    changed = Some((*id).to_string());
                                }
                                ui.close();
                            }
                        }
                    });
            });
            response
        })
        .inner;
    SelectResult {
        changed,
        header_rect: header.rect,
        item_rects,
    }
}

/// One MENU row: a toolbar button's own artwork and its human label, as a
/// selectable row inside a popup. This is what a toolbar menu entry
/// looks like — the same glyph it draws in the row, plus the label that is only
/// a tooltip while it is on the strip.
///
/// `selected` is the entry's live PRESSED state, so menus and toolbar buttons
/// communicate their current state with the same selected fill.
///
/// No marker slot, unlike [`switcher_row`]: a menu of toolbar buttons has no
/// "which one is active" tick to reserve room for — several can be pressed at
/// once (the three display toggles), and the pressed FILL says so. Every
/// icon's artwork takes the same square slot, so the labels of a menu start at
/// one x (lane U audit item 6); a glyph with no artwork is drawn as text
/// before the label, as it always was.
pub(crate) fn menu_row_widget<'a>(glyph: &'a str, label: &'a str, width: f32, selected: bool) -> MenuRow<'a> {
    MenuRow { glyph, label, width, selected }
}

/// A [`menu_row_widget`], an `egui::Widget` so it can be added disabled.
pub(crate) struct MenuRow<'a> {
    glyph: &'a str,
    label: &'a str,
    width: f32,
    selected: bool,
}

impl egui::Widget for MenuRow<'_> {
    fn ui(self, ui: &mut egui::Ui) -> egui::Response {
        let size = egui::vec2(self.width, TOOLBAR_BTN);
        if artwork(self.glyph).is_some() {
            ToolRow::new(RowIcon::Glyph(self.glyph), self.label, size).selected(self.selected).show(ui).0
        } else {
            let text = format!("{} {}", self.glyph, self.label);
            ToolRow::new(RowIcon::None, &text, size).selected(self.selected).show(ui).0
        }
    }
}

/// Draw one overflow-menu row `width` wide. Returns its response, so the caller
/// publishes the hit-rect and reads the click.
pub fn menu_row(
    ui: &mut egui::Ui,
    glyph: &str,
    label: &str,
    selected: bool,
    width: f32,
) -> egui::Response {
    ui.add(menu_row_widget(glyph, label, width, selected))
}

/// The natural width of one menu row.
fn menu_row_width(ui: &egui::Ui, glyph: &str, label: &str) -> f32 {
    if artwork(glyph).is_some() {
        ToolRow::width(ui, RowIcon::Glyph(glyph), label, false)
    } else {
        ToolRow::width(ui, RowIcon::None, &format!("{glyph} {label}"), false)
    }
}

/// The width an overflow menu of `rows` — `(glyph, label)` pairs — is drawn at:
/// the NATURAL width of its widest row, by the rows' own measure.
pub fn menu_width(ui: &egui::Ui, rows: &[(&str, &str)]) -> f32 {
    menu_width_salted(ui, "menu-measure", rows)
}

/// [`menu_width`] for a menu that measures two columns' rows in one frame
/// (the File menu's workbench and document columns). The measure registers
/// no widget any more, so the salt is kept only for its callers.
pub fn menu_width_salted(ui: &egui::Ui, _salt: &str, rows: &[(&str, &str)]) -> f32 {
    rows.iter().fold(0.0_f32, |widest, (glyph, label)| widest.max(menu_row_width(ui, glyph, label)))
}