Skip to main content

egui/data/input/
event_filter.rs

1use super::Event;
2
3// TODO(emilk): generalize this to a proper event filter.
4/// Controls which events that a focused widget will have exclusive access to.
5///
6/// Currently this only controls a few special keyboard events,
7/// but in the future this `struct` should be extended into a full callback thing.
8///
9/// Any events not covered by the filter are given to the widget, but are not exclusive.
10#[derive(Clone, Copy, Debug)]
11pub struct EventFilter {
12    /// If `true`, pressing tab will act on the widget,
13    /// and NOT move focus away from the focused widget.
14    ///
15    /// Default: `false`
16    pub tab: bool,
17
18    /// If `true`, pressing horizontal arrows will act on the
19    /// widget, and NOT move focus away from the focused widget.
20    ///
21    /// Default: `false`
22    pub horizontal_arrows: bool,
23
24    /// If `true`, pressing vertical arrows will act on the
25    /// widget, and NOT move focus away from the focused widget.
26    ///
27    /// Default: `false`
28    pub vertical_arrows: bool,
29
30    /// If `true`, pressing escape will act on the widget,
31    /// and NOT surrender focus from the focused widget.
32    ///
33    /// Default: `false`
34    pub escape: bool,
35}
36
37#[expect(clippy::derivable_impls)] // let's be explicit
38impl Default for EventFilter {
39    fn default() -> Self {
40        Self {
41            tab: false,
42            horizontal_arrows: false,
43            vertical_arrows: false,
44            escape: false,
45        }
46    }
47}
48
49impl EventFilter {
50    pub fn matches(&self, event: &Event) -> bool {
51        if let Event::Key { key, .. } = event {
52            match key {
53                crate::Key::Tab => self.tab,
54                crate::Key::ArrowUp | crate::Key::ArrowDown => self.vertical_arrows,
55                crate::Key::ArrowRight | crate::Key::ArrowLeft => self.horizontal_arrows,
56                crate::Key::Escape => self.escape,
57                _ => true,
58            }
59        } else {
60            true
61        }
62    }
63}