events.rs

   1use std::rc::Rc;
   2
   3use ::util::ResultExt;
   4use anyhow::Context;
   5use windows::Win32::{
   6    Foundation::*,
   7    Graphics::Gdi::*,
   8    System::SystemServices::*,
   9    UI::{
  10        HiDpi::*,
  11        Input::{Ime::*, KeyboardAndMouse::*},
  12        WindowsAndMessaging::*,
  13    },
  14};
  15
  16use crate::*;
  17
  18pub(crate) const CURSOR_STYLE_CHANGED: u32 = WM_USER + 1;
  19pub(crate) const CLOSE_ONE_WINDOW: u32 = WM_USER + 2;
  20
  21const SIZE_MOVE_LOOP_TIMER_ID: usize = 1;
  22
  23pub(crate) fn handle_msg(
  24    handle: HWND,
  25    msg: u32,
  26    wparam: WPARAM,
  27    lparam: LPARAM,
  28    state_ptr: Rc<WindowsWindowStatePtr>,
  29) -> LRESULT {
  30    let handled = match msg {
  31        WM_ACTIVATE => handle_activate_msg(handle, wparam, state_ptr),
  32        WM_CREATE => handle_create_msg(handle, state_ptr),
  33        WM_MOVE => handle_move_msg(handle, lparam, state_ptr),
  34        WM_SIZE => handle_size_msg(lparam, state_ptr),
  35        WM_ENTERSIZEMOVE | WM_ENTERMENULOOP => handle_size_move_loop(handle),
  36        WM_EXITSIZEMOVE | WM_EXITMENULOOP => handle_size_move_loop_exit(handle),
  37        WM_TIMER => handle_timer_msg(handle, wparam, state_ptr),
  38        WM_NCCALCSIZE => handle_calc_client_size(handle, wparam, lparam, state_ptr),
  39        WM_DPICHANGED => handle_dpi_changed_msg(handle, wparam, lparam, state_ptr),
  40        WM_DISPLAYCHANGE => handle_display_change_msg(handle, state_ptr),
  41        WM_NCHITTEST => handle_hit_test_msg(handle, msg, wparam, lparam, state_ptr),
  42        WM_PAINT => handle_paint_msg(handle, state_ptr),
  43        WM_CLOSE => handle_close_msg(state_ptr),
  44        WM_DESTROY => handle_destroy_msg(handle, state_ptr),
  45        WM_MOUSEMOVE => handle_mouse_move_msg(lparam, wparam, state_ptr),
  46        WM_NCMOUSEMOVE => handle_nc_mouse_move_msg(handle, lparam, state_ptr),
  47        WM_NCLBUTTONDOWN => {
  48            handle_nc_mouse_down_msg(handle, MouseButton::Left, wparam, lparam, state_ptr)
  49        }
  50        WM_NCRBUTTONDOWN => {
  51            handle_nc_mouse_down_msg(handle, MouseButton::Right, wparam, lparam, state_ptr)
  52        }
  53        WM_NCMBUTTONDOWN => {
  54            handle_nc_mouse_down_msg(handle, MouseButton::Middle, wparam, lparam, state_ptr)
  55        }
  56        WM_NCLBUTTONUP => {
  57            handle_nc_mouse_up_msg(handle, MouseButton::Left, wparam, lparam, state_ptr)
  58        }
  59        WM_NCRBUTTONUP => {
  60            handle_nc_mouse_up_msg(handle, MouseButton::Right, wparam, lparam, state_ptr)
  61        }
  62        WM_NCMBUTTONUP => {
  63            handle_nc_mouse_up_msg(handle, MouseButton::Middle, wparam, lparam, state_ptr)
  64        }
  65        WM_LBUTTONDOWN => handle_mouse_down_msg(handle, MouseButton::Left, lparam, state_ptr),
  66        WM_RBUTTONDOWN => handle_mouse_down_msg(handle, MouseButton::Right, lparam, state_ptr),
  67        WM_MBUTTONDOWN => handle_mouse_down_msg(handle, MouseButton::Middle, lparam, state_ptr),
  68        WM_XBUTTONDOWN => {
  69            handle_xbutton_msg(handle, wparam, lparam, handle_mouse_down_msg, state_ptr)
  70        }
  71        WM_LBUTTONUP => handle_mouse_up_msg(handle, MouseButton::Left, lparam, state_ptr),
  72        WM_RBUTTONUP => handle_mouse_up_msg(handle, MouseButton::Right, lparam, state_ptr),
  73        WM_MBUTTONUP => handle_mouse_up_msg(handle, MouseButton::Middle, lparam, state_ptr),
  74        WM_XBUTTONUP => handle_xbutton_msg(handle, wparam, lparam, handle_mouse_up_msg, state_ptr),
  75        WM_MOUSEWHEEL => handle_mouse_wheel_msg(handle, wparam, lparam, state_ptr),
  76        WM_MOUSEHWHEEL => handle_mouse_horizontal_wheel_msg(handle, wparam, lparam, state_ptr),
  77        WM_SYSKEYDOWN => handle_syskeydown_msg(wparam, lparam, state_ptr),
  78        WM_SYSKEYUP => handle_syskeyup_msg(wparam, state_ptr),
  79        WM_KEYDOWN => handle_keydown_msg(wparam, lparam, state_ptr),
  80        WM_KEYUP => handle_keyup_msg(wparam, state_ptr),
  81        WM_CHAR => handle_char_msg(wparam, lparam, state_ptr),
  82        WM_IME_STARTCOMPOSITION => handle_ime_position(handle, state_ptr),
  83        WM_IME_COMPOSITION => handle_ime_composition(handle, lparam, state_ptr),
  84        WM_SETCURSOR => handle_set_cursor(lparam, state_ptr),
  85        WM_SETTINGCHANGE => handle_system_settings_changed(state_ptr),
  86        CURSOR_STYLE_CHANGED => handle_cursor_changed(lparam, state_ptr),
  87        _ => None,
  88    };
  89    if let Some(n) = handled {
  90        LRESULT(n)
  91    } else {
  92        unsafe { DefWindowProcW(handle, msg, wparam, lparam) }
  93    }
  94}
  95
  96fn handle_move_msg(
  97    handle: HWND,
  98    lparam: LPARAM,
  99    state_ptr: Rc<WindowsWindowStatePtr>,
 100) -> Option<isize> {
 101    let mut lock = state_ptr.state.borrow_mut();
 102    let origin = logical_point(
 103        lparam.signed_loword() as f32,
 104        lparam.signed_hiword() as f32,
 105        lock.scale_factor,
 106    );
 107    lock.origin = origin;
 108    let size = lock.logical_size;
 109    let center_x = origin.x.0 + size.width.0 / 2.;
 110    let center_y = origin.y.0 + size.height.0 / 2.;
 111    let monitor_bounds = lock.display.bounds();
 112    if center_x < monitor_bounds.left().0
 113        || center_x > monitor_bounds.right().0
 114        || center_y < monitor_bounds.top().0
 115        || center_y > monitor_bounds.bottom().0
 116    {
 117        // center of the window may have moved to another monitor
 118        let monitor = unsafe { MonitorFromWindow(handle, MONITOR_DEFAULTTONULL) };
 119        // minimize the window can trigger this event too, in this case,
 120        // monitor is invalid, we do nothing.
 121        if !monitor.is_invalid() && lock.display.handle != monitor {
 122            // we will get the same monitor if we only have one
 123            lock.display = WindowsDisplay::new_with_handle(monitor);
 124        }
 125    }
 126    if let Some(mut callback) = lock.callbacks.moved.take() {
 127        drop(lock);
 128        callback();
 129        state_ptr.state.borrow_mut().callbacks.moved = Some(callback);
 130    }
 131    Some(0)
 132}
 133
 134fn handle_size_msg(lparam: LPARAM, state_ptr: Rc<WindowsWindowStatePtr>) -> Option<isize> {
 135    let width = lparam.loword().max(1) as i32;
 136    let height = lparam.hiword().max(1) as i32;
 137    let mut lock = state_ptr.state.borrow_mut();
 138    let new_size = size(DevicePixels(width), DevicePixels(height));
 139    let scale_factor = lock.scale_factor;
 140    lock.renderer.update_drawable_size(new_size);
 141    let new_size = new_size.to_pixels(scale_factor);
 142    lock.logical_size = new_size;
 143    if let Some(mut callback) = lock.callbacks.resize.take() {
 144        drop(lock);
 145        callback(new_size, scale_factor);
 146        state_ptr.state.borrow_mut().callbacks.resize = Some(callback);
 147    }
 148    Some(0)
 149}
 150
 151fn handle_size_move_loop(handle: HWND) -> Option<isize> {
 152    unsafe {
 153        let ret = SetTimer(handle, SIZE_MOVE_LOOP_TIMER_ID, USER_TIMER_MINIMUM, None);
 154        if ret == 0 {
 155            log::error!(
 156                "unable to create timer: {}",
 157                std::io::Error::last_os_error()
 158            );
 159        }
 160    }
 161    None
 162}
 163
 164fn handle_size_move_loop_exit(handle: HWND) -> Option<isize> {
 165    unsafe {
 166        KillTimer(handle, SIZE_MOVE_LOOP_TIMER_ID).log_err();
 167    }
 168    None
 169}
 170
 171fn handle_timer_msg(
 172    handle: HWND,
 173    wparam: WPARAM,
 174    state_ptr: Rc<WindowsWindowStatePtr>,
 175) -> Option<isize> {
 176    if wparam.0 == SIZE_MOVE_LOOP_TIMER_ID {
 177        handle_paint_msg(handle, state_ptr)
 178    } else {
 179        None
 180    }
 181}
 182
 183fn handle_paint_msg(handle: HWND, state_ptr: Rc<WindowsWindowStatePtr>) -> Option<isize> {
 184    let mut lock = state_ptr.state.borrow_mut();
 185    if let Some(mut request_frame) = lock.callbacks.request_frame.take() {
 186        drop(lock);
 187        request_frame();
 188        state_ptr.state.borrow_mut().callbacks.request_frame = Some(request_frame);
 189    }
 190    unsafe { ValidateRect(handle, None).ok().log_err() };
 191    Some(0)
 192}
 193
 194fn handle_close_msg(state_ptr: Rc<WindowsWindowStatePtr>) -> Option<isize> {
 195    let mut lock = state_ptr.state.borrow_mut();
 196    if let Some(mut callback) = lock.callbacks.should_close.take() {
 197        drop(lock);
 198        let should_close = callback();
 199        state_ptr.state.borrow_mut().callbacks.should_close = Some(callback);
 200        if should_close {
 201            None
 202        } else {
 203            Some(0)
 204        }
 205    } else {
 206        None
 207    }
 208}
 209
 210fn handle_destroy_msg(handle: HWND, state_ptr: Rc<WindowsWindowStatePtr>) -> Option<isize> {
 211    let callback = {
 212        let mut lock = state_ptr.state.borrow_mut();
 213        lock.callbacks.close.take()
 214    };
 215    if let Some(callback) = callback {
 216        callback();
 217    }
 218    unsafe {
 219        PostMessageW(None, CLOSE_ONE_WINDOW, None, LPARAM(handle.0)).log_err();
 220    }
 221    Some(0)
 222}
 223
 224fn handle_mouse_move_msg(
 225    lparam: LPARAM,
 226    wparam: WPARAM,
 227    state_ptr: Rc<WindowsWindowStatePtr>,
 228) -> Option<isize> {
 229    let mut lock = state_ptr.state.borrow_mut();
 230    if let Some(mut callback) = lock.callbacks.input.take() {
 231        let scale_factor = lock.scale_factor;
 232        drop(lock);
 233        let pressed_button = match MODIFIERKEYS_FLAGS(wparam.loword() as u32) {
 234            flags if flags.contains(MK_LBUTTON) => Some(MouseButton::Left),
 235            flags if flags.contains(MK_RBUTTON) => Some(MouseButton::Right),
 236            flags if flags.contains(MK_MBUTTON) => Some(MouseButton::Middle),
 237            flags if flags.contains(MK_XBUTTON1) => {
 238                Some(MouseButton::Navigate(NavigationDirection::Back))
 239            }
 240            flags if flags.contains(MK_XBUTTON2) => {
 241                Some(MouseButton::Navigate(NavigationDirection::Forward))
 242            }
 243            _ => None,
 244        };
 245        let x = lparam.signed_loword() as f32;
 246        let y = lparam.signed_hiword() as f32;
 247        let event = MouseMoveEvent {
 248            position: logical_point(x, y, scale_factor),
 249            pressed_button,
 250            modifiers: current_modifiers(),
 251        };
 252        let result = if callback(PlatformInput::MouseMove(event)).default_prevented {
 253            Some(0)
 254        } else {
 255            Some(1)
 256        };
 257        state_ptr.state.borrow_mut().callbacks.input = Some(callback);
 258        return result;
 259    }
 260    Some(1)
 261}
 262
 263fn handle_syskeydown_msg(
 264    wparam: WPARAM,
 265    lparam: LPARAM,
 266    state_ptr: Rc<WindowsWindowStatePtr>,
 267) -> Option<isize> {
 268    // we need to call `DefWindowProcW`, or we will lose the system-wide `Alt+F4`, `Alt+{other keys}`
 269    // shortcuts.
 270    let Some(keystroke) = parse_syskeydown_msg_keystroke(wparam) else {
 271        return None;
 272    };
 273    let mut lock = state_ptr.state.borrow_mut();
 274    let Some(mut func) = lock.callbacks.input.take() else {
 275        return None;
 276    };
 277    drop(lock);
 278    let event = KeyDownEvent {
 279        keystroke,
 280        is_held: lparam.0 & (0x1 << 30) > 0,
 281    };
 282    let result = if func(PlatformInput::KeyDown(event)).default_prevented {
 283        Some(0)
 284    } else {
 285        None
 286    };
 287    state_ptr.state.borrow_mut().callbacks.input = Some(func);
 288
 289    result
 290}
 291
 292fn handle_syskeyup_msg(wparam: WPARAM, state_ptr: Rc<WindowsWindowStatePtr>) -> Option<isize> {
 293    // we need to call `DefWindowProcW`, or we will lose the system-wide `Alt+F4`, `Alt+{other keys}`
 294    // shortcuts.
 295    let Some(keystroke) = parse_syskeydown_msg_keystroke(wparam) else {
 296        return None;
 297    };
 298    let mut lock = state_ptr.state.borrow_mut();
 299    let Some(mut func) = lock.callbacks.input.take() else {
 300        return None;
 301    };
 302    drop(lock);
 303    let event = KeyUpEvent { keystroke };
 304    let result = if func(PlatformInput::KeyUp(event)).default_prevented {
 305        Some(0)
 306    } else {
 307        Some(1)
 308    };
 309    state_ptr.state.borrow_mut().callbacks.input = Some(func);
 310
 311    result
 312}
 313
 314fn handle_keydown_msg(
 315    wparam: WPARAM,
 316    lparam: LPARAM,
 317    state_ptr: Rc<WindowsWindowStatePtr>,
 318) -> Option<isize> {
 319    let Some(keystroke_or_modifier) = parse_keydown_msg_keystroke(wparam) else {
 320        return Some(1);
 321    };
 322    let mut lock = state_ptr.state.borrow_mut();
 323    let Some(mut func) = lock.callbacks.input.take() else {
 324        return Some(1);
 325    };
 326    drop(lock);
 327
 328    let event = match keystroke_or_modifier {
 329        KeystrokeOrModifier::Keystroke(keystroke) => PlatformInput::KeyDown(KeyDownEvent {
 330            keystroke,
 331            is_held: lparam.0 & (0x1 << 30) > 0,
 332        }),
 333        KeystrokeOrModifier::Modifier(modifiers) => {
 334            PlatformInput::ModifiersChanged(ModifiersChangedEvent { modifiers })
 335        }
 336    };
 337
 338    let result = if func(event).default_prevented {
 339        Some(0)
 340    } else {
 341        Some(1)
 342    };
 343    state_ptr.state.borrow_mut().callbacks.input = Some(func);
 344
 345    result
 346}
 347
 348fn handle_keyup_msg(wparam: WPARAM, state_ptr: Rc<WindowsWindowStatePtr>) -> Option<isize> {
 349    let Some(keystroke_or_modifier) = parse_keydown_msg_keystroke(wparam) else {
 350        return Some(1);
 351    };
 352    let mut lock = state_ptr.state.borrow_mut();
 353    let Some(mut func) = lock.callbacks.input.take() else {
 354        return Some(1);
 355    };
 356    drop(lock);
 357
 358    let event = match keystroke_or_modifier {
 359        KeystrokeOrModifier::Keystroke(keystroke) => PlatformInput::KeyUp(KeyUpEvent { keystroke }),
 360        KeystrokeOrModifier::Modifier(modifiers) => {
 361            PlatformInput::ModifiersChanged(ModifiersChangedEvent { modifiers })
 362        }
 363    };
 364
 365    let result = if func(event).default_prevented {
 366        Some(0)
 367    } else {
 368        Some(1)
 369    };
 370    state_ptr.state.borrow_mut().callbacks.input = Some(func);
 371
 372    result
 373}
 374
 375fn handle_char_msg(
 376    wparam: WPARAM,
 377    lparam: LPARAM,
 378    state_ptr: Rc<WindowsWindowStatePtr>,
 379) -> Option<isize> {
 380    let Some(keystroke) = parse_char_msg_keystroke(wparam) else {
 381        return Some(1);
 382    };
 383    let mut lock = state_ptr.state.borrow_mut();
 384    let Some(mut func) = lock.callbacks.input.take() else {
 385        return Some(1);
 386    };
 387    drop(lock);
 388    let ime_key = keystroke.ime_key.clone();
 389    let event = KeyDownEvent {
 390        keystroke,
 391        is_held: lparam.0 & (0x1 << 30) > 0,
 392    };
 393
 394    let dispatch_event_result = func(PlatformInput::KeyDown(event));
 395    let mut lock = state_ptr.state.borrow_mut();
 396    lock.callbacks.input = Some(func);
 397    if dispatch_event_result.default_prevented || !dispatch_event_result.propagate {
 398        return Some(0);
 399    }
 400    let Some(ime_char) = ime_key else {
 401        return Some(1);
 402    };
 403    let Some(mut input_handler) = lock.input_handler.take() else {
 404        return Some(1);
 405    };
 406    drop(lock);
 407    input_handler.replace_text_in_range(None, &ime_char);
 408    state_ptr.state.borrow_mut().input_handler = Some(input_handler);
 409
 410    Some(0)
 411}
 412
 413fn handle_mouse_down_msg(
 414    handle: HWND,
 415    button: MouseButton,
 416    lparam: LPARAM,
 417    state_ptr: Rc<WindowsWindowStatePtr>,
 418) -> Option<isize> {
 419    unsafe { SetCapture(handle) };
 420    let mut lock = state_ptr.state.borrow_mut();
 421    if let Some(mut callback) = lock.callbacks.input.take() {
 422        let x = lparam.signed_loword() as f32;
 423        let y = lparam.signed_hiword() as f32;
 424        let physical_point = point(DevicePixels(x as i32), DevicePixels(y as i32));
 425        let click_count = lock.click_state.update(button, physical_point);
 426        let scale_factor = lock.scale_factor;
 427        drop(lock);
 428
 429        let event = MouseDownEvent {
 430            button,
 431            position: logical_point(x, y, scale_factor),
 432            modifiers: current_modifiers(),
 433            click_count,
 434            first_mouse: false,
 435        };
 436        let result = if callback(PlatformInput::MouseDown(event)).default_prevented {
 437            Some(0)
 438        } else {
 439            Some(1)
 440        };
 441        state_ptr.state.borrow_mut().callbacks.input = Some(callback);
 442
 443        result
 444    } else {
 445        Some(1)
 446    }
 447}
 448
 449fn handle_mouse_up_msg(
 450    _handle: HWND,
 451    button: MouseButton,
 452    lparam: LPARAM,
 453    state_ptr: Rc<WindowsWindowStatePtr>,
 454) -> Option<isize> {
 455    unsafe { ReleaseCapture().log_err() };
 456    let mut lock = state_ptr.state.borrow_mut();
 457    if let Some(mut callback) = lock.callbacks.input.take() {
 458        let x = lparam.signed_loword() as f32;
 459        let y = lparam.signed_hiword() as f32;
 460        let click_count = lock.click_state.current_count;
 461        let scale_factor = lock.scale_factor;
 462        drop(lock);
 463
 464        let event = MouseUpEvent {
 465            button,
 466            position: logical_point(x, y, scale_factor),
 467            modifiers: current_modifiers(),
 468            click_count,
 469        };
 470        let result = if callback(PlatformInput::MouseUp(event)).default_prevented {
 471            Some(0)
 472        } else {
 473            Some(1)
 474        };
 475        state_ptr.state.borrow_mut().callbacks.input = Some(callback);
 476
 477        result
 478    } else {
 479        Some(1)
 480    }
 481}
 482
 483fn handle_xbutton_msg(
 484    handle: HWND,
 485    wparam: WPARAM,
 486    lparam: LPARAM,
 487    handler: impl Fn(HWND, MouseButton, LPARAM, Rc<WindowsWindowStatePtr>) -> Option<isize>,
 488    state_ptr: Rc<WindowsWindowStatePtr>,
 489) -> Option<isize> {
 490    let nav_dir = match wparam.hiword() {
 491        XBUTTON1 => NavigationDirection::Back,
 492        XBUTTON2 => NavigationDirection::Forward,
 493        _ => return Some(1),
 494    };
 495    handler(handle, MouseButton::Navigate(nav_dir), lparam, state_ptr)
 496}
 497
 498fn handle_mouse_wheel_msg(
 499    handle: HWND,
 500    wparam: WPARAM,
 501    lparam: LPARAM,
 502    state_ptr: Rc<WindowsWindowStatePtr>,
 503) -> Option<isize> {
 504    let mut lock = state_ptr.state.borrow_mut();
 505    if let Some(mut callback) = lock.callbacks.input.take() {
 506        let scale_factor = lock.scale_factor;
 507        let wheel_scroll_lines = lock.system_settings.mouse_wheel_settings.wheel_scroll_lines;
 508        drop(lock);
 509        let wheel_distance =
 510            (wparam.signed_hiword() as f32 / WHEEL_DELTA as f32) * wheel_scroll_lines as f32;
 511        let mut cursor_point = POINT {
 512            x: lparam.signed_loword().into(),
 513            y: lparam.signed_hiword().into(),
 514        };
 515        unsafe { ScreenToClient(handle, &mut cursor_point).ok().log_err() };
 516        let event = ScrollWheelEvent {
 517            position: logical_point(cursor_point.x as f32, cursor_point.y as f32, scale_factor),
 518            delta: ScrollDelta::Lines(Point {
 519                x: 0.0,
 520                y: wheel_distance,
 521            }),
 522            modifiers: current_modifiers(),
 523            touch_phase: TouchPhase::Moved,
 524        };
 525        let result = if callback(PlatformInput::ScrollWheel(event)).default_prevented {
 526            Some(0)
 527        } else {
 528            Some(1)
 529        };
 530        state_ptr.state.borrow_mut().callbacks.input = Some(callback);
 531
 532        result
 533    } else {
 534        Some(1)
 535    }
 536}
 537
 538fn handle_mouse_horizontal_wheel_msg(
 539    handle: HWND,
 540    wparam: WPARAM,
 541    lparam: LPARAM,
 542    state_ptr: Rc<WindowsWindowStatePtr>,
 543) -> Option<isize> {
 544    let mut lock = state_ptr.state.borrow_mut();
 545    if let Some(mut callback) = lock.callbacks.input.take() {
 546        let scale_factor = lock.scale_factor;
 547        let wheel_scroll_chars = lock.system_settings.mouse_wheel_settings.wheel_scroll_chars;
 548        drop(lock);
 549        let wheel_distance =
 550            (-wparam.signed_hiword() as f32 / WHEEL_DELTA as f32) * wheel_scroll_chars as f32;
 551        let mut cursor_point = POINT {
 552            x: lparam.signed_loword().into(),
 553            y: lparam.signed_hiword().into(),
 554        };
 555        unsafe { ScreenToClient(handle, &mut cursor_point).ok().log_err() };
 556        let event = ScrollWheelEvent {
 557            position: logical_point(cursor_point.x as f32, cursor_point.y as f32, scale_factor),
 558            delta: ScrollDelta::Lines(Point {
 559                x: wheel_distance,
 560                y: 0.0,
 561            }),
 562            modifiers: current_modifiers(),
 563            touch_phase: TouchPhase::Moved,
 564        };
 565        let result = if callback(PlatformInput::ScrollWheel(event)).default_prevented {
 566            Some(0)
 567        } else {
 568            Some(1)
 569        };
 570        state_ptr.state.borrow_mut().callbacks.input = Some(callback);
 571
 572        result
 573    } else {
 574        Some(1)
 575    }
 576}
 577
 578fn handle_ime_position(handle: HWND, state_ptr: Rc<WindowsWindowStatePtr>) -> Option<isize> {
 579    unsafe {
 580        let mut lock = state_ptr.state.borrow_mut();
 581        let ctx = ImmGetContext(handle);
 582        let Some(mut input_handler) = lock.input_handler.take() else {
 583            return Some(1);
 584        };
 585        let scale_factor = lock.scale_factor;
 586        drop(lock);
 587
 588        let Some(caret_range) = input_handler.selected_text_range() else {
 589            state_ptr.state.borrow_mut().input_handler = Some(input_handler);
 590            return Some(0);
 591        };
 592        let caret_position = input_handler.bounds_for_range(caret_range).unwrap();
 593        state_ptr.state.borrow_mut().input_handler = Some(input_handler);
 594        let config = CANDIDATEFORM {
 595            dwStyle: CFS_CANDIDATEPOS,
 596            // logical to physical
 597            ptCurrentPos: POINT {
 598                x: (caret_position.origin.x.0 * scale_factor) as i32,
 599                y: (caret_position.origin.y.0 * scale_factor) as i32
 600                    + ((caret_position.size.height.0 * scale_factor) as i32 / 2),
 601            },
 602            ..Default::default()
 603        };
 604        ImmSetCandidateWindow(ctx, &config as _).ok().log_err();
 605        ImmReleaseContext(handle, ctx).ok().log_err();
 606        Some(0)
 607    }
 608}
 609
 610fn handle_ime_composition(
 611    handle: HWND,
 612    lparam: LPARAM,
 613    state_ptr: Rc<WindowsWindowStatePtr>,
 614) -> Option<isize> {
 615    let mut ime_input = None;
 616    if lparam.0 as u32 & GCS_COMPSTR.0 > 0 {
 617        let Some((string, string_len)) = parse_ime_compostion_string(handle) else {
 618            return None;
 619        };
 620        let mut lock = state_ptr.state.borrow_mut();
 621        let Some(mut input_handler) = lock.input_handler.take() else {
 622            return None;
 623        };
 624        drop(lock);
 625        input_handler.replace_and_mark_text_in_range(None, string.as_str(), Some(0..string_len));
 626        state_ptr.state.borrow_mut().input_handler = Some(input_handler);
 627        ime_input = Some(string);
 628    }
 629    if lparam.0 as u32 & GCS_CURSORPOS.0 > 0 {
 630        let Some(ref comp_string) = ime_input else {
 631            return None;
 632        };
 633        let caret_pos = retrieve_composition_cursor_position(handle);
 634        let mut lock = state_ptr.state.borrow_mut();
 635        let Some(mut input_handler) = lock.input_handler.take() else {
 636            return None;
 637        };
 638        drop(lock);
 639        input_handler.replace_and_mark_text_in_range(None, comp_string, Some(0..caret_pos));
 640        state_ptr.state.borrow_mut().input_handler = Some(input_handler);
 641    }
 642    if lparam.0 as u32 & GCS_RESULTSTR.0 > 0 {
 643        let Some(comp_result) = parse_ime_compostion_result(handle) else {
 644            return None;
 645        };
 646        let mut lock = state_ptr.state.borrow_mut();
 647        let Some(mut input_handler) = lock.input_handler.take() else {
 648            return Some(1);
 649        };
 650        drop(lock);
 651        input_handler.replace_text_in_range(None, &comp_result);
 652        state_ptr.state.borrow_mut().input_handler = Some(input_handler);
 653        return Some(0);
 654    }
 655    // currently, we don't care other stuff
 656    None
 657}
 658
 659/// SEE: https://learn.microsoft.com/en-us/windows/win32/winmsg/wm-nccalcsize
 660fn handle_calc_client_size(
 661    handle: HWND,
 662    wparam: WPARAM,
 663    lparam: LPARAM,
 664    state_ptr: Rc<WindowsWindowStatePtr>,
 665) -> Option<isize> {
 666    if !state_ptr.hide_title_bar || state_ptr.state.borrow().is_fullscreen() {
 667        return None;
 668    }
 669
 670    if wparam.0 == 0 {
 671        return None;
 672    }
 673
 674    let dpi = unsafe { GetDpiForWindow(handle) };
 675
 676    let frame_x = unsafe { GetSystemMetricsForDpi(SM_CXFRAME, dpi) };
 677    let frame_y = unsafe { GetSystemMetricsForDpi(SM_CYFRAME, dpi) };
 678    let padding = unsafe { GetSystemMetricsForDpi(SM_CXPADDEDBORDER, dpi) };
 679
 680    // wparam is TRUE so lparam points to an NCCALCSIZE_PARAMS structure
 681    let mut params = lparam.0 as *mut NCCALCSIZE_PARAMS;
 682    let mut requested_client_rect = unsafe { &mut ((*params).rgrc) };
 683
 684    requested_client_rect[0].right -= frame_x + padding;
 685    requested_client_rect[0].left += frame_x + padding;
 686    requested_client_rect[0].bottom -= frame_y + padding;
 687
 688    Some(0)
 689}
 690
 691fn handle_activate_msg(
 692    handle: HWND,
 693    wparam: WPARAM,
 694    state_ptr: Rc<WindowsWindowStatePtr>,
 695) -> Option<isize> {
 696    let activated = wparam.loword() > 0;
 697    if state_ptr.hide_title_bar {
 698        if let Some(titlebar_rect) = state_ptr.state.borrow().get_titlebar_rect().log_err() {
 699            unsafe {
 700                InvalidateRect(handle, Some(&titlebar_rect), FALSE)
 701                    .ok()
 702                    .log_err()
 703            };
 704        }
 705    }
 706    let this = state_ptr.clone();
 707    state_ptr
 708        .executor
 709        .spawn(async move {
 710            let mut lock = this.state.borrow_mut();
 711            if let Some(mut cb) = lock.callbacks.active_status_change.take() {
 712                drop(lock);
 713                cb(activated);
 714                this.state.borrow_mut().callbacks.active_status_change = Some(cb);
 715            }
 716        })
 717        .detach();
 718
 719    None
 720}
 721
 722fn handle_create_msg(handle: HWND, state_ptr: Rc<WindowsWindowStatePtr>) -> Option<isize> {
 723    let mut size_rect = RECT::default();
 724    unsafe { GetWindowRect(handle, &mut size_rect).log_err() };
 725
 726    let width = size_rect.right - size_rect.left;
 727    let height = size_rect.bottom - size_rect.top;
 728
 729    if state_ptr.hide_title_bar {
 730        unsafe {
 731            SetWindowPos(
 732                handle,
 733                None,
 734                size_rect.left,
 735                size_rect.top,
 736                width,
 737                height,
 738                SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE,
 739            )
 740            .log_err()
 741        };
 742    }
 743
 744    Some(0)
 745}
 746
 747fn handle_dpi_changed_msg(
 748    handle: HWND,
 749    wparam: WPARAM,
 750    lparam: LPARAM,
 751    state_ptr: Rc<WindowsWindowStatePtr>,
 752) -> Option<isize> {
 753    let new_dpi = wparam.loword() as f32;
 754    state_ptr.state.borrow_mut().scale_factor = new_dpi / USER_DEFAULT_SCREEN_DPI as f32;
 755
 756    let rect = unsafe { &*(lparam.0 as *const RECT) };
 757    let width = rect.right - rect.left;
 758    let height = rect.bottom - rect.top;
 759    // this will emit `WM_SIZE` and `WM_MOVE` right here
 760    // even before this function returns
 761    // the new size is handled in `WM_SIZE`
 762    unsafe {
 763        SetWindowPos(
 764            handle,
 765            None,
 766            rect.left,
 767            rect.top,
 768            width,
 769            height,
 770            SWP_NOZORDER | SWP_NOACTIVATE,
 771        )
 772        .context("unable to set window position after dpi has changed")
 773        .log_err();
 774    }
 775
 776    Some(0)
 777}
 778
 779/// The following conditions will trigger this event:
 780/// 1. The monitor on which the window is located goes offline or changes resolution.
 781/// 2. Another monitor goes offline, is plugged in, or changes resolution.
 782///
 783/// In either case, the window will only receive information from the monitor on which
 784/// it is located.
 785///
 786/// For example, in the case of condition 2, where the monitor on which the window is
 787/// located has actually changed nothing, it will still receive this event.
 788fn handle_display_change_msg(handle: HWND, state_ptr: Rc<WindowsWindowStatePtr>) -> Option<isize> {
 789    // NOTE:
 790    // Even the `lParam` holds the resolution of the screen, we just ignore it.
 791    // Because WM_DPICHANGED, WM_MOVE, WM_SIEZ will come first, window reposition and resize
 792    // are handled there.
 793    // So we only care about if monitor is disconnected.
 794    let previous_monitor = state_ptr.as_ref().state.borrow().display;
 795    if WindowsDisplay::is_connected(previous_monitor.handle) {
 796        // we are fine, other display changed
 797        return None;
 798    }
 799    // display disconnected
 800    // in this case, the OS will move our window to another monitor, and minimize it.
 801    // we deminimize the window and query the monitor after moving
 802    unsafe {
 803        let _ = ShowWindow(handle, SW_SHOWNORMAL);
 804    };
 805    let new_monitor = unsafe { MonitorFromWindow(handle, MONITOR_DEFAULTTONULL) };
 806    // all monitors disconnected
 807    if new_monitor.is_invalid() {
 808        log::error!("No monitor detected!");
 809        return None;
 810    }
 811    let new_display = WindowsDisplay::new_with_handle(new_monitor);
 812    state_ptr.as_ref().state.borrow_mut().display = new_display;
 813    Some(0)
 814}
 815
 816fn handle_hit_test_msg(
 817    handle: HWND,
 818    msg: u32,
 819    wparam: WPARAM,
 820    lparam: LPARAM,
 821    state_ptr: Rc<WindowsWindowStatePtr>,
 822) -> Option<isize> {
 823    if !state_ptr.hide_title_bar {
 824        return None;
 825    }
 826
 827    // default handler for resize areas
 828    let hit = unsafe { DefWindowProcW(handle, msg, wparam, lparam) };
 829    if matches!(
 830        hit.0 as u32,
 831        HTNOWHERE
 832            | HTRIGHT
 833            | HTLEFT
 834            | HTTOPLEFT
 835            | HTTOP
 836            | HTTOPRIGHT
 837            | HTBOTTOMRIGHT
 838            | HTBOTTOM
 839            | HTBOTTOMLEFT
 840    ) {
 841        return Some(hit.0);
 842    }
 843
 844    if state_ptr.state.borrow().is_fullscreen() {
 845        return Some(HTCLIENT as _);
 846    }
 847
 848    let dpi = unsafe { GetDpiForWindow(handle) };
 849    let frame_y = unsafe { GetSystemMetricsForDpi(SM_CYFRAME, dpi) };
 850    let padding = unsafe { GetSystemMetricsForDpi(SM_CXPADDEDBORDER, dpi) };
 851
 852    let mut cursor_point = POINT {
 853        x: lparam.signed_loword().into(),
 854        y: lparam.signed_hiword().into(),
 855    };
 856    unsafe { ScreenToClient(handle, &mut cursor_point).ok().log_err() };
 857    if cursor_point.y > 0 && cursor_point.y < frame_y + padding {
 858        return Some(HTTOP as _);
 859    }
 860
 861    let titlebar_rect = state_ptr.state.borrow().get_titlebar_rect();
 862    if let Ok(titlebar_rect) = titlebar_rect {
 863        if cursor_point.y < titlebar_rect.bottom {
 864            let caption_btn_width = (state_ptr.state.borrow().caption_button_width().0
 865                * state_ptr.state.borrow().scale_factor) as i32;
 866            if cursor_point.x >= titlebar_rect.right - caption_btn_width {
 867                return Some(HTCLOSE as _);
 868            } else if cursor_point.x >= titlebar_rect.right - caption_btn_width * 2 {
 869                return Some(HTMAXBUTTON as _);
 870            } else if cursor_point.x >= titlebar_rect.right - caption_btn_width * 3 {
 871                return Some(HTMINBUTTON as _);
 872            }
 873
 874            return Some(HTCAPTION as _);
 875        }
 876    }
 877
 878    Some(HTCLIENT as _)
 879}
 880
 881fn handle_nc_mouse_move_msg(
 882    handle: HWND,
 883    lparam: LPARAM,
 884    state_ptr: Rc<WindowsWindowStatePtr>,
 885) -> Option<isize> {
 886    if !state_ptr.hide_title_bar {
 887        return None;
 888    }
 889
 890    let mut lock = state_ptr.state.borrow_mut();
 891    if let Some(mut callback) = lock.callbacks.input.take() {
 892        let scale_factor = lock.scale_factor;
 893        drop(lock);
 894        let mut cursor_point = POINT {
 895            x: lparam.signed_loword().into(),
 896            y: lparam.signed_hiword().into(),
 897        };
 898        unsafe { ScreenToClient(handle, &mut cursor_point).ok().log_err() };
 899        let event = MouseMoveEvent {
 900            position: logical_point(cursor_point.x as f32, cursor_point.y as f32, scale_factor),
 901            pressed_button: None,
 902            modifiers: current_modifiers(),
 903        };
 904        let result = if callback(PlatformInput::MouseMove(event)).default_prevented {
 905            Some(0)
 906        } else {
 907            Some(1)
 908        };
 909        state_ptr.state.borrow_mut().callbacks.input = Some(callback);
 910
 911        result
 912    } else {
 913        None
 914    }
 915}
 916
 917fn handle_nc_mouse_down_msg(
 918    handle: HWND,
 919    button: MouseButton,
 920    wparam: WPARAM,
 921    lparam: LPARAM,
 922    state_ptr: Rc<WindowsWindowStatePtr>,
 923) -> Option<isize> {
 924    if !state_ptr.hide_title_bar {
 925        return None;
 926    }
 927
 928    let mut lock = state_ptr.state.borrow_mut();
 929    if let Some(mut callback) = lock.callbacks.input.take() {
 930        let scale_factor = lock.scale_factor;
 931        let mut cursor_point = POINT {
 932            x: lparam.signed_loword().into(),
 933            y: lparam.signed_hiword().into(),
 934        };
 935        unsafe { ScreenToClient(handle, &mut cursor_point).ok().log_err() };
 936        let physical_point = point(DevicePixels(cursor_point.x), DevicePixels(cursor_point.y));
 937        let click_count = lock.click_state.update(button, physical_point);
 938        drop(lock);
 939        let event = MouseDownEvent {
 940            button,
 941            position: logical_point(cursor_point.x as f32, cursor_point.y as f32, scale_factor),
 942            modifiers: current_modifiers(),
 943            click_count,
 944            first_mouse: false,
 945        };
 946        let result = if callback(PlatformInput::MouseDown(event)).default_prevented {
 947            Some(0)
 948        } else {
 949            None
 950        };
 951        state_ptr.state.borrow_mut().callbacks.input = Some(callback);
 952
 953        if result.is_some() {
 954            return result;
 955        }
 956    } else {
 957        drop(lock);
 958    };
 959
 960    // Since these are handled in handle_nc_mouse_up_msg we must prevent the default window proc
 961    if button == MouseButton::Left {
 962        match wparam.0 as u32 {
 963            HTMINBUTTON => state_ptr.state.borrow_mut().nc_button_pressed = Some(HTMINBUTTON),
 964            HTMAXBUTTON => state_ptr.state.borrow_mut().nc_button_pressed = Some(HTMAXBUTTON),
 965            HTCLOSE => state_ptr.state.borrow_mut().nc_button_pressed = Some(HTCLOSE),
 966            _ => return None,
 967        };
 968        Some(0)
 969    } else {
 970        None
 971    }
 972}
 973
 974fn handle_nc_mouse_up_msg(
 975    handle: HWND,
 976    button: MouseButton,
 977    wparam: WPARAM,
 978    lparam: LPARAM,
 979    state_ptr: Rc<WindowsWindowStatePtr>,
 980) -> Option<isize> {
 981    if !state_ptr.hide_title_bar {
 982        return None;
 983    }
 984
 985    let mut lock = state_ptr.state.borrow_mut();
 986    if let Some(mut callback) = lock.callbacks.input.take() {
 987        let scale_factor = lock.scale_factor;
 988        drop(lock);
 989        let mut cursor_point = POINT {
 990            x: lparam.signed_loword().into(),
 991            y: lparam.signed_hiword().into(),
 992        };
 993        unsafe { ScreenToClient(handle, &mut cursor_point).ok().log_err() };
 994        let event = MouseUpEvent {
 995            button,
 996            position: logical_point(cursor_point.x as f32, cursor_point.y as f32, scale_factor),
 997            modifiers: current_modifiers(),
 998            click_count: 1,
 999        };
1000        let result = if callback(PlatformInput::MouseUp(event)).default_prevented {
1001            Some(0)
1002        } else {
1003            None
1004        };
1005        state_ptr.state.borrow_mut().callbacks.input = Some(callback);
1006        if result.is_some() {
1007            return result;
1008        }
1009    } else {
1010        drop(lock);
1011    }
1012
1013    let last_pressed = state_ptr.state.borrow_mut().nc_button_pressed.take();
1014    if button == MouseButton::Left && last_pressed.is_some() {
1015        let last_button = last_pressed.unwrap();
1016        let mut handled = false;
1017        match wparam.0 as u32 {
1018            HTMINBUTTON => {
1019                if last_button == HTMINBUTTON {
1020                    unsafe { ShowWindowAsync(handle, SW_MINIMIZE).ok().log_err() };
1021                    handled = true;
1022                }
1023            }
1024            HTMAXBUTTON => {
1025                if last_button == HTMAXBUTTON {
1026                    if state_ptr.state.borrow().is_maximized() {
1027                        unsafe { ShowWindowAsync(handle, SW_NORMAL).ok().log_err() };
1028                    } else {
1029                        unsafe { ShowWindowAsync(handle, SW_MAXIMIZE).ok().log_err() };
1030                    }
1031                    handled = true;
1032                }
1033            }
1034            HTCLOSE => {
1035                if last_button == HTCLOSE {
1036                    unsafe {
1037                        PostMessageW(handle, WM_CLOSE, WPARAM::default(), LPARAM::default())
1038                            .log_err()
1039                    };
1040                    handled = true;
1041                }
1042            }
1043            _ => {}
1044        };
1045        if handled {
1046            return Some(0);
1047        }
1048    }
1049
1050    None
1051}
1052
1053fn handle_cursor_changed(lparam: LPARAM, state_ptr: Rc<WindowsWindowStatePtr>) -> Option<isize> {
1054    state_ptr.state.borrow_mut().current_cursor = HCURSOR(lparam.0);
1055    Some(0)
1056}
1057
1058fn handle_set_cursor(lparam: LPARAM, state_ptr: Rc<WindowsWindowStatePtr>) -> Option<isize> {
1059    if matches!(
1060        lparam.loword() as u32,
1061        HTLEFT | HTRIGHT | HTTOP | HTTOPLEFT | HTTOPRIGHT | HTBOTTOM | HTBOTTOMLEFT | HTBOTTOMRIGHT
1062    ) {
1063        return None;
1064    }
1065    unsafe { SetCursor(state_ptr.state.borrow().current_cursor) };
1066    Some(1)
1067}
1068
1069fn handle_system_settings_changed(state_ptr: Rc<WindowsWindowStatePtr>) -> Option<isize> {
1070    let mut lock = state_ptr.state.borrow_mut();
1071    // mouse wheel
1072    lock.system_settings.mouse_wheel_settings.update();
1073    Some(0)
1074}
1075
1076fn parse_syskeydown_msg_keystroke(wparam: WPARAM) -> Option<Keystroke> {
1077    let modifiers = current_modifiers();
1078    if !modifiers.alt {
1079        // on Windows, F10 can trigger this event, not just the alt key
1080        // and we just don't care about F10
1081        return None;
1082    }
1083
1084    let vk_code = wparam.loword();
1085    let basic_key = basic_vkcode_to_string(vk_code, modifiers);
1086    if basic_key.is_some() {
1087        return basic_key;
1088    }
1089
1090    let key = match VIRTUAL_KEY(vk_code) {
1091        VK_BACK => Some("backspace"),
1092        VK_RETURN => Some("enter"),
1093        VK_TAB => Some("tab"),
1094        VK_UP => Some("up"),
1095        VK_DOWN => Some("down"),
1096        VK_RIGHT => Some("right"),
1097        VK_LEFT => Some("left"),
1098        VK_HOME => Some("home"),
1099        VK_END => Some("end"),
1100        VK_PRIOR => Some("pageup"),
1101        VK_NEXT => Some("pagedown"),
1102        VK_ESCAPE => Some("escape"),
1103        VK_INSERT => Some("insert"),
1104        _ => None,
1105    };
1106
1107    if let Some(key) = key {
1108        Some(Keystroke {
1109            modifiers,
1110            key: key.to_string(),
1111            ime_key: None,
1112        })
1113    } else {
1114        None
1115    }
1116}
1117
1118enum KeystrokeOrModifier {
1119    Keystroke(Keystroke),
1120    Modifier(Modifiers),
1121}
1122
1123fn parse_keydown_msg_keystroke(wparam: WPARAM) -> Option<KeystrokeOrModifier> {
1124    let vk_code = wparam.loword();
1125
1126    let modifiers = current_modifiers();
1127
1128    if is_modifier(VIRTUAL_KEY(vk_code)) {
1129        return Some(KeystrokeOrModifier::Modifier(modifiers));
1130    }
1131
1132    if modifiers.control || modifiers.alt {
1133        let basic_key = basic_vkcode_to_string(vk_code, modifiers);
1134        if let Some(basic_key) = basic_key {
1135            return Some(KeystrokeOrModifier::Keystroke(basic_key));
1136        }
1137    }
1138
1139    if vk_code >= VK_F1.0 && vk_code <= VK_F24.0 {
1140        let offset = vk_code - VK_F1.0;
1141        return Some(KeystrokeOrModifier::Keystroke(Keystroke {
1142            modifiers,
1143            key: format!("f{}", offset + 1),
1144            ime_key: None,
1145        }));
1146    }
1147
1148    let key = match VIRTUAL_KEY(vk_code) {
1149        VK_BACK => Some("backspace"),
1150        VK_RETURN => Some("enter"),
1151        VK_TAB => Some("tab"),
1152        VK_UP => Some("up"),
1153        VK_DOWN => Some("down"),
1154        VK_RIGHT => Some("right"),
1155        VK_LEFT => Some("left"),
1156        VK_HOME => Some("home"),
1157        VK_END => Some("end"),
1158        VK_PRIOR => Some("pageup"),
1159        VK_NEXT => Some("pagedown"),
1160        VK_ESCAPE => Some("escape"),
1161        VK_INSERT => Some("insert"),
1162        VK_DELETE => Some("delete"),
1163        _ => None,
1164    };
1165
1166    if let Some(key) = key {
1167        Some(KeystrokeOrModifier::Keystroke(Keystroke {
1168            modifiers,
1169            key: key.to_string(),
1170            ime_key: None,
1171        }))
1172    } else {
1173        None
1174    }
1175}
1176
1177fn parse_char_msg_keystroke(wparam: WPARAM) -> Option<Keystroke> {
1178    let src = [wparam.0 as u16];
1179    let Ok(first_char) = char::decode_utf16(src).collect::<Vec<_>>()[0] else {
1180        return None;
1181    };
1182    if first_char.is_control() {
1183        None
1184    } else {
1185        let mut modifiers = current_modifiers();
1186        // for characters that use 'shift' to type it is expected that the
1187        // shift is not reported if the uppercase/lowercase are the same and instead only the key is reported
1188        if first_char.to_lowercase().to_string() == first_char.to_uppercase().to_string() {
1189            modifiers.shift = false;
1190        }
1191        let key = match first_char {
1192            ' ' => "space".to_string(),
1193            first_char => first_char.to_lowercase().to_string(),
1194        };
1195        Some(Keystroke {
1196            modifiers,
1197            key,
1198            ime_key: Some(first_char.to_string()),
1199        })
1200    }
1201}
1202
1203fn parse_ime_compostion_string(handle: HWND) -> Option<(String, usize)> {
1204    unsafe {
1205        let ctx = ImmGetContext(handle);
1206        let string_len = ImmGetCompositionStringW(ctx, GCS_COMPSTR, None, 0);
1207        let result = if string_len >= 0 {
1208            let mut buffer = vec![0u8; string_len as usize + 2];
1209            ImmGetCompositionStringW(
1210                ctx,
1211                GCS_COMPSTR,
1212                Some(buffer.as_mut_ptr() as _),
1213                string_len as _,
1214            );
1215            let wstring = std::slice::from_raw_parts::<u16>(
1216                buffer.as_mut_ptr().cast::<u16>(),
1217                string_len as usize / 2,
1218            );
1219            let string = String::from_utf16_lossy(wstring);
1220            Some((string, string_len as usize / 2))
1221        } else {
1222            None
1223        };
1224        ImmReleaseContext(handle, ctx).ok().log_err();
1225        result
1226    }
1227}
1228
1229fn retrieve_composition_cursor_position(handle: HWND) -> usize {
1230    unsafe {
1231        let ctx = ImmGetContext(handle);
1232        let ret = ImmGetCompositionStringW(ctx, GCS_CURSORPOS, None, 0);
1233        ImmReleaseContext(handle, ctx).ok().log_err();
1234        ret as usize
1235    }
1236}
1237
1238fn parse_ime_compostion_result(handle: HWND) -> Option<String> {
1239    unsafe {
1240        let ctx = ImmGetContext(handle);
1241        let string_len = ImmGetCompositionStringW(ctx, GCS_RESULTSTR, None, 0);
1242        let result = if string_len >= 0 {
1243            let mut buffer = vec![0u8; string_len as usize + 2];
1244            ImmGetCompositionStringW(
1245                ctx,
1246                GCS_RESULTSTR,
1247                Some(buffer.as_mut_ptr() as _),
1248                string_len as _,
1249            );
1250            let wstring = std::slice::from_raw_parts::<u16>(
1251                buffer.as_mut_ptr().cast::<u16>(),
1252                string_len as usize / 2,
1253            );
1254            let string = String::from_utf16_lossy(wstring);
1255            Some(string)
1256        } else {
1257            None
1258        };
1259        ImmReleaseContext(handle, ctx).ok().log_err();
1260        result
1261    }
1262}
1263
1264fn basic_vkcode_to_string(code: u16, modifiers: Modifiers) -> Option<Keystroke> {
1265    match code {
1266        // VK_0 - VK_9
1267        48..=57 => Some(Keystroke {
1268            modifiers,
1269            key: format!("{}", code - VK_0.0),
1270            ime_key: None,
1271        }),
1272        // VK_A - VK_Z
1273        65..=90 => Some(Keystroke {
1274            modifiers,
1275            key: format!("{}", (b'a' + code as u8 - VK_A.0 as u8) as char),
1276            ime_key: None,
1277        }),
1278        // VK_F1 - VK_F24
1279        112..=135 => Some(Keystroke {
1280            modifiers,
1281            key: format!("f{}", code - VK_F1.0 + 1),
1282            ime_key: None,
1283        }),
1284        // OEM3: `/~, OEM_MINUS: -/_, OEM_PLUS: =/+, ...
1285        _ => {
1286            if let Some(key) = oemkey_vkcode_to_string(code) {
1287                Some(Keystroke {
1288                    modifiers,
1289                    key,
1290                    ime_key: None,
1291                })
1292            } else {
1293                None
1294            }
1295        }
1296    }
1297}
1298
1299fn oemkey_vkcode_to_string(code: u16) -> Option<String> {
1300    match code {
1301        186 => Some(";".to_string()), // VK_OEM_1
1302        187 => Some("=".to_string()), // VK_OEM_PLUS
1303        188 => Some(",".to_string()), // VK_OEM_COMMA
1304        189 => Some("-".to_string()), // VK_OEM_MINUS
1305        190 => Some(".".to_string()), // VK_OEM_PERIOD
1306        // https://kbdlayout.info/features/virtualkeys/VK_ABNT_C1
1307        191 | 193 => Some("/".to_string()), // VK_OEM_2 VK_ABNT_C1
1308        192 => Some("`".to_string()),       // VK_OEM_3
1309        219 => Some("[".to_string()),       // VK_OEM_4
1310        220 => Some("\\".to_string()),      // VK_OEM_5
1311        221 => Some("]".to_string()),       // VK_OEM_6
1312        222 => Some("'".to_string()),       // VK_OEM_7
1313        _ => None,
1314    }
1315}
1316
1317#[inline]
1318fn is_virtual_key_pressed(vkey: VIRTUAL_KEY) -> bool {
1319    unsafe { GetKeyState(vkey.0 as i32) < 0 }
1320}
1321
1322fn is_modifier(virtual_key: VIRTUAL_KEY) -> bool {
1323    matches!(
1324        virtual_key,
1325        VK_CONTROL | VK_MENU | VK_SHIFT | VK_LWIN | VK_RWIN
1326    )
1327}
1328
1329#[inline]
1330fn current_modifiers() -> Modifiers {
1331    Modifiers {
1332        control: is_virtual_key_pressed(VK_CONTROL),
1333        alt: is_virtual_key_pressed(VK_MENU),
1334        shift: is_virtual_key_pressed(VK_SHIFT),
1335        platform: is_virtual_key_pressed(VK_LWIN) || is_virtual_key_pressed(VK_RWIN),
1336        function: false,
1337    }
1338}