events.rs

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