From d1920c54e71abdd997d95aacc0d14ec01d0e5542 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Wed, 25 Nov 2026 08:04:54 +0700 Subject: [PATCH] ui-contract: an edit command fired before the pass's UI (a system menu pick) reaches the focused component in that pass, and a text part's stop registers the edit keys its pass's edits left, so a menu Copy after a Select All is not disabled; a pick in the window's own menus or bars still reaches it in the next pass --- crates/ui-contract/src/contract/run.rs | 27 ++++++---- crates/ui-contract/src/contract/text.rs | 12 +++-- .../src/primitives/text_adapter.rs | 30 +++++++----- crates/ui-contract/src/runtime/keys.rs | 3 ++ .../ui-contract/src/runtime/keys/intents.rs | 6 ++- crates/ui-contract/src/runtime/keys/route.rs | 19 +++++-- crates/ui-widgets/tests/it/bars/edit_focus.rs | 49 +++++++++++++++++-- 7 files changed, 108 insertions(+), 38 deletions(-) diff --git a/crates/ui-contract/src/contract/run.rs b/crates/ui-contract/src/contract/run.rs index c87b86cf68..942b93fd31 100644 --- a/crates/ui-contract/src/contract/run.rs +++ b/crates/ui-contract/src/contract/run.rs @@ -702,13 +702,10 @@ fn own_sense(e: &dyn ErasedPass<'_>, resolved: &Resolved, inert: bool) -> Sense } /// The widget that holds the component's text or editor and the keys it keeps, when it has either. -fn text_holder(ctx: &Context, id: Id, parts: &PartsStep, base: focus::KeyUse, memory: &mut MemoryStage) -> (Option, Option) { +fn text_holder(id: Id, parts: &PartsStep, base: focus::KeyUse) -> (Option, Option) { let text = parts.text.decl.as_ref().map(|decl| { let decl = &decl.part; - let widget = crate::primitives::text_adapter::text_id(id, decl.key); - let held = crate::contract::text::held_selection(memory, id); - let draft = crate::contract::text::draft(memory, id); - (widget, crate::primitives::text_adapter::keys_of(ctx, widget, held, draft.as_deref().unwrap_or(&decl.shown), base, &decl.options)) + (crate::primitives::text_adapter::text_id(id, decl.key), crate::primitives::text_adapter::keys_of(base, &decl.options)) }); let editor = parts.text.editor.as_ref().map(|decl| (crate::primitives::ImeSurface::of(id, decl.key).widget(), super::editor::keys_of(base, decl.purpose))); @@ -718,6 +715,17 @@ fn text_holder(ctx: &Context, id: Id, parts: &PartsStep, base: focus::KeyUse, me } } +/// `keys`, those of the component's text part, with the edits it cannot run now inactive (`text_adapter::with_idle`), +/// read after the text step, so they are as the pass's edits left the selection and the undo steps. +fn idle_keys(ctx: &Context, id: Id, parts: &PartsStep, keys: focus::KeyUse, memory: &mut MemoryStage) -> focus::KeyUse { + let Some(decl) = &parts.text.decl else { return keys }; + let decl = &decl.part; + let held = crate::contract::text::held_selection(memory, id); + let draft = crate::contract::text::draft(memory, id); + let widget = crate::primitives::text_adapter::text_id(id, decl.key); + crate::primitives::text_adapter::with_idle(ctx, widget, held, draft.as_deref().unwrap_or(&decl.shown), keys) +} + /// What the stops of a component read: the owner, its place in a member group and the text it holds. struct StopsStep<'a> { ctx: &'a Context, @@ -1000,7 +1008,7 @@ fn sense_steps(p: &mut Pass<'_, '_, '_>, ui: &mut Ui, host_at: Option, e } steps::check_parts(&ctx, facts.name, &parts); let keys = e.keys(); - let (holder_widget, text_keys) = text_holder(&ctx, id, &parts, keys, &mut *e.core().memory); + let (holder_widget, text_keys) = text_holder(id, &parts, keys); let own = own_sense(e, resolved, inert); // The collection handles a row's click, but its access node must still offer the redirected action. let unnarrowed = own; @@ -1175,9 +1183,10 @@ fn update_steps(p: &mut Pass<'_, '_, '_>, env: &Env, h: &HostStep) { } e.updated(); steps::record_context(e.core_ref()); - // The stops register after `update`, which says whether the component joins its body's roving group. - let at = - StopsStep { ctx, id, rtl, env, resolved: p.resolved, holder_widget: h.holder_widget, member: h.member, own: h.own, text_keys: h.text_keys }; + // The stops register after `update`, which says whether the component joins its body's roving group, and after + // the text step, so a Select All of the pass makes Copy active. + let text_keys = h.text_keys.map(|keys| idle_keys(ctx, id, &h.parts, keys, &mut *e.core().memory)); + let at = StopsStep { ctx, id, rtl, env, resolved: p.resolved, holder_widget: h.holder_widget, member: h.member, own: h.own, text_keys }; stops_step(at, e, facts, &h.parts); // The body's group registers after `update`, which may change its rules from what the component knows now. if let Some(roving) = e.roving() { diff --git a/crates/ui-contract/src/contract/text.rs b/crates/ui-contract/src/contract/text.rs index eb2926753f..5a855c7f06 100644 --- a/crates/ui-contract/src/contract/text.rs +++ b/crates/ui-contract/src/contract/text.rs @@ -99,8 +99,9 @@ pub(crate) fn run_selections(core: &mut super::cx::CxCore<'_>, selections: &[Sel pub(crate) struct TextDecl { pub part: TextPart, - /// A `Resolve` for the component's value type, invoked after the adapter records the pass. - resolve: Box, + /// A `Resolve` for the component's value type, which the text step takes and invokes after the adapter records + /// the pass; the part stays declared, so the stops read its keys as the pass's edits left them. + resolve: Option>, values: ValueOps, } @@ -309,7 +310,7 @@ impl PartsCx<'_, C> { shown, options: declared, }, - resolve, + resolve: Some(resolve), values: ValueOps::of::(), }); } @@ -590,8 +591,9 @@ pub(crate) fn run( ink: egui::Color32, underline: f32, ) { - let Some(decl) = step.decl.take() else { return }; - let Ok(resolve) = decl.resolve.downcast::>>() else { + let Some(decl) = step.decl.as_mut() else { return }; + let Some(resolve) = decl.resolve.take() else { return }; + let Ok(resolve) = resolve.downcast::>>() else { debug_assert!(false, "the text part's codec value is the component's value"); return; }; diff --git a/crates/ui-contract/src/primitives/text_adapter.rs b/crates/ui-contract/src/primitives/text_adapter.rs index a283417256..f57d2d47f0 100644 --- a/crates/ui-contract/src/primitives/text_adapter.rs +++ b/crates/ui-contract/src/primitives/text_adapter.rs @@ -98,15 +98,8 @@ pub(crate) fn text_id(id: Id, key: PartKey) -> Id { crate::runtime::memory::sub(id, ("text", key)) } -/// The keys the text part keeps, from its options and the selection of its widget `widget`: with no selection Cut, -/// Copy and Delete are inactive, and so are Undo and Redo while the widget has no step for them, so their keys and menu -/// picks still reach the part and the edit menu shows them disabled. Cut, Copy and Delete then do nothing and never -/// reach the app; an Undo or Redo with no step goes on to the app command (`commands::fall_through`), which the board -/// resolves it to. The board reads the keys the stop registered; a selection or text change repaints, which registers -/// them again. The selection is the one the part acts on: `held`, the one it kept while its edit menu or a menu bar has -/// the focus (egui collapses the selection of a widget without focus), else its widget's. `text` is the part's current text, which -/// the widget's undo steps are judged against. -pub(crate) fn keys_of(ctx: &Context, widget: Id, held: Option<(usize, usize)>, text: &str, base: KeyUse, options: &TextOptions) -> KeyUse { +/// The keys the text part keeps, from its options. +pub(crate) fn keys_of(base: KeyUse, options: &TextOptions) -> KeyUse { // A part whose Tab inserts, rewrites or reports keeps Tab, so the focus service never moves focus on it. let keys = if options.tab != TabKey::Moves { base.with_keep(KeepKeys::Tab) @@ -117,6 +110,19 @@ pub(crate) fn keys_of(ctx: &Context, widget: Id, held: Option<(usize, usize)>, t }; let keys = keys.with_value(base.value || options.steps_value); let keys = if options.holds_drafts { keys.with_holds_drafts() } else { keys }; + // A multi-line part makes a plain Enter a line break. + if options.submits || options.multiline() { keys.with_submits() } else { keys } +} + +/// `keys`, the text part's, with the edits its widget `widget` cannot run now inactive: with no selection Cut, Copy +/// and Delete, and Undo and Redo while the widget has no step for them, so their keys and menu picks still reach the +/// part and the edit menu shows them disabled. Cut, Copy and Delete then do nothing and never reach the app; an Undo +/// or Redo with no step goes on to the app command (`commands::fall_through`), which the board resolves it to. The +/// board reads the keys the stop registered, which reads them after the part applied the pass's edits, so a Select All +/// of the pass makes Copy active. The selection is the one the part acts on: `held`, the one it kept while its edit +/// menu or a menu bar has the focus (egui collapses the selection of a widget without focus), else its widget's. +/// `text` is the part's current text, which the widget's undo steps are judged against. +pub(crate) fn with_idle(ctx: &Context, widget: Id, held: Option<(usize, usize)>, text: &str, keys: KeyUse) -> KeyUse { let selected = held.or_else(|| selection(ctx, widget)).is_some_and(|(caret, anchor)| caret != anchor); let (undo, redo) = text_edit::history(ctx, widget, text); let idle = [ @@ -127,11 +133,9 @@ pub(crate) fn keys_of(ctx: &Context, widget: Id, held: Option<(usize, usize)>, t (EditCommand::Redo, !redo), ] .into_iter() - .filter(|(command, idle)| *idle && base.edits.contains(*command)) + .filter(|(command, idle)| *idle && keys.edits.contains(*command)) .map(|(command, _)| command); - let keys = keys.with_inactive(idle.fold(base.inactive, EditSet::with)); - // A multi-line part makes a plain Enter a line break. - if options.submits || options.multiline() { keys.with_submits() } else { keys } + keys.with_inactive(idle.fold(keys.inactive, EditSet::with)) } pub(crate) struct AdapterIn<'a> { diff --git a/crates/ui-contract/src/runtime/keys.rs b/crates/ui-contract/src/runtime/keys.rs index a09f13fb0a..bc84720273 100644 --- a/crates/ui-contract/src/runtime/keys.rs +++ b/crates/ui-contract/src/runtime/keys.rs @@ -325,6 +325,9 @@ pub(crate) struct Stage { pasted: Option<(Id, ClipContent)>, /// Edit commands fired from the queue for the focused component. queued_edits: Vec, + /// A component read its intents in this pass, so the pass's UI is running: an edit fired from now on waits for the + /// next pass. + intents_read: bool, /// The components that asked for a context menu in this pass, with the rect it opens at. contexts: Vec<(Id, egui::Rect, Option)>, /// Components with an open edit run this pass: Escape cancels the run before it leaves a row's child. diff --git a/crates/ui-contract/src/runtime/keys/intents.rs b/crates/ui-contract/src/runtime/keys/intents.rs index 925c3123a5..d97420d34b 100644 --- a/crates/ui-contract/src/runtime/keys/intents.rs +++ b/crates/ui-contract/src/runtime/keys/intents.rs @@ -264,7 +264,11 @@ fn editor_input_of(intent: &Intent, shift: bool) -> Option { /// The intents routed to `id` this pass, with physical horizontal moves read in the component's direction. #[doc(hidden)] pub fn intents_of(ctx: &Context, id: Option, rtl: bool) -> Intents { - let routed = current(ctx, |stage| stage.routed.get(&id).cloned()).unwrap_or_default(); + let routed = current(ctx, |stage| { + stage.intents_read = true; + stage.routed.get(&id).cloned() + }) + .unwrap_or_default(); let flip = |mv| match (rtl, mv) { (true, NavMove::Back) => NavMove::Forward, (true, NavMove::Forward) => NavMove::Back, diff --git a/crates/ui-contract/src/runtime/keys/route.rs b/crates/ui-contract/src/runtime/keys/route.rs index 8e0b2918ec..9a001b6986 100644 --- a/crates/ui-contract/src/runtime/keys/route.rs +++ b/crates/ui-contract/src/runtime/keys/route.rs @@ -24,6 +24,7 @@ pub(crate) fn begin(ctx: &Context, press_captured: bool) -> EscapeRouting { let target = focus::focused_rec(ctx); let (batch, nodes, captures, held_claims, alt_claims, fired_claims, hover_deletes) = current(ctx, |stage| { stage.routed.clear(); + stage.intents_read = false; stage.contexts.clear(); stage.claimed.clear(); stage.activated.clear(); @@ -548,19 +549,27 @@ pub(crate) fn take_shortcuts(ctx: &Context) -> Shortcuts { shortcuts } -/// Asks the focused component of the running viewport to take `command` as `Intent::Edit` in the next pass. +/// Asks the focused component of the running viewport to take `command` as `Intent::Edit`: in this pass when no +/// component has read its intents in it yet (a system menu pick the host dispatches before the UI), else in the next +/// pass (a pick in the window's own menus or bars, which run in the UI). /// `false` when it does not list the command, or is the app's own widget (`Stop::host`), whose edits are the app's. A paste asks the platform for the clipboard text, which arrives as /// the paste event that becomes the intent. Focus is read as it is now: a menu pick returns focus in its pass /// before its command fires, and the command goes where focus returned. pub(crate) fn queue_edit(ctx: &Context, command: EditCommand) -> bool { let viewport = crate::runtime::egui::pass::current_viewport(ctx); - if !focus::focused_rec(ctx).is_some_and(|rec| !rec.stop.host && rec.stop.keys.edits.contains(command)) { + let Some(id) = focus::focused_rec(ctx).filter(|rec| !rec.stop.host && rec.stop.keys.edits.contains(command)).map(|rec| rec.stop.id) else { return false; - } + }; if command == EditCommand::Paste { crate::runtime::egui::clipboard::request_paste(ctx); - } else { - with(ctx, viewport, |stage| stage.queued_edits.push(command)); + } else if with(ctx, viewport, |stage| { + if !stage.intents_read { + push(&mut stage.routed, Some(id), Intent::Edit(command), false); + } else { + stage.queued_edits.push(command); + } + stage.intents_read + }) { crate::runtime::egui::repaint::request_of(ctx, viewport); } true diff --git a/crates/ui-widgets/tests/it/bars/edit_focus.rs b/crates/ui-widgets/tests/it/bars/edit_focus.rs index 01c3d0dbe0..c374f40786 100644 --- a/crates/ui-widgets/tests/it/bars/edit_focus.rs +++ b/crates/ui-widgets/tests/it/bars/edit_focus.rs @@ -1,9 +1,11 @@ //! A toolbar's Undo and Redo act in the focused text field while it has a step for them, and otherwise go on to the -//! app's command, whose state then enables the button; the press keeps the focus in the field either way. +//! app's command, whose state then enables the button; the press keeps the focus in the field either way. A menu's +//! edit commands act in the focused field too. use craft_ui::bars::{BarItem, BarItems}; use craft_ui::contract::{Bind, Props as _, Show as _}; -use craft_ui::runtime::commands::{CommandRef, CommandSet as _, CommandState, EditCommands}; +use craft_ui::display::Text; +use craft_ui::runtime::commands::{self, CommandRef, CommandSet as _, CommandState, EditCommands, FireSource}; use craft_ui::runtime::frame; use craft_ui::testing::{Fixture, trial}; use craft_ui::text::TextField; @@ -18,19 +20,33 @@ fn label_of(command: EditCommands) -> String { defs.into_iter().find(|def| def.command.id == id).map(|def| def.label).expect("the edit command has a definition") } -/// A text field holding "hello" over a toolbar with Undo and Redo; the field comes first, so Tab focuses it. +/// A title, then a text field holding "hello" over a toolbar with Undo and Redo; the field is the first stop, so Tab +/// focuses it. struct Rig { fixture: Fixture, text: Rc>, field: Rc>>, + /// A menu pick the next frame fires, and whether in the UI (after the title, before the field, as the window's own + /// menu bar runs) or before it (as a host dispatches a system menu before the app's UI). + menu: Rc>>, } /// The rig with the field focused and the app's Undo and Redo in `app_can_undo`'s state. fn rig(app_can_undo: bool) -> Rig { let text = Rc::new(RefCell::new("hello".to_owned())); let field = Rc::new(Cell::new(None)); - let (held, id) = (text.clone(), field.clone()); + let menu = Rc::new(Cell::new(None)); + let (held, id, pick) = (text.clone(), field.clone(), menu.clone()); let mut fixture = Fixture::new(move |ui| { + let (pick, ctx) = (pick.take(), ui.ctx().clone()); + let fire = |in_ui| { + if let Some((command, _)) = pick.filter(|&(_, at)| at == in_ui) { + commands::fire(&ctx, command, FireSource::Menu); + } + }; + fire(false); + Text::new("Title").show(ui); + fire(true); id.set(Some(TextField::new("Name", Bind::bound(&mut *held.borrow_mut())).id_salt("name").show(ui).response.id)); BarItems::new(vec![BarItem::new(EditCommands::Undo), BarItem::new(EditCommands::Redo)]).show(ui); }); @@ -40,7 +56,7 @@ fn rig(app_can_undo: bool) -> Rig { fixture.room(Vec2::new(600.0, 200.0)).settle(); fixture.key(Key::Tab, Modifiers::NONE); fixture.settle(); - let rig = Rig { fixture, text, field }; + let rig = Rig { fixture, text, field, menu }; assert!(rig.focus_in_the_field(), "Tab focuses the field"); rig } @@ -109,3 +125,26 @@ fn undo_with_no_step_in_the_field_runs_the_app_command() { rig.fixture.settle(); assert!(rig.disabled(EditCommands::Undo), "with neither the field nor the app able to undo, the toolbar's Undo is disabled"); } + +/// A system menu's Select All, then its Copy, each picked before the frame's UI, select the field's text and copy it +/// in their own frames; a menu pick in the UI, though before the field, copies in the next frame. Guards against a +/// system menu edit that waited a pass, against a field whose recorded edits kept Copy disabled after a Select All of +/// the same pass (which dropped the Copy), and against an in-window menu's edit taken a frame earlier than before or +/// lost. +#[trial] +fn a_menus_select_all_then_copy_copy_the_fields_text() { + let mut rig = rig(false); + rig.fixture.key(Key::End, Modifiers::NONE).settle(); + rig.menu.set(Some((EditCommands::SelectAll, false))); + rig.fixture.frame(Vec::new()); + rig.menu.set(Some((EditCommands::Copy, false))); + rig.fixture.frame(Vec::new()); + assert_eq!(rig.fixture.copied(), ["hello"], "the system menu's Copy copies the selected text in its own frame"); + assert!(rig.focus_in_the_field(), "the field keeps the focus"); + + rig.menu.set(Some((EditCommands::Copy, true))); + rig.fixture.frame(Vec::new()); + assert!(rig.fixture.copied().is_empty(), "the in-window menu's Copy waits for the next frame"); + rig.fixture.frame(Vec::new()); + assert_eq!(rig.fixture.copied(), ["hello"], "the in-window menu's Copy copies in the next frame"); +}