diff --git a/Cargo.lock b/Cargo.lock index 081411052..a209115ca 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -996,6 +996,15 @@ dependencies = [ "cfg-if", ] +[[package]] +name = "crossbeam-channel" +version = "0.5.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "98b0cc327b5bc766e7fda9c9260cc0fa81b43a8e240440422dff70788e3f9ef1" +dependencies = [ + "crossbeam-utils", +] + [[package]] name = "crossbeam-deque" version = "0.8.8" @@ -2271,6 +2280,16 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "keyboard-types" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fbe853b403ae61a04233030ae8a79d94975281ed9770a1f9e246732b534b28d" +dependencies = [ + "bitflags 2.13.2", + "serde", +] + [[package]] name = "keyring" version = "3.6.3" @@ -2480,6 +2499,24 @@ dependencies = [ "pxfm", ] +[[package]] +name = "muda" +version = "0.21.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4340e89c178916e62879c5c36b7f699019369be413e496178a6983ce91b8bc03" +dependencies = [ + "crossbeam-channel", + "dpi", + "keyboard-types", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-core-foundation", + "objc2-foundation 0.3.2", + "png", + "thiserror 2.0.21", + "windows-sys 0.61.2", +] + [[package]] name = "multiversion_no_op" version = "1.0.0" @@ -4172,6 +4209,7 @@ dependencies = [ "hidapi", "keyring", "log", + "muda", "objc2 0.6.5", "objc2-app-kit 0.3.2", "objc2-foundation 0.3.2", diff --git a/apps/solidcraft/Cargo.toml b/apps/solidcraft/Cargo.toml index 5078470dd..3eebf7824 100644 --- a/apps/solidcraft/Cargo.toml +++ b/apps/solidcraft/Cargo.toml @@ -70,6 +70,7 @@ windows-sys = { version = "0.61", features = [ ] } [target.'cfg(target_os = "macos")'.dependencies] +muda = { version = "0.21.2", default-features = false } # The 3D mouse through the 3Dconnexion driver, which keeps the device to itself (src/space_mouse.rs). solidcraft-3dx-client = { workspace = true } # The 3D mouse (src/space_mouse.rs), in the shared-device open mode so that a running 3DxWare @@ -78,7 +79,7 @@ hidapi = { version = "2.6.7", default-features = false, features = ["macos-share # Files opened from Finder and the Dock (src/open_documents.rs); all already come with eframe and rfd. objc2 = "0.6" objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "NSApplication", "NSResponder"] } -objc2-foundation = { version = "0.3", default-features = false, features = ["std", "block2", "NSArray", "NSNotification", "NSOperation", "NSString", "NSURL"] } +objc2-foundation = { version = "0.3", default-features = false, features = ["std", "block2", "NSArray", "NSNotification", "NSOperation", "NSProcessInfo", "NSString", "NSURL"] } block2 = "0.6" [target.'cfg(all(unix, not(target_os = "macos")))'.dependencies] diff --git a/apps/solidcraft/src/main.rs b/apps/solidcraft/src/main.rs index 7cbe44253..f5eac643e 100644 --- a/apps/solidcraft/src/main.rs +++ b/apps/solidcraft/src/main.rs @@ -25,6 +25,8 @@ mod native_crash; #[cfg(target_os = "windows")] mod native_frame; #[cfg(target_os = "macos")] +mod native_menu; +#[cfg(target_os = "macos")] mod open_documents; #[cfg(any(target_os = "windows", target_os = "linux", target_os = "macos"))] mod space_mouse; @@ -81,6 +83,8 @@ struct App { gpu: Option, #[cfg(any(target_os = "windows", target_os = "linux", target_os = "macos"))] space_mouse: space_mouse::SpaceMouse, + #[cfg(target_os = "macos")] + native_menu: Option, } impl eframe::App for App { @@ -123,6 +127,10 @@ impl eframe::App for App { for f in if self.solve.file_picker_busy() { Vec::new() } else { open_documents::take() } { self.solve.open_path_async(&f); } + #[cfg(target_os = "macos")] + if let Some(menu) = &mut self.native_menu { + menu.tick(&mut self.solve, ctx); + } self.solve.logic(ctx); #[cfg(any(target_os = "windows", target_os = "linux", target_os = "macos"))] if !self.solve.file_picker_busy() { @@ -133,6 +141,10 @@ impl eframe::App for App { } } fn raw_input_hook(&mut self, _ctx: &egui::Context, raw: &mut egui::RawInput) { + #[cfg(target_os = "macos")] + if let Some(menu) = &mut self.native_menu { + menu.raw_input_hook(&mut self.solve, _ctx, raw); + } // Before the app's own hook, which adds the control channel's events. #[cfg(any(target_os = "windows", target_os = "linux", target_os = "macos"))] self.space_mouse.raw_input_hook(self.solve.preferences.space_mouse_enabled, raw); @@ -556,6 +568,8 @@ fn app_viewport() -> Result { const APP_ID: &str = solidcraft_engine::io::APP_ID; fn main() -> eframe::Result { + #[cfg(target_os = "macos")] + objc2_foundation::NSProcessInfo::processInfo().setProcessName(objc2_foundation::ns_string!("SolidCraft")); mark("main"); adopt_legacy_settings(); let mut safe_mode = startup::env_on(std::env::var(startup::SAFE_MODE_ENV).ok().as_deref()); @@ -779,6 +793,18 @@ fn main() -> eframe::Result { } #[cfg(any(target_os = "windows", target_os = "linux", target_os = "macos"))] let space_mouse = space_mouse::SpaceMouse::start(&cc.egui_ctx); + #[cfg(target_os = "macos")] + let native_menu = match native_menu::NativeMenu::new(&app, &cc.egui_ctx) { + Ok(menu) => Some(menu), + Err(error) => { + app.set_status(format!("System menu: {error}"), true); + None + } + }; + #[cfg(target_os = "macos")] + { + app.native_file_menu = native_menu.is_some(); + } mark("app created"); solidcraft_engine::crash::phase("first frame"); Ok(Box::new(App { @@ -789,6 +815,8 @@ fn main() -> eframe::Result { gpu, #[cfg(any(target_os = "windows", target_os = "linux", target_os = "macos"))] space_mouse, + #[cfg(target_os = "macos")] + native_menu, })) }), ); diff --git a/apps/solidcraft/src/native_menu.rs b/apps/solidcraft/src/native_menu.rs new file mode 100644 index 000000000..02e9d5571 --- /dev/null +++ b/apps/solidcraft/src/native_menu.rs @@ -0,0 +1,189 @@ +//! macOS system menus, owned and updated on eframe's main thread. + +use std::sync::mpsc::{Receiver, sync_channel}; + +use muda::{ + AboutMetadata, Menu, MenuEvent, MenuItem, PredefinedMenuItem, Submenu, + accelerator::{Accelerator, Code, Modifiers}, +}; +use solidcraft_ui_egui::{SolveApp, toolbar::FileAction}; + +pub struct NativeMenu { + menu: Menu, + actions: Vec<(MenuItem, FileAction)>, + help_actions: Vec<(MenuItem, &'static str)>, + events: Receiver, + recent: Submenu, + recent_paths: Vec, +} + +impl NativeMenu { + pub fn new(app: &SolveApp, ctx: &egui::Context) -> muda::Result { + let menu = Menu::new(); + let application = Submenu::new("SolidCraft", true); + let file = Submenu::new(app.tr("ui.file"), true); + let edit = Submenu::new(app.tr_label("Edit"), true); + let recent = Submenu::new(app.tr("ui.open_recent"), true); + let window = Submenu::new("Window", true); + let help = Submenu::new(app.tr("ui.help"), true); + let mut help_actions = Vec::new(); + let mut actions = Vec::new(); + let mut add = |parent: &Submenu, label: &str, action: FileAction, shortcut: Option| -> muda::Result<()> { + let item = MenuItem::new(label, Self::action_enabled(&action, app, ctx), shortcut); + parent.append(&item)?; + actions.push((item, action)); + Ok(()) + }; + application.append(&PredefinedMenuItem::about( + Some("About SolidCraft"), + Some(AboutMetadata { name: Some("SolidCraft".into()), version: Some(env!("CARGO_PKG_VERSION").into()), ..Default::default() }), + ))?; + application.append(&PredefinedMenuItem::separator())?; + add( + &application, + &format!("{}\u{2026}", app.tr("ui.preferences")), + FileAction::Settings, + Some(Accelerator::new(Modifiers::META, Code::Comma)), + )?; + add(&application, &format!("{}\u{2026}", app.tr("ui.keyboard_shortcuts")), FileAction::Shortcuts, None)?; + application.append(&PredefinedMenuItem::separator())?; + application.append(&PredefinedMenuItem::services(None))?; + application.append(&PredefinedMenuItem::separator())?; + application.append_items(&[ + &PredefinedMenuItem::hide(Some("Hide SolidCraft")), + &PredefinedMenuItem::hide_others(None), + &PredefinedMenuItem::show_all(None), + &PredefinedMenuItem::separator(), + ])?; + add(&application, &format!("{} SolidCraft", app.tr("ui.quit")), FileAction::Quit, Some(Accelerator::new(Modifiers::META, Code::KeyQ)))?; + add(&file, app.tr("ui.new_design"), FileAction::New, Some(Accelerator::new(Modifiers::META, Code::KeyN)))?; + add(&file, &format!("{}\u{2026}", app.tr("ui.open")), FileAction::Open, Some(Accelerator::new(Modifiers::META, Code::KeyO)))?; + file.append(&recent)?; + file.append(&PredefinedMenuItem::separator())?; + for (label, command) in + [("Insert STEP\u{2026}", "file.insert_step"), ("Insert Mesh\u{2026}", "file.insert_mesh"), ("Insert Design", "component.insert_design")] + { + add(&file, app.tr_label(label), FileAction::Command(command), None)?; + } + file.append(&PredefinedMenuItem::separator())?; + add(&file, app.tr("ui.save"), FileAction::Save, Some(Accelerator::new(Modifiers::META, Code::KeyS)))?; + add( + &file, + &format!("{}\u{2026}", app.tr("ui.save_as")), + FileAction::SaveAs, + Some(Accelerator::new(Modifiers::META | Modifiers::SHIFT, Code::KeyS)), + )?; + add(&file, app.tr_label("Save As JSON\u{2026}"), FileAction::SaveJson, None)?; + file.append(&PredefinedMenuItem::separator())?; + for (label, action) in [ + ("Export STL\u{2026}", FileAction::ExportMesh("stl")), + ("Export 3MF\u{2026}", FileAction::ExportMesh("3mf")), + ("Export STEP\u{2026}", FileAction::Export("step")), + ("Export Current View as DXF\u{2026}", FileAction::Command("file.export_view_dxf")), + ("Export OBJ\u{2026}", FileAction::Export("obj")), + ("Export URDF\u{2026}", FileAction::Export("urdf")), + ("Export Design as JSON\u{2026}", FileAction::Export("json")), + ] { + add(&file, app.tr_label(label), action, None)?; + } + file.append(&PredefinedMenuItem::separator())?; + add(&file, app.tr_label("Design Properties"), FileAction::Command("document.metadata"), None)?; + add(&edit, app.tr("ui.undo"), FileAction::Undo, Some(Accelerator::new(Modifiers::META, Code::KeyZ)))?; + add(&edit, app.tr("ui.redo"), FileAction::Redo, Some(Accelerator::new(Modifiers::META | Modifiers::SHIFT, Code::KeyZ)))?; + add(&window, app.tr_label("Agent Chat"), FileAction::AgentChat, None)?; + window.append(&PredefinedMenuItem::separator())?; + window.append_items(&[ + &PredefinedMenuItem::minimize(None), + &PredefinedMenuItem::maximize(None), + &PredefinedMenuItem::fullscreen(None), + &PredefinedMenuItem::separator(), + &PredefinedMenuItem::bring_all_to_front(None), + ])?; + for (action, label) in [ + ("docs", "Documentation"), + ("shortcuts", "Keyboard Shortcuts"), + ("messages", "Messages\u{2026}"), + ("report", "Report an Issue\u{2026}"), + ("crashes", "Crash Reports\u{2026}"), + ] { + let item = MenuItem::new(app.tr_label(label), true, None); + help.append(&item)?; + help_actions.push((item, action)); + } + menu.append_items(&[&application, &file, &edit, &window, &help])?; + let (sender, events) = sync_channel(64); + let ctx = ctx.clone(); + MenuEvent::set_event_handler(Some(move |event| { + let _ = sender.try_send(event); + ctx.request_repaint(); + })); + menu.init_for_nsapp(); + let mut native = Self { menu, actions, help_actions, events, recent, recent_paths: Vec::new() }; + native.update_recent(app)?; + Ok(native) + } + + pub fn raw_input_hook(&mut self, app: &mut SolveApp, ctx: &egui::Context, raw: &mut egui::RawInput) { + for event in self.events.try_iter().take(64) { + if let Some((_, action)) = self.help_actions.iter().find(|(item, _)| item.id() == &event.id) { + solidcraft_ui_egui::help::run(app, ctx, action); + } + if let Some((_, action)) = self.actions.iter().find(|(item, _)| item.id() == &event.id) { + if matches!(action, FileAction::Undo | FileAction::Redo) && ctx.egui_wants_keyboard_input() { + raw.events.push(egui::Event::Key { + key: egui::Key::Z, + physical_key: None, + pressed: true, + repeat: false, + modifiers: egui::Modifiers { command: true, mac_cmd: true, shift: matches!(action, FileAction::Redo), ..Default::default() }, + }); + } else { + action.run(app); + } + } + } + } + + fn action_enabled(action: &FileAction, app: &SolveApp, ctx: &egui::Context) -> bool { + action.enabled(app) + || (matches!(action, FileAction::Undo | FileAction::Redo) && ctx.egui_wants_keyboard_input() && FileAction::Settings.enabled(app)) + } + + pub fn tick(&mut self, app: &mut SolveApp, ctx: &egui::Context) { + for (item, action) in &self.actions { + let enabled = Self::action_enabled(action, app, ctx); + if item.is_enabled() != enabled { + item.set_enabled(enabled); + } + } + if !self.recent_paths.iter().eq(app.home.recent.iter().take(32)) + && let Err(error) = self.update_recent(app) + { + app.set_status(format!("Recent designs menu: {error}"), true); + } + } + + fn update_recent(&mut self, app: &SolveApp) -> muda::Result<()> { + while self.recent.remove_at(0).is_some() {} + self.actions.retain(|(_, action)| !matches!(action, FileAction::OpenRecent(_) | FileAction::ClearRecent)); + self.recent_paths = app.home.recent.iter().take(32).cloned().collect(); + for path in &self.recent_paths { + let action = FileAction::OpenRecent(path.clone()); + let item = MenuItem::new(path, action.enabled(app), None); + self.recent.append(&item)?; + self.actions.push((item, action)); + } + self.recent.append(&PredefinedMenuItem::separator())?; + let clear = MenuItem::new(app.tr("ui.clear_recent"), !self.recent_paths.is_empty(), None); + self.recent.append(&clear)?; + self.actions.push((clear, FileAction::ClearRecent)); + Ok(()) + } +} + +impl Drop for NativeMenu { + fn drop(&mut self) { + MenuEvent::set_event_handler(None::); + self.menu.remove_for_nsapp(); + } +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 91ef3eb28..c425b71c8 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -468,6 +468,8 @@ pub struct SolveApp { pub native_resize_border: bool, /// macOS: the traffic lights sit over the application bar's left end. pub integrated_titlebar: bool, + /// The desktop host installed a system File menu; omit the in-window duplicate. + pub native_file_menu: bool, /// Build bodies' display meshes on the CPU even where the GPU could (safe mode). Read by /// [`SolveApp::set_wgpu`]. pub cpu_meshing: bool, @@ -590,6 +592,7 @@ impl SolveApp { custom_titlebar: false, native_resize_border: false, integrated_titlebar: false, + native_file_menu: false, cpu_meshing: false, frame_ms: 0.0, frame_rate: frame_rate::FrameRate::default(), diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 0ddbca259..03921fd2e 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -329,7 +329,9 @@ pub fn app_bar(app: &mut SolveApp, ui: &mut egui::Ui) { // While a file loads the design waits: no menus or commands from the bar. // The File menu: a text button (New, Open, Save, Save As, Export…). Its handle keeps the // old `appbar:folder` name too, for scripts written against the folder button. - let file = { + let file = if app.native_file_menu { + false + } else { let label = app.tr("ui.file").to_string(); let galley = ui.painter().layout_no_wrap(label.clone(), FontId::proportional(t.font_button), t.app_bar_text); let br = Rect::from_min_size(pos2(x - 13.0, r.center().y - 13.0), vec2(galley.size().x + 16.0, 26.0)); @@ -375,13 +377,13 @@ pub fn app_bar(app: &mut SolveApp, ui: &mut egui::Ui) { } x += step; // Narrow windows retain Save; Undo and Redo remain available from their shortcuts and menus. - if !compact_actions { + if !compact_actions && !app.native_file_menu { if click(ui, x, "undo", &undo_tip, shown) { - let _ = app.run("edit.undo", json!({})); + FileAction::Undo.run(app); } x += step; if click(ui, x, "redo", &redo_tip, shown) { - let _ = app.run("edit.redo", json!({})); + FileAction::Redo.run(app); } x += step; } @@ -407,7 +409,7 @@ pub fn app_bar(app: &mut SolveApp, ui: &mut egui::Ui) { let label_width = ui.painter().layout_no_wrap(report_text.to_string(), report_font.clone(), t.app_bar_text).size().x; let (report, report_label) = report_rect(r, captions, tabs_start, label_width); // Assistant, Settings, Help and Report a bug form the right-hand cluster. - if click(ui, help_x(report), "help", app.tr("ui.help"), true) { + if !app.native_file_menu && click(ui, help_x(report), "help", app.tr("ui.help"), true) { app.help.menu = !app.help.menu; let at = help_x(report); ui.ctx().data_mut(|d| { @@ -417,57 +419,70 @@ pub fn app_bar(app: &mut SolveApp, ui: &mut egui::Ui) { } // A newer release: its Update button stays before the right cluster, in the space up to // the bar's own file actions on the left. - let span = Rect::from_min_max(pos2(x, report.top()), pos2(report.left() - CLUSTER_BUTTONS - 2.0, report.bottom())); + let controls_left = if app.native_file_menu { r.right() - captions - 12.0 } else { report.left() - CLUSTER_BUTTONS }; + let span = Rect::from_min_max(pos2(x, report.top()), pos2(controls_left - 2.0, report.bottom())); let update_labeled = report_label; let update = crate::update::button(app, ui, span, update_labeled); - let tabs_end = update.map_or(report.left() - CLUSTER_BUTTONS, |u| u.left()) - 8.0; + let tabs_end = update.map_or(controls_left, |u| u.left()) - 8.0; // Narrow title bars can fit only part of the tab strip. Its hit regions must not // extend into the persistent report and window controls. let tabs_rect = Rect::from_min_max(pos2(tabs_start.min(tabs_end), r.top()), pos2(tabs_end, r.bottom())); let mut tabs_ui = ui.new_child(egui::UiBuilder::new().max_rect(tabs_rect)); tabs_ui.set_clip_rect(tabs_rect.intersect(ui.clip_rect())); crate::documents::tabs(app, &mut tabs_ui, r, tabs_start, tabs_end); - let response = ui.interact(report, ui.id().with("sc_report_button"), Sense::click()); - response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), report_text)); - crate::scenario::publish_target("titlebar:report", report); - ui.painter().rect_filled(report, t.radius_sm, if response.hovered() || response.has_focus() { t.app_bar_hover_button } else { t.app_bar }); - ui.painter().rect_stroke(report, t.radius_sm, Stroke::new(1.0, t.app_bar_separator), egui::StrokeKind::Inside); - let icon = Rect::from_center_size(pos2(report.left() + 14.0, report.center().y), vec2(18.0, 18.0)); - icons::paint_app_bar(ui.painter(), icon, "bug_report", 1.0); - if report_label { - ui.painter().text(pos2(report.left() + REPORT_TEXT_X, report.center().y), Align2::LEFT_CENTER, report_text, report_font, t.app_bar_text); - } - if response.on_hover_text(crate::i18n::tr_label("Report a bug — review a screenshot and open a GitHub draft")).clicked() { - crate::help::run(app, &ui.ctx().clone(), "report"); - } - // Settings sits immediately left of Help (also Ctrl+,). - let gear = Rect::from_center_size(pos2(report.left() - 52.0, r.center().y), vec2(32.0, 32.0)); - let gresp = ui.interact(gear, ui.id().with("sc_prefs_button"), Sense::click()); - if gresp.hovered() || gresp.has_focus() { - ui.painter().rect_filled(gear.shrink(3.0), t.radius_sm, t.app_bar_hover_button); - } - icons::paint_app_bar(ui.painter(), gear.shrink(7.0), "settings", 1.0); - crate::scenario::publish_rect("titlebar:preferences", gear); - if crate::agent_chat::app_bar_button_shown(app) { - assistant_button(app, ui, Rect::from_center_size(pos2(report.left() - 86.0, r.center().y), vec2(32.0, 32.0))); - } - crate::scenario::publish_handle("titlebar:preferences", gear.center()); - let prefs_tip = if cfg!(target_os = "macos") { - format!("{} (Cmd+,)", app.tr("ui.preferences")) - } else { - format!("{} (Ctrl+,)", app.tr("ui.preferences")) - }; - if gresp.on_hover_text(prefs_tip).clicked() { - crate::prefs::open_at(app, 0); - } - if r.width() >= 640.0 { - ui.painter().text( - pos2(r.right() - 12.0 - captions, r.center().y), - Align2::RIGHT_CENTER, - format!("v{}", crate::update::current_version()), - FontId::proportional(t.font_small), - t.app_bar_text, + if !app.native_file_menu { + let response = ui.interact(report, ui.id().with("sc_report_button"), Sense::click()); + response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), report_text)); + crate::scenario::publish_target("titlebar:report", report); + ui.painter().rect_filled( + report, + t.radius_sm, + if response.hovered() || response.has_focus() { t.app_bar_hover_button } else { t.app_bar }, ); + ui.painter().rect_stroke(report, t.radius_sm, Stroke::new(1.0, t.app_bar_separator), egui::StrokeKind::Inside); + let icon = Rect::from_center_size(pos2(report.left() + 14.0, report.center().y), vec2(18.0, 18.0)); + icons::paint_app_bar(ui.painter(), icon, "bug_report", 1.0); + if report_label { + ui.painter().text( + pos2(report.left() + REPORT_TEXT_X, report.center().y), + Align2::LEFT_CENTER, + report_text, + report_font, + t.app_bar_text, + ); + } + if response.on_hover_text(crate::i18n::tr_label("Report a bug — review a screenshot and open a GitHub draft")).clicked() { + crate::help::run(app, &ui.ctx().clone(), "report"); + } + // Settings sits immediately left of Help (also Ctrl+,). + let gear = Rect::from_center_size(pos2(report.left() - 52.0, r.center().y), vec2(32.0, 32.0)); + let gresp = ui.interact(gear, ui.id().with("sc_prefs_button"), Sense::click()); + if gresp.hovered() || gresp.has_focus() { + ui.painter().rect_filled(gear.shrink(3.0), t.radius_sm, t.app_bar_hover_button); + } + icons::paint_app_bar(ui.painter(), gear.shrink(7.0), "settings", 1.0); + crate::scenario::publish_rect("titlebar:preferences", gear); + if crate::agent_chat::app_bar_button_shown(app) { + assistant_button(app, ui, Rect::from_center_size(pos2(report.left() - 86.0, r.center().y), vec2(32.0, 32.0))); + } + crate::scenario::publish_handle("titlebar:preferences", gear.center()); + let prefs_tip = if cfg!(target_os = "macos") { + format!("{} (Cmd+,)", app.tr("ui.preferences")) + } else { + format!("{} (Ctrl+,)", app.tr("ui.preferences")) + }; + if gresp.on_hover_text(prefs_tip).clicked() { + crate::prefs::open_at(app, 0); + } + if r.width() >= 640.0 { + ui.painter().text( + pos2(r.right() - 12.0 - captions, r.center().y), + Align2::RIGHT_CENTER, + format!("v{}", crate::update::current_version()), + FontId::proportional(t.font_small), + t.app_bar_text, + ); + } } if app.custom_titlebar { crate::titlebar::caption_buttons(app, ui, r); @@ -478,8 +493,100 @@ pub fn app_bar(app: &mut SolveApp, ui: &mut egui::Ui) { crate::help::show(app, &ui.ctx().clone(), pos2(help_x - 14.0, APP_BAR_HEIGHT)); } +/// File, edit and application actions shared by the in-window and native menus. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum FileAction { + /// Create a design using the document lifecycle. + New, + /// Pick a design or an exchange file to open. + Open, + /// Save the active design, asking for a path when needed. + Save, + /// Save the active design under another name. + SaveAs, + /// Undo the active design's last command. + Undo, + /// Redo the active design's last undone command. + Redo, + /// Save a JSON design using the existing save-as flow. + SaveJson, + /// Export through the format-specific export command. + Export(&'static str), + /// Open the mesh export dialog with the selected format. + ExportMesh(&'static str), + /// Start an existing interactive command. + Command(&'static str), + /// Open an entry from the recent-design list. + OpenRecent(String), + /// Clear recent designs and their last-opened dates. + ClearRecent, + /// Show the application's preferences. + Settings, + /// Show the keyboard shortcut editor. + Shortcuts, + /// Toggle the agent chat panel. + AgentChat, + /// Request application exit, checking for unsaved documents. + Quit, +} + +impl FileAction { + /// Whether this action is available in the current document and picker state. + pub fn enabled(&self, app: &SolveApp) -> bool { + let needs_design = matches!(self, Self::Save | Self::SaveAs | Self::Undo | Self::Redo | Self::ExportMesh(_) | Self::Command(_)) + || matches!(self, Self::Export(extension) if *extension != "json"); + let available = match self { + Self::Undo => !app.session.undo.is_empty(), + Self::Redo => !app.session.redo.is_empty(), + Self::ClearRecent => !app.home.recent.is_empty(), + Self::AgentChat => crate::agent_chat::app_bar_button_shown(app), + _ => true, + }; + !app.file_picker_busy() && !app.file_load.busy() && (!needs_design || design_shown(app)) && available + } + + /// Execute through the same document, save-job and preferences paths as the toolbar. + pub fn run(&self, app: &mut SolveApp) { + if !self.enabled(app) { + return; + } + match self { + Self::New => crate::documents::new_design(app), + Self::Open => app.pick_open(|app, path| { + if let Some(path) = path { + app.open_path_async(&path); + } + }), + Self::Save => save(app), + Self::SaveAs => save_as(app), + Self::Undo => drop(app.run("edit.undo", json!({}))), + Self::Redo => drop(app.run("edit.redo", json!({}))), + Self::SaveJson => save_as_with_extension(app, "json"), + Self::Export(extension) => export(app, extension), + Self::ExportMesh(format) => crate::dialogs_save_mesh::start_with_format(app, format), + Self::Command(command) => app.start(command), + Self::OpenRecent(path) => crate::home::open_recent(app, path), + Self::ClearRecent => { + app.home.recent.clear(); + app.home.opened_at.clear(); + } + Self::Settings => crate::prefs::open_at(app, 0), + Self::Shortcuts => { + app.keymap.open = true; + app.keymap.read_only = false; + } + Self::AgentChat => crate::agent_chat::toggle(app), + Self::Quit => crate::documents::request_quit(app), + } + } +} + fn file_menu(app: &mut SolveApp, ctx: &egui::Context) { let id = egui::Id::new("sc_file_menu"); + if app.native_file_menu { + ctx.data_mut(|data| data.insert_temp(id, false)); + return; + } if !ctx.data(|d| d.get_temp::(id).unwrap_or(false)) { return; } @@ -501,15 +608,11 @@ fn file_menu(app: &mut SolveApp, ctx: &egui::Context) { // Insert, Save and Export act on the design, which Home hides. let shown = design_shown(app); if item(ui, app.tr("ui.new_design"), "Ctrl+N", "new") { - crate::documents::new_design(app); + FileAction::New.run(app); close = true; } if item(ui, &format!("{}…", app.tr("ui.open")), "Ctrl+O", "open") { - app.pick_open(|app, path| { - if let Some(path) = path { - app.open_path_async(&path); - } - }); + FileAction::Open.run(app); close = true; } crate::ui_kit::Menu::button(ui, app.tr("ui.open_recent"), |ui| { @@ -517,41 +620,40 @@ fn file_menu(app: &mut SolveApp, ctx: &egui::Context) { let missing = !crate::home::available(app, &path); let label = format!("{path}{}", if missing { " (missing)" } else { "" }); if crate::context_menu::button(ui, &label, "open").clicked() { - crate::home::open_recent(app, &path); + FileAction::OpenRecent(path).run(app); close = true; ui.close(); } } ui.separator(); if crate::context_menu::button(ui, app.tr("ui.clear_recent"), "delete").clicked() { - app.home.recent.clear(); - app.home.opened_at.clear(); + FileAction::ClearRecent.run(app); close = true; ui.close(); } }); if item_if(ui, "Insert STEP…", "", "import", shown) { - app.start("file.insert_step"); + FileAction::Command("file.insert_step").run(app); close = true; } if item_if(ui, "Insert Mesh…", "", "import", shown) { - app.start("file.insert_mesh"); + FileAction::Command("file.insert_mesh").run(app); close = true; } if item_if(ui, &format!("{}…", app.tr_label("Insert Design")), "", "component", shown) { - app.start("component.insert_design"); + FileAction::Command("component.insert_design").run(app); close = true; } if item_if(ui, app.tr("ui.save"), "Ctrl+S", "save", shown) { - save(app); + FileAction::Save.run(app); close = true; } if item_if(ui, &format!("{}…", app.tr("ui.save_as")), "", "save", shown) { - save_as(app); + FileAction::SaveAs.run(app); close = true; } if item(ui, "Save As JSON…", "", "save") { - save_as_with_extension(app, "json"); + FileAction::SaveJson.run(app); close = true; } // The browser build: a copy as a downloaded file, whatever Save does. @@ -567,36 +669,36 @@ fn file_menu(app: &mut SolveApp, ctx: &egui::Context) { } ui.separator(); if item_if(ui, "Export STL…", "", "mesh_export", shown) { - crate::dialogs_save_mesh::start_with_format(app, "stl"); + FileAction::ExportMesh("stl").run(app); close = true; } if item_if(ui, "Export 3MF…", "", "mesh_export", shown) { - crate::dialogs_save_mesh::start_with_format(app, "3mf"); + FileAction::ExportMesh("3mf").run(app); close = true; } if item_if(ui, "Export STEP…", "", "export", shown) { - export(app, "step"); + FileAction::Export("step").run(app); close = true; } if item_if(ui, app.tr_label("Export Current View as DXF…"), "", "export", shown) { - app.start("file.export_view_dxf"); + FileAction::Command("file.export_view_dxf").run(app); close = true; } if item_if(ui, "Export OBJ…", "", "export", shown) { - export(app, "obj"); + FileAction::Export("obj").run(app); close = true; } if item_if(ui, "Export URDF…", "", "export", shown) { - export(app, "urdf"); + FileAction::Export("urdf").run(app); close = true; } if item(ui, "Export Design as JSON…", "", "export") { - export(app, "json"); + FileAction::Export("json").run(app); close = true; } ui.separator(); if item_if(ui, &format!("{}…", app.tr_label("Design Properties")), "", "settings", shown) { - app.start("document.metadata"); + FileAction::Command("document.metadata").run(app); close = true; } ui.separator(); @@ -610,16 +712,15 @@ fn file_menu(app: &mut SolveApp, ctx: &egui::Context) { close = true; } if item(ui, &format!("{}…", app.tr("ui.preferences")), "", "settings") { - app.prefs_window.open = true; + FileAction::Settings.run(app); close = true; } if item(ui, &format!("{}…", app.tr("ui.keyboard_shortcuts")), "", "list") { - app.keymap.open = true; - app.keymap.read_only = false; + FileAction::Shortcuts.run(app); close = true; } if item(ui, app.tr("ui.quit"), "", "close") { - crate::documents::request_quit(app); + FileAction::Quit.run(app); close = true; } }); @@ -1942,6 +2043,90 @@ pub fn shortcuts(app: &mut SolveApp, ctx: &egui::Context) { mod header_report_tests { use super::*; + #[test] + fn native_file_menu_replaces_window_button_and_preserves_fallback() { + let mut h = crate::scenario::Harness::new(); + h.frames(3); + assert!(crate::scenario::handle_at("appbar:file").is_some()); + h.ctx.data_mut(|data| data.insert_temp(egui::Id::new("sc_file_menu"), true)); + h.app.native_file_menu = true; + h.frames(3); + assert!(crate::scenario::handle_at("appbar:file").is_none()); + assert!(!h.ctx.data(|data| data.get_temp::(egui::Id::new("sc_file_menu")).unwrap_or(false))); + assert!(crate::scenario::handle_at("appbar:save").is_some()); + assert!(crate::scenario::handle_at("appbar:undo").is_none()); + assert!(crate::scenario::handle_at("appbar:redo").is_none()); + h.app.native_file_menu = false; + h.frames(3); + assert!(crate::scenario::handle_at("appbar:file").is_some()); + assert!(crate::scenario::handle_at("appbar:undo").is_some()); + assert!(crate::scenario::handle_at("appbar:redo").is_some()); + } + + #[test] + fn native_menu_actions_share_undo_and_redo_history() { + let mut h = crate::scenario::Harness::new(); + h.app.home.open = false; + assert!(!FileAction::Undo.enabled(&h.app)); + assert!(!FileAction::Redo.enabled(&h.app)); + h.app.run("solid.box", json!({"length":2,"width":3,"height":4})).unwrap(); + let depth = h.app.session.undo.len(); + assert!(FileAction::Undo.enabled(&h.app)); + FileAction::Undo.run(&mut h.app); + assert_eq!(h.app.session.undo.len(), depth - 1); + assert!(FileAction::Redo.enabled(&h.app)); + FileAction::Redo.run(&mut h.app); + assert_eq!(h.app.session.undo.len(), depth); + assert!(!FileAction::Redo.enabled(&h.app)); + } + + #[test] + fn native_menu_actions_share_settings_and_unsaved_quit() { + let mut h = crate::scenario::Harness::new(); + FileAction::Settings.run(&mut h.app); + assert!(h.app.prefs_window.open); + h.app.run("solid.box", json!({"length":2,"width":3,"height":4})).unwrap(); + FileAction::Quit.run(&mut h.app); + assert!(!h.app.quit_requested); + assert!(h.app.docs.quitting.is_some()); + } + + #[test] + fn native_menu_actions_disable_save_on_home() { + let mut h = crate::scenario::Harness::new(); + h.app.home.open = true; + assert!(!FileAction::Save.enabled(&h.app)); + assert!(!FileAction::SaveAs.enabled(&h.app)); + assert!(FileAction::New.enabled(&h.app)); + assert!(FileAction::Open.enabled(&h.app)); + assert!(FileAction::Settings.enabled(&h.app)); + assert!(!FileAction::Export("step").enabled(&h.app)); + assert!(!FileAction::ExportMesh("stl").enabled(&h.app)); + assert!(!FileAction::Command("document.metadata").enabled(&h.app)); + h.app.home.open = false; + assert!(FileAction::Save.enabled(&h.app)); + assert!(FileAction::Export("step").enabled(&h.app)); + } + + #[test] + fn native_menu_actions_share_json_save_and_recent_cleanup() { + let mut h = crate::scenario::Harness::new(); + let path = h.dir.join("native-menu.json"); + let output = path.clone(); + h.app.services.pick_save = Some(Box::new(move |_, _| Box::pin(std::future::ready(Some(output.to_string_lossy().into_owned()))))); + h.app.run("solid.box", json!({"length":2,"width":3,"height":4})).unwrap(); + FileAction::SaveJson.run(&mut h.app); + h.frames(3); + h.settle(); + let bytes = std::fs::read(path).unwrap(); + assert!(serde_json::from_slice::(&bytes).is_ok()); + assert!(!h.app.home.recent.is_empty()); + FileAction::ClearRecent.run(&mut h.app); + assert!(h.app.home.recent.is_empty()); + assert!(h.app.home.opened_at.is_empty()); + assert!(!FileAction::ClearRecent.enabled(&h.app)); + } + #[test] fn file_menu_json_save_and_export_use_commands_and_keep_distinct_paths() { let mut h = crate::scenario::Harness::new();