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_keystroke_from_vkey(wparam, false) 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_keystroke_from_vkey(wparam, true) 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    let mut state = state_ptr.state.borrow_mut();
1131    let had_cursor = state.current_cursor.is_some();
1132
1133    state.current_cursor = if lparam.0 == 0 {
1134        None
1135    } else {
1136        Some(HCURSOR(lparam.0 as _))
1137    };
1138
1139    if had_cursor != state.current_cursor.is_some() {
1140        unsafe { SetCursor(state.current_cursor) };
1141    }
1142
1143    Some(0)
1144}
1145
1146fn handle_set_cursor(lparam: LPARAM, state_ptr: Rc<WindowsWindowStatePtr>) -> Option<isize> {
1147    if matches!(
1148        lparam.loword() as u32,
1149        HTLEFT | HTRIGHT | HTTOP | HTTOPLEFT | HTTOPRIGHT | HTBOTTOM | HTBOTTOMLEFT | HTBOTTOMRIGHT
1150    ) {
1151        return None;
1152    }
1153    unsafe {
1154        SetCursor(state_ptr.state.borrow().current_cursor);
1155    };
1156    Some(1)
1157}
1158
1159fn handle_system_settings_changed(
1160    handle: HWND,
1161    lparam: LPARAM,
1162    state_ptr: Rc<WindowsWindowStatePtr>,
1163) -> Option<isize> {
1164    let mut lock = state_ptr.state.borrow_mut();
1165    let display = lock.display;
1166    // system settings
1167    lock.system_settings.update(display);
1168    // mouse double click
1169    lock.click_state.system_update();
1170    // window border offset
1171    lock.border_offset.update(handle).log_err();
1172    drop(lock);
1173
1174    // lParam is a pointer to a string that indicates the area containing the system parameter
1175    // that was changed.
1176    let parameter = PCWSTR::from_raw(lparam.0 as _);
1177    if unsafe { !parameter.is_null() && !parameter.is_empty() } {
1178        if let Some(parameter_string) = unsafe { parameter.to_string() }.log_err() {
1179            log::info!("System settings changed: {}", parameter_string);
1180            match parameter_string.as_str() {
1181                "ImmersiveColorSet" => {
1182                    handle_system_theme_changed(handle, state_ptr);
1183                }
1184                _ => {}
1185            }
1186        }
1187    }
1188
1189    // Force to trigger WM_NCCALCSIZE event to ensure that we handle auto hide
1190    // taskbar correctly.
1191    notify_frame_changed(handle);
1192    Some(0)
1193}
1194
1195fn handle_system_command(wparam: WPARAM, state_ptr: Rc<WindowsWindowStatePtr>) -> Option<isize> {
1196    if wparam.0 == SC_KEYMENU as usize {
1197        let mut lock = state_ptr.state.borrow_mut();
1198        if lock.system_key_handled {
1199            lock.system_key_handled = false;
1200            return Some(0);
1201        }
1202    }
1203    None
1204}
1205
1206fn handle_system_theme_changed(
1207    handle: HWND,
1208    state_ptr: Rc<WindowsWindowStatePtr>,
1209) -> Option<isize> {
1210    let mut callback = state_ptr
1211        .state
1212        .borrow_mut()
1213        .callbacks
1214        .appearance_changed
1215        .take()?;
1216    callback();
1217    state_ptr.state.borrow_mut().callbacks.appearance_changed = Some(callback);
1218    configure_dwm_dark_mode(handle);
1219    Some(0)
1220}
1221
1222fn parse_syskeydown_msg_keystroke(wparam: WPARAM) -> Option<Keystroke> {
1223    let modifiers = current_modifiers();
1224    let vk_code = wparam.loword();
1225
1226    // on Windows, F10 can trigger this event, not just the alt key,
1227    // so when F10 was pressed, handle only it
1228    if !modifiers.alt {
1229        if vk_code == VK_F10.0 {
1230            let offset = vk_code - VK_F1.0;
1231            return Some(Keystroke {
1232                modifiers,
1233                key: format!("f{}", offset + 1),
1234                key_char: None,
1235            });
1236        } else {
1237            return None;
1238        }
1239    }
1240
1241    let key = match VIRTUAL_KEY(vk_code) {
1242        VK_BACK => "backspace",
1243        VK_RETURN => "enter",
1244        VK_TAB => "tab",
1245        VK_UP => "up",
1246        VK_DOWN => "down",
1247        VK_RIGHT => "right",
1248        VK_LEFT => "left",
1249        VK_HOME => "home",
1250        VK_END => "end",
1251        VK_PRIOR => "pageup",
1252        VK_NEXT => "pagedown",
1253        VK_BROWSER_BACK => "back",
1254        VK_BROWSER_FORWARD => "forward",
1255        VK_ESCAPE => "escape",
1256        VK_INSERT => "insert",
1257        VK_DELETE => "delete",
1258        VK_APPS => "menu",
1259        _ => {
1260            let basic_key = basic_vkcode_to_string(vk_code, modifiers);
1261            if basic_key.is_some() {
1262                return basic_key;
1263            } else {
1264                if vk_code >= VK_F1.0 && vk_code <= VK_F24.0 {
1265                    let offset = vk_code - VK_F1.0;
1266                    return Some(Keystroke {
1267                        modifiers,
1268                        key: format!("f{}", offset + 1),
1269                        key_char: None,
1270                    });
1271                } else {
1272                    return None;
1273                }
1274            }
1275        }
1276    }
1277    .to_owned();
1278
1279    Some(Keystroke {
1280        modifiers,
1281        key,
1282        key_char: None,
1283    })
1284}
1285
1286enum KeystrokeOrModifier {
1287    Keystroke(Keystroke),
1288    Modifier(Modifiers),
1289}
1290
1291fn parse_keystroke_from_vkey(wparam: WPARAM, is_keyup: bool) -> Option<KeystrokeOrModifier> {
1292    let vk_code = wparam.loword();
1293
1294    let modifiers = current_modifiers();
1295
1296    let key = match VIRTUAL_KEY(vk_code) {
1297        VK_BACK => "backspace",
1298        VK_RETURN => "enter",
1299        VK_TAB => "tab",
1300        VK_UP => "up",
1301        VK_DOWN => "down",
1302        VK_RIGHT => "right",
1303        VK_LEFT => "left",
1304        VK_HOME => "home",
1305        VK_END => "end",
1306        VK_PRIOR => "pageup",
1307        VK_NEXT => "pagedown",
1308        VK_BROWSER_BACK => "back",
1309        VK_BROWSER_FORWARD => "forward",
1310        VK_ESCAPE => "escape",
1311        VK_INSERT => "insert",
1312        VK_DELETE => "delete",
1313        VK_APPS => "menu",
1314        _ => {
1315            if is_modifier(VIRTUAL_KEY(vk_code)) {
1316                return Some(KeystrokeOrModifier::Modifier(modifiers));
1317            }
1318
1319            if modifiers.control || modifiers.alt || is_keyup {
1320                let basic_key = basic_vkcode_to_string(vk_code, modifiers);
1321                if let Some(basic_key) = basic_key {
1322                    return Some(KeystrokeOrModifier::Keystroke(basic_key));
1323                }
1324            }
1325
1326            if vk_code >= VK_F1.0 && vk_code <= VK_F24.0 {
1327                let offset = vk_code - VK_F1.0;
1328                return Some(KeystrokeOrModifier::Keystroke(Keystroke {
1329                    modifiers,
1330                    key: format!("f{}", offset + 1),
1331                    key_char: None,
1332                }));
1333            };
1334            return None;
1335        }
1336    }
1337    .to_owned();
1338
1339    Some(KeystrokeOrModifier::Keystroke(Keystroke {
1340        modifiers,
1341        key,
1342        key_char: None,
1343    }))
1344}
1345
1346fn parse_char_msg_keystroke(wparam: WPARAM) -> Option<Keystroke> {
1347    let first_char = char::from_u32((wparam.0 as u16).into())?;
1348    if first_char.is_control() {
1349        None
1350    } else {
1351        let mut modifiers = current_modifiers();
1352        // for characters that use 'shift' to type it is expected that the
1353        // shift is not reported if the uppercase/lowercase are the same and instead only the key is reported
1354        if first_char.to_ascii_uppercase() == first_char.to_ascii_lowercase() {
1355            modifiers.shift = false;
1356        }
1357        let key = match first_char {
1358            ' ' => "space".to_string(),
1359            first_char => first_char.to_lowercase().to_string(),
1360        };
1361        Some(Keystroke {
1362            modifiers,
1363            key,
1364            key_char: Some(first_char.to_string()),
1365        })
1366    }
1367}
1368
1369fn parse_ime_compostion_string(ctx: HIMC) -> Option<(String, usize)> {
1370    unsafe {
1371        let string_len = ImmGetCompositionStringW(ctx, GCS_COMPSTR, None, 0);
1372        if string_len >= 0 {
1373            let mut buffer = vec![0u8; string_len as usize + 2];
1374            ImmGetCompositionStringW(
1375                ctx,
1376                GCS_COMPSTR,
1377                Some(buffer.as_mut_ptr() as _),
1378                string_len as _,
1379            );
1380            let wstring = std::slice::from_raw_parts::<u16>(
1381                buffer.as_mut_ptr().cast::<u16>(),
1382                string_len as usize / 2,
1383            );
1384            let string = String::from_utf16_lossy(wstring);
1385            Some((string, string_len as usize / 2))
1386        } else {
1387            None
1388        }
1389    }
1390}
1391
1392#[inline]
1393fn retrieve_composition_cursor_position(ctx: HIMC) -> usize {
1394    unsafe { ImmGetCompositionStringW(ctx, GCS_CURSORPOS, None, 0) as usize }
1395}
1396
1397fn parse_ime_compostion_result(ctx: HIMC) -> Option<String> {
1398    unsafe {
1399        let string_len = ImmGetCompositionStringW(ctx, GCS_RESULTSTR, None, 0);
1400        if string_len >= 0 {
1401            let mut buffer = vec![0u8; string_len as usize + 2];
1402            ImmGetCompositionStringW(
1403                ctx,
1404                GCS_RESULTSTR,
1405                Some(buffer.as_mut_ptr() as _),
1406                string_len as _,
1407            );
1408            let wstring = std::slice::from_raw_parts::<u16>(
1409                buffer.as_mut_ptr().cast::<u16>(),
1410                string_len as usize / 2,
1411            );
1412            let string = String::from_utf16_lossy(wstring);
1413            Some(string)
1414        } else {
1415            None
1416        }
1417    }
1418}
1419
1420fn basic_vkcode_to_string(code: u16, modifiers: Modifiers) -> Option<Keystroke> {
1421    let mapped_code = unsafe { MapVirtualKeyW(code as u32, MAPVK_VK_TO_CHAR) };
1422
1423    let key = match mapped_code {
1424        0 => None,
1425        raw_code => char::from_u32(raw_code),
1426    }?
1427    .to_ascii_lowercase();
1428
1429    let key = if matches!(code as u32, 112..=135) {
1430        format!("f{key}")
1431    } else {
1432        key.to_string()
1433    };
1434
1435    Some(Keystroke {
1436        modifiers,
1437        key,
1438        key_char: None,
1439    })
1440}
1441
1442#[inline]
1443fn is_virtual_key_pressed(vkey: VIRTUAL_KEY) -> bool {
1444    unsafe { GetKeyState(vkey.0 as i32) < 0 }
1445}
1446
1447fn is_modifier(virtual_key: VIRTUAL_KEY) -> bool {
1448    matches!(
1449        virtual_key,
1450        VK_CONTROL | VK_MENU | VK_SHIFT | VK_LWIN | VK_RWIN
1451    )
1452}
1453
1454#[inline]
1455pub(crate) fn current_modifiers() -> Modifiers {
1456    Modifiers {
1457        control: is_virtual_key_pressed(VK_CONTROL),
1458        alt: is_virtual_key_pressed(VK_MENU),
1459        shift: is_virtual_key_pressed(VK_SHIFT),
1460        platform: is_virtual_key_pressed(VK_LWIN) || is_virtual_key_pressed(VK_RWIN),
1461        function: false,
1462    }
1463}
1464
1465fn get_client_area_insets(
1466    handle: HWND,
1467    is_maximized: bool,
1468    windows_version: WindowsVersion,
1469) -> RECT {
1470    // For maximized windows, Windows outdents the window rect from the screen's client rect
1471    // by `frame_thickness` on each edge, meaning `insets` must contain `frame_thickness`
1472    // on all sides (including the top) to avoid the client area extending onto adjacent
1473    // monitors.
1474    //
1475    // For non-maximized windows, things become complicated:
1476    //
1477    // - On Windows 10
1478    // The top inset must be zero, since if there is any nonclient area, Windows will draw
1479    // a full native titlebar outside the client area. (This doesn't occur in the maximized
1480    // case.)
1481    //
1482    // - On Windows 11
1483    // The top inset is calculated using an empirical formula that I derived through various
1484    // tests. Without this, the top 1-2 rows of pixels in our window would be obscured.
1485    let dpi = unsafe { GetDpiForWindow(handle) };
1486    let frame_thickness = get_frame_thickness(dpi);
1487    let top_insets = if is_maximized {
1488        frame_thickness
1489    } else {
1490        match windows_version {
1491            WindowsVersion::Win10 => 0,
1492            WindowsVersion::Win11 => (dpi as f32 / USER_DEFAULT_SCREEN_DPI as f32).round() as i32,
1493        }
1494    };
1495    RECT {
1496        left: frame_thickness,
1497        top: top_insets,
1498        right: frame_thickness,
1499        bottom: frame_thickness,
1500    }
1501}
1502
1503// there is some additional non-visible space when talking about window
1504// borders on Windows:
1505// - SM_CXSIZEFRAME: The resize handle.
1506// - SM_CXPADDEDBORDER: Additional border space that isn't part of the resize handle.
1507fn get_frame_thickness(dpi: u32) -> i32 {
1508    let resize_frame_thickness = unsafe { GetSystemMetricsForDpi(SM_CXSIZEFRAME, dpi) };
1509    let padding_thickness = unsafe { GetSystemMetricsForDpi(SM_CXPADDEDBORDER, dpi) };
1510    resize_frame_thickness + padding_thickness
1511}
1512
1513fn notify_frame_changed(handle: HWND) {
1514    unsafe {
1515        SetWindowPos(
1516            handle,
1517            None,
1518            0,
1519            0,
1520            0,
1521            0,
1522            SWP_FRAMECHANGED
1523                | SWP_NOACTIVATE
1524                | SWP_NOCOPYBITS
1525                | SWP_NOMOVE
1526                | SWP_NOOWNERZORDER
1527                | SWP_NOREPOSITION
1528                | SWP_NOSENDCHANGING
1529                | SWP_NOSIZE
1530                | SWP_NOZORDER,
1531        )
1532        .log_err();
1533    }
1534}
1535
1536fn start_tracking_mouse(
1537    handle: HWND,
1538    state_ptr: &Rc<WindowsWindowStatePtr>,
1539    flags: TRACKMOUSEEVENT_FLAGS,
1540) {
1541    let mut lock = state_ptr.state.borrow_mut();
1542    if !lock.hovered {
1543        lock.hovered = true;
1544        unsafe {
1545            TrackMouseEvent(&mut TRACKMOUSEEVENT {
1546                cbSize: std::mem::size_of::<TRACKMOUSEEVENT>() as u32,
1547                dwFlags: flags,
1548                hwndTrack: handle,
1549                dwHoverTime: HOVER_DEFAULT,
1550            })
1551            .log_err()
1552        };
1553        if let Some(mut callback) = lock.callbacks.hovered_status_change.take() {
1554            drop(lock);
1555            callback(true);
1556            state_ptr.state.borrow_mut().callbacks.hovered_status_change = Some(callback);
1557        }
1558    }
1559}
1560
1561fn with_input_handler<F, R>(state_ptr: &Rc<WindowsWindowStatePtr>, f: F) -> Option<R>
1562where
1563    F: FnOnce(&mut PlatformInputHandler) -> R,
1564{
1565    let mut input_handler = state_ptr.state.borrow_mut().input_handler.take()?;
1566    let result = f(&mut input_handler);
1567    state_ptr.state.borrow_mut().input_handler = Some(input_handler);
1568    Some(result)
1569}
1570
1571fn with_input_handler_and_scale_factor<F, R>(
1572    state_ptr: &Rc<WindowsWindowStatePtr>,
1573    f: F,
1574) -> Option<R>
1575where
1576    F: FnOnce(&mut PlatformInputHandler, f32) -> Option<R>,
1577{
1578    let mut lock = state_ptr.state.borrow_mut();
1579    let mut input_handler = lock.input_handler.take()?;
1580    let scale_factor = lock.scale_factor;
1581    drop(lock);
1582    let result = f(&mut input_handler, scale_factor);
1583    state_ptr.state.borrow_mut().input_handler = Some(input_handler);
1584    result
1585}