events.rs

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