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