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