Skip to main content

egui_pop_core/
focus.rs

1//! Focus scopes and the focus chain (ADR 0007).
2//!
3//! A [`scope`] is a named region of the interface (a panel, a dialog, a
4//! list) that sets context keys while the focus is inside it. Scopes nest
5//! the way they are drawn; each pass records them, and the **focus
6//! chain** is the scopes containing the focused widget (or, when nothing
7//! has the keyboard focus, the place last clicked), outermost first. The
8//! [`when_context`] built from it gives each scope's keys the scope's
9//! depth, so key resolution prefers the binding nearest the focus.
10//!
11//! In hover mode ([`focus_mode`](crate::focus_mode)), the place the
12//! pointer moved to stands for the place last clicked, and a widget
13//! focused in another scope lets go of the focus.
14//!
15//! The chain is computed from the previous pass's scopes (egui decides
16//! focus between passes), so it is ready before this pass's widgets read
17//! the keyboard. Each window has its own scopes and chain (egui keeps a
18//! focus per window): in a detached panel's window, [`when_context`]
19//! says what has the keyboard there.
20//!
21//! A focused widget belongs to the scopes it was drawn in, wherever it lies:
22//! a row scrolled out of its panel is still that panel's. The place a pointer
23//! pressed has no widget to ask, so it goes by the scopes' rectangles.
24//!
25//! [`take_moved`] says when the focus went somewhere else, once per change,
26//! for what keeps a notion of its own of where the user is (the workbench's
27//! focused panel); [`prefer`] names the widget a scope's focus should land on
28//! when something hands the scope the keyboard.
29//!
30//! A [`region`] is a scope F6 goes to, see [`regions`](crate::regions).
31//!
32//! # A focus you can see, from the keyboard only
33//!
34//! egui-pop rings the focus by the web's `:focus-visible` rule: each window
35//! keeps one flag, turned on by a navigation key (Tab and Shift+Tab, the
36//! arrows, Home, End, Page Up, Page Down) or a focus moved without the
37//! pointer (F6, a shortcut, a screen reader), and off by any press of the
38//! pointer. Every focus ring egui-pop draws (the plugin's, and the focus look
39//! of its widgets, views, grids, panels and the kit's `focus` state) shows
40//! only while it is on ([`ring_shown`], [`shows_ring`]); text inputs show
41//! their focus however it came. Where the keyboard goes, and the focus
42//! AccessKit reports, never change with it.
43//!
44//! # Escape, in order
45//!
46//! With the focus plugin [`install`]ed, one press of Escape goes to the
47//! first of these that takes it:
48//!
49//! 1. a focused **text input** lets go of the focus, which stays in the
50//!    input's surface (its scope still heads the focus chain); nothing
51//!    else sees that press (unless the input lets Escape through, see
52//!    [`escape_passes`]); an input that cancels on Escape (a slider's
53//!    typed entry) learns of that press through [`escape_left`];
54//! 2. a **gesture** in progress: egui aborts a drag, and the press is
55//!    the drag's alone (a slider's, a knob's, a scrub's, a viewport's):
56//!    the plugin takes it out of the input, so no host around the
57//!    gesture (a dialog, the Settings window, a popover) dismisses on
58//!    it; the widget puts its value back, reading the press through
59//!    [`escape_cancelled`] or [`cancel_pressed`], and a value store
60//!    gesture is rolled back ([`binding`](crate::binding)). Only the
61//!    next Escape reaches the host;
62//! 3. the **top overlay** closes, if it closes on Escape (popovers,
63//!    menus, dialogs: "Escape dismisses"), see `overlay::begin_pass`;
64//! 4. the **key bindings** of Escape, the innermost focused surface's
65//!    first, then the outer surfaces', then the global ones (ADR 0007);
66//! 5. what is left reaches egui's widgets.
67//!
68//! So in a text field of a panel, the first Escape leaves the field and
69//! the second reaches the panel's own Escape (cancelling a gesture,
70//! closing the panel's overlay).
71//!
72//! While a text input owns the keyboard ([`text_input_owns_keyboard`]:
73//! a text field has the focus, or an open input claimed it with
74//! [`claim_keyboard`]), the key dispatcher leaves Escape and Enter to it.
75//!
76//! ```
77//! use egui_pop_core::focus;
78//!
79//! fn panel(ui: &mut egui::Ui) {
80//!     focus::scope(ui, "list", &[("listMode", "grid")], |ui| {
81//!         let _ = ui.button("Item");
82//!     });
83//! }
84//! ```
85
86use std::collections::HashMap;
87use std::ops::Range;
88
89use egui::{Context, Id, LayerId, Pos2, Rect, Ui};
90use egui_pop_model::when::WhenContext;
91use serde::Serialize;
92
93use crate::state::{lock, pass, shared, shared_in_window, shared_of_window};
94
95/// One scope as drawn in a pass.
96#[derive(Clone, Debug, PartialEq, Serialize)]
97pub struct ScopeRecord {
98    pub name: String,
99    pub keys: Vec<(String, String)>,
100    /// The enclosing scope, by index in the pass.
101    pub parent: Option<usize>,
102    /// 1 for a top-level scope.
103    pub depth: u32,
104    #[serde(skip)]
105    pub layer: LayerId,
106    #[serde(skip)]
107    pub rect: Rect,
108    /// A [`region`]: its place in F6's order, lowest first.
109    #[serde(skip_serializing_if = "Option::is_none")]
110    pub region: Option<u32>,
111}
112
113#[derive(Debug, Default)]
114struct State {
115    pass: u64,
116    /// This pass's scopes.
117    building: Vec<ScopeRecord>,
118    open: Vec<usize>,
119    /// The previous pass's scopes, the chain computed from them.
120    last: Vec<ScopeRecord>,
121    chain: Vec<usize>,
122    /// Where the pointer last pressed, on which layer (or where the
123    /// focused widget was when Escape took its focus away).
124    pressed: Option<(LayerId, Pos2)>,
125    /// The focus plugin is installed.
126    installed: bool,
127    /// Text inputs that let Escape through, this pass and the previous.
128    passing: Vec<Id>,
129    passing_last: Vec<Id>,
130    /// Text inputs that claimed the keyboard, with the pass of their
131    /// last claim ([`claim_keyboard`]).
132    claims: Vec<(Id, u64)>,
133    /// The text input Escape took the focus from, and in which pass.
134    escaped: Option<(Id, u64)>,
135    /// The widget whose drag Escape cancelled, and in which pass.
136    gesture_escaped: Option<(Id, u64)>,
137    /// `building` and `last`'s other half.
138    drawn: Vec<Drawn>,
139    drawn_last: Vec<Drawn>,
140    /// The widget holding the focus when last looked at.
141    seen: Option<Id>,
142    /// Whether the window had the system's focus when last looked at.
143    window: Option<bool>,
144    /// What changed at the start of this pass, until asked.
145    moved: Option<Moved>,
146    /// The widget this window's last pass left with the focus, and where it
147    /// was, for the input hook ([`remember_holder`]).
148    holder: Option<(Id, (LayerId, Pos2))>,
149    /// The text input Escape is taking the focus from, once this window's
150    /// pass has begun.
151    leaving: Option<Id>,
152    /// The widget focused last in each region, by name.
153    remembered: HashMap<String, Id>,
154    /// The widgets that said this pass that they read navigation keys.
155    taking: Vec<Id>,
156    /// The keys each widget said it reads itself while focused
157    /// ([`reads_keys`]), this pass and the previous.
158    reading: Vec<(Id, Vec<egui::Key>)>,
159    reading_last: Vec<(Id, Vec<egui::Key>)>,
160}
161
162/// What a scope is besides its record, by the same index: not part of
163/// [`ScopeRecord`], which the debug bridge shows.
164#[derive(Clone, Debug, Default)]
165struct Drawn {
166    /// The widgets drawn inside it, as their order in its layer.
167    widgets: Range<usize>,
168    /// The widget it wants to hand the focus to ([`prefer`]).
169    preferred: Option<Id>,
170    /// A [`Region::holding`]: its content can hold the focus itself.
171    holding: bool,
172}
173
174/// How the place the user works in changed, from [`take_moved`].
175#[derive(Clone, Debug, PartialEq)]
176pub enum Moved {
177    /// The pointer pressed there (or, in hover mode, moved there): the
178    /// scopes at that place, outermost first.
179    Pressed(Vec<ScopeRecord>),
180    /// A widget took the focus, or the window holding it got the system's
181    /// focus back: the focus chain.
182    Focused(Vec<ScopeRecord>),
183    /// The widget holding the focus let it go and nothing took it.
184    Left,
185}
186
187/// The focus state of the window being drawn: each window (a detached
188/// panel's included) has its own scopes and chain, as egui keeps a
189/// focus per window.
190fn state(ctx: &Context) -> std::sync::Arc<std::sync::Mutex<State>> {
191    shared_in_window::<State>(ctx, "core.focus")
192}
193
194/// A widget's response from this pass (else the last), read without
195/// touching the focus.
196///
197/// `Context::read_response` runs egui's "clicked elsewhere" rule: on a
198/// click that did not land on the widget, a focused widget loses the
199/// focus. Called every pass for the focused widget (to find its layer,
200/// its place), it drops the focus a widget took when a click landed on
201/// one of its children (a tree focused through its clicked row). This
202/// reads the response with that rule off.
203///
204/// upstream: egui has no side-effect free way to read a widget's
205/// response or layer (see docs/upstream.md).
206pub fn peek_response(ctx: &Context, id: Id) -> Option<egui::Response> {
207    use egui::SurrenderFocusOn;
208    let was = ctx.options_mut(|o| {
209        std::mem::replace(
210            &mut o.input_options.surrender_focus_on,
211            SurrenderFocusOn::Never,
212        )
213    });
214    let r = ctx.read_response(id);
215    ctx.options_mut(|o| o.input_options.surrender_focus_on = was);
216    r
217}
218
219/// The deepest scope drawn around a widget of the last pass: the one whose
220/// widgets include it. Its place would not do: a row scrolled out of its
221/// panel lies over the next panel, or nowhere.
222fn holding(ctx: &Context, s: &State, id: Id) -> Option<Option<usize>> {
223    let (layer, order) = ctx.viewport(|v| v.prev_pass.widgets.order(id))?;
224    let at = s
225        .last
226        .iter()
227        .zip(&s.drawn_last)
228        .enumerate()
229        .filter(|(_, (r, d))| r.layer == layer && d.widgets.contains(&order))
230        .max_by_key(|(i, (r, _))| (r.depth, *i))
231        .map(|(i, _)| i);
232    Some(at)
233}
234
235/// The deepest scope the focus chain is pointed at.
236fn target(ctx: &Context, s: &State) -> Option<usize> {
237    if let Some(id) = ctx.memory(|m| m.focused()) {
238        if let Some(at) = holding(ctx, s, id) {
239            return at;
240        }
241        if let Some(r) = peek_response(ctx, id) {
242            return deepest(&s.last, r.layer_id, r.interact_rect.center());
243        }
244    }
245    let (layer, pos) = s.pressed?;
246    deepest(&s.last, layer, pos)
247}
248
249/// A scope and those around it, outermost first.
250fn outward(scopes: &[ScopeRecord], mut at: Option<usize>) -> Vec<usize> {
251    let mut chain = Vec::new();
252    while let Some(i) = at {
253        chain.push(i);
254        at = scopes[i].parent;
255    }
256    chain.reverse();
257    chain
258}
259
260/// The deepest scope drawn at a place.
261fn deepest(scopes: &[ScopeRecord], layer: LayerId, pos: Pos2) -> Option<usize> {
262    scopes
263        .iter()
264        .enumerate()
265        .filter(|(_, r)| r.layer == layer && r.rect.contains(pos))
266        .max_by_key(|(i, r)| (r.depth, *i))
267        .map(|(i, _)| i)
268}
269
270/// In hover mode (`focus_mode`), the surface under the moving pointer
271/// gets the keys: the chain points there, and a widget holding the
272/// focus in another surface lets go of it.
273///
274/// The place it moved to, if it did.
275fn follow_pointer(ctx: &Context, s: &mut State) -> Option<(LayerId, Pos2)> {
276    if !crate::focus_mode::pointer_may_focus(ctx) {
277        return None;
278    }
279    let pos = ctx.input(|i| i.pointer.hover_pos())?;
280    let layer = ctx.layer_id_at(pos)?;
281    let under = deepest(&s.last, layer, pos)?;
282    if let Some(id) = ctx.memory(|m| m.focused())
283        && let Some(r) = peek_response(ctx, id)
284        && deepest(&s.last, r.layer_id, r.interact_rect.center()) != Some(under)
285    {
286        ctx.memory_mut(|m| m.surrender_focus(id));
287    }
288    s.pressed = Some((layer, pos));
289    Some((layer, pos))
290}
291
292fn rotate(ctx: &Context, s: &mut State) {
293    let now = pass(ctx);
294    if s.pass == now {
295        return;
296    }
297    s.pass = now;
298    let mut press = None;
299    s.last = std::mem::take(&mut s.building);
300    s.drawn_last = std::mem::take(&mut s.drawn);
301    s.passing_last = std::mem::take(&mut s.passing);
302    s.taking.clear();
303    s.reading_last = std::mem::take(&mut s.reading);
304    s.open.clear();
305    if let Some(pos) = ctx.input(|i| {
306        i.pointer
307            .any_pressed()
308            .then(|| i.pointer.interact_pos())
309            .flatten()
310    }) && let Some(layer) = ctx.layer_id_at(pos)
311    {
312        s.pressed = Some((layer, pos));
313        press = Some((layer, pos));
314    }
315    press = follow_pointer(ctx, s).or(press);
316    s.chain = outward(&s.last, target(ctx, s));
317    s.moved = what_moved(ctx, s, press);
318    remember_in_region(ctx, s);
319}
320
321/// Notes the focused widget for the region around it.
322fn remember_in_region(ctx: &Context, s: &mut State) {
323    let Some(id) = ctx.memory(|m| m.focused()) else {
324        return;
325    };
326    if let Some(&at) = s.chain.iter().rev().find(|&&i| s.last[i].region.is_some()) {
327        let name = s.last[at].name.clone();
328        s.remembered.insert(name, id);
329    }
330}
331
332/// What changed since the last pass, given where the pointer pressed in this
333/// one. A press says where it landed even when the focus stays elsewhere
334/// until it is released.
335fn what_moved(ctx: &Context, s: &mut State, press: Option<(LayerId, Pos2)>) -> Option<Moved> {
336    let focused = ctx.memory(|m| m.focused());
337    let window = ctx.input(|i| i.viewport().focused);
338    let widget_changed = std::mem::replace(&mut s.seen, focused) != focused;
339    let came_back = std::mem::replace(&mut s.window, window) == Some(false) && window == Some(true);
340    let records = |s: &State, chain: &[usize]| -> Vec<ScopeRecord> {
341        chain.iter().map(|&i| s.last[i].clone()).collect()
342    };
343    if let Some((layer, pos)) = press {
344        let at = outward(&s.last, deepest(&s.last, layer, pos));
345        return Some(Moved::Pressed(records(s, &at)));
346    }
347    if widget_changed {
348        return Some(match focused {
349            Some(_) => Moved::Focused(records(s, &s.chain)),
350            None => Moved::Left,
351        });
352    }
353    came_back.then(|| Moved::Focused(records(s, &s.chain)))
354}
355
356/// Draws `add` inside a named scope that sets `keys` (and `<name>Focus`)
357/// while the focus is in it.
358pub fn scope<R>(
359    ui: &mut Ui,
360    name: &str,
361    keys: &[(&str, &str)],
362    add: impl FnOnce(&mut Ui) -> R,
363) -> R {
364    open_scope(ui, name, keys, None, add)
365}
366
367/// What makes a scope a region of the window, for [`region`].
368#[derive(Clone, Debug, PartialEq, Eq)]
369pub struct Region {
370    name: String,
371    rank: u32,
372    holding: bool,
373}
374
375impl Region {
376    /// A region named `name`, in F6's order by `rank`, lowest first. Regions
377    /// of one rank go in the order they were drawn.
378    pub fn new(name: impl Into<String>, rank: u32) -> Self {
379        Self {
380            name: name.into(),
381            rank,
382            holding: false,
383        }
384    }
385
386    /// Its content can hold the focus itself when no scope inside it has a
387    /// focusable widget (a panel of text alone): F6 then says so
388    /// ([`Hop::target`](crate::regions::Hop::target)) rather than land on a
389    /// widget around that content (a dock's tab).
390    pub fn holding(mut self, holding: bool) -> Self {
391        self.holding = holding;
392        self
393    }
394}
395
396/// A [`scope`] that F6 goes to: a part of the window (an area, a palette, the
397/// status bar), see [`regions`](crate::regions). Don't draw one inside another.
398pub fn region<R>(ui: &mut Ui, region: &Region, add: impl FnOnce(&mut Ui) -> R) -> R {
399    open_scope(ui, &region.name, &[], Some(region), add)
400}
401
402fn open_scope<R>(
403    ui: &mut Ui,
404    name: &str,
405    keys: &[(&str, &str)],
406    region: Option<&Region>,
407    add: impl FnOnce(&mut Ui) -> R,
408) -> R {
409    let st = state(ui.ctx());
410    let index = {
411        let mut s = lock(&st);
412        rotate(ui.ctx(), &mut s);
413        let parent = s.open.last().copied();
414        let depth = parent.map_or(1, |p| s.building[p].depth + 1);
415        let mut all: Vec<(String, String)> = vec![(format!("{name}Focus"), "true".into())];
416        all.extend(keys.iter().map(|(k, v)| (k.to_string(), v.to_string())));
417        s.building.push(ScopeRecord {
418            name: name.into(),
419            keys: all,
420            parent,
421            depth,
422            layer: ui.layer_id(),
423            rect: Rect::NOTHING,
424            region: region.map(|r| r.rank),
425        });
426        let first = widgets_in(ui);
427        s.drawn.push(Drawn {
428            widgets: first..first,
429            preferred: None,
430            holding: region.is_some_and(|r| r.holding),
431        });
432        let i = s.building.len() - 1;
433        s.open.push(i);
434        i
435    };
436    // The region the scope may use (a panel's whole area), as visible.
437    let (inner, rect) = ui
438        .scope(|ui| {
439            let inner = add(ui);
440            let rect = ui.max_rect().union(ui.min_rect()).intersect(ui.clip_rect());
441            (inner, rect)
442        })
443        .inner;
444    let mut s = lock(&st);
445    if let Some(r) = s.building.get_mut(index) {
446        r.rect = rect;
447    }
448    let end = widgets_in(ui);
449    if let Some(d) = s.drawn.get_mut(index) {
450        d.widgets.end = end;
451    }
452    s.open.pop();
453    inner
454}
455
456/// A region as the last pass drew it, for [`regions`](crate::regions).
457#[derive(Clone, Debug)]
458pub(crate) struct DrawnRegion {
459    pub name: String,
460    pub holding: bool,
461    pub layer: LayerId,
462    /// Its widgets, as their order in its layer.
463    pub widgets: Range<usize>,
464    /// Those of the scopes inside it.
465    pub inner: Vec<Range<usize>>,
466    pub preferred: Option<Id>,
467    pub remembered: Option<Id>,
468}
469
470/// The regions the last pass drew, in F6's order, and which one the focus chain
471/// is in, as an index of them.
472pub(crate) fn drawn_regions(ctx: &Context) -> (Vec<DrawnRegion>, Option<usize>) {
473    let st = state(ctx);
474    let mut s = lock(&st);
475    rotate(ctx, &mut s);
476    let mut at: Vec<(u32, usize)> = (s.last.iter().enumerate())
477        .filter_map(|(i, r)| Some((r.region?, i)))
478        .collect();
479    at.sort_by_key(|&(rank, _)| rank);
480    let here = s.chain.iter().rev().find(|&&i| s.last[i].region.is_some());
481    let current = here.and_then(|h| at.iter().position(|&(_, i)| i == *h));
482    let regions = at.iter().map(|&(_, i)| {
483        let (r, d) = (&s.last[i], &s.drawn_last[i]);
484        let inner = (0..s.last.len())
485            .filter(|&j| j != i && outward(&s.last, Some(j)).contains(&i))
486            .map(|j| s.drawn_last[j].widgets.clone());
487        DrawnRegion {
488            name: r.name.clone(),
489            holding: d.holding,
490            layer: r.layer,
491            widgets: d.widgets.clone(),
492            inner: inner.collect(),
493            preferred: d.preferred,
494            remembered: s.remembered.get(&r.name).copied(),
495        }
496    });
497    (regions.collect(), current)
498}
499
500/// Whether the window's last pass drew a region. Reads without starting this
501/// pass's scopes: a plugin asks before the focus has settled.
502pub(crate) fn has_regions(ctx: &Context) -> bool {
503    let st = state(ctx);
504    let s = lock(&st);
505    let scopes = if s.pass == pass(ctx) {
506        &s.last
507    } else {
508        &s.building
509    };
510    scopes.iter().any(|r| r.region.is_some())
511}
512
513/// The names of the scopes this pass drew around a widget, innermost first.
514/// Called at the end of the pass; empty if no scope was drawn in it.
515pub(crate) fn scopes_holding(ctx: &Context, id: Id) -> Vec<String> {
516    let st = state(ctx);
517    let s = lock(&st);
518    if s.pass != pass(ctx) {
519        return Vec::new();
520    }
521    let Some((layer, order)) = ctx.viewport(|v| v.this_pass.widgets.order(id)) else {
522        return Vec::new();
523    };
524    let at = s
525        .building
526        .iter()
527        .zip(&s.drawn)
528        .enumerate()
529        .filter(|(_, (r, d))| r.layer == layer && d.widgets.contains(&order))
530        .max_by_key(|(i, (r, _))| (r.depth, *i))
531        .map(|(i, _)| i);
532    let mut names: Vec<String> = outward(&s.building, at)
533        .into_iter()
534        .map(|i| s.building[i].name.clone())
535        .collect();
536    names.reverse();
537    names
538}
539
540/// The widgets this pass drew in each of these scopes, in the same order, as
541/// their order in the layer. A scope not drawn in this layer is left out.
542pub(crate) fn spans_of(ctx: &Context, layer: LayerId, names: &[String]) -> Vec<Range<usize>> {
543    let st = state(ctx);
544    let s = lock(&st);
545    if s.pass != pass(ctx) {
546        return Vec::new();
547    }
548    names
549        .iter()
550        .filter_map(|name| {
551            let at = s
552                .building
553                .iter()
554                .position(|r| r.layer == layer && r.name == *name)?;
555            Some(s.drawn.get(at)?.widgets.clone())
556        })
557        .collect()
558}
559
560/// How many widgets this pass drew so far in `ui`'s layer.
561fn widgets_in(ui: &Ui) -> usize {
562    let layer = ui.layer_id();
563    ui.ctx()
564        .viewport(|v| v.this_pass.widgets.get_layer(layer).count())
565}
566
567/// Names the widget the scopes open around it hand the focus to when asked
568/// (call it each pass, in the scope, where it is drawn): the canvas under a
569/// panel's toolbar, the search field a "go to the search" command lands in.
570/// Without one, a panel given the keyboard holds it itself, and Tab enters
571/// its widgets. The first widget to ask in a scope wins.
572pub fn prefer(ctx: &Context, id: Id) {
573    let st = state(ctx);
574    let mut s = lock(&st);
575    rotate(ctx, &mut s);
576    let open = s.open.clone();
577    for i in open {
578        if let Some(d) = s.drawn.get_mut(i) {
579            d.preferred.get_or_insert(id);
580        }
581    }
582}
583
584/// The widget named by [`prefer`] so far in the scope being drawn.
585pub fn preferred(ctx: &Context) -> Option<Id> {
586    let st = state(ctx);
587    let s = lock(&st);
588    let at = *s.open.last()?;
589    s.drawn.get(at)?.preferred
590}
591
592/// What moved since the last time this was asked, at most once per change
593/// and per window: where the pointer pressed, where a widget took the focus,
594/// or that the focus went nowhere. Read before the pass's drawing, it says
595/// what the end of the previous pass settled.
596pub fn take_moved(ctx: &Context) -> Option<Moved> {
597    let st = state(ctx);
598    let mut s = lock(&st);
599    rotate(ctx, &mut s);
600    s.moved.take()
601}
602
603/// Installs the focus plugin on a context (once; later calls do
604/// nothing): Escape leaves a text input before anything else sees it,
605/// see [the order](self#escape-in-order), the keys typed with an AccessKit
606/// `Focus` action reach the field it focuses, a widget the keyboard
607/// focuses comes into view in the scroll areas around it, nested ones
608/// included (the pointer's focus leaves them where they are), and the focus
609/// keeps its place: Tab after Escape or after the focused widget went away
610/// goes on from there, and a widget removed hands the focus to its neighbour.
611pub fn install(ctx: &Context) {
612    // Once per context, whichever window asks.
613    let st = shared::<State>(ctx, "core.focus");
614    let mut s = lock(&st);
615    if !s.installed {
616        s.installed = true;
617        drop(s);
618        ctx.add_plugin(FocusPlugin);
619    }
620}
621
622/// Makes the popover being drawn keep Tab: past its last stop Tab comes back to
623/// its first, Shift+Tab the other way, and Tab from outside it goes in, so that
624/// nothing walks the window behind it while it stays open. With no stop in it,
625/// it closes as Tab goes on. A focused widget taking Tab itself keeps it.
626///
627/// Call it at the end of the popover's content, each pass, with the focus plugin
628/// installed ([`install`]; otherwise it does nothing, and Tab goes on as egui has
629/// it). An overlay of [`Kind::Popover`](crate::overlay::Kind::Popover) does so by
630/// itself while it is the top one; this is for an [`egui::Popup`] used as a
631/// popover. A menu has its own keys, and a flyout (`overlay::hold`) stays open as
632/// the focus leaves it.
633pub fn keep_tab(ui: &mut Ui) {
634    let installed = lock(&shared::<State>(ui.ctx(), "core.focus")).installed;
635    if installed {
636        crate::place::keep_tab(ui);
637    }
638}
639
640/// Says that a widget shows its own focus (call it each pass it is drawn), so
641/// that the focus plugin paints no ring around it. A widget painting a kit
642/// state from [`State::from_response`](crate::kit::State::from_response) has
643/// it said for it.
644///
645/// With the focus plugin [`install`]ed, a widget the keyboard focused gets a
646/// ring of the `focus.ring` token at the end of the pass, unless it says this;
647/// a click focuses without one ([`ring_shown`]).
648pub fn own_ring(ctx: &Context, id: Id) {
649    crate::ring::own(ctx, id);
650}
651
652/// Whether the focus is visible (the web's `:focus-visible`): a navigation
653/// key (Tab, Shift+Tab, an arrow, Home, End, Page Up, Page Down) was pressed,
654/// or the focus moved without the pointer (F6, a command, a screen reader),
655/// since the last press of the pointer. The focus plugin then rings the
656/// focused widget, and a widget drawing its own focus ring draws it only while
657/// this holds ([`shows_ring`]). One flag per window.
658///
659/// Only the ring's visibility follows it: where the keyboard goes, and the
660/// focus AccessKit reports, do not change. Without the focus plugin
661/// [`install`]ed this is always true, as before the rule.
662pub fn ring_shown(ctx: &Context) -> bool {
663    let installed = lock(&shared::<State>(ctx, "core.focus")).installed;
664    !installed || crate::ring::visible(ctx)
665}
666
667/// Whether a widget draws its focus ring now: it has the focus, and the focus
668/// is visible ([`ring_shown`]). A widget showing its own focus still calls
669/// [`own_ring`] whenever it has the focus, ring drawn or not.
670pub fn shows_ring(r: &egui::Response) -> bool {
671    r.has_focus() && ring_shown(&r.ctx)
672}
673
674/// Says that a widget reads Page Up, Page Down, Home or End while focused (call
675/// it each pass it is drawn, before the scroll area around it ends), so that the
676/// area leaves them to it. A widget sensing drags needs none of this, nor does a
677/// text input: a list, a grid or a row of stars does.
678///
679/// A view whose focusable widget lies around its own scroll area rather than in
680/// it (a list, a grid) calls it inside the area's content: the area then knows
681/// that the view is the Tab stop, and does not become one itself.
682///
683/// upstream: egui's widgets read keys without taking them from the input, so a
684/// scroll area cannot see what a widget inside it has read (docs/upstream.md,
685/// "egui: a scroll area reads no key").
686pub fn takes_keys(ctx: &Context, id: Id) {
687    let st = state(ctx);
688    let mut s = lock(&st);
689    rotate(ctx, &mut s);
690    s.taking.push(id);
691}
692
693/// Whether a widget said this pass that it reads navigation keys, see
694/// [`takes_keys`].
695pub(crate) fn keys_taken_by(ctx: &Context, id: Id) -> bool {
696    let st = state(ctx);
697    let mut s = lock(&st);
698    rotate(ctx, &mut s);
699    s.taking.contains(&id)
700}
701
702/// How many times [`takes_keys`] was called so far this pass: a scroll area
703/// compares it before and after its content, to learn whether a view inside reads
704/// the keys itself.
705pub(crate) fn keys_taken_count(ctx: &Context) -> usize {
706    let st = state(ctx);
707    let mut s = lock(&st);
708    rotate(ctx, &mut s);
709    s.taking.len()
710}
711
712/// Says that a widget reads these keys itself while it has the focus (call
713/// it each pass it is drawn): pressed without Ctrl or Alt while it is
714/// focused, they reach it before a global key binding of theirs, as a text
715/// field keeps the keys it types. A list or a grid says so of its arrows,
716/// Home, End, Page Up and Page Down, Space and Enter.
717///
718/// The key dispatcher runs before the widgets are drawn, so it reads what
719/// the focused widget said in this pass or the last
720/// ([`keys_read_by_focus`]). A binding scoped to the widget's surface, its
721/// panel or its window was declared for that place and still goes first; a
722/// binding that fires `always` (`Typing::Always`) does too.
723pub fn reads_keys(ctx: &Context, id: Id, keys: &[egui::Key]) {
724    let st = state(ctx);
725    let mut s = lock(&st);
726    rotate(ctx, &mut s);
727    match s.reading.iter_mut().find(|(w, _)| *w == id) {
728        Some((_, k)) => k.extend_from_slice(keys),
729        None => s.reading.push((id, keys.to_vec())),
730    }
731}
732
733/// The keys the widget holding the focus in this window said it reads
734/// itself ([`reads_keys`]), this pass or the last; none when nothing has
735/// the focus.
736pub fn keys_read_by_focus(ctx: &Context) -> Vec<egui::Key> {
737    let Some(focused) = ctx.memory(|m| m.focused()) else {
738        return Vec::new();
739    };
740    let st = state(ctx);
741    let mut s = lock(&st);
742    rotate(ctx, &mut s);
743    let mut keys: Vec<egui::Key> = s
744        .reading
745        .iter()
746        .chain(&s.reading_last)
747        .filter(|(w, _)| *w == focused)
748        .flat_map(|(_, k)| k.iter().copied())
749        .collect();
750    keys.sort_by_key(|k| k.name());
751    keys.dedup();
752    keys
753}
754
755/// Lets Escape through a text input (call it each pass it is drawn):
756/// Escape then goes on to the overlay around it, as for a search field
757/// that is the whole of a popup (the command palette), instead of
758/// leaving the field first.
759pub fn escape_passes(ctx: &Context, id: Id) {
760    let st = state(ctx);
761    let mut s = lock(&st);
762    rotate(ctx, &mut s);
763    s.passing.push(id);
764}
765
766/// Claims the keyboard for an open text input (call it each pass it
767/// stays open): while it is claimed, [`text_input_owns_keyboard`] is
768/// true, so key dispatchers leave Escape and Enter to the input. The
769/// claim holds for the pass it is made in and the next one, since a
770/// dispatcher runs before the input is drawn. A slider's typed entry
771/// claims it: Escape cancels the entry, Enter commits it, and neither
772/// runs a key binding.
773pub fn claim_keyboard(ctx: &Context, id: Id) {
774    let now = pass(ctx);
775    let st = state(ctx);
776    let mut s = lock(&st);
777    s.claims.retain(|(c, p)| *c != id && p + 1 >= now);
778    s.claims.push((id, now));
779}
780
781/// Whether a text input owns the keyboard: a text field has the focus,
782/// or an open input claimed it ([`claim_keyboard`]) this pass or the
783/// last. egui-pop's key dispatcher then leaves Escape and Enter (without
784/// Ctrl or Alt) to the input; a host with a dispatcher of its own, or
785/// one that reads Escape before the widgets are drawn, should ask this
786/// first and do the same.
787///
788/// The claim matters for Escape: egui lets go of the focus when Escape
789/// is pressed, before the pass is drawn, so on that pass no text field
790/// has the focus any more.
791pub fn text_input_owns_keyboard(ctx: &Context) -> bool {
792    if ctx.text_edit_focused() {
793        return true;
794    }
795    let now = pass(ctx);
796    let st = state(ctx);
797    let s = lock(&st);
798    s.claims.iter().any(|(_, p)| p + 1 >= now)
799}
800
801/// Whether Escape just took the focus from this text input (the focus
802/// plugin swallows that press, see [the order](self#escape-in-order)):
803/// an input that cancels on Escape reads it here, since the key itself
804/// is gone. Answered once: the press is spent by the first call that
805/// sees it.
806pub fn escape_left(ctx: &Context, id: Id) -> bool {
807    let now = pass(ctx);
808    let st = state(ctx);
809    let mut s = lock(&st);
810    match s.escaped {
811        Some((e, p)) if e == id && p + 1 >= now => {
812            s.escaped = None;
813            true
814        }
815        _ => false,
816    }
817}
818
819/// Runs before egui reads each pass's input.
820#[derive(Debug)]
821struct FocusPlugin;
822
823impl egui::plugin::Plugin for FocusPlugin {
824    fn debug_name(&self) -> &'static str {
825        "egui_pop_core::focus"
826    }
827
828    fn input_hook(&mut self, ctx: &Context, input: &mut egui::RawInput) {
829        hold_after_accesskit_focus(ctx, input);
830        escape(ctx, input);
831    }
832
833    fn on_begin_pass(&mut self, ui: &mut Ui) {
834        leave_text_input(ui.ctx());
835        escape_gesture(ui.ctx());
836        crate::stay::begin_pass(ui.ctx());
837        crate::ring::begin_pass(ui.ctx());
838        crate::reveal::begin_pass(ui.ctx());
839        crate::place::begin_pass(ui.ctx());
840        crate::roving::begin_pass(ui.ctx());
841    }
842
843    fn on_end_pass(&mut self, ui: &mut Ui) {
844        crate::place::end_pass(ui.ctx());
845        crate::ring::end_pass(ui.ctx());
846        remember_holder(ui.ctx());
847        crate::a11y::name_window(ui.ctx());
848    }
849}
850
851/// Events held back for each window's next pass, see
852/// [`hold_after_accesskit_focus`].
853#[derive(Debug, Default)]
854struct Held(Vec<(egui::ViewportId, Vec<egui::Event>)>);
855
856/// An AccessKit `Focus` action (a screen reader, an agent) gives a text
857/// field the keyboard from the next pass only: the keys typed with it
858/// would be lost. The keyboard input that comes after the action in the
859/// same pass is held back for the next one, in order, where the field
860/// has the focus.
861///
862/// upstream: egui hands the focus over while the field is drawn, after
863/// the field has read its input (docs/upstream.md, "egui: input in the
864/// pass of an AccessKit focus is lost").
865fn hold_after_accesskit_focus(ctx: &Context, input: &mut egui::RawInput) {
866    let window = input.viewport_id;
867    let st = shared::<Held>(ctx, "core.focus.held");
868    let mut held = lock(&st);
869    if let Some(i) = held.0.iter().position(|(w, _)| *w == window) {
870        let (_, mut events) = held.0.swap_remove(i);
871        events.append(&mut input.events);
872        input.events = events;
873    }
874    let Some(at) = input.events.iter().position(is_accesskit_focus) else {
875        return;
876    };
877    if !input.events[at + 1..].iter().any(is_keyboard_input) {
878        return;
879    }
880    let rest = input.events.split_off(at + 1);
881    held.0.push((window, rest));
882    drop(held);
883    ctx.request_repaint_of(window);
884}
885
886/// Whether an event asks, through AccessKit, to focus a widget.
887fn is_accesskit_focus(e: &egui::Event) -> bool {
888    matches!(
889        e,
890        egui::Event::AccessKitActionRequest(r) if r.action == egui::accesskit::Action::Focus
891    )
892}
893
894/// Whether an event is input a focused text field reads.
895fn is_keyboard_input(e: &egui::Event) -> bool {
896    matches!(
897        e,
898        egui::Event::Text(_)
899            | egui::Event::Key { .. }
900            | egui::Event::Paste(_)
901            | egui::Event::Copy
902            | egui::Event::Cut
903            | egui::Event::Ime(_)
904    )
905}
906
907/// Whether an event is a press of Escape without modifiers.
908fn is_escape(e: &egui::Event) -> bool {
909    matches!(
910        e,
911        egui::Event::Key {
912            key: egui::Key::Escape,
913            pressed: true,
914            modifiers,
915            ..
916        } if !modifiers.any()
917    )
918}
919
920/// Step 1 of the Escape order: a focused text input lets go of the
921/// focus and swallows the press. Whatever had the focus, its place is
922/// kept for the focus chain (egui drops the focus on Escape before this
923/// pass draws), so the surface around it still gets the keys.
924///
925/// upstream: the input hook runs before the window's pass has begun, so
926/// the memory, the context's viewport and the responses are still another
927/// window's: its own focus is out of reach. This reads what the window's
928/// last pass left and lets go of the focus when the pass has begun
929/// (docs/upstream.md, "egui: a plugin's input hook runs in another window").
930fn escape(ctx: &Context, input: &mut egui::RawInput) {
931    let Some(at) = input.events.iter().position(is_escape) else {
932        return;
933    };
934    let st = shared_of_window::<State>(ctx, "core.focus", input.viewport_id);
935    let mut s = lock(&st);
936    let Some((id, place)) = s.holder else {
937        return;
938    };
939    s.pressed = Some(place);
940    let passes = s.passing.contains(&id) || s.passing_last.contains(&id);
941    if egui::text_edit::TextEditState::load(ctx, id).is_some() && !passes {
942        input.events.remove(at);
943        s.leaving = Some(id);
944    }
945}
946
947/// Lets go of the focus [`escape`] took a press for, now that the memory is
948/// this window's.
949fn leave_text_input(ctx: &Context) {
950    let st = state(ctx);
951    let mut s = lock(&st);
952    let Some(id) = s.leaving.take() else {
953        return;
954    };
955    ctx.memory_mut(|m| m.surrender_focus(id));
956    s.escaped = Some((id, pass(ctx)));
957    log::debug!(target: "egui_pop", "Escape: left the text input {id:?}");
958}
959
960/// Step 2 of the Escape order: egui stopped a drag on this press (it
961/// aborts a drag on Escape as the pass begins), so the press is the
962/// gesture's. It is taken out of the pass's input, so that no host around
963/// the gesture (a dialog, the Settings window, a popover, a key binding)
964/// dismisses on it; the widget learns of it through [`escape_cancelled`].
965fn escape_gesture(ctx: &Context) {
966    let Some(id) = ctx.drag_stopped_id() else {
967        return;
968    };
969    if !ctx.input(|i| i.events.iter().any(is_escape)) {
970        return;
971    }
972    ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape));
973    lock(&state(ctx)).gesture_escaped = Some((id, pass(ctx)));
974    log::debug!(target: "egui_pop", "Escape: cancelled the drag of {id:?}");
975}
976
977/// The widget whose drag Escape cancelled in this pass, if any. With the
978/// focus plugin [`install`]ed, a press of Escape during a drag is the
979/// drag's, before any host's (see [the order](self#escape-in-order)): the
980/// plugin takes the press out of the input, so a gesture reads it here
981/// (or through [`cancel_pressed`]) and not from the keys. Asked as often
982/// as needed in the pass.
983pub fn escape_cancelled(ctx: &Context) -> Option<Id> {
984    let now = pass(ctx);
985    let st = state(ctx);
986    let s = lock(&st);
987    s.gesture_escaped
988        .filter(|(_, p)| *p == now)
989        .map(|(id, _)| id)
990}
991
992/// Whether a gesture's cancel key was pressed in this pass: the key
993/// itself, or, for Escape, the press the focus plugin took for the drag
994/// it cancelled ([`escape_cancelled`]). A drag that ends (`drag_stopped`)
995/// asks this to know whether it was cancelled.
996pub fn cancel_pressed(ctx: &Context, key: egui::Key) -> bool {
997    ctx.input(|i| i.key_pressed(key))
998        || (key == egui::Key::Escape && escape_cancelled(ctx).is_some())
999}
1000
1001/// Notes what the pass leaves with the focus, for the next pass's input hook.
1002/// A widget not drawn in this pass is not kept: egui drops its focus as the
1003/// pass ends.
1004fn remember_holder(ctx: &Context) {
1005    let holder = ctx
1006        .memory(|m| m.focused())
1007        .filter(|&id| ctx.viewport(|v| v.this_pass.widgets.contains(id)))
1008        .and_then(|id| {
1009            let r = peek_response(ctx, id)?;
1010            Some((id, (r.layer_id, r.interact_rect.center())))
1011        });
1012    lock(&state(ctx)).holder = holder;
1013}
1014
1015/// The scopes of the focus chain, outermost first.
1016pub fn chain(ctx: &Context) -> Vec<ScopeRecord> {
1017    let st = state(ctx);
1018    let mut s = lock(&st);
1019    rotate(ctx, &mut s);
1020    s.chain.iter().map(|&i| s.last[i].clone()).collect()
1021}
1022
1023/// The names in the focus chain, outermost first.
1024pub fn chain_names(ctx: &Context) -> Vec<String> {
1025    chain(ctx).into_iter().map(|r| r.name).collect()
1026}
1027
1028/// The context keys: `base` (depth 0), each scope of the chain at its
1029/// depth, then `textInputFocus` at the deepest depth when a text field
1030/// has the focus, and `widgetFocus` whenever a widget has it.
1031pub fn when_context(ctx: &Context, base: &WhenContext) -> WhenContext {
1032    let mut cx = base.clone();
1033    let chain = chain(ctx);
1034    let mut depth = 0;
1035    for r in &chain {
1036        depth = r.depth;
1037        for (k, v) in &r.keys {
1038            cx.set_at(k, v, r.depth);
1039        }
1040    }
1041    if ctx.text_edit_focused() {
1042        cx.flag_at("textInputFocus", true, depth + 1);
1043    }
1044    if ctx.memory(|m| m.focused()).is_some() {
1045        cx.flag_at("widgetFocus", true, depth + 1);
1046    }
1047    cx
1048}
1049
1050/// The focused widget, if any.
1051pub fn focused(ctx: &Context) -> Option<Id> {
1052    ctx.memory(|m| m.focused())
1053}
1054
1055/// The widget a window's last pass left with the focus, for a plugin's input
1056/// hook, which should ask this with [`RawInput::viewport_id`] and not the
1057/// memory: for most windows, the memory is still another window's there. To let
1058/// go of that focus, wait for the window's pass to begin (`on_begin_pass`).
1059///
1060/// It needs the focus plugin ([`install`]), which keeps it, and a host running
1061/// its passes through [`Context::run_ui`]: otherwise this answers `None`.
1062///
1063/// upstream: no public method reads a given window's focus (docs/upstream.md,
1064/// "egui: a plugin's input hook runs in another window").
1065///
1066/// [`RawInput::viewport_id`]: egui::RawInput::viewport_id
1067pub fn focused_in_window(ctx: &Context, window: egui::ViewportId) -> Option<Id> {
1068    let st = shared_of_window::<State>(ctx, "core.focus", window);
1069    lock(&st).holder.map(|(id, _)| id)
1070}
1071
1072/// The scopes recorded in the previous pass (for the debug bridge).
1073pub fn scopes(ctx: &Context) -> Vec<ScopeRecord> {
1074    let st = state(ctx);
1075    let mut s = lock(&st);
1076    rotate(ctx, &mut s);
1077    s.last.clone()
1078}