events.rs

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