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