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