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