events.rs

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