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