BREP_app 0.3.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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
//! Workbench actions toolbar — a second top strip drawn UNDER the primary
//! toolbar, listing the ACTIVE WORKBENCH's creatable features as one square
//! icon button each, and (in a workbench that shows the Constraints panel —
//! Assembly, and All as its union) a second group with one button per
//! assembly-constraint type.
//!
//! It is a shortcut surface over creation, nothing more: a feature button does
//! exactly what picking that entry in the **Add new feature** palette does
//! (`HistoryPanel::add_feature_of_type`, so ACOMP still routes to the
//! component selector), and a constraint button does what the context bar's
//! constraint offer does (`context_bar::add_constraint_from_selection`, seeding
//! `elements` from the current selection). Which features appear is the SAME
//! workbench filter the palette applies ([`workbench::includes_feature`]); the
//! constraints group is gated on the SAME panel claim the dock and the context
//! bar use ([`workbench::panel_visible`]). Nothing here decides anything on
//! its own.
//!
//! Shown only while `settings.show_workbench_toolbar` is on (the Settings
//! "Show workbench actions toolbar" checkbox), and NEVER in a special mode: a
//! sketch takes over the shell with its own tool strip, and reference
//! selection bypasses the dock the new feature's form would open in. Follows
//! the toolbar pattern: a small state struct owning only the per-frame `hits`
//! map (widget rects) the headed verifier reads, a `show(...)` the shell calls
//! right after the primary toolbar so the strip lands below it, and clicks
//! flow OUT through a returned [`WorkbenchToolbarOutcome`] — the shell
//! dispatches, because adding a feature touches panels this strip cannot
//! borrow.

use crate::panels::toolbar_button;
use crate::workbench;
use brep_render::engine_state::EngineState;
use brep_render::features;
use eframe::egui;
use serde_json::Value;
use std::collections::HashMap;

/// What one frame of the strip produced for the shell to act on.
#[derive(Default)]
pub struct WorkbenchToolbarOutcome {
    /// A feature button click — the feature TYPE CODE to add (`"E"`, `"ACOMP"`).
    pub feature: Option<String>,
    /// A constraint button click — the constraint type id to add (`"fixed"`).
    pub constraint: Option<String>,
}

/// One drawn button: its stable id, the glyph on the square, and the tooltip.
struct ActionButton {
    id: String,
    glyph: String,
    tooltip: String,
}

/// The strip's own state: the per-frame hit-rects, plus the button lists,
/// which are derived from the kernel catalogues and so are rebuilt only when
/// the workbench changes rather than re-walked every frame.
#[derive(Default)]
pub struct WorkbenchToolbarPanel {
    hits: HashMap<String, egui::Rect>,
    /// The feature buttons for `cached_workbench` (the catalogue filtered by
    /// that workbench, in catalogue order).
    features: Vec<ActionButton>,
    cached_workbench: Option<String>,
    /// The constraint buttons — the constraint catalogue is static, so this is
    /// built once.
    constraints: Vec<ActionButton>,
}

impl WorkbenchToolbarPanel {
    pub fn new() -> Self {
        Self::default()
    }

    /// Whether the strip is drawn this frame: the setting is on AND no special
    /// mode owns the shell (a sketch has its own tool strip; reference
    /// selection hides the dock the new feature's form would open in).
    pub fn visible(state: &EngineState) -> bool {
        state.settings.show_workbench_toolbar && !state.sketch_mode() && !state.ref_select_active()
    }

    /// Draw the strip as a top panel — called right AFTER the primary toolbar
    /// so egui stacks it directly underneath. Draws nothing (and publishes no
    /// hit-rects) when [`Self::visible`] is false, or when the active
    /// workbench offers nothing to put on it (the placeholder workbenches).
    pub fn show(&mut self, ui: &mut egui::Ui, state: &EngineState) -> WorkbenchToolbarOutcome {
        self.hits.clear();
        let mut outcome = WorkbenchToolbarOutcome::default();
        if !Self::visible(state) {
            return outcome;
        }
        let active = state.settings.workbench.clone();
        self.refresh_buttons(&active);
        let with_constraints =
            workbench::panel_visible(&active, workbench::assembly::CONSTRAINTS_PANEL_ID);
        if self.features.is_empty() && !with_constraints {
            return outcome;
        }
        egui::containers::panel::Panel::top("brep-workbench-toolbar")
            .resizable(false)
            .show(ui, |ui| {
                ui.add_space(2.0);
                ui.horizontal_wrapped(|ui| {
                    if !self.features.is_empty() {
                        caption(ui, "Features");
                        outcome.feature = Self::draw_group(ui, &self.features, &mut self.hits);
                    }
                    if with_constraints {
                        if !self.features.is_empty() {
                            ui.separator();
                        }
                        caption(ui, "Constraints");
                        outcome.constraint =
                            Self::draw_group(ui, &self.constraints, &mut self.hits);
                    }
                });
                ui.add_space(2.0);
            });
        outcome
    }

    /// Rebuild the button lists when the workbench changed (or on first use).
    fn refresh_buttons(&mut self, active: &str) {
        if self.cached_workbench.as_deref() != Some(active) {
            self.features = feature_buttons(active);
            self.cached_workbench = Some(active.to_string());
        }
        if self.constraints.is_empty() {
            self.constraints = constraint_buttons();
        }
    }

    /// Draw one group of square buttons through the shared toolbar-button
    /// helper, publishing each hit-rect under `wbtb:<id>`; returns the clicked
    /// button's payload (the part of the id after the group prefix).
    fn draw_group(
        ui: &mut egui::Ui,
        buttons: &[ActionButton],
        hits: &mut HashMap<String, egui::Rect>,
    ) -> Option<String> {
        let mut clicked = None;
        for button in buttons {
            let resp = toolbar_button::button(ui, &button.glyph, &button.tooltip);
            hits.insert(format!("wbtb:{}", button.id), resp.rect);
            if resp.clicked() {
                clicked = button.id.split_once(':').map(|(_, payload)| payload.to_string());
            }
        }
        clicked
    }

    /// The published widget hit-rects (egui points) for the headed verifier —
    /// `wbtb:feature:<type>` / `wbtb:constraint:<type>`; empty while hidden.
    pub fn hits_json(&self) -> String {
        let map: serde_json::Map<String, Value> = self
            .hits
            .iter()
            .map(|(k, r)| {
                (
                    k.clone(),
                    serde_json::json!([r.min.x, r.min.y, r.width(), r.height()]),
                )
            })
            .collect();
        Value::Object(map).to_string()
    }
}

/// A small, dim group caption ahead of its buttons.
fn caption(ui: &mut egui::Ui, text: &str) {
    ui.label(egui::RichText::new(text).weak().small());
}

/// One button per catalogue feature the workbench INCLUDES, in catalogue
/// order — the same list, same filter, as the Add-feature palette. The glyph is
/// the feature's icon (the catalogued artwork paints it); a feature with no icon
/// falls back to its short name as text.
fn feature_buttons(active: &str) -> Vec<ActionButton> {
    let catalogue = features::feature_catalogue();
    let mut buttons = Vec::new();
    if let Some(list) = catalogue.get("features").and_then(Value::as_array) {
        for feature in list {
            let ty = feature.get("type").and_then(Value::as_str).unwrap_or("");
            if ty.is_empty() || !workbench::includes_feature(active, ty) {
                continue;
            }
            let name = feature
                .get("longName")
                .and_then(Value::as_str)
                .unwrap_or(ty)
                .to_string();
            let glyph = match features::feature_icon(ty) {
                Some(icon) => icon.to_string(),
                None => feature
                    .get("shortName")
                    .and_then(Value::as_str)
                    .unwrap_or(ty)
                    .to_string(),
            };
            buttons.push(ActionButton {
                id: format!("feature:{ty}"),
                glyph,
                tooltip: format!("Add {name}"),
            });
        }
    }
    buttons
}

/// One button per assembly-constraint type, spec §4 order (the same order as
/// the constraint catalogue and the panel's `+` dropdown). The glyph is the
/// type's icon (`ConstraintTypeDef::icon` — the picture the context bar's
/// offer and the viewport chip show), drawn as catalogued artwork; the plain
/// name rides in the tooltip.
fn constraint_buttons() -> Vec<ActionButton> {
    brep_render::brep_kernel::CONSTRAINT_TYPES
        .iter()
        .map(|def| ActionButton {
            id: format!("constraint:{}", def.type_id),
            glyph: def.icon.to_string(),
            tooltip: format!("Add {} constraint from the selection", def.label),
        })
        .collect()
}

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

    /// One headless egui frame of the strip with `events` as input, on a
    /// screen wide enough that the wrapped row keeps every button on screen.
    fn frame(
        ctx: &egui::Context,
        panel: &mut WorkbenchToolbarPanel,
        state: &EngineState,
        events: Vec<egui::Event>,
    ) -> WorkbenchToolbarOutcome {
        let raw = egui::RawInput {
            screen_rect: Some(egui::Rect::from_min_size(
                egui::pos2(0.0, 0.0),
                egui::vec2(1600.0, 300.0),
            )),
            events,
            ..Default::default()
        };
        let mut out = WorkbenchToolbarOutcome::default();
        let _ = ctx.run_ui(raw, |ui| out = panel.show(ui, state));
        out
    }

    fn keys(panel: &WorkbenchToolbarPanel) -> Vec<String> {
        let mut keys: Vec<_> = panel.hits.keys().cloned().collect();
        keys.sort();
        keys
    }

    /// The setting defaults ON and the strip publishes the Modeling feature
    /// set: Extrude yes, sheet metal and the assembly component no, and no
    /// constraints group outside a workbench that shows the panel.
    #[test]
    fn modeling_lists_its_features_and_no_constraints() {
        let ctx = egui::Context::default();
        let state = EngineState::new();
        assert!(state.settings.show_workbench_toolbar, "the strip is on by default");
        let mut panel = WorkbenchToolbarPanel::new();
        let out = frame(&ctx, &mut panel, &state, vec![]);
        assert!(out.feature.is_none() && out.constraint.is_none(), "a passive render is not a click");
        let keys = keys(&panel);
        assert!(keys.contains(&"wbtb:feature:E".to_string()), "extrude offered: {keys:?}");
        assert!(keys.contains(&"wbtb:feature:S".to_string()), "sketch offered");
        assert!(!keys.contains(&"wbtb:feature:SM.F".to_string()), "sheet metal filtered");
        assert!(!keys.contains(&"wbtb:feature:ACOMP".to_string()), "assembly component filtered");
        assert!(
            !keys.iter().any(|k| k.starts_with("wbtb:constraint:")),
            "no constraints group in Modeling: {keys:?}"
        );
    }

    /// The strip is the SAME filter as the palette: every type the strip
    /// offers is one `includes_feature` accepts, and vice versa, for each
    /// workbench.
    #[test]
    fn strip_matches_the_palette_filter_per_workbench() {
        let ctx = egui::Context::default();
        let catalogue = features::feature_catalogue();
        let all_types: Vec<String> = catalogue["features"]
            .as_array()
            .unwrap()
            .iter()
            .filter_map(|f| f.get("type").and_then(Value::as_str).map(String::from))
            .collect();
        for wb in ["all", "modeling", "sheetMetal", "assembly"] {
            let mut state = EngineState::new();
            state
                .apply_settings_json(&format!(r#"{{"workbench":"{wb}"}}"#))
                .unwrap();
            let mut panel = WorkbenchToolbarPanel::new();
            frame(&ctx, &mut panel, &state, vec![]);
            for ty in &all_types {
                let shown = panel.hits.contains_key(&format!("wbtb:feature:{ty}"));
                assert_eq!(
                    shown,
                    workbench::includes_feature(wb, ty),
                    "{wb}: strip and palette disagree on {ty}"
                );
            }
        }
    }

    /// Assembly (and All, its union) add the constraints group — one button per
    /// catalogue constraint type — and Assembly drops the modeling features.
    #[test]
    fn assembly_and_all_show_the_constraints_group() {
        let ctx = egui::Context::default();
        let constraint_types: Vec<String> =
            brep_render::brep_kernel::constraint_schema_catalogue()
                .as_array()
                .unwrap()
                .iter()
                .filter_map(|s| s.get("type").and_then(Value::as_str).map(String::from))
                .collect();
        assert!(constraint_types.contains(&"fixed".to_string()));
        for wb in ["assembly", "all"] {
            let mut state = EngineState::new();
            state
                .apply_settings_json(&format!(r#"{{"workbench":"{wb}"}}"#))
                .unwrap();
            let mut panel = WorkbenchToolbarPanel::new();
            frame(&ctx, &mut panel, &state, vec![]);
            for ty in &constraint_types {
                assert!(
                    panel.hits.contains_key(&format!("wbtb:constraint:{ty}")),
                    "{wb} offers the {ty} constraint: {:?}",
                    keys(&panel)
                );
            }
            assert!(panel.hits.contains_key("wbtb:feature:ACOMP"), "{wb} offers ACOMP");
        }
        // Assembly's feature group is the four building blocks only.
        let mut state = EngineState::new();
        state.apply_settings_json(r#"{"workbench":"assembly"}"#).unwrap();
        let mut panel = WorkbenchToolbarPanel::new();
        frame(&ctx, &mut panel, &state, vec![]);
        assert!(!panel.hits.contains_key("wbtb:feature:E"), "assembly hides Extrude");
        // Sheet Metal shows no constraints group (the panel is not shown there).
        let mut state = EngineState::new();
        state.apply_settings_json(r#"{"workbench":"sheetMetal"}"#).unwrap();
        let mut panel = WorkbenchToolbarPanel::new();
        frame(&ctx, &mut panel, &state, vec![]);
        assert!(!keys(&panel).iter().any(|k| k.starts_with("wbtb:constraint:")));
    }

    /// The Settings checkbox hides the strip: nothing drawn, no hit-rects.
    #[test]
    fn setting_off_hides_the_strip() {
        let ctx = egui::Context::default();
        let mut state = EngineState::new();
        state.apply_settings_json(r#"{"showWorkbenchToolbar": false}"#).unwrap();
        assert!(!WorkbenchToolbarPanel::visible(&state));
        let mut panel = WorkbenchToolbarPanel::new();
        frame(&ctx, &mut panel, &state, vec![]);
        assert!(panel.hits.is_empty(), "hidden strip publishes nothing: {:?}", keys(&panel));
        // Round trip: the setting survives to_json → apply_json.
        let json = state.settings_json();
        assert!(json.contains(r#""showWorkbenchToolbar":false"#), "{json}");
    }

    /// While a sketch is being edited the strip is gone regardless of the
    /// setting — the sketch's own tool strip owns that slot.
    #[test]
    fn sketch_mode_hides_the_strip() {
        let ctx = egui::Context::default();
        let mut state = EngineState::new();
        let history = serde_json::json!({
            "features": [{
                "type": "S",
                "inputParams": { "id": "Sk" },
                "persistentData": {
                    "basis": { "origin": [0, 0, 0], "x": [1, 0, 0], "y": [0, 1, 0], "z": [0, 0, 1] },
                    "sketch": {
                        "points": [
                            { "id": 0, "x": 0.0, "y": 0.0 },
                            { "id": 1, "x": 10.0, "y": 0.0 }
                        ],
                        "geometries": [
                            { "id": 10, "type": "line", "points": [0, 1], "construction": false }
                        ],
                        "constraints": []
                    }
                }
            }]
        });
        state.set_history_json(&history.to_string()).expect("sketch history loads");
        let mut panel = WorkbenchToolbarPanel::new();
        frame(&ctx, &mut panel, &state, vec![]);
        assert!(panel.hits.contains_key("wbtb:feature:E"), "visible before the sketch opens");

        state.enter_sketch_mode("Sk").expect("enter sketch mode");
        assert!(state.sketch_mode());
        assert!(!WorkbenchToolbarPanel::visible(&state));
        frame(&ctx, &mut panel, &state, vec![]);
        assert!(panel.hits.is_empty(), "hidden in sketch mode: {:?}", keys(&panel));

        let _ = state.exit_sketch_mode(false);
        frame(&ctx, &mut panel, &state, vec![]);
        assert!(panel.hits.contains_key("wbtb:feature:E"), "back after the sketch closes");
    }

    /// A real press + release on a feature button surfaces its type code
    /// through the outcome (the return path the shell dispatches on).
    #[test]
    fn click_surfaces_the_feature_type() {
        let ctx = egui::Context::default();
        let state = EngineState::new();
        let mut panel = WorkbenchToolbarPanel::new();
        frame(&ctx, &mut panel, &state, vec![]);
        let pos = panel
            .hits
            .get("wbtb:feature:P.CU")
            .expect("the cube button publishes a hit-rect")
            .center();
        frame(
            &ctx,
            &mut panel,
            &state,
            vec![
                egui::Event::PointerMoved(pos),
                egui::Event::PointerButton {
                    pos,
                    button: egui::PointerButton::Primary,
                    pressed: true,
                    modifiers: egui::Modifiers::default(),
                },
            ],
        );
        let out = frame(
            &ctx,
            &mut panel,
            &state,
            vec![egui::Event::PointerButton {
                pos,
                button: egui::PointerButton::Primary,
                pressed: false,
                modifiers: egui::Modifiers::default(),
            }],
        );
        assert_eq!(out.feature.as_deref(), Some("P.CU"));
        assert!(out.constraint.is_none());
    }

    /// The strip's constraint click on a PLAIN part (no components, nothing
    /// selected) is the shell's `add_constraint_from_selection` — it must
    /// either add an (element-less) row for the user to fill in, or refuse
    /// with an error the shell can toast; never a silent no-op.
    #[test]
    fn constraint_click_on_a_plain_part_adds_or_refuses_loudly() {
        let mut state = EngineState::new();
        state
            .set_history_json(&crate::app::seed_history_json())
            .expect("seed history loads");
        let before = state.assembly_state_value()["constraints"]
            .as_array()
            .map_or(0, Vec::len);
        let outcome = crate::panels::context_bar::add_constraint_from_selection(&mut state, "fixed");
        let after = state.assembly_state_value()["constraints"]
            .as_array()
            .map_or(0, Vec::len);
        eprintln!("plain-part fixed constraint: before={before} after={after} outcome={outcome:?}");
        match &outcome {
            Ok(id) => assert_eq!(after, before + 1, "row {id} added"),
            Err(error) => assert!(!error.is_empty(), "a refusal names its reason"),
        }
    }

    /// Same for a constraint button under the Assembly workbench.
    #[test]
    fn click_surfaces_the_constraint_type() {
        let ctx = egui::Context::default();
        let mut state = EngineState::new();
        state.apply_settings_json(r#"{"workbench":"assembly"}"#).unwrap();
        let mut panel = WorkbenchToolbarPanel::new();
        frame(&ctx, &mut panel, &state, vec![]);
        let pos = panel
            .hits
            .get("wbtb:constraint:fixed")
            .expect("the fixed-constraint button publishes a hit-rect")
            .center();
        frame(
            &ctx,
            &mut panel,
            &state,
            vec![
                egui::Event::PointerMoved(pos),
                egui::Event::PointerButton {
                    pos,
                    button: egui::PointerButton::Primary,
                    pressed: true,
                    modifiers: egui::Modifiers::default(),
                },
            ],
        );
        let out = frame(
            &ctx,
            &mut panel,
            &state,
            vec![egui::Event::PointerButton {
                pos,
                button: egui::PointerButton::Primary,
                pressed: false,
                modifiers: egui::Modifiers::default(),
            }],
        );
        assert_eq!(out.constraint.as_deref(), Some("fixed"));
        assert!(out.feature.is_none());
    }

    /// Every constraint button's glyph is the type's catalogued icon — the
    /// same picture the context bar offer and the viewport chip show — never
    /// the `FIXD`/`DIST` short name. Coincident included (it had no glyph
    /// anywhere until 2026-09-06).
    #[test]
    fn constraint_buttons_carry_the_type_icon_as_artwork() {
        let buttons = constraint_buttons();
        assert_eq!(buttons.len(), 10);
        for (button, def) in buttons.iter().zip(brep_render::brep_kernel::CONSTRAINT_TYPES.iter()) {
            assert_eq!(button.glyph, def.icon, "{}", def.type_id);
            assert!(
                crate::icons::artwork(&button.glyph).is_some(),
                "{}: the icon {:?} must be catalogued artwork, not a font character",
                def.type_id,
                button.glyph
            );
            assert!(button.tooltip.contains(def.label), "{}: {}", def.type_id, button.tooltip);
            assert!(!button.glyph.contains(def.short_name), "{}: no short names on the strip", def.type_id);
        }
        assert_eq!(buttons[1].glyph, "\u{2261}", "coincident is \u{2261}, as in the sketch solver");
    }
}