pub struct KeyState { /* private fields */ }Expand description
Tracks which keys are currently held down.
Feed it every KeyEvent (or Event) you receive and query
is_held each frame for held-key movement. A key is
considered held from its first KeyEventKind::Press until a matching
KeyEventKind::Release, or until apply_event sees an
Event::FocusLost, whichever comes first.
Held keys are keyed by (KeyCode, KeyLocation), so a held Numpad8 and a held digit-row 8 are
tracked separately: is_held takes the pair, and held yields
it.
Release events are what actually clear a key, and not every backend emits them: plain
terminals only ever report KeyEventKind::Press (see KeyEventKind). On those
press-only backends a key never leaves the held set on its own – not even on focus loss, since
there is no release to match – so call clear at a suitable boundary (e.g.
once per turn) if you rely on held-key state there. Backends rich enough to emit releases
(winit, or a terminal with the kitty keyboard protocol) are exactly the ones that also emit
Event::FocusLost, so apply_event clears the
held set on it: without that, alt-tabbing or clicking away while a key is down would leave it
stuck held forever, since the release is delivered to whichever window/app gains focus instead.
Implementations§
Source§impl KeyState
impl KeyState
Sourcepub fn apply_event(&mut self, event: &Event)
pub fn apply_event(&mut self, event: &Event)
Updates the held set from an Event.
Key events update the held set as apply does;
Event::FocusLost clears it entirely (see the type-level docs
for why); every other event is ignored.
Sourcepub fn is_held(&self, code: KeyCode, location: KeyLocation) -> bool
pub fn is_held(&self, code: KeyCode, location: KeyLocation) -> bool
Returns true if code at location is currently held.
Sourcepub fn held(&self) -> impl Iterator<Item = (KeyCode, KeyLocation)> + '_
pub fn held(&self) -> impl Iterator<Item = (KeyCode, KeyLocation)> + '_
Iterates the currently held (code, location) pairs, in first-pressed order.