| 1 | use crossterm_winapi::{ControlKeyState, EventFlags, KeyEventRecord, ScreenBuffer}; |
| 2 | use winapi::um::{ |
| 3 | wincon::{ |
| 4 | CAPSLOCK_ON, LEFT_ALT_PRESSED, LEFT_CTRL_PRESSED, RIGHT_ALT_PRESSED, RIGHT_CTRL_PRESSED, |
| 5 | SHIFT_PRESSED, |
| 6 | }, |
| 7 | winuser::{ |
| 8 | GetForegroundWindow, GetKeyboardLayout, GetWindowThreadProcessId, ToUnicodeEx, VK_BACK, |
| 9 | VK_CONTROL, VK_DELETE, VK_DOWN, VK_END, VK_ESCAPE, VK_F1, VK_F24, VK_HOME, VK_INSERT, |
| 10 | VK_LEFT, VK_MENU, VK_NEXT, VK_NUMPAD0, VK_NUMPAD9, VK_PRIOR, VK_RETURN, VK_RIGHT, VK_SHIFT, |
| 11 | VK_TAB, VK_UP, |
| 12 | }, |
| 13 | }; |
| 14 | |
| 15 | use crate::event::{ |
| 16 | Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers, MouseButton, MouseEvent, MouseEventKind, |
| 17 | }; |
| 18 | |
| 19 | #[derive(Default)] |
| 20 | pub struct MouseButtonsPressed { |
| 21 | pub(crate) left: bool, |
| 22 | pub(crate) right: bool, |
| 23 | pub(crate) middle: bool, |
| 24 | } |
| 25 | |
| 26 | pub(crate) fn handle_mouse_event( |
| 27 | mouse_event: crossterm_winapi::MouseEvent, |
| 28 | buttons_pressed: &MouseButtonsPressed, |
| 29 | ) -> Option<Event> { |
| 30 | if let Ok(Some(event)) = parse_mouse_event_record(&mouse_event, buttons_pressed) { |
| 31 | return Some(Event::Mouse(event)); |
| 32 | } |
| 33 | |
| 34 | None |
| 35 | } |
| 36 | |
| 37 | enum WindowsKeyEvent { |
| 38 | KeyEvent(KeyEvent), |
| 39 | Surrogate(u16), |
| 40 | } |
| 41 | |
| 42 | pub(crate) fn handle_key_event( |
| 43 | key_event: KeyEventRecord, |
| 44 | surrogate_buffer: &mut Option<u16>, |
| 45 | ) -> Option<Event> { |
| 46 | let windows_key_event = parse_key_event_record(&key_event)?; |
| 47 | match windows_key_event { |
| 48 | WindowsKeyEvent::KeyEvent(key_event) => { |
| 49 | // Discard any buffered surrogate value if another valid key event comes before the |
| 50 | // next surrogate value. |
| 51 | *surrogate_buffer = None; |
| 52 | Some(Event::Key(key_event)) |
| 53 | } |
| 54 | WindowsKeyEvent::Surrogate(new_surrogate) => { |
| 55 | let ch = handle_surrogate(surrogate_buffer, new_surrogate)?; |
| 56 | let modifiers = KeyModifiers::from(&key_event.control_key_state); |
| 57 | let key_event = KeyEvent::new(KeyCode::Char(ch), modifiers); |
| 58 | Some(Event::Key(key_event)) |
| 59 | } |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | fn handle_surrogate(surrogate_buffer: &mut Option<u16>, new_surrogate: u16) -> Option<char> { |
| 64 | match *surrogate_buffer { |
| 65 | Some(buffered_surrogate) => { |
| 66 | *surrogate_buffer = None; |
| 67 | std::char::decode_utf16([buffered_surrogate, new_surrogate]) |
| 68 | .next() |
| 69 | .unwrap() |
| 70 | .ok() |
| 71 | } |
| 72 | None => { |
| 73 | *surrogate_buffer = Some(new_surrogate); |
| 74 | None |
| 75 | } |
| 76 | } |
| 77 | } |
| 78 | |
| 79 | impl From<&ControlKeyState> for KeyModifiers { |
| 80 | fn from(state: &ControlKeyState) -> Self { |
| 81 | let shift = state.has_state(SHIFT_PRESSED); |
| 82 | let alt = state.has_state(LEFT_ALT_PRESSED | RIGHT_ALT_PRESSED); |
| 83 | let control = state.has_state(LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED); |
| 84 | |
| 85 | let mut modifier = KeyModifiers::empty(); |
| 86 | |
| 87 | if shift { |
| 88 | modifier |= KeyModifiers::SHIFT; |
| 89 | } |
| 90 | if control { |
| 91 | modifier |= KeyModifiers::CONTROL; |
| 92 | } |
| 93 | if alt { |
| 94 | modifier |= KeyModifiers::ALT; |
| 95 | } |
| 96 | |
| 97 | modifier |
| 98 | } |
| 99 | } |
| 100 | |
| 101 | enum CharCase { |
| 102 | LowerCase, |
| 103 | UpperCase, |
| 104 | } |
| 105 | |
| 106 | fn try_ensure_char_case(ch: char, desired_case: CharCase) -> char { |
| 107 | match desired_case { |
| 108 | CharCase::LowerCase if ch.is_uppercase() => { |
| 109 | let mut iter = ch.to_lowercase(); |
| 110 | // Unwrap is safe; iterator yields one or more chars. |
| 111 | let ch_lower = iter.next().unwrap(); |
| 112 | if iter.next().is_none() { |
| 113 | ch_lower |
| 114 | } else { |
| 115 | ch |
| 116 | } |
| 117 | } |
| 118 | CharCase::UpperCase if ch.is_lowercase() => { |
| 119 | let mut iter = ch.to_uppercase(); |
| 120 | // Unwrap is safe; iterator yields one or more chars. |
| 121 | let ch_upper = iter.next().unwrap(); |
| 122 | if iter.next().is_none() { |
| 123 | ch_upper |
| 124 | } else { |
| 125 | ch |
| 126 | } |
| 127 | } |
| 128 | _ => ch, |
| 129 | } |
| 130 | } |
| 131 | |
| 132 | // Attempts to return the character for a key event accounting for the user's keyboard layout. |
| 133 | // The returned character (if any) is capitalized (if applicable) based on shift and capslock state. |
| 134 | // Returns None if the key doesn't map to a character or if it is a dead key. |
| 135 | // We use the *currently* active keyboard layout (if it can be determined). This layout may not |
| 136 | // correspond to the keyboard layout that was active when the user typed their input, since console |
| 137 | // applications get their input asynchronously from the terminal. By the time a console application |
| 138 | // can process a key input, the user may have changed the active layout. In this case, the character |
| 139 | // returned might not correspond to what the user expects, but there is no way for a console |
| 140 | // application to know what the keyboard layout actually was for a key event, so this is our best |
| 141 | // effort. If a console application processes input in a timely fashion, then it is unlikely that a |
| 142 | // user has time to change their keyboard layout before a key event is processed. |
| 143 | fn get_char_for_key(key_event: &KeyEventRecord) -> Option<char> { |
| 144 | let virtual_key_code = key_event.virtual_key_code as u32; |
| 145 | let virtual_scan_code = key_event.virtual_scan_code as u32; |
| 146 | let key_state = [0u8; 256]; |
| 147 | let mut utf16_buf = [0u16, 16]; |
| 148 | let dont_change_kernel_keyboard_state = 0x4; |
| 149 | |
| 150 | // Best-effort attempt at determining the currently active keyboard layout. |
| 151 | // At the time of writing, this works for a console application running in Windows Terminal, but |
| 152 | // doesn't work under a Conhost terminal. For Conhost, the window handle returned by |
| 153 | // GetForegroundWindow() does not appear to actually be the foreground window which has the |
| 154 | // keyboard layout associated with it (or perhaps it is, but also has special protection that |
| 155 | // doesn't allow us to query it). |
| 156 | // When this determination fails, the returned keyboard layout handle will be null, which is an |
| 157 | // acceptable input for ToUnicodeEx, as that argument is optional. In this case ToUnicodeEx |
| 158 | // appears to use the keyboard layout associated with the current thread, which will be the |
| 159 | // layout that was inherited when the console application started (or possibly when the current |
| 160 | // thread was spawned). This is then unfortunately not updated when the user changes their |
| 161 | // keyboard layout in the terminal, but it's what we get. |
| 162 | let active_keyboard_layout = unsafe { |
| 163 | let foreground_window = GetForegroundWindow(); |
| 164 | let foreground_thread = GetWindowThreadProcessId(foreground_window, std::ptr::null_mut()); |
| 165 | GetKeyboardLayout(foreground_thread) |
| 166 | }; |
| 167 | |
| 168 | let ret = unsafe { |
| 169 | ToUnicodeEx( |
| 170 | virtual_key_code, |
| 171 | virtual_scan_code, |
| 172 | key_state.as_ptr(), |
| 173 | utf16_buf.as_mut_ptr(), |
| 174 | utf16_buf.len() as i32, |
| 175 | dont_change_kernel_keyboard_state, |
| 176 | active_keyboard_layout, |
| 177 | ) |
| 178 | }; |
| 179 | |
| 180 | // -1 indicates a dead key. |
| 181 | // 0 indicates no character for this key. |
| 182 | if ret < 1 { |
| 183 | return None; |
| 184 | } |
| 185 | |
| 186 | let mut ch_iter = std::char::decode_utf16(utf16_buf.into_iter().take(ret as usize)); |
| 187 | let mut ch = ch_iter.next()?.ok()?; |
| 188 | if ch_iter.next().is_some() { |
| 189 | // Key doesn't map to a single char. |
| 190 | return None; |
| 191 | } |
| 192 | |
| 193 | let is_shift_pressed = key_event.control_key_state.has_state(SHIFT_PRESSED); |
| 194 | let is_capslock_on = key_event.control_key_state.has_state(CAPSLOCK_ON); |
| 195 | let desired_case = if is_shift_pressed ^ is_capslock_on { |
| 196 | CharCase::UpperCase |
| 197 | } else { |
| 198 | CharCase::LowerCase |
| 199 | }; |
| 200 | ch = try_ensure_char_case(ch, desired_case); |
| 201 | Some(ch) |
| 202 | } |
| 203 | |
| 204 | fn parse_key_event_record(key_event: &KeyEventRecord) -> Option<WindowsKeyEvent> { |
| 205 | let modifiers = KeyModifiers::from(&key_event.control_key_state); |
| 206 | let virtual_key_code = key_event.virtual_key_code as i32; |
| 207 | |
| 208 | // We normally ignore all key release events, but we will make an exception for an Alt key |
| 209 | // release if it carries a u_char value, as this indicates an Alt code. |
| 210 | let is_alt_code = virtual_key_code == VK_MENU && !key_event.key_down && key_event.u_char != 0; |
| 211 | if is_alt_code { |
| 212 | let utf16 = key_event.u_char; |
| 213 | match utf16 { |
| 214 | surrogate @ 0xD800..=0xDFFF => { |
| 215 | return Some(WindowsKeyEvent::Surrogate(surrogate)); |
| 216 | } |
| 217 | unicode_scalar_value => { |
| 218 | // Unwrap is safe: We tested for surrogate values above and those are the only |
| 219 | // u16 values that are invalid when directly interpreted as unicode scalar |
| 220 | // values. |
| 221 | let ch = std::char::from_u32(unicode_scalar_value as u32).unwrap(); |
| 222 | let key_code = KeyCode::Char(ch); |
| 223 | let kind = if key_event.key_down { |
| 224 | KeyEventKind::Press |
| 225 | } else { |
| 226 | KeyEventKind::Release |
| 227 | }; |
| 228 | let key_event = KeyEvent::new_with_kind(key_code, modifiers, kind); |
| 229 | return Some(WindowsKeyEvent::KeyEvent(key_event)); |
| 230 | } |
| 231 | } |
| 232 | } |
| 233 | |
| 234 | // Don't generate events for numpad key presses when they're producing Alt codes. |
| 235 | let is_numpad_numeric_key = (VK_NUMPAD0..=VK_NUMPAD9).contains(&virtual_key_code); |
| 236 | let is_only_alt_modifier = modifiers.contains(KeyModifiers::ALT) |
| 237 | && !modifiers.contains(KeyModifiers::SHIFT | KeyModifiers::CONTROL); |
| 238 | if is_only_alt_modifier && is_numpad_numeric_key { |
| 239 | return None; |
| 240 | } |
| 241 | |
| 242 | let parse_result = match virtual_key_code { |
| 243 | VK_SHIFT | VK_CONTROL | VK_MENU => None, |
| 244 | VK_BACK => Some(KeyCode::Backspace), |
| 245 | VK_ESCAPE => Some(KeyCode::Esc), |
| 246 | VK_RETURN => Some(KeyCode::Enter), |
| 247 | VK_F1..=VK_F24 => Some(KeyCode::F((key_event.virtual_key_code - 111) as u8)), |
| 248 | VK_LEFT => Some(KeyCode::Left), |
| 249 | VK_UP => Some(KeyCode::Up), |
| 250 | VK_RIGHT => Some(KeyCode::Right), |
| 251 | VK_DOWN => Some(KeyCode::Down), |
| 252 | VK_PRIOR => Some(KeyCode::PageUp), |
| 253 | VK_NEXT => Some(KeyCode::PageDown), |
| 254 | VK_HOME => Some(KeyCode::Home), |
| 255 | VK_END => Some(KeyCode::End), |
| 256 | VK_DELETE => Some(KeyCode::Delete), |
| 257 | VK_INSERT => Some(KeyCode::Insert), |
| 258 | VK_TAB if modifiers.contains(KeyModifiers::SHIFT) => Some(KeyCode::BackTab), |
| 259 | VK_TAB => Some(KeyCode::Tab), |
| 260 | _ => { |
| 261 | let utf16 = key_event.u_char; |
| 262 | match utf16 { |
| 263 | 0x00..=0x1f => { |
| 264 | // Some key combinations generate either no u_char value or generate control |
| 265 | // codes. To deliver back a KeyCode::Char(...) event we want to know which |
| 266 | // character the key normally maps to on the user's keyboard layout. |
| 267 | // The keys that intentionally generate control codes (ESC, ENTER, TAB, etc.) |
| 268 | // are handled by their virtual key codes above. |
| 269 | get_char_for_key(key_event).map(KeyCode::Char) |
| 270 | } |
| 271 | surrogate @ 0xD800..=0xDFFF => { |
| 272 | // Codewhale patch: Windows Terminal sends a key-down and a key-up record |
| 273 | // for each UTF-16 half of a pasted astral character. Pairing a half with |
| 274 | // its own key-up decodes to nothing and drops the character, so only the |
| 275 | // key-down halves take part in surrogate pairing. |
| 276 | if !key_event.key_down { |
| 277 | return None; |
| 278 | } |
| 279 | return Some(WindowsKeyEvent::Surrogate(surrogate)); |
| 280 | } |
| 281 | unicode_scalar_value => { |
| 282 | // Unwrap is safe: We tested for surrogate values above and those are the only |
| 283 | // u16 values that are invalid when directly interpreted as unicode scalar |
| 284 | // values. |
| 285 | let ch = std::char::from_u32(unicode_scalar_value as u32).unwrap(); |
| 286 | Some(KeyCode::Char(ch)) |
| 287 | } |
| 288 | } |
| 289 | } |
| 290 | }; |
| 291 | |
| 292 | if let Some(key_code) = parse_result { |
| 293 | let kind = if key_event.key_down { |
| 294 | KeyEventKind::Press |
| 295 | } else { |
| 296 | KeyEventKind::Release |
| 297 | }; |
| 298 | let key_event = KeyEvent::new_with_kind(key_code, modifiers, kind); |
| 299 | return Some(WindowsKeyEvent::KeyEvent(key_event)); |
| 300 | } |
| 301 | |
| 302 | None |
| 303 | } |
| 304 | |
| 305 | // The 'y' position of a mouse event or resize event is not relative to the window but absolute to screen buffer. |
| 306 | // This means that when the mouse cursor is at the top left it will be x: 0, y: 2295 (e.g. y = number of cells conting from the absolute buffer height) instead of relative x: 0, y: 0 to the window. |
| 307 | pub fn parse_relative_y(y: i16) -> std::io::Result<i16> { |
| 308 | let window_size = ScreenBuffer::current()?.info()?.terminal_window(); |
| 309 | Ok(y - window_size.top) |
| 310 | } |
| 311 | |
| 312 | fn parse_mouse_event_record( |
| 313 | event: &crossterm_winapi::MouseEvent, |
| 314 | buttons_pressed: &MouseButtonsPressed, |
| 315 | ) -> std::io::Result<Option<MouseEvent>> { |
| 316 | let modifiers = KeyModifiers::from(&event.control_key_state); |
| 317 | |
| 318 | let xpos = event.mouse_position.x as u16; |
| 319 | let ypos = parse_relative_y(event.mouse_position.y)? as u16; |
| 320 | |
| 321 | let button_state = event.button_state; |
| 322 | |
| 323 | let kind = match event.event_flags { |
| 324 | EventFlags::PressOrRelease | EventFlags::DoubleClick => { |
| 325 | if button_state.left_button() && !buttons_pressed.left { |
| 326 | Some(MouseEventKind::Down(MouseButton::Left)) |
| 327 | } else if !button_state.left_button() && buttons_pressed.left { |
| 328 | Some(MouseEventKind::Up(MouseButton::Left)) |
| 329 | } else if button_state.right_button() && !buttons_pressed.right { |
| 330 | Some(MouseEventKind::Down(MouseButton::Right)) |
| 331 | } else if !button_state.right_button() && buttons_pressed.right { |
| 332 | Some(MouseEventKind::Up(MouseButton::Right)) |
| 333 | } else if button_state.middle_button() && !buttons_pressed.middle { |
| 334 | Some(MouseEventKind::Down(MouseButton::Middle)) |
| 335 | } else if !button_state.middle_button() && buttons_pressed.middle { |
| 336 | Some(MouseEventKind::Up(MouseButton::Middle)) |
| 337 | } else { |
| 338 | None |
| 339 | } |
| 340 | } |
| 341 | EventFlags::MouseMoved => { |
| 342 | let button = if button_state.right_button() { |
| 343 | MouseButton::Right |
| 344 | } else if button_state.middle_button() { |
| 345 | MouseButton::Middle |
| 346 | } else { |
| 347 | MouseButton::Left |
| 348 | }; |
| 349 | if button_state.release_button() { |
| 350 | Some(MouseEventKind::Moved) |
| 351 | } else { |
| 352 | Some(MouseEventKind::Drag(button)) |
| 353 | } |
| 354 | } |
| 355 | EventFlags::MouseWheeled => { |
| 356 | // Vertical scroll |
| 357 | // from https://docs.microsoft.com/en-us/windows/console/mouse-event-record-str |
| 358 | // if `button_state` is negative then the wheel was rotated backward, toward the user. |
| 359 | if button_state.scroll_down() { |
| 360 | Some(MouseEventKind::ScrollDown) |
| 361 | } else if button_state.scroll_up() { |
| 362 | Some(MouseEventKind::ScrollUp) |
| 363 | } else { |
| 364 | None |
| 365 | } |
| 366 | } |
| 367 | EventFlags::MouseHwheeled => { |
| 368 | if button_state.scroll_left() { |
| 369 | Some(MouseEventKind::ScrollLeft) |
| 370 | } else if button_state.scroll_right() { |
| 371 | Some(MouseEventKind::ScrollRight) |
| 372 | } else { |
| 373 | None |
| 374 | } |
| 375 | } |
| 376 | _ => None, |
| 377 | }; |
| 378 | |
| 379 | Ok(kind.map(|kind| MouseEvent { |
| 380 | kind, |
| 381 | column: xpos, |
| 382 | row: ypos, |
| 383 | modifiers, |
| 384 | })) |
| 385 | } |
| 386 |