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 = (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 {
 888        return None;
 889    }
 890
 891    // default handler for resize areas
 892    let hit = unsafe { DefWindowProcW(handle, msg, wparam, lparam) };
 893    if matches!(
 894        hit.0 as u32,
 895        HTNOWHERE
 896            | HTRIGHT
 897            | HTLEFT
 898            | HTTOPLEFT
 899            | HTTOP
 900            | HTTOPRIGHT
 901            | HTBOTTOMRIGHT
 902            | HTBOTTOM
 903            | HTBOTTOMLEFT
 904    ) {
 905        return Some(hit.0);
 906    }
 907
 908    if state_ptr.state.borrow().is_fullscreen() {
 909        return Some(HTCLIENT as _);
 910    }
 911
 912    let dpi = unsafe { GetDpiForWindow(handle) };
 913    let frame_y = unsafe { GetSystemMetricsForDpi(SM_CYFRAME, dpi) };
 914
 915    let mut cursor_point = POINT {
 916        x: lparam.signed_loword().into(),
 917        y: lparam.signed_hiword().into(),
 918    };
 919    unsafe { ScreenToClient(handle, &mut cursor_point).ok().log_err() };
 920    if !state_ptr.state.borrow().is_maximized() && cursor_point.y >= 0 && cursor_point.y <= frame_y
 921    {
 922        return Some(HTTOP as _);
 923    }
 924
 925    let mut lock = state_ptr.state.borrow_mut();
 926    if let Some(mut callback) = lock.callbacks.hit_test_window_control.take() {
 927        drop(lock);
 928        let area = callback();
 929        state_ptr
 930            .state
 931            .borrow_mut()
 932            .callbacks
 933            .hit_test_window_control = Some(callback);
 934        if let Some(area) = area {
 935            return match area {
 936                WindowControlArea::Drag => Some(HTCAPTION as _),
 937                WindowControlArea::Close => Some(HTCLOSE as _),
 938                WindowControlArea::Max => Some(HTMAXBUTTON as _),
 939                WindowControlArea::Min => Some(HTMINBUTTON as _),
 940            };
 941        }
 942    }
 943
 944    Some(HTCLIENT as _)
 945}
 946
 947fn handle_nc_mouse_move_msg(
 948    handle: HWND,
 949    lparam: LPARAM,
 950    state_ptr: Rc<WindowsWindowStatePtr>,
 951) -> Option<isize> {
 952    start_tracking_mouse(handle, &state_ptr, TME_LEAVE | TME_NONCLIENT);
 953
 954    let mut lock = state_ptr.state.borrow_mut();
 955    let mut func = lock.callbacks.input.take()?;
 956    let scale_factor = lock.scale_factor;
 957    drop(lock);
 958
 959    let mut cursor_point = POINT {
 960        x: lparam.signed_loword().into(),
 961        y: lparam.signed_hiword().into(),
 962    };
 963    unsafe { ScreenToClient(handle, &mut cursor_point).ok().log_err() };
 964    let input = PlatformInput::MouseMove(MouseMoveEvent {
 965        position: logical_point(cursor_point.x as f32, cursor_point.y as f32, scale_factor),
 966        pressed_button: None,
 967        modifiers: current_modifiers(),
 968    });
 969    let handled = !func(input).propagate;
 970    state_ptr.state.borrow_mut().callbacks.input = Some(func);
 971
 972    if handled { Some(0) } else { None }
 973}
 974
 975fn handle_nc_mouse_down_msg(
 976    handle: HWND,
 977    button: MouseButton,
 978    wparam: WPARAM,
 979    lparam: LPARAM,
 980    state_ptr: Rc<WindowsWindowStatePtr>,
 981) -> Option<isize> {
 982    let mut lock = state_ptr.state.borrow_mut();
 983    if let Some(mut func) = lock.callbacks.input.take() {
 984        let scale_factor = lock.scale_factor;
 985        let mut cursor_point = POINT {
 986            x: lparam.signed_loword().into(),
 987            y: lparam.signed_hiword().into(),
 988        };
 989        unsafe { ScreenToClient(handle, &mut cursor_point).ok().log_err() };
 990        let physical_point = point(DevicePixels(cursor_point.x), DevicePixels(cursor_point.y));
 991        let click_count = lock.click_state.update(button, physical_point);
 992        drop(lock);
 993
 994        let input = PlatformInput::MouseDown(MouseDownEvent {
 995            button,
 996            position: logical_point(cursor_point.x as f32, cursor_point.y as f32, scale_factor),
 997            modifiers: current_modifiers(),
 998            click_count,
 999            first_mouse: false,
1000        });
1001        let result = func(input.clone());
1002        let handled = !result.propagate || result.default_prevented;
1003        state_ptr.state.borrow_mut().callbacks.input = Some(func);
1004
1005        if handled {
1006            return Some(0);
1007        }
1008    } else {
1009        drop(lock);
1010    };
1011
1012    // Since these are handled in handle_nc_mouse_up_msg we must prevent the default window proc
1013    if button == MouseButton::Left {
1014        match wparam.0 as u32 {
1015            HTMINBUTTON => state_ptr.state.borrow_mut().nc_button_pressed = Some(HTMINBUTTON),
1016            HTMAXBUTTON => state_ptr.state.borrow_mut().nc_button_pressed = Some(HTMAXBUTTON),
1017            HTCLOSE => state_ptr.state.borrow_mut().nc_button_pressed = Some(HTCLOSE),
1018            _ => return None,
1019        };
1020        Some(0)
1021    } else {
1022        None
1023    }
1024}
1025
1026fn handle_nc_mouse_up_msg(
1027    handle: HWND,
1028    button: MouseButton,
1029    wparam: WPARAM,
1030    lparam: LPARAM,
1031    state_ptr: Rc<WindowsWindowStatePtr>,
1032) -> Option<isize> {
1033    let mut lock = state_ptr.state.borrow_mut();
1034    if let Some(mut func) = lock.callbacks.input.take() {
1035        let scale_factor = lock.scale_factor;
1036        drop(lock);
1037
1038        let mut cursor_point = POINT {
1039            x: lparam.signed_loword().into(),
1040            y: lparam.signed_hiword().into(),
1041        };
1042        unsafe { ScreenToClient(handle, &mut cursor_point).ok().log_err() };
1043        let input = PlatformInput::MouseUp(MouseUpEvent {
1044            button,
1045            position: logical_point(cursor_point.x as f32, cursor_point.y as f32, scale_factor),
1046            modifiers: current_modifiers(),
1047            click_count: 1,
1048        });
1049        let handled = !func(input).propagate;
1050        state_ptr.state.borrow_mut().callbacks.input = Some(func);
1051
1052        if handled {
1053            return Some(0);
1054        }
1055    } else {
1056        drop(lock);
1057    }
1058
1059    let last_pressed = state_ptr.state.borrow_mut().nc_button_pressed.take();
1060    if button == MouseButton::Left && last_pressed.is_some() {
1061        let handled = match (wparam.0 as u32, last_pressed.unwrap()) {
1062            (HTMINBUTTON, HTMINBUTTON) => {
1063                unsafe { ShowWindowAsync(handle, SW_MINIMIZE).ok().log_err() };
1064                true
1065            }
1066            (HTMAXBUTTON, HTMAXBUTTON) => {
1067                if state_ptr.state.borrow().is_maximized() {
1068                    unsafe { ShowWindowAsync(handle, SW_NORMAL).ok().log_err() };
1069                } else {
1070                    unsafe { ShowWindowAsync(handle, SW_MAXIMIZE).ok().log_err() };
1071                }
1072                true
1073            }
1074            (HTCLOSE, HTCLOSE) => {
1075                unsafe {
1076                    PostMessageW(Some(handle), WM_CLOSE, WPARAM::default(), LPARAM::default())
1077                        .log_err()
1078                };
1079                true
1080            }
1081            _ => false,
1082        };
1083        if handled {
1084            return Some(0);
1085        }
1086    }
1087
1088    None
1089}
1090
1091fn handle_cursor_changed(lparam: LPARAM, state_ptr: Rc<WindowsWindowStatePtr>) -> Option<isize> {
1092    let mut state = state_ptr.state.borrow_mut();
1093    let had_cursor = state.current_cursor.is_some();
1094
1095    state.current_cursor = if lparam.0 == 0 {
1096        None
1097    } else {
1098        Some(HCURSOR(lparam.0 as _))
1099    };
1100
1101    if had_cursor != state.current_cursor.is_some() {
1102        unsafe { SetCursor(state.current_cursor) };
1103    }
1104
1105    Some(0)
1106}
1107
1108fn handle_set_cursor(lparam: LPARAM, state_ptr: Rc<WindowsWindowStatePtr>) -> Option<isize> {
1109    if matches!(
1110        lparam.loword() as u32,
1111        HTLEFT | HTRIGHT | HTTOP | HTTOPLEFT | HTTOPRIGHT | HTBOTTOM | HTBOTTOMLEFT | HTBOTTOMRIGHT
1112    ) {
1113        return None;
1114    }
1115    unsafe {
1116        SetCursor(state_ptr.state.borrow().current_cursor);
1117    };
1118    Some(1)
1119}
1120
1121fn handle_system_settings_changed(
1122    handle: HWND,
1123    lparam: LPARAM,
1124    state_ptr: Rc<WindowsWindowStatePtr>,
1125) -> Option<isize> {
1126    let mut lock = state_ptr.state.borrow_mut();
1127    let display = lock.display;
1128    // system settings
1129    lock.system_settings.update(display);
1130    // mouse double click
1131    lock.click_state.system_update();
1132    // window border offset
1133    lock.border_offset.update(handle).log_err();
1134    drop(lock);
1135
1136    // lParam is a pointer to a string that indicates the area containing the system parameter
1137    // that was changed.
1138    let parameter = PCWSTR::from_raw(lparam.0 as _);
1139    if unsafe { !parameter.is_null() && !parameter.is_empty() } {
1140        if let Some(parameter_string) = unsafe { parameter.to_string() }.log_err() {
1141            log::info!("System settings changed: {}", parameter_string);
1142            match parameter_string.as_str() {
1143                "ImmersiveColorSet" => {
1144                    handle_system_theme_changed(handle, state_ptr);
1145                }
1146                _ => {}
1147            }
1148        }
1149    }
1150
1151    // Force to trigger WM_NCCALCSIZE event to ensure that we handle auto hide
1152    // taskbar correctly.
1153    notify_frame_changed(handle);
1154    Some(0)
1155}
1156
1157fn handle_system_command(wparam: WPARAM, state_ptr: Rc<WindowsWindowStatePtr>) -> Option<isize> {
1158    if wparam.0 == SC_KEYMENU as usize {
1159        let mut lock = state_ptr.state.borrow_mut();
1160        if lock.system_key_handled {
1161            lock.system_key_handled = false;
1162            return Some(0);
1163        }
1164    }
1165    None
1166}
1167
1168fn handle_system_theme_changed(
1169    handle: HWND,
1170    state_ptr: Rc<WindowsWindowStatePtr>,
1171) -> Option<isize> {
1172    let mut callback = state_ptr
1173        .state
1174        .borrow_mut()
1175        .callbacks
1176        .appearance_changed
1177        .take()?;
1178    callback();
1179    state_ptr.state.borrow_mut().callbacks.appearance_changed = Some(callback);
1180    configure_dwm_dark_mode(handle);
1181    Some(0)
1182}
1183
1184fn handle_input_language_changed(
1185    lparam: LPARAM,
1186    state_ptr: Rc<WindowsWindowStatePtr>,
1187) -> Option<isize> {
1188    let thread = state_ptr.main_thread_id_win32;
1189    let validation = state_ptr.validation_number;
1190    unsafe {
1191        PostThreadMessageW(thread, WM_INPUTLANGCHANGE, WPARAM(validation), lparam).log_err();
1192    }
1193    Some(0)
1194}
1195
1196#[inline]
1197fn translate_message(handle: HWND, wparam: WPARAM, lparam: LPARAM) {
1198    let msg = MSG {
1199        hwnd: handle,
1200        message: WM_KEYDOWN,
1201        wParam: wparam,
1202        lParam: lparam,
1203        // It seems like leaving the following two parameters empty doesn't break key events, they still work as expected.
1204        // But if any bugs pop up after this PR, this is probably the place to look first.
1205        time: 0,
1206        pt: POINT::default(),
1207    };
1208    unsafe { TranslateMessage(&msg).ok().log_err() };
1209}
1210
1211fn handle_key_event<F>(
1212    handle: HWND,
1213    wparam: WPARAM,
1214    lparam: LPARAM,
1215    state: &mut WindowsWindowState,
1216    f: F,
1217) -> Option<PlatformInput>
1218where
1219    F: FnOnce(Keystroke) -> PlatformInput,
1220{
1221    let virtual_key = VIRTUAL_KEY(wparam.loword());
1222    let mut modifiers = current_modifiers();
1223
1224    match virtual_key {
1225        VK_SHIFT | VK_CONTROL | VK_MENU | VK_LWIN | VK_RWIN => {
1226            if state
1227                .last_reported_modifiers
1228                .is_some_and(|prev_modifiers| prev_modifiers == modifiers)
1229            {
1230                return None;
1231            }
1232            state.last_reported_modifiers = Some(modifiers);
1233            Some(PlatformInput::ModifiersChanged(ModifiersChangedEvent {
1234                modifiers,
1235            }))
1236        }
1237        vkey => {
1238            let vkey = if vkey == VK_PROCESSKEY {
1239                VIRTUAL_KEY(unsafe { ImmGetVirtualKey(handle) } as u16)
1240            } else {
1241                vkey
1242            };
1243            let keystroke = parse_normal_key(vkey, lparam, modifiers)?;
1244            Some(f(keystroke))
1245        }
1246    }
1247}
1248
1249fn parse_immutable(vkey: VIRTUAL_KEY) -> Option<String> {
1250    Some(
1251        match vkey {
1252            VK_SPACE => "space",
1253            VK_BACK => "backspace",
1254            VK_RETURN => "enter",
1255            VK_TAB => "tab",
1256            VK_UP => "up",
1257            VK_DOWN => "down",
1258            VK_RIGHT => "right",
1259            VK_LEFT => "left",
1260            VK_HOME => "home",
1261            VK_END => "end",
1262            VK_PRIOR => "pageup",
1263            VK_NEXT => "pagedown",
1264            VK_BROWSER_BACK => "back",
1265            VK_BROWSER_FORWARD => "forward",
1266            VK_ESCAPE => "escape",
1267            VK_INSERT => "insert",
1268            VK_DELETE => "delete",
1269            VK_APPS => "menu",
1270            VK_F1 => "f1",
1271            VK_F2 => "f2",
1272            VK_F3 => "f3",
1273            VK_F4 => "f4",
1274            VK_F5 => "f5",
1275            VK_F6 => "f6",
1276            VK_F7 => "f7",
1277            VK_F8 => "f8",
1278            VK_F9 => "f9",
1279            VK_F10 => "f10",
1280            VK_F11 => "f11",
1281            VK_F12 => "f12",
1282            VK_F13 => "f13",
1283            VK_F14 => "f14",
1284            VK_F15 => "f15",
1285            VK_F16 => "f16",
1286            VK_F17 => "f17",
1287            VK_F18 => "f18",
1288            VK_F19 => "f19",
1289            VK_F20 => "f20",
1290            VK_F21 => "f21",
1291            VK_F22 => "f22",
1292            VK_F23 => "f23",
1293            VK_F24 => "f24",
1294            _ => return None,
1295        }
1296        .to_string(),
1297    )
1298}
1299
1300fn parse_normal_key(
1301    vkey: VIRTUAL_KEY,
1302    lparam: LPARAM,
1303    mut modifiers: Modifiers,
1304) -> Option<Keystroke> {
1305    let mut key_char = None;
1306    let key = parse_immutable(vkey).or_else(|| {
1307        let scan_code = lparam.hiword() & 0xFF;
1308        key_char = generate_key_char(
1309            vkey,
1310            scan_code as u32,
1311            modifiers.control,
1312            modifiers.shift,
1313            modifiers.alt,
1314        );
1315        get_keystroke_key(vkey, scan_code as u32, &mut modifiers)
1316    })?;
1317    Some(Keystroke {
1318        modifiers,
1319        key,
1320        key_char,
1321    })
1322}
1323
1324fn parse_ime_composition_string(ctx: HIMC, comp_type: IME_COMPOSITION_STRING) -> Option<String> {
1325    unsafe {
1326        let string_len = ImmGetCompositionStringW(ctx, comp_type, None, 0);
1327        if string_len >= 0 {
1328            let mut buffer = vec![0u8; string_len as usize + 2];
1329            ImmGetCompositionStringW(
1330                ctx,
1331                comp_type,
1332                Some(buffer.as_mut_ptr() as _),
1333                string_len as _,
1334            );
1335            let wstring = std::slice::from_raw_parts::<u16>(
1336                buffer.as_mut_ptr().cast::<u16>(),
1337                string_len as usize / 2,
1338            );
1339            Some(String::from_utf16_lossy(wstring))
1340        } else {
1341            None
1342        }
1343    }
1344}
1345
1346#[inline]
1347fn retrieve_composition_cursor_position(ctx: HIMC) -> usize {
1348    unsafe { ImmGetCompositionStringW(ctx, GCS_CURSORPOS, None, 0) as usize }
1349}
1350
1351#[inline]
1352fn is_virtual_key_pressed(vkey: VIRTUAL_KEY) -> bool {
1353    unsafe { GetKeyState(vkey.0 as i32) < 0 }
1354}
1355
1356#[inline]
1357pub(crate) fn current_modifiers() -> Modifiers {
1358    Modifiers {
1359        control: is_virtual_key_pressed(VK_CONTROL),
1360        alt: is_virtual_key_pressed(VK_MENU),
1361        shift: is_virtual_key_pressed(VK_SHIFT),
1362        platform: is_virtual_key_pressed(VK_LWIN) || is_virtual_key_pressed(VK_RWIN),
1363        function: false,
1364    }
1365}
1366
1367fn get_client_area_insets(
1368    handle: HWND,
1369    is_maximized: bool,
1370    windows_version: WindowsVersion,
1371) -> RECT {
1372    // For maximized windows, Windows outdents the window rect from the screen's client rect
1373    // by `frame_thickness` on each edge, meaning `insets` must contain `frame_thickness`
1374    // on all sides (including the top) to avoid the client area extending onto adjacent
1375    // monitors.
1376    //
1377    // For non-maximized windows, things become complicated:
1378    //
1379    // - On Windows 10
1380    // The top inset must be zero, since if there is any nonclient area, Windows will draw
1381    // a full native titlebar outside the client area. (This doesn't occur in the maximized
1382    // case.)
1383    //
1384    // - On Windows 11
1385    // The top inset is calculated using an empirical formula that I derived through various
1386    // tests. Without this, the top 1-2 rows of pixels in our window would be obscured.
1387    let dpi = unsafe { GetDpiForWindow(handle) };
1388    let frame_thickness = get_frame_thickness(dpi);
1389    let top_insets = if is_maximized {
1390        frame_thickness
1391    } else {
1392        match windows_version {
1393            WindowsVersion::Win10 => 0,
1394            WindowsVersion::Win11 => (dpi as f32 / USER_DEFAULT_SCREEN_DPI as f32).round() as i32,
1395        }
1396    };
1397    RECT {
1398        left: frame_thickness,
1399        top: top_insets,
1400        right: frame_thickness,
1401        bottom: frame_thickness,
1402    }
1403}
1404
1405// there is some additional non-visible space when talking about window
1406// borders on Windows:
1407// - SM_CXSIZEFRAME: The resize handle.
1408// - SM_CXPADDEDBORDER: Additional border space that isn't part of the resize handle.
1409fn get_frame_thickness(dpi: u32) -> i32 {
1410    let resize_frame_thickness = unsafe { GetSystemMetricsForDpi(SM_CXSIZEFRAME, dpi) };
1411    let padding_thickness = unsafe { GetSystemMetricsForDpi(SM_CXPADDEDBORDER, dpi) };
1412    resize_frame_thickness + padding_thickness
1413}
1414
1415fn notify_frame_changed(handle: HWND) {
1416    unsafe {
1417        SetWindowPos(
1418            handle,
1419            None,
1420            0,
1421            0,
1422            0,
1423            0,
1424            SWP_FRAMECHANGED
1425                | SWP_NOACTIVATE
1426                | SWP_NOCOPYBITS
1427                | SWP_NOMOVE
1428                | SWP_NOOWNERZORDER
1429                | SWP_NOREPOSITION
1430                | SWP_NOSENDCHANGING
1431                | SWP_NOSIZE
1432                | SWP_NOZORDER,
1433        )
1434        .log_err();
1435    }
1436}
1437
1438fn start_tracking_mouse(
1439    handle: HWND,
1440    state_ptr: &Rc<WindowsWindowStatePtr>,
1441    flags: TRACKMOUSEEVENT_FLAGS,
1442) {
1443    let mut lock = state_ptr.state.borrow_mut();
1444    if !lock.hovered {
1445        lock.hovered = true;
1446        unsafe {
1447            TrackMouseEvent(&mut TRACKMOUSEEVENT {
1448                cbSize: std::mem::size_of::<TRACKMOUSEEVENT>() as u32,
1449                dwFlags: flags,
1450                hwndTrack: handle,
1451                dwHoverTime: HOVER_DEFAULT,
1452            })
1453            .log_err()
1454        };
1455        if let Some(mut callback) = lock.callbacks.hovered_status_change.take() {
1456            drop(lock);
1457            callback(true);
1458            state_ptr.state.borrow_mut().callbacks.hovered_status_change = Some(callback);
1459        }
1460    }
1461}
1462
1463fn with_input_handler<F, R>(state_ptr: &Rc<WindowsWindowStatePtr>, f: F) -> Option<R>
1464where
1465    F: FnOnce(&mut PlatformInputHandler) -> R,
1466{
1467    let mut input_handler = state_ptr.state.borrow_mut().input_handler.take()?;
1468    let result = f(&mut input_handler);
1469    state_ptr.state.borrow_mut().input_handler = Some(input_handler);
1470    Some(result)
1471}
1472
1473fn with_input_handler_and_scale_factor<F, R>(
1474    state_ptr: &Rc<WindowsWindowStatePtr>,
1475    f: F,
1476) -> Option<R>
1477where
1478    F: FnOnce(&mut PlatformInputHandler, f32) -> Option<R>,
1479{
1480    let mut lock = state_ptr.state.borrow_mut();
1481    let mut input_handler = lock.input_handler.take()?;
1482    let scale_factor = lock.scale_factor;
1483    drop(lock);
1484    let result = f(&mut input_handler, scale_factor);
1485    state_ptr.state.borrow_mut().input_handler = Some(input_handler);
1486    result
1487}