Skip to main content

egui_pop_core/
tab.rs

1//! Tab order and focus scopes for the keyboard: Tab moves through a
2//! scope's stops in reading order, or as explicit indices and groups
3//! say ([`egui_pop_model::tab`]); F6 moves between panels.
4//!
5//! A [`scope`] is a region whose Tab order egui-pop decides: a panel
6//! ([`ScopeKind::Panel`]) or a modal ([`ScopeKind::Modal`]). Inside it,
7//! a widget joins the order as a **stop** ([`stop`]); egui-pop's inputs
8//! and sliders do so themselves, any other widget with
9//! `tab::stop(ui, &response, TabStop::new())`.
10//!
11//! - **Tab and Shift+Tab** from a stop go to the next or previous stop
12//!   of its scope: reading order by default (rows from top to bottom,
13//!   left to right), stops with an explicit [`TabStop::index`] first,
14//!   the stops of a [`TabStop::group`] together.
15//! - **Disabled fields are skipped** (they cannot take the focus);
16//!   read-only ones are not.
17//! - **In a modal**, Tab cycles: after the last stop comes the first,
18//!   and Shift+Tab goes round the other way. Every control of a modal
19//!   scope should then be a stop, or Tab never reaches it. (egui-pop's
20//!   modal overlays keep the focus inside them anyway: egui only lets
21//!   the widgets of the top modal layer take it.)
22//! - **In a panel**, Tab past the last stop leaves the order to egui,
23//!   which goes on in the order widgets were drawn (to the next panel).
24//! - **F6 and Shift+F6** move to the next or previous panel scope that
25//!   has stops, to the stop focused there last (or its first). F6 does
26//!   nothing while a modal scope or a modal overlay is open. In a window
27//!   with [`regions`](crate::regions) (an application's), F6 is theirs, and
28//!   the panel scopes of a region take that region's turn.
29//! - A [`roving`] group (a toolbar, a strip) is one stop: Tab leaves it and
30//!   comes back to the widget focused there last, the arrows go inside.
31//! - The focus on a widget that is not a stop is left to egui (its own
32//!   Tab order is the order widgets were drawn), and a focused widget
33//!   that takes the keys itself (a terminal) keeps Tab and F6.
34//!
35//! ```
36//! use egui_pop_core::tab::{self, ScopeKind, TabStop};
37//!
38//! fn form(ui: &mut egui::Ui, name: &mut String, city: &mut String) {
39//!     tab::scope(ui, "form", ScopeKind::Panel, |ui| {
40//!         let r = ui.text_edit_singleline(city);
41//!         tab::stop(ui, &r, TabStop::new().index(2));
42//!         let r = ui.text_edit_singleline(name);
43//!         tab::stop(ui, &r, TabStop::new().index(1));
44//!     });
45//! }
46//! ```
47
48use std::collections::HashMap;
49
50use egui::{Context, FocusDirection, Id, Key, LayerId, Modifiers, Rect, Response, Ui};
51use egui_pop_model::tab::{self as model, TabEntry};
52use serde::Serialize;
53
54use crate::state::{lock, pass, shared};
55
56/// What a scope is, which decides the ends of its Tab order and F6.
57#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
58#[serde(rename_all = "lowercase")]
59pub enum ScopeKind {
60    /// A panel: F6 comes here; Tab past its ends goes on with egui.
61    Panel,
62    /// A modal: Tab cycles inside; F6 does nothing while it is open.
63    Modal,
64}
65
66/// How a widget joins the Tab order.
67#[derive(Clone, Debug, Default, PartialEq, Eq)]
68pub struct TabStop {
69    index: Option<i32>,
70    group: Option<String>,
71    skip: bool,
72}
73
74impl TabStop {
75    pub fn new() -> Self {
76        Self::default()
77    }
78
79    /// An explicit place: stops with an index come first, by index.
80    pub fn index(mut self, index: i32) -> Self {
81        self.index = Some(index);
82        self
83    }
84
85    /// The stops of a group follow each other.
86    pub fn group(mut self, group: impl Into<String>) -> Self {
87        self.group = Some(group.into());
88        self
89    }
90
91    /// Out of the order (a disabled field).
92    pub fn skip(mut self, skip: bool) -> Self {
93        self.skip = skip;
94        self
95    }
96
97    /// The group, if any.
98    pub fn group_name(&self) -> Option<&str> {
99        self.group.as_deref()
100    }
101
102    /// The explicit index, if any.
103    pub fn explicit_index(&self) -> Option<i32> {
104        self.index
105    }
106}
107
108/// One stop as drawn.
109#[derive(Clone, Debug, PartialEq, Serialize)]
110pub struct StopRecord {
111    #[serde(skip)]
112    pub id: Id,
113    pub entry: TabEntry,
114}
115
116/// One scope as drawn, with its stops.
117#[derive(Clone, Debug, PartialEq, Serialize)]
118pub struct ScopeRecord {
119    pub name: String,
120    pub kind: ScopeKind,
121    #[serde(skip)]
122    pub layer: LayerId,
123    #[serde(skip)]
124    pub rect: Rect,
125    pub stops: Vec<StopRecord>,
126}
127
128impl ScopeRecord {
129    /// Its stops' ids in Tab order.
130    pub fn order(&self) -> Vec<Id> {
131        let entries: Vec<TabEntry> = self.stops.iter().map(|s| s.entry.clone()).collect();
132        model::order(&entries, false)
133            .into_iter()
134            .map(|i| self.stops[i].id)
135            .collect()
136    }
137
138    fn has_stops(&self) -> bool {
139        self.stops.iter().any(|s| !s.entry.skip)
140    }
141}
142
143#[derive(Debug, Default)]
144struct State {
145    pass: u64,
146    building: Vec<ScopeRecord>,
147    open: Vec<usize>,
148    last: Vec<ScopeRecord>,
149    /// The stop focused last in each panel, by scope name.
150    remembered: HashMap<String, Id>,
151    installed: bool,
152}
153
154fn state(ctx: &Context) -> std::sync::Arc<std::sync::Mutex<State>> {
155    shared::<State>(ctx, "core.tab")
156}
157
158fn rotate(ctx: &Context, s: &mut State) {
159    let now = pass(ctx);
160    if s.pass != now {
161        s.pass = now;
162        s.last = std::mem::take(&mut s.building);
163        s.open.clear();
164    }
165}
166
167/// Draws `add` as a Tab scope named `name` (see [the rules](self)).
168pub fn scope<R>(ui: &mut Ui, name: &str, kind: ScopeKind, add: impl FnOnce(&mut Ui) -> R) -> R {
169    install(ui.ctx());
170    let st = state(ui.ctx());
171    let index = {
172        let mut s = lock(&st);
173        rotate(ui.ctx(), &mut s);
174        s.building.push(ScopeRecord {
175            name: name.into(),
176            kind,
177            layer: ui.layer_id(),
178            rect: Rect::NOTHING,
179            stops: Vec::new(),
180        });
181        let i = s.building.len() - 1;
182        s.open.push(i);
183        i
184    };
185    let (inner, rect) = ui
186        .scope(|ui| {
187            let inner = add(ui);
188            (inner, ui.min_rect())
189        })
190        .inner;
191    let mut s = lock(&st);
192    if let Some(r) = s.building.get_mut(index) {
193        r.rect = rect;
194    }
195    s.open.pop();
196    inner
197}
198
199/// Puts a widget in the Tab order of the innermost scope being drawn
200/// (outside any scope, it stays in egui's order). A widget that cannot
201/// take the focus (disabled) is skipped whatever `stop` says.
202pub fn stop(ui: &Ui, response: &Response, stop: TabStop) {
203    let st = state(ui.ctx());
204    let mut s = lock(&st);
205    rotate(ui.ctx(), &mut s);
206    let Some(&i) = s.open.last() else {
207        return;
208    };
209    let r = response.rect;
210    let entry = TabEntry {
211        rect: [r.left(), r.top(), r.width(), r.height()],
212        index: stop.index,
213        group: stop.group,
214        skip: stop.skip || !response.enabled(),
215    };
216    s.building[i].stops.push(StopRecord {
217        id: response.id,
218        entry,
219    });
220}
221
222/// Which way a [`roving`] group runs, which decides its arrows.
223#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
224#[serde(rename_all = "lowercase")]
225pub enum Axis {
226    /// A row: Left and Right.
227    Horizontal,
228    /// A column: Up and Down.
229    Vertical,
230    /// The group keeps Tab only: its widgets move the focus with the arrows
231    /// themselves (a graph's nodes, by place). Home and End are left to them
232    /// too.
233    Own,
234}
235
236/// Draws `add` as a roving group named `name`: one Tab stop for all its
237/// widgets, the arrows going between them (a toolbar, a strip of icons, a
238/// status bar), as ARIA's toolbar pattern has it.
239///
240/// - **Tab** from any of its widgets leaves the group, past its last widget,
241///   and Shift+Tab before its first.
242/// - **Tab coming in**, either way, lands on the widget focused there last; on
243///   its first the first time.
244/// - **The arrows along it** (Left and Right for [`Axis::Horizontal`], Up and
245///   Down for [`Axis::Vertical`]) go to the widget placed before or after,
246///   round from one end to the other; **Home** and **End** to its ends. The
247///   other arrows are left to egui (and stay in their region).
248///
249/// Its widgets are those drawn inside `add` that can take the focus, so a
250/// disabled one is passed over. An open menu or popup keeps the arrows, and a
251/// focused text field every key. Name each group of a window apart: the widget
252/// focused last is remembered by name.
253///
254/// It needs the focus plugin ([`focus::install`](crate::focus::install); an
255/// application has it): without it, the widgets stay stops of egui's order.
256///
257/// ```
258/// use egui_pop_core::tab::{self, Axis};
259///
260/// fn tools(ui: &mut egui::Ui) {
261///     tab::roving(ui, "tools", Axis::Horizontal, |ui| {
262///         ui.horizontal(|ui| {
263///             let _ = ui.button("Cut");
264///             let _ = ui.button("Copy");
265///             let _ = ui.button("Paste");
266///         });
267///     });
268/// }
269/// ```
270pub fn roving<R>(ui: &mut Ui, name: &str, axis: Axis, add: impl FnOnce(&mut Ui) -> R) -> R {
271    crate::roving::show(ui, name, axis, add)
272}
273
274/// Draws `add` as the parts of the widget `owner` (a graph node's chevron,
275/// ports and sliders), inside a [`roving`] group: Tab coming into the group
276/// lands on the widget, not on its parts.
277///
278/// - **Enter** on `owner` goes into its parts, on the first.
279/// - **Tab** and **Shift+Tab** go round them, from the last to the first.
280/// - **Escape** goes back to `owner`.
281///
282/// Name each widget's parts apart. It needs the focus plugin.
283pub fn parts<R>(ui: &mut Ui, name: &str, owner: Id, add: impl FnOnce(&mut Ui) -> R) -> R {
284    crate::roving::parts(ui, name, owner, add)
285}
286
287/// The roving groups drawn in the last pass, by name, with their widgets that
288/// can take the focus in the order drawn.
289pub fn rovings(ctx: &Context) -> Vec<(String, Vec<Id>)> {
290    crate::roving::groups(ctx)
291}
292
293/// The scopes drawn in the last pass, with their stops.
294pub fn scopes(ctx: &Context) -> Vec<ScopeRecord> {
295    let st = state(ctx);
296    let mut s = lock(&st);
297    rotate(ctx, &mut s);
298    s.last.clone()
299}
300
301/// A scope's stops in Tab order, as drawn in the last pass.
302pub fn order(ctx: &Context, name: &str) -> Vec<Id> {
303    scopes(ctx)
304        .iter()
305        .find(|r| r.name == name)
306        .map(ScopeRecord::order)
307        .unwrap_or_default()
308}
309
310/// A panel scope F6 can go to, as [`regions`](crate::regions) reads it.
311#[derive(Clone, Debug)]
312pub(crate) struct PanelHop {
313    /// Its first stop drawn, to tell which region holds it.
314    pub first: Id,
315    /// Where F6 lands in it.
316    pub target: Id,
317    /// The focus is in it.
318    pub here: bool,
319}
320
321/// The panel scopes with stops the last pass drew, in the order drawn.
322pub(crate) fn panel_hops(ctx: &Context) -> Vec<PanelHop> {
323    let focused = ctx.memory(|m| m.focused());
324    let at = focused.and_then(|f| {
325        let r = crate::focus::peek_response(ctx, f)?;
326        Some((r.layer_id, r.rect.center()))
327    });
328    let st = state(ctx);
329    let mut s = lock(&st);
330    rotate(ctx, &mut s);
331    let drawn = s.last.iter().filter(|sc| sc.kind == ScopeKind::Panel);
332    drawn
333        .filter_map(|sc| {
334            let order = sc.order();
335            let target = s
336                .remembered
337                .get(&sc.name)
338                .filter(|r| order.contains(r))
339                .or(order.first())?;
340            let holds = focused.is_some_and(|f| sc.stops.iter().any(|x| x.id == f));
341            let lies = at.is_some_and(|(layer, pos)| sc.layer == layer && sc.rect.contains(pos));
342            Some(PanelHop {
343                first: sc.stops.first()?.id,
344                target: *target,
345                here: holds || lies,
346            })
347        })
348        .collect()
349}
350
351/// Whether a modal scope with stops was drawn in the last pass.
352pub(crate) fn modal_drawn(ctx: &Context) -> bool {
353    let st = state(ctx);
354    let mut s = lock(&st);
355    rotate(ctx, &mut s);
356    s.last
357        .iter()
358        .any(|sc| sc.kind == ScopeKind::Modal && sc.has_stops())
359}
360
361/// Installs the Tab plugin on a context (once; [`scope`] does it).
362pub fn install(ctx: &Context) {
363    let st = state(ctx);
364    let mut s = lock(&st);
365    if !s.installed {
366        s.installed = true;
367        drop(s);
368        ctx.add_plugin(TabPlugin);
369    }
370}
371
372/// Moves the focus on Tab and F6, after egui has read the input and
373/// before anything is drawn.
374#[derive(Debug)]
375struct TabPlugin;
376
377impl egui::plugin::Plugin for TabPlugin {
378    fn debug_name(&self) -> &'static str {
379        "egui_pop_core::tab"
380    }
381
382    fn on_begin_pass(&mut self, ui: &mut Ui) {
383        begin_pass(ui.ctx());
384    }
385}
386
387/// A press of `key`, plain or with Shift only: whether it goes back.
388fn pressed(ctx: &Context, key: Key) -> Option<bool> {
389    ctx.input(|i| {
390        i.events.iter().find_map(|e| match e {
391            egui::Event::Key {
392                key: k,
393                pressed: true,
394                modifiers,
395                ..
396            } if *k == key && (modifiers.is_none() || modifiers.shift_only()) => {
397                Some(modifiers.shift)
398            }
399            _ => None,
400        })
401    })
402}
403
404fn focus(ctx: &Context, target: Id, key: Key, back: bool) {
405    ctx.memory_mut(|m| {
406        m.request_focus(target);
407        m.move_focus(FocusDirection::None);
408    });
409    let mods = if back {
410        Modifiers::SHIFT
411    } else {
412        Modifiers::NONE
413    };
414    ctx.input_mut(|i| i.consume_key(mods, key));
415}
416
417fn begin_pass(ctx: &Context) {
418    let st = state(ctx);
419    let mut s = lock(&st);
420    rotate(ctx, &mut s);
421    let focused = ctx.memory(|m| m.focused());
422    // Where the focus is: a scope and its stop.
423    let at = focused.and_then(|f| {
424        s.last
425            .iter()
426            .enumerate()
427            .find_map(|(i, sc)| sc.stops.iter().position(|x| x.id == f).map(|j| (i, j)))
428    });
429    if let Some((i, _)) = at
430        && s.last[i].kind == ScopeKind::Panel
431        && let Some(f) = focused
432    {
433        let name = s.last[i].name.clone();
434        s.remembered.insert(name, f);
435    }
436    if let Some(back) = pressed(ctx, Key::Tab)
437        && let Some((i, j)) = at
438    {
439        let sc = &s.last[i];
440        let entries: Vec<TabEntry> = sc.stops.iter().map(|x| x.entry.clone()).collect();
441        let order = model::order(&entries, false);
442        let cycle = sc.kind == ScopeKind::Modal;
443        if let Some(k) = model::next(&order, Some(j), back, cycle) {
444            let target = sc.stops[k].id;
445            drop(s);
446            focus(ctx, target, Key::Tab, back);
447            return;
448        }
449    }
450    if let Some(back) = pressed(ctx, Key::F6) {
451        // F6 is the regions' here, through the application's key binding.
452        if crate::focus::has_regions(ctx) {
453            return;
454        }
455        let modal = s
456            .last
457            .iter()
458            .any(|sc| sc.kind == ScopeKind::Modal && sc.has_stops())
459            || crate::overlay::modal_open(ctx);
460        if modal {
461            return;
462        }
463        let panels: Vec<usize> = (0..s.last.len())
464            .filter(|&i| s.last[i].kind == ScopeKind::Panel && s.last[i].has_stops())
465            .collect();
466        if panels.is_empty() {
467            return;
468        }
469        let current = at.map(|(i, _)| i).or_else(|| {
470            let f = focused?;
471            let r = crate::focus::peek_response(ctx, f)?;
472            panels.iter().copied().find(|&p| {
473                s.last[p].layer == r.layer_id && s.last[p].rect.contains(r.rect.center())
474            })
475        });
476        let pos = current.and_then(|c| panels.iter().position(|&p| p == c));
477        let n = panels.len();
478        let next = match pos {
479            None if back => panels[n - 1],
480            None => panels[0],
481            Some(p) if back => panels[(p + n - 1) % n],
482            Some(p) => panels[(p + 1) % n],
483        };
484        let sc = &s.last[next];
485        let order = sc.order();
486        let target = s
487            .remembered
488            .get(&sc.name)
489            .copied()
490            .filter(|r| order.contains(r))
491            .or_else(|| order.first().copied());
492        if let Some(target) = target {
493            drop(s);
494            focus(ctx, target, Key::F6, back);
495        }
496    }
497}