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