diff --git a/apps/effectcraft/src/main.rs b/apps/effectcraft/src/main.rs index 61554858f..a008a7b7a 100644 --- a/apps/effectcraft/src/main.rs +++ b/apps/effectcraft/src/main.rs @@ -441,6 +441,8 @@ fn run_desktop(reporter: &crash_report::Shutdown) -> eframe::Result { #[cfg(target_os = "macos")] menu: native_menu::NativeBar::new(&cc.egui_ctx), #[cfg(target_os = "macos")] + menu_sync: Default::default(), + #[cfg(target_os = "macos")] apple_events: apple_events.connect(&cc.egui_ctx), app, file_dialogs, @@ -531,6 +533,8 @@ struct Desktop { dialog_errors: std::sync::mpsc::Receiver, #[cfg(target_os = "macos")] menu: native_menu::NativeBar, + #[cfg(target_os = "macos")] + menu_sync: effectcraft_ui_egui::native_menu::MenuSync, /// Documents opened from Finder, the Dock or `open` (macOS). #[cfg(target_os = "macos")] apple_events: apple_events::Opened, @@ -547,7 +551,7 @@ impl eframe::App for Desktop { /// file dialogs asked for and, last, hand a close to the platform quit. fn logic(&mut self, ctx: &egui::Context, frame: &mut eframe::Frame) { #[cfg(target_os = "macos")] - self.menu.update(&mut self.app, ctx); + self.menu_sync.before(&mut self.app, |app| self.menu.update(app, ctx)); self.app.tick(ctx, frame); self.app.finish_ime_logic(ctx); while let Ok(e) = self.dialog_errors.try_recv() { @@ -561,6 +565,9 @@ impl eframe::App for Desktop { fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) { self.app.ui(ui, frame); + // A file dialog this frame's commands opened (or one that closed) syncs the menu again. + #[cfg(target_os = "macos")] + self.menu_sync.after(&mut self.app, |app| self.menu.update(app, ui.ctx())); if let Some(asked) = &self.file_dialogs { file_dialogs::show_asked(asked, frame, ui.ctx()); } diff --git a/apps/effectcraft/src/native_menu.rs b/apps/effectcraft/src/native_menu.rs index c3b142c5f..f8263fd70 100644 --- a/apps/effectcraft/src/native_menu.rs +++ b/apps/effectcraft/src/native_menu.rs @@ -118,6 +118,12 @@ impl NativeBar { Role::Hide => PredefinedMenuItem::hide(Some(label)), Role::HideOthers => PredefinedMenuItem::hide_others(Some(label)), Role::ShowAll => PredefinedMenuItem::show_all(Some(label)), + Role::SelectAll => PredefinedMenuItem::select_all(Some(label)), + Role::Cut => PredefinedMenuItem::cut(Some(label)), + Role::Copy => PredefinedMenuItem::copy(Some(label)), + Role::Paste => PredefinedMenuItem::paste(Some(label)), + Role::Undo => PredefinedMenuItem::undo(Some(label)), + Role::Redo => PredefinedMenuItem::redo(Some(label)), }; parent.append(&item) } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 717a9a370..5d49d397b 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -542,6 +542,11 @@ impl FileDialogsUp { self.count = self.count.saturating_sub(1); } + /// How many dialogs are up, as last checked ([`FileDialogsUp::up`] drops those taken for gone). + pub(crate) fn count(&self) -> usize { + self.count + } + /// Whether a dialog is up at `now`, `focused`: whether one of the app's windows has the /// keyboard. pub(crate) fn up(&mut self, focused: bool, now: f64) -> bool { diff --git a/crates/ui-egui/src/menus/entries.rs b/crates/ui-egui/src/menus/entries.rs index 3391e47bd..c3641196f 100644 --- a/crates/ui-egui/src/menus/entries.rs +++ b/crates/ui-egui/src/menus/entries.rs @@ -101,6 +101,12 @@ pub(crate) fn entry_checked(app: &EffectcraftApp, e: &MenuEntry) -> Option } pub(crate) fn entry_enabled(app: &EffectcraftApp, e: &MenuEntry) -> bool { + // A disabled macOS menu item lets its key through, so a native file dialog gets Cmd+A, C, V + // (and Z) instead of the Edit menu acting on the window behind it (#1986). Only macOS: the + // native menu bar owns the keys there, and Linux's portal dialog is a separate window. + if cfg!(target_os = "macos") && e.command.starts_with("edit.") && app.file_dialogs.count() > 0 { + return false; + } // The Project-panel enabled rules mirror the invoke redirects, so they stand down for the // same reason (see the redirect block): while a text edit is open the menu items must be // enabled by what their routed command can do, or the menu grays out commands that work. diff --git a/crates/ui-egui/src/menus/tests.rs b/crates/ui-egui/src/menus/tests.rs index 68c8d3f43..f261d1057 100644 --- a/crates/ui-egui/src/menus/tests.rs +++ b/crates/ui-egui/src/menus/tests.rs @@ -448,6 +448,41 @@ fn file_dialogs_block_floating_windows_only_while_up() { assert!(blocked(&mut app, false, 13.1), "a later dialog blocks again"); } +/// While a native file dialog is up, the Edit menu is disabled on macOS so the OS hands Cmd+A +/// to the dialog instead of selecting in the Project panel behind it (#1986). Elsewhere the +/// menu stays as it was. +#[test] +fn edit_menu_is_disabled_while_a_file_dialog_is_open() { + use std::sync::{Arc, Mutex}; + let mut app = EffectcraftApp::new(effectcraft_engine::Session::default()); + app.session.execute("file.openDemoProject", json!({})).unwrap(); + app.ui.focused = PanelKind::Project; + let ctx = egui::Context::default(); + let entries = effectcraft_engine::menus::entries(); + let select_all = entries.iter().map(|(_, e)| e).find(|e| e.command == "edit.selectAll").expect("Select All is in the menu"); + let import = entries.iter().map(|(_, e)| e).find(|e| e.command == "file.import").expect("Import is in the menu"); + assert!(entry_enabled(&app, select_all)); + let steps_aside = cfg!(target_os = "macos"); + let pending: Arc>> = Arc::default(); + let queue = pending.clone(); + app.hooks.file_dialog_async = Some(Box::new(move |_, done| queue.lock().unwrap().push(done))); + invoke(&mut app, &ctx, "file.importMultiple", json!({})).unwrap(); + assert_eq!(!entry_enabled(&app, select_all), steps_aside, "Cmd+A must reach the dialog on macOS only"); + assert!(entry_enabled(&app, import), "only the Edit menu steps aside"); + // Cancelled: the menu is back. + let done = pending.lock().unwrap().pop().expect("a dialog was shown"); + done(Ok(Vec::new())); + app.run_dialog_answers(); + assert!(entry_enabled(&app, select_all)); + // Ended without answering: the menu is back once the dialog is taken for gone. + invoke(&mut app, &ctx, "file.importMultiple", json!({})).unwrap(); + assert_eq!(!entry_enabled(&app, select_all), steps_aside); + let _ = app.file_dialogs.up(true, 0.0); + let _ = app.file_dialogs.up(false, 0.1); + let _ = app.file_dialogs.up(true, 0.2); + assert!(entry_enabled(&app, select_all)); +} + /// #3084: a host whose dialog couldn't open (macOS: `+[NSOpenPanel openPanel]` returned nil) /// answers with the error. The status line says why, the command doesn't run and the dialog /// no longer blocks floating windows; the next dialog opens as usual. diff --git a/crates/ui-egui/src/native_menu.rs b/crates/ui-egui/src/native_menu.rs index 1d892b38a..f856db01d 100644 --- a/crates/ui-egui/src/native_menu.rs +++ b/crates/ui-egui/src/native_menu.rs @@ -29,6 +29,12 @@ pub enum Role { Hide, HideOthers, ShowAll, + SelectAll, + Cut, + Copy, + Paste, + Undo, + Redo, } /// One node of the native menu. @@ -151,9 +157,37 @@ pub fn build_now(app: &EffectcraftApp, ctx: &egui::Context) -> NativeMenu { } } let mut menu = build(app); - if text_field_window(ctx).is_some() { + // On macOS a file dialog takes the keys over the field behind it (#1986). + let dialog = cfg!(target_os = "macos") && app.file_dialogs.count() > 0; + if text_field_window(ctx).is_some() && !dialog { enable(app, &mut menu.menus); } + if dialog { + // The sandboxed open panel is a remote view: it gets Cmd+A, C, X, V, Z through the host's + // standard Edit items (first-responder selectors), not through items that run our + // commands, which swallow the key or leave the panel without one (#1986). + fn standard(nodes: &mut [NativeNode]) { + for node in nodes { + match node { + NativeNode::Item(item) => { + let role = match item.command.as_str() { + "edit.selectAll" => Role::SelectAll, + "edit.cut" => Role::Cut, + "edit.copy" => Role::Copy, + "edit.paste" => Role::Paste, + "edit.undo" => Role::Undo, + "edit.redo" => Role::Redo, + _ => continue, + }; + *node = NativeNode::Predefined { role, label: item.label.clone(), command: item.command.clone() }; + } + NativeNode::Submenu { children, .. } => standard(children), + _ => {} + } + } + } + standard(&mut menu.menus); + } menu } @@ -374,12 +408,37 @@ pub fn state_key(app: &EffectcraftApp) -> u64 { s.keymaps.active.hash(&mut h); let v = &app.ui.viewer; (v.rulers, v.guides, v.snap_guides, v.lock_guides, v.grid, v.snap_grid, v.show_layer_controls, v.pasteboard).hash(&mut h); - (app.ui.cache_when_idle, app.session.prefs.preview.active().include_audio, &app.ui.workspace, app.dialog.is_some()).hash(&mut h); + (app.ui.cache_when_idle, app.session.prefs.preview.active().include_audio, &app.ui.workspace, app.dialog.is_some(), app.file_dialogs.count()).hash(&mut h); // Window menu check marks: the panels on screen. crate::dock::PanelKind::ALL.iter().filter(|p| crate::menus::panel_shown(app, **p)).for_each(|p| p.hash(&mut h)); h.finish() } +/// Keeps the native menu in step with native file dialogs within a frame. The menu syncs at the +/// frame's start, but a dialog opened by the frame's commands is counted only after that: sync +/// again then, so its Edit items step aside before the next key (#1986). The second sync runs +/// only when the dialog count changed. +#[derive(Default)] +pub struct MenuSync { + /// Native file dialogs on screen at the last sync. + dialogs: usize, +} + +impl MenuSync { + /// The frame's sync, before its commands run. + pub fn before(&mut self, app: &mut EffectcraftApp, update: impl FnOnce(&mut EffectcraftApp)) { + update(app); + self.dialogs = app.file_dialogs.count(); + } + + /// After the frame's commands: sync again if a file dialog opened or closed meanwhile. + pub fn after(&mut self, app: &mut EffectcraftApp, update: impl FnOnce(&mut EffectcraftApp)) { + if app.file_dialogs.count() != self.dialogs { + self.before(app, update); + } + } +} + /// The window whose text field has the keyboard: a floating panel's own OS window, or the main /// window, where any widget that holds the keyboard counts (the Viewer's text editor is not an /// egui text field). @@ -490,9 +549,37 @@ mod tests { fn app() -> EffectcraftApp { let mut s = effectcraft_engine::Session::default(); s.execute("file.openDemoProject", json!({})).unwrap(); + // The default is "Match System": pin English so the tests do not follow the machine's locale. + s.execute("prefs.set", json!({"key": "general.language", "value": "en"})).unwrap(); EffectcraftApp::new(s) } + /// A file dialog opened by the frame's commands syncs the menu a second time (#1986); a + /// frame without one syncs it once. + #[test] + fn menu_syncs_again_when_a_frame_opens_a_file_dialog() { + let mut app = app(); + let ctx = egui::Context::default(); + let pending: std::sync::Arc>> = Default::default(); + let queue = pending.clone(); + app.hooks.file_dialog_async = Some(Box::new(move |_, done| queue.lock().unwrap().push(done))); + let mut sync = MenuSync::default(); + // A fake menu: records the dialog count each update sees. + let mut updates = Vec::new(); + let mut frame = |app: &mut EffectcraftApp, command: Option<&str>| { + sync.before(app, |a| updates.push(a.file_dialogs.count())); + if let Some(id) = command { + crate::menus::invoke(app, &ctx, id, json!({})).unwrap(); + } + sync.after(app, |a| updates.push(a.file_dialogs.count())); + }; + frame(&mut app, None); + frame(&mut app, Some("file.importMultiple")); + frame(&mut app, None); + assert_eq!(updates, [0, 0, 1, 1], "no dialog: one update; dialog opened: a second one that sees it"); + assert_eq!(pending.lock().unwrap().len(), 1, "a dialog was shown"); + } + #[test] fn every_engine_entry_is_in_the_native_menu() { let app = app(); @@ -822,6 +909,79 @@ mod tests { assert!(edits_text("edit.copy") && edits_text("edit.paste")); assert!(!edits_text("layer.newNull")); } + /// #1986: a file dialog opened while a text field has the keyboard takes Cmd+A: the field + /// behind it does not keep the Edit items enabled. + #[test] + fn a_file_dialog_takes_the_edit_keys_from_a_focused_text_field() { + let mut app = app(); + let ctx = egui::Context::default(); + let mut text = String::new(); + for _ in 0..2 { + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| ui.text_edit_singleline(&mut text).request_focus()); + out.textures_delta.clear(); + } + let select_all = |m: &NativeMenu| m.items().into_iter().any(|i| i.command == "edit.selectAll" && i.enabled); + assert!(select_all(&build_now(&app, &ctx))); + app.hooks.file_dialog_async = Some(Box::new(|_, _| {})); + crate::menus::invoke(&mut app, &ctx, "file.importMultiple", json!({})).unwrap(); + assert_eq!(select_all(&build_now(&app, &ctx)), !cfg!(target_os = "macos")); + } + + /// #1986: while a file dialog is open on macOS the Edit items for select-all, cut, copy, + /// paste, undo and redo become the host's standard (predefined) items, keeping label and + /// command; without a dialog they stay plain command items. + #[test] + fn a_file_dialog_turns_the_edit_keys_into_standard_items() { + fn predefined(menu: &NativeMenu) -> Vec<(String, Role, String)> { + fn rec(n: &[NativeNode], out: &mut Vec<(String, Role, String)>) { + for x in n { + match x { + NativeNode::Predefined { role, label, command } + if matches!(role, Role::SelectAll | Role::Cut | Role::Copy | Role::Paste | Role::Undo | Role::Redo) => + { + out.push((command.clone(), *role, label.to_string())) + } + NativeNode::Submenu { children, .. } => rec(children, out), + _ => {} + } + } + } + let mut out = vec![]; + rec(&menu.menus, &mut out); + out + } + fn by_command<'a>(menu: &'a NativeMenu, id: &str) -> Option<&'a NativeItem> { + menu.items().into_iter().find(|i| i.command == id) + } + let mut app = app(); + let ctx = egui::Context::default(); + let ids = ["edit.selectAll", "edit.cut", "edit.copy", "edit.paste", "edit.undo", "edit.redo"]; + let before = build_now(&app, &ctx); + assert!(predefined(&before).is_empty(), "no dialog: no standard edit items"); + let plain: Vec<_> = ids.iter().filter(|id| by_command(&before, id).is_some()).collect(); + app.hooks.file_dialog_async = Some(Box::new(|_, _| {})); + crate::menus::invoke(&mut app, &ctx, "file.importMultiple", json!({})).unwrap(); + let after = build_now(&app, &ctx); + let got = predefined(&after); + if cfg!(target_os = "macos") { + let want = [Role::SelectAll, Role::Cut, Role::Copy, Role::Paste, Role::Undo, Role::Redo]; + for (id, role) in ids.iter().zip(want) { + if !plain.contains(&id) { + continue; + } + let (_, r, label) = got.iter().find(|(c, _, _)| c == id).unwrap_or_else(|| panic!("{id} not predefined")); + assert_eq!(*r, role, "{id}"); + assert_eq!(label, &by_command(&before, id).map(|i| i.label.to_string()).unwrap_or_default(), "{id} keeps its label"); + assert!(by_command(&after, id).is_none(), "{id} no longer runs our command"); + } + assert_eq!(got.len(), plain.len()); + // Unrelated items are untouched. + assert!(by_command(&after, "file.importMultiple").is_some()); + } else { + assert!(got.is_empty()); + } + } + /// #2459: while a text field has the keyboard the Edit menu's Undo and Redo act on the field and /// read plain "Undo" / "Redo"; the project history labels come back once focus leaves. #[test]