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