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. |