From f1bf62a70558b7f64e21ac23468dcb64f91f74ad Mon Sep 17 00:00:00 2001 From: aiongg Date: Wed, 25 Nov 2026 13:00:57 +0000 Subject: [PATCH 1/5] host_canvas: a declared canvas no widget draws is a finding egui drops the focus of an id no interactive widget of the pass has, so Tab lost the focus at such a canvas and started over at the first stop. The end hook looks each declared canvas up among the pass's widgets and reports `canvas-without-widget` when it is not there; debug builds log it once. --- crates/ui-contract/src/runtime/egui/focus.rs | 6 ++++ crates/ui-contract/src/runtime/focus.rs | 36 +++++++++++++++++-- .../src/testing/host_key_trials.rs | 31 ++++++++++++++++ docs/craft-framework.md | 2 +- 4 files changed, 72 insertions(+), 3 deletions(-) diff --git a/crates/ui-contract/src/runtime/egui/focus.rs b/crates/ui-contract/src/runtime/egui/focus.rs index 0941e5d43..6e845caa1 100644 --- a/crates/ui-contract/src/runtime/egui/focus.rs +++ b/crates/ui-contract/src/runtime/egui/focus.rs @@ -33,6 +33,12 @@ pub(crate) fn candidates_since(ctx: &Context, seen: usize) -> Vec::to_vec).unwrap_or_default()) } +/// Whether egui keeps the focus of `id` at the end of the running pass: an interactive widget drawn so far has the id +/// (`PassState::used_ids`, which egui's end pass checks the focused id against). +pub(crate) fn keeps_focus_of(ctx: &Context, id: Id) -> bool { + ctx.viewport(|viewport| viewport.this_pass.used_ids.contains_key(&id)) +} + /// Whether the widget egui holds key focus on keeps Tab by its event filter (`Memory::focus_lock_filter`). pub(crate) fn focused_keeps_tab(ctx: &Context) -> bool { ctx.memory(|memory| memory.focus_lock_filter()).is_some_and(|filter| filter.tab) diff --git a/crates/ui-contract/src/runtime/focus.rs b/crates/ui-contract/src/runtime/focus.rs index 7cdd0fe54..b3275feed 100644 --- a/crates/ui-contract/src/runtime/focus.rs +++ b/crates/ui-contract/src/runtime/focus.rs @@ -17,8 +17,11 @@ pub(crate) use registration::{Group, Stop}; use crate::runtime::egui::focus as egui_focus; use crate::runtime::egui::memory::FastMap; use crate::runtime::frame::PerViewport; +use crate::runtime::inspect; +use crate::style::log_once; use craft_behavior::{DocKey, OwnerClass, PartRef}; use egui::{Context, Id, IdSet, ViewportId}; +use smallvec::SmallVec; use std::fmt; use std::sync::Arc; use std::sync::atomic::{AtomicU64, Ordering}; @@ -194,6 +197,9 @@ pub(crate) struct State { /// How many of egui's focus candidates of the running pass (`Memory::focus_candidates`) `take_app_widgets` has /// read. pub(super) candidates_seen: usize, + /// The canvases the running pass declared with `host_canvas`, which the end hook takes and looks up among egui's + /// widgets. + pub(super) host_canvases: SmallVec<[Id; 1]>, /// A text widget that gave its Escape on to the enclosing scopes and lets focus go at the end of the pass. surrender_after_scopes: Option, /// A text widget in a scope that gives focus back to its opener, held one more pass: the scope the Escape closes is @@ -318,9 +324,17 @@ fn take_app_widgets(ctx: &Context, except: Option) { /// them; Page Up and Down, Home and End arrive as its `Intent::Move`, as while it has the focus. A bare Tab with nothing /// focused is never the canvas's, even when it keeps Tab: it moves focus into the window or toggles the panels, so the /// canvas cannot trap keyboard navigation. With the canvas focused, the same keys stay in egui, a Tab it keeps and -/// Escape too, as for any focused widget of the app's own; Escape with nothing focused is the window's cancel. Call it -/// each pass the canvas shows. +/// Escape too, as for any focused widget of the app's own; Escape with nothing focused is the window's cancel. +/// +/// Call it in each pass the canvas shows, before or after the canvas is drawn, with the id of the interactive egui widget +/// the app draws for it in every such pass (`ui.interact(rect, id, Sense::click())`). egui drops the focus of an id that +/// no such widget of the pass has, so Tab would lose the focus at the canvas and start over at the window's first stop. +/// A pass that declares a canvas and draws no widget with its id reports the finding `canvas-without-widget`, and debug +/// builds log it once. A pass that hides the canvas makes no call. pub fn host_canvas(ctx: &Context, id: Id, keys: KeyUse) { + if !crate::runtime::measure::active(ctx) { + with(ctx, |state| state.host_canvases.push(id)); + } register_stop(ctx, Stop::new(id, keys.with_chrome_key(true)).host()); } @@ -1102,11 +1116,29 @@ pub(crate) fn surrender_after_scopes(ctx: &Context, widget: Id) { with(ctx, |state| state.surrender_after_scopes = Some(widget)); } +/// Reports each canvas the running pass declared (`host_canvas`) whose id no interactive egui widget of the pass has. +/// Read at the pass's end, since a canvas may be declared before it is drawn. A canvas hidden for one pass and still +/// declared counts: egui drops its focus at the end of that pass. +fn report_undrawn_canvases(ctx: &Context) { + for id in with(ctx, |state| std::mem::take(&mut state.host_canvases)) { + if egui_focus::keeps_focus_of(ctx, id) { + continue; + } + if cfg!(debug_assertions) { + log_once(format!("canvas:{id:?}"), || { + log::warn!("`host_canvas` declared the canvas {id:?}, but no interactive egui widget with that id was drawn in the pass"); + }); + } + inspect::finding(ctx, inspect::Finding { rule: "canvas-without-widget", component: "host_canvas", subject: format!("{id:?}") }); + } +} + /// The end hook: applies the press's focus move, returns focus to the opener of a scope that went away, /// moves it off a stop that was not registered, and records what the next input hook reads. pub(crate) fn end(ctx: &Context) { let viewport = viewport(ctx); take_app_widgets(ctx, None); + report_undrawn_canvases(ctx); // A field held a pass for the scope it sits in lets go now, unless that scope is going away with focus in the field: // nav::end below then gives the focus back to the scope's opener from where the field holds it. if let Some(widget) = with(ctx, |state| state.surrender_deferred.take()) diff --git a/crates/ui-contract/src/testing/host_key_trials.rs b/crates/ui-contract/src/testing/host_key_trials.rs index 393718b49..1ad0c3026 100644 --- a/crates/ui-contract/src/testing/host_key_trials.rs +++ b/crates/ui-contract/src/testing/host_key_trials.rs @@ -12,6 +12,7 @@ use crate::runtime::frame::{ChromeToggle, take_output}; use crate::runtime::ime; use crate::runtime::keys::with_window_intents; use crate::style::{ComponentStyle, StyleCx}; +use crate::testing::contract::findings; use crate::testing::focus::{Stop, egui_focused, key_release, named_id, pop_scope, push_scope, register_stop, widget}; use crate::testing::input::{key_press, key_reached, slop}; use crate::testing::pointer::{self, moved, press, release}; @@ -998,6 +999,36 @@ fn a_host_canvas_marks_the_window_and_tab_toggles_its_panels() { ); } +/// Guards the finding that tells an app its canvas stop takes Tab and loses the focus: `host_canvas` named an id that no +/// egui widget of the pass has. A canvas declared before it is drawn, and one neither declared nor drawn, give none. +#[trial] +fn a_host_canvas_no_widget_draws_is_a_finding() { + let canvas = named_id("host canvas"); + let (declared, drawn) = (Rc::new(Cell::new(true)), Rc::new(Cell::new(true))); + let (declares, draws) = (Rc::clone(&declared), Rc::clone(&drawn)); + let mut show = move |ui: &mut Ui| { + if declares.get() { + host_canvas(ui.ctx(), canvas, KeyUse::CANVAS); + } + if draws.get() { + widget(ui, canvas); + } + }; + let mut frames = Frames::new(); + frames.idle(3, &mut show); + declared.set(false); + drawn.set(false); + frames.idle(1, &mut show); + assert!(findings(&frames.ctx).is_empty(), "a drawn canvas and a hidden one: {:?}", findings(&frames.ctx)); + declared.set(true); + frames.idle(1, &mut show); + let found = findings(&frames.ctx); + assert!( + matches!(found.as_slice(), [only] if only.rule == "canvas-without-widget" && only.subject == format!("{canvas:?}")), + "the declared canvas no widget draws: {found:?}" + ); +} + /// What `event` did with nothing focused in a window whose host declares its canvas with `keys`: whether the event /// reached egui's input, and the ids of the commands it fired. fn clipboard_with_canvas(keys: KeyUse, event: Event) -> (bool, Vec) { diff --git a/docs/craft-framework.md b/docs/craft-framework.md index 2c2af4139..9d7a00314 100644 --- a/docs/craft-framework.md +++ b/docs/craft-framework.md @@ -144,7 +144,7 @@ An app with its own eframe `App` calls the hooks in `craft::ui::shell::embed`. ` | Each frame | `raw_input_hook` | `embed::before_input(ctx, \|output\| { ...; input })`: the closure receives the `FrameOutput` of the frame before (fired commands, announcements, chrome toggles) and returns the `FrameInput` for this frame (`RootEnv`, command states, the `Host`). eframe runs the hook for the main window only: an app that drops the window system's input there (an agent-driven session) sets `FrameInput::window_input(WindowInput::Dropped)` too, and the runtime drops it in every other OS window it hosts, before injected input joins. macOS Control+Click is the runtime's in every window; the app does not map it. | | Each frame | `logic`, after the app's own logic | `embed::logic(ctx, \|\| decision)`: the root window's close path. The closure runs only when the root window was asked to close, and returns `CloseDecision::Close` or `Hold`. | | Each pass | `ui`, before the app's UI | `embed::before_ui(ctx, frame)`: hands the runtime the root's native window (eframe's `Frame`, or any `raw_window_handle::HasWindowHandle`) on Windows, where the runtime answers the window's hit test (resize edges, the title bar's move area, snap layouts on the maximize button), and fits the root window to its monitor once. Native only; it needs no eframe feature of the facade. | -| Each pass | `ui`, where the app draws its own document canvas | Optional: `ui::runtime::focus::host_canvas(ctx, id, KeyUse::CANVAS)` declares it as the window's canvas (Tab row below). Every other focusable egui widget the app draws is a Tab stop with no call: the window's one Tab order holds it among the framework's stops, in the order the pass draws them. | +| Each pass | `ui`, where the app draws its own document canvas | Optional: `ui::runtime::focus::host_canvas(ctx, id, KeyUse::CANVAS)` declares it as the window's canvas (Tab row below). `id` is the id of the interactive egui widget the app draws for the canvas in that pass: egui drops the focus of an id no widget has, so Tab would lose the focus there, and the pass reports the finding `canvas-without-widget`. Every other focusable egui widget the app draws is a Tab stop with no call: the window's one Tab order holds it among the framework's stops, in the order the pass draws them. | | Each pass | `ui`, last | Optional: `ui::runtime::keys::with_window_intents(ctx, rtl, \|intents\| ...)` reads the keys no component took (below). | `install` takes over these parts of the context for the whole window, not only for framework components: From d6f213e0b10fb5275170076678f9e6ca9b482208 Mon Sep 17 00:00:00 2001 From: aiongg Date: Wed, 25 Nov 2026 13:05:28 +0000 Subject: [PATCH 2/5] Focus the runtime gives an app's own widget follows egui's rule Focus that Tab, F6 or a framework request gave an app's own egui widget kept the runtime's surrender rule (Never) while the runtime's press rule left that widget to egui, so a press elsewhere released it nowhere. The end hook of the pass that drew the widget leaves the focus to egui's rule, the app's `surrender_focus_on`; until then the press or click of the pass that gave the focus does not take it back. The stop of an app's own widget sets no Escape filter, so Escape releases it as egui does; the declared canvas keeps its filter. --- crates/ui-contract/src/runtime/egui/focus.rs | 15 +- crates/ui-contract/src/runtime/focus.rs | 15 +- crates/ui-contract/src/runtime/focus/nav.rs | 6 +- .../src/testing/host_key_trials.rs | 130 ++++++++++++++++++ docs/craft-framework.md | 2 +- 5 files changed, 161 insertions(+), 7 deletions(-) diff --git a/crates/ui-contract/src/runtime/egui/focus.rs b/crates/ui-contract/src/runtime/egui/focus.rs index 0941e5d43..3ade595c5 100644 --- a/crates/ui-contract/src/runtime/egui/focus.rs +++ b/crates/ui-contract/src/runtime/egui/focus.rs @@ -44,8 +44,8 @@ pub(crate) fn label_selection(ctx: &Context) -> bool { } /// Gives `id` key focus with `filter`, applied from this pass: a filter set afterwards acts a pass late. egui never -/// takes this focus away on a press or click elsewhere: the runtime moves it on press (8.3). egui's own rule, the -/// app's `surrender_focus_on`, applies to the focus of the app's own widgets. +/// takes this focus away on a press or click elsewhere: the runtime moves it on press (8.3). The end hook leaves +/// the focus of an app's own widget to egui's rule (`leave_to_egui`). pub(crate) fn focus_with_filter(ctx: &Context, id: Id, filter: KeyFilter) { let filter = EventFilter { tab: filter.tab, horizontal_arrows: filter.horizontal_arrows, vertical_arrows: filter.vertical_arrows, escape: filter.escape }; @@ -55,6 +55,17 @@ pub(crate) fn focus_with_filter(ctx: &Context, id: Id, filter: KeyFilter) { }); } +/// Leaves the focus of the app's own widget `id`, if it holds it, to egui's rule, the app's `surrender_focus_on`, with +/// the key filter it has. +pub(crate) fn leave_to_egui(ctx: &Context, id: Id) { + ctx.memory_mut(|memory| { + if memory.has_focus(id) { + let filter = memory.focus_lock_filter().unwrap_or_default(); + memory.request_focus_with_filter(id, filter); + } + }); +} + /// Gives a component's widget `id` back the focus egui dropped in this pass (egui drops the focus of a disabled /// widget), as the runtime's focus: egui never surrenders it on a press or click elsewhere. pub(crate) fn keep_focus(memory: &mut egui::Memory, id: Id) { diff --git a/crates/ui-contract/src/runtime/focus.rs b/crates/ui-contract/src/runtime/focus.rs index 7cdd0fe54..fb3e95e98 100644 --- a/crates/ui-contract/src/runtime/focus.rs +++ b/crates/ui-contract/src/runtime/focus.rs @@ -194,6 +194,10 @@ pub(crate) struct State { /// How many of egui's focus candidates of the running pass (`Memory::focus_candidates`) `take_app_widgets` has /// read. pub(super) candidates_seen: usize, + /// The widget the runtime gave egui's focus, under its own press rule, until the end hook of a pass that drew it: the + /// focus of an app's own widget (`State::app_widget`) is left to egui's rule there. A press or click of the pass that + /// gave the focus so never takes it back. + given: Option, /// A text widget that gave its Escape on to the enclosing scopes and lets focus go at the end of the pass. surrender_after_scopes: Option, /// A text widget in a scope that gives focus back to its opener, held one more pass: the scope the Escape closes is @@ -228,7 +232,10 @@ pub(crate) fn apply(ctx: &Context, acts: Vec) { } for act in acts { match act { - Act::Focus(id, filter) => egui_focus::focus_with_filter(ctx, id, filter), + Act::Focus(id, filter) => { + egui_focus::focus_with_filter(ctx, id, filter); + with(ctx, |state| state.given = Some(id)); + } Act::Surrender(id) => egui_focus::surrender(ctx, id), } } @@ -1144,6 +1151,12 @@ pub(crate) fn end(ctx: &Context) { let frame = crate::runtime::egui::pass::frame_nr(ctx, viewport); let acts = with(ctx, |state| nav::end(state, focused, on_app_widget, frame)); apply(ctx, acts); + if let Some(id) = with(ctx, |state| state.given).filter(|id| ctx.read_response(*id).is_some()) { + with(ctx, |state| state.given = None); + if app_widget(id) { + egui_focus::leave_to_egui(ctx, id); + } + } // Escape over a captured framework press or drag cancels it (`frame::begin_pass`), whatever egui has focused. let captured = crate::runtime::pointer::press_captured(ctx) || crate::runtime::drag::running(ctx); let host_focus = !captured && with(ctx, |state| state.focus_now).is_some_and(app_widget); diff --git a/crates/ui-contract/src/runtime/focus/nav.rs b/crates/ui-contract/src/runtime/focus/nav.rs index 0fa84e5e2..bba7b6ea7 100644 --- a/crates/ui-contract/src/runtime/focus/nav.rs +++ b/crates/ui-contract/src/runtime/focus/nav.rs @@ -266,9 +266,9 @@ impl State { let stop = &rec.stop; let roving = stop.group.is_some(); let keys = stop.keys; - // An app's own widget (`Stop::host`) reads its Escape from egui, as a stop that claims it does: egui keeps its - // focus on it. - let escape = stop.host || keys.claims.iter().any(|chord| chord.key == craft_keymap::Key::Escape); + // The app's canvas (`host_canvas`) reads its Escape from egui, as a stop that claims it does: egui keeps its focus + // on it. Every other widget of the app's own keeps Escape by its own egui filter. + let escape = (stop.host && !stop.automatic()) || keys.claims.iter().any(|chord| chord.key == craft_keymap::Key::Escape); let filter = egui_focus::filter( keys.keep == super::KeepKeys::Tab, roving || matches!(keys.keep, super::KeepKeys::InlineArrows | super::KeepKeys::BlockArrows), diff --git a/crates/ui-contract/src/testing/host_key_trials.rs b/crates/ui-contract/src/testing/host_key_trials.rs index 393718b49..eedeb63cd 100644 --- a/crates/ui-contract/src/testing/host_key_trials.rs +++ b/crates/ui-contract/src/testing/host_key_trials.rs @@ -750,6 +750,136 @@ fn an_app_field_that_keeps_tab_types_it_and_a_single_line_field_tabs_on() { assert_eq!(texts.borrow().1, "", "and types nothing"); } +/// How the focus of the app's own widget `id` in `mixed_window`, given by Tab (`tab`) or by the app's own egui request, +/// ends. +#[derive(Debug, PartialEq, Eq)] +struct FocusEnds { + /// egui's focus after the press and after the release of a click elsewhere. + click: (Option, Option), + /// Whether the widget lost focus by egui's word, in each pass from the press on. + lost: Vec, + /// egui's focus after Escape, the focus given again. + escape: Option, + /// egui's focus after a click elsewhere while the app's option is never to surrender it, the focus given again. + kept: Option, +} + +fn focus_ends(id: Id, tab: bool) -> FocusEnds { + let lost = Rc::new(RefCell::new(Vec::new())); + let losses = Rc::clone(&lost); + let mut base = mixed_window(); + let mut show = move |ui: &mut Ui| { + base(ui); + losses.borrow_mut().push(ui.ctx().read_response(id).is_some_and(|response| response.lost_focus())); + }; + let give = |frames: &mut Frames, show: &mut dyn FnMut(&mut Ui)| { + for _ in 0..MIXED.len() { + if tab && egui_focused(&frames.ctx) != Some(id) { + tab_with(frames, &mut &mut *show, Modifiers::NONE); + } + } + if !tab { + fixture::host_focus(&frames.ctx, id); + } + frames.idle(2, &mut *show); + assert_eq!(egui_focused(&frames.ctx), Some(id), "the widget has the focus"); + }; + let mut frames = Frames::new(); + frames.idle(2, &mut show); + let empty = Pos2::new(300.0, 450.0); + give(&mut frames, &mut show); + lost.borrow_mut().clear(); + let click = click_focus(&mut frames, &mut show, empty); + frames.idle(2, &mut show); + let lost = lost.take(); + give(&mut frames, &mut show); + press_key(&mut frames, &mut show, Key::Escape); + let escape = egui_focused(&frames.ctx); + fixture::set_app_surrender(&frames.ctx, true); + give(&mut frames, &mut show); + let (_, kept) = click_focus(&mut frames, &mut show, empty); + FocusEnds { click, lost, escape, kept } +} + +/// Focus that Tab gave an app's own button or text field ends as the focus the app's own request gave it: a click +/// elsewhere and Escape release it once, by egui's rule and the app's surrender option. +#[trial] +fn tab_focus_on_an_app_widget_ends_as_the_focus_the_app_gave_it() { + for id in ["app first", "app field"].map(named_id) { + let ends = focus_ends(id, true); + assert_eq!(ends.click, (Some(id), None), "a click elsewhere releases it, at the release by egui's option"); + assert!(ends.lost.contains(&true), "and the widget sees its focus lost"); + assert_eq!(ends.escape, None, "Escape releases it"); + assert_eq!(ends.kept, Some(id), "the app's option keeps it over a click elsewhere"); + assert_eq!(ends, focus_ends(id, false), "as the focus the app gave it does, seen lost in the same passes"); + } +} + +/// A component reached with Tab keeps its focus over Escape and drops it at a press no component takes. +#[trial] +fn tab_focus_on_a_component_ends_by_the_framework_s_press_rule() { + let mut show = mixed_window(); + let mut frames = Frames::new(); + frames.idle(2, &mut show); + tab_with(&mut frames, &mut show, Modifiers::NONE); + let one = Some(named_id("framework one")); + assert_eq!(tab_with(&mut frames, &mut show, Modifiers::NONE), one); + press_key(&mut frames, &mut show, Key::Escape); + assert_eq!(egui_focused(&frames.ctx), one, "Escape leaves the component's focus"); + let empty = Pos2::new(300.0, 450.0); + assert_eq!(click_focus(&mut frames, &mut show, empty).0, None, "a press no component takes drops it at the press"); +} + +/// A press on a component that takes focus moves it there from the app's field that Tab focused, and the field sees its +/// focus lost once. +#[trial] +fn a_press_on_a_component_takes_the_focus_tab_gave_an_app_field() { + let field = named_id("app field"); + let rect = Rect::from_min_size(Pos2::new(300.0, 400.0), egui::vec2(160.0, 40.0)); + let lost = Rc::new(Cell::new(0)); + let losses = Rc::clone(&lost); + let mut base = mixed_window(); + let mut show = move |ui: &mut Ui| { + base(ui); + sensing::show(ui, &[ProbeRoot::new("probe", rect, Sense::CLICK | Sense::TAKE_FOCUS)]); + register_stop(ui.ctx(), Stop::new(ProbeRoot::id("probe"), KeyUse::of(Input::Pointer))); + losses.set(losses.get() + usize::from(ui.ctx().read_response(field).is_some_and(|response| response.lost_focus()))); + }; + let mut frames = Frames::new(); + frames.idle(2, &mut show); + for _ in 0..3 { + tab_with(&mut frames, &mut show, Modifiers::NONE); + } + assert_eq!(egui_focused(&frames.ctx), Some(field)); + lost.set(0); + let probe = Some(ProbeRoot::id("probe")); + assert_eq!(click_focus(&mut frames, &mut show, rect.center()), (probe, probe), "the press moves the focus to the component"); + frames.idle(2, &mut show); + assert_eq!(lost.get(), 1, "the field sees its focus lost once"); +} + +/// A focus request that a click makes for an app's own widget drawn later in the same pass stands: the click, which is +/// elsewhere for that widget, does not take the focus back. The next click elsewhere does. +#[trial] +fn a_request_at_a_click_gives_an_app_field_drawn_later_the_focus() { + let field = named_id("app field"); + let asking = Rc::new(Cell::new(false)); + let ask = Rc::clone(&asking); + let mut base = mixed_window(); + let mut show = move |ui: &mut Ui| { + if ui.input(|input| input.pointer.any_click()) && ask.take() { + request(ui.ctx(), FocusTarget::Id(field)); + } + base(ui); + }; + let mut frames = Frames::new(); + frames.idle(2, &mut show); + asking.set(true); + let empty = Pos2::new(300.0, 450.0); + assert_eq!(click_focus(&mut frames, &mut show, empty).1, Some(field), "the requested focus stands"); + assert_eq!(click_focus(&mut frames, &mut show, empty).1, None, "the next click elsewhere takes it by egui's rule"); +} + /// Where Tab reaches only text fields (the Mac's default), it reaches the app's own text field and skips the app's /// own buttons, as it skips the framework's. #[trial] diff --git a/docs/craft-framework.md b/docs/craft-framework.md index 2c2af4139..3aee59ee6 100644 --- a/docs/craft-framework.md +++ b/docs/craft-framework.md @@ -160,7 +160,7 @@ An app with its own eframe `App` calls the hooks in `craft::ui::shell::embed`. ` | IME | Taken while a framework editor owns the IME: its events and `PlatformOutput.ime` are the runtime's. Otherwise they stay egui's, for the app's own `TextEdit` or IME code. | | An app's own focused widget | While egui focus is on a widget no framework component made, or an egui popup is open, and no framework press or drag is captured, Escape, the plain Enter and egui's clipboard events stay in egui's input for it, and the runtime routes nothing for them; Tab and Shift+Tab are the window's focus moves (Tab row) unless the widget keeps Tab or the popup is open. While egui focus is on such a widget, the arrows move egui focus among the app's widgets as egui does; while a framework stop has the focus, egui's arrow moves are off. | | Releases | The release of every key the runtime took is taken too. | -| Focus surrender | The runtime moves its own focus on press (8.3): a press a framework component takes moves focus to it; a press no component takes drops the framework's focus. egui's click-away never takes the framework's focus. egui's surrender option (`InputOptions::surrender_focus_on`) stays the app's and governs the focus of the app's own widgets, as in egui alone: a press no component takes leaves that focus to egui's rule. | +| Focus surrender | The runtime moves its own focus on press (8.3): a press a framework component takes moves focus to it; a press no component takes drops the framework's focus. egui's click-away never takes the framework's focus. egui's surrender option (`InputOptions::surrender_focus_on`) stays the app's and governs the focus of the app's own widgets, however they got it (the app's code, a click, Tab, F6, a framework request), as in egui alone: a press no component takes leaves that focus to egui's rule, except that the press or click of the pass that gives the focus never takes it back. Escape releases it too, unless the widget's egui key filter keeps Escape. | | Clicks | egui's click options (`InputOptions::max_click_dist`, `max_click_duration`) stay the app's, for its own widgets. A framework component clicks and drags by the framework's press lifecycle: a release within the slop (`HitSizes::slop`), whatever its duration. Read a component's click with `contract::clicked(&response)` or its output's `clicked()`; egui's `Response::clicked()` on a component's response also needs a click by egui's options. | | Zoom keys | egui's keyboard zoom is off and nothing takes its place: the interface scale is `RootEnv::scale`, and an app whose ⌘= and ⌘- changed it binds them itself. | | Quit | egui's quit shortcuts are cleared. ⌘Q (Ctrl+Q on Windows and Linux) is the default of the command `QuitCommand::Quit` (id `window.quit`), which the runtime runs from any source: it asks the root window to close through the close path below, so the app's close decision asks about unsaved work. It fires with a modal open; the close path then refuses under an app-modal layer. Its default is bound and yielded as F6 is; an app whose own shortcut table reads its quit key from egui unbinds it there. | From 4bdb8b850a36599aacf778a8331d07ba67652fa1 Mon Sep 17 00:00:00 2001 From: aiongg Date: Wed, 25 Nov 2026 13:10:39 +0000 Subject: [PATCH 3/5] host_canvas: a canvas widget that takes no focus is the same finding A widget drawn with the bare Sense::DRAG or Sense::CLICK is not focusable, and egui takes the focus from it when it is drawn, so Tab is lost there too. The end hook reads the sense of the canvas's widget and names it in the finding. --- .../ui-contract/src/runtime/egui/fixture.rs | 6 ++ crates/ui-contract/src/runtime/egui/focus.rs | 8 +-- crates/ui-contract/src/runtime/focus.rs | 31 ++++----- .../src/testing/host_key_trials.rs | 65 +++++++++++++------ docs/craft-framework.md | 2 +- 5 files changed, 71 insertions(+), 41 deletions(-) diff --git a/crates/ui-contract/src/runtime/egui/fixture.rs b/crates/ui-contract/src/runtime/egui/fixture.rs index c7a8eca3e..e2434526e 100644 --- a/crates/ui-contract/src/runtime/egui/fixture.rs +++ b/crates/ui-contract/src/runtime/egui/fixture.rs @@ -618,6 +618,12 @@ pub(crate) fn host_drag_area(ui: &Ui, id: egui::Id, rect: Rect) -> (bool, bool) (response.dragged(), response.drag_stopped()) } +/// A host's own egui widget `id` at `rect` that senses drags and takes no focus. +#[cfg(feature = "suite")] +pub(crate) fn host_unfocusable_area(ui: &Ui, id: egui::Id, rect: Rect) { + ui.interact(rect, id, egui::Sense::DRAG); +} + /// A host's own selectable egui label of `text`; returns its rect. #[cfg(feature = "suite")] pub(crate) fn host_label(ui: &mut Ui, text: &str) -> Rect { diff --git a/crates/ui-contract/src/runtime/egui/focus.rs b/crates/ui-contract/src/runtime/egui/focus.rs index 6e845caa1..01c16aca8 100644 --- a/crates/ui-contract/src/runtime/egui/focus.rs +++ b/crates/ui-contract/src/runtime/egui/focus.rs @@ -33,10 +33,10 @@ pub(crate) fn candidates_since(ctx: &Context, seen: usize) -> Vec::to_vec).unwrap_or_default()) } -/// Whether egui keeps the focus of `id` at the end of the running pass: an interactive widget drawn so far has the id -/// (`PassState::used_ids`, which egui's end pass checks the focused id against). -pub(crate) fn keeps_focus_of(ctx: &Context, id: Id) -> bool { - ctx.viewport(|viewport| viewport.this_pass.used_ids.contains_key(&id)) +/// What the widget `id` drawn so far in the running pass senses; `None` when no widget has the id. egui takes the focus +/// from a widget that is not focusable when it is drawn, and from an id no interactive widget has at the pass's end. +pub(crate) fn drawn_sense(ctx: &Context, id: Id) -> Option { + ctx.viewport(|viewport| viewport.this_pass.widgets.get(id).map(|widget| widget.sense)) } /// Whether the widget egui holds key focus on keeps Tab by its event filter (`Memory::focus_lock_filter`). diff --git a/crates/ui-contract/src/runtime/focus.rs b/crates/ui-contract/src/runtime/focus.rs index b3275feed..10ed5a645 100644 --- a/crates/ui-contract/src/runtime/focus.rs +++ b/crates/ui-contract/src/runtime/focus.rs @@ -326,11 +326,12 @@ fn take_app_widgets(ctx: &Context, except: Option) { /// canvas cannot trap keyboard navigation. With the canvas focused, the same keys stay in egui, a Tab it keeps and /// Escape too, as for any focused widget of the app's own; Escape with nothing focused is the window's cancel. /// -/// Call it in each pass the canvas shows, before or after the canvas is drawn, with the id of the interactive egui widget -/// the app draws for it in every such pass (`ui.interact(rect, id, Sense::click())`). egui drops the focus of an id that -/// no such widget of the pass has, so Tab would lose the focus at the canvas and start over at the window's first stop. -/// A pass that declares a canvas and draws no widget with its id reports the finding `canvas-without-widget`, and debug -/// builds log it once. A pass that hides the canvas makes no call. +/// Call it in each pass the canvas shows, before or after the canvas is drawn, with the id of the focusable egui widget +/// the app draws for it in every such pass (`Sense::click()`, `Sense::drag()`; the bare flags `Sense::CLICK` and +/// `Sense::DRAG` are not focusable). egui drops the focus of an id that no such widget of the pass has, so Tab would +/// lose the focus at the canvas and start over at the window's first stop. A pass that declares a canvas and draws no +/// such widget reports the finding `canvas-without-widget`, and debug builds log it once. A pass that hides the canvas +/// makes no call. pub fn host_canvas(ctx: &Context, id: Id, keys: KeyUse) { if !crate::runtime::measure::active(ctx) { with(ctx, |state| state.host_canvases.push(id)); @@ -1116,20 +1117,20 @@ pub(crate) fn surrender_after_scopes(ctx: &Context, widget: Id) { with(ctx, |state| state.surrender_after_scopes = Some(widget)); } -/// Reports each canvas the running pass declared (`host_canvas`) whose id no interactive egui widget of the pass has. -/// Read at the pass's end, since a canvas may be declared before it is drawn. A canvas hidden for one pass and still -/// declared counts: egui drops its focus at the end of that pass. +/// Reports each canvas the running pass declared (`host_canvas`) whose id no focusable egui widget of the pass has. Read +/// at the pass's end, since a canvas may be declared before it is drawn. A canvas hidden for one pass and still declared +/// counts: egui drops its focus at the end of that pass. fn report_undrawn_canvases(ctx: &Context) { for id in with(ctx, |state| std::mem::take(&mut state.host_canvases)) { - if egui_focus::keeps_focus_of(ctx, id) { - continue; - } + let subject = match egui_focus::drawn_sense(ctx, id) { + Some(sense) if sense.is_focusable() => continue, + Some(sense) => format!("{id:?}: its widget senses {sense:?}, which takes no focus"), + None => format!("{id:?}: no egui widget with the id was drawn"), + }; if cfg!(debug_assertions) { - log_once(format!("canvas:{id:?}"), || { - log::warn!("`host_canvas` declared the canvas {id:?}, but no interactive egui widget with that id was drawn in the pass"); - }); + log_once(format!("canvas:{subject}"), || log::warn!("`host_canvas` declared the canvas {subject}")); } - inspect::finding(ctx, inspect::Finding { rule: "canvas-without-widget", component: "host_canvas", subject: format!("{id:?}") }); + inspect::finding(ctx, inspect::Finding { rule: "canvas-without-widget", component: "host_canvas", subject }); } } diff --git a/crates/ui-contract/src/testing/host_key_trials.rs b/crates/ui-contract/src/testing/host_key_trials.rs index 1ad0c3026..d717b889e 100644 --- a/crates/ui-contract/src/testing/host_key_trials.rs +++ b/crates/ui-contract/src/testing/host_key_trials.rs @@ -999,34 +999,57 @@ fn a_host_canvas_marks_the_window_and_tab_toggles_its_panels() { ); } -/// Guards the finding that tells an app its canvas stop takes Tab and loses the focus: `host_canvas` named an id that no -/// egui widget of the pass has. A canvas declared before it is drawn, and one neither declared nor drawn, give none. -#[trial] -fn a_host_canvas_no_widget_draws_is_a_finding() { +/// How an app's window shows the canvas of `host_canvas_findings`. +#[derive(Clone, Copy, Debug)] +enum Shown { + /// Neither declared nor drawn. + Hidden, + /// Declared, and drawn with a focusable widget that senses clicks or drags. + Click, + Drag, + /// Declared, and drawn with a widget that senses drags and is not focusable. + Unfocusable, + /// Declared and not drawn. + Undrawn, +} + +/// Whether the canvas holds egui focus after a Tab from nothing in a window that shows it as `shown`, declared before it +/// is drawn, and the subjects of the findings on it. +fn host_canvas_findings(shown: Shown) -> (bool, Vec) { let canvas = named_id("host canvas"); - let (declared, drawn) = (Rc::new(Cell::new(true)), Rc::new(Cell::new(true))); - let (declares, draws) = (Rc::clone(&declared), Rc::clone(&drawn)); let mut show = move |ui: &mut Ui| { - if declares.get() { + if !matches!(shown, Shown::Hidden) { host_canvas(ui.ctx(), canvas, KeyUse::CANVAS); } - if draws.get() { - widget(ui, canvas); + let rect = Rect::from_min_size(Pos2::new(100.0, 300.0), egui::vec2(80.0, 30.0)); + match shown { + Shown::Hidden | Shown::Undrawn => {} + Shown::Click => _ = fixture::host_button(ui, canvas, rect), + Shown::Drag => _ = fixture::host_drag_area(ui, canvas, rect), + Shown::Unfocusable => fixture::host_unfocusable_area(ui, canvas, rect), } }; let mut frames = Frames::new(); - frames.idle(3, &mut show); - declared.set(false); - drawn.set(false); - frames.idle(1, &mut show); - assert!(findings(&frames.ctx).is_empty(), "a drawn canvas and a hidden one: {:?}", findings(&frames.ctx)); - declared.set(true); - frames.idle(1, &mut show); - let found = findings(&frames.ctx); - assert!( - matches!(found.as_slice(), [only] if only.rule == "canvas-without-widget" && only.subject == format!("{canvas:?}")), - "the declared canvas no widget draws: {found:?}" - ); + frames.idle(2, &mut show); + press_key(&mut frames, &mut show, Key::Tab); + frames.idle(2, &mut show); + let found = findings(&frames.ctx).into_iter().filter(|finding| finding.rule == "canvas-without-widget"); + (egui_focused(&frames.ctx) == Some(canvas), found.map(|finding| finding.subject).collect()) +} + +/// Guards the finding that tells an app its canvas stop takes Tab and loses the focus: `host_canvas` named an id that no +/// focusable egui widget of the pass has. +#[trial] +fn a_host_canvas_no_focusable_widget_draws_is_a_finding() { + for shown in [Shown::Click, Shown::Drag] { + assert_eq!(host_canvas_findings(shown), (true, Vec::new()), "{shown:?}: Tab stays at a canvas with a focusable widget"); + } + assert_eq!(host_canvas_findings(Shown::Hidden).1, Vec::::new(), "a hidden canvas makes no call"); + for (shown, says) in [(Shown::Undrawn, "no egui widget"), (Shown::Unfocusable, "Sense")] { + let (focused, found) = host_canvas_findings(shown); + assert!(!focused, "{shown:?}: egui drops the focus Tab gave the canvas"); + assert!(matches!(found.as_slice(), [only] if only.contains(says)), "{shown:?}: {found:?}"); + } } /// What `event` did with nothing focused in a window whose host declares its canvas with `keys`: whether the event diff --git a/docs/craft-framework.md b/docs/craft-framework.md index 9d7a00314..8064f47d8 100644 --- a/docs/craft-framework.md +++ b/docs/craft-framework.md @@ -144,7 +144,7 @@ An app with its own eframe `App` calls the hooks in `craft::ui::shell::embed`. ` | Each frame | `raw_input_hook` | `embed::before_input(ctx, \|output\| { ...; input })`: the closure receives the `FrameOutput` of the frame before (fired commands, announcements, chrome toggles) and returns the `FrameInput` for this frame (`RootEnv`, command states, the `Host`). eframe runs the hook for the main window only: an app that drops the window system's input there (an agent-driven session) sets `FrameInput::window_input(WindowInput::Dropped)` too, and the runtime drops it in every other OS window it hosts, before injected input joins. macOS Control+Click is the runtime's in every window; the app does not map it. | | Each frame | `logic`, after the app's own logic | `embed::logic(ctx, \|\| decision)`: the root window's close path. The closure runs only when the root window was asked to close, and returns `CloseDecision::Close` or `Hold`. | | Each pass | `ui`, before the app's UI | `embed::before_ui(ctx, frame)`: hands the runtime the root's native window (eframe's `Frame`, or any `raw_window_handle::HasWindowHandle`) on Windows, where the runtime answers the window's hit test (resize edges, the title bar's move area, snap layouts on the maximize button), and fits the root window to its monitor once. Native only; it needs no eframe feature of the facade. | -| Each pass | `ui`, where the app draws its own document canvas | Optional: `ui::runtime::focus::host_canvas(ctx, id, KeyUse::CANVAS)` declares it as the window's canvas (Tab row below). `id` is the id of the interactive egui widget the app draws for the canvas in that pass: egui drops the focus of an id no widget has, so Tab would lose the focus there, and the pass reports the finding `canvas-without-widget`. Every other focusable egui widget the app draws is a Tab stop with no call: the window's one Tab order holds it among the framework's stops, in the order the pass draws them. | +| Each pass | `ui`, where the app draws its own document canvas | Optional: `ui::runtime::focus::host_canvas(ctx, id, KeyUse::CANVAS)` declares it as the window's canvas (Tab row below). `id` is the id of the focusable egui widget the app draws for the canvas in that pass (`Sense::click()`, `Sense::drag()`): egui drops the focus of any other id, so Tab would lose the focus there, and the pass reports the finding `canvas-without-widget`. Every other focusable egui widget the app draws is a Tab stop with no call: the window's one Tab order holds it among the framework's stops, in the order the pass draws them. | | Each pass | `ui`, last | Optional: `ui::runtime::keys::with_window_intents(ctx, rtl, \|intents\| ...)` reads the keys no component took (below). | `install` takes over these parts of the context for the whole window, not only for framework components: From 0f8d8365e215ed4d7dac53f7d5ead8f68c96bc2e Mon Sep 17 00:00:00 2001 From: aiongg Date: Wed, 25 Nov 2026 13:24:39 +0000 Subject: [PATCH 4/5] Focus given to the app's own widgets: held presses, stale records, canvases The runtime keeps its surrender rule on the focus it gave an app's own widget until no pointer button is down, so the release of the press that gave the focus does not take it back. The record of the given focus ends once egui's focus is elsewhere. Whether a widget is drawn is read from egui's widgets of the running pass, for the given focus and for `host_canvas` findings alike. Focus given to a canvas before `host_canvas` registers it follows the canvas's keys. A canvas drawn in a disabled `Ui` is a `canvas-without-widget` finding too; the finding's text is made only when it is kept, and a fault is logged once. --- .../ui-contract/src/runtime/egui/fixture.rs | 6 ++ crates/ui-contract/src/runtime/egui/focus.rs | 9 +- crates/ui-contract/src/runtime/egui/input.rs | 5 ++ crates/ui-contract/src/runtime/focus.rs | 66 +++++++++----- crates/ui-contract/src/runtime/focus/nav.rs | 3 +- crates/ui-contract/src/runtime/inspect.rs | 9 +- .../src/testing/host_key_trials.rs | 86 +++++++++++++++---- docs/craft-framework.md | 4 +- 8 files changed, 140 insertions(+), 48 deletions(-) diff --git a/crates/ui-contract/src/runtime/egui/fixture.rs b/crates/ui-contract/src/runtime/egui/fixture.rs index e2434526e..1202576a3 100644 --- a/crates/ui-contract/src/runtime/egui/fixture.rs +++ b/crates/ui-contract/src/runtime/egui/fixture.rs @@ -618,6 +618,12 @@ pub(crate) fn host_drag_area(ui: &Ui, id: egui::Id, rect: Rect) -> (bool, bool) (response.dragged(), response.drag_stopped()) } +/// A host's own clickable egui widget `id` at `rect` in a disabled `Ui`. +#[cfg(feature = "suite")] +pub(crate) fn host_disabled_button(ui: &mut Ui, id: egui::Id, rect: Rect) { + ui.scope_builder(egui::UiBuilder::new().disabled(), |ui| host_button(ui, id, rect)); +} + /// A host's own egui widget `id` at `rect` that senses drags and takes no focus. #[cfg(feature = "suite")] pub(crate) fn host_unfocusable_area(ui: &Ui, id: egui::Id, rect: Rect) { diff --git a/crates/ui-contract/src/runtime/egui/focus.rs b/crates/ui-contract/src/runtime/egui/focus.rs index 1685b0aa1..82045ed93 100644 --- a/crates/ui-contract/src/runtime/egui/focus.rs +++ b/crates/ui-contract/src/runtime/egui/focus.rs @@ -33,10 +33,11 @@ pub(crate) fn candidates_since(ctx: &Context, seen: usize) -> Vec::to_vec).unwrap_or_default()) } -/// What the widget `id` drawn so far in the running pass senses; `None` when no widget has the id. egui takes the focus -/// from a widget that is not focusable when it is drawn, and from an id no interactive widget has at the pass's end. -pub(crate) fn drawn_sense(ctx: &Context, id: Id) -> Option { - ctx.viewport(|viewport| viewport.this_pass.widgets.get(id).map(|widget| widget.sense)) +/// The widget `id` as drawn so far in the running pass; `None` when no widget has the id. egui takes the focus from a +/// widget that is not focusable or not enabled when it is drawn, and from an id no interactive widget has at the pass's +/// end. +pub(crate) fn drawn_widget(ctx: &Context, id: Id) -> Option { + ctx.viewport(|viewport| viewport.this_pass.widgets.get(id).copied()) } /// Whether the widget egui holds key focus on keeps Tab by its event filter (`Memory::focus_lock_filter`). diff --git a/crates/ui-contract/src/runtime/egui/input.rs b/crates/ui-contract/src/runtime/egui/input.rs index 3db5179fd..ae62f7c0e 100644 --- a/crates/ui-contract/src/runtime/egui/input.rs +++ b/crates/ui-contract/src/runtime/egui/input.rs @@ -795,6 +795,11 @@ pub(crate) fn dragged(ctx: &Context) -> Option { ctx.dragged_id() } +/// Whether a pointer button is down. +pub(crate) fn button_down(ctx: &Context) -> bool { + ctx.input(|input| input.pointer.any_down()) +} + /// Where the press that is held down began, while a button is down. pub(crate) fn held_press_origin(ctx: &Context) -> Option { ctx.input(|input| if input.pointer.any_down() { input.pointer.press_origin() } else { None }) diff --git a/crates/ui-contract/src/runtime/focus.rs b/crates/ui-contract/src/runtime/focus.rs index 0d2f24486..c94ed1c6b 100644 --- a/crates/ui-contract/src/runtime/focus.rs +++ b/crates/ui-contract/src/runtime/focus.rs @@ -247,16 +247,19 @@ pub(crate) fn apply(ctx: &Context, acts: Vec) { /// Registers a stop of the running pass in the innermost open scope, in registration order: after the app's own /// widgets drawn before it (`take_app_widgets`). The app's own widget `stop` names (`host_canvas`) takes the place of -/// its stop as one of those widgets, if the pass took it already. +/// its stop as one of those widgets, if the pass took it already; focus the runtime gave that stop follows the canvas's +/// keys from then on. pub(crate) fn register_stop(ctx: &Context, stop: Stop) { take_app_widgets(ctx, Some(stop.root)); + let held = stop.host && egui_focus::has_focus(ctx, stop.root); let acts = with(ctx, |state| { if stop.host && let Some(rec) = state.stops.iter_mut().find(|rec| rec.stop.host && rec.stop.id == stop.id) { state.stop_roots.insert(stop.root); rec.stop = stop; - return Vec::new(); + let rec = rec.clone(); + return if held && state.given == Some(rec.stop.root) { state.enter_stop(rec, FocusOrigin::Request) } else { Vec::new() }; } state.push_stop(stop) }); @@ -331,12 +334,12 @@ fn take_app_widgets(ctx: &Context, except: Option) { /// canvas cannot trap keyboard navigation. With the canvas focused, the same keys stay in egui, a Tab it keeps and /// Escape too, as for any focused widget of the app's own; Escape with nothing focused is the window's cancel. /// -/// Call it in each pass the canvas shows, before or after the canvas is drawn, with the id of the focusable egui widget -/// the app draws for it in every such pass (`Sense::click()`, `Sense::drag()`; the bare flags `Sense::CLICK` and -/// `Sense::DRAG` are not focusable). egui drops the focus of an id that no such widget of the pass has, so Tab would +/// Call it in each pass the canvas shows, before or after the canvas is drawn, with the id of the focusable, enabled +/// egui widget the app draws for it in every such pass (`Sense::click()`, `Sense::drag()`; the bare flags `Sense::CLICK` +/// and `Sense::DRAG` are not focusable). egui drops the focus of an id that no such widget of the pass has, so Tab would /// lose the focus at the canvas and start over at the window's first stop. A pass that declares a canvas and draws no -/// such widget reports the finding `canvas-without-widget`, and debug builds log it once. A pass that hides the canvas -/// makes no call. +/// such widget reports the finding `canvas-without-widget`, and debug builds log it once. A pass that hides or disables +/// the canvas makes no call. pub fn host_canvas(ctx: &Context, id: Id, keys: KeyUse) { if !crate::runtime::measure::active(ctx) { with(ctx, |state| state.host_canvases.push(id)); @@ -1122,23 +1125,45 @@ pub(crate) fn surrender_after_scopes(ctx: &Context, widget: Id) { with(ctx, |state| state.surrender_after_scopes = Some(widget)); } -/// Reports each canvas the running pass declared (`host_canvas`) whose id no focusable egui widget of the pass has. Read -/// at the pass's end, since a canvas may be declared before it is drawn. A canvas hidden for one pass and still declared -/// counts: egui drops its focus at the end of that pass. +/// Reports each canvas the running pass declared (`host_canvas`) whose id no focusable, enabled egui widget of the pass +/// has. Read at the pass's end, since a canvas may be declared before it is drawn. A canvas hidden for one pass and still +/// declared counts: egui drops its focus at the end of that pass. fn report_undrawn_canvases(ctx: &Context) { - for id in with(ctx, |state| std::mem::take(&mut state.host_canvases)) { - let subject = match egui_focus::drawn_sense(ctx, id) { - Some(sense) if sense.is_focusable() => continue, - Some(sense) => format!("{id:?}: its widget senses {sense:?}, which takes no focus"), - None => format!("{id:?}: no egui widget with the id was drawn"), + for id in with(ctx, |state| state.host_canvases.clone()) { + let fault = match egui_focus::drawn_widget(ctx, id) { + None => "no egui widget with the id was drawn", + Some(widget) if !widget.sense.is_focusable() => "its widget's sense takes no focus", + Some(widget) if !widget.enabled => "its widget is disabled, which takes no focus", + Some(_) => continue, }; if cfg!(debug_assertions) { - log_once(format!("canvas:{subject}"), || log::warn!("`host_canvas` declared the canvas {subject}")); + log_once(fault.to_owned(), || log::warn!("`host_canvas` declared the canvas {id:?}: {fault}")); + } + if inspect::reports(ctx) { + let subject = format!("{id:?}: {fault}"); + inspect::finding(ctx, inspect::Finding { rule: "canvas-without-widget", component: "host_canvas", subject }); } - inspect::finding(ctx, inspect::Finding { rule: "canvas-without-widget", component: "host_canvas", subject }); } } +/// Leaves the focus the runtime gave an app's own widget (`State::app_widget`) to egui's rule, at the end of a pass that +/// drew the widget with no pointer button down: until then the press, and the click its release makes, of the gesture +/// that gave the focus never takes it back. The record of a focus that has moved, or that egui dropped +/// because no pass drew the widget, ends here too. +fn settle_given(ctx: &Context, app_widget: impl Fn(Id) -> bool) { + let Some(id) = with(ctx, |state| state.given) else { return }; + if egui_focus::has_focus(ctx, id) { + let drawn = egui_focus::drawn_widget(ctx, id).is_some(); + if !drawn || (app_widget(id) && crate::runtime::egui::input::button_down(ctx)) { + return; + } + if app_widget(id) { + egui_focus::leave_to_egui(ctx, id); + } + } + with(ctx, |state| state.given = None); +} + /// The end hook: applies the press's focus move, returns focus to the opener of a scope that went away, /// moves it off a stop that was not registered, and records what the next input hook reads. pub(crate) fn end(ctx: &Context) { @@ -1182,12 +1207,7 @@ pub(crate) fn end(ctx: &Context) { let frame = crate::runtime::egui::pass::frame_nr(ctx, viewport); let acts = with(ctx, |state| nav::end(state, focused, on_app_widget, frame)); apply(ctx, acts); - if let Some(id) = with(ctx, |state| state.given).filter(|id| ctx.read_response(*id).is_some()) { - with(ctx, |state| state.given = None); - if app_widget(id) { - egui_focus::leave_to_egui(ctx, id); - } - } + settle_given(ctx, app_widget); // Escape over a captured framework press or drag cancels it (`frame::begin_pass`), whatever egui has focused. let captured = crate::runtime::pointer::press_captured(ctx) || crate::runtime::drag::running(ctx); let host_focus = !captured && with(ctx, |state| state.focus_now).is_some_and(app_widget); diff --git a/crates/ui-contract/src/runtime/focus/nav.rs b/crates/ui-contract/src/runtime/focus/nav.rs index bba7b6ea7..3fa62bd52 100644 --- a/crates/ui-contract/src/runtime/focus/nav.rs +++ b/crates/ui-contract/src/runtime/focus/nav.rs @@ -195,6 +195,7 @@ impl State { self.entered = false; self.asked = false; self.candidates_seen = 0; + self.host_canvases.clear(); } /// The registrations of last pass, which Tab and the arrows move over. @@ -261,7 +262,7 @@ impl State { self.enter_stop(rec, FocusOrigin::Press) } - fn enter_stop(&mut self, rec: StopRec, origin: FocusOrigin) -> Vec { + pub(super) fn enter_stop(&mut self, rec: StopRec, origin: FocusOrigin) -> Vec { self.note_entry(&rec); let stop = &rec.stop; let roving = stop.group.is_some(); diff --git a/crates/ui-contract/src/runtime/inspect.rs b/crates/ui-contract/src/runtime/inspect.rs index b7eac2e3c..fc48d8fda 100644 --- a/crates/ui-contract/src/runtime/inspect.rs +++ b/crates/ui-contract/src/runtime/inspect.rs @@ -65,9 +65,14 @@ pub(crate) fn steps_of(ctx: &Context, id: Id) -> Vec<&'static str> { pass_state::with::(ctx, |log| log.steps.get(&id).cloned().unwrap_or_default()) } +/// Whether a finding reported now is kept. +pub(crate) fn reports(ctx: &Context) -> bool { + fixture_frame() || recording(ctx) +} + /// Reports a finding. pub(crate) fn finding(ctx: &Context, finding: Finding) { - if !fixture_frame() && !recording(ctx) { + if !reports(ctx) { return; } pass_state::with::(ctx, |log| { @@ -86,7 +91,7 @@ pub(crate) fn findings(ctx: &Context) -> Vec { /// Records that the canvas control `type_name` showed in this pass, so the canvas-control cases can check that a /// press away from its parts reaches the tool. pub(crate) fn canvas_control(ctx: &Context, type_name: &'static str) { - if !fixture_frame() && !recording(ctx) { + if !reports(ctx) { return; } pass_state::with::(ctx, |log| { diff --git a/crates/ui-contract/src/testing/host_key_trials.rs b/crates/ui-contract/src/testing/host_key_trials.rs index 19af4891e..8c44785ed 100644 --- a/crates/ui-contract/src/testing/host_key_trials.rs +++ b/crates/ui-contract/src/testing/host_key_trials.rs @@ -859,26 +859,77 @@ fn a_press_on_a_component_takes_the_focus_tab_gave_an_app_field() { assert_eq!(lost.get(), 1, "the field sees its focus lost once"); } -/// A focus request that a click makes for an app's own widget drawn later in the same pass stands: the click, which is -/// elsewhere for that widget, does not take the focus back. The next click elsewhere does. +/// What gives an app's field the focus during a click elsewhere. +#[derive(Clone, Copy, Debug)] +enum GivenAt { + /// The press closes a popup, which gives the focus back to the field it opened from. + PopupPress, + /// The app's request at the press. + Press, + /// The app's request at the release, in a pass that draws the field later. + Release, +} + +/// Focus the runtime gives an app's own widget during a click elsewhere stands: neither the press nor its release takes +/// it back. The next click elsewhere does, by egui's rule. #[trial] -fn a_request_at_a_click_gives_an_app_field_drawn_later_the_focus() { - let field = named_id("app field"); - let asking = Rc::new(Cell::new(false)); - let ask = Rc::clone(&asking); - let mut base = mixed_window(); - let mut show = move |ui: &mut Ui| { - if ui.input(|input| input.pointer.any_click()) && ask.take() { - request(ui.ctx(), FocusTarget::Id(field)); +fn a_click_that_gives_an_app_field_the_focus_does_not_take_it_back() { + for at in [GivenAt::PopupPress, GivenAt::Press, GivenAt::Release] { + let field = named_id("app field"); + let (asking, popup) = (Rc::new(Cell::new(false)), Rc::new(Cell::new(false))); + let (ask, open) = (Rc::clone(&asking), Rc::clone(&popup)); + let mut base = mixed_window(); + let mut show = move |ui: &mut Ui| { + let (pressed, clicked) = ui.input(|input| (input.pointer.primary_pressed(), input.pointer.any_click())); + let now = if matches!(at, GivenAt::Release) { clicked } else { pressed }; + if now && ask.take() { + match at { + GivenAt::PopupPress => open.set(false), + GivenAt::Press | GivenAt::Release => _ = request(ui.ctx(), FocusTarget::Id(field)), + } + } + base(ui); + if open.get() { + push_scope(ui.ctx(), named_id("popup"), FocusPolicy::POPUP, None); + widget(ui, named_id("popup button")); + register_stop(ui.ctx(), Stop::new(named_id("popup button"), KeyUse::of(Input::Pointer))); + pop_scope(ui.ctx()); + } + }; + let mut frames = Frames::new(); + frames.idle(2, &mut show); + if matches!(at, GivenAt::PopupPress) { + fixture::host_focus(&frames.ctx, field); + frames.idle(1, &mut show); + popup.set(true); + frames.idle(2, &mut show); + assert_eq!(egui_focused(&frames.ctx), Some(named_id("popup button")), "the popup takes the focus"); } - base(ui); + asking.set(true); + let empty = Pos2::new(300.0, 450.0); + assert_eq!(click_focus(&mut frames, &mut show, empty).1, Some(field), "{at:?}: the focus stands over the release"); + assert_eq!(click_focus(&mut frames, &mut show, empty).1, None, "{at:?}: the next click elsewhere takes it"); + } +} + +/// A canvas declared after a component registered behind it is first taken as one of the app's widgets: focus the runtime +/// gave it there follows the canvas's rules, which keep it over Escape. +#[trial] +fn focus_given_to_a_canvas_before_its_declaration_is_the_canvas_s() { + let canvas = named_id("host canvas"); + let mut show = move |ui: &mut Ui| { + fixture::host_button(ui, canvas, Rect::from_min_size(Pos2::new(100.0, 300.0), egui::vec2(80.0, 30.0))); + widget(ui, named_id("button")); + register_stop(ui.ctx(), Stop::new(named_id("button"), KeyUse::of(Input::Pointer))); + host_canvas(ui.ctx(), canvas, KeyUse::CANVAS); }; let mut frames = Frames::new(); + frames.frame(Vec::new(), |_| {}); + request(&frames.ctx, FocusTarget::Id(canvas)); frames.idle(2, &mut show); - asking.set(true); - let empty = Pos2::new(300.0, 450.0); - assert_eq!(click_focus(&mut frames, &mut show, empty).1, Some(field), "the requested focus stands"); - assert_eq!(click_focus(&mut frames, &mut show, empty).1, None, "the next click elsewhere takes it by egui's rule"); + assert_eq!(egui_focused(&frames.ctx), Some(canvas)); + press_key(&mut frames, &mut show, Key::Escape); + assert_eq!(egui_focused(&frames.ctx), Some(canvas), "egui keeps the focus on the canvas over its Escape"); } /// Where Tab reaches only text fields (the Mac's default), it reaches the app's own text field and skips the app's @@ -1139,6 +1190,8 @@ enum Shown { Drag, /// Declared, and drawn with a widget that senses drags and is not focusable. Unfocusable, + /// Declared, and drawn in a disabled `Ui`. + Disabled, /// Declared and not drawn. Undrawn, } @@ -1157,6 +1210,7 @@ fn host_canvas_findings(shown: Shown) -> (bool, Vec) { Shown::Click => _ = fixture::host_button(ui, canvas, rect), Shown::Drag => _ = fixture::host_drag_area(ui, canvas, rect), Shown::Unfocusable => fixture::host_unfocusable_area(ui, canvas, rect), + Shown::Disabled => fixture::host_disabled_button(ui, canvas, rect), } }; let mut frames = Frames::new(); @@ -1175,7 +1229,7 @@ fn a_host_canvas_no_focusable_widget_draws_is_a_finding() { assert_eq!(host_canvas_findings(shown), (true, Vec::new()), "{shown:?}: Tab stays at a canvas with a focusable widget"); } assert_eq!(host_canvas_findings(Shown::Hidden).1, Vec::::new(), "a hidden canvas makes no call"); - for (shown, says) in [(Shown::Undrawn, "no egui widget"), (Shown::Unfocusable, "Sense")] { + for (shown, says) in [(Shown::Undrawn, "no egui widget"), (Shown::Unfocusable, "sense"), (Shown::Disabled, "disabled")] { let (focused, found) = host_canvas_findings(shown); assert!(!focused, "{shown:?}: egui drops the focus Tab gave the canvas"); assert!(matches!(found.as_slice(), [only] if only.contains(says)), "{shown:?}: {found:?}"); diff --git a/docs/craft-framework.md b/docs/craft-framework.md index ffc6b199f..5484774f9 100644 --- a/docs/craft-framework.md +++ b/docs/craft-framework.md @@ -144,7 +144,7 @@ An app with its own eframe `App` calls the hooks in `craft::ui::shell::embed`. ` | Each frame | `raw_input_hook` | `embed::before_input(ctx, \|output\| { ...; input })`: the closure receives the `FrameOutput` of the frame before (fired commands, announcements, chrome toggles) and returns the `FrameInput` for this frame (`RootEnv`, command states, the `Host`). eframe runs the hook for the main window only: an app that drops the window system's input there (an agent-driven session) sets `FrameInput::window_input(WindowInput::Dropped)` too, and the runtime drops it in every other OS window it hosts, before injected input joins. macOS Control+Click is the runtime's in every window; the app does not map it. | | Each frame | `logic`, after the app's own logic | `embed::logic(ctx, \|\| decision)`: the root window's close path. The closure runs only when the root window was asked to close, and returns `CloseDecision::Close` or `Hold`. | | Each pass | `ui`, before the app's UI | `embed::before_ui(ctx, frame)`: hands the runtime the root's native window (eframe's `Frame`, or any `raw_window_handle::HasWindowHandle`) on Windows, where the runtime answers the window's hit test (resize edges, the title bar's move area, snap layouts on the maximize button), and fits the root window to its monitor once. Native only; it needs no eframe feature of the facade. | -| Each pass | `ui`, where the app draws its own document canvas | Optional: `ui::runtime::focus::host_canvas(ctx, id, KeyUse::CANVAS)` declares it as the window's canvas (Tab row below). `id` is the id of the focusable egui widget the app draws for the canvas in that pass (`Sense::click()`, `Sense::drag()`): egui drops the focus of any other id, so Tab would lose the focus there, and the pass reports the finding `canvas-without-widget`. Every other focusable egui widget the app draws is a Tab stop with no call: the window's one Tab order holds it among the framework's stops, in the order the pass draws them. | +| Each pass | `ui`, where the app draws its own document canvas | Optional: `ui::runtime::focus::host_canvas(ctx, id, KeyUse::CANVAS)` declares it as the window's canvas (Tab row below). `id` is the id of the focusable, enabled egui widget the app draws for the canvas in that pass (`Sense::click()`, `Sense::drag()`): egui drops the focus of any other id, so Tab would lose the focus there, and the pass reports the finding `canvas-without-widget`. Every other focusable egui widget the app draws is a Tab stop with no call: the window's one Tab order holds it among the framework's stops, in the order the pass draws them. | | Each pass | `ui`, last | Optional: `ui::runtime::keys::with_window_intents(ctx, rtl, \|intents\| ...)` reads the keys no component took (below). | `install` takes over these parts of the context for the whole window, not only for framework components: @@ -160,7 +160,7 @@ An app with its own eframe `App` calls the hooks in `craft::ui::shell::embed`. ` | IME | Taken while a framework editor owns the IME: its events and `PlatformOutput.ime` are the runtime's. Otherwise they stay egui's, for the app's own `TextEdit` or IME code. | | An app's own focused widget | While egui focus is on a widget no framework component made, or an egui popup is open, and no framework press or drag is captured, Escape, the plain Enter and egui's clipboard events stay in egui's input for it, and the runtime routes nothing for them; Tab and Shift+Tab are the window's focus moves (Tab row) unless the widget keeps Tab or the popup is open. While egui focus is on such a widget, the arrows move egui focus among the app's widgets as egui does; while a framework stop has the focus, egui's arrow moves are off. | | Releases | The release of every key the runtime took is taken too. | -| Focus surrender | The runtime moves its own focus on press (8.3): a press a framework component takes moves focus to it; a press no component takes drops the framework's focus. egui's click-away never takes the framework's focus. egui's surrender option (`InputOptions::surrender_focus_on`) stays the app's and governs the focus of the app's own widgets, however they got it (the app's code, a click, Tab, F6, a framework request), as in egui alone: a press no component takes leaves that focus to egui's rule, except that the press or click of the pass that gives the focus never takes it back. Escape releases it too, unless the widget's egui key filter keeps Escape. | +| Focus surrender | The runtime moves its own focus on press (8.3): a press a framework component takes moves focus to it; a press no component takes drops the framework's focus. egui's click-away never takes the framework's focus. egui's surrender option (`InputOptions::surrender_focus_on`) stays the app's and governs the focus of the app's own widgets, however they got it (the app's code, a click, Tab, F6, a framework request), as in egui alone: a press no component takes leaves that focus to egui's rule, except that a press that gives the focus, and its release, never take it back: the next press or click elsewhere does. Escape releases it too, unless the widget's egui key filter keeps Escape. | | Clicks | egui's click options (`InputOptions::max_click_dist`, `max_click_duration`) stay the app's, for its own widgets. A framework component clicks and drags by the framework's press lifecycle: a release within the slop (`HitSizes::slop`), whatever its duration. Read a component's click with `contract::clicked(&response)` or its output's `clicked()`; egui's `Response::clicked()` on a component's response also needs a click by egui's options. | | Zoom keys | egui's keyboard zoom is off and nothing takes its place: the interface scale is `RootEnv::scale`, and an app whose ⌘= and ⌘- changed it binds them itself. | | Quit | egui's quit shortcuts are cleared. ⌘Q (Ctrl+Q on Windows and Linux) is the default of the command `QuitCommand::Quit` (id `window.quit`), which the runtime runs from any source: it asks the root window to close through the close path below, so the app's close decision asks about unsaved work. It fires with a modal open; the close path then refuses under an app-modal layer. Its default is bound and yielded as F6 is; an app whose own shortcut table reads its quit key from egui unbinds it there. | From d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e Mon Sep 17 00:00:00 2001 From: aiongg Date: Wed, 25 Nov 2026 13:41:08 +0000 Subject: [PATCH 5/5] host_canvas: sizing passes report nothing, and declaring a focused canvas enters nothing A canvas widget in an invisible Ui, which egui disables, is not reported as disabled (WidgetRect::visible). A declaration that takes over a focused canvas's automatic stop applies its key filter alone (nav::focus_act): the opener of the layer around it and the recorded arrival stay. --- crates/ui-contract/src/runtime/egui/areas.rs | 6 +++ crates/ui-contract/src/runtime/focus.rs | 13 +++--- crates/ui-contract/src/runtime/focus/nav.rs | 33 ++++++++------- .../src/testing/host_key_trials.rs | 40 ++++++++++++++++++- 4 files changed, 71 insertions(+), 21 deletions(-) diff --git a/crates/ui-contract/src/runtime/egui/areas.rs b/crates/ui-contract/src/runtime/egui/areas.rs index 1a3041283..0e814afa0 100644 --- a/crates/ui-contract/src/runtime/egui/areas.rs +++ b/crates/ui-contract/src/runtime/egui/areas.rs @@ -551,6 +551,12 @@ pub(crate) fn host_popup(ui: &Ui, id: egui::Id, at: Pos2) { egui::Popup::new(id, ui.ctx().clone(), at, ui.layer_id()).open_memory(None).show(|ui| ui.allocate_space(ui.spacing().interact_size)); } +/// A host's own egui window `id` around `body`: its first pass is a sizing pass, in an invisible `Ui`. +#[cfg(feature = "suite")] +pub(crate) fn host_egui_window(ctx: &Context, id: Id, body: impl FnOnce(&mut Ui)) { + egui::Window::new("host").id(id).show(ctx, body); +} + /// The size of one entry of [`host_popup_list`], as an app's popup list entry. #[cfg(feature = "suite")] const HOST_LIST_ENTRY: Vec2 = Vec2::new(104.0, 22.0); diff --git a/crates/ui-contract/src/runtime/focus.rs b/crates/ui-contract/src/runtime/focus.rs index c94ed1c6b..1bac55998 100644 --- a/crates/ui-contract/src/runtime/focus.rs +++ b/crates/ui-contract/src/runtime/focus.rs @@ -257,9 +257,9 @@ pub(crate) fn register_stop(ctx: &Context, stop: Stop) { && let Some(rec) = state.stops.iter_mut().find(|rec| rec.stop.host && rec.stop.id == stop.id) { state.stop_roots.insert(stop.root); + let acts = if held && state.given == Some(stop.root) { vec![nav::focus_act(&stop)] } else { Vec::new() }; rec.stop = stop; - let rec = rec.clone(); - return if held && state.given == Some(rec.stop.root) { state.enter_stop(rec, FocusOrigin::Request) } else { Vec::new() }; + return acts; } state.push_stop(stop) }); @@ -338,8 +338,8 @@ fn take_app_widgets(ctx: &Context, except: Option) { /// egui widget the app draws for it in every such pass (`Sense::click()`, `Sense::drag()`; the bare flags `Sense::CLICK` /// and `Sense::DRAG` are not focusable). egui drops the focus of an id that no such widget of the pass has, so Tab would /// lose the focus at the canvas and start over at the window's first stop. A pass that declares a canvas and draws no -/// such widget reports the finding `canvas-without-widget`, and debug builds log it once. A pass that hides or disables -/// the canvas makes no call. +/// such widget reports the finding `canvas-without-widget`, and debug builds log it once; a canvas drawn in an invisible +/// `Ui` (an egui sizing pass) is not reported as disabled. A pass that hides or disables the canvas makes no call. pub fn host_canvas(ctx: &Context, id: Id, keys: KeyUse) { if !crate::runtime::measure::active(ctx) { with(ctx, |state| state.host_canvases.push(id)); @@ -1127,13 +1127,14 @@ pub(crate) fn surrender_after_scopes(ctx: &Context, widget: Id) { /// Reports each canvas the running pass declared (`host_canvas`) whose id no focusable, enabled egui widget of the pass /// has. Read at the pass's end, since a canvas may be declared before it is drawn. A canvas hidden for one pass and still -/// declared counts: egui drops its focus at the end of that pass. +/// declared counts: egui drops its focus at the end of that pass. Only a visible widget counts as disabled: egui disables +/// every widget of an invisible `Ui`, as the sizing pass of an `Area`, a `Window` or a `Grid` has. fn report_undrawn_canvases(ctx: &Context) { for id in with(ctx, |state| state.host_canvases.clone()) { let fault = match egui_focus::drawn_widget(ctx, id) { None => "no egui widget with the id was drawn", Some(widget) if !widget.sense.is_focusable() => "its widget's sense takes no focus", - Some(widget) if !widget.enabled => "its widget is disabled, which takes no focus", + Some(widget) if widget.visible && !widget.enabled => "its widget is disabled, which takes no focus", Some(_) => continue, }; if cfg!(debug_assertions) { diff --git a/crates/ui-contract/src/runtime/focus/nav.rs b/crates/ui-contract/src/runtime/focus/nav.rs index 3fa62bd52..d7d299d37 100644 --- a/crates/ui-contract/src/runtime/focus/nav.rs +++ b/crates/ui-contract/src/runtime/focus/nav.rs @@ -1,7 +1,7 @@ //! Focus movement: Tab and F6, roving groups, initial focus, restore, programmatic requests and focus after //! removal. Every movement reads last pass's registrations and returns the egui changes to apply. -use super::{Act, BeginIn, FocusOrigin, FocusTarget, Initial, PickedIn, State, StopKey, StopRec, TabReach}; +use super::{Act, BeginIn, FocusOrigin, FocusTarget, Initial, PickedIn, State, Stop, StopKey, StopRec, TabReach}; use crate::runtime::egui::focus as egui_focus; use crate::runtime::egui::memory::FastMap; use craft_behavior::nav::step; @@ -262,27 +262,16 @@ impl State { self.enter_stop(rec, FocusOrigin::Press) } - pub(super) fn enter_stop(&mut self, rec: StopRec, origin: FocusOrigin) -> Vec { + fn enter_stop(&mut self, rec: StopRec, origin: FocusOrigin) -> Vec { self.note_entry(&rec); let stop = &rec.stop; - let roving = stop.group.is_some(); - let keys = stop.keys; - // The app's canvas (`host_canvas`) reads its Escape from egui, as a stop that claims it does: egui keeps its focus - // on it. Every other widget of the app's own keeps Escape by its own egui filter. - let escape = (stop.host && !stop.automatic()) || keys.claims.iter().any(|chord| chord.key == craft_keymap::Key::Escape); - let filter = egui_focus::filter( - keys.keep == super::KeepKeys::Tab, - roving || matches!(keys.keep, super::KeepKeys::InlineArrows | super::KeepKeys::BlockArrows), - roving || keys.keep == super::KeepKeys::BlockArrows, - escape, - ); let moved = self.focus_now != Some(stop.root) || self.focused.get(&stop.root) != Some(&stop.key()); if moved { self.arrived = Some((self.frame, stop.key(), origin)); } self.focused.insert(stop.root, stop.key()); self.focus_now = Some(stop.root); - vec![Act::Focus(stop.root, filter)] + vec![focus_act(stop)] } /// Focus moving to `rec` from outside a scope that traps nothing and restores focus (a layer that Tab reaches, such as @@ -745,6 +734,22 @@ impl State { } } +/// Focus on the egui widget of `stop`, with the key filter its keys ask for. +pub(super) fn focus_act(stop: &Stop) -> Act { + let roving = stop.group.is_some(); + let keys = stop.keys; + // The app's canvas (`host_canvas`) reads its Escape from egui, as a stop that claims it does: egui keeps its focus + // on it. Every other widget of the app's own keeps Escape by its own egui filter. + let escape = (stop.host && !stop.automatic()) || keys.claims.iter().any(|chord| chord.key == craft_keymap::Key::Escape); + let filter = egui_focus::filter( + keys.keep == super::KeepKeys::Tab, + roving || matches!(keys.keep, super::KeepKeys::InlineArrows | super::KeepKeys::BlockArrows), + roving || keys.keep == super::KeepKeys::BlockArrows, + escape, + ); + Act::Focus(stop.root, filter) +} + fn cycle(entries: &[Entry], current: Option<&StopRec>, top: Option, forward: bool) -> Option { if entries.is_empty() { return None; diff --git a/crates/ui-contract/src/testing/host_key_trials.rs b/crates/ui-contract/src/testing/host_key_trials.rs index 8c44785ed..bf22eedf3 100644 --- a/crates/ui-contract/src/testing/host_key_trials.rs +++ b/crates/ui-contract/src/testing/host_key_trials.rs @@ -1180,6 +1180,41 @@ fn a_host_canvas_marks_the_window_and_tab_toggles_its_panels() { ); } +/// Focus that Tab moves to the app's canvas in a layer returns to the stop it came from when the layer goes away, also +/// when the group the canvas sits in first appears in the pass of the Tab: declaring the canvas enters nothing. +#[trial] +fn declaring_a_focused_canvas_keeps_the_opener_of_its_layer() { + let (opener, canvas) = (named_id("opener"), named_id("host canvas")); + let layer = Rc::new(Cell::new(true)); + let grouped = Rc::new(Cell::new(false)); + let (shown, group) = (Rc::clone(&layer), Rc::clone(&grouped)); + let mut show = move |ui: &mut Ui| { + widget(ui, opener); + register_stop(ui.ctx(), Stop::new(opener, KeyUse::of(Input::Pointer))); + if !shown.get() { + return; + } + push_scope(ui.ctx(), named_id("layer"), FocusPolicy::TAB_LAYER, None); + if group.get() { + push_scope(ui.ctx(), named_id("group"), FocusPolicy::NONE, None); + } + widget(ui, canvas); + host_canvas(ui.ctx(), canvas, KeyUse::CANVAS); + if group.get() { + pop_scope(ui.ctx()); + } + pop_scope(ui.ctx()); + }; + let mut frames = Frames::new(); + frames.idle(2, &mut show); + focus_stop(&mut frames, &mut show, opener); + grouped.set(true); + assert_eq!(tab_with(&mut frames, &mut show, Modifiers::NONE), Some(canvas), "Tab goes from the stop into the layer"); + layer.set(false); + frames.idle(2, &mut show); + assert_eq!(egui_focused(&frames.ctx), Some(opener), "the layer gives the focus back to the stop it came from"); +} + /// How an app's window shows the canvas of `host_canvas_findings`. #[derive(Clone, Copy, Debug)] enum Shown { @@ -1188,6 +1223,8 @@ enum Shown { /// Declared, and drawn with a focusable widget that senses clicks or drags. Click, Drag, + /// Declared, and drawn with a focusable widget in an egui window, whose first pass sizes it invisibly. + Window, /// Declared, and drawn with a widget that senses drags and is not focusable. Unfocusable, /// Declared, and drawn in a disabled `Ui`. @@ -1209,6 +1246,7 @@ fn host_canvas_findings(shown: Shown) -> (bool, Vec) { Shown::Hidden | Shown::Undrawn => {} Shown::Click => _ = fixture::host_button(ui, canvas, rect), Shown::Drag => _ = fixture::host_drag_area(ui, canvas, rect), + Shown::Window => areas::host_egui_window(ui.ctx(), named_id("host window"), |ui| _ = widget(ui, canvas)), Shown::Unfocusable => fixture::host_unfocusable_area(ui, canvas, rect), Shown::Disabled => fixture::host_disabled_button(ui, canvas, rect), } @@ -1225,7 +1263,7 @@ fn host_canvas_findings(shown: Shown) -> (bool, Vec) { /// focusable egui widget of the pass has. #[trial] fn a_host_canvas_no_focusable_widget_draws_is_a_finding() { - for shown in [Shown::Click, Shown::Drag] { + for shown in [Shown::Click, Shown::Drag, Shown::Window] { assert_eq!(host_canvas_findings(shown), (true, Vec::new()), "{shown:?}: Tab stays at a canvas with a focusable widget"); } assert_eq!(host_canvas_findings(Shown::Hidden).1, Vec::::new(), "a hidden canvas makes no call");