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