ui_input_state/
input_state.rs

1// Copyright 2025 the UI Events Authors
2// SPDX-License-Identifier: Apache-2.0 OR MIT
3
4//! # Frame-level input state aggregation.
5//!
6//! `InputState` groups together [`PrimaryPointerState`] and [`KeyboardState`]
7//! and provides a single [`clear_frame`](InputState::clear_frame) call to reset
8//! per-frame transitions. Feed events into the contained states as they arrive
9//! from your backend, then query during your UI update pass.
10//!
11//! ## Example:
12//!
13//! ```no_run
14//! use ui_input_state::InputState;
15//! use ui_events::keyboard::{KeyboardEvent, KeyState, Key, Location, Code, Modifiers};
16//! use ui_events::pointer::{
17//!     PointerEvent, PointerButtonEvent, PointerInfo, PointerType, PointerId,
18//! };
19//! use dpi::{PhysicalPosition, PhysicalSize};
20//!
21//! let mut input = InputState::default();
22//!
23//! // Minimal keyboard event
24//! let key_down = KeyboardEvent {
25//!     state: KeyState::Down,
26//!     key: Key::Character("a".into()),
27//!     location: Location::Standard,
28//!     code: Code::KeyA,
29//!     modifiers: Modifiers::empty(),
30//!     is_composing: false,
31//!     repeat: false,
32//! };
33//! input.keyboard.process_keyboard_event(key_down);
34//!
35//! // Minimal pointer down
36//! let pointer_down = PointerEvent::Down(PointerButtonEvent {
37//!     button: None,
38//!     pointer: PointerInfo {
39//!         pointer_id: Some(PointerId::PRIMARY),
40//!         persistent_device_id: None,
41//!         pointer_type: PointerType::Mouse,
42//!     },
43//!     state: ui_events::pointer::PointerState {
44//!         time: 0,
45//!         position: PhysicalPosition { x: 0.0, y: 0.0 },
46//!         buttons: Default::default(),
47//!         modifiers: Modifiers::empty(),
48//!         count: 1,
49//!         contact_geometry: PhysicalSize { width: 1.0, height: 1.0 },
50//!         orientation: Default::default(),
51//!         pressure: 0.5,
52//!         tangential_pressure: 0.0,
53//!         scale_factor: 1.0,
54//!     },
55//! });
56//! input.primary_pointer.process_pointer_event(pointer_down);
57//!
58//! // Use state during your frame
59//! let _any_key = input.keyboard.is_any_down();
60//! let _pointer_pos = input.primary_pointer.current_position();
61//!
62//! // Clear transitions
63//! input.clear_frame();
64//! ```
65use crate::KeyboardState;
66use crate::PrimaryPointerState;
67
68/// A stateful view of the input data for a frame, rather than
69/// processing it event-by-event.
70#[derive(Debug, Default)]
71pub struct InputState {
72    /// The state of the primary pointer.
73    pub primary_pointer: PrimaryPointerState,
74
75    /// The state of the keyboard.
76    pub keyboard: KeyboardState,
77}
78
79impl InputState {
80    /// Clear the per-frame state to prepare for a new frame.
81    pub fn clear_frame(&mut self) {
82        self.primary_pointer.clear_frame();
83        self.keyboard.clear_frame();
84    }
85}