Skip to main content

brep_app/workbench/
commands.rs

1//! Renderer-neutral command snapshots. Availability and dispatch belong to their owners.
2use super::{ButtonState, WorkbenchButton};
3use brep_render::engine_state::EngineState;
4
5/// The Ribbon's tabs, in strip order. "PMI" is drawn only where a PMI command
6/// is offered ([`ribbon_tab_shown`]); the others always.
7pub const RIBBON_TABS: [&str; 4] = ["Home", super::pmi::TAB, "View", "Help"];
8
9/// Whether the Ribbon draws `tab` for this command list: the PMI tab exists
10/// only in a workbench that offers PMI commands.
11pub fn ribbon_tab_shown(tab: &str, commands: &[OfferedCommand]) -> bool {
12    tab != super::pmi::TAB || commands.iter().any(|c| c.segments()[0] == tab)
13}
14
15/// The tabs whose creation commands the Classic strip draws, in order: it has
16/// no tab strip, so the PMI tab's groups follow Home's.
17pub const CREATION_TABS: [&str; 2] = ["Home", super::pmi::TAB];
18
19/// [`command_groups`] over every creation tab: what the Classic strip draws.
20pub fn creation_groups(commands: &[OfferedCommand]) -> Vec<(&str, Vec<&OfferedCommand>)> {
21    CREATION_TABS.iter().flat_map(|tab| command_groups(commands, tab)).collect()
22}
23
24#[derive(Clone, Copy, Debug, PartialEq, Eq)]
25pub enum CommandSize {
26    Large,
27    Compact,
28}
29
30/// Built-ins borrow static strings; runtime adapters borrow their owned metadata.
31#[derive(Clone, Copy, Debug)]
32pub struct CommandPresentation<'a> {
33    pub id: &'a str,
34    pub glyph: &'a str,
35    pub ribbon_path: &'a str,
36    pub size: CommandSize,
37}
38impl<'a> CommandPresentation<'a> {
39    pub fn label(&self) -> &'a str {
40        self.ribbon_path.rsplit('/').next().unwrap_or("")
41    }
42}
43
44pub fn ribbon_segments(path: &str) -> Result<[&str; 3], String> {
45    let parts: Vec<_> = path.split('/').collect();
46    if parts.len() != 3 || parts.iter().any(|p| p.trim().is_empty() || p.trim() != *p) {
47        return Err(format!("invalid ribbon path: {path:?}"));
48    }
49    if !RIBBON_TABS.contains(&parts[0]) {
50        return Err(format!("unknown ribbon tab: {}", parts[0]));
51    }
52    Ok([parts[0], parts[1], parts[2]])
53}
54
55#[derive(Clone, Debug, PartialEq, Eq)]
56pub enum CommandTarget {
57    Shell(&'static str),
58    Workbench(&'static str),
59    Plugin(String),
60    Feature(String),
61    Constraint(String),
62    Annotation(String),
63}
64
65#[derive(Clone, Debug)]
66pub struct OfferedCommand {
67    pub id: String,
68    pub glyph: String,
69    pub ribbon_path: String,
70    pub size: CommandSize,
71    pub target: CommandTarget,
72    pub pressed: bool,
73    pub toggle: bool,
74    pub disabled_reason: Option<String>,
75    pub detail: String,
76    pub menu: Vec<OfferedCommand>,
77}
78impl OfferedCommand {
79    pub fn presentation(&self) -> CommandPresentation<'_> {
80        CommandPresentation {
81            id: &self.id,
82            glyph: &self.glyph,
83            ribbon_path: &self.ribbon_path,
84            size: self.size,
85        }
86    }
87    pub fn segments(&self) -> [&str; 3] {
88        ribbon_segments(self.presentation().ribbon_path).expect("validated command path")
89    }
90    pub fn label(&self) -> &str {
91        self.presentation().label()
92    }
93    pub fn is_home(&self) -> bool {
94        self.segments()[0] == "Home"
95    }
96    /// A creation command: Classic draws these on its creation strip, and
97    /// everything else (File, Undo, actions, tools) on its primary row.
98    pub fn is_creation(&self) -> bool {
99        matches!(
100            self.target,
101            CommandTarget::Feature(_) | CommandTarget::Constraint(_) | CommandTarget::Annotation(_)
102        )
103    }
104}
105
106pub fn validate_commands(commands: &[OfferedCommand]) -> Result<(), String> {
107    fn visit(
108        commands: &[OfferedCommand],
109        ids: &mut std::collections::HashSet<String>,
110    ) -> Result<(), String> {
111        for command in commands {
112            ribbon_segments(&command.ribbon_path)?;
113            if command.id.is_empty() || !ids.insert(command.id.clone()) {
114                return Err(format!("duplicate or empty command id: {}", command.id));
115            }
116            visit(&command.menu, ids)?;
117        }
118        Ok(())
119    }
120    visit(commands, &mut Default::default())
121}
122
123fn static_command(p: CommandPresentation<'static>, target: CommandTarget) -> OfferedCommand {
124    OfferedCommand {
125        id: p.id.into(),
126        glyph: p.glyph.into(),
127        ribbon_path: p.ribbon_path.into(),
128        size: p.size,
129        target,
130        pressed: false,
131        toggle: false,
132        disabled_reason: None,
133        detail: p.label().into(),
134        menu: vec![],
135    }
136}
137
138/// File commands share metadata; Properties and Settings are offered only in File.
139pub const FILE_COMMANDS: &[CommandPresentation<'static>] = &[
140    CommandPresentation {
141        id: "file:new",
142        glyph: "\u{E010}",
143        ribbon_path: "Home/File/New",
144        size: CommandSize::Large,
145    },
146    CommandPresentation {
147        id: "file:open",
148        glyph: "\u{E011}",
149        ribbon_path: "Home/File/Open",
150        size: CommandSize::Large,
151    },
152    CommandPresentation {
153        id: "file:save",
154        glyph: "\u{E012}",
155        ribbon_path: "Home/File/Save",
156        size: CommandSize::Large,
157    },
158    CommandPresentation {
159        id: "file:saveas",
160        glyph: "\u{E013}",
161        ribbon_path: "Home/File/Save As",
162        size: CommandSize::Compact,
163    },
164    CommandPresentation {
165        id: "file:import",
166        glyph: "\u{E014}",
167        ribbon_path: "Home/File/Import",
168        size: CommandSize::Compact,
169    },
170    CommandPresentation {
171        id: "file:export",
172        glyph: "\u{E015}",
173        ribbon_path: "Home/File/Export",
174        size: CommandSize::Compact,
175    },
176    CommandPresentation {
177        id: "properties",
178        glyph: "\u{E066}",
179        ribbon_path: "Home/File/Document Properties",
180        size: CommandSize::Compact,
181    },
182    CommandPresentation {
183        id: "settings",
184        glyph: "\u{2699}",
185        ribbon_path: "Home/File/Settings",
186        size: CommandSize::Compact,
187    },
188    // Plugin management lives under Settings in the File menu, in both styles.
189    CommandPresentation {
190        id: "workbench:manage:plugins",
191        glyph: "\u{2699}",
192        ribbon_path: "Home/File/Plugins",
193        size: CommandSize::Compact,
194    },
195    CommandPresentation {
196        id: "workbench:manage:javascript",
197        glyph: "\u{270E}",
198        ribbon_path: "Home/File/JavaScript",
199        size: CommandSize::Compact,
200    },
201];
202
203/// Flat New rows in DocumentClass::ALL order.
204pub const NEW_DOCUMENT_COMMANDS: &[CommandPresentation<'static>] = &[
205    CommandPresentation {
206        id: "file:newclass:normal",
207        glyph: "\u{E010}",
208        ribbon_path: "Home/File/New part",
209        size: CommandSize::Compact,
210    },
211    CommandPresentation {
212        id: "file:newclass:family",
213        glyph: "\u{E010}",
214        ribbon_path: "Home/File/New family",
215        size: CommandSize::Compact,
216    },
217    CommandPresentation {
218        id: "file:newclass:template",
219        glyph: "\u{E010}",
220        ribbon_path: "Home/File/New template",
221        size: CommandSize::Compact,
222    },
223];
224
225pub fn file_presentation(id: &str) -> CommandPresentation<'static> {
226    *FILE_COMMANDS
227        .iter()
228        .find(|c| c.id == id)
229        .expect("File command is declared")
230}
231
232pub const SHELL_COMMANDS: &[CommandPresentation<'static>] = &[
233    CommandPresentation {
234        id: "undo",
235        glyph: "\u{E016}",
236        ribbon_path: "Home/Undo/Undo",
237        size: CommandSize::Compact,
238    },
239    CommandPresentation {
240        id: "redo",
241        glyph: "\u{E017}",
242        ribbon_path: "Home/Undo/Redo",
243        size: CommandSize::Compact,
244    },
245    CommandPresentation {
246        id: "wireframe",
247        glyph: "\u{1F578}",
248        ribbon_path: "View/Display/Wireframe",
249        size: CommandSize::Compact,
250    },
251    CommandPresentation {
252        id: "projection",
253        glyph: "\u{E018}",
254        ribbon_path: "View/Display/Projection",
255        size: CommandSize::Compact,
256    },
257    CommandPresentation {
258        id: "show:faces",
259        glyph: "\u{E028}",
260        ribbon_path: "View/Display/Show faces",
261        size: CommandSize::Compact,
262    },
263    CommandPresentation {
264        id: "show:edges",
265        glyph: "\u{E029}",
266        ribbon_path: "View/Display/Show edges",
267        size: CommandSize::Compact,
268    },
269    CommandPresentation {
270        id: "show:vertices",
271        glyph: "\u{E02A}",
272        ribbon_path: "View/Display/Show vertices",
273        size: CommandSize::Compact,
274    },
275    CommandPresentation {
276        id: "fit",
277        glyph: "\u{26F6}",
278        ribbon_path: "View/Navigation/Zoom to fit",
279        size: CommandSize::Large,
280    },
281    CommandPresentation {
282        id: "help",
283        glyph: "\u{2753}",
284        ribbon_path: "Help/Support/Help",
285        size: CommandSize::Large,
286    },
287    CommandPresentation {
288        id: "info",
289        glyph: "\u{2139}",
290        ribbon_path: "Help/Support/Info",
291        size: CommandSize::Compact,
292    },
293    CommandPresentation {
294        id: "bug",
295        glyph: "\u{1F41E}",
296        ribbon_path: "Help/Support/Submit Bug",
297        size: CommandSize::Compact,
298    },
299];
300
301pub(crate) fn adapt_button(button: &WorkbenchButton, state: &ButtonState) -> OfferedCommand {
302    let mut c = static_command(button.presentation(), CommandTarget::Workbench(button.id));
303    c.pressed = button.is_pressed(state);
304    c.toggle = button.pressed.is_some();
305    c.disabled_reason = button.disabled_reason(state).map(str::to_owned);
306    c.detail = button.detail(state);
307    c.menu = button
308        .menu
309        .iter()
310        .filter(|b| b.offered(state))
311        .map(|b| adapt_button(b, state))
312        .collect();
313    c
314}
315
316/// Canonical feature command text for text-and-icon surfaces such as palettes.
317pub fn feature_command_label(feature: &serde_json::Value) -> String {
318    let ty = feature["type"].as_str().unwrap_or("");
319    let label = feature["ribbonPath"]
320        .as_str()
321        .and_then(|p| p.rsplit('/').next())
322        .or(feature["longName"].as_str())
323        .or(feature["label"].as_str())
324        .unwrap_or(ty);
325    let glyph = brep_render::features::feature_icon(ty)
326        .map(|g| g.to_string())
327        .or_else(|| feature["icon"].as_str().map(str::to_owned));
328    glyph.map_or_else(|| label.to_owned(), |g| format!("{g} {label}"))
329}
330
331/// The same creation descriptors feed the Classic strip and Ribbon (Home, and
332/// the PMI tab's annotation commands). Order is catalogue order.
333pub fn offered_home_commands(engine: &EngineState) -> Vec<OfferedCommand> {
334    if !engine.settings.show_workbench_toolbar || engine.any_sketch_mode() || engine.ref_select_modal()
335    {
336        return vec![];
337    }
338    // A FORM FIELD's reference pick keeps the strip drawn (the dock stays, so
339    // the layout must not jump) but nothing on it may run: a new feature's
340    // form would replace the one being picked into.
341    let picking = engine.ref_select_active();
342    let mut commands = offered_home_commands_unchecked(engine);
343    if picking {
344        for command in &mut commands {
345            command.disabled_reason = Some(PICKING_DISABLED.into());
346        }
347    }
348    commands
349}
350
351/// Why every creation command is disabled while a form field's reference
352/// pick runs.
353pub const PICKING_DISABLED: &str = "Finish picking the reference first (Done on its field, or Escape)";
354
355/// [`offered_home_commands`] before its mode gate: the catalogue's offer for
356/// the active workbench.
357fn offered_home_commands_unchecked(engine: &EngineState) -> Vec<OfferedCommand> {
358    let active = &engine.settings.workbench;
359    let dynamic = super::owned_workbenches(engine);
360    let active_owned = dynamic.iter().find(|w| w.id == *active);
361    let mut commands = vec![];
362    let catalogue = engine.feature_catalogue();
363    for f in catalogue["features"].as_array().into_iter().flatten() {
364        let Some(ty) = f["type"].as_str() else {
365            continue;
366        };
367        if !active_owned.map_or_else(
368            || super::includes_feature(active, ty),
369            |w| w.feature_types.iter().any(|f| f == ty),
370        ) {
371            continue;
372        }
373        // Older runtime plugins are adapted at this boundary; built-ins declare paths in their schemas.
374        let label = f["label"].as_str().or(f["longName"].as_str()).unwrap_or(ty);
375        let path = f["ribbonPath"]
376            .as_str()
377            .map(str::to_owned)
378            .unwrap_or_else(|| format!("Home/Extensions/{}", label.replace('/', " ")));
379        commands.push(OfferedCommand {
380            id: format!("feature:{ty}"),
381            glyph: brep_render::features::feature_icon(ty)
382                .map(|glyph| glyph.to_string())
383                .or_else(|| f["icon"].as_str().map(str::to_owned))
384                .unwrap_or_else(|| ty.into()),
385            ribbon_path: path,
386            size: if f["commandSize"] == "Compact" {
387                CommandSize::Compact
388            } else {
389                CommandSize::Large
390            },
391            target: CommandTarget::Feature(ty.into()),
392            pressed: false,
393            toggle: false,
394            disabled_reason: None,
395            detail: format!("Add {label}"),
396            menu: vec![],
397        });
398    }
399    let state = ButtonState::of(engine);
400    if super::panel_visible(active, super::assembly::CONSTRAINTS_PANEL_ID, &state) {
401        for d in brep_render::brep_kernel::CONSTRAINT_TYPES {
402            commands.push(creation(
403                format!("constraint:{}", d.type_id),
404                d.icon,
405                format!("Home/Constraints/{}", d.label),
406                CommandTarget::Constraint(d.type_id.into()),
407            ));
408        }
409    }
410    if super::panel_visible(active, super::pmi::PANEL_ID, &state) {
411        for d in brep_render::brep_kernel::PMI_TYPES {
412            commands.push(creation(
413                format!("annotation:{}", d.type_id),
414                d.icon,
415                format!("{}/{}/{}", super::pmi::TAB, super::pmi::group_of(d.type_id), d.label),
416                CommandTarget::Annotation(d.type_id.into()),
417            ));
418        }
419    }
420    // The Reference group leads the home commands: the catalogue lists its
421    // features in two runs (Datium and Plane, then Sketch, Spline, Waypoint
422    // and Helix after the Primitives), and the group is shown as one block
423    // directly after Undo (`place_reference_after_undo`), so the creation
424    // order here is the order the toolbar draws.
425    let (reference, rest): (Vec<_>, Vec<_>) = commands.into_iter().partition(|c| {
426        let s = c.segments();
427        s[0] == "Home" && s[1] == "Reference"
428    });
429    reference.into_iter().chain(rest).collect()
430}
431fn creation(id: String, glyph: &str, path: String, target: CommandTarget) -> OfferedCommand {
432    let label = path.rsplit('/').next().unwrap_or("");
433    let detail = match &target {
434        CommandTarget::Constraint(_) => format!("Add {label} constraint from the selection"),
435        CommandTarget::Annotation(_) => format!(
436            "Add a {} to the active view, from the selection",
437            label.to_lowercase()
438        ),
439        _ => String::new(),
440    };
441    OfferedCommand {
442        id,
443        glyph: glyph.into(),
444        ribbon_path: path,
445        size: CommandSize::Compact,
446        target,
447        pressed: false,
448        toggle: false,
449        disabled_reason: None,
450        detail,
451        menu: vec![],
452    }
453}
454
455pub fn offered_commands(state: &ButtonState, info_open: bool) -> Vec<OfferedCommand> {
456    #[cfg(debug_assertions)]
457    {
458        static VALIDATED: std::sync::OnceLock<()> = std::sync::OnceLock::new();
459        VALIDATED.get_or_init(|| {
460            validate_builtin_presentations().expect("invalid built-in command registry")
461        });
462    }
463    let engine = state.engine;
464    let mut commands: Vec<_> = FILE_COMMANDS
465        .iter()
466        .filter(|p| p.id.starts_with("file:"))
467        .chain(SHELL_COMMANDS)
468        .map(|p| {
469            let mut c = static_command(*p, CommandTarget::Shell(p.id));
470            c.toggle = matches!(
471                p.id,
472                "wireframe" | "projection" | "show:faces" | "show:edges" | "show:vertices" | "info"
473            );
474            c.pressed = match p.id {
475                "wireframe" => engine.settings.wireframe,
476                "projection" => matches!(
477                    engine.camera.projection,
478                    brep_render::view::Projection::Perspective { .. }
479                ),
480                "show:faces" => engine.settings.show_faces,
481                "show:edges" => engine.settings.show_edges,
482                "show:vertices" => engine.settings.show_vertices,
483                "info" => info_open,
484                _ => false,
485            };
486            let unavailable = match p.id {
487                "undo" => {
488                    !(if engine.sketch_mode() {
489                        engine.sketch_can_undo()
490                    } else if engine.sketch3d_mode() {
491                        engine.sketch3d_can_undo()
492                    } else {
493                        engine.can_undo()
494                    })
495                }
496                "redo" => {
497                    !(if engine.sketch_mode() {
498                        engine.sketch_can_redo()
499                    } else if engine.sketch3d_mode() {
500                        engine.sketch3d_can_redo()
501                    } else {
502                        engine.can_redo()
503                    })
504                }
505                _ => false,
506            };
507            if unavailable {
508                c.disabled_reason = Some("No history step available".into());
509            }
510            match p.id {
511                "undo" if engine.any_sketch_mode() => c.detail = "Undo sketch edit (Ctrl+Z)".into(),
512                "redo" if engine.any_sketch_mode() => c.detail = "Redo sketch edit (Ctrl+Y)".into(),
513                "fit" if engine.sheet_open().is_some() => {
514                    c.detail = "Zoom to fit (the open sheet's paper)".into()
515                }
516                "info" => c.detail = "Info (licences and diagnostics)".into(),
517                _ => {}
518            }
519            if p.id == "projection" {
520                c.detail = if c.pressed {
521                    "Perspective projection"
522                } else {
523                    "Orthographic projection"
524                }
525                .into();
526            }
527            c
528        })
529        .collect();
530    commands.extend(
531        super::offered_buttons(&engine.settings.workbench, state)
532            .into_iter()
533            .map(|b| adapt_button(b, state)),
534    );
535    for a in super::plugin_actions(engine, &engine.settings.workbench) {
536        let Some(id) = a["id"].as_str() else { continue };
537        let label = a["label"].as_str().unwrap_or(id);
538        commands.push(OfferedCommand {
539            id: id.into(),
540            glyph: a["glyph"].as_str().unwrap_or("\u{2699}").into(),
541            ribbon_path: a["ribbonPath"]
542                .as_str()
543                .map(str::to_owned)
544                .unwrap_or_else(|| format!("Home/Extensions/{}", label.replace('/', " "))),
545            size: if a["commandSize"] == "Large" {
546                CommandSize::Large
547            } else {
548                CommandSize::Compact
549            },
550            target: CommandTarget::Plugin(id.into()),
551            pressed: false,
552            toggle: false,
553            disabled_reason: None,
554            detail: label.into(),
555            menu: vec![],
556        });
557    }
558    commands.extend(offered_home_commands(engine));
559    place_reference_after_undo(&mut commands);
560    debug_assert!(
561        validate_commands(&commands).is_ok(),
562        "invalid command registry: {:?}",
563        validate_commands(&commands)
564    );
565    commands
566}
567
568/// The Reference group sits directly after Undo in every workbench. A
569/// workbench's own buttons (the Sheet Metal and Assembly groups) are declared
570/// before the feature catalogue, which is where Reference comes from, so
571/// without this they would push Reference behind them. Commands keep their
572/// relative order; only the Reference ones move.
573fn place_reference_after_undo(commands: &mut Vec<OfferedCommand>) {
574    let in_group = |c: &OfferedCommand, group: &str| {
575        let s = c.segments();
576        s[0] == "Home" && s[1] == group
577    };
578    if !commands.iter().any(|c| in_group(c, "Undo")) {
579        return;
580    }
581    let (reference, mut rest): (Vec<_>, Vec<_>) = std::mem::take(commands)
582        .into_iter()
583        .partition(|c| in_group(c, "Reference"));
584    let insert = rest
585        .iter()
586        .rposition(|c| in_group(c, "Undo"))
587        .map_or(rest.len(), |i| i + 1);
588    rest.splice(insert..insert, reference);
589    *commands = rest;
590}
591
592/// Groups are derived in first-declaration order; commands retain source order within them.
593pub fn command_groups<'a>(
594    commands: &'a [OfferedCommand],
595    tab: &str,
596) -> Vec<(&'a str, Vec<&'a OfferedCommand>)> {
597    let mut groups: Vec<(&str, Vec<&OfferedCommand>)> = vec![];
598    for c in commands.iter().filter(|c| c.segments()[0] == tab) {
599        let group = c.segments()[1];
600        if let Some((_, members)) = groups.iter_mut().find(|(name, _)| *name == group) {
601            members.push(c);
602        } else {
603            groups.push((group, vec![c]));
604        }
605    }
606    groups
607}
608
609/// Validate all declarations, including commands not currently offered.
610pub fn validate_builtin_presentations() -> Result<(), String> {
611    let mut seen = std::collections::HashSet::new();
612    let catalogue = brep_render::features::feature_catalogue();
613    for p in FILE_COMMANDS
614        .iter()
615        .chain(NEW_DOCUMENT_COMMANDS)
616        .chain(SHELL_COMMANDS)
617        .copied()
618        .chain(super::every_button_in(super::WORKBENCHES).map(|b| b.presentation()))
619    {
620        ribbon_segments(p.ribbon_path)?;
621        if !seen.insert(p.id.to_owned()) {
622            return Err(format!("duplicate command id: {}", p.id));
623        }
624    }
625    for feature in catalogue["features"].as_array().into_iter().flatten() {
626        let path = feature["ribbonPath"]
627            .as_str()
628            .ok_or_else(|| format!("feature has no ribbonPath: {}", feature["type"]))?;
629        if ribbon_segments(path)?[0] != "Home" {
630            return Err(format!("feature outside Home: {path}"));
631        }
632        if !matches!(feature["commandSize"].as_str(), Some("Large" | "Compact")) {
633            return Err(format!("feature has no commandSize: {path}"));
634        }
635        let ty = feature["type"].as_str().ok_or("feature has no type")?;
636        if !seen.insert(format!("feature:{ty}")) {
637            return Err(format!("duplicate feature type: {ty}"));
638        }
639    }
640    Ok(())
641}
642