FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust
macOS Edit menu keys edit a focused text field
aiongg6829266b0a1d
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex 37872e071..0dea8c34a 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -1829,12 +1829,18 @@ impl FilmcraftApp {/// Sends the menu tree to the native menu bar when it changed, so its items show the same/// labels, shortcuts and enablement as the in-window menus (Undo with nothing to undo is- /// disabled). Without a native menu bar this does nothing.- fn sync_native_menu(&mut self) {+ /// disabled). The items a focused text field takes stay enabled while one has the keyboard.+ /// Without a native menu bar this does nothing.+ fn sync_native_menu(&mut self, ctx: &egui::Context) {if self.hooks.menu_changed.is_none() {return;}- let items = menus::menu_items(self);+ let mut items = menus::menu_items(self);+ if menus::text_field_window(ctx).is_some() {+ for it in items.iter_mut().filter(|it| menus::edits_text(&it.id)) {+ it.enabled = true;+ }+ }if items == self.menu_sent {return;}@@ -2552,7 +2558,7 @@ impl FilmcraftApp {if self.control_input_only && id != "app.quit" {continue;}- if let Err(e) = menus::invoke(self, ctx, &id, json!({})) {+ if let Err(e) = menus::activate_native(self, ctx, &id) {self.ui.status = e;}}@@ -2632,7 +2638,7 @@ impl FilmcraftApp {self.begin_press(&ctx);self.latch_escape_cancel(&ctx);self.handle_shortcuts(&ctx);- self.sync_native_menu();+ self.sync_native_menu(&ctx);self.scrub_audio(&ctx);} else {// Pass 1+ redraws the same frame; drop the discarded pass's registrations so lookups@@ -3555,23 +3561,24 @@ mod native_menu_tests {let mut app = FilmcraftApp::new(Session::default());let sink = sent.clone();app.hooks.menu_changed = Some(Box::new(move |items: &[menus::MenuItem]| sink.borrow_mut().push(items.to_vec())));+ let ctx = egui::Context::default();- app.sync_native_menu();+ app.sync_native_menu(&ctx);let last = |sent: &Rc<RefCell<Vec<Vec<menus::MenuItem>>>>, id: &str| sent.borrow().last().and_then(|items| enabled(items, id));assert_eq!(last(&sent, "edit.undo"), Some(false), "nothing to undo in an empty project");assert_eq!(last(&sent, "edit.redo"), Some(false), "nothing to redo in an empty project");assert_eq!(last(&sent, "file.newProject"), Some(true));- app.sync_native_menu();+ app.sync_native_menu(&ctx);assert_eq!(sent.borrow().len(), 1, "an unchanged menu is not sent again");app.session.execute("file.newSequence", json!({"width":16,"height":16})).unwrap();- app.sync_native_menu();+ app.sync_native_menu(&ctx);assert_eq!(last(&sent, "edit.undo"), Some(true), "an edit can be undone");assert_eq!(last(&sent, "edit.redo"), Some(false));app.session.execute("edit.undo", json!({})).unwrap();- app.sync_native_menu();+ app.sync_native_menu(&ctx);assert_eq!(last(&sent, "edit.undo"), Some(false));assert_eq!(last(&sent, "edit.redo"), Some(true), "the undone edit can be redone");}diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rsindex 3700e749e..885dc62b3 100644--- a/crates/ui-egui/src/menus.rs+++ b/crates/ui-egui/src/menus.rs@@ -619,6 +619,61 @@ pub fn invoke(app: &mut FilmcraftApp, ctx: &egui::Context, id: &str, mut params:r}+/// Run the command `id` chosen in the native menu bar, which takes the Edit menu's key+/// equivalents (⌘C, ⌘X, ⌘V, ⌘A, ⌘Z, ⇧⌘Z) before any window sees them: while a text field has+/// the keyboard, in the main window or a floating panel's own window, the field gets the key+/// and the project command does not run.+pub fn activate_native(app: &mut FilmcraftApp, ctx: &egui::Context, id: &str) -> Result<Value, String> {+ let (Some(window), Some(text)) = (text_field_window(ctx), text_command(id, ctx.os().is_mac())) else {+ return invoke(app, ctx, id, json!({}));+ };+ match text {+ TextCommand::Paste => ctx.send_viewport_cmd_to(window, egui::ViewportCommand::RequestPaste),+ TextCommand::Events(events) if window == egui::ViewportId::ROOT => {+ app.synthetic.extend(events);+ ctx.request_repaint();+ }+ TextCommand::Events(events) => craft_ui::docking::send_keys(ctx, window, events),+ }+ Ok(Value::Null)+}++/// The window whose text field has the keyboard: a floating panel's own OS window, or the main+/// window.+pub fn text_field_window(ctx: &egui::Context) -> Option<egui::ViewportId> {+ craft_ui::docking::typing_window(ctx).or_else(|| ctx.text_edit_focused().then_some(egui::ViewportId::ROOT))+}++/// Whether a focused text field takes the menu command `id` ([`activate_native`]): the native+/// menu keeps such items enabled while one has the keyboard, whatever the project allows.+pub fn edits_text(id: &str) -> bool {+ text_command(id, false).is_some()+}++/// What a focused text field does for an Edit menu command.+#[derive(Debug, PartialEq)]+enum TextCommand {+ /// The clipboard text, which the window asks for and receives as `Paste`.+ Paste,+ Events(Vec<egui::Event>),+}++fn text_command(id: &str, mac: bool) -> Option<TextCommand> {+ let key = |key, shift| {+ let modifiers = egui::Modifiers { mac_cmd: mac, ctrl: !mac, command: true, shift, alt: false };+ TextCommand::Events([true, false].map(|pressed| egui::Event::Key { key, physical_key: None, pressed, repeat: false, modifiers }).into())+ };+ Some(match id {+ "edit.copy" => TextCommand::Events(vec![egui::Event::Copy]),+ "edit.cut" => TextCommand::Events(vec![egui::Event::Cut]),+ "edit.paste" => TextCommand::Paste,+ "edit.undo" => key(egui::Key::Z, false),+ "edit.redo" => key(egui::Key::Z, true),+ "edit.selectAll" => key(egui::Key::A, false),+ _ => return None,+ })+}+/// Snapshot OS files/image present at Copy/Cut. Many platforms keep a previous file list after/// `copy_text`, so Paste would otherwise import those files instead of the clips (#697).fn remember_stale_clipboard_media(app: &mut FilmcraftApp) {diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rsindex 010a5098a..31a8ec902 100644--- a/crates/ui-egui/tests/it/main.rs+++ b/crates/ui-egui/tests/it/main.rs@@ -39,6 +39,7 @@ mod mixer_ui;mod monitor_geometry;mod multicam_ui;mod native_dialogs_ui;+mod native_menu_text_keys;mod native_windows_ui;mod nest_editing_ui;mod nest_rendering_ui;diff --git a/crates/ui-egui/tests/it/native_menu_text_keys.rs b/crates/ui-egui/tests/it/native_menu_text_keys.rsnew file mode 100644index 000000000..766ae8c00--- /dev/null+++ b/crates/ui-egui/tests/it/native_menu_text_keys.rs@@ -0,0 +1,111 @@+//! The macOS menu bar takes the Edit menu's key equivalents before the window does: with a text+//! field focused they edit the field, and only without one do they run the project command.++use std::cell::RefCell;+use std::rc::Rc;+use std::sync::mpsc::{Sender, channel};++use egui_kittest::Harness;+use filmcraft_engine::Session;+use filmcraft_ui_egui::FilmcraftApp;+use filmcraft_ui_egui::control::ControlRequest;+use filmcraft_ui_egui::menus::{self, MenuItem};+use serde_json::{Value, json};++struct Driver {+ harness: Harness<'static, FilmcraftApp>,+ tx: Sender<ControlRequest>,+ menu: Sender<String>,+ sent: Rc<RefCell<Vec<MenuItem>>>,+}++impl Driver {+ fn new() -> Self {+ let mut s = Session::default();+ s.execute("file.openDemoProject", json!({})).unwrap();+ let (tx, rx) = channel();+ let (menu, inbox) = channel();+ let sent: Rc<RefCell<Vec<MenuItem>>> = Rc::default();+ let sink = sent.clone();+ let mut app = FilmcraftApp::new(s).with_control(rx);+ app.command_inbox = Some(inbox);+ app.hooks.menu_changed = Some(Box::new(move |items: &[MenuItem]| *sink.borrow_mut() = items.to_vec()));+ let harness = Harness::builder().with_size(egui::vec2(1600.0, 980.0)).with_max_steps(10_000).build_eframe(move |_cc| app);+ let mut d = Driver { harness, tx, menu, sent };+ d.frames(4);+ d+ }++ fn frames(&mut self, n: usize) {+ for _ in 0..n {+ let ctx = self.harness.ctx.clone();+ let mut raw = std::mem::take(self.harness.input_mut());+ eframe::App::raw_input_hook(self.harness.state_mut(), &ctx, &mut raw);+ *self.harness.input_mut() = raw;+ self.harness.step();+ }+ }++ fn ok(&mut self, method: &str, params: Value) -> Value {+ let (req, reply) = ControlRequest::new(method, params.clone());+ self.tx.send(req).unwrap();+ for _ in 0..600 {+ self.frames(1);+ if let Ok(v) = reply.try_recv() {+ assert_eq!(v["ok"], json!(true), "{method} {params} failed: {v}");+ return v["result"].clone();+ }+ }+ panic!("no reply to {method} {params}");+ }++ /// A native menu choice, then the frames that deliver what it queued for the window.+ fn menu(&mut self, id: &str) {+ self.menu.send(id.into()).unwrap();+ self.frames(4);+ }++ fn undo_steps(&mut self) -> usize {+ self.ok("engine.execute", json!({"command": "history.list", "params": {}}))["undo"].as_array().unwrap().len()+ }++ fn enabled(&self, id: &str) -> Option<bool> {+ self.sent.borrow().iter().find(|it| it.id == id).map(|it| it.enabled)+ }++ fn search(&mut self) -> String {+ self.harness.state().ui.project_search.clone()+ }+}++#[test]+fn edit_menu_keys_edit_the_focused_text_field_and_otherwise_the_project() {+ let mut d = Driver::new();+ d.ok("engine.execute", json!({"command": "markers.markIn", "params": {"seconds": 1.0}}));+ let steps = d.undo_steps();+ assert!(steps > 0);+ assert_eq!(d.enabled("edit.paste"), Some(false), "nothing copied in the project");++ let elements = d.ok("ui.elements", json!({"prefix": "project"}));+ let field = elements.as_array().unwrap().iter().filter_map(|e| e["id"].as_str()).find(|id| id.ends_with(".search")).unwrap().to_string();+ d.ok("ui.click", json!({"id": field}));+ d.ok("ui.type", json!({"text": "abc"}));+ d.frames(3);+ assert_eq!(d.search(), "abc");+ assert_eq!(menus::text_field_window(&d.harness.ctx), Some(egui::ViewportId::ROOT));+ assert_eq!(d.enabled("edit.paste"), Some(true), "Paste stays enabled for the field");+ assert!(menus::edits_text("edit.paste") && !menus::edits_text("file.newProject"));++ d.menu("edit.selectAll");+ d.menu("edit.cut");+ assert_eq!(d.search(), "", "Select All and Cut act on the field");+ d.menu("edit.undo");+ assert_eq!(d.search(), "abc", "Undo undoes the field's cut");+ assert_eq!(d.undo_steps(), steps, "the project history is untouched");++ d.harness.ctx.memory_mut(|m| m.stop_text_input());+ d.frames(3);+ assert_eq!(menus::text_field_window(&d.harness.ctx), None);+ d.menu("edit.undo");+ assert_eq!(d.undo_steps(), steps - 1, "without a focused field, Undo undoes the project");+}