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