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_GPUI_CURSOR_STYLE_CHANGED => self.handle_cursor_changed(lparam),
 104            WM_GPUI_FORCE_UPDATE_WINDOW => self.draw_window(handle, true),
 105            _ => None,
 106        };
 107        if let Some(n) = handled {
 108            LRESULT(n)
 109        } else {
 110            unsafe { DefWindowProcW(handle, msg, wparam, lparam) }
 111        }
 112    }
 113
 114    fn handle_move_msg(&self, handle: HWND, lparam: LPARAM) -> Option<isize> {
 115        let mut lock = self.state.borrow_mut();
 116        let origin = logical_point(
 117            lparam.signed_loword() as f32,
 118            lparam.signed_hiword() as f32,
 119            lock.scale_factor,
 120        );
 121        lock.origin = origin;
 122        let size = lock.logical_size;
 123        let center_x = origin.x.0 + size.width.0 / 2.;
 124        let center_y = origin.y.0 + size.height.0 / 2.;
 125        let monitor_bounds = lock.display.bounds();
 126        if center_x < monitor_bounds.left().0
 127            || center_x > monitor_bounds.right().0
 128            || center_y < monitor_bounds.top().0
 129            || center_y > monitor_bounds.bottom().0
 130        {
 131            // center of the window may have moved to another monitor
 132            let monitor = unsafe { MonitorFromWindow(handle, MONITOR_DEFAULTTONULL) };
 133            // minimize the window can trigger this event too, in this case,
 134            // monitor is invalid, we do nothing.
 135            if !monitor.is_invalid() && lock.display.handle != monitor {
 136                // we will get the same monitor if we only have one
 137                lock.display = WindowsDisplay::new_with_handle(monitor);
 138            }
 139        }
 140        if let Some(mut callback) = lock.callbacks.moved.take() {
 141            drop(lock);
 142            callback();
 143            self.state.borrow_mut().callbacks.moved = Some(callback);
 144        }
 145        Some(0)
 146    }
 147
 148    fn handle_get_min_max_info_msg(&self, lparam: LPARAM) -> Option<isize> {
 149        let lock = self.state.borrow();
 150        let min_size = lock.min_size?;
 151        let scale_factor = lock.scale_factor;
 152        let boarder_offset = lock.border_offset;
 153        drop(lock);
 154        unsafe {
 155            let minmax_info = &mut *(lparam.0 as *mut MINMAXINFO);
 156            minmax_info.ptMinTrackSize.x =
 157                min_size.width.scale(scale_factor).0 as i32 + boarder_offset.width_offset;
 158            minmax_info.ptMinTrackSize.y =
 159                min_size.height.scale(scale_factor).0 as i32 + boarder_offset.height_offset;
 160        }
 161        Some(0)
 162    }
 163
 164    fn handle_size_msg(&self, wparam: WPARAM, lparam: LPARAM) -> Option<isize> {
 165        let mut lock = self.state.borrow_mut();
 166
 167        // Don't resize the renderer when the window is minimized, but record that it was minimized so
 168        // that on restore the swap chain can be recreated via `update_drawable_size_even_if_unchanged`.
 169        if wparam.0 == SIZE_MINIMIZED as usize {
 170            lock.restore_from_minimized = lock.callbacks.request_frame.take();
 171            return Some(0);
 172        }
 173
 174        let width = lparam.loword().max(1) as i32;
 175        let height = lparam.hiword().max(1) as i32;
 176        let new_size = size(DevicePixels(width), DevicePixels(height));
 177
 178        let scale_factor = lock.scale_factor;
 179        let mut should_resize_renderer = false;
 180        if lock.restore_from_minimized.is_some() {
 181            lock.callbacks.request_frame = lock.restore_from_minimized.take();
 182        } else {
 183            should_resize_renderer = true;
 184        }
 185        drop(lock);
 186
 187        self.handle_size_change(new_size, scale_factor, should_resize_renderer);
 188        Some(0)
 189    }
 190
 191    fn handle_size_change(
 192        &self,
 193        device_size: Size<DevicePixels>,
 194        scale_factor: f32,
 195        should_resize_renderer: bool,
 196    ) {
 197        let new_logical_size = device_size.to_pixels(scale_factor);
 198        let mut lock = self.state.borrow_mut();
 199        lock.logical_size = new_logical_size;
 200        if should_resize_renderer {
 201            lock.renderer.resize(device_size).log_err();
 202        }
 203        if let Some(mut callback) = lock.callbacks.resize.take() {
 204            drop(lock);
 205            callback(new_logical_size, scale_factor);
 206            self.state.borrow_mut().callbacks.resize = Some(callback);
 207        }
 208    }
 209
 210    fn handle_size_move_loop(&self, handle: HWND) -> Option<isize> {
 211        unsafe {
 212            let ret = SetTimer(
 213                Some(handle),
 214                SIZE_MOVE_LOOP_TIMER_ID,
 215                USER_TIMER_MINIMUM,
 216                None,
 217            );
 218            if ret == 0 {
 219                log::error!(
 220                    "unable to create timer: {}",
 221                    std::io::Error::last_os_error()
 222                );
 223            }
 224        }
 225        None
 226    }
 227
 228    fn handle_size_move_loop_exit(&self, handle: HWND) -> Option<isize> {
 229        unsafe {
 230            KillTimer(Some(handle), SIZE_MOVE_LOOP_TIMER_ID).log_err();
 231        }
 232        None
 233    }
 234
 235    fn handle_timer_msg(&self, handle: HWND, wparam: WPARAM) -> Option<isize> {
 236        if wparam.0 == SIZE_MOVE_LOOP_TIMER_ID {
 237            for runnable in self.main_receiver.drain() {
 238                runnable.run();
 239            }
 240            self.handle_paint_msg(handle)
 241        } else {
 242            None
 243        }
 244    }
 245
 246    fn handle_paint_msg(&self, handle: HWND) -> Option<isize> {
 247        self.draw_window(handle, false)
 248    }
 249
 250    fn handle_close_msg(&self) -> Option<isize> {
 251        let mut callback = self.state.borrow_mut().callbacks.should_close.take()?;
 252        let should_close = callback();
 253        self.state.borrow_mut().callbacks.should_close = Some(callback);
 254        if should_close { None } else { Some(0) }
 255    }
 256
 257    fn handle_destroy_msg(&self, handle: HWND) -> Option<isize> {
 258        let callback = {
 259            let mut lock = self.state.borrow_mut();
 260            lock.callbacks.close.take()
 261        };
 262        if let Some(callback) = callback {
 263            callback();
 264        }
 265        unsafe {
 266            PostThreadMessageW(
 267                self.main_thread_id_win32,
 268                WM_GPUI_CLOSE_ONE_WINDOW,
 269                WPARAM(self.validation_number),
 270                LPARAM(handle.0 as isize),
 271            )
 272            .log_err();
 273        }
 274        Some(0)
 275    }
 276
 277    fn handle_mouse_move_msg(&self, handle: HWND, lparam: LPARAM, wparam: WPARAM) -> Option<isize> {
 278        self.start_tracking_mouse(handle, TME_LEAVE);
 279
 280        let mut lock = self.state.borrow_mut();
 281        let Some(mut func) = lock.callbacks.input.take() else {
 282            return Some(1);
 283        };
 284        let scale_factor = lock.scale_factor;
 285        drop(lock);
 286
 287        let pressed_button = match MODIFIERKEYS_FLAGS(wparam.loword() as u32) {
 288            flags if flags.contains(MK_LBUTTON) => Some(MouseButton::Left),
 289            flags if flags.contains(MK_RBUTTON) => Some(MouseButton::Right),
 290            flags if flags.contains(MK_MBUTTON) => Some(MouseButton::Middle),
 291            flags if flags.contains(MK_XBUTTON1) => {
 292                Some(MouseButton::Navigate(NavigationDirection::Back))
 293            }
 294            flags if flags.contains(MK_XBUTTON2) => {
 295                Some(MouseButton::Navigate(NavigationDirection::Forward))
 296            }
 297            _ => None,
 298        };
 299        let x = lparam.signed_loword() as f32;
 300        let y = lparam.signed_hiword() as f32;
 301        let input = PlatformInput::MouseMove(MouseMoveEvent {
 302            position: logical_point(x, y, scale_factor),
 303            pressed_button,
 304            modifiers: current_modifiers(),
 305        });
 306        let handled = !func(input).propagate;
 307        self.state.borrow_mut().callbacks.input = Some(func);
 308
 309        if handled { Some(0) } else { Some(1) }
 310    }
 311
 312    fn handle_mouse_leave_msg(&self) -> Option<isize> {
 313        let mut lock = self.state.borrow_mut();
 314        lock.hovered = false;
 315        if let Some(mut callback) = lock.callbacks.hovered_status_change.take() {
 316            drop(lock);
 317            callback(false);
 318            self.state.borrow_mut().callbacks.hovered_status_change = Some(callback);
 319        }
 320
 321        Some(0)
 322    }
 323
 324    fn handle_syskeydown_msg(&self, handle: HWND, wparam: WPARAM, lparam: LPARAM) -> Option<isize> {
 325        let mut lock = self.state.borrow_mut();
 326        let input = handle_key_event(handle, wparam, lparam, &mut lock, |keystroke| {
 327            PlatformInput::KeyDown(KeyDownEvent {
 328                keystroke,
 329                is_held: lparam.0 & (0x1 << 30) > 0,
 330            })
 331        })?;
 332        let mut func = lock.callbacks.input.take()?;
 333        drop(lock);
 334
 335        let handled = !func(input).propagate;
 336
 337        let mut lock = self.state.borrow_mut();
 338        lock.callbacks.input = Some(func);
 339
 340        if handled {
 341            lock.system_key_handled = true;
 342            Some(0)
 343        } else {
 344            // we need to call `DefWindowProcW`, or we will lose the system-wide `Alt+F4`, `Alt+{other keys}`
 345            // shortcuts.
 346            None
 347        }
 348    }
 349
 350    fn handle_syskeyup_msg(&self, handle: HWND, wparam: WPARAM, lparam: LPARAM) -> Option<isize> {
 351        let mut lock = self.state.borrow_mut();
 352        let input = handle_key_event(handle, wparam, lparam, &mut lock, |keystroke| {
 353            PlatformInput::KeyUp(KeyUpEvent { keystroke })
 354        })?;
 355        let mut func = lock.callbacks.input.take()?;
 356        drop(lock);
 357        func(input);
 358        self.state.borrow_mut().callbacks.input = Some(func);
 359
 360        // Always return 0 to indicate that the message was handled, so we could properly handle `ModifiersChanged` event.
 361        Some(0)
 362    }
 363
 364    // It's a known bug that you can't trigger `ctrl-shift-0`. See:
 365    // https://superuser.com/questions/1455762/ctrl-shift-number-key-combination-has-stopped-working-for-a-few-numbers
 366    fn handle_keydown_msg(&self, handle: HWND, wparam: WPARAM, lparam: LPARAM) -> Option<isize> {
 367        let mut lock = self.state.borrow_mut();
 368        let Some(input) = handle_key_event(handle, wparam, lparam, &mut lock, |keystroke| {
 369            PlatformInput::KeyDown(KeyDownEvent {
 370                keystroke,
 371                is_held: lparam.0 & (0x1 << 30) > 0,
 372            })
 373        }) else {
 374            return Some(1);
 375        };
 376        drop(lock);
 377
 378        let is_composing = self
 379            .with_input_handler(|input_handler| input_handler.marked_text_range())
 380            .flatten()
 381            .is_some();
 382        if is_composing {
 383            translate_message(handle, wparam, lparam);
 384            return Some(0);
 385        }
 386
 387        let Some(mut func) = self.state.borrow_mut().callbacks.input.take() else {
 388            return Some(1);
 389        };
 390
 391        let handled = !func(input).propagate;
 392
 393        self.state.borrow_mut().callbacks.input = Some(func);
 394
 395        if handled {
 396            Some(0)
 397        } else {
 398            translate_message(handle, wparam, lparam);
 399            Some(1)
 400        }
 401    }
 402
 403    fn handle_keyup_msg(&self, handle: HWND, wparam: WPARAM, lparam: LPARAM) -> Option<isize> {
 404        let mut lock = self.state.borrow_mut();
 405        let Some(input) = handle_key_event(handle, wparam, lparam, &mut lock, |keystroke| {
 406            PlatformInput::KeyUp(KeyUpEvent { keystroke })
 407        }) else {
 408            return Some(1);
 409        };
 410
 411        let Some(mut func) = lock.callbacks.input.take() else {
 412            return Some(1);
 413        };
 414        drop(lock);
 415
 416        let handled = !func(input).propagate;
 417        self.state.borrow_mut().callbacks.input = Some(func);
 418
 419        if handled { Some(0) } else { Some(1) }
 420    }
 421
 422    fn handle_char_msg(&self, wparam: WPARAM) -> Option<isize> {
 423        let input = self.parse_char_message(wparam)?;
 424        self.with_input_handler(|input_handler| {
 425            input_handler.replace_text_in_range(None, &input);
 426        });
 427
 428        Some(0)
 429    }
 430
 431    fn handle_dead_char_msg(&self, wparam: WPARAM) -> Option<isize> {
 432        let ch = char::from_u32(wparam.0 as u32)?.to_string();
 433        self.with_input_handler(|input_handler| {
 434            input_handler.replace_and_mark_text_in_range(None, &ch, None);
 435        });
 436        None
 437    }
 438
 439    fn handle_mouse_down_msg(
 440        &self,
 441        handle: HWND,
 442        button: MouseButton,
 443        lparam: LPARAM,
 444    ) -> Option<isize> {
 445        unsafe { SetCapture(handle) };
 446        let mut lock = self.state.borrow_mut();
 447        let Some(mut func) = lock.callbacks.input.take() else {
 448            return Some(1);
 449        };
 450        let x = lparam.signed_loword();
 451        let y = lparam.signed_hiword();
 452        let physical_point = point(DevicePixels(x as i32), DevicePixels(y as i32));
 453        let click_count = lock.click_state.update(button, physical_point);
 454        let scale_factor = lock.scale_factor;
 455        drop(lock);
 456
 457        let input = PlatformInput::MouseDown(MouseDownEvent {
 458            button,
 459            position: logical_point(x as f32, y as f32, scale_factor),
 460            modifiers: current_modifiers(),
 461            click_count,
 462            first_mouse: false,
 463        });
 464        let handled = !func(input).propagate;
 465        self.state.borrow_mut().callbacks.input = Some(func);
 466
 467        if handled { Some(0) } else { Some(1) }
 468    }
 469
 470    fn handle_mouse_up_msg(
 471        &self,
 472        _handle: HWND,
 473        button: MouseButton,
 474        lparam: LPARAM,
 475    ) -> Option<isize> {
 476        unsafe { ReleaseCapture().log_err() };
 477        let mut lock = self.state.borrow_mut();
 478        let Some(mut func) = lock.callbacks.input.take() else {
 479            return Some(1);
 480        };
 481        let x = lparam.signed_loword() as f32;
 482        let y = lparam.signed_hiword() as f32;
 483        let click_count = lock.click_state.current_count;
 484        let scale_factor = lock.scale_factor;
 485        drop(lock);
 486
 487        let input = PlatformInput::MouseUp(MouseUpEvent {
 488            button,
 489            position: logical_point(x, y, scale_factor),
 490            modifiers: current_modifiers(),
 491            click_count,
 492        });
 493        let handled = !func(input).propagate;
 494        self.state.borrow_mut().callbacks.input = Some(func);
 495
 496        if handled { Some(0) } else { Some(1) }
 497    }
 498
 499    fn handle_xbutton_msg(
 500        &self,
 501        handle: HWND,
 502        wparam: WPARAM,
 503        lparam: LPARAM,
 504        handler: impl Fn(&Self, HWND, MouseButton, LPARAM) -> Option<isize>,
 505    ) -> Option<isize> {
 506        let nav_dir = match wparam.hiword() {
 507            XBUTTON1 => NavigationDirection::Back,
 508            XBUTTON2 => NavigationDirection::Forward,
 509            _ => return Some(1),
 510        };
 511        handler(self, handle, MouseButton::Navigate(nav_dir), lparam)
 512    }
 513
 514    fn handle_mouse_wheel_msg(
 515        &self,
 516        handle: HWND,
 517        wparam: WPARAM,
 518        lparam: LPARAM,
 519    ) -> Option<isize> {
 520        let modifiers = current_modifiers();
 521        let mut lock = self.state.borrow_mut();
 522        let Some(mut func) = lock.callbacks.input.take() else {
 523            return Some(1);
 524        };
 525        let scale_factor = lock.scale_factor;
 526        let wheel_scroll_amount = match modifiers.shift {
 527            true => lock.system_settings.mouse_wheel_settings.wheel_scroll_chars,
 528            false => lock.system_settings.mouse_wheel_settings.wheel_scroll_lines,
 529        };
 530        drop(lock);
 531
 532        let wheel_distance =
 533            (wparam.signed_hiword() as f32 / WHEEL_DELTA as f32) * wheel_scroll_amount as f32;
 534        let mut cursor_point = POINT {
 535            x: lparam.signed_loword().into(),
 536            y: lparam.signed_hiword().into(),
 537        };
 538        unsafe { ScreenToClient(handle, &mut cursor_point).ok().log_err() };
 539        let input = PlatformInput::ScrollWheel(ScrollWheelEvent {
 540            position: logical_point(cursor_point.x as f32, cursor_point.y as f32, scale_factor),
 541            delta: ScrollDelta::Lines(match modifiers.shift {
 542                true => Point {
 543                    x: wheel_distance,
 544                    y: 0.0,
 545                },
 546                false => Point {
 547                    y: wheel_distance,
 548                    x: 0.0,
 549                },
 550            }),
 551            modifiers,
 552            touch_phase: TouchPhase::Moved,
 553        });
 554        let handled = !func(input).propagate;
 555        self.state.borrow_mut().callbacks.input = Some(func);
 556
 557        if handled { Some(0) } else { Some(1) }
 558    }
 559
 560    fn handle_mouse_horizontal_wheel_msg(
 561        &self,
 562        handle: HWND,
 563        wparam: WPARAM,
 564        lparam: LPARAM,
 565    ) -> Option<isize> {
 566        let mut lock = self.state.borrow_mut();
 567        let Some(mut func) = lock.callbacks.input.take() else {
 568            return Some(1);
 569        };
 570        let scale_factor = lock.scale_factor;
 571        let wheel_scroll_chars = lock.system_settings.mouse_wheel_settings.wheel_scroll_chars;
 572        drop(lock);
 573
 574        let wheel_distance =
 575            (-wparam.signed_hiword() as f32 / WHEEL_DELTA as f32) * wheel_scroll_chars as f32;
 576        let mut cursor_point = POINT {
 577            x: lparam.signed_loword().into(),
 578            y: lparam.signed_hiword().into(),
 579        };
 580        unsafe { ScreenToClient(handle, &mut cursor_point).ok().log_err() };
 581        let event = PlatformInput::ScrollWheel(ScrollWheelEvent {
 582            position: logical_point(cursor_point.x as f32, cursor_point.y as f32, scale_factor),
 583            delta: ScrollDelta::Lines(Point {
 584                x: wheel_distance,
 585                y: 0.0,
 586            }),
 587            modifiers: current_modifiers(),
 588            touch_phase: TouchPhase::Moved,
 589        });
 590        let handled = !func(event).propagate;
 591        self.state.borrow_mut().callbacks.input = Some(func);
 592
 593        if handled { Some(0) } else { Some(1) }
 594    }
 595
 596    fn retrieve_caret_position(&self) -> Option<POINT> {
 597        self.with_input_handler_and_scale_factor(|input_handler, scale_factor| {
 598            let caret_range = input_handler.selected_text_range(false)?;
 599            let caret_position = input_handler.bounds_for_range(caret_range.range)?;
 600            Some(POINT {
 601                // logical to physical
 602                x: (caret_position.origin.x.0 * scale_factor) as i32,
 603                y: (caret_position.origin.y.0 * scale_factor) as i32
 604                    + ((caret_position.size.height.0 * scale_factor) as i32 / 2),
 605            })
 606        })
 607    }
 608
 609    fn handle_ime_position(&self, handle: HWND) -> Option<isize> {
 610        unsafe {
 611            let ctx = ImmGetContext(handle);
 612
 613            let Some(caret_position) = self.retrieve_caret_position() else {
 614                return Some(0);
 615            };
 616            {
 617                let config = COMPOSITIONFORM {
 618                    dwStyle: CFS_POINT,
 619                    ptCurrentPos: caret_position,
 620                    ..Default::default()
 621                };
 622                ImmSetCompositionWindow(ctx, &config as _).ok().log_err();
 623            }
 624            {
 625                let config = CANDIDATEFORM {
 626                    dwStyle: CFS_CANDIDATEPOS,
 627                    ptCurrentPos: caret_position,
 628                    ..Default::default()
 629                };
 630                ImmSetCandidateWindow(ctx, &config as _).ok().log_err();
 631            }
 632            ImmReleaseContext(handle, ctx).ok().log_err();
 633            Some(0)
 634        }
 635    }
 636
 637    fn handle_ime_composition(&self, handle: HWND, lparam: LPARAM) -> Option<isize> {
 638        let ctx = unsafe { ImmGetContext(handle) };
 639        let result = self.handle_ime_composition_inner(ctx, lparam);
 640        unsafe { ImmReleaseContext(handle, ctx).ok().log_err() };
 641        result
 642    }
 643
 644    fn handle_ime_composition_inner(&self, ctx: HIMC, lparam: LPARAM) -> Option<isize> {
 645        let lparam = lparam.0 as u32;
 646        if lparam == 0 {
 647            // Japanese IME may send this message with lparam = 0, which indicates that
 648            // there is no composition string.
 649            self.with_input_handler(|input_handler| {
 650                input_handler.replace_text_in_range(None, "");
 651            })?;
 652            Some(0)
 653        } else {
 654            if lparam & GCS_COMPSTR.0 > 0 {
 655                let comp_string = parse_ime_composition_string(ctx, GCS_COMPSTR)?;
 656                let caret_pos =
 657                    (!comp_string.is_empty() && lparam & GCS_CURSORPOS.0 > 0).then(|| {
 658                        let pos = retrieve_composition_cursor_position(ctx);
 659                        pos..pos
 660                    });
 661                self.with_input_handler(|input_handler| {
 662                    input_handler.replace_and_mark_text_in_range(None, &comp_string, caret_pos);
 663                })?;
 664            }
 665            if lparam & GCS_RESULTSTR.0 > 0 {
 666                let comp_result = parse_ime_composition_string(ctx, GCS_RESULTSTR)?;
 667                self.with_input_handler(|input_handler| {
 668                    input_handler.replace_text_in_range(None, &comp_result);
 669                })?;
 670                return Some(0);
 671            }
 672
 673            // currently, we don't care other stuff
 674            None
 675        }
 676    }
 677
 678    /// SEE: https://learn.microsoft.com/en-us/windows/win32/winmsg/wm-nccalcsize
 679    fn handle_calc_client_size(
 680        &self,
 681        handle: HWND,
 682        wparam: WPARAM,
 683        lparam: LPARAM,
 684    ) -> Option<isize> {
 685        if !self.hide_title_bar || self.state.borrow().is_fullscreen() || wparam.0 == 0 {
 686            return None;
 687        }
 688
 689        let is_maximized = self.state.borrow().is_maximized();
 690        let insets = get_client_area_insets(handle, is_maximized, self.windows_version);
 691        // wparam is TRUE so lparam points to an NCCALCSIZE_PARAMS structure
 692        let mut params = lparam.0 as *mut NCCALCSIZE_PARAMS;
 693        let mut requested_client_rect = unsafe { &mut ((*params).rgrc) };
 694
 695        requested_client_rect[0].left += insets.left;
 696        requested_client_rect[0].top += insets.top;
 697        requested_client_rect[0].right -= insets.right;
 698        requested_client_rect[0].bottom -= insets.bottom;
 699
 700        // Fix auto hide taskbar not showing. This solution is based on the approach
 701        // used by Chrome. However, it may result in one row of pixels being obscured
 702        // in our client area. But as Chrome says, "there seems to be no better solution."
 703        if is_maximized {
 704            if let Some(ref taskbar_position) = self
 705                .state
 706                .borrow()
 707                .system_settings
 708                .auto_hide_taskbar_position
 709            {
 710                // Fot the auto-hide taskbar, adjust in by 1 pixel on taskbar edge,
 711                // so the window isn't treated as a "fullscreen app", which would cause
 712                // the taskbar to disappear.
 713                match taskbar_position {
 714                    AutoHideTaskbarPosition::Left => {
 715                        requested_client_rect[0].left += AUTO_HIDE_TASKBAR_THICKNESS_PX
 716                    }
 717                    AutoHideTaskbarPosition::Top => {
 718                        requested_client_rect[0].top += AUTO_HIDE_TASKBAR_THICKNESS_PX
 719                    }
 720                    AutoHideTaskbarPosition::Right => {
 721                        requested_client_rect[0].right -= AUTO_HIDE_TASKBAR_THICKNESS_PX
 722                    }
 723                    AutoHideTaskbarPosition::Bottom => {
 724                        requested_client_rect[0].bottom -= AUTO_HIDE_TASKBAR_THICKNESS_PX
 725                    }
 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.clone());
 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            if let Some(parameter_string) = unsafe { parameter.to_string() }.log_err() {
1129                log::info!("System settings changed: {}", parameter_string);
1130                match parameter_string.as_str() {
1131                    "ImmersiveColorSet" => {
1132                        let new_appearance = system_appearance()
1133                            .context(
1134                                "unable to get system appearance when handling ImmersiveColorSet",
1135                            )
1136                            .log_err()?;
1137                        let mut lock = self.state.borrow_mut();
1138                        if new_appearance != lock.appearance {
1139                            lock.appearance = new_appearance;
1140                            let mut callback = lock.callbacks.appearance_changed.take()?;
1141                            drop(lock);
1142                            callback();
1143                            self.state.borrow_mut().callbacks.appearance_changed = Some(callback);
1144                            configure_dwm_dark_mode(handle, new_appearance);
1145                        }
1146                    }
1147                    _ => {}
1148                }
1149            }
1150        }
1151        Some(0)
1152    }
1153
1154    fn handle_input_language_changed(&self, lparam: LPARAM) -> Option<isize> {
1155        let thread = self.main_thread_id_win32;
1156        let validation = self.validation_number;
1157        unsafe {
1158            PostThreadMessageW(thread, WM_INPUTLANGCHANGE, WPARAM(validation), lparam).log_err();
1159        }
1160        Some(0)
1161    }
1162
1163    fn handle_device_change_msg(&self, handle: HWND, wparam: WPARAM) -> Option<isize> {
1164        if wparam.0 == DBT_DEVNODES_CHANGED as usize {
1165            // The reason for sending this message is to actually trigger a redraw of the window.
1166            unsafe {
1167                PostMessageW(
1168                    Some(handle),
1169                    WM_GPUI_FORCE_UPDATE_WINDOW,
1170                    WPARAM(0),
1171                    LPARAM(0),
1172                )
1173                .log_err();
1174            }
1175            // If the GPU device is lost, this redraw will take care of recreating the device context.
1176            // The WM_GPUI_FORCE_UPDATE_WINDOW message will take care of redrawing the window, after
1177            // the device context has been recreated.
1178            self.draw_window(handle, true)
1179        } else {
1180            // Other device change messages are not handled.
1181            None
1182        }
1183    }
1184
1185    #[inline]
1186    fn draw_window(&self, handle: HWND, force_render: bool) -> Option<isize> {
1187        let mut request_frame = self.state.borrow_mut().callbacks.request_frame.take()?;
1188        request_frame(RequestFrameOptions {
1189            require_presentation: false,
1190            force_render,
1191        });
1192        self.state.borrow_mut().callbacks.request_frame = Some(request_frame);
1193        unsafe { ValidateRect(Some(handle), None).ok().log_err() };
1194        Some(0)
1195    }
1196
1197    #[inline]
1198    fn parse_char_message(&self, wparam: WPARAM) -> Option<String> {
1199        let code_point = wparam.loword();
1200        let mut lock = self.state.borrow_mut();
1201        // https://www.unicode.org/versions/Unicode16.0.0/core-spec/chapter-3/#G2630
1202        match code_point {
1203            0xD800..=0xDBFF => {
1204                // High surrogate, wait for low surrogate
1205                lock.pending_surrogate = Some(code_point);
1206                None
1207            }
1208            0xDC00..=0xDFFF => {
1209                if let Some(high_surrogate) = lock.pending_surrogate.take() {
1210                    // Low surrogate, combine with pending high surrogate
1211                    String::from_utf16(&[high_surrogate, code_point]).ok()
1212                } else {
1213                    // Invalid low surrogate without a preceding high surrogate
1214                    log::warn!(
1215                        "Received low surrogate without a preceding high surrogate: {code_point:x}"
1216                    );
1217                    None
1218                }
1219            }
1220            _ => {
1221                lock.pending_surrogate = None;
1222                char::from_u32(code_point as u32)
1223                    .filter(|c| !c.is_control())
1224                    .map(|c| c.to_string())
1225            }
1226        }
1227    }
1228
1229    fn start_tracking_mouse(&self, handle: HWND, flags: TRACKMOUSEEVENT_FLAGS) {
1230        let mut lock = self.state.borrow_mut();
1231        if !lock.hovered {
1232            lock.hovered = true;
1233            unsafe {
1234                TrackMouseEvent(&mut TRACKMOUSEEVENT {
1235                    cbSize: std::mem::size_of::<TRACKMOUSEEVENT>() as u32,
1236                    dwFlags: flags,
1237                    hwndTrack: handle,
1238                    dwHoverTime: HOVER_DEFAULT,
1239                })
1240                .log_err()
1241            };
1242            if let Some(mut callback) = lock.callbacks.hovered_status_change.take() {
1243                drop(lock);
1244                callback(true);
1245                self.state.borrow_mut().callbacks.hovered_status_change = Some(callback);
1246            }
1247        }
1248    }
1249
1250    fn with_input_handler<F, R>(&self, f: F) -> Option<R>
1251    where
1252        F: FnOnce(&mut PlatformInputHandler) -> R,
1253    {
1254        let mut input_handler = self.state.borrow_mut().input_handler.take()?;
1255        let result = f(&mut input_handler);
1256        self.state.borrow_mut().input_handler = Some(input_handler);
1257        Some(result)
1258    }
1259
1260    fn with_input_handler_and_scale_factor<F, R>(&self, f: F) -> Option<R>
1261    where
1262        F: FnOnce(&mut PlatformInputHandler, f32) -> Option<R>,
1263    {
1264        let mut lock = self.state.borrow_mut();
1265        let mut input_handler = lock.input_handler.take()?;
1266        let scale_factor = lock.scale_factor;
1267        drop(lock);
1268        let result = f(&mut input_handler, scale_factor);
1269        self.state.borrow_mut().input_handler = Some(input_handler);
1270        result
1271    }
1272}
1273
1274#[inline]
1275fn translate_message(handle: HWND, wparam: WPARAM, lparam: LPARAM) {
1276    let msg = MSG {
1277        hwnd: handle,
1278        message: WM_KEYDOWN,
1279        wParam: wparam,
1280        lParam: lparam,
1281        // It seems like leaving the following two parameters empty doesn't break key events, they still work as expected.
1282        // But if any bugs pop up after this PR, this is probably the place to look first.
1283        time: 0,
1284        pt: POINT::default(),
1285    };
1286    unsafe { TranslateMessage(&msg).ok().log_err() };
1287}
1288
1289fn handle_key_event<F>(
1290    handle: HWND,
1291    wparam: WPARAM,
1292    lparam: LPARAM,
1293    state: &mut WindowsWindowState,
1294    f: F,
1295) -> Option<PlatformInput>
1296where
1297    F: FnOnce(Keystroke) -> PlatformInput,
1298{
1299    let virtual_key = VIRTUAL_KEY(wparam.loword());
1300    let mut modifiers = current_modifiers();
1301
1302    match virtual_key {
1303        VK_SHIFT | VK_CONTROL | VK_MENU | VK_LWIN | VK_RWIN => {
1304            if state
1305                .last_reported_modifiers
1306                .is_some_and(|prev_modifiers| prev_modifiers == modifiers)
1307            {
1308                return None;
1309            }
1310            state.last_reported_modifiers = Some(modifiers);
1311            Some(PlatformInput::ModifiersChanged(ModifiersChangedEvent {
1312                modifiers,
1313                capslock: current_capslock(),
1314            }))
1315        }
1316        VK_PACKET => {
1317            translate_message(handle, wparam, lparam);
1318            None
1319        }
1320        VK_CAPITAL => {
1321            let capslock = current_capslock();
1322            if state
1323                .last_reported_capslock
1324                .is_some_and(|prev_capslock| prev_capslock == capslock)
1325            {
1326                return None;
1327            }
1328            state.last_reported_capslock = Some(capslock);
1329            Some(PlatformInput::ModifiersChanged(ModifiersChangedEvent {
1330                modifiers,
1331                capslock,
1332            }))
1333        }
1334        vkey => {
1335            let vkey = if vkey == VK_PROCESSKEY {
1336                VIRTUAL_KEY(unsafe { ImmGetVirtualKey(handle) } as u16)
1337            } else {
1338                vkey
1339            };
1340            let keystroke = parse_normal_key(vkey, lparam, modifiers)?;
1341            Some(f(keystroke))
1342        }
1343    }
1344}
1345
1346fn parse_immutable(vkey: VIRTUAL_KEY) -> Option<String> {
1347    Some(
1348        match vkey {
1349            VK_SPACE => "space",
1350            VK_BACK => "backspace",
1351            VK_RETURN => "enter",
1352            VK_TAB => "tab",
1353            VK_UP => "up",
1354            VK_DOWN => "down",
1355            VK_RIGHT => "right",
1356            VK_LEFT => "left",
1357            VK_HOME => "home",
1358            VK_END => "end",
1359            VK_PRIOR => "pageup",
1360            VK_NEXT => "pagedown",
1361            VK_BROWSER_BACK => "back",
1362            VK_BROWSER_FORWARD => "forward",
1363            VK_ESCAPE => "escape",
1364            VK_INSERT => "insert",
1365            VK_DELETE => "delete",
1366            VK_APPS => "menu",
1367            VK_F1 => "f1",
1368            VK_F2 => "f2",
1369            VK_F3 => "f3",
1370            VK_F4 => "f4",
1371            VK_F5 => "f5",
1372            VK_F6 => "f6",
1373            VK_F7 => "f7",
1374            VK_F8 => "f8",
1375            VK_F9 => "f9",
1376            VK_F10 => "f10",
1377            VK_F11 => "f11",
1378            VK_F12 => "f12",
1379            VK_F13 => "f13",
1380            VK_F14 => "f14",
1381            VK_F15 => "f15",
1382            VK_F16 => "f16",
1383            VK_F17 => "f17",
1384            VK_F18 => "f18",
1385            VK_F19 => "f19",
1386            VK_F20 => "f20",
1387            VK_F21 => "f21",
1388            VK_F22 => "f22",
1389            VK_F23 => "f23",
1390            VK_F24 => "f24",
1391            _ => return None,
1392        }
1393        .to_string(),
1394    )
1395}
1396
1397fn parse_normal_key(
1398    vkey: VIRTUAL_KEY,
1399    lparam: LPARAM,
1400    mut modifiers: Modifiers,
1401) -> Option<Keystroke> {
1402    let mut key_char = None;
1403    let key = parse_immutable(vkey).or_else(|| {
1404        let scan_code = lparam.hiword() & 0xFF;
1405        key_char = generate_key_char(
1406            vkey,
1407            scan_code as u32,
1408            modifiers.control,
1409            modifiers.shift,
1410            modifiers.alt,
1411        );
1412        get_keystroke_key(vkey, scan_code as u32, &mut modifiers)
1413    })?;
1414    Some(Keystroke {
1415        modifiers,
1416        key,
1417        key_char,
1418    })
1419}
1420
1421fn parse_ime_composition_string(ctx: HIMC, comp_type: IME_COMPOSITION_STRING) -> Option<String> {
1422    unsafe {
1423        let string_len = ImmGetCompositionStringW(ctx, comp_type, None, 0);
1424        if string_len >= 0 {
1425            let mut buffer = vec![0u8; string_len as usize + 2];
1426            ImmGetCompositionStringW(
1427                ctx,
1428                comp_type,
1429                Some(buffer.as_mut_ptr() as _),
1430                string_len as _,
1431            );
1432            let wstring = std::slice::from_raw_parts::<u16>(
1433                buffer.as_mut_ptr().cast::<u16>(),
1434                string_len as usize / 2,
1435            );
1436            Some(String::from_utf16_lossy(wstring))
1437        } else {
1438            None
1439        }
1440    }
1441}
1442
1443#[inline]
1444fn retrieve_composition_cursor_position(ctx: HIMC) -> usize {
1445    unsafe { ImmGetCompositionStringW(ctx, GCS_CURSORPOS, None, 0) as usize }
1446}
1447
1448#[inline]
1449fn is_virtual_key_pressed(vkey: VIRTUAL_KEY) -> bool {
1450    unsafe { GetKeyState(vkey.0 as i32) < 0 }
1451}
1452
1453#[inline]
1454pub(crate) fn current_modifiers() -> Modifiers {
1455    Modifiers {
1456        control: is_virtual_key_pressed(VK_CONTROL),
1457        alt: is_virtual_key_pressed(VK_MENU),
1458        shift: is_virtual_key_pressed(VK_SHIFT),
1459        platform: is_virtual_key_pressed(VK_LWIN) || is_virtual_key_pressed(VK_RWIN),
1460        function: false,
1461    }
1462}
1463
1464#[inline]
1465pub(crate) fn current_capslock() -> Capslock {
1466    let on = unsafe { GetKeyState(VK_CAPITAL.0 as i32) & 1 } > 0;
1467    Capslock { on: on }
1468}
1469
1470fn get_client_area_insets(
1471    handle: HWND,
1472    is_maximized: bool,
1473    windows_version: WindowsVersion,
1474) -> RECT {
1475    // For maximized windows, Windows outdents the window rect from the screen's client rect
1476    // by `frame_thickness` on each edge, meaning `insets` must contain `frame_thickness`
1477    // on all sides (including the top) to avoid the client area extending onto adjacent
1478    // monitors.
1479    //
1480    // For non-maximized windows, things become complicated:
1481    //
1482    // - On Windows 10
1483    // The top inset must be zero, since if there is any nonclient area, Windows will draw
1484    // a full native titlebar outside the client area. (This doesn't occur in the maximized
1485    // case.)
1486    //
1487    // - On Windows 11
1488    // The top inset is calculated using an empirical formula that I derived through various
1489    // tests. Without this, the top 1-2 rows of pixels in our window would be obscured.
1490    let dpi = unsafe { GetDpiForWindow(handle) };
1491    let frame_thickness = get_frame_thickness(dpi);
1492    let top_insets = if is_maximized {
1493        frame_thickness
1494    } else {
1495        match windows_version {
1496            WindowsVersion::Win10 => 0,
1497            WindowsVersion::Win11 => (dpi as f32 / USER_DEFAULT_SCREEN_DPI as f32).round() as i32,
1498        }
1499    };
1500    RECT {
1501        left: frame_thickness,
1502        top: top_insets,
1503        right: frame_thickness,
1504        bottom: frame_thickness,
1505    }
1506}
1507
1508// there is some additional non-visible space when talking about window
1509// borders on Windows:
1510// - SM_CXSIZEFRAME: The resize handle.
1511// - SM_CXPADDEDBORDER: Additional border space that isn't part of the resize handle.
1512fn get_frame_thickness(dpi: u32) -> i32 {
1513    let resize_frame_thickness = unsafe { GetSystemMetricsForDpi(SM_CXSIZEFRAME, dpi) };
1514    let padding_thickness = unsafe { GetSystemMetricsForDpi(SM_CXPADDEDBORDER, dpi) };
1515    resize_frame_thickness + padding_thickness
1516}
1517
1518fn notify_frame_changed(handle: HWND) {
1519    unsafe {
1520        SetWindowPos(
1521            handle,
1522            None,
1523            0,
1524            0,
1525            0,
1526            0,
1527            SWP_FRAMECHANGED
1528                | SWP_NOACTIVATE
1529                | SWP_NOCOPYBITS
1530                | SWP_NOMOVE
1531                | SWP_NOOWNERZORDER
1532                | SWP_NOREPOSITION
1533                | SWP_NOSENDCHANGING
1534                | SWP_NOSIZE
1535                | SWP_NOZORDER,
1536        )
1537        .log_err();
1538    }
1539}