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 toolbar's own controls on the refreshed look (ui-refresh-spec section 5,
//! "Icon buttons"), for `panels/toolbar_button.rs`, the one place every
//! toolbar, ribbon, context and sketch button is drawn: a square tool button,
//! the ribbon's Large button (artwork over a label) and an icon row for menus
//! and the workbench switcher. Owned by the UI-CHROME lane.
//!
//! Unlike [`super::IconButton`], these keep the toolbar's own metrics (the
//! caller passes the square's size, which already includes the touch target)
//! and attach no tooltip: the caller does, with the command's detail and its
//! disabled reason. They are `egui::Widget`s that read `ui.is_enabled()`, so
//! `ui.add_enabled(false, ...)` disables them exactly as it did the
//! `egui::Button` each replaces, `on_disabled_hover_text` included.
use super::paint;
use crate::theme::{radius, space, Text, Theme, RING};
use eframe::egui::{self, Color32, Rect, Stroke, Vec2};

/// Painted edge of a tool button's artwork (and a menu row's icon slot).
pub const GLYPH_SIZE: f32 = 17.0;
/// Side of a Large button's artwork square.
pub const LARGE_ART: f32 = 28.0;

/// The text colour of a control in its state: primary, or disabled.
fn ink(theme: &Theme, enabled: bool) -> Color32 {
    if enabled { theme.colors.text_primary } else { theme.colors.text_disabled }
}

/// Paint `glyph`'s catalogued cropped artwork in `rect`: monochrome artwork
/// in `color`, colour artwork in its own colours (dimmed when disabled).
/// Returns whether the glyph is catalogued.
fn paint_artwork(ui: &egui::Ui, glyph: &str, rect: Rect, color: Color32, enabled: bool) -> bool {
    let Some(icon) = crate::icons::artwork(glyph) else { return false };
    egui_extras::install_image_loaders(ui.ctx());
    let tint = if icon.mono {
        color
    } else if enabled {
        Color32::WHITE
    } else {
        Color32::WHITE.gamma_multiply(0.4)
    };
    egui::Image::new(egui::ImageSource::Bytes {
        uri: format!("bytes://brep-toolbar/{}.svg", icon.name).into(),
        bytes: egui::load::Bytes::Static(icon.artwork_svg.as_bytes()),
    })
    .fit_to_exact_size(rect.size())
    .tint(tint)
    .paint_at(ui, rect);
    true
}

/// The hover / pressed / selected background and the focus ring every
/// toolbar control shares. `bar` draws the 2 px accent bar under a selected
/// control (the ribbon and toolbars); rows leave it off.
fn paint_state(ui: &egui::Ui, rect: Rect, response: &egui::Response, selected: bool, bar: bool, theme: &Theme) {
    let c = &theme.colors;
    let enabled = ui.is_enabled();
    let hover = ui.ctx().animate_bool_with_time(response.id.with("hover"), enabled && response.hovered(), theme.motion_fast());
    let on = ui.ctx().animate_bool_with_time(response.id.with("on"), selected, theme.motion_base());
    let body = rect.shrink(1.0);
    if on > 0.0 {
        ui.painter().rect_filled(body, radius::BUTTON, paint::lerp_color(Color32::TRANSPARENT, c.accent_muted, on));
    }
    let overlay = if enabled && response.is_pointer_button_down_on() { c.pressed } else { paint::lerp_color(Color32::TRANSPARENT, c.hover, hover) };
    ui.painter().rect_filled(body, radius::BUTTON, overlay);
    if bar && on > 0.0 {
        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));
        ui.painter().rect_filled(strip, 1.0, paint::lerp_color(Color32::TRANSPARENT, c.accent_ring, on));
    }
    if response.has_focus() {
        paint::focus_ring(ui, body, radius::BUTTON, theme);
    }
}

/// A square toolbar button: `glyph`'s artwork centred, or the characters
/// themselves when it has none.
#[must_use = "a tool button does nothing until it is added to a Ui"]
pub struct ToolButton<'a> {
    glyph: &'a str,
    size: Vec2,
    selected: bool,
}

impl<'a> ToolButton<'a> {
    pub fn new(glyph: &'a str, size: Vec2) -> Self {
        Self { glyph, size, selected: false }
    }
    /// A toggle that is on, or the tool in use.
    pub fn selected(mut self, selected: bool) -> Self {
        self.selected = selected;
        self
    }
}

impl egui::Widget for ToolButton<'_> {
    fn ui(self, ui: &mut egui::Ui) -> egui::Response {
        let theme = Theme::of(ui);
        // A glyph with no catalogued artwork is drawn as its text ("Faces", "Planes"):
        // widen the button to fit it, as the egui button it replaced did, or a row of
        // text toggles paints each label over its neighbours.
        let mut size = self.size;
        if crate::icons::artwork(self.glyph).is_none() {
            let text_width = paint::galley(ui, self.glyph, theme.font(Text::Body)).size().x;
            size.x = size.x.max(text_width + 2.0 * space::MD);
        }
        let (rect, response) = ui.allocate_exact_size(size, egui::Sense::click());
        let enabled = ui.is_enabled();
        response.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::Button, enabled, self.selected, self.glyph));
        if ui.is_rect_visible(rect) {
            paint_state(ui, rect, &response, self.selected, true, &theme);
            let nudge = Vec2::new(0.0, if enabled && response.is_pointer_button_down_on() { 1.0 } else { 0.0 });
            let slot = Rect::from_center_size(rect.center() + nudge, Vec2::splat(GLYPH_SIZE));
            let color = ink(&theme, enabled);
            if !paint_artwork(ui, self.glyph, slot, color, enabled) {
                let g = paint::galley(ui, self.glyph, theme.font(Text::Body));
                ui.painter().galley(rect.center() + nudge - g.size() / 2.0, g, color);
            }
        }
        response
    }
}

/// The ribbon's Large button: artwork over its label, [`crate::panels::toolbar_button::LARGE_BTN`] tall.
#[must_use = "a large button does nothing until it is added to a Ui"]
pub struct LargeButton<'a> {
    glyph: &'a str,
    label: &'a str,
    height: f32,
    selected: bool,
}

impl<'a> LargeButton<'a> {
    pub fn new(glyph: &'a str, label: &'a str, height: f32) -> Self {
        Self { glyph, label, height, selected: false }
    }
    pub fn selected(mut self, selected: bool) -> Self {
        self.selected = selected;
        self
    }
    /// The width the button takes: its label (at least 32 pt) and the
    /// control padding either side.
    pub fn width(ui: &egui::Ui, label: &str) -> f32 {
        let theme = Theme::of(ui);
        paint::galley(ui, label, large_font(&theme)).size().x.max(32.0) + 2.0 * space::XS
    }
}

/// A Large button's label font: the caption size, so a 1600 pt Modeling
/// ribbon keeps its Large buttons.
fn large_font(theme: &Theme) -> egui::FontId {
    theme.font(Text::Caption)
}

impl egui::Widget for LargeButton<'_> {
    fn ui(self, ui: &mut egui::Ui) -> egui::Response {
        let theme = Theme::of(ui);
        let width = LargeButton::width(ui, self.label);
        let (rect, response) = ui.allocate_exact_size(Vec2::new(width, self.height), egui::Sense::click());
        let enabled = ui.is_enabled();
        response.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::Button, enabled, self.selected, self.label));
        if ui.is_rect_visible(rect) {
            paint_state(ui, rect, &response, self.selected, true, &theme);
            let color = ink(&theme, enabled);
            let art = Rect::from_center_size(egui::pos2(rect.center().x, rect.top() + 22.0), Vec2::splat(LARGE_ART));
            if !paint_artwork(ui, self.glyph, art, color, enabled) {
                let g = paint::galley(ui, self.glyph, theme.font(Text::Body));
                ui.painter().galley(art.center() - g.size() / 2.0, g, color);
            }
            let g = paint::galley(ui, self.label, large_font(&theme));
            ui.painter().galley(egui::pos2(rect.center().x - g.size().x / 2.0, rect.bottom() - 6.0 - g.size().y), g, color);
        }
        response
    }
}

/// The icon at the start of a [`ToolRow`].
#[derive(Debug, Clone, Copy)]
pub enum RowIcon<'a> {
    /// A toolbar glyph's cropped artwork in a `GLYPH_SIZE` square, so every
    /// row's label starts at one x whatever the icon.
    Glyph(&'a str),
    /// A workbench icon's padded artwork at its own proportions, `height` tall.
    Workbench(&'a str, f32),
    None,
}

impl RowIcon<'_> {
    fn width(&self) -> f32 {
        match self {
            RowIcon::Glyph(g) => if crate::icons::artwork(g).is_some() { GLYPH_SIZE } else { 0.0 },
            RowIcon::Workbench(g, h) => crate::icons::artwork(g).map_or(0.0, |i| h * i.aspect),
            RowIcon::None => 0.0,
        }
    }
}

/// Edge of a row's trailing marker (the switcher's chevron and tick).
pub const ROW_MARKER: f32 = 12.0;
/// A row's inner padding either side, and the gap between its icon, label and
/// marker: as tight as the egui button it replaced, so the 1400 pt automation
/// window still holds every workbench's toolbar on one line.
pub const ROW_PAD: f32 = space::SM;
pub const ROW_GAP: f32 = space::XS;

/// A menu row: an icon, the label and an optional trailing marker slot, on
/// the selected fill when selected. `ToolRow::width` is what it measures to.
#[must_use = "a tool row does nothing until it is shown"]
pub struct ToolRow<'a> {
    icon: RowIcon<'a>,
    label: &'a str,
    size: Vec2,
    selected: bool,
    marker: Option<&'a str>,
    reserve_marker: bool,
}

impl<'a> ToolRow<'a> {
    /// A row at least `size`: wider when its contents need it.
    pub fn new(icon: RowIcon<'a>, label: &'a str, size: Vec2) -> Self {
        Self { icon, label, size, selected: false, marker: None, reserve_marker: false }
    }
    pub fn selected(mut self, selected: bool) -> Self {
        self.selected = selected;
        self
    }
    /// Reserve the trailing marker slot, and paint `marker`'s artwork in it
    /// when there is one.
    pub fn marker(mut self, marker: Option<&'a str>) -> Self {
        self.reserve_marker = true;
        self.marker = marker;
        self
    }
    /// The natural width of a row: padding, icon, gap, label, the marker
    /// slot when reserved, padding.
    pub fn width(ui: &egui::Ui, icon: RowIcon<'_>, label: &str, marker: bool) -> f32 {
        let theme = Theme::of(ui);
        let iw = icon.width();
        let gap = if iw > 0.0 { ROW_GAP } else { 0.0 };
        let label_w = paint::galley(ui, label, theme.font(Text::Body)).size().x;
        let marker_w = if marker { ROW_GAP + ROW_MARKER } else { 0.0 };
        2.0 * ROW_PAD + iw + gap + label_w + marker_w
    }

    /// Draw the row; returns its response and the marker slot's rect when reserved.
    pub fn show(self, ui: &mut egui::Ui) -> (egui::Response, Option<Rect>) {
        let theme = Theme::of(ui);
        let natural = ToolRow::width(ui, self.icon, self.label, self.reserve_marker);
        // At least the interact height, as the egui button rows this replaces
        // were: 44 pt on a touch screen (viewport::touch raises it).
        let height = self.size.y.max(ui.spacing().interact_size.y);
        let (rect, response) = ui.allocate_exact_size(Vec2::new(self.size.x.max(natural), height), egui::Sense::click());
        let enabled = ui.is_enabled();
        response.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::SelectableLabel, enabled, self.selected, self.label));
        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)));
        if ui.is_rect_visible(rect) {
            paint_state(ui, rect, &response, self.selected, false, &theme);
            let color = ink(&theme, enabled);
            let mut x = rect.left() + ROW_PAD;
            let iw = self.icon.width();
            match self.icon {
                RowIcon::Glyph(g) => {
                    paint_artwork(ui, g, Rect::from_min_size(egui::pos2(x, rect.center().y - GLYPH_SIZE / 2.0), Vec2::splat(GLYPH_SIZE)), color, enabled);
                }
                RowIcon::Workbench(g, h) => {
                    if let Some(icon) = crate::icons::artwork(g) {
                        egui_extras::install_image_loaders(ui.ctx());
                        let tint = if icon.mono { color } else if enabled { Color32::WHITE } else { Color32::WHITE.gamma_multiply(0.4) };
                        egui::Image::new(egui::ImageSource::Bytes { uri: icon.uri.into(), bytes: egui::load::Bytes::Static(icon.svg.as_bytes()) })
                            .fit_to_exact_size(Vec2::new(iw, h))
                            .tint(tint)
                            .paint_at(ui, Rect::from_min_size(egui::pos2(x, rect.center().y - h / 2.0), Vec2::new(iw, h)));
                    }
                }
                RowIcon::None => {}
            }
            if iw > 0.0 {
                x += iw + ROW_GAP;
            }
            let g = paint::galley(ui, self.label, theme.font(Text::Body));
            ui.painter().galley(egui::pos2(x, rect.center().y - g.size().y / 2.0), g, color);
            if let (Some(marker), Some(slot)) = (self.marker, slot) {
                let tint = if self.selected { theme.colors.accent_text } else { theme.colors.text_secondary };
                paint_artwork(ui, marker, slot, tint, enabled);
            }
        }
        (response, slot)
    }
}

/// A ribbon tab's height on the desktop in every density (the compact
/// control height).
pub const TAB_HEIGHT: f32 = 24.0;

/// A tab of a tab row that wraps with its neighbours (the ribbon's tabs share
/// a wrapping row with the switcher and the File menu): its text, a hover
/// overlay, and the active tab in `text.primary` over a 2 px accent underline.
pub fn wrapping_tab(ui: &mut egui::Ui, label: &str, selected: bool) -> egui::Response {
    let theme = Theme::of(ui);
    let c = &theme.colors;
    let g = paint::galley(ui, label, theme.font(Text::Body));
    // The top bar never moves with the density setting (step 2 keeps it on
    // the classic metrics): the compact control height, or the touch target.
    let size = Vec2::new(g.size().x + 2.0 * space::MD, TAB_HEIGHT.max(ui.spacing().interact_size.y));
    let (rect, response) = ui.allocate_exact_size(size, egui::Sense::click());
    response.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::SelectableLabel, ui.is_enabled(), selected, label));
    if ui.is_rect_visible(rect) {
        if response.hovered() {
            let overlay = if response.is_pointer_button_down_on() { c.pressed } else { c.hover };
            ui.painter().rect_filled(rect.shrink2(Vec2::new(0.0, 1.0)), radius::BUTTON, overlay);
        }
        if response.has_focus() {
            paint::focus_ring(ui, rect.shrink(1.0), radius::BUTTON, &theme);
        }
        let ink = if selected { c.text_primary } else { c.text_secondary };
        ui.painter().galley(rect.center() - g.size() / 2.0, g, ink);
        if selected {
            let line = Rect::from_min_max(egui::pos2(rect.left() + space::SM, rect.bottom() - RING), egui::pos2(rect.right() - space::SM, rect.bottom()));
            ui.painter().rect_filled(line, 1.0, c.accent_ring);
        }
    }
    response.on_hover_cursor(egui::CursorIcon::PointingHand)
}

/// The frame of a ribbon group: a 1 px `border.subtle` outline, no fill.
pub fn group_frame(ui: &egui::Ui) -> egui::Frame {
    let theme = Theme::of(ui);
    egui::Frame::new()
        .inner_margin(egui::Margin::same(space::SM as i8))
        .corner_radius(radius::BUTTON)
        .stroke(Stroke::new(crate::theme::BORDER, theme.colors.border_subtle))
}

/// A thin `border.subtle` rule, for separating toolbar groups.
pub fn rule(ui: &egui::Ui, x: f32, y: egui::Rangef) {
    ui.painter().vline(x, y, Stroke::new(1.0, Theme::of(ui).colors.border_subtle));
}