events.rs

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