leejunyoung5819 wayland-android-remote
공개Ubuntu(Wayland/X11)에서 Android 기기 화면 미러링 및 원격 제어 (Rust)
| 1 | //! 메인 창의 마우스·휠·키보드·IME 입력을 제어 메시지로 바꾼다. |
| 2 | //! |
| 3 | //! egui가 프레임마다 모은 원시 이벤트를 순서대로 읽어 메시지를 만든다. 위젯 응답 대신 원시 |
| 4 | //! 이벤트를 쓰는 이유는 드래그 판정 지연 없이 누르는 즉시 DOWN을 보내고, 한 프레임 안의 |
| 5 | //! 누름·이동·뗌 순서를 그대로 지키기 위해서다. |
| 6 | |
| 7 | use egui::{Event, ImeEvent, Key, Modifiers, MouseWheelUnit, PointerButton, Pos2, Rect, Vec2}; |
| 8 | use wayland_android_remote::protocol::{ |
| 9 | KeyAction, KeyEvent, Message, ScrollEvent, SystemAction, TextInput, TouchAction, TouchEvent, |
| 10 | }; |
| 11 | |
| 12 | use super::keymap; |
| 13 | |
| 14 | /// 터치 압력 최댓값 (누른 상태). |
| 15 | const FULL_PRESSURE: u16 = 0xFFFF; |
| 16 | /// 휠 한 노치 = 120 단위 (Android AXIS_VSCROLL 1.0). |
| 17 | const NOTCH: f32 = 120.0; |
| 18 | /// 픽셀 단위 휠(터치패드)에서 한 노치로 치는 논리 픽셀 수. egui의 줄 단위 스크롤 |
| 19 | /// 속도(40pt)보다 조금 크게 잡아 손가락 이동량과 휴대폰 스크롤 양이 비슷하게 느껴지도록 했다. |
| 20 | pub const POINTS_PER_NOTCH: f32 = 50.0; |
| 21 | /// 페이지 단위 휠은 3줄(3노치)로 친다. |
| 22 | const LINES_PER_PAGE: f32 = 3.0; |
| 23 | |
| 24 | /// 입력을 받을 휴대폰 화면 영역. |
| 25 | #[derive(Debug, Clone, Copy, PartialEq)] |
| 26 | pub struct VideoTarget { |
| 27 | /// 창 안에서 영상이 그려진 사각형 (논리 픽셀). |
| 28 | pub rect: Rect, |
| 29 | /// 휴대폰이 기대하는 좌표계 크기 (`VideoConfig.width/height`). |
| 30 | pub width: u16, |
| 31 | pub height: u16, |
| 32 | } |
| 33 | |
| 34 | impl VideoTarget { |
| 35 | /// 창 좌표를 영상 프레임 픽셀 좌표로 바꾼다. 영역 밖은 가장자리로 붙인다. |
| 36 | pub fn to_frame(self, p: Pos2) -> (u32, u32) { |
| 37 | let axis = |v: f32, min: f32, len: f32, size: u16| { |
| 38 | let max = u32::from(size.max(1) - 1); |
| 39 | let n = if len > 0.0 { (v - min) / len } else { 0.0 }; |
| 40 | ((n * f32::from(size)).floor().max(0.0) as u32).min(max) |
| 41 | }; |
| 42 | ( |
| 43 | axis(p.x, self.rect.min.x, self.rect.width(), self.width), |
| 44 | axis(p.y, self.rect.min.y, self.rect.height(), self.height), |
| 45 | ) |
| 46 | } |
| 47 | } |
| 48 | |
| 49 | /// 누르고 있는 터치 하나 (pointer_id 0). |
| 50 | #[derive(Debug, Clone, Copy)] |
| 51 | struct Touch { |
| 52 | /// 마지막으로 보낸 좌표. |
| 53 | last: (u32, u32), |
| 54 | /// 누를 때의 프레임 크기. 바뀌면 취소한다. |
| 55 | frame: (u16, u16), |
| 56 | /// 이번 프레임에서 아직 보내지 않은 최신 이동 위치. |
| 57 | pending: Option<Pos2>, |
| 58 | } |
| 59 | |
| 60 | /// 휴대폰에 DOWN을 보낸 키. UP도 같은 키코드로 보낸다. |
| 61 | #[derive(Debug, Clone, Copy)] |
| 62 | struct HeldKey { |
| 63 | key: Key, |
| 64 | keycode: u16, |
| 65 | repeat: u16, |
| 66 | } |
| 67 | |
| 68 | /// 프레임 사이에 유지하는 입력 상태. |
| 69 | #[derive(Debug, Default)] |
| 70 | pub struct InputState { |
| 71 | touch: Option<Touch>, |
| 72 | /// 마지막 포인터 위치. 휠 이벤트 위치로 쓴다. |
| 73 | pointer: Option<Pos2>, |
| 74 | /// 아직 보내지 않은 휠 양 (1/120 노치 단위, 위·오른쪽 양수). |
| 75 | wheel_acc: Vec2, |
| 76 | held_keys: Vec<HeldKey>, |
| 77 | /// IME 조합 중인 글자. 휴대폰에는 보내지 않고 화면에만 표시한다. |
| 78 | preedit: String, |
| 79 | } |
| 80 | |
| 81 | impl InputState { |
| 82 | /// 조합 중인 IME 글자. |
| 83 | pub fn preedit(&self) -> &str { |
| 84 | &self.preedit |
| 85 | } |
| 86 | |
| 87 | /// 한 프레임의 이벤트를 처리해 보낼 메시지를 `out`에 순서대로 넣는다. |
| 88 | /// |
| 89 | /// `keyboard`는 연결되어 키보드 입력을 휴대폰으로 보낼 상태인지, `target`은 터치·휠을 |
| 90 | /// 받을 영상 영역(연결되고 영상 설정과 프레임이 있을 때)이다. |
| 91 | pub fn process( |
| 92 | &mut self, |
| 93 | events: &[Event], |
| 94 | keyboard: bool, |
| 95 | target: Option<VideoTarget>, |
| 96 | out: &mut Vec<Message>, |
| 97 | ) { |
| 98 | // 연결이 끊기거나 영상 크기가 바뀌면 누르던 터치를 취소한다. |
| 99 | if let Some(t) = self.touch |
| 100 | && target.is_none_or(|v| (v.width, v.height) != t.frame) |
| 101 | { |
| 102 | self.cancel_touch(out); |
| 103 | } |
| 104 | if !keyboard { |
| 105 | self.held_keys.clear(); |
| 106 | self.preedit.clear(); |
| 107 | } |
| 108 | |
| 109 | let mut skip_text = false; |
| 110 | for (i, event) in events.iter().enumerate() { |
| 111 | // 직전 키 이벤트로 이미 보낸 키가 만든 글자는 건너뛴다 (예: Alt+문자). |
| 112 | let skip = std::mem::take(&mut skip_text); |
| 113 | match event { |
| 114 | Event::PointerMoved(p) => { |
| 115 | self.pointer = Some(*p); |
| 116 | if let Some(t) = &mut self.touch { |
| 117 | t.pending = Some(*p); |
| 118 | } |
| 119 | } |
| 120 | Event::PointerGone => self.pointer = None, |
| 121 | Event::PointerButton { |
| 122 | pos, |
| 123 | button: PointerButton::Primary, |
| 124 | pressed, |
| 125 | .. |
| 126 | } => { |
| 127 | self.pointer = Some(*pos); |
| 128 | match (*pressed, target) { |
| 129 | (true, Some(v)) if self.touch.is_none() && v.rect.contains(*pos) => { |
| 130 | self.touch_down(v, *pos, out); |
| 131 | } |
| 132 | (false, Some(v)) if self.touch.is_some() => self.touch_up(v, *pos, out), |
| 133 | _ => {} |
| 134 | } |
| 135 | } |
| 136 | Event::MouseWheel { unit, delta, .. } => { |
| 137 | if let Some(v) = target { |
| 138 | self.wheel(v, *unit, *delta, out); |
| 139 | } |
| 140 | } |
| 141 | Event::WindowFocused(false) => { |
| 142 | self.cancel_touch(out); |
| 143 | self.release_keys(Modifiers::NONE, out); |
| 144 | self.preedit.clear(); |
| 145 | } |
| 146 | Event::Key { |
| 147 | key, |
| 148 | pressed, |
| 149 | repeat, |
| 150 | modifiers, |
| 151 | .. |
| 152 | } if keyboard => { |
| 153 | let next_is_text = matches!(events.get(i + 1), Some(Event::Text(_))); |
| 154 | if *pressed { |
| 155 | skip_text = self.key_down(*key, *modifiers, *repeat, next_is_text, out); |
| 156 | } else { |
| 157 | self.key_up(*key, *modifiers, out); |
| 158 | } |
| 159 | } |
| 160 | Event::Text(text) if keyboard && !skip => send_text(text, out), |
| 161 | Event::Ime(ime) if keyboard => match ime { |
| 162 | ImeEvent::Preedit { text, .. } => self.preedit.clone_from(text), |
| 163 | ImeEvent::Commit(text) => { |
| 164 | self.preedit.clear(); |
| 165 | send_text(text, out); |
| 166 | } |
| 167 | _ => {} |
| 168 | }, |
| 169 | // 클립보드 단축키를 egui-winit이 가로챈 경우 (메인 창은 연결 중 끄지만 대비해 둔다). |
| 170 | Event::Copy if keyboard => out.push(Message::SystemAction(SystemAction::Copy)), |
| 171 | Event::Cut if keyboard => out.push(Message::SystemAction(SystemAction::Cut)), |
| 172 | Event::Paste(_) if keyboard => out.push(Message::SystemAction(SystemAction::Paste)), |
| 173 | _ => {} |
| 174 | } |
| 175 | } |
| 176 | |
| 177 | // 이동은 프레임마다 최신 위치 한 번만 보낸다. |
| 178 | if let (Some(v), Some(_)) = (target, self.touch) { |
| 179 | self.flush_move(v, out); |
| 180 | } |
| 181 | } |
| 182 | |
| 183 | fn touch_down(&mut self, v: VideoTarget, pos: Pos2, out: &mut Vec<Message>) { |
| 184 | let last = v.to_frame(pos); |
| 185 | out.push(touch_message(TouchAction::Down, last, (v.width, v.height))); |
| 186 | self.touch = Some(Touch { |
| 187 | last, |
| 188 | frame: (v.width, v.height), |
| 189 | pending: None, |
| 190 | }); |
| 191 | } |
| 192 | |
| 193 | fn flush_move(&mut self, v: VideoTarget, out: &mut Vec<Message>) { |
| 194 | let Some(t) = &mut self.touch else { return }; |
| 195 | let Some(p) = t.pending.take() else { return }; |
| 196 | let pos = v.to_frame(p); |
| 197 | if pos != t.last { |
| 198 | t.last = pos; |
| 199 | out.push(touch_message(TouchAction::Move, pos, t.frame)); |
| 200 | } |
| 201 | } |
| 202 | |
| 203 | fn touch_up(&mut self, v: VideoTarget, pos: Pos2, out: &mut Vec<Message>) { |
| 204 | self.flush_move(v, out); |
| 205 | if let Some(t) = self.touch.take() { |
| 206 | out.push(touch_message(TouchAction::Up, v.to_frame(pos), t.frame)); |
| 207 | } |
| 208 | } |
| 209 | |
| 210 | fn cancel_touch(&mut self, out: &mut Vec<Message>) { |
| 211 | if let Some(t) = self.touch.take() { |
| 212 | out.push(touch_message(TouchAction::Cancel, t.last, t.frame)); |
| 213 | } |
| 214 | } |
| 215 | |
| 216 | fn wheel(&mut self, v: VideoTarget, unit: MouseWheelUnit, delta: Vec2, out: &mut Vec<Message>) { |
| 217 | let Some(p) = self.pointer.filter(|p| v.rect.contains(*p)) else { |
| 218 | self.wheel_acc = Vec2::ZERO; |
| 219 | return; |
| 220 | }; |
| 221 | // egui(=winit) 휠 delta는 내용이 움직일 방향이다: y>0이면 내용이 아래로 내려가 위쪽이 |
| 222 | // 보인다(휠을 위로 굴림), x>0이면 내용이 오른쪽으로 가 왼쪽이 보인다(왼쪽 스크롤). |
| 223 | // Android AXIS_VSCROLL은 위가 양수, AXIS_HSCROLL은 오른쪽이 양수라 x만 부호를 뒤집는다. |
| 224 | let notches = match unit { |
| 225 | MouseWheelUnit::Line => delta, |
| 226 | MouseWheelUnit::Point => delta / POINTS_PER_NOTCH, |
| 227 | MouseWheelUnit::Page => delta * LINES_PER_PAGE, |
| 228 | }; |
| 229 | self.wheel_acc += Vec2::new(-notches.x, notches.y) * NOTCH; |
| 230 | // 정수 부분만 보내고 남은 소수는 다음 이벤트에 더한다 (터치패드의 작은 이동 보존). |
| 231 | let send = Vec2::new( |
| 232 | self.wheel_acc |
| 233 | .x |
| 234 | .trunc() |
| 235 | .clamp(i16::MIN.into(), i16::MAX.into()), |
| 236 | self.wheel_acc |
| 237 | .y |
| 238 | .trunc() |
| 239 | .clamp(i16::MIN.into(), i16::MAX.into()), |
| 240 | ); |
| 241 | if send == Vec2::ZERO { |
| 242 | return; |
| 243 | } |
| 244 | self.wheel_acc -= send; |
| 245 | let (x, y) = v.to_frame(p); |
| 246 | out.push(Message::ScrollEvent(ScrollEvent { |
| 247 | x, |
| 248 | y, |
| 249 | frame_width: v.width, |
| 250 | frame_height: v.height, |
| 251 | h_scroll: send.x as i16, |
| 252 | v_scroll: send.y as i16, |
| 253 | })); |
| 254 | } |
| 255 | |
| 256 | /// 키 누름을 처리한다. 키 이벤트(또는 시스템 동작)를 보냈으면 true. |
| 257 | fn key_down( |
| 258 | &mut self, |
| 259 | key: Key, |
| 260 | modifiers: Modifiers, |
| 261 | repeat: bool, |
| 262 | next_is_text: bool, |
| 263 | out: &mut Vec<Message>, |
| 264 | ) -> bool { |
| 265 | if let Some(action) = keymap::clipboard_action(key, modifiers) { |
| 266 | if !repeat { |
| 267 | out.push(Message::SystemAction(action)); |
| 268 | } |
| 269 | return true; |
| 270 | } |
| 271 | let keycode = keymap::special_keycode(key) |
| 272 | .or_else(|| keymap::combo_keycode(key, modifiers)) |
| 273 | // 스페이스는 글자를 만들지 않았을 때(Ctrl+Space 등)만 키로 보낸다. |
| 274 | .or_else(|| (key == Key::Space && !next_is_text).then_some(keymap::KEYCODE_SPACE)); |
| 275 | let Some(keycode) = keycode else { |
| 276 | return false; |
| 277 | }; |
| 278 | let held = match self.held_keys.iter_mut().find(|h| h.key == key) { |
| 279 | Some(h) if repeat => { |
| 280 | h.repeat = h.repeat.saturating_add(1); |
| 281 | *h |
| 282 | } |
| 283 | Some(h) => { |
| 284 | *h = HeldKey { |
| 285 | key, |
| 286 | keycode, |
| 287 | repeat: 0, |
| 288 | }; |
| 289 | *h |
| 290 | } |
| 291 | None => { |
| 292 | let h = HeldKey { |
| 293 | key, |
| 294 | keycode, |
| 295 | repeat: 0, |
| 296 | }; |
| 297 | self.held_keys.push(h); |
| 298 | h |
| 299 | } |
| 300 | }; |
| 301 | out.push(key_message( |
| 302 | KeyAction::Down, |
| 303 | held.keycode, |
| 304 | modifiers, |
| 305 | held.repeat, |
| 306 | )); |
| 307 | true |
| 308 | } |
| 309 | |
| 310 | fn key_up(&mut self, key: Key, modifiers: Modifiers, out: &mut Vec<Message>) { |
| 311 | if let Some(i) = self.held_keys.iter().position(|h| h.key == key) { |
| 312 | let h = self.held_keys.remove(i); |
| 313 | out.push(key_message(KeyAction::Up, h.keycode, modifiers, 0)); |
| 314 | } |
| 315 | } |
| 316 | |
| 317 | /// 누르고 있던 키를 모두 뗀다 (창 포커스를 잃으면 뗌 이벤트가 오지 않을 수 있다). |
| 318 | fn release_keys(&mut self, modifiers: Modifiers, out: &mut Vec<Message>) { |
| 319 | for h in self.held_keys.drain(..) { |
| 320 | out.push(key_message(KeyAction::Up, h.keycode, modifiers, 0)); |
| 321 | } |
| 322 | } |
| 323 | } |
| 324 | |
| 325 | fn touch_message(action: TouchAction, (x, y): (u32, u32), frame: (u16, u16)) -> Message { |
| 326 | Message::TouchEvent(TouchEvent { |
| 327 | action, |
| 328 | pointer_id: 0, |
| 329 | x, |
| 330 | y, |
| 331 | frame_width: frame.0, |
| 332 | frame_height: frame.1, |
| 333 | pressure: match action { |
| 334 | TouchAction::Down | TouchAction::Move => FULL_PRESSURE, |
| 335 | TouchAction::Up | TouchAction::Cancel => 0, |
| 336 | }, |
| 337 | }) |
| 338 | } |
| 339 | |
| 340 | fn key_message(action: KeyAction, keycode: u16, modifiers: Modifiers, repeat: u16) -> Message { |
| 341 | Message::KeyEvent(KeyEvent { |
| 342 | action, |
| 343 | keycode, |
| 344 | meta_state: keymap::meta_state(modifiers), |
| 345 | repeat, |
| 346 | scancode: 0, |
| 347 | }) |
| 348 | } |
| 349 | |
| 350 | fn send_text(text: &str, out: &mut Vec<Message>) { |
| 351 | if !text.is_empty() { |
| 352 | out.push(Message::TextInput(TextInput { |
| 353 | text: text.to_owned(), |
| 354 | })); |
| 355 | } |
| 356 | } |
| 357 | |
| 358 | #[cfg(test)] |
| 359 | mod tests { |
| 360 | use super::*; |
| 361 | use egui::{pos2, vec2}; |
| 362 | |
| 363 | fn target() -> VideoTarget { |
| 364 | VideoTarget { |
| 365 | rect: Rect::from_min_size(pos2(40.0, 22.0), vec2(360.0, 640.0)), |
| 366 | width: 1080, |
| 367 | height: 1920, |
| 368 | } |
| 369 | } |
| 370 | |
| 371 | #[test] |
| 372 | fn maps_window_points_to_frame_pixels() { |
| 373 | let v = target(); |
| 374 | assert_eq!(v.to_frame(v.rect.min), (0, 0)); |
| 375 | assert_eq!(v.to_frame(v.rect.center()), (540, 960)); |
| 376 | assert_eq!(v.to_frame(v.rect.max), (1079, 1919)); |
| 377 | assert_eq!(v.to_frame(pos2(0.0, 2000.0)), (0, 1919)); |
| 378 | } |
| 379 | |
| 380 | fn wheel(unit: MouseWheelUnit, delta: Vec2) -> Event { |
| 381 | Event::MouseWheel { |
| 382 | unit, |
| 383 | delta, |
| 384 | phase: egui::TouchPhase::Move, |
| 385 | source: egui::MouseWheelSource::Unknown, |
| 386 | modifiers: Modifiers::NONE, |
| 387 | } |
| 388 | } |
| 389 | |
| 390 | fn scrolls(out: &[Message]) -> Vec<(i16, i16)> { |
| 391 | out.iter() |
| 392 | .filter_map(|m| match m { |
| 393 | Message::ScrollEvent(s) => Some((s.h_scroll, s.v_scroll)), |
| 394 | _ => None, |
| 395 | }) |
| 396 | .collect() |
| 397 | } |
| 398 | |
| 399 | #[test] |
| 400 | fn wheel_units_and_signs() { |
| 401 | let v = target(); |
| 402 | let mut s = InputState::default(); |
| 403 | let mut out = Vec::new(); |
| 404 | let events = [ |
| 405 | Event::PointerMoved(v.rect.center()), |
| 406 | wheel(MouseWheelUnit::Line, vec2(0.0, 1.0)), |
| 407 | wheel(MouseWheelUnit::Line, vec2(1.0, 0.0)), |
| 408 | wheel(MouseWheelUnit::Page, vec2(0.0, -1.0)), |
| 409 | wheel(MouseWheelUnit::Point, vec2(0.0, POINTS_PER_NOTCH)), |
| 410 | ]; |
| 411 | s.process(&events, true, Some(v), &mut out); |
| 412 | assert_eq!(scrolls(&out), [(0, 120), (-120, 0), (0, -360), (0, 120)]); |
| 413 | } |
| 414 | |
| 415 | #[test] |
| 416 | fn small_pixel_deltas_accumulate() { |
| 417 | let v = target(); |
| 418 | let mut s = InputState::default(); |
| 419 | let mut out = Vec::new(); |
| 420 | let step = wheel(MouseWheelUnit::Point, vec2(0.0, 0.2)); |
| 421 | s.process( |
| 422 | &[Event::PointerMoved(v.rect.center())], |
| 423 | true, |
| 424 | Some(v), |
| 425 | &mut out, |
| 426 | ); |
| 427 | for _ in 0..10 { |
| 428 | s.process(std::slice::from_ref(&step), true, Some(v), &mut out); |
| 429 | } |
| 430 | // 0.2pt = 0.48 단위씩 10번 = 4.8 → 정수 부분만 나간다. |
| 431 | let total: i32 = scrolls(&out).iter().map(|&(_, y)| i32::from(y)).sum(); |
| 432 | assert_eq!(total, 4); |
| 433 | } |
| 434 | |
| 435 | #[test] |
| 436 | fn huge_wheel_delta_is_clamped() { |
| 437 | let v = target(); |
| 438 | let mut s = InputState::default(); |
| 439 | let mut out = Vec::new(); |
| 440 | let events = [ |
| 441 | Event::PointerMoved(v.rect.center()), |
| 442 | wheel(MouseWheelUnit::Line, vec2(0.0, 1000.0)), |
| 443 | ]; |
| 444 | s.process(&events, true, Some(v), &mut out); |
| 445 | assert_eq!(scrolls(&out), [(0, i16::MAX)]); |
| 446 | } |
| 447 | |
| 448 | #[test] |
| 449 | fn focus_loss_cancels_touch_and_releases_keys() { |
| 450 | let v = target(); |
| 451 | let mut s = InputState::default(); |
| 452 | let mut out = Vec::new(); |
| 453 | let press = Event::PointerButton { |
| 454 | pos: v.rect.center(), |
| 455 | button: PointerButton::Primary, |
| 456 | pressed: true, |
| 457 | modifiers: Modifiers::NONE, |
| 458 | }; |
| 459 | let enter = Event::Key { |
| 460 | key: Key::Enter, |
| 461 | physical_key: None, |
| 462 | pressed: true, |
| 463 | repeat: false, |
| 464 | modifiers: Modifiers::NONE, |
| 465 | }; |
| 466 | s.process(&[press, enter], true, Some(v), &mut out); |
| 467 | out.clear(); |
| 468 | s.process(&[Event::WindowFocused(false)], true, Some(v), &mut out); |
| 469 | assert!(matches!( |
| 470 | out.as_slice(), |
| 471 | [ |
| 472 | Message::TouchEvent(TouchEvent { |
| 473 | action: TouchAction::Cancel, |
| 474 | .. |
| 475 | }), |
| 476 | Message::KeyEvent(KeyEvent { |
| 477 | action: KeyAction::Up, |
| 478 | keycode: 66, |
| 479 | .. |
| 480 | }), |
| 481 | ] |
| 482 | )); |
| 483 | } |
| 484 | |
| 485 | #[test] |
| 486 | fn lost_target_cancels_touch() { |
| 487 | let v = target(); |
| 488 | let mut s = InputState::default(); |
| 489 | let mut out = Vec::new(); |
| 490 | let press = Event::PointerButton { |
| 491 | pos: v.rect.center(), |
| 492 | button: PointerButton::Primary, |
| 493 | pressed: true, |
| 494 | modifiers: Modifiers::NONE, |
| 495 | }; |
| 496 | s.process(&[press], true, Some(v), &mut out); |
| 497 | out.clear(); |
| 498 | s.process(&[], false, None, &mut out); |
| 499 | assert!(matches!( |
| 500 | out.as_slice(), |
| 501 | [Message::TouchEvent(TouchEvent { |
| 502 | action: TouchAction::Cancel, |
| 503 | x: 540, |
| 504 | y: 960, |
| 505 | .. |
| 506 | })] |
| 507 | )); |
| 508 | } |
| 509 | |
| 510 | #[test] |
| 511 | fn key_repeat_increments_count() { |
| 512 | let mut s = InputState::default(); |
| 513 | let mut out = Vec::new(); |
| 514 | let key = |pressed, repeat| Event::Key { |
| 515 | key: Key::Backspace, |
| 516 | physical_key: None, |
| 517 | pressed, |
| 518 | repeat, |
| 519 | modifiers: Modifiers::NONE, |
| 520 | }; |
| 521 | s.process( |
| 522 | &[ |
| 523 | key(true, false), |
| 524 | key(true, true), |
| 525 | key(true, true), |
| 526 | key(false, false), |
| 527 | ], |
| 528 | true, |
| 529 | None, |
| 530 | &mut out, |
| 531 | ); |
| 532 | let got: Vec<_> = out |
| 533 | .iter() |
| 534 | .map(|m| match m { |
| 535 | Message::KeyEvent(k) => (k.action, k.repeat), |
| 536 | other => panic!("{other:?}"), |
| 537 | }) |
| 538 | .collect(); |
| 539 | assert_eq!( |
| 540 | got, |
| 541 | [ |
| 542 | (KeyAction::Down, 0), |
| 543 | (KeyAction::Down, 1), |
| 544 | (KeyAction::Down, 2), |
| 545 | (KeyAction::Up, 0) |
| 546 | ] |
| 547 | ); |
| 548 | } |
| 549 | |
| 550 | #[test] |
| 551 | fn space_sends_key_only_without_text() { |
| 552 | let mut s = InputState::default(); |
| 553 | let mut out = Vec::new(); |
| 554 | let space = |pressed, modifiers| Event::Key { |
| 555 | key: Key::Space, |
| 556 | physical_key: None, |
| 557 | pressed, |
| 558 | repeat: false, |
| 559 | modifiers, |
| 560 | }; |
| 561 | s.process( |
| 562 | &[ |
| 563 | space(true, Modifiers::NONE), |
| 564 | Event::Text(" ".into()), |
| 565 | space(false, Modifiers::NONE), |
| 566 | ], |
| 567 | true, |
| 568 | None, |
| 569 | &mut out, |
| 570 | ); |
| 571 | assert_eq!(out, [Message::TextInput(TextInput { text: " ".into() })]); |
| 572 | out.clear(); |
| 573 | s.process( |
| 574 | &[space(true, Modifiers::CTRL), space(false, Modifiers::CTRL)], |
| 575 | true, |
| 576 | None, |
| 577 | &mut out, |
| 578 | ); |
| 579 | assert_eq!(out.len(), 2); |
| 580 | assert!(matches!( |
| 581 | out[0], |
| 582 | Message::KeyEvent(KeyEvent { |
| 583 | action: KeyAction::Down, |
| 584 | keycode: keymap::KEYCODE_SPACE, |
| 585 | meta_state: keymap::META_CTRL, |
| 586 | .. |
| 587 | }) |
| 588 | )); |
| 589 | } |
| 590 | |
| 591 | #[test] |
| 592 | fn alt_letter_text_is_not_doubled() { |
| 593 | let mut s = InputState::default(); |
| 594 | let mut out = Vec::new(); |
| 595 | let events = [ |
| 596 | Event::Key { |
| 597 | key: Key::F, |
| 598 | physical_key: None, |
| 599 | pressed: true, |
| 600 | repeat: false, |
| 601 | modifiers: Modifiers::ALT, |
| 602 | }, |
| 603 | Event::Text("f".into()), |
| 604 | ]; |
| 605 | s.process(&events, true, None, &mut out); |
| 606 | assert!(matches!( |
| 607 | out.as_slice(), |
| 608 | [Message::KeyEvent(KeyEvent { |
| 609 | keycode: 34, |
| 610 | meta_state: keymap::META_ALT, |
| 611 | .. |
| 612 | })] |
| 613 | )); |
| 614 | } |
| 615 | } |