1use super::{ButtonState, WorkbenchButton};
3use brep_render::engine_state::EngineState;
4
5pub const RIBBON_TABS: [&str; 5] = ["Home", super::welding::TAB, super::pmi::TAB, "View", "Help"];
8
9const OPTIONAL_TABS: [&str; 2] = [super::welding::TAB, super::pmi::TAB];
11
12pub fn ribbon_tab_shown(tab: &str, commands: &[OfferedCommand]) -> bool {
15 !OPTIONAL_TABS.contains(&tab) || commands.iter().any(|c| c.segments()[0] == tab)
16}
17
18pub const CREATION_TABS: [&str; 3] = ["Home", super::welding::TAB, super::pmi::TAB];
21
22pub 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#[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 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
141pub 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 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
206pub 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
319pub 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
334pub 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 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
354pub const PICKING_DISABLED: &str = "Finish picking the reference first (Done on its field, or Escape)";
357
358fn 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 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 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 debug_assert!(
564 validate_commands(&commands).is_ok(),
565 "invalid command registry: {:?}",
566 validate_commands(&commands)
567 );
568 commands
569}
570
571fn place_reference_after_undo(commands: &mut Vec<OfferedCommand>) {
577 let in_group = |c: &OfferedCommand, group: &str| {
578 let s = c.segments();
579 s[0] == "Home" && s[1] == group
580 };
581 if !commands.iter().any(|c| in_group(c, "Undo")) {
582 return;
583 }
584 let (reference, mut rest): (Vec<_>, Vec<_>) = std::mem::take(commands)
585 .into_iter()
586 .partition(|c| in_group(c, "Reference"));
587 let insert = rest
588 .iter()
589 .rposition(|c| in_group(c, "Undo"))
590 .map_or(rest.len(), |i| i + 1);
591 rest.splice(insert..insert, reference);
592 *commands = rest;
593}
594
595pub fn command_groups<'a>(
597 commands: &'a [OfferedCommand],
598 tab: &str,
599) -> Vec<(&'a str, Vec<&'a OfferedCommand>)> {
600 let mut groups: Vec<(&str, Vec<&OfferedCommand>)> = vec![];
601 for c in commands.iter().filter(|c| c.segments()[0] == tab) {
602 let group = c.segments()[1];
603 if let Some((_, members)) = groups.iter_mut().find(|(name, _)| *name == group) {
604 members.push(c);
605 } else {
606 groups.push((group, vec![c]));
607 }
608 }
609 groups
610}
611
612pub fn validate_builtin_presentations() -> Result<(), String> {
614 let mut seen = std::collections::HashSet::new();
615 let catalogue = brep_render::features::feature_catalogue();
616 for p in FILE_COMMANDS
617 .iter()
618 .chain(NEW_DOCUMENT_COMMANDS)
619 .chain(SHELL_COMMANDS)
620 .copied()
621 .chain(super::every_button_in(super::WORKBENCHES).map(|b| b.presentation()))
622 {
623 ribbon_segments(p.ribbon_path)?;
624 if !seen.insert(p.id.to_owned()) {
625 return Err(format!("duplicate command id: {}", p.id));
626 }
627 }
628 for feature in catalogue["features"].as_array().into_iter().flatten() {
629 let path = feature["ribbonPath"]
630 .as_str()
631 .ok_or_else(|| format!("feature has no ribbonPath: {}", feature["type"]))?;
632 let ty = feature["type"].as_str().unwrap_or("");
634 let tab = if super::welding::is_weld_type(ty) { super::welding::TAB } else { "Home" };
635 if ribbon_segments(path)?[0] != tab {
636 return Err(format!("feature outside {tab}: {path}"));
637 }
638 if !matches!(feature["commandSize"].as_str(), Some("Large" | "Compact")) {
639 return Err(format!("feature has no commandSize: {path}"));
640 }
641 let ty = feature["type"].as_str().ok_or("feature has no type")?;
642 if !seen.insert(format!("feature:{ty}")) {
643 return Err(format!("duplicate feature type: {ty}"));
644 }
645 }
646 Ok(())
647}
648