events.rs

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