BREP_app 0.17.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
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
//! Renderer-neutral command snapshots. Availability and dispatch belong to their owners.
use super::{ButtonState, WorkbenchButton};
use brep_render::engine_state::EngineState;

pub const RIBBON_TABS: [&str; 3] = ["Home", "View", "Help"];

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CommandSize {
    Large,
    Compact,
}

/// Built-ins borrow static strings; runtime adapters borrow their owned metadata.
#[derive(Clone, Copy, Debug)]
pub struct CommandPresentation<'a> {
    pub id: &'a str,
    pub glyph: &'a str,
    pub ribbon_path: &'a str,
    pub size: CommandSize,
}
impl<'a> CommandPresentation<'a> {
    pub fn label(&self) -> &'a str {
        self.ribbon_path.rsplit('/').next().unwrap_or("")
    }
}

pub fn ribbon_segments(path: &str) -> Result<[&str; 3], String> {
    let parts: Vec<_> = path.split('/').collect();
    if parts.len() != 3 || parts.iter().any(|p| p.trim().is_empty() || p.trim() != *p) {
        return Err(format!("invalid ribbon path: {path:?}"));
    }
    if !RIBBON_TABS.contains(&parts[0]) {
        return Err(format!("unknown ribbon tab: {}", parts[0]));
    }
    Ok([parts[0], parts[1], parts[2]])
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum CommandTarget {
    Shell(&'static str),
    Workbench(&'static str),
    Plugin(String),
    Feature(String),
    Constraint(String),
    Annotation(String),
}

#[derive(Clone, Debug)]
pub struct OfferedCommand {
    pub id: String,
    pub glyph: String,
    pub ribbon_path: String,
    pub size: CommandSize,
    pub target: CommandTarget,
    pub pressed: bool,
    pub toggle: bool,
    pub disabled_reason: Option<String>,
    pub detail: String,
    pub menu: Vec<OfferedCommand>,
}
impl OfferedCommand {
    pub fn presentation(&self) -> CommandPresentation<'_> {
        CommandPresentation {
            id: &self.id,
            glyph: &self.glyph,
            ribbon_path: &self.ribbon_path,
            size: self.size,
        }
    }
    pub fn segments(&self) -> [&str; 3] {
        ribbon_segments(self.presentation().ribbon_path).expect("validated command path")
    }
    pub fn label(&self) -> &str {
        self.presentation().label()
    }
    pub fn is_home(&self) -> bool {
        self.segments()[0] == "Home"
    }
    /// A creation command: Classic draws these on its creation strip, and
    /// everything else (File, Undo, actions, tools) on its primary row.
    pub fn is_creation(&self) -> bool {
        matches!(
            self.target,
            CommandTarget::Feature(_) | CommandTarget::Constraint(_) | CommandTarget::Annotation(_)
        )
    }
}

pub fn validate_commands(commands: &[OfferedCommand]) -> Result<(), String> {
    fn visit(
        commands: &[OfferedCommand],
        ids: &mut std::collections::HashSet<String>,
    ) -> Result<(), String> {
        for command in commands {
            ribbon_segments(&command.ribbon_path)?;
            if command.id.is_empty() || !ids.insert(command.id.clone()) {
                return Err(format!("duplicate or empty command id: {}", command.id));
            }
            visit(&command.menu, ids)?;
        }
        Ok(())
    }
    visit(commands, &mut Default::default())
}

fn static_command(p: CommandPresentation<'static>, target: CommandTarget) -> OfferedCommand {
    OfferedCommand {
        id: p.id.into(),
        glyph: p.glyph.into(),
        ribbon_path: p.ribbon_path.into(),
        size: p.size,
        target,
        pressed: false,
        toggle: false,
        disabled_reason: None,
        detail: p.label().into(),
        menu: vec![],
    }
}

/// File commands share metadata; Properties and Settings are offered only in File.
pub const FILE_COMMANDS: &[CommandPresentation<'static>] = &[
    CommandPresentation {
        id: "file:new",
        glyph: "\u{E010}",
        ribbon_path: "Home/File/New",
        size: CommandSize::Large,
    },
    CommandPresentation {
        id: "file:open",
        glyph: "\u{E011}",
        ribbon_path: "Home/File/Open",
        size: CommandSize::Large,
    },
    CommandPresentation {
        id: "file:save",
        glyph: "\u{E012}",
        ribbon_path: "Home/File/Save",
        size: CommandSize::Large,
    },
    CommandPresentation {
        id: "file:saveas",
        glyph: "\u{E013}",
        ribbon_path: "Home/File/Save As",
        size: CommandSize::Compact,
    },
    CommandPresentation {
        id: "file:import",
        glyph: "\u{E014}",
        ribbon_path: "Home/File/Import",
        size: CommandSize::Compact,
    },
    CommandPresentation {
        id: "file:export",
        glyph: "\u{E015}",
        ribbon_path: "Home/File/Export",
        size: CommandSize::Compact,
    },
    CommandPresentation {
        id: "properties",
        glyph: "\u{E066}",
        ribbon_path: "Home/File/Document Properties",
        size: CommandSize::Compact,
    },
    CommandPresentation {
        id: "settings",
        glyph: "\u{2699}",
        ribbon_path: "Home/File/Settings",
        size: CommandSize::Compact,
    },
    // Plugin management lives under Settings in the File menu, in both styles.
    CommandPresentation {
        id: "workbench:manage:plugins",
        glyph: "\u{2699}",
        ribbon_path: "Home/File/Plugins",
        size: CommandSize::Compact,
    },
    CommandPresentation {
        id: "workbench:manage:javascript",
        glyph: "\u{270E}",
        ribbon_path: "Home/File/JavaScript",
        size: CommandSize::Compact,
    },
];

/// Flat New rows in DocumentClass::ALL order.
pub const NEW_DOCUMENT_COMMANDS: &[CommandPresentation<'static>] = &[
    CommandPresentation {
        id: "file:newclass:normal",
        glyph: "\u{E010}",
        ribbon_path: "Home/File/New part",
        size: CommandSize::Compact,
    },
    CommandPresentation {
        id: "file:newclass:family",
        glyph: "\u{E010}",
        ribbon_path: "Home/File/New family",
        size: CommandSize::Compact,
    },
    CommandPresentation {
        id: "file:newclass:template",
        glyph: "\u{E010}",
        ribbon_path: "Home/File/New template",
        size: CommandSize::Compact,
    },
];

pub fn file_presentation(id: &str) -> CommandPresentation<'static> {
    *FILE_COMMANDS
        .iter()
        .find(|c| c.id == id)
        .expect("File command is declared")
}

pub const SHELL_COMMANDS: &[CommandPresentation<'static>] = &[
    CommandPresentation {
        id: "undo",
        glyph: "\u{E016}",
        ribbon_path: "Home/Undo/Undo",
        size: CommandSize::Compact,
    },
    CommandPresentation {
        id: "redo",
        glyph: "\u{E017}",
        ribbon_path: "Home/Undo/Redo",
        size: CommandSize::Compact,
    },
    CommandPresentation {
        id: "wireframe",
        glyph: "\u{1F578}",
        ribbon_path: "View/Display/Wireframe",
        size: CommandSize::Compact,
    },
    CommandPresentation {
        id: "projection",
        glyph: "\u{E018}",
        ribbon_path: "View/Display/Projection",
        size: CommandSize::Compact,
    },
    CommandPresentation {
        id: "show:faces",
        glyph: "\u{E028}",
        ribbon_path: "View/Display/Show faces",
        size: CommandSize::Compact,
    },
    CommandPresentation {
        id: "show:edges",
        glyph: "\u{E029}",
        ribbon_path: "View/Display/Show edges",
        size: CommandSize::Compact,
    },
    CommandPresentation {
        id: "show:vertices",
        glyph: "\u{E02A}",
        ribbon_path: "View/Display/Show vertices",
        size: CommandSize::Compact,
    },
    CommandPresentation {
        id: "fit",
        glyph: "\u{26F6}",
        ribbon_path: "View/Navigation/Zoom to fit",
        size: CommandSize::Large,
    },
    CommandPresentation {
        id: "help",
        glyph: "\u{2753}",
        ribbon_path: "Help/Support/Help",
        size: CommandSize::Large,
    },
    CommandPresentation {
        id: "info",
        glyph: "\u{2139}",
        ribbon_path: "Help/Support/Info",
        size: CommandSize::Compact,
    },
    CommandPresentation {
        id: "bug",
        glyph: "\u{1F41E}",
        ribbon_path: "Help/Support/Submit Bug",
        size: CommandSize::Compact,
    },
];

pub(crate) fn adapt_button(button: &WorkbenchButton, state: &ButtonState) -> OfferedCommand {
    let mut c = static_command(button.presentation(), CommandTarget::Workbench(button.id));
    c.pressed = button.is_pressed(state);
    c.toggle = button.pressed.is_some();
    c.disabled_reason = button.disabled_reason(state).map(str::to_owned);
    c.detail = button.detail(state);
    c.menu = button
        .menu
        .iter()
        .filter(|b| b.offered(state))
        .map(|b| adapt_button(b, state))
        .collect();
    c
}

/// Canonical feature command text for text-and-icon surfaces such as palettes.
pub fn feature_command_label(feature: &serde_json::Value) -> String {
    let ty = feature["type"].as_str().unwrap_or("");
    let label = feature["ribbonPath"]
        .as_str()
        .and_then(|p| p.rsplit('/').next())
        .or(feature["longName"].as_str())
        .or(feature["label"].as_str())
        .unwrap_or(ty);
    let glyph = brep_render::features::feature_icon(ty)
        .map(|g| g.to_string())
        .or_else(|| feature["icon"].as_str().map(str::to_owned));
    glyph.map_or_else(|| label.to_owned(), |g| format!("{g} {label}"))
}

/// The same Home descriptors feed the Classic strip and Ribbon. Order is catalogue order.
pub fn offered_home_commands(engine: &EngineState) -> Vec<OfferedCommand> {
    if !engine.settings.show_workbench_toolbar || engine.any_sketch_mode() || engine.ref_select_modal()
    {
        return vec![];
    }
    // A FORM FIELD's reference pick keeps the strip drawn (the dock stays, so
    // the layout must not jump) but nothing on it may run: a new feature's
    // form would replace the one being picked into.
    let picking = engine.ref_select_active();
    let mut commands = offered_home_commands_unchecked(engine);
    if picking {
        for command in &mut commands {
            command.disabled_reason = Some(PICKING_DISABLED.into());
        }
    }
    commands
}

/// Why every creation command is disabled while a form field's reference
/// pick runs.
pub const PICKING_DISABLED: &str = "Finish picking the reference first (Done on its field, or Escape)";

/// [`offered_home_commands`] before its mode gate: the catalogue's offer for
/// the active workbench.
fn offered_home_commands_unchecked(engine: &EngineState) -> Vec<OfferedCommand> {
    let active = &engine.settings.workbench;
    let dynamic = super::owned_workbenches(engine);
    let active_owned = dynamic.iter().find(|w| w.id == *active);
    let mut commands = vec![];
    let catalogue = engine.feature_catalogue();
    for f in catalogue["features"].as_array().into_iter().flatten() {
        let Some(ty) = f["type"].as_str() else {
            continue;
        };
        if !active_owned.map_or_else(
            || super::includes_feature(active, ty),
            |w| w.feature_types.iter().any(|f| f == ty),
        ) {
            continue;
        }
        // Older runtime plugins are adapted at this boundary; built-ins declare paths in their schemas.
        let label = f["label"].as_str().or(f["longName"].as_str()).unwrap_or(ty);
        let path = f["ribbonPath"]
            .as_str()
            .map(str::to_owned)
            .unwrap_or_else(|| format!("Home/Extensions/{}", label.replace('/', " ")));
        commands.push(OfferedCommand {
            id: format!("feature:{ty}"),
            glyph: brep_render::features::feature_icon(ty)
                .map(|glyph| glyph.to_string())
                .or_else(|| f["icon"].as_str().map(str::to_owned))
                .unwrap_or_else(|| ty.into()),
            ribbon_path: path,
            size: if f["commandSize"] == "Compact" {
                CommandSize::Compact
            } else {
                CommandSize::Large
            },
            target: CommandTarget::Feature(ty.into()),
            pressed: false,
            toggle: false,
            disabled_reason: None,
            detail: format!("Add {label}"),
            menu: vec![],
        });
    }
    let state = ButtonState::of(engine);
    if super::panel_visible(active, super::assembly::CONSTRAINTS_PANEL_ID, &state) {
        for d in brep_render::brep_kernel::CONSTRAINT_TYPES {
            commands.push(creation(
                format!("constraint:{}", d.type_id),
                d.icon,
                format!("Home/Constraints/{}", d.label),
                CommandTarget::Constraint(d.type_id.into()),
            ));
        }
    }
    if super::panel_visible(active, super::pmi::PANEL_ID, &state) {
        for d in brep_render::brep_kernel::PMI_TYPES {
            commands.push(creation(
                format!("annotation:{}", d.type_id),
                d.icon,
                format!("Home/Annotations/{}", d.label),
                CommandTarget::Annotation(d.type_id.into()),
            ));
        }
    }
    // The Reference group leads the home commands: the catalogue lists its
    // features in two runs (Datium and Plane, then Sketch, Spline, Waypoint
    // and Helix after the Primitives), and the group is shown as one block
    // directly after Undo (`place_reference_after_undo`), so the creation
    // order here is the order the toolbar draws.
    let (reference, rest): (Vec<_>, Vec<_>) = commands.into_iter().partition(|c| {
        let s = c.segments();
        s[0] == "Home" && s[1] == "Reference"
    });
    reference.into_iter().chain(rest).collect()
}
fn creation(id: String, glyph: &str, path: String, target: CommandTarget) -> OfferedCommand {
    let label = path.rsplit('/').next().unwrap_or("");
    let detail = match &target {
        CommandTarget::Constraint(_) => format!("Add {label} constraint from the selection"),
        CommandTarget::Annotation(_) => format!(
            "Add a {} to the active view, from the selection",
            label.to_lowercase()
        ),
        _ => String::new(),
    };
    OfferedCommand {
        id,
        glyph: glyph.into(),
        ribbon_path: path,
        size: CommandSize::Compact,
        target,
        pressed: false,
        toggle: false,
        disabled_reason: None,
        detail,
        menu: vec![],
    }
}

pub fn offered_commands(state: &ButtonState, info_open: bool) -> Vec<OfferedCommand> {
    #[cfg(debug_assertions)]
    {
        static VALIDATED: std::sync::OnceLock<()> = std::sync::OnceLock::new();
        VALIDATED.get_or_init(|| {
            validate_builtin_presentations().expect("invalid built-in command registry")
        });
    }
    let engine = state.engine;
    let mut commands: Vec<_> = FILE_COMMANDS
        .iter()
        .filter(|p| p.id.starts_with("file:"))
        .chain(SHELL_COMMANDS)
        .map(|p| {
            let mut c = static_command(*p, CommandTarget::Shell(p.id));
            c.toggle = matches!(
                p.id,
                "wireframe" | "projection" | "show:faces" | "show:edges" | "show:vertices" | "info"
            );
            c.pressed = match p.id {
                "wireframe" => engine.settings.wireframe,
                "projection" => matches!(
                    engine.camera.projection,
                    brep_render::view::Projection::Perspective { .. }
                ),
                "show:faces" => engine.settings.show_faces,
                "show:edges" => engine.settings.show_edges,
                "show:vertices" => engine.settings.show_vertices,
                "info" => info_open,
                _ => false,
            };
            let unavailable = match p.id {
                "undo" => {
                    !(if engine.sketch_mode() {
                        engine.sketch_can_undo()
                    } else if engine.sketch3d_mode() {
                        engine.sketch3d_can_undo()
                    } else {
                        engine.can_undo()
                    })
                }
                "redo" => {
                    !(if engine.sketch_mode() {
                        engine.sketch_can_redo()
                    } else if engine.sketch3d_mode() {
                        engine.sketch3d_can_redo()
                    } else {
                        engine.can_redo()
                    })
                }
                _ => false,
            };
            if unavailable {
                c.disabled_reason = Some("No history step available".into());
            }
            match p.id {
                "undo" if engine.any_sketch_mode() => c.detail = "Undo sketch edit (Ctrl+Z)".into(),
                "redo" if engine.any_sketch_mode() => c.detail = "Redo sketch edit (Ctrl+Y)".into(),
                "fit" if engine.sheet_open().is_some() => {
                    c.detail = "Zoom to fit (the open sheet's paper)".into()
                }
                "info" => c.detail = "Info (licences and diagnostics)".into(),
                _ => {}
            }
            if p.id == "projection" {
                c.detail = if c.pressed {
                    "Perspective projection"
                } else {
                    "Orthographic projection"
                }
                .into();
            }
            c
        })
        .collect();
    commands.extend(
        super::offered_buttons(&engine.settings.workbench, state)
            .into_iter()
            .map(|b| adapt_button(b, state)),
    );
    for a in super::plugin_actions(engine, &engine.settings.workbench) {
        let Some(id) = a["id"].as_str() else { continue };
        let label = a["label"].as_str().unwrap_or(id);
        commands.push(OfferedCommand {
            id: id.into(),
            glyph: a["glyph"].as_str().unwrap_or("\u{2699}").into(),
            ribbon_path: a["ribbonPath"]
                .as_str()
                .map(str::to_owned)
                .unwrap_or_else(|| format!("Home/Extensions/{}", label.replace('/', " "))),
            size: if a["commandSize"] == "Large" {
                CommandSize::Large
            } else {
                CommandSize::Compact
            },
            target: CommandTarget::Plugin(id.into()),
            pressed: false,
            toggle: false,
            disabled_reason: None,
            detail: label.into(),
            menu: vec![],
        });
    }
    commands.extend(offered_home_commands(engine));
    place_reference_after_undo(&mut commands);
    debug_assert!(
        validate_commands(&commands).is_ok(),
        "invalid command registry: {:?}",
        validate_commands(&commands)
    );
    commands
}

/// The Reference group sits directly after Undo in every workbench. A
/// workbench's own buttons (the Sheet Metal and Assembly groups) are declared
/// before the feature catalogue, which is where Reference comes from, so
/// without this they would push Reference behind them. Commands keep their
/// relative order; only the Reference ones move.
fn place_reference_after_undo(commands: &mut Vec<OfferedCommand>) {
    let in_group = |c: &OfferedCommand, group: &str| {
        let s = c.segments();
        s[0] == "Home" && s[1] == group
    };
    if !commands.iter().any(|c| in_group(c, "Undo")) {
        return;
    }
    let (reference, mut rest): (Vec<_>, Vec<_>) = std::mem::take(commands)
        .into_iter()
        .partition(|c| in_group(c, "Reference"));
    let insert = rest
        .iter()
        .rposition(|c| in_group(c, "Undo"))
        .map_or(rest.len(), |i| i + 1);
    rest.splice(insert..insert, reference);
    *commands = rest;
}

/// Groups are derived in first-declaration order; commands retain source order within them.
pub fn command_groups<'a>(
    commands: &'a [OfferedCommand],
    tab: &str,
) -> Vec<(&'a str, Vec<&'a OfferedCommand>)> {
    let mut groups: Vec<(&str, Vec<&OfferedCommand>)> = vec![];
    for c in commands.iter().filter(|c| c.segments()[0] == tab) {
        let group = c.segments()[1];
        if let Some((_, members)) = groups.iter_mut().find(|(name, _)| *name == group) {
            members.push(c);
        } else {
            groups.push((group, vec![c]));
        }
    }
    groups
}

/// Validate all declarations, including commands not currently offered.
pub fn validate_builtin_presentations() -> Result<(), String> {
    let mut seen = std::collections::HashSet::new();
    let catalogue = brep_render::features::feature_catalogue();
    for p in FILE_COMMANDS
        .iter()
        .chain(NEW_DOCUMENT_COMMANDS)
        .chain(SHELL_COMMANDS)
        .copied()
        .chain(super::every_button_in(super::WORKBENCHES).map(|b| b.presentation()))
    {
        ribbon_segments(p.ribbon_path)?;
        if !seen.insert(p.id.to_owned()) {
            return Err(format!("duplicate command id: {}", p.id));
        }
    }
    for feature in catalogue["features"].as_array().into_iter().flatten() {
        let path = feature["ribbonPath"]
            .as_str()
            .ok_or_else(|| format!("feature has no ribbonPath: {}", feature["type"]))?;
        if ribbon_segments(path)?[0] != "Home" {
            return Err(format!("feature outside Home: {path}"));
        }
        if !matches!(feature["commandSize"].as_str(), Some("Large" | "Compact")) {
            return Err(format!("feature has no commandSize: {path}"));
        }
        let ty = feature["type"].as_str().ok_or("feature has no type")?;
        if !seen.insert(format!("feature:{ty}")) {
            return Err(format!("duplicate feature type: {ty}"));
        }
    }
    Ok(())
}