Merge pull request #3505 from aiongg/app-stop-focus

The app's own widgets: focus follows egui's rule, and a canvas that can't take focus is a finding
This commit is contained in:
aiongg
2026-11-25 10:16:44 -05:00
committed by GitHub
9 changed files with 417 additions and 24 deletions
@@ -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);
@@ -618,6 +618,18 @@ 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) {
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 {
+20 -2
View File
@@ -33,6 +33,13 @@ pub(crate) fn candidates_since(ctx: &Context, seen: usize) -> Vec<egui::FocusCan
ctx.memory(|memory| memory.focus_candidates().get(seen..).map(<[_]>::to_vec).unwrap_or_default())
}
/// 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<egui::WidgetRect> {
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`).
pub(crate) fn focused_keeps_tab(ctx: &Context) -> bool {
ctx.memory(|memory| memory.focus_lock_filter()).is_some_and(|filter| filter.tab)
@@ -44,8 +51,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 +62,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) {
@@ -795,6 +795,11 @@ pub(crate) fn dragged(ctx: &Context) -> Option<Id> {
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<Pos2> {
ctx.input(|input| if input.pointer.any_down() { input.pointer.press_origin() } else { None })
+70 -5
View File
@@ -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,11 @@ 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 settles it
/// (`settle_given`): the focus of an app's own widget is left to egui's rule there.
given: Option<Id>,
/// The canvases the running pass declared with `host_canvas`, which the end hook looks up among egui's widgets.
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<Id>,
/// 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 +236,10 @@ pub(crate) fn apply(ctx: &Context, acts: Vec<Act>) {
}
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),
}
}
@@ -236,16 +247,19 @@ pub(crate) fn apply(ctx: &Context, acts: Vec<Act>) {
/// 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);
let acts = if held && state.given == Some(stop.root) { vec![nav::focus_act(&stop)] } else { Vec::new() };
rec.stop = stop;
return Vec::new();
return acts;
}
state.push_stop(stop)
});
@@ -318,9 +332,18 @@ fn take_app_widgets(ctx: &Context, except: Option<Id>) {
/// 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 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 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));
}
register_stop(ctx, Stop::new(id, keys.with_chrome_key(true)).host());
}
@@ -1102,11 +1125,52 @@ 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, 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. 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.visible && !widget.enabled => "its widget is disabled, which takes no focus",
Some(_) => continue,
};
if cfg!(debug_assertions) {
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 });
}
}
}
/// 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) {
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())
@@ -1144,6 +1208,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);
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);
+19 -13
View File
@@ -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;
@@ -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.
@@ -264,24 +265,13 @@ impl State {
fn enter_stop(&mut self, rec: StopRec, origin: FocusOrigin) -> Vec<Act> {
self.note_entry(&rec);
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);
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
@@ -744,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<Id>, forward: bool) -> Option<usize> {
if entries.is_empty() {
return None;
+7 -2
View File
@@ -65,9 +65,14 @@ pub(crate) fn steps_of(ctx: &Context, id: Id) -> Vec<&'static str> {
pass_state::with::<Log, _>(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::<Log, _>(ctx, |log| {
@@ -86,7 +91,7 @@ pub(crate) fn findings(ctx: &Context) -> Vec<Finding> {
/// 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::<Log, _>(ctx, |log| {
@@ -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};
@@ -750,6 +751,187 @@ 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<Id>, Option<Id>),
/// Whether the widget lost focus by egui's word, in each pass from the press on.
lost: Vec<bool>,
/// egui's focus after Escape, the focus given again.
escape: Option<Id>,
/// egui's focus after a click elsewhere while the app's option is never to surrender it, the focus given again.
kept: Option<Id>,
}
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");
}
/// 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_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");
}
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);
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
/// own buttons, as it skips the framework's.
#[trial]
@@ -998,6 +1180,100 @@ 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 {
/// Neither declared nor drawn.
Hidden,
/// 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`.
Disabled,
/// 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<String>) {
let canvas = named_id("host canvas");
let mut show = move |ui: &mut Ui| {
if !matches!(shown, Shown::Hidden) {
host_canvas(ui.ctx(), canvas, KeyUse::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::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),
}
};
let mut frames = Frames::new();
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, 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::<String>::new(), "a hidden canvas makes no call");
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:?}");
}
}
/// 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<String>) {
+2 -2
View File
@@ -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 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, 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 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. |