1use std::cell::RefCell;
2use std::collections::{HashMap, HashSet};
3use std::rc::Rc;
4
5use glam::Vec2;
6use repame_input::{AimTracker, GamepadState, MouseState, StagedClick, TouchContact};
7use repose_core::input::{Key, KeyEvent, KeyEventType, PhysicalKey, PointerButton};
8use repose_core::runtime::Scheduler;
9
10#[derive(Default)]
11pub struct Staging {
12 pub held: HashSet<PhysicalKey>,
13 pub edges: Vec<PhysicalKey>,
14 pub window_focused: bool,
15 pub capture_armed: bool,
16 pub clicks: Vec<StagedClick>,
17 pub aim: AimTracker,
18 pub mouse_edges: Vec<(PointerButton, bool)>,
19 pub lmb_held: bool,
20 pub rmb_held: bool,
21 pub rmb_down_edge: bool,
22 pub capture_pending_physical: Option<PhysicalKey>,
23 pub capture_pending_key: Option<Key>,
24 pub capture_pending_mouse: Option<bool>,
25 pub touch_active: HashMap<u64, (Vec2, Vec2)>,
26 pub touch_new: HashSet<u64>,
27 pub touch_released: Vec<u64>,
28 pub pads: Vec<GamepadState>,
29 pub pad_live: bool,
30 pub view_width: f32,
31}
32
33impl Staging {
34 pub fn shared() -> Rc<RefCell<Self>> {
35 Rc::new(RefCell::new(Self {
36 window_focused: true,
37 view_width: 1280.0,
38 ..Default::default()
39 }))
40 }
41
42 pub fn handle_key(&mut self, ke: &KeyEvent) {
43 let down = matches!(ke.event_type, KeyEventType::Down);
44 if down && !ke.is_repeat {
45 match &ke.key {
46 Key::Backspace => {
47 self.capture_pending_key = Some(Key::Backspace);
48 return;
49 }
50 _ => {}
51 }
52 if self.capture_armed {
53 if let Some(key) = ke.physical {
54 self.capture_pending_physical = Some(key);
55 } else {
56 self.capture_pending_key = Some(ke.key.clone());
57 }
58 return;
59 }
60 if matches!(ke.key, Key::Escape | Key::Enter) {
61 return;
62 }
63 }
64 match &ke.key {
65 Key::Escape | Key::Enter => {}
66 Key::Character(_) => {
67 if let Some(key) = ke.physical {
68 self.stage_physical(key, down, ke.is_repeat);
69 }
70 }
71 Key::ShiftLeft => self.stage_code(PhysicalKey::ShiftLeft, down, ke.is_repeat),
72 Key::ShiftRight => self.stage_code(PhysicalKey::ShiftRight, down, ke.is_repeat),
73 Key::Space => self.stage_code(PhysicalKey::Space, down, ke.is_repeat),
74 Key::Tab => self.stage_code(PhysicalKey::Tab, down, ke.is_repeat),
75 Key::ArrowUp => self.stage_code(PhysicalKey::ArrowUp, down, ke.is_repeat),
76 Key::ArrowDown => self.stage_code(PhysicalKey::ArrowDown, down, ke.is_repeat),
77 Key::ArrowLeft => self.stage_code(PhysicalKey::ArrowLeft, down, ke.is_repeat),
78 Key::ArrowRight => self.stage_code(PhysicalKey::ArrowRight, down, ke.is_repeat),
79 _ => {}
80 }
81 }
82
83 pub fn stage_physical(&mut self, key: PhysicalKey, down: bool, is_repeat: bool) {
84 if down {
85 if self.held.insert(key) && !is_repeat {
86 self.edges.push(key);
87 }
88 } else {
89 self.held.remove(&key);
90 }
91 }
92
93 fn stage_code(&mut self, code: PhysicalKey, down: bool, is_repeat: bool) {
94 self.stage_physical(code, down, is_repeat);
95 }
96
97 pub fn stage_physical_key(&mut self, key: PhysicalKey, down: bool) {
98 self.stage_physical(key, down, false);
99 }
100
101 pub fn set_window_focused(&mut self, focused: bool) {
102 self.window_focused = focused;
103 if !focused {
104 self.held.clear();
105 self.edges.clear();
106 self.capture_pending_physical = None;
107 self.capture_pending_key = None;
108 self.capture_pending_mouse = None;
109 self.lmb_held = false;
110 self.rmb_held = false;
111 self.aim = AimTracker::default();
112 self.clicks.clear();
113 self.mouse_edges.clear();
114 self.rmb_down_edge = false;
115 self.touch_active.clear();
116 self.touch_new.clear();
117 self.touch_released.clear();
118 self.pads.clear();
119 self.pad_live = false;
120 }
121 }
122
123 pub fn feed_polled(&mut self, sched: &Scheduler) {
124 if !sched.window_focused {
125 self.set_window_focused(false);
126 return;
127 }
128 self.window_focused = true;
129 self.held.retain(|key| sched.held_keys.contains(key));
132 if !sched.mouse_primary {
133 self.lmb_held = false;
134 }
135 if !sched.mouse_secondary {
136 self.rmb_held = false;
137 }
138 if !sched.mouse_middle {
139 self.mouse_edges
140 .retain(|(button, _)| *button != PointerButton::Tertiary);
141 }
142 if sched.touch_points.is_empty() {
146 if !self.touch_active.is_empty() {
147 self.touch_released
148 .extend(self.touch_active.keys().copied());
149 self.touch_active.clear();
150 self.touch_new.clear();
151 }
152 } else {
153 let d = repose_core::locals::effective_density_scale().max(1e-6);
154 let live: std::collections::HashSet<u64> =
155 sched.touch_points.iter().map(|(id, _, _)| *id).collect();
156 self.touch_active
157 .retain(|id, _| live.contains(id) || self.touch_new.contains(id));
158 for (id, x, y) in sched.touch_points.iter() {
159 let p = Vec2::new(*x, *y) / d;
160 if let Some(contact) = self.touch_active.get_mut(id) {
161 contact.1 = p;
162 } else {
163 self.touch_active.insert(*id, (p, p));
164 self.touch_new.insert(*id);
165 }
166 }
167 }
168 }
169
170 pub fn pick_down(&mut self, button: PointerButton) {
171 if self.capture_armed {
172 self.capture_pending_mouse = Some(button == PointerButton::Primary);
173 return;
174 }
175 self.mouse_edges.push((button, true));
176 if button == PointerButton::Primary {
177 self.lmb_held = true;
178 } else {
179 self.rmb_down_edge = true;
180 self.rmb_held = true;
181 }
182 }
183
184 pub fn pick_up(&mut self, button: PointerButton) {
185 self.mouse_edges.push((button, false));
186 if button == PointerButton::Primary {
187 self.lmb_held = false;
188 } else {
189 self.rmb_held = false;
190 }
191 }
192
193 pub fn take_capture_physical(&mut self) -> Option<PhysicalKey> {
194 self.capture_pending_physical.take()
195 }
196
197 pub fn take_capture_key(&mut self) -> Option<Key> {
198 self.capture_pending_key.take()
199 }
200
201 pub fn take_capture_mouse(&mut self) -> Option<bool> {
202 self.capture_pending_mouse.take()
203 }
204
205 pub fn take_rmb_down(&mut self) -> bool {
206 std::mem::replace(&mut self.rmb_down_edge, false)
207 }
208
209 pub fn stage_click(&mut self, world: Vec2, screen: [f32; 2], density: f32) {
210 let d = density.max(1e-6);
211 self.clicks.push(StagedClick {
212 world,
213 dp: [screen[0] / d, screen[1] / d],
214 });
215 }
216
217 pub fn take_clicks(&mut self) -> Vec<StagedClick> {
218 std::mem::take(&mut self.clicks)
219 }
220
221 pub fn take_edges(&mut self) -> Vec<PhysicalKey> {
222 std::mem::take(&mut self.edges)
223 }
224
225 pub fn take_mouse_edges(&mut self) -> Vec<(PointerButton, bool)> {
226 std::mem::take(&mut self.mouse_edges)
227 }
228
229 pub fn take_pads(&mut self) -> Vec<GamepadState> {
230 self.pad_live = !self.pads.is_empty();
231 std::mem::take(&mut self.pads)
232 }
233
234 pub fn stage_gamepad(&mut self, pad: GamepadState) {
235 self.pads.push(pad);
236 self.pad_live = true;
237 }
238
239 pub fn touch_down(&mut self, id: u64, screen_dp: Vec2) {
240 self.touch_active.insert(id, (screen_dp, screen_dp));
241 self.touch_new.insert(id);
242 }
243
244 pub fn touch_move(&mut self, id: u64, screen_dp: Vec2) {
245 if let Some(contact) = self.touch_active.get_mut(&id) {
246 contact.1 = screen_dp;
247 }
248 }
249
250 pub fn touch_up(&mut self, id: u64) {
251 if self.touch_active.remove(&id).is_some() {
252 self.touch_released.push(id);
253 }
254 self.touch_new.remove(&id);
255 }
256
257 pub fn touch_contacts(&mut self) -> Vec<TouchContact> {
258 let out = self.touch_contacts_snapshot();
259 self.touch_new.clear();
260 out
261 }
262
263 pub fn touch_contacts_snapshot(&self) -> Vec<TouchContact> {
266 self.touch_active
267 .iter()
268 .map(|(id, (start, pos))| TouchContact {
269 id: *id,
270 start: *start,
271 pos: *pos,
272 just_pressed: self.touch_new.contains(id),
273 })
274 .collect()
275 }
276
277 pub fn take_touch_released(&mut self) -> Vec<u64> {
278 std::mem::take(&mut self.touch_released)
279 }
280
281 pub fn cursor_move(&mut self, phys_px: Vec2) {
282 self.aim.cursor_move(phys_px);
283 }
284
285 pub fn stage_hover(&mut self, world: Vec2, screen: [f32; 2]) {
286 self.aim.stage_hover(world, screen);
287 }
288
289 pub fn mouse_state(&self, allow_fire: bool) -> MouseState {
290 MouseState {
291 left_held: self.lmb_held && allow_fire,
292 left_pressed: !self.clicks.is_empty() && allow_fire,
293 right_held: self.rmb_held,
294 right_pressed: self.rmb_down_edge,
295 }
296 }
297}
298
299#[cfg(test)]
300mod tests {
301 use super::*;
302 use repose_core::input::{Key, Modifiers};
303
304 fn key(physical: PhysicalKey) -> KeyEvent {
305 KeyEvent {
306 key: Key::Character('x'),
307 modifiers: Modifiers::default(),
308 is_repeat: false,
309 event_type: KeyEventType::Down,
310 utf16_code_point: 0,
311 physical: Some(physical),
312 }
313 }
314
315 #[test]
316 fn edges_dedupe_while_held() {
317 let mut s = Staging::default();
318 s.handle_key(&key(PhysicalKey::KeyW));
319 s.handle_key(&key(PhysicalKey::KeyW));
320 assert_eq!(s.take_edges().len(), 1);
321 }
322
323 #[test]
324 fn focus_loss_clears_levels() {
325 let mut s = Staging::default();
326 s.handle_key(&key(PhysicalKey::KeyW));
327 s.set_window_focused(false);
328 assert!(s.held.is_empty());
329 }
330
331 #[test]
332 fn capture_stashes_physical_and_skips_edges() {
333 let mut s = Staging::default();
334 s.capture_armed = true;
335 s.handle_key(&key(PhysicalKey::KeyZ));
336 assert_eq!(s.capture_pending_physical, Some(PhysicalKey::KeyZ));
337 assert!(s.take_edges().is_empty());
338 }
339
340 #[test]
341 fn capture_click_stashes_button_not_click_edge() {
342 let mut s = Staging::default();
343 s.capture_armed = true;
344 s.pick_down(PointerButton::Primary);
345 assert_eq!(s.capture_pending_mouse, Some(true));
346 assert!(s.take_clicks().is_empty());
347 assert!(!s.lmb_held);
348 }
349}