From 4a6ea8a9840f21e9f949779fe00de483a886d4b9 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Tue, 24 Nov 2026 00:57:49 +0700 Subject: [PATCH 1/5] ui-contract: a text part asks where the keyboard goes back to only once it held the focus or keeps a selection for a menu, so a part that never held the focus reads no focus in its run: the replay audit found a memoized view whose field read the focus only when another stop had it --- crates/ui-contract/src/contract/text.rs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/crates/ui-contract/src/contract/text.rs b/crates/ui-contract/src/contract/text.rs index 058bad9600..46da94442e 100644 --- a/crates/ui-contract/src/contract/text.rs +++ b/crates/ui-contract/src/contract/text.rs @@ -439,8 +439,11 @@ fn prepare(core: &mut CxCore<'_>, ui: &mut Ui, decl: &TextPart, state: &mut Text let ink = if enabled { ink } else { crate::style::rgba_color(crate::runtime::env::Env::of(ui).tokens.color.text.disabled) }; let held = core.popup(EDIT_MENU).is_open_in(core); // A menu bar or a menu the keyboard goes back to the part from has the focus: their Cut and Copy act on the - // selection the part keeps for them. - let returns_here = crate::runtime::focus::focused_stop(&ctx) + // selection the part keeps for them. Only a part that had the focus last pass, or keeps a selection already, can be + // gone back to: asking reads the focus, which a part that never held it has not read, so its replay stays true. + let returns_here = (state.focused || state.held_selection.is_some()) + .then(|| crate::runtime::focus::focused_stop(&ctx)) + .flatten() .filter(|(focused, _)| *focused != id) .and_then(|(focused, _)| crate::runtime::focus::returning(&ctx, focused)) .is_some_and(|((to, _), _)| to == id); From 662ff9264a8f9d832b5a3eeef769b68818a3bbee Mon Sep 17 00:00:00 2001 From: bflatastic Date: Tue, 24 Nov 2026 00:57:52 +0700 Subject: [PATCH 2/5] ui-contract: with RootEnv::escape_leaves_fields, Escape in a field of a dialog that Escape closes stays the dialog's with nothing typed too: the field took it to give up the focus and the dialog stayed open --- .../src/primitives/text_adapter.rs | 9 ++-- .../tests/it/form_dialogs/dialog.rs | 48 ++++++++++++------- 2 files changed, 36 insertions(+), 21 deletions(-) diff --git a/crates/ui-contract/src/primitives/text_adapter.rs b/crates/ui-contract/src/primitives/text_adapter.rs index 70785e6222..382e8ee8e2 100644 --- a/crates/ui-contract/src/primitives/text_adapter.rs +++ b/crates/ui-contract/src/primitives/text_adapter.rs @@ -481,19 +481,20 @@ pub(crate) fn run(state: &mut TextState, mut input: AdapterIn<'_>) -> AdapterOut // a list open on it (a search box's results) then gets the Escape that finds the field empty and closes. // A draft in a dialog whose Escape closes it does not take the Escape: the one Escape cancels the dialog and // the typing with it (Word, and the old apps). Outside dialogs Escape reverts the draft first. - let dialog_escape = focused_before - && state.draft.is_some() + let closes_dialog = focused_before && state.preedit.is_none() && !input.options.clear_on_escape && input.intents.untaken(&Intent::Cancel) && crate::runtime::focus::escape_closes_dialog(ctx); + let dialog_escape = closes_dialog && state.draft.is_some(); if dialog_escape { // The draft ends as for Escape (its typing is dropped), and the Escape stays for the dialog. state.end = Some(End::Escape); } let draft_takes = state.draft.is_some() && !dialog_escape; - // With `RootEnv::escape_leaves_fields` a field takes Escape with nothing to revert too, and gives up the focus. - let leaves = !input.options.clear_on_escape && !dialog_escape && crate::runtime::env::Env::of(input.ui).escape_leaves_fields; + // With `RootEnv::escape_leaves_fields` a field takes Escape with nothing to revert too, and gives up the focus; + // in a dialog that Escape closes, the Escape stays the dialog's. + let leaves = !input.options.clear_on_escape && !closes_dialog && crate::runtime::env::Env::of(input.ui).escape_leaves_fields; let takes_escape = if input.options.clear_on_escape { !base.is_empty() || state.preedit.is_some() } else { draft_takes || state.preedit.is_some() || leaves }; let list_first = input.list_open && !input.options.clear_on_escape; diff --git a/crates/ui-patterns/tests/it/form_dialogs/dialog.rs b/crates/ui-patterns/tests/it/form_dialogs/dialog.rs index 8751131007..dc34f24837 100644 --- a/crates/ui-patterns/tests/it/form_dialogs/dialog.rs +++ b/crates/ui-patterns/tests/it/form_dialogs/dialog.rs @@ -588,26 +588,40 @@ fn enter_on_a_focused_cancel_cancels_the_form() { } // One Escape in a number field holding typed text cancels the dialog, as in Word and the old apps: the draft does -// not take the Escape first, and the dialog answers no OK, so the typing goes with it. +// not take the Escape first, and the dialog answers no OK, so the typing goes with it. A field with nothing typed +// leaves the Escape to the dialog too, also where Escape otherwise takes a field's focus (`escape_leaves_fields`). #[trial] fn one_escape_over_a_typed_draft_cancels_the_dialog() { - let seen = Rc::new(Cell::new(None::<(CloseReason, bool)>)); - let out = seen.clone(); - let mut fixture = Fixture::new(move |ui| { - let dialog = ParamDialog::new("blur", "Blur", Param::parse_list(SPEC)).show(ui); - if let Some(closed) = dialog.closed { - out.set(Some((closed, dialog.result.is_some()))); + for leaves in [false, true] { + for typed in [true, false] { + let seen = Rc::new(Cell::new(None::<(CloseReason, bool)>)); + let out = seen.clone(); + let mut fixture = Fixture::new(move |ui| { + let dialog = ParamDialog::new("blur", "Blur", Param::parse_list(SPEC)).show(ui); + if let Some(closed) = dialog.closed { + out.set(Some((closed, dialog.result.is_some()))); + } + }); + let mut root = craft_ui::runtime::env::RootEnv::new(); + root.escape_leaves_fields = leaves; + fixture.root(root).settle(); + let field = fixture.by_role(Role::SPIN_BUTTON).into_iter().next().expect("the radius row has a number field"); + fixture.click(&field).settle(); + if typed { + fixture.key(Key::A, Modifiers::COMMAND); + fixture.type_text("55").settle(); + let draft = + fixture.by_role(Role::SPIN_BUTTON).into_iter().next().and_then(|field| fixture.tree().value_of(field.node).map(str::to_owned)); + assert_eq!(draft.as_deref(), Some("55"), "the field shows the typing as a draft"); + } + fixture.key(Key::Escape, Modifiers::NONE).settle(); + assert!( + matches!(seen.get(), Some((CloseReason::Escape, false))), + "leaves {leaves}, typed {typed}: one Escape cancels the dialog: {:?}", + seen.get() + ); } - }); - fixture.settle(); - let field = fixture.by_role(Role::SPIN_BUTTON).into_iter().next().expect("the radius row has a number field"); - fixture.click(&field).settle(); - fixture.key(Key::A, Modifiers::COMMAND); - fixture.type_text("55").settle(); - let typed = fixture.by_role(Role::SPIN_BUTTON).into_iter().next().and_then(|field| fixture.tree().value_of(field.node).map(str::to_owned)); - assert_eq!(typed.as_deref(), Some("55"), "the field shows the typing as a draft"); - fixture.key(Key::Escape, Modifiers::NONE).settle(); - assert!(matches!(seen.get(), Some((CloseReason::Escape, false))), "one Escape cancels the dialog: {:?}", seen.get()); + } } // Alt turns Cancel into Reset, which restores the opening values with the `reset_to` ones over them: a key `reset_to` From 85ba69b147b17fba8cd2eb554e0e723cb5932cbc Mon Sep 17 00:00:00 2001 From: bflatastic Date: Tue, 24 Nov 2026 00:57:53 +0700 Subject: [PATCH 3/5] ui-patterns: PaletteOutput::refused names the disabled command Enter was pressed on, from the new CollectionEvent::Refused of a disabled lead's Enter, so an app can close the palette and say why: the palette stayed open and told the app nothing --- .../src/contract/collection/events.rs | 2 ++ crates/ui-contract/src/contract/items/keys.rs | 7 ++++++- crates/ui-contract/src/testing/story.rs | 3 +++ .../src/patterns/panels/palette.rs | 20 +++++++++++-------- crates/ui-patterns/tests/it/panels/palette.rs | 17 +++++++++++----- 5 files changed, 35 insertions(+), 14 deletions(-) diff --git a/crates/ui-contract/src/contract/collection/events.rs b/crates/ui-contract/src/contract/collection/events.rs index b9d884319b..ecf778f440 100644 --- a/crates/ui-contract/src/contract/collection/events.rs +++ b/crates/ui-contract/src/contract/collection/events.rs @@ -232,6 +232,8 @@ pub enum CollectionEvent { }, /// Enter or a double click on an item. Activate(K), + /// Enter on a disabled lead: nothing ran. A host that says why, or closes what the collection is in, reads it. + Refused(K), /// The pointer has rested on the hovered lead row for the tooltip delay, or the lead moved by a key: the row's /// key, once per lead change. Rested(K), diff --git a/crates/ui-contract/src/contract/items/keys.rs b/crates/ui-contract/src/contract/items/keys.rs index a12afc00b8..bc2c1ad8fc 100644 --- a/crates/ui-contract/src/contract/items/keys.rs +++ b/crates/ui-contract/src/contract/items/keys.rs @@ -150,7 +150,12 @@ impl ItemsHooks<'_, '_, C> { // A disabled lead does not run, as a press on it does not. if activated && !header_held - && let Some(row) = lead_at.filter(|&row| self.source.enabled(row)) + && let Some(row) = lead_at.filter(|&row| !self.source.enabled(row)) + { + self.events.push(CollectionEvent::Refused(self.source.key(row))); + } else if activated + && !header_held + && let Some(row) = lead_at { // Where the arrows leave the selection, Enter picks the lead it activates. if !props.arrows_select && !self.holds(row) { diff --git a/crates/ui-contract/src/testing/story.rs b/crates/ui-contract/src/testing/story.rs index d8619dd577..a4f8af6a50 100644 --- a/crates/ui-contract/src/testing/story.rs +++ b/crates/ui-contract/src/testing/story.rs @@ -649,6 +649,8 @@ pub enum CollectionKind { Rested, /// Enter or a double click on an item. Activate, + /// Enter on a disabled lead. + Refused, /// A double click on the empty space. EmptyActivated, /// A secondary click on the empty space. @@ -691,6 +693,7 @@ impl CollectionKind { CollectionEvent::Picked { .. } => CollectionKind::Picked, CollectionEvent::LeadMoved { .. } => CollectionKind::LeadMoved, CollectionEvent::Activate(_) => CollectionKind::Activate, + CollectionEvent::Refused(_) => CollectionKind::Refused, CollectionEvent::Rested(_) => CollectionKind::Rested, CollectionEvent::EmptyActivated => CollectionKind::EmptyActivated, CollectionEvent::EmptyContextMenu { .. } => CollectionKind::EmptyContextMenu, diff --git a/crates/ui-patterns/src/patterns/panels/palette.rs b/crates/ui-patterns/src/patterns/panels/palette.rs index 37f6153e61..2ac09e7201 100644 --- a/crates/ui-patterns/src/patterns/panels/palette.rs +++ b/crates/ui-patterns/src/patterns/panels/palette.rs @@ -99,6 +99,9 @@ pub struct PaletteOutput { pub closed: Option, /// The query the fallback row handed back, when the user picked it in this pass. pub fallback: Option, + /// The disabled command of the active row Enter was pressed on in this pass: nothing ran and the palette stays + /// open, its footer saying why. An app that closes the palette there and reports the reason itself reads it. + pub refused: Option, } impl crate::contract::Outcome for PaletteOutput { @@ -269,7 +272,7 @@ impl<'a> CommandPalette<'a> { conclude(cx, &ctx, &chosen, &label, recent, &mut recents); }); let closed = shown.output.closed; - PaletteOutput { response: shown.output.response, picked: chosen.picked, closed, fallback: chosen.fallback } + PaletteOutput { response: shown.output.response, picked: chosen.picked, closed, fallback: chosen.fallback, refused: chosen.refused } } fn show_in_place(self, ui: &mut Ui) -> PaletteOutput { @@ -336,7 +339,7 @@ impl<'a> CommandPalette<'a> { closed = popup.output.closed; }); }); - PaletteOutput { response: shown.output, picked: chosen.picked, closed, fallback: chosen.fallback } + PaletteOutput { response: shown.output, picked: chosen.picked, closed, fallback: chosen.fallback, refused: chosen.refused } } } @@ -349,6 +352,7 @@ struct WasOpen(bool); struct Chosen { picked: Option, fallback: Option, + refused: Option, } /// What the list body reads, the same for both faces. @@ -407,13 +411,13 @@ fn show_rows(ui: &mut Ui, input: &RowsInput<'_>, state: &mut Session, env: &crat } let events = list.show_items(ui, &source, &mut |key, _| rows[position(&listed.keys, *key)].row()).events; let mut chosen = Chosen::default(); + let command = |at: usize| input.entries.get(at).map(|entry| entry.command().clone()); for event in events { - if let CollectionEvent::Activate(key) = event { - match key { - Line::Entry(at) => chosen.picked = input.entries.get(at).map(|entry| entry.command().clone()), - Line::Fallback => chosen.fallback = Some(found.clone()), - Line::Heading | Line::Separator => {} - } + match event { + CollectionEvent::Activate(Line::Entry(at)) => chosen.picked = command(at), + CollectionEvent::Activate(Line::Fallback) => chosen.fallback = Some(found.clone()), + CollectionEvent::Refused(Line::Entry(at)) => chosen.refused = command(at), + _ => {} } } let status = status_of(ui, input, &listed, &rows, state.selection.lead, found.is_empty(), env); diff --git a/crates/ui-patterns/tests/it/panels/palette.rs b/crates/ui-patterns/tests/it/panels/palette.rs index 70f7ad786b..ecfd5ea24a 100644 --- a/crates/ui-patterns/tests/it/panels/palette.rs +++ b/crates/ui-patterns/tests/it/panels/palette.rs @@ -38,6 +38,8 @@ struct Rig { open: Rc>, /// The last command picked. picked: Rc>>, + /// The last disabled command Enter was refused on. + refused: Rc>>, /// The bound `recents`, newest first; empty and unused when the rig keeps them in the palette. recents: Rc>>, } @@ -47,9 +49,10 @@ struct Rig { fn rig(entries: Vec, recents: Option>, in_dialog: bool, beneath: impl Fn(&mut Ui) + 'static) -> Rig { let open = Rc::new(Cell::new(true)); let picked = Rc::new(RefCell::new(None::)); + let refused = Rc::new(RefCell::new(None::)); let bound = recents.is_some(); let held = Rc::new(RefCell::new(recents.unwrap_or_default())); - let (shown_open, shown_picked, shown_held) = (open.clone(), picked.clone(), held.clone()); + let (shown_open, shown_picked, shown_refused, shown_held) = (open.clone(), picked.clone(), refused.clone(), held.clone()); let fixture = Fixture::new(move |ui| { beneath(ui); let show = |ui: &mut Ui| { @@ -70,6 +73,9 @@ fn rig(entries: Vec, recents: Option>, in_dialog: boo if let Some(command) = output.picked { *shown_picked.borrow_mut() = Some(command); } + if let Some(command) = output.refused { + *shown_refused.borrow_mut() = Some(command); + } }; if in_dialog { Popover::new("Levels", Bind::given(true)).overlay(|_| Overlay::modal()).show(ui, |ui, _| show(ui)); @@ -77,7 +83,7 @@ fn rig(entries: Vec, recents: Option>, in_dialog: boo show(ui); } }); - Rig { fixture, open, picked, recents: held } + Rig { fixture, open, picked, refused, recents: held } } /// A palette open over `entries`, inside a modal dialog when `in_dialog`; `picked` holds the last pick. @@ -504,12 +510,12 @@ fn the_active_row_marks_its_shown_control_and_a_hidden_home_goes_to_the_footer() } /// Enter on a query whose first match is disabled runs nothing, though an enabled match follows it: the first match is -/// the active row, the one the footer explains. Guards against an active row that skipped the disabled first match, so -/// Enter ran the match after it. +/// the active row, the one the footer explains, and the output names it as refused so an app can close and say why. +/// Guards against an active row that skipped the disabled first match, so Enter ran the match after it. #[trial] fn enter_on_a_disabled_first_match_runs_nothing() { let entries = vec![HelpEntry::new(EditCommands::Undo, "Undo").with_path(["Edit"]), HelpEntry::new(TrialCommand::Rotate, "Undo Rotation")]; - let (mut fixture, open, picked) = palette(entries, false); + let Rig { mut fixture, open, picked, refused, .. } = rig(entries, None, false, |_| ()); fixture.command_state(EditCommands::Undo, CommandState::new().enabled(false)); fixture.settle(); fixture.type_text("undo").settle(); @@ -518,6 +524,7 @@ fn enter_on_a_disabled_first_match_runs_nothing() { let _ = take_output(fixture.ctx()); fixture.key(Key::Enter, Modifiers::NONE).settle(); assert_eq!(*picked.borrow(), None, "Enter on the disabled first match picks nothing"); + assert_eq!(*refused.borrow(), Some(CommandRef::from(EditCommands::Undo)), "the output names the refused command"); assert!(open.get(), "the palette stays open"); assert!(take_output(fixture.ctx()).fired.is_empty(), "nothing ran"); } From 83b922e633cbc5dc08b687424790244345e410b4 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Tue, 24 Nov 2026 00:58:07 +0700 Subject: [PATCH 4/5] ui-contract: an Alt chord's text is withheld only when a binding of it in a scope around the focus can run, as the key stage matches the press: a type editor's Alt chord in a scope no focused component is in kept the character a layout types for it (a Blob Brush's [) from reaching anything --- .../ui-contract/src/runtime/commands/board.rs | 17 +++++-- crates/ui-contract/src/runtime/keys/input.rs | 4 +- crates/ui-contract/tests/it/text/editor.rs | 46 +++++++++++++++++++ 3 files changed, 60 insertions(+), 7 deletions(-) diff --git a/crates/ui-contract/src/runtime/commands/board.rs b/crates/ui-contract/src/runtime/commands/board.rs index b470a9cdcf..76f549da39 100644 --- a/crates/ui-contract/src/runtime/commands/board.rs +++ b/crates/ui-contract/src/runtime/commands/board.rs @@ -1241,11 +1241,18 @@ pub(crate) fn holder(ctx: &Context, chord: &Chord) -> Option { with(ctx, |board| board.keymap.as_ref().and_then(|cache| cache.keymap.holder(chord))) } -/// Whether a command the window's keymap binds `chord` to is enabled, as the last pass resolved it for a surface with -/// no component of its own (the state a menu row shows): a press of the chord can run something. Notes no reader. -pub(crate) fn runs_now(ctx: &Context, chord: &Chord) -> bool { - let holders = with(ctx, |board| board.keymap.as_ref().map(|cache| cache.keymap.holders(chord)).unwrap_or_default()); - holders.iter().any(|command| resolve_from(ctx, command, None).0.enabled) +/// Whether a press of `chord` in `viewport` can run something: a command the window's keymap binds it to in a scope +/// around the focus of the viewport's last pass, matched as the key stage matches a press outside typing, is enabled as +/// that pass resolved it for a surface with no component of its own (the state a menu row shows). A binding in a scope +/// that is not around the focus (a typing scope with no editor shown) runs nothing. Notes no reader. +pub(crate) fn runs_now(ctx: &Context, viewport: ViewportId, chord: &Chord) -> bool { + let keys = with(ctx, |board| { + let chain = board.here.focused.iter().find(|(at, _)| *at == viewport).map(|(_, chain)| chain.clone()).unwrap_or_default(); + board.key_scopes(&chain) + }); + let Some(keys) = keys else { return false }; + let enabled = |command: &CommandRef| resolve_from(ctx, command, None).0.enabled; + keys.matching(false, |active, outer| !matches!(keys.keymap.lookup_where(chord, false, active, outer, &enabled), craft_keymap::Lookup::None)) } /// The chords bound to the window's keys, which the input hook takes before any component. diff --git a/crates/ui-contract/src/runtime/keys/input.rs b/crates/ui-contract/src/runtime/keys/input.rs index 6c078ba97d..07db079be5 100644 --- a/crates/ui-contract/src/runtime/keys/input.rs +++ b/crates/ui-contract/src/runtime/keys/input.rs @@ -629,7 +629,7 @@ pub(crate) fn input_hook(ctx: &Context, input: &RawInput, events: &mut Vec NavKeys { let viewport = crate::runtime::egui::pass::current_viewport(ctx); let gate = tab_toggles_now(ctx); let layout = layout_of(ctx); - let fires = |input: &KeyInput| layout.candidates(input).iter().any(|chord| commands::runs_now(ctx, chord)); + let fires = |input: &KeyInput| layout.candidates(input).iter().any(|chord| commands::runs_now(ctx, viewport, chord)); for press in tabs { match gate.then(|| chrome_toggle_of(ctx, &press.input)).flatten() { Some(toggle) if !press.repeat => request_chrome_toggle(ctx, viewport, toggle), diff --git a/crates/ui-contract/tests/it/text/editor.rs b/crates/ui-contract/tests/it/text/editor.rs index 6061749136..3c7db0a92e 100644 --- a/crates/ui-contract/tests/it/text/editor.rs +++ b/crates/ui-contract/tests/it/text/editor.rs @@ -957,3 +957,49 @@ fn a_command_a_chord_fires_reaches_its_editor_between_the_typing_around_it() { "the command sits between the texts its chord came between: {steps:?}" ); } + +/// A type editor's typing scope with a chord that types a character on some layouts: a dash command on Alt+Shift+-, +/// where Option+Shift+- types an em dash on the Mac. +#[derive(Clone, Copy, Debug, PartialEq, Eq, CommandSet)] +#[command(prefix = "dashTrial", scope = "trial.dashes", typing)] +#[non_exhaustive] +enum DashCommand { + #[command(label = "Dash", default = "Alt+Shift+-")] + Dash, +} + +/// The text of an Alt chord bound only in a scope that is not around the focus (the typing scope of a type editor shown +/// beside the focused field) is typed in the field: the press runs nothing there. Guards a key stage that withheld the +/// text for any enabled binding of the chord, whatever its scope, so the character went nowhere. +#[trial] +fn an_alt_chord_bound_only_out_of_scope_leaves_its_text_typed() { + use craft_behavior::Input; + use craft_ui::runtime::focus::{FocusTarget, request}; + use craft_ui::runtime::frame::take_output; + use craft_ui::testing::focus::{Stop, intents_of, named_id, register_stop, widget}; + + let field = named_id("dash field"); + let (typed, focus, steps) = (RefCell::new(String::new()), Cell::new(true), RefCell::new(Vec::new())); + let mut show = |ui: &mut egui::Ui| { + let _ = Typer { common: Common::new(), steps: &steps }.label("Type").command_scope(::SCOPE).show_at(ui, AT); + widget(ui, field); + register_stop(ui.ctx(), Stop::new(field, KeyUse::of(Input::Text))); + if focus.take() { + request(ui.ctx(), FocusTarget::Id(field)); + } + let mut intents = intents_of(ui.ctx(), Some(field), false); + while let Some(text) = intents.take_text() { + typed.borrow_mut().push_str(&text); + } + }; + let mut frames = Frames::new(); + frames.idle(3, &mut show); + take_output(&frames.ctx); + let alt_shift = Modifiers { alt: true, shift: true, ..Modifiers::NONE }; + frames.frame(vec![key_press(Key::Minus, alt_shift), Event::Text("\u{2014}".into())], &mut show); + frames.frame(vec![key_release(Key::Minus, alt_shift)], &mut show); + frames.idle(1, &mut show); + assert_eq!(typed.take(), "\u{2014}", "the field types the chord's text"); + let fired: Vec = take_output(&frames.ctx).fired.into_iter().map(|fired| fired.command.id).collect(); + assert!(fired.is_empty(), "nothing ran: {fired:?}"); +} From 0726c0f87de00ce8390003b635478b8a08d161c8 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Tue, 24 Nov 2026 00:58:13 +0700 Subject: [PATCH 5/5] ui-contract, ui-canvas: KeyUse::command_keys and Canvas::editor_command_keys: a canvas editor that has the keys leaves chords with the platform's command modifier and function keys to the app's commands under any typing rule, its text editing chords kept; off by default: under TypingRule::AllWait a type tool's editor ran none of the app's Cmd chords or function keys --- crates/ui-canvas/src/canvas/mod.rs | 11 ++++- crates/ui-canvas/tests/it/canvas/editor.rs | 42 ++++++++++++++++++- .../ui-contract/src/runtime/commands/board.rs | 9 +++- .../ui-contract/src/runtime/focus/policy.rs | 12 ++++++ crates/ui-contract/src/runtime/keys.rs | 2 + crates/ui-contract/src/runtime/keys/route.rs | 3 +- 6 files changed, 75 insertions(+), 4 deletions(-) diff --git a/crates/ui-canvas/src/canvas/mod.rs b/crates/ui-canvas/src/canvas/mod.rs index 1749760a68..521fa72e65 100644 --- a/crates/ui-canvas/src/canvas/mod.rs +++ b/crates/ui-canvas/src/canvas/mod.rs @@ -223,6 +223,11 @@ pub struct Canvas<'a> { /// and Redo fall through to the app command's state. Ignored without [`editor`](Self::editor). #[prop] inactive_edits: EditSet, + /// While the editor part has the keys, chords with the platform's command modifier and function keys still run the + /// app's commands, whatever its typing rule ([`KeyUse::command_keys`]): a type tool whose app runs its commands + /// while typing. The editor keeps its text editing chords. Ignored without [`editor`](Self::editor). + #[prop] + editor_command_keys: bool, /// The editor part's inputs of this pass, taken once in `update`: `tool_pass` is built from a shared `Cx`. editor_input: Arc<[EditorInput]>, /// The rulers' units and zero point, published to the body in its [`CanvasSpace`]. @@ -315,6 +320,7 @@ impl<'a> Canvas<'a> { keys_to_body: false, editor: None, inactive_edits: EditSet::NONE, + editor_command_keys: false, editor_input: Arc::from([]), pasteboard: PasteboardColor::Default, precise_cursors: false, @@ -838,7 +844,10 @@ impl Component for Canvas<'_> { /// nudges. It still marks its window as showing a document. fn keys(&self) -> KeyUse { match self.editor { - Some(_) => KeyUse::of(Input::Editor).with_chrome_key(true).with_moves().with_inactive(self.inactive_edits), + Some(_) => { + let keys = KeyUse::of(Input::Editor).with_chrome_key(true).with_moves().with_inactive(self.inactive_edits); + if self.editor_command_keys { keys.with_command_keys() } else { keys } + } None => Self::KEYS, } } diff --git a/crates/ui-canvas/tests/it/canvas/editor.rs b/crates/ui-canvas/tests/it/canvas/editor.rs index 688d7438a0..d449f8b960 100644 --- a/crates/ui-canvas/tests/it/canvas/editor.rs +++ b/crates/ui-canvas/tests/it/canvas/editor.rs @@ -8,7 +8,9 @@ use craft_ui::canvas::{Canvas, tool_pass}; use craft_ui::contract::{Bind, Show as _, ShowContainer as _}; use craft_ui::primitives::{EditorPurpose, EditorState}; use craft_ui::runtime::access::Role; -use craft_ui::runtime::commands::{CommandRef, CommandState, EditCommands, resolve}; +use craft_ui::runtime::commands::{ + AppCatalog, Binding, CommandDef, CommandInput, CommandRef, CommandState, EditCommands, Platform, Scope, TypingRule, resolve, +}; use craft_ui::runtime::focus::{self, EditSet}; use craft_ui::runtime::frame; use craft_ui::testing::focus::egui_focused; @@ -213,3 +215,41 @@ fn inactive_edits_disable_cut_and_let_undo_and_redo_fall_through_to_app_state() fixture.settle(); assert!(resolve(fixture.ctx(), EditCommands::Cut).enabled, "selecting text in the TextField enables Cut independently"); } + +/// Under a typing rule that fires nothing while typing (`AllWait`), a canvas editor that lets command keys through +/// (`Canvas::editor_command_keys`) leaves a Cmd chord and a function key to the app's commands while it has the keys, +/// and a plain key bound to a command stays its typing; without it none of them fires. Guards a type tool whose app ran +/// its commands while typing. +#[trial] +fn a_canvas_editor_that_lets_command_keys_through_runs_them_while_typing() { + const ALIGN: &str = "canvasTrial.alignRight"; + const ACTION: &str = "canvasTrial.action"; + const TOOL: &str = "canvasTrial.tool"; + for through in [false, true] { + let mut fixture = Fixture::new(move |ui| { + let room = ui.available_rect_before_wrap(); + let view = CanvasView::new(room, Point::new(PAGE.width / 2.0, PAGE.height / 2.0), 1.0); + let _ = canvas(view).editor_command_keys(through).show_at(ui, room, |_, _| {}); + }); + fixture.os(Platform::Linux); + let def = + |id: &str, chord: &str| CommandDef::new(id, id, Scope::app()).with_default(Binding::parse(chord).expect("the trial's chord parses")); + let catalog = AppCatalog::new(vec![def(ALIGN, "Cmd+Shift+R"), def(ACTION, "F7"), def(TOOL, "P")], 1) + .expect("the trial's catalog is valid") + .typing_rule(TypingRule::AllWait); + fixture.commands(CommandInput::new().catalog(catalog)); + fixture.room(ROOM); + fixture.settle(); + fixture.click_at((ROOM / 2.0).to_pos2()); + fixture.settle(); + frame::take_output(fixture.ctx()); + fixture.key(Key::R, Modifiers::COMMAND | Modifiers::SHIFT); + fixture.key(Key::F7, Modifiers::NONE); + fixture.key(Key::P, Modifiers::NONE); + fixture.settle(); + let fired: Vec = + frame::take_output(fixture.ctx()).fired.into_iter().map(|fired| fired.command.id).filter(|id| id.starts_with("canvasTrial.")).collect(); + let expected: Vec = if through { vec![ALIGN.to_owned(), ACTION.to_owned()] } else { Vec::new() }; + assert_eq!(fired, expected, "command keys let through: {through}"); + } +} diff --git a/crates/ui-contract/src/runtime/commands/board.rs b/crates/ui-contract/src/runtime/commands/board.rs index 76f549da39..11d9e804cf 100644 --- a/crates/ui-contract/src/runtime/commands/board.rs +++ b/crates/ui-contract/src/runtime/commands/board.rs @@ -2080,7 +2080,14 @@ pub(crate) fn begin(ctx: &Context) { let (_, instance) = with(ctx, |board| board.target_of(ctx, command, &board.here)); resolve_in(ctx, command, instance, Reach::Focus, None, Reads::default()).0.enabled }; - let typing = shortcuts.typing && !shortcut.canvas; + // A text component that lets command keys through leaves their presses to the app's commands. + let command_key = shortcuts.command_keys + && shortcuts + .layout + .candidates(&shortcut.input) + .first() + .is_some_and(|chord| TypingRule::CommandKeysOnly.fires(chord, keys.keymap.platform())); + let typing = shortcuts.typing && !shortcut.canvas && !command_key; let hold = key .filter(|_| !typing && !modal_at_start) .and_then(|key| keys.hold(&shortcuts.layout, &shortcut.input, typing).map(|hold| (key, hold))); diff --git a/crates/ui-contract/src/runtime/focus/policy.rs b/crates/ui-contract/src/runtime/focus/policy.rs index f5077026c4..d0f6a20b68 100644 --- a/crates/ui-contract/src/runtime/focus/policy.rs +++ b/crates/ui-contract/src/runtime/focus/policy.rs @@ -312,6 +312,10 @@ pub struct KeyUse { /// The component is a text field whose draft a press on a part declared `holds_drafts`, or on a popup layer above /// it, leaves unapplied; a lone Alt in the field only alerts and a window deactivation does not commit the draft. pub holds_drafts: bool, + /// While the component types, chords with the platform's command modifier and function keys still run the app's + /// commands whatever the app's typing rule, as under `TypingRule::CommandKeysOnly`; the text editing chords stay + /// the component's. For a canvas tool's text editor whose app runs its commands while typing. + pub command_keys: bool, } /// Which Tab stops a dialog's Tab order visits. @@ -348,6 +352,7 @@ impl KeyUse { session: false, type_ahead: false, holds_drafts: false, + command_keys: false, }; /// A divider between panes: it takes the arrows as moves of its value, but it is no document and no canvas tool, so /// it marks no window as showing a document and takes no nudges. @@ -389,6 +394,7 @@ impl KeyUse { session: false, type_ahead: false, holds_drafts: false, + command_keys: false, } } @@ -398,6 +404,12 @@ impl KeyUse { self } + /// The same use letting command chords and function keys run the app's commands while it types (`command_keys`). + pub const fn with_command_keys(mut self) -> Self { + self.command_keys = true; + self + } + /// The same use taking typed letters as `Intent::Text`. pub const fn with_type_ahead(mut self) -> Self { self.type_ahead = true; diff --git a/crates/ui-contract/src/runtime/keys.rs b/crates/ui-contract/src/runtime/keys.rs index 0685723b3d..37558efe90 100644 --- a/crates/ui-contract/src/runtime/keys.rs +++ b/crates/ui-contract/src/runtime/keys.rs @@ -133,6 +133,8 @@ pub(crate) struct Shortcuts { pub(crate) keys: Vec, /// A text field owns the keys: plain keys wait for it. pub(crate) typing: bool, + /// The text component that owns the keys leaves command chords and function keys to the app (`KeyUse::command_keys`). + pub(crate) command_keys: bool, /// A dialog owns the keys: commands that do not fire in dialogs wait. pub(crate) dialog: bool, /// The layout that reads the presses. diff --git a/crates/ui-contract/src/runtime/keys/route.rs b/crates/ui-contract/src/runtime/keys/route.rs index b182cf499d..2dc9982b95 100644 --- a/crates/ui-contract/src/runtime/keys/route.rs +++ b/crates/ui-contract/src/runtime/keys/route.rs @@ -252,6 +252,7 @@ fn owned_shortcuts(ctx: &Context, target: Option<&StopRec>, batch: &Batch, consu let dialog = owner == KeyOwner::Class(OwnerClass::Dialog); // The focused component keeps its own keys inside a dialog: a text field its typing, a widget its activation. let typing = owner != KeyOwner::Blocked && own == Some(OwnerClass::Text); + let command_keys = typing && target.is_some_and(|rec| rec.stop.keys.command_keys); let held: Vec = batch .presses .iter() @@ -275,7 +276,7 @@ fn owned_shortcuts(ctx: &Context, target: Option<&StopRec>, batch: &Batch, consu .collect(); let keys = batch.shortcuts.iter().zip(&kept).filter(|(_, stays)| **stays).map(|(shortcut, _)| *shortcut).collect(); let mods = remap_mods(&batch.mods, &kept); - (Shortcuts { keys, typing, dialog, layout: Layout::default(), mods, focus_lost: batch.focus_lost }, held) + (Shortcuts { keys, typing, command_keys, dialog, layout: Layout::default(), mods, focus_lost: batch.focus_lost }, held) } /// Whether the focused stop `target`, whose keys `owner` owns, holds `press`: the press is its own and reaches neither