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