events.rs

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