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