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