events.rs

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