Debian Codegraph @

Xtermina/src/parse/windows.rs

raw symbols SCIP
1 // CREDIT (VTE Reader): <https://github.com/wezterm/wezterm/blob/a87358516004a652ad840bc1661bdf65ffc89b43/termwiz/src/input.rs#L676-L885>
2 // I have dropped the legacy Console API handling however and switched to the `AsciiChar` part of
3 // the key record. I suspect that Termwiz may be incorrect here as the Microsoft docs say that the
4 // proper way to read UTF-8 is to use the `A` variant (`ReadConsoleInputA` while WezTerm uses
5 // `ReadConsoleInputW`) to read a byte.
6 //
7 // CREDIT (Console API):
8 // Most legacy input handling comes from crossterm <https://github.com/crossterm-rs/crossterm/blob/4f08595ef4477de2d504dcced24060ed9e3d582a/src/event/sys/windows/parse.rs>
9 // with some bits coming from crossterm-winapi <https://github.com/crossterm-rs/crossterm-winapi/blob/49bc68d73e82374224284baf0ba51ed3a29c0d81/src/structs/input.rs>
10 // The Windows API functions have been converted from winapi to the windows-sys crate.
11
12 use super::*;
13 use windows_sys::Win32::System::Console;
14
15 #[cfg(feature = "windows-legacy")]
16 pub use legacy::cursor_position;
17
18 /// Mode to use for reading Windows input events.
19 ///
20 /// VTE mode asks the Windows console to emit virtual-terminal input and then parses those bytes
21 /// with [`crate::Parser`]. Legacy mode reads `INPUT_RECORD` values from the classic console API and
22 /// translates them directly into [`crate::Event`] values.
23 ///
24 /// [`crate::PlatformTerminal`] uses [`Self::Vte`] by default. The `windows-legacy` feature must be
25 /// enabled to construct a terminal with a custom input reader mode.
26 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
27 pub enum InputReaderMode {
28 /// Read input as virtual-terminal escape sequences.
29 ///
30 /// This is the default mode. It matches Unix terminal input more closely and supports terminal
31 /// protocol responses that arrive as escape sequences.
32 Vte,
33
34 /// Read input through the classic Windows console API.
35 ///
36 /// This mode is available only with the `windows-legacy` feature. It can be useful in console
37 /// environments where virtual-terminal input is unavailable or unreliable.
38 Legacy,
39 }
40
41 impl Parser {
42 pub(crate) fn decode_input_records(&mut self, records: &[Console::INPUT_RECORD]) {
43 for record in records {
44 match record.EventType as u32 {
45 Console::KEY_EVENT => {
46 let record = unsafe { record.Event.KeyEvent };
47 match self.mode {
48 InputReaderMode::Vte => {
49 // This skips 'down's. IIRC Termwiz skips 'down's and Crossterm skips
50 // 'up's. If we skip 'up's we don't seem to get key events at all.
51 if record.bKeyDown == 0 {
52 continue;
53 }
54 let byte = unsafe { record.uChar.AsciiChar } as u8;
55 // The zero byte is sent when the input record is not VT.
56 if byte == 0 {
57 continue;
58 }
59 // `read_console_input` uses `ReadConsoleInputA` so we should treat the
60 // key code as a byte and add it to the buffer.
61 self.buffer.push(byte);
62 }
63 InputReaderMode::Legacy => {
64 #[cfg(feature = "windows-legacy")]
65 if let Some(event) =
66 legacy::handle_key_event(record, &mut self.surrogate_buffer)
67 {
68 self.events.push_back(event);
69 }
70 }
71 }
72 }
73 Console::WINDOW_BUFFER_SIZE_EVENT => {
74 // NOTE: the `WINDOW_BUFFER_SIZE_EVENT` coordinates are one-based, even
75 // though `GetConsoleScreenBufferInfo` is zero-based.
76
77 use crate::{OneBased, WindowSize};
78 let record = unsafe { record.Event.WindowBufferSizeEvent };
79 let Some(rows) = OneBased::new(record.dwSize.Y as u16) else {
80 continue;
81 };
82 let Some(cols) = OneBased::new(record.dwSize.X as u16) else {
83 continue;
84 };
85 self.events.push_back(Event::WindowResized(WindowSize {
86 rows: rows.get(),
87 cols: cols.get(),
88 pixel_width: None,
89 pixel_height: None,
90 }));
91 }
92 Console::FOCUS_EVENT => {
93 #[cfg(feature = "windows-legacy")]
94 self.events
95 .push_back(legacy::handle_focus(unsafe { record.Event.FocusEvent }));
96 }
97 Console::MOUSE_EVENT => {
98 #[cfg(feature = "windows-legacy")]
99 {
100 let record = unsafe { record.Event.MouseEvent };
101 let button_state: legacy::ButtonState = record.dwButtonState.into();
102 let mouse_event =
103 legacy::handle_mouse_event(record, &self.mouse_buttons_pressed);
104 self.mouse_buttons_pressed = legacy::MouseButtonsPressed {
105 left: button_state.left_button(),
106 right: button_state.right_button(),
107 middle: button_state.middle_button(),
108 };
109 if let Some(event) = mouse_event {
110 self.events.push_back(event);
111 }
112 }
113 }
114 _ => (),
115 }
116 }
117 if self.mode == InputReaderMode::Vte {
118 self.process_bytes(false);
119 }
120 }
121 }
122
123 #[cfg(feature = "windows-legacy")]
124 pub(crate) mod legacy {
125 use std::{io, ptr};
126
127 use crate::event::{
128 KeyCode, KeyEvent, KeyEventKind, KeyEventState, Modifiers, MouseButton, MouseEvent,
129 MouseEventKind,
130 };
131 use crate::{Event, OneBased};
132 use windows_sys::Win32::Foundation::{GENERIC_READ, GENERIC_WRITE};
133
134 use windows_sys::Win32::Storage::FileSystem::{
135 CreateFileW, FILE_SHARE_READ, FILE_SHARE_WRITE, OPEN_EXISTING,
136 };
137 use windows_sys::Win32::System::Console::{
138 self, CAPSLOCK_ON, CONSOLE_SCREEN_BUFFER_INFO, DOUBLE_CLICK, FOCUS_EVENT_RECORD,
139 FROM_LEFT_1ST_BUTTON_PRESSED, FROM_LEFT_2ND_BUTTON_PRESSED, FROM_LEFT_3RD_BUTTON_PRESSED,
140 FROM_LEFT_4TH_BUTTON_PRESSED, KEY_EVENT_RECORD, LEFT_ALT_PRESSED, LEFT_CTRL_PRESSED,
141 MOUSE_EVENT_RECORD, MOUSE_HWHEELED, MOUSE_MOVED, MOUSE_WHEELED, RIGHTMOST_BUTTON_PRESSED,
142 RIGHT_ALT_PRESSED, RIGHT_CTRL_PRESSED, SHIFT_PRESSED,
143 };
144 use windows_sys::Win32::UI::Input::KeyboardAndMouse::{
145 GetKeyboardLayout, ToUnicodeEx, VK_BACK, VK_CONTROL, VK_DELETE, VK_DOWN, VK_END, VK_ESCAPE,
146 VK_F1, VK_F24, VK_HOME, VK_INSERT, VK_LEFT, VK_MENU, VK_NEXT, VK_NUMPAD0, VK_NUMPAD9,
147 VK_PRIOR, VK_RETURN, VK_RIGHT, VK_SHIFT, VK_TAB, VK_UP,
148 };
149 use windows_sys::Win32::UI::WindowsAndMessaging::{
150 GetForegroundWindow, GetWindowThreadProcessId,
151 };
152
153 enum WindowsKeyEvent {
154 KeyEvent(KeyEvent),
155 Surrogate(u16),
156 }
157
158 enum CharCase {
159 LowerCase,
160 UpperCase,
161 }
162
163 #[derive(Debug, Default)]
164 pub(crate) struct MouseButtonsPressed {
165 pub(crate) left: bool,
166 pub(crate) right: bool,
167 pub(crate) middle: bool,
168 }
169
170 /// The status of the mouse buttons.
171 /// The least significant bit corresponds to the leftmost mouse button.
172 /// The next least significant bit corresponds to the rightmost mouse button.
173 /// The next bit indicates the next-to-leftmost mouse button.
174 /// The bits then correspond left to right to the mouse buttons.
175 /// A bit is 1 if the button was pressed.
176 ///
177 /// The state can be one of the following:
178 ///
179 /// ```
180 /// # enum __ {
181 /// Release = 0x0000,
182 /// /// The leftmost mouse button.
183 /// FromLeft1stButtonPressed = 0x0001,
184 /// /// The second button from the left.
185 /// FromLeft2ndButtonPressed = 0x0004,
186 /// /// The third button from the left.
187 /// FromLeft3rdButtonPressed = 0x0008,
188 /// /// The fourth button from the left.
189 /// FromLeft4thButtonPressed = 0x0010,
190 /// /// The rightmost mouse button.
191 /// RightmostButtonPressed = 0x0002,
192 /// /// This button state is not recognized.
193 /// Unknown = 0x0021,
194 /// /// The wheel was rotated backward, toward the user.
195 /// /// This is active only for `MOUSE_WHEELED` from `dwEventFlags`.
196 /// Negative = 0x0020,
197 /// # }
198 /// ```
199 ///
200 /// [Ms Docs](https://docs.microsoft.com/en-us/windows/console/mouse-event-record-str#members)
201 #[derive(PartialEq, Debug, Copy, Clone, Eq)]
202 pub(super) struct ButtonState {
203 state: i32,
204 }
205
206 impl From<u32> for ButtonState {
207 #[inline]
208 fn from(event: u32) -> Self {
209 let state = event as i32;
210 ButtonState { state }
211 }
212 }
213
214 impl ButtonState {
215 /// Get whether no buttons are being pressed.
216 fn release_button(&self) -> bool {
217 self.state == 0
218 }
219
220 /// Returns whether the left button was pressed.
221 pub(super) fn left_button(&self) -> bool {
222 self.state as u32 & FROM_LEFT_1ST_BUTTON_PRESSED != 0
223 }
224
225 /// Returns whether the right button was pressed.
226 pub(super) fn right_button(&self) -> bool {
227 self.state as u32
228 & (RIGHTMOST_BUTTON_PRESSED
229 | FROM_LEFT_3RD_BUTTON_PRESSED
230 | FROM_LEFT_4TH_BUTTON_PRESSED)
231 != 0
232 }
233
234 /// Returns whether the right button was pressed.
235 pub(super) fn middle_button(&self) -> bool {
236 self.state as u32 & FROM_LEFT_2ND_BUTTON_PRESSED != 0
237 }
238
239 /// Returns whether there is a down scroll.
240 fn scroll_down(&self) -> bool {
241 self.state < 0
242 }
243
244 /// Returns whether there is a up scroll.
245 fn scroll_up(&self) -> bool {
246 self.state > 0
247 }
248
249 /// Returns whether there is a horizontal scroll to the right.
250 fn scroll_right(&self) -> bool {
251 self.state > 0
252 }
253
254 /// Returns whether there is a horizontal scroll to the left.
255 fn scroll_left(&self) -> bool {
256 self.state < 0
257 }
258 }
259
260 pub(super) fn handle_key_event(
261 key_event: KEY_EVENT_RECORD,
262 surrogate_buffer: &mut Option<u16>,
263 ) -> Option<Event> {
264 let windows_key_event = parse_key_event_record(&key_event)?;
265 match windows_key_event {
266 WindowsKeyEvent::KeyEvent(key_event) => {
267 // Discard any buffered surrogate value if another valid key event comes before the
268 // next surrogate value.
269 *surrogate_buffer = None;
270 Some(Event::Key(key_event))
271 }
272 WindowsKeyEvent::Surrogate(new_surrogate) => {
273 let ch = handle_surrogate(surrogate_buffer, new_surrogate)?;
274 let modifiers = handle_control_key_state(key_event.dwControlKeyState);
275 let key_event = KeyEvent::new(KeyCode::Char(ch), modifiers);
276 Some(Event::Key(key_event))
277 }
278 }
279 }
280
281 pub(super) fn handle_focus(record: FOCUS_EVENT_RECORD) -> Event {
282 if record.bSetFocus > 0 {
283 Event::FocusIn
284 } else {
285 Event::FocusOut
286 }
287 }
288
289 fn parse_key_event_record(key_event: &KEY_EVENT_RECORD) -> Option<WindowsKeyEvent> {
290 let modifiers = handle_control_key_state(key_event.dwControlKeyState);
291 let virtual_key_code = key_event.wVirtualKeyCode as i32;
292
293 // We normally ignore all key release events, but we will make an exception for an Alt key
294 // release if it carries a u_char value, as this indicates an Alt code.
295 let is_alt_code = virtual_key_code == VK_MENU as i32
296 && key_event.bKeyDown != 1
297 && unsafe { key_event.uChar.UnicodeChar } != 0;
298 if is_alt_code {
299 let utf16 = unsafe { key_event.uChar.UnicodeChar };
300 match utf16 {
301 surrogate @ 0xD800..=0xDFFF => {
302 return Some(WindowsKeyEvent::Surrogate(surrogate));
303 }
304 unicode_scalar_value => {
305 // Unwrap is safe: We tested for surrogate values above and those are the only
306 // u16 values that are invalid when directly interpreted as unicode scalar
307 // values.
308 let ch = std::char::from_u32(unicode_scalar_value as u32).unwrap();
309 let key_code = KeyCode::Char(ch);
310 let kind = if key_event.bKeyDown == 1 {
311 KeyEventKind::Press
312 } else {
313 KeyEventKind::Release
314 };
315 let key_event = KeyEvent {
316 code: key_code,
317 modifiers,
318 kind,
319 state: KeyEventState::empty(),
320 };
321 return Some(WindowsKeyEvent::KeyEvent(key_event));
322 }
323 }
324 }
325
326 // Don't generate events for numpad key presses when they're producing Alt codes.
327 let is_numpad_numeric_key = (VK_NUMPAD0..=VK_NUMPAD9).contains(&(virtual_key_code as u16));
328 let is_only_alt_modifier = modifiers.contains(Modifiers::ALT)
329 && !modifiers.contains(Modifiers::SHIFT | Modifiers::CONTROL);
330 if is_only_alt_modifier && is_numpad_numeric_key {
331 return None;
332 }
333
334 let parse_result = match virtual_key_code as u16 {
335 VK_SHIFT | VK_CONTROL | VK_MENU => None,
336 VK_BACK => Some(KeyCode::Backspace),
337 VK_ESCAPE => Some(KeyCode::Escape),
338 VK_RETURN => Some(KeyCode::Enter),
339 VK_F1..=VK_F24 => Some(KeyCode::Function((key_event.wVirtualKeyCode - 111) as u8)),
340 VK_LEFT => Some(KeyCode::Left),
341 VK_UP => Some(KeyCode::Up),
342 VK_RIGHT => Some(KeyCode::Right),
343 VK_DOWN => Some(KeyCode::Down),
344 VK_PRIOR => Some(KeyCode::PageUp),
345 VK_NEXT => Some(KeyCode::PageDown),
346 VK_HOME => Some(KeyCode::Home),
347 VK_END => Some(KeyCode::End),
348 VK_DELETE => Some(KeyCode::Delete),
349 VK_INSERT => Some(KeyCode::Insert),
350 VK_TAB if modifiers.contains(Modifiers::SHIFT) => Some(KeyCode::BackTab),
351 VK_TAB => Some(KeyCode::Tab),
352 _ => {
353 let utf16 = unsafe { key_event.uChar.UnicodeChar };
354 match utf16 {
355 0x00..=0x1f => {
356 // Some key combinations generate either no u_char value or generate control
357 // codes. To deliver back a KeyCode::Char(...) event we want to know which
358 // character the key normally maps to on the user's keyboard layout.
359 // The keys that intentionally generate control codes (ESC, ENTER, TAB, etc.)
360 // are handled by their virtual key codes above.
361 get_char_for_key(key_event).map(KeyCode::Char)
362 }
363 surrogate @ 0xD800..=0xDFFF => {
364 return Some(WindowsKeyEvent::Surrogate(surrogate));
365 }
366 unicode_scalar_value => {
367 // Unwrap is safe: We tested for surrogate values above and those are the only
368 // u16 values that are invalid when directly interpreted as unicode scalar
369 // values.
370 let ch = std::char::from_u32(unicode_scalar_value as u32).unwrap();
371 Some(KeyCode::Char(ch))
372 }
373 }
374 }
375 };
376
377 if let Some(key_code) = parse_result {
378 let kind = if key_event.bKeyDown == 1 {
379 KeyEventKind::Press
380 } else {
381 KeyEventKind::Release
382 };
383 let key_event = KeyEvent {
384 code: key_code,
385 modifiers,
386 kind,
387 state: KeyEventState::empty(),
388 };
389 return Some(WindowsKeyEvent::KeyEvent(key_event));
390 }
391
392 None
393 }
394
395 fn handle_surrogate(surrogate_buffer: &mut Option<u16>, new_surrogate: u16) -> Option<char> {
396 match *surrogate_buffer {
397 Some(buffered_surrogate) => {
398 *surrogate_buffer = None;
399 std::char::decode_utf16([buffered_surrogate, new_surrogate])
400 .next()
401 .unwrap()
402 .ok()
403 }
404 None => {
405 *surrogate_buffer = Some(new_surrogate);
406 None
407 }
408 }
409 }
410
411 fn handle_control_key_state(state: u32) -> Modifiers {
412 let mut modifier = Modifiers::empty();
413
414 if has_state(state, SHIFT_PRESSED) {
415 modifier |= Modifiers::SHIFT;
416 }
417 if has_state(state, LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED) {
418 modifier |= Modifiers::CONTROL;
419 }
420 if has_state(state, LEFT_ALT_PRESSED | RIGHT_ALT_PRESSED) {
421 modifier |= Modifiers::ALT;
422 }
423
424 modifier
425 }
426
427 fn has_state(a: u32, b: u32) -> bool {
428 (a & b) != 0
429 }
430
431 // Attempts to return the character for a key event accounting for the user's keyboard layout.
432 // The returned character (if any) is capitalized (if applicable) based on shift and capslock state.
433 // Returns None if the key doesn't map to a character or if it is a dead key.
434 // We use the *currently* active keyboard layout (if it can be determined). This layout may not
435 // correspond to the keyboard layout that was active when the user typed their input, since console
436 // applications get their input asynchronously from the terminal. By the time a console application
437 // can process a key input, the user may have changed the active layout. In this case, the character
438 // returned might not correspond to what the user expects, but there is no way for a console
439 // application to know what the keyboard layout actually was for a key event, so this is our best
440 // effort. If a console application processes input in a timely fashion, then it is unlikely that a
441 // user has time to change their keyboard layout before a key event is processed.
442 fn get_char_for_key(key_event: &KEY_EVENT_RECORD) -> Option<char> {
443 let virtual_key_code = key_event.wVirtualKeyCode as u32;
444 let virtual_scan_code = key_event.wVirtualScanCode as u32;
445 let key_state = [0u8; 256];
446 let mut utf16_buf = [0u16, 16];
447 let dont_change_kernel_keyboard_state = 0x4;
448
449 // Best-effort attempt at determining the currently active keyboard layout.
450 // At the time of writing, this works for a console application running in Windows Terminal, but
451 // doesn't work under a Conhost terminal. For Conhost, the window handle returned by
452 // GetForegroundWindow() does not appear to actually be the foreground window which has the
453 // keyboard layout associated with it (or perhaps it is, but also has special protection that
454 // doesn't allow us to query it).
455 // When this determination fails, the returned keyboard layout handle will be null, which is an
456 // acceptable input for ToUnicodeEx, as that argument is optional. In this case ToUnicodeEx
457 // appears to use the keyboard layout associated with the current thread, which will be the
458 // layout that was inherited when the console application started (or possibly when the current
459 // thread was spawned). This is then unfortunately not updated when the user changes their
460 // keyboard layout in the terminal, but it's what we get.
461 let active_keyboard_layout = unsafe {
462 let foreground_window = GetForegroundWindow();
463 let foreground_thread =
464 GetWindowThreadProcessId(foreground_window, std::ptr::null_mut());
465 GetKeyboardLayout(foreground_thread)
466 };
467
468 let ret = unsafe {
469 ToUnicodeEx(
470 virtual_key_code,
471 virtual_scan_code,
472 key_state.as_ptr(),
473 utf16_buf.as_mut_ptr(),
474 utf16_buf.len() as i32,
475 dont_change_kernel_keyboard_state,
476 active_keyboard_layout,
477 )
478 };
479
480 // -1 indicates a dead key.
481 // 0 indicates no character for this key.
482 if ret < 1 {
483 return None;
484 }
485
486 let mut ch_iter = std::char::decode_utf16(utf16_buf.into_iter().take(ret as usize));
487 let mut ch = ch_iter.next()?.ok()?;
488 if ch_iter.next().is_some() {
489 // Key doesn't map to a single char.
490 return None;
491 }
492
493 let is_shift_pressed = has_state(key_event.dwControlKeyState, SHIFT_PRESSED);
494 let is_capslock_on = has_state(key_event.dwControlKeyState, CAPSLOCK_ON);
495 let desired_case = if is_shift_pressed ^ is_capslock_on {
496 CharCase::UpperCase
497 } else {
498 CharCase::LowerCase
499 };
500 ch = try_ensure_char_case(ch, desired_case);
501 Some(ch)
502 }
503
504 fn try_ensure_char_case(ch: char, desired_case: CharCase) -> char {
505 match desired_case {
506 CharCase::LowerCase if ch.is_uppercase() => {
507 let mut iter = ch.to_lowercase();
508 // Unwrap is safe; iterator yields one or more chars.
509 let ch_lower = iter.next().unwrap();
510 if iter.next().is_none() {
511 ch_lower
512 } else {
513 ch
514 }
515 }
516 CharCase::UpperCase if ch.is_lowercase() => {
517 let mut iter = ch.to_uppercase();
518 // Unwrap is safe; iterator yields one or more chars.
519 let ch_upper = iter.next().unwrap();
520 if iter.next().is_none() {
521 ch_upper
522 } else {
523 ch
524 }
525 }
526 _ => ch,
527 }
528 }
529
530 pub(super) fn handle_mouse_event(
531 mouse_event: Console::MOUSE_EVENT_RECORD,
532 buttons_pressed: &MouseButtonsPressed,
533 ) -> Option<Event> {
534 if let Ok(Some(event)) = parse_mouse_event_record(&mouse_event, buttons_pressed) {
535 return Some(Event::Mouse(event));
536 }
537
538 None
539 }
540
541 fn screen_buffer() -> CONSOLE_SCREEN_BUFFER_INFO {
542 unsafe {
543 let utf16: Vec<u16> = "CONOUT$\0".encode_utf16().collect();
544 let utf16_ptr: *const u16 = utf16.as_ptr();
545
546 let handle = CreateFileW(
547 utf16_ptr,
548 GENERIC_READ | GENERIC_WRITE,
549 FILE_SHARE_READ | FILE_SHARE_WRITE,
550 ptr::null_mut(),
551 OPEN_EXISTING,
552 0,
553 ptr::null_mut(),
554 );
555
556 let mut buffer_info = CONSOLE_SCREEN_BUFFER_INFO::default();
557 Console::GetConsoleScreenBufferInfo(handle, &mut buffer_info);
558 buffer_info
559 }
560 }
561
562 // The 'y' position of a mouse event or resize event is not relative to the window but absolute to screen buffer.
563 // 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 counting from the absolute buffer height) instead of relative x: 0, y: 0 to the window.
564 fn parse_relative_y(y: i16) -> std::io::Result<i16> {
565 let window_size = screen_buffer().srWindow;
566 Ok(y - window_size.Top)
567 }
568
569 pub fn cursor_position() -> io::Result<(OneBased, OneBased)> {
570 let buffer = screen_buffer();
571 let position = buffer.dwCursorPosition;
572 Ok((
573 OneBased::from_zero_based(position.X as u16),
574 OneBased::from_zero_based((position.Y - buffer.srWindow.Top) as u16),
575 ))
576 }
577
578 fn parse_mouse_event_record(
579 event: &MOUSE_EVENT_RECORD,
580 buttons_pressed: &MouseButtonsPressed,
581 ) -> std::io::Result<Option<MouseEvent>> {
582 let modifiers = handle_control_key_state(event.dwControlKeyState);
583
584 let xpos = event.dwMousePosition.X as u16;
585 let ypos = parse_relative_y(event.dwMousePosition.Y)? as u16;
586
587 let button_state: ButtonState = event.dwButtonState.into();
588
589 let kind = match event.dwEventFlags {
590 0x0000 | DOUBLE_CLICK => {
591 if button_state.left_button() && !buttons_pressed.left {
592 Some(MouseEventKind::Down(MouseButton::Left))
593 } else if !button_state.left_button() && buttons_pressed.left {
594 Some(MouseEventKind::Up(MouseButton::Left))
595 } else if button_state.right_button() && !buttons_pressed.right {
596 Some(MouseEventKind::Down(MouseButton::Right))
597 } else if !button_state.right_button() && buttons_pressed.right {
598 Some(MouseEventKind::Up(MouseButton::Right))
599 } else if button_state.middle_button() && !buttons_pressed.middle {
600 Some(MouseEventKind::Down(MouseButton::Middle))
601 } else if !button_state.middle_button() && buttons_pressed.middle {
602 Some(MouseEventKind::Up(MouseButton::Middle))
603 } else {
604 None
605 }
606 }
607 MOUSE_MOVED => {
608 let button = if button_state.right_button() {
609 MouseButton::Right
610 } else if button_state.middle_button() {
611 MouseButton::Middle
612 } else {
613 MouseButton::Left
614 };
615 if button_state.release_button() {
616 Some(MouseEventKind::Moved)
617 } else {
618 Some(MouseEventKind::Drag(button))
619 }
620 }
621 MOUSE_WHEELED => {
622 // Vertical scroll
623 // from https://docs.microsoft.com/en-us/windows/console/mouse-event-record-str
624 // if `button_state` is negative then the wheel was rotated backward, toward the user.
625 if button_state.scroll_down() {
626 Some(MouseEventKind::ScrollDown)
627 } else if button_state.scroll_up() {
628 Some(MouseEventKind::ScrollUp)
629 } else {
630 None
631 }
632 }
633 MOUSE_HWHEELED => {
634 if button_state.scroll_left() {
635 Some(MouseEventKind::ScrollLeft)
636 } else if button_state.scroll_right() {
637 Some(MouseEventKind::ScrollRight)
638 } else {
639 None
640 }
641 }
642 _ => None,
643 };
644
645 Ok(kind.map(|kind| MouseEvent {
646 kind,
647 column: xpos,
648 row: ypos,
649 modifiers,
650 }))
651 }
652 }