BREP_app 0.2.0

The BREP CAD application: an eframe (egui + wgpu) host that draws the brep-render 3D engine into an egui frame — native + wasm from one codebase.
Documentation
//! Per-file WORKBENCH registry — a UI FILTER over feature-CREATION.
//!
//! A "workbench" trims the feature-creation UI (the "Add new feature" palette and
//! the selection context bar) and can gate workbench-specific toolbar buttons /
//! panels. It NEVER changes what the feature history executes, renders, or lets
//! the user edit: a document full of sheet-metal features opens and works
//! identically under Modeling. The ONLY things a workbench touches are the palette
//! (see [`includes_feature`]) and the context offers.
//!
//! EXTENSIBILITY is the whole point: a new workbench = one new file here + one
//! entry in [`WORKBENCHES`]. No enums to edit. Each file exposes a single
//! `'static` [`Workbench`] that OWNS its own inclusion decision (`includes`), its
//! extra toolbar buttons (data only), and the ids of existing panels it claims.
//!
//! `"All"` is special: it accepts every feature and its buttons are the DERIVED
//! union of every other workbench's buttons ([`workbench_buttons`]) — never
//! hand-maintained — so adding a workbench automatically grows it.

pub mod all;
pub mod assembly;
pub mod modeling;
pub mod pmi;
pub mod sheet_metal;
pub mod wire_harness;

/// The minimal view of one catalogue entry a workbench predicate consumes: the
/// feature `type` CODE (e.g. `"E"`, `"S"`, `"SM.F"`), read from the existing
/// app-side catalogue accessor ([`brep_render::features::feature_catalogue`]).
/// Each workbench file classifies DIRECTLY off this code (no kernel-stamped
/// category — the kernel stays untouched). Borrows from the runtime catalogue
/// JSON, hence the lifetime — the registry itself stays `'static` because the
/// fn-pointer predicate is higher-ranked over the borrow.
pub struct FeatureInfo<'a> {
    pub type_code: &'a str,
}

/// A workbench-specific toolbar button, DATA ONLY (no egui, no behavior): the
/// shared toolbar-button helper renders it and a click surfaces `id` out of the
/// toolbar to the shell, which dispatches on `id`. Phase 1 ships none.
pub struct WorkbenchButton {
    /// Stable id the shell matches on when the button is clicked.
    pub id: &'static str,
    /// The single unicode glyph shown on the square button.
    pub glyph: &'static str,
    /// Hover tooltip / human label.
    pub tooltip: &'static str,
}

/// One workbench: a UI filter + optional toolbar buttons + claimed panels. Fully
/// `'static` — fn-pointer predicate and `&'static` slices, no `OnceLock`.
pub struct Workbench {
    /// Stable id, e.g. `"all"` / `"modeling"` / `"sheetMetal"` — the value stored
    /// in `RenderSettings.workbench` and published to the verifier.
    pub id: &'static str,
    /// Human label for the dropdown, e.g. `"Sheet Metal"`.
    pub label: &'static str,
    /// This workbench OWNS its inclusion decision: does a catalogue entry belong
    /// in this workbench's feature-creation UI?
    pub includes: fn(&FeatureInfo<'_>) -> bool,
    /// Extra toolbar buttons this workbench adds (data only). EMPTY in v1.
    pub buttons: &'static [WorkbenchButton],
    /// Ids of EXISTING panels this workbench CLAIMS. Claim-based, not hide-based:
    /// a panel is visible unless it is claimed by ≥1 workbench and the active one
    /// does not list it (see [`panel_visible`]). EMPTY in v1 (nothing claimed →
    /// every panel visible everywhere). Phase 2 adds claims here, editing NO other
    /// file — the same anti-rot property the button union gives.
    pub panels: &'static [&'static str],
}

/// The fallback / default workbench id. Boot-read validation is implicit:
/// [`resolve`] maps any unknown stored id to this, so there is no separate boot
/// step — every consumer routes through `resolve`.
pub const DEFAULT_WORKBENCH_ID: &str = "modeling";

/// Every workbench, in DROPDOWN ORDER: All, Modeling, Sheet Metal. The dropdown
/// iterates THIS — labels are never hardcoded. A new workbench is appended here.
pub static WORKBENCHES: &[&Workbench] = &[
    &all::ALL,
    &modeling::MODELING,
    &sheet_metal::SHEET_METAL,
    // Placeholders — established for the dropdown, fleshed out later.
    &wire_harness::WIRE_HARNESS,
    &assembly::ASSEMBLY,
    &pmi::PMI,
];

/// Pure lookup by id — `None` if there is no such workbench.
pub fn workbench_by_id(id: &str) -> Option<&'static Workbench> {
    WORKBENCHES.iter().copied().find(|w| w.id == id)
}

/// Resolve a (possibly stale / unknown) stored id to a live workbench, falling
/// back to the default. This IS the boot/read validation — route ALL consumers
/// (dropdown display, palette/offer filters, buttons, panels) through here.
pub fn resolve(id: &str) -> &'static Workbench {
    workbench_by_id(id).unwrap_or_else(|| {
        workbench_by_id(DEFAULT_WORKBENCH_ID).expect("default workbench must be registered")
    })
}

/// The active workbench's toolbar buttons. For `"all"` this is the DEDUPED UNION
/// of every workbench's buttons (so "All" shows every icon without a
/// hand-maintained list); for any other workbench it is that workbench's own
/// buttons.
pub fn workbench_buttons(id: &str) -> Vec<&'static WorkbenchButton> {
    let wb = resolve(id);
    if wb.id == "all" {
        dedupe_buttons(WORKBENCHES.iter().map(|w| w.buttons))
    } else {
        wb.buttons.iter().collect()
    }
}

/// Collect buttons across lists, keeping FIRST occurrence per `id` and preserving
/// order. The union logic behind [`workbench_buttons`] for `"all"`.
fn dedupe_buttons<'a>(
    lists: impl Iterator<Item = &'a [WorkbenchButton]>,
) -> Vec<&'a WorkbenchButton> {
    let mut seen = std::collections::HashSet::new();
    let mut out = Vec::new();
    for list in lists {
        for button in list {
            if seen.insert(button.id) {
                out.push(button);
            }
        }
    }
    out
}

/// Whether a catalogue entry belongs in workbench `active_id`'s feature-creation
/// UI. The ONE entry point the palette + context-offer filters call: builds a
/// [`FeatureInfo`] from the feature `type_code` and runs the resolved workbench's
/// predicate (each workbench file owns its classification off the code).
pub fn includes_feature(active_id: &str, type_code: &str) -> bool {
    let info = FeatureInfo { type_code };
    (resolve(active_id).includes)(&info)
}

/// Whether panel `panel_id` is visible in workbench `active_id`. Claim-based: a
/// panel is visible UNLESS it is claimed by ≥1 workbench and the active workbench
/// does not list it. `"all"` sees every panel (mirrors the button union). With
/// v1's empty `panels` slices nothing is claimed, so every panel is visible in
/// every workbench — the scaffolding is wired but hides nothing.
pub fn panel_visible(active_id: &str, panel_id: &str) -> bool {
    let claimed = WORKBENCHES.iter().any(|w| w.panels.contains(&panel_id));
    if !claimed {
        return true;
    }
    let wb = resolve(active_id);
    if wb.id == "all" {
        return true;
    }
    wb.panels.contains(&panel_id)
}

/// The workbench list as `{id, label}` JSON plus the resolved current id — the
/// `__brepWorkbench` logical-state global the headed verifier reads to drive the
/// dropdown and confirm the active workbench. `current` is the RESOLVED id (an
/// unknown stored id reads back as the default).
pub fn workbench_state_json(current_stored: &str) -> String {
    let available: Vec<serde_json::Value> = WORKBENCHES
        .iter()
        .map(|w| serde_json::json!({ "id": w.id, "label": w.label }))
        .collect();
    serde_json::json!({
        "current": resolve(current_stored).id,
        "available": available,
    })
    .to_string()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn registry_order_and_labels() {
        // The dropdown iterates WORKBENCHES; the order (and labels) live here.
        let ids: Vec<_> = WORKBENCHES.iter().map(|w| w.id).collect();
        assert_eq!(
            ids,
            ["all", "modeling", "sheetMetal", "wireHarness", "assembly", "pmi"]
        );
        let labels: Vec<_> = WORKBENCHES.iter().map(|w| w.label).collect();
        assert_eq!(
            labels,
            ["All", "Modeling", "Sheet Metal", "Wire harness", "Assembly", "PMI"]
        );
    }

    /// The placeholder workbenches are established (resolvable) but expose no
    /// features yet — their `includes` predicate rejects everything. (Assembly
    /// is no longer a placeholder — see `assembly_workbench_is_defined`.)
    #[test]
    fn placeholder_workbenches_are_empty_shells() {
        let info = |code| FeatureInfo { type_code: code };
        for id in ["wireHarness", "pmi"] {
            let wb = resolve(id);
            assert_eq!(wb.id, id, "placeholder `{id}` resolves");
            for code in ["S", "D", "P", "E", "SM.F", "B"] {
                assert!(
                    !(wb.includes)(&info(code)),
                    "placeholder `{id}` includes no features yet ({code})"
                );
            }
            assert!(wb.buttons.is_empty() && wb.panels.is_empty());
        }
    }

    /// The Assembly workbench (spec §8.1): creatable = Datum / Plane / Sketch /
    /// Component (ACOMP); everything else filtered; claims the two assembly
    /// panels — which therefore hide outside Assembly (and All), while an
    /// UNCLAIMED panel (history) stays visible everywhere.
    #[test]
    fn assembly_workbench_is_defined() {
        let info = |code| FeatureInfo { type_code: code };
        let wb = resolve("assembly");
        for code in ["S", "D", "P", "ACOMP"] {
            assert!((wb.includes)(&info(code)), "assembly includes {code}");
        }
        for code in ["E", "B", "SM.F", "SM.TAB"] {
            assert!(!(wb.includes)(&info(code)), "assembly excludes {code}");
        }
        // ACOMP is Assembly's creatable: Modeling and Sheet Metal hide it,
        // All (the superset) still offers it.
        assert!(!includes_feature("modeling", "ACOMP"));
        assert!(!includes_feature("sheetMetal", "ACOMP"));
        assert!(includes_feature("all", "ACOMP"));
        assert!(includes_feature("assembly", "ACOMP"));

        // Panel claims: the assembly panels show under Assembly + All only.
        for panel in [assembly::BOM_PANEL_ID, assembly::CONSTRAINTS_PANEL_ID] {
            assert!(panel_visible("assembly", panel), "{panel} visible in assembly");
            assert!(panel_visible("all", panel), "{panel} visible in All");
            assert!(!panel_visible("modeling", panel), "{panel} hidden in modeling");
            assert!(!panel_visible("sheetMetal", panel), "{panel} hidden in sheet metal");
        }
        // Unclaimed panels stay visible in Assembly (history is never filtered).
        assert!(panel_visible("assembly", "history"));
        assert!(panel_visible("assembly", "scene"));
    }

    #[test]
    fn unknown_id_falls_back_to_default() {
        // Pure lookup is `None`; the resolver falls back to the default.
        assert!(workbench_by_id("bogus").is_none());
        assert!(workbench_by_id("").is_none());
        assert_eq!(resolve("bogus").id, DEFAULT_WORKBENCH_ID);
        assert_eq!(resolve("").id, "modeling");
        // A known id resolves to itself.
        assert_eq!(resolve("sheetMetal").id, "sheetMetal");
    }

    #[test]
    fn predicates_classify_by_type_code() {
        // The three predicates classify DIRECTLY off the feature type code: a
        // sheet-metal code (SM.F), a shared building block (S/D/P), and a plain
        // modeling code (E).
        let info = |code| FeatureInfo { type_code: code };

        // All accepts everything.
        let all = resolve("all");
        for code in ["SM.F", "S", "D", "P", "E"] {
            assert!((all.includes)(&info(code)), "All includes {code}");
        }

        // Modeling excludes sheet metal (SM.*), keeps modeling + the common S/D/P.
        let m = resolve("modeling");
        assert!(!(m.includes)(&info("SM.F")), "modeling excludes SM.F");
        assert!(!(m.includes)(&info("SM.TAB")), "modeling excludes SM.TAB");
        for code in ["S", "D", "P", "E"] {
            assert!((m.includes)(&info(code)), "modeling includes {code}");
        }

        // Sheet Metal keeps SM.* + the common S/D/P, excludes pure modeling (E).
        let s = resolve("sheetMetal");
        assert!((s.includes)(&info("SM.F")), "sheet metal includes SM.F");
        for code in ["S", "D", "P"] {
            assert!((s.includes)(&info(code)), "sheet metal includes common {code}");
        }
        assert!(!(s.includes)(&info("E")), "sheet metal excludes Extrude");
    }

    #[test]
    fn includes_feature_entry_point() {
        assert!(!includes_feature("modeling", "SM.TAB"));
        assert!(includes_feature("modeling", "E"));
        assert!(includes_feature("modeling", "S"));
        assert!(includes_feature("sheetMetal", "SM.TAB"));
        assert!(!includes_feature("sheetMetal", "E"));
        assert!(includes_feature("all", "E"));
        assert!(includes_feature("all", "SM.TAB"));
        // Unknown workbench id falls back to Modeling's filtering.
        assert!(!includes_feature("bogus", "SM.TAB"));
    }

    #[test]
    fn all_buttons_is_the_deduped_union() {
        // Sheet Metal owns the flat-pattern export button (Phase 2), Assembly
        // Add-Component + the interference check; Modeling still declares none.
        // "All" is the DEDUPED UNION, so it carries all without a hand-maintained
        // list.
        let ids = |wb: &str| -> Vec<&str> {
            workbench_buttons(wb).iter().map(|b| b.id).collect()
        };
        assert_eq!(ids("sheetMetal"), ["sheetmetal.flat_pattern"]);
        assert_eq!(
            ids("assembly"),
            [
                "assembly.add_component",
                "assembly.step_parts_library",
                "assembly.interference"
            ]
        );
        assert!(workbench_buttons("modeling").is_empty());
        assert_eq!(
            ids("all"),
            [
                "sheetmetal.flat_pattern",
                "assembly.add_component",
                "assembly.step_parts_library",
                "assembly.interference"
            ]
        );
    }

    #[test]
    fn dedupe_preserves_order_and_drops_duplicate_ids() {
        // Exercise the union logic directly with synthetic overlapping lists (the
        // real slices are empty in v1). `y` appears in both lists; the FIRST wins
        // and order is preserved.
        let a = [
            WorkbenchButton { id: "x", glyph: "1", tooltip: "X" },
            WorkbenchButton { id: "y", glyph: "2", tooltip: "Y" },
        ];
        let b = [
            WorkbenchButton { id: "y", glyph: "3", tooltip: "Y-dup" },
            WorkbenchButton { id: "z", glyph: "4", tooltip: "Z" },
        ];
        let out = dedupe_buttons([a.as_slice(), b.as_slice()].into_iter());
        let ids: Vec<_> = out.iter().map(|button| button.id).collect();
        assert_eq!(ids, ["x", "y", "z"]);
        // The kept `y` is the first list's (glyph "2"), not the duplicate.
        assert_eq!(out[1].glyph, "2");
    }

    #[test]
    fn panels_default_visible_when_unclaimed() {
        // v1: no workbench claims any panel → every panel is visible everywhere.
        for wb in ["all", "modeling", "sheetMetal", "bogus"] {
            assert!(panel_visible(wb, "history"));
            assert!(panel_visible(wb, "scene"));
            assert!(panel_visible(wb, "expressions"));
        }
    }

    #[test]
    fn state_json_reports_current_and_available() {
        let json: serde_json::Value =
            serde_json::from_str(&workbench_state_json("sheetMetal")).unwrap();
        assert_eq!(json["current"], "sheetMetal");
        // An unknown stored id reads back as the resolved default.
        let fallback: serde_json::Value =
            serde_json::from_str(&workbench_state_json("bogus")).unwrap();
        assert_eq!(fallback["current"], "modeling");
        let available = json["available"].as_array().unwrap();
        assert_eq!(available.len(), WORKBENCHES.len());
        assert_eq!(available[0]["id"], "all");
        assert_eq!(available[2]["label"], "Sheet Metal");
        assert_eq!(available[5]["id"], "pmi");
    }
}