events.rs

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