1use std::{
   2    rc::Rc,
   3    time::{Duration, Instant},
   4};
   5
   6use ::util::ResultExt;
   7use anyhow::Context as _;
   8use windows::{
   9    Win32::{
  10        Foundation::*,
  11        Graphics::Gdi::*,
  12        System::SystemServices::*,
  13        UI::{
  14            Controls::*,
  15            HiDpi::*,
  16            Input::{Ime::*, KeyboardAndMouse::*},
  17            WindowsAndMessaging::*,
  18        },
  19    },
  20    core::PCWSTR,
  21};
  22
  23use crate::*;
  24
  25pub(crate) const WM_GPUI_CURSOR_STYLE_CHANGED: u32 = WM_USER + 1;
  26pub(crate) const WM_GPUI_CLOSE_ONE_WINDOW: u32 = WM_USER + 2;
  27pub(crate) const WM_GPUI_TASK_DISPATCHED_ON_MAIN_THREAD: u32 = WM_USER + 3;
  28pub(crate) const WM_GPUI_DOCK_MENU_ACTION: u32 = WM_USER + 4;
  29pub(crate) const WM_GPUI_FORCE_UPDATE_WINDOW: u32 = WM_USER + 5;
  30pub(crate) const WM_GPUI_KEYBOARD_LAYOUT_CHANGED: u32 = WM_USER + 6;
  31pub(crate) const WM_GPUI_GPU_DEVICE_LOST: u32 = WM_USER + 7;
  32
  33const SIZE_MOVE_LOOP_TIMER_ID: usize = 1;
  34const AUTO_HIDE_TASKBAR_THICKNESS_PX: i32 = 1;
  35
  36impl WindowsWindowInner {
  37    pub(crate) fn handle_msg(
  38        self: &Rc<Self>,
  39        handle: HWND,
  40        msg: u32,
  41        wparam: WPARAM,
  42        lparam: LPARAM,
  43    ) -> LRESULT {
  44        let handled = match msg {
  45            WM_ACTIVATE => self.handle_activate_msg(wparam),
  46            WM_CREATE => self.handle_create_msg(handle),
  47            WM_MOVE => self.handle_move_msg(handle, lparam),
  48            WM_SIZE => self.handle_size_msg(wparam, lparam),
  49            WM_GETMINMAXINFO => self.handle_get_min_max_info_msg(lparam),
  50            WM_ENTERSIZEMOVE | WM_ENTERMENULOOP => self.handle_size_move_loop(handle),
  51            WM_EXITSIZEMOVE | WM_EXITMENULOOP => self.handle_size_move_loop_exit(handle),
  52            WM_TIMER => self.handle_timer_msg(handle, wparam),
  53            WM_NCCALCSIZE => self.handle_calc_client_size(handle, wparam, lparam),
  54            WM_DPICHANGED => self.handle_dpi_changed_msg(handle, wparam, lparam),
  55            WM_DISPLAYCHANGE => self.handle_display_change_msg(handle),
  56            WM_NCHITTEST => self.handle_hit_test_msg(handle, msg, wparam, lparam),
  57            WM_PAINT => self.handle_paint_msg(handle),
  58            WM_CLOSE => self.handle_close_msg(),
  59            WM_DESTROY => self.handle_destroy_msg(handle),
  60            WM_MOUSEMOVE => self.handle_mouse_move_msg(handle, lparam, wparam),
  61            WM_MOUSELEAVE | WM_NCMOUSELEAVE => self.handle_mouse_leave_msg(),
  62            WM_NCMOUSEMOVE => self.handle_nc_mouse_move_msg(handle, lparam),
  63            // Treat double click as a second single click, since we track the double clicks ourselves.
  64            // If you don't interact with any elements, this will fall through to the windows default
  65            // behavior of toggling whether the window is maximized.
  66            WM_NCLBUTTONDBLCLK | WM_NCLBUTTONDOWN => {
  67                self.handle_nc_mouse_down_msg(handle, MouseButton::Left, wparam, lparam)
  68            }
  69            WM_NCRBUTTONDOWN => {
  70                self.handle_nc_mouse_down_msg(handle, MouseButton::Right, wparam, lparam)
  71            }
  72            WM_NCMBUTTONDOWN => {
  73                self.handle_nc_mouse_down_msg(handle, MouseButton::Middle, wparam, lparam)
  74            }
  75            WM_NCLBUTTONUP => {
  76                self.handle_nc_mouse_up_msg(handle, MouseButton::Left, wparam, lparam)
  77            }
  78            WM_NCRBUTTONUP => {
  79                self.handle_nc_mouse_up_msg(handle, MouseButton::Right, wparam, lparam)
  80            }
  81            WM_NCMBUTTONUP => {
  82                self.handle_nc_mouse_up_msg(handle, MouseButton::Middle, wparam, lparam)
  83            }
  84            WM_LBUTTONDOWN => self.handle_mouse_down_msg(handle, MouseButton::Left, lparam),
  85            WM_RBUTTONDOWN => self.handle_mouse_down_msg(handle, MouseButton::Right, lparam),
  86            WM_MBUTTONDOWN => self.handle_mouse_down_msg(handle, MouseButton::Middle, lparam),
  87            WM_XBUTTONDOWN => {
  88                self.handle_xbutton_msg(handle, wparam, lparam, Self::handle_mouse_down_msg)
  89            }
  90            WM_LBUTTONUP => self.handle_mouse_up_msg(handle, MouseButton::Left, lparam),
  91            WM_RBUTTONUP => self.handle_mouse_up_msg(handle, MouseButton::Right, lparam),
  92            WM_MBUTTONUP => self.handle_mouse_up_msg(handle, MouseButton::Middle, lparam),
  93            WM_XBUTTONUP => {
  94                self.handle_xbutton_msg(handle, wparam, lparam, Self::handle_mouse_up_msg)
  95            }
  96            WM_MOUSEWHEEL => self.handle_mouse_wheel_msg(handle, wparam, lparam),
  97            WM_MOUSEHWHEEL => self.handle_mouse_horizontal_wheel_msg(handle, wparam, lparam),
  98            WM_SYSKEYDOWN => self.handle_syskeydown_msg(handle, wparam, lparam),
  99            WM_SYSKEYUP => self.handle_syskeyup_msg(handle, wparam, lparam),
 100            WM_SYSCOMMAND => self.handle_system_command(wparam),
 101            WM_KEYDOWN => self.handle_keydown_msg(handle, wparam, lparam),
 102            WM_KEYUP => self.handle_keyup_msg(handle, wparam, lparam),
 103            WM_CHAR => self.handle_char_msg(wparam),
 104            WM_DEADCHAR => self.handle_dead_char_msg(wparam),
 105            WM_IME_STARTCOMPOSITION => self.handle_ime_position(handle),
 106            WM_IME_COMPOSITION => self.handle_ime_composition(handle, lparam),
 107            WM_SETCURSOR => self.handle_set_cursor(handle, lparam),
 108            WM_SETTINGCHANGE => self.handle_system_settings_changed(handle, wparam, lparam),
 109            WM_INPUTLANGCHANGE => self.handle_input_language_changed(),
 110            WM_SHOWWINDOW => self.handle_window_visibility_changed(handle, wparam),
 111            WM_GPUI_CURSOR_STYLE_CHANGED => self.handle_cursor_changed(lparam),
 112            WM_GPUI_FORCE_UPDATE_WINDOW => self.draw_window(handle, true),
 113            WM_GPUI_GPU_DEVICE_LOST => self.handle_device_lost(lparam),
 114            _ => None,
 115        };
 116        if let Some(n) = handled {
 117            LRESULT(n)
 118        } else {
 119            unsafe { DefWindowProcW(handle, msg, wparam, lparam) }
 120        }
 121    }
 122
 123    fn handle_move_msg(&self, handle: HWND, lparam: LPARAM) -> Option<isize> {
 124        let mut lock = self.state.borrow_mut();
 125        let origin = logical_point(
 126            lparam.signed_loword() as f32,
 127            lparam.signed_hiword() as f32,
 128            lock.scale_factor,
 129        );
 130        lock.origin = origin;
 131        let size = lock.logical_size;
 132        let center_x = origin.x.0 + size.width.0 / 2.;
 133        let center_y = origin.y.0 + size.height.0 / 2.;
 134        let monitor_bounds = lock.display.bounds();
 135        if center_x < monitor_bounds.left().0
 136            || center_x > monitor_bounds.right().0
 137            || center_y < monitor_bounds.top().0
 138            || center_y > monitor_bounds.bottom().0
 139        {
 140            // center of the window may have moved to another monitor
 141            let monitor = unsafe { MonitorFromWindow(handle, MONITOR_DEFAULTTONULL) };
 142            // minimize the window can trigger this event too, in this case,
 143            // monitor is invalid, we do nothing.
 144            if !monitor.is_invalid() && lock.display.handle != monitor {
 145                // we will get the same monitor if we only have one
 146                lock.display = WindowsDisplay::new_with_handle(monitor);
 147            }
 148        }
 149        if let Some(mut callback) = lock.callbacks.moved.take() {
 150            drop(lock);
 151            callback();
 152            self.state.borrow_mut().callbacks.moved = Some(callback);
 153        }
 154        Some(0)
 155    }
 156
 157    fn handle_get_min_max_info_msg(&self, lparam: LPARAM) -> Option<isize> {
 158        let lock = self.state.borrow();
 159        let min_size = lock.min_size?;
 160        let scale_factor = lock.scale_factor;
 161        let boarder_offset = lock.border_offset;
 162        drop(lock);
 163        unsafe {
 164            let minmax_info = &mut *(lparam.0 as *mut MINMAXINFO);
 165            minmax_info.ptMinTrackSize.x =
 166                min_size.width.scale(scale_factor).0 as i32 + boarder_offset.width_offset;
 167            minmax_info.ptMinTrackSize.y =
 168                min_size.height.scale(scale_factor).0 as i32 + boarder_offset.height_offset;
 169        }
 170        Some(0)
 171    }
 172
 173    fn handle_size_msg(&self, wparam: WPARAM, lparam: LPARAM) -> Option<isize> {
 174        let mut lock = self.state.borrow_mut();
 175
 176        // Don't resize the renderer when the window is minimized, but record that it was minimized so
 177        // that on restore the swap chain can be recreated via `update_drawable_size_even_if_unchanged`.
 178        if wparam.0 == SIZE_MINIMIZED as usize {
 179            lock.restore_from_minimized = lock.callbacks.request_frame.take();
 180            return Some(0);
 181        }
 182
 183        let width = lparam.loword().max(1) as i32;
 184        let height = lparam.hiword().max(1) as i32;
 185        let new_size = size(DevicePixels(width), DevicePixels(height));
 186
 187        let scale_factor = lock.scale_factor;
 188        let mut should_resize_renderer = false;
 189        if lock.restore_from_minimized.is_some() {
 190            lock.callbacks.request_frame = lock.restore_from_minimized.take();
 191        } else {
 192            should_resize_renderer = true;
 193        }
 194        drop(lock);
 195
 196        self.handle_size_change(new_size, scale_factor, should_resize_renderer);
 197        Some(0)
 198    }
 199
 200    fn handle_size_change(
 201        &self,
 202        device_size: Size<DevicePixels>,
 203        scale_factor: f32,
 204        should_resize_renderer: bool,
 205    ) {
 206        let new_logical_size = device_size.to_pixels(scale_factor);
 207        let mut lock = self.state.borrow_mut();
 208        lock.logical_size = new_logical_size;
 209        if should_resize_renderer {
 210            lock.renderer.resize(device_size).log_err();
 211        }
 212        if let Some(mut callback) = lock.callbacks.resize.take() {
 213            drop(lock);
 214            callback(new_logical_size, scale_factor);
 215            self.state.borrow_mut().callbacks.resize = Some(callback);
 216        }
 217    }
 218
 219    fn handle_size_move_loop(&self, handle: HWND) -> Option<isize> {
 220        unsafe {
 221            let ret = SetTimer(
 222                Some(handle),
 223                SIZE_MOVE_LOOP_TIMER_ID,
 224                USER_TIMER_MINIMUM,
 225                None,
 226            );
 227            if ret == 0 {
 228                log::error!(
 229                    "unable to create timer: {}",
 230                    std::io::Error::last_os_error()
 231                );
 232            }
 233        }
 234        None
 235    }
 236
 237    fn handle_size_move_loop_exit(&self, handle: HWND) -> Option<isize> {
 238        unsafe {
 239            KillTimer(Some(handle), SIZE_MOVE_LOOP_TIMER_ID).log_err();
 240        }
 241        None
 242    }
 243
 244    fn handle_timer_msg(&self, handle: HWND, wparam: WPARAM) -> Option<isize> {
 245        if wparam.0 == SIZE_MOVE_LOOP_TIMER_ID {
 246            drain_main_receiver(&self.main_receiver);
 247            self.handle_paint_msg(handle)
 248        } else {
 249            None
 250        }
 251    }
 252
 253    fn handle_paint_msg(&self, handle: HWND) -> Option<isize> {
 254        self.draw_window(handle, false)
 255    }
 256
 257    fn handle_close_msg(&self) -> Option<isize> {
 258        let mut callback = self.state.borrow_mut().callbacks.should_close.take()?;
 259        let should_close = callback();
 260        self.state.borrow_mut().callbacks.should_close = Some(callback);
 261        if should_close { None } else { Some(0) }
 262    }
 263
 264    fn handle_destroy_msg(&self, handle: HWND) -> Option<isize> {
 265        let callback = {
 266            let mut lock = self.state.borrow_mut();
 267            lock.callbacks.close.take()
 268        };
 269        if let Some(callback) = callback {
 270            callback();
 271        }
 272        unsafe {
 273            PostMessageW(
 274                Some(self.platform_window_handle),
 275                WM_GPUI_CLOSE_ONE_WINDOW,
 276                WPARAM(self.validation_number),
 277                LPARAM(handle.0 as isize),
 278            )
 279            .log_err();
 280        }
 281        Some(0)
 282    }
 283
 284    fn handle_mouse_move_msg(&self, handle: HWND, lparam: LPARAM, wparam: WPARAM) -> Option<isize> {
 285        self.start_tracking_mouse(handle, TME_LEAVE);
 286
 287        let mut lock = self.state.borrow_mut();
 288        let Some(mut func) = lock.callbacks.input.take() else {
 289            return Some(1);
 290        };
 291        let scale_factor = lock.scale_factor;
 292        drop(lock);
 293
 294        let pressed_button = match MODIFIERKEYS_FLAGS(wparam.loword() as u32) {
 295            flags if flags.contains(MK_LBUTTON) => Some(MouseButton::Left),
 296            flags if flags.contains(MK_RBUTTON) => Some(MouseButton::Right),
 297            flags if flags.contains(MK_MBUTTON) => Some(MouseButton::Middle),
 298            flags if flags.contains(MK_XBUTTON1) => {
 299                Some(MouseButton::Navigate(NavigationDirection::Back))
 300            }
 301            flags if flags.contains(MK_XBUTTON2) => {
 302                Some(MouseButton::Navigate(NavigationDirection::Forward))
 303            }
 304            _ => None,
 305        };
 306        let x = lparam.signed_loword() as f32;
 307        let y = lparam.signed_hiword() as f32;
 308        let input = PlatformInput::MouseMove(MouseMoveEvent {
 309            position: logical_point(x, y, scale_factor),
 310            pressed_button,
 311            modifiers: current_modifiers(),
 312        });
 313        let handled = !func(input).propagate;
 314        self.state.borrow_mut().callbacks.input = Some(func);
 315
 316        if handled { Some(0) } else { Some(1) }
 317    }
 318
 319    fn handle_mouse_leave_msg(&self) -> Option<isize> {
 320        let mut lock = self.state.borrow_mut();
 321        lock.hovered = false;
 322        if let Some(mut callback) = lock.callbacks.hovered_status_change.take() {
 323            drop(lock);
 324            callback(false);
 325            self.state.borrow_mut().callbacks.hovered_status_change = Some(callback);
 326        }
 327
 328        Some(0)
 329    }
 330
 331    fn handle_syskeydown_msg(&self, handle: HWND, wparam: WPARAM, lparam: LPARAM) -> Option<isize> {
 332        let mut lock = self.state.borrow_mut();
 333        let input = handle_key_event(handle, wparam, lparam, &mut lock, |keystroke| {
 334            PlatformInput::KeyDown(KeyDownEvent {
 335                keystroke,
 336                is_held: lparam.0 & (0x1 << 30) > 0,
 337            })
 338        })?;
 339        let mut func = lock.callbacks.input.take()?;
 340        drop(lock);
 341
 342        let handled = !func(input).propagate;
 343
 344        let mut lock = self.state.borrow_mut();
 345        lock.callbacks.input = Some(func);
 346
 347        if handled {
 348            lock.system_key_handled = true;
 349            Some(0)
 350        } else {
 351            // we need to call `DefWindowProcW`, or we will lose the system-wide `Alt+F4`, `Alt+{other keys}`
 352            // shortcuts.
 353            None
 354        }
 355    }
 356
 357    fn handle_syskeyup_msg(&self, handle: HWND, wparam: WPARAM, lparam: LPARAM) -> Option<isize> {
 358        let mut lock = self.state.borrow_mut();
 359        let input = handle_key_event(handle, wparam, lparam, &mut lock, |keystroke| {
 360            PlatformInput::KeyUp(KeyUpEvent { keystroke })
 361        })?;
 362        let mut func = lock.callbacks.input.take()?;
 363        drop(lock);
 364        func(input);
 365        self.state.borrow_mut().callbacks.input = Some(func);
 366
 367        // Always return 0 to indicate that the message was handled, so we could properly handle `ModifiersChanged` event.
 368        Some(0)
 369    }
 370
 371    // It's a known bug that you can't trigger `ctrl-shift-0`. See:
 372    // https://superuser.com/questions/1455762/ctrl-shift-number-key-combination-has-stopped-working-for-a-few-numbers
 373    fn handle_keydown_msg(&self, handle: HWND, wparam: WPARAM, lparam: LPARAM) -> Option<isize> {
 374        let mut lock = self.state.borrow_mut();
 375        let Some(input) = handle_key_event(handle, wparam, lparam, &mut lock, |keystroke| {
 376            PlatformInput::KeyDown(KeyDownEvent {
 377                keystroke,
 378                is_held: lparam.0 & (0x1 << 30) > 0,
 379            })
 380        }) else {
 381            return Some(1);
 382        };
 383        drop(lock);
 384
 385        let is_composing = self
 386            .with_input_handler(|input_handler| input_handler.marked_text_range())
 387            .flatten()
 388            .is_some();
 389        if is_composing {
 390            translate_message(handle, wparam, lparam);
 391            return Some(0);
 392        }
 393
 394        let Some(mut func) = self.state.borrow_mut().callbacks.input.take() else {
 395            return Some(1);
 396        };
 397
 398        let handled = !func(input).propagate;
 399
 400        self.state.borrow_mut().callbacks.input = Some(func);
 401
 402        if handled {
 403            Some(0)
 404        } else {
 405            translate_message(handle, wparam, lparam);
 406            Some(1)
 407        }
 408    }
 409
 410    fn handle_keyup_msg(&self, handle: HWND, wparam: WPARAM, lparam: LPARAM) -> Option<isize> {
 411        let mut lock = self.state.borrow_mut();
 412        let Some(input) = handle_key_event(handle, wparam, lparam, &mut lock, |keystroke| {
 413            PlatformInput::KeyUp(KeyUpEvent { keystroke })
 414        }) else {
 415            return Some(1);
 416        };
 417
 418        let Some(mut func) = lock.callbacks.input.take() else {
 419            return Some(1);
 420        };
 421        drop(lock);
 422
 423        let handled = !func(input).propagate;
 424        self.state.borrow_mut().callbacks.input = Some(func);
 425
 426        if handled { Some(0) } else { Some(1) }
 427    }
 428
 429    fn handle_char_msg(&self, wparam: WPARAM) -> Option<isize> {
 430        let input = self.parse_char_message(wparam)?;
 431        self.with_input_handler(|input_handler| {
 432            input_handler.replace_text_in_range(None, &input);
 433        });
 434
 435        Some(0)
 436    }
 437
 438    fn handle_dead_char_msg(&self, wparam: WPARAM) -> Option<isize> {
 439        let ch = char::from_u32(wparam.0 as u32)?.to_string();
 440        self.with_input_handler(|input_handler| {
 441            input_handler.replace_and_mark_text_in_range(None, &ch, None);
 442        });
 443        None
 444    }
 445
 446    fn handle_mouse_down_msg(
 447        &self,
 448        handle: HWND,
 449        button: MouseButton,
 450        lparam: LPARAM,
 451    ) -> Option<isize> {
 452        unsafe { SetCapture(handle) };
 453        let mut lock = self.state.borrow_mut();
 454        let Some(mut func) = lock.callbacks.input.take() else {
 455            return Some(1);
 456        };
 457        let x = lparam.signed_loword();
 458        let y = lparam.signed_hiword();
 459        let physical_point = point(DevicePixels(x as i32), DevicePixels(y as i32));
 460        let click_count = lock.click_state.update(button, physical_point);
 461        let scale_factor = lock.scale_factor;
 462        drop(lock);
 463
 464        let input = PlatformInput::MouseDown(MouseDownEvent {
 465            button,
 466            position: logical_point(x as f32, y as f32, scale_factor),
 467            modifiers: current_modifiers(),
 468            click_count,
 469            first_mouse: false,
 470        });
 471        let handled = !func(input).propagate;
 472        self.state.borrow_mut().callbacks.input = Some(func);
 473
 474        if handled { Some(0) } else { Some(1) }
 475    }
 476
 477    fn handle_mouse_up_msg(
 478        &self,
 479        _handle: HWND,
 480        button: MouseButton,
 481        lparam: LPARAM,
 482    ) -> Option<isize> {
 483        unsafe { ReleaseCapture().log_err() };
 484        let mut lock = self.state.borrow_mut();
 485        let Some(mut func) = lock.callbacks.input.take() else {
 486            return Some(1);
 487        };
 488        let x = lparam.signed_loword() as f32;
 489        let y = lparam.signed_hiword() as f32;
 490        let click_count = lock.click_state.current_count;
 491        let scale_factor = lock.scale_factor;
 492        drop(lock);
 493
 494        let input = PlatformInput::MouseUp(MouseUpEvent {
 495            button,
 496            position: logical_point(x, y, scale_factor),
 497            modifiers: current_modifiers(),
 498            click_count,
 499        });
 500        let handled = !func(input).propagate;
 501        self.state.borrow_mut().callbacks.input = Some(func);
 502
 503        if handled { Some(0) } else { Some(1) }
 504    }
 505
 506    fn handle_xbutton_msg(
 507        &self,
 508        handle: HWND,
 509        wparam: WPARAM,
 510        lparam: LPARAM,
 511        handler: impl Fn(&Self, HWND, MouseButton, LPARAM) -> Option<isize>,
 512    ) -> Option<isize> {
 513        let nav_dir = match wparam.hiword() {
 514            XBUTTON1 => NavigationDirection::Back,
 515            XBUTTON2 => NavigationDirection::Forward,
 516            _ => return Some(1),
 517        };
 518        handler(self, handle, MouseButton::Navigate(nav_dir), lparam)
 519    }
 520
 521    fn handle_mouse_wheel_msg(
 522        &self,
 523        handle: HWND,
 524        wparam: WPARAM,
 525        lparam: LPARAM,
 526    ) -> Option<isize> {
 527        let modifiers = current_modifiers();
 528        let mut lock = self.state.borrow_mut();
 529        let Some(mut func) = lock.callbacks.input.take() else {
 530            return Some(1);
 531        };
 532        let scale_factor = lock.scale_factor;
 533        let wheel_scroll_amount = match modifiers.shift {
 534            true => {
 535                self.system_settings
 536                    .borrow()
 537                    .mouse_wheel_settings
 538                    .wheel_scroll_chars
 539            }
 540            false => {
 541                self.system_settings
 542                    .borrow()
 543                    .mouse_wheel_settings
 544                    .wheel_scroll_lines
 545            }
 546        };
 547        drop(lock);
 548
 549        let wheel_distance =
 550            (wparam.signed_hiword() as f32 / WHEEL_DELTA as f32) * wheel_scroll_amount as f32;
 551        let mut cursor_point = POINT {
 552            x: lparam.signed_loword().into(),
 553            y: lparam.signed_hiword().into(),
 554        };
 555        unsafe { ScreenToClient(handle, &mut cursor_point).ok().log_err() };
 556        let input = PlatformInput::ScrollWheel(ScrollWheelEvent {
 557            position: logical_point(cursor_point.x as f32, cursor_point.y as f32, scale_factor),
 558            delta: ScrollDelta::Lines(match modifiers.shift {
 559                true => Point {
 560                    x: wheel_distance,
 561                    y: 0.0,
 562                },
 563                false => Point {
 564                    y: wheel_distance,
 565                    x: 0.0,
 566                },
 567            }),
 568            modifiers,
 569            touch_phase: TouchPhase::Moved,
 570        });
 571        let handled = !func(input).propagate;
 572        self.state.borrow_mut().callbacks.input = Some(func);
 573
 574        if handled { Some(0) } else { Some(1) }
 575    }
 576
 577    fn handle_mouse_horizontal_wheel_msg(
 578        &self,
 579        handle: HWND,
 580        wparam: WPARAM,
 581        lparam: LPARAM,
 582    ) -> Option<isize> {
 583        let mut lock = self.state.borrow_mut();
 584        let Some(mut func) = lock.callbacks.input.take() else {
 585            return Some(1);
 586        };
 587        let scale_factor = lock.scale_factor;
 588        let wheel_scroll_chars = self
 589            .system_settings
 590            .borrow()
 591            .mouse_wheel_settings
 592            .wheel_scroll_chars;
 593        drop(lock);
 594
 595        let wheel_distance =
 596            (-wparam.signed_hiword() as f32 / WHEEL_DELTA as f32) * wheel_scroll_chars as f32;
 597        let mut cursor_point = POINT {
 598            x: lparam.signed_loword().into(),
 599            y: lparam.signed_hiword().into(),
 600        };
 601        unsafe { ScreenToClient(handle, &mut cursor_point).ok().log_err() };
 602        let event = PlatformInput::ScrollWheel(ScrollWheelEvent {
 603            position: logical_point(cursor_point.x as f32, cursor_point.y as f32, scale_factor),
 604            delta: ScrollDelta::Lines(Point {
 605                x: wheel_distance,
 606                y: 0.0,
 607            }),
 608            modifiers: current_modifiers(),
 609            touch_phase: TouchPhase::Moved,
 610        });
 611        let handled = !func(event).propagate;
 612        self.state.borrow_mut().callbacks.input = Some(func);
 613
 614        if handled { Some(0) } else { Some(1) }
 615    }
 616
 617    fn retrieve_caret_position(&self) -> Option<POINT> {
 618        self.with_input_handler_and_scale_factor(|input_handler, scale_factor| {
 619            let caret_range = input_handler.selected_text_range(false)?;
 620            let caret_position = input_handler.bounds_for_range(caret_range.range)?;
 621            Some(POINT {
 622                // logical to physical
 623                x: (caret_position.origin.x.0 * scale_factor) as i32,
 624                y: (caret_position.origin.y.0 * scale_factor) as i32
 625                    + ((caret_position.size.height.0 * scale_factor) as i32 / 2),
 626            })
 627        })
 628    }
 629
 630    fn handle_ime_position(&self, handle: HWND) -> Option<isize> {
 631        unsafe {
 632            let ctx = ImmGetContext(handle);
 633
 634            let Some(caret_position) = self.retrieve_caret_position() else {
 635                return Some(0);
 636            };
 637            {
 638                let config = COMPOSITIONFORM {
 639                    dwStyle: CFS_POINT,
 640                    ptCurrentPos: caret_position,
 641                    ..Default::default()
 642                };
 643                ImmSetCompositionWindow(ctx, &config as _).ok().log_err();
 644            }
 645            {
 646                let config = CANDIDATEFORM {
 647                    dwStyle: CFS_CANDIDATEPOS,
 648                    ptCurrentPos: caret_position,
 649                    ..Default::default()
 650                };
 651                ImmSetCandidateWindow(ctx, &config as _).ok().log_err();
 652            }
 653            ImmReleaseContext(handle, ctx).ok().log_err();
 654            Some(0)
 655        }
 656    }
 657
 658    fn handle_ime_composition(&self, handle: HWND, lparam: LPARAM) -> Option<isize> {
 659        let ctx = unsafe { ImmGetContext(handle) };
 660        let result = self.handle_ime_composition_inner(ctx, lparam);
 661        unsafe { ImmReleaseContext(handle, ctx).ok().log_err() };
 662        result
 663    }
 664
 665    fn handle_ime_composition_inner(&self, ctx: HIMC, lparam: LPARAM) -> Option<isize> {
 666        let lparam = lparam.0 as u32;
 667        if lparam == 0 {
 668            // Japanese IME may send this message with lparam = 0, which indicates that
 669            // there is no composition string.
 670            self.with_input_handler(|input_handler| {
 671                input_handler.replace_text_in_range(None, "");
 672            })?;
 673            Some(0)
 674        } else {
 675            if lparam & GCS_COMPSTR.0 > 0 {
 676                let comp_string = parse_ime_composition_string(ctx, GCS_COMPSTR)?;
 677                let caret_pos =
 678                    (!comp_string.is_empty() && lparam & GCS_CURSORPOS.0 > 0).then(|| {
 679                        let pos = retrieve_composition_cursor_position(ctx);
 680                        pos..pos
 681                    });
 682                self.with_input_handler(|input_handler| {
 683                    input_handler.replace_and_mark_text_in_range(None, &comp_string, caret_pos);
 684                })?;
 685            }
 686            if lparam & GCS_RESULTSTR.0 > 0 {
 687                let comp_result = parse_ime_composition_string(ctx, GCS_RESULTSTR)?;
 688                self.with_input_handler(|input_handler| {
 689                    input_handler.replace_text_in_range(None, &comp_result);
 690                })?;
 691                return Some(0);
 692            }
 693
 694            // currently, we don't care other stuff
 695            None
 696        }
 697    }
 698
 699    /// SEE: https://learn.microsoft.com/en-us/windows/win32/winmsg/wm-nccalcsize
 700    fn handle_calc_client_size(
 701        &self,
 702        handle: HWND,
 703        wparam: WPARAM,
 704        lparam: LPARAM,
 705    ) -> Option<isize> {
 706        if !self.hide_title_bar || self.state.borrow().is_fullscreen() || wparam.0 == 0 {
 707            return None;
 708        }
 709
 710        let is_maximized = self.state.borrow().is_maximized();
 711        let insets = get_client_area_insets(handle, is_maximized, self.windows_version);
 712        // wparam is TRUE so lparam points to an NCCALCSIZE_PARAMS structure
 713        let mut params = lparam.0 as *mut NCCALCSIZE_PARAMS;
 714        let mut requested_client_rect = unsafe { &mut ((*params).rgrc) };
 715
 716        requested_client_rect[0].left += insets.left;
 717        requested_client_rect[0].top += insets.top;
 718        requested_client_rect[0].right -= insets.right;
 719        requested_client_rect[0].bottom -= insets.bottom;
 720
 721        // Fix auto hide taskbar not showing. This solution is based on the approach
 722        // used by Chrome. However, it may result in one row of pixels being obscured
 723        // in our client area. But as Chrome says, "there seems to be no better solution."
 724        if is_maximized
 725            && let Some(ref taskbar_position) =
 726                self.system_settings.borrow().auto_hide_taskbar_position
 727        {
 728            // For the auto-hide taskbar, adjust in by 1 pixel on taskbar edge,
 729            // so the window isn't treated as a "fullscreen app", which would cause
 730            // the taskbar to disappear.
 731            match taskbar_position {
 732                AutoHideTaskbarPosition::Left => {
 733                    requested_client_rect[0].left += AUTO_HIDE_TASKBAR_THICKNESS_PX
 734                }
 735                AutoHideTaskbarPosition::Top => {
 736                    requested_client_rect[0].top += AUTO_HIDE_TASKBAR_THICKNESS_PX
 737                }
 738                AutoHideTaskbarPosition::Right => {
 739                    requested_client_rect[0].right -= AUTO_HIDE_TASKBAR_THICKNESS_PX
 740                }
 741                AutoHideTaskbarPosition::Bottom => {
 742                    requested_client_rect[0].bottom -= AUTO_HIDE_TASKBAR_THICKNESS_PX
 743                }
 744            }
 745        }
 746
 747        Some(0)
 748    }
 749
 750    fn handle_activate_msg(self: &Rc<Self>, wparam: WPARAM) -> Option<isize> {
 751        let activated = wparam.loword() > 0;
 752        let this = self.clone();
 753        self.executor
 754            .spawn(async move {
 755                let mut lock = this.state.borrow_mut();
 756                if let Some(mut func) = lock.callbacks.active_status_change.take() {
 757                    drop(lock);
 758                    func(activated);
 759                    this.state.borrow_mut().callbacks.active_status_change = Some(func);
 760                }
 761            })
 762            .detach();
 763
 764        None
 765    }
 766
 767    fn handle_create_msg(&self, handle: HWND) -> Option<isize> {
 768        if self.hide_title_bar {
 769            notify_frame_changed(handle);
 770            Some(0)
 771        } else {
 772            None
 773        }
 774    }
 775
 776    fn handle_dpi_changed_msg(
 777        &self,
 778        handle: HWND,
 779        wparam: WPARAM,
 780        lparam: LPARAM,
 781    ) -> Option<isize> {
 782        let new_dpi = wparam.loword() as f32;
 783        let mut lock = self.state.borrow_mut();
 784        let is_maximized = lock.is_maximized();
 785        let new_scale_factor = new_dpi / USER_DEFAULT_SCREEN_DPI as f32;
 786        lock.scale_factor = new_scale_factor;
 787        lock.border_offset.update(handle).log_err();
 788        drop(lock);
 789
 790        let rect = unsafe { &*(lparam.0 as *const RECT) };
 791        let width = rect.right - rect.left;
 792        let height = rect.bottom - rect.top;
 793        // this will emit `WM_SIZE` and `WM_MOVE` right here
 794        // even before this function returns
 795        // the new size is handled in `WM_SIZE`
 796        unsafe {
 797            SetWindowPos(
 798                handle,
 799                None,
 800                rect.left,
 801                rect.top,
 802                width,
 803                height,
 804                SWP_NOZORDER | SWP_NOACTIVATE,
 805            )
 806            .context("unable to set window position after dpi has changed")
 807            .log_err();
 808        }
 809
 810        // When maximized, SetWindowPos doesn't send WM_SIZE, so we need to manually
 811        // update the size and call the resize callback
 812        if is_maximized {
 813            let device_size = size(DevicePixels(width), DevicePixels(height));
 814            self.handle_size_change(device_size, new_scale_factor, true);
 815        }
 816
 817        Some(0)
 818    }
 819
 820    /// The following conditions will trigger this event:
 821    /// 1. The monitor on which the window is located goes offline or changes resolution.
 822    /// 2. Another monitor goes offline, is plugged in, or changes resolution.
 823    ///
 824    /// In either case, the window will only receive information from the monitor on which
 825    /// it is located.
 826    ///
 827    /// For example, in the case of condition 2, where the monitor on which the window is
 828    /// located has actually changed nothing, it will still receive this event.
 829    fn handle_display_change_msg(&self, handle: HWND) -> Option<isize> {
 830        // NOTE:
 831        // Even the `lParam` holds the resolution of the screen, we just ignore it.
 832        // Because WM_DPICHANGED, WM_MOVE, WM_SIZE will come first, window reposition and resize
 833        // are handled there.
 834        // So we only care about if monitor is disconnected.
 835        let previous_monitor = self.state.borrow().display;
 836        if WindowsDisplay::is_connected(previous_monitor.handle) {
 837            // we are fine, other display changed
 838            return None;
 839        }
 840        // display disconnected
 841        // in this case, the OS will move our window to another monitor, and minimize it.
 842        // we deminimize the window and query the monitor after moving
 843        unsafe {
 844            let _ = ShowWindow(handle, SW_SHOWNORMAL);
 845        };
 846        let new_monitor = unsafe { MonitorFromWindow(handle, MONITOR_DEFAULTTONULL) };
 847        // all monitors disconnected
 848        if new_monitor.is_invalid() {
 849            log::error!("No monitor detected!");
 850            return None;
 851        }
 852        let new_display = WindowsDisplay::new_with_handle(new_monitor);
 853        self.state.borrow_mut().display = new_display;
 854        Some(0)
 855    }
 856
 857    fn handle_hit_test_msg(
 858        &self,
 859        handle: HWND,
 860        msg: u32,
 861        wparam: WPARAM,
 862        lparam: LPARAM,
 863    ) -> Option<isize> {
 864        if !self.is_movable || self.state.borrow().is_fullscreen() {
 865            return None;
 866        }
 867
 868        let mut lock = self.state.borrow_mut();
 869        if let Some(mut callback) = lock.callbacks.hit_test_window_control.take() {
 870            drop(lock);
 871            let area = callback();
 872            self.state.borrow_mut().callbacks.hit_test_window_control = Some(callback);
 873            if let Some(area) = area {
 874                return match area {
 875                    WindowControlArea::Drag => Some(HTCAPTION as _),
 876                    WindowControlArea::Close => Some(HTCLOSE as _),
 877                    WindowControlArea::Max => Some(HTMAXBUTTON as _),
 878                    WindowControlArea::Min => Some(HTMINBUTTON as _),
 879                };
 880            }
 881        } else {
 882            drop(lock);
 883        }
 884
 885        if !self.hide_title_bar {
 886            // If the OS draws the title bar, we don't need to handle hit test messages.
 887            return None;
 888        }
 889
 890        // default handler for resize areas
 891        let hit = unsafe { DefWindowProcW(handle, msg, wparam, lparam) };
 892        if matches!(
 893            hit.0 as u32,
 894            HTNOWHERE
 895                | HTRIGHT
 896                | HTLEFT
 897                | HTTOPLEFT
 898                | HTTOP
 899                | HTTOPRIGHT
 900                | HTBOTTOMRIGHT
 901                | HTBOTTOM
 902                | HTBOTTOMLEFT
 903        ) {
 904            return Some(hit.0);
 905        }
 906
 907        if self.state.borrow().is_fullscreen() {
 908            return Some(HTCLIENT as _);
 909        }
 910
 911        let dpi = unsafe { GetDpiForWindow(handle) };
 912        let frame_y = unsafe { GetSystemMetricsForDpi(SM_CYFRAME, dpi) };
 913
 914        let mut cursor_point = POINT {
 915            x: lparam.signed_loword().into(),
 916            y: lparam.signed_hiword().into(),
 917        };
 918        unsafe { ScreenToClient(handle, &mut cursor_point).ok().log_err() };
 919        if !self.state.borrow().is_maximized() && cursor_point.y >= 0 && cursor_point.y <= frame_y {
 920            return Some(HTTOP as _);
 921        }
 922
 923        Some(HTCLIENT as _)
 924    }
 925
 926    fn handle_nc_mouse_move_msg(&self, handle: HWND, lparam: LPARAM) -> Option<isize> {
 927        self.start_tracking_mouse(handle, TME_LEAVE | TME_NONCLIENT);
 928
 929        let mut lock = self.state.borrow_mut();
 930        let mut func = lock.callbacks.input.take()?;
 931        let scale_factor = lock.scale_factor;
 932        drop(lock);
 933
 934        let mut cursor_point = POINT {
 935            x: lparam.signed_loword().into(),
 936            y: lparam.signed_hiword().into(),
 937        };
 938        unsafe { ScreenToClient(handle, &mut cursor_point).ok().log_err() };
 939        let input = PlatformInput::MouseMove(MouseMoveEvent {
 940            position: logical_point(cursor_point.x as f32, cursor_point.y as f32, scale_factor),
 941            pressed_button: None,
 942            modifiers: current_modifiers(),
 943        });
 944        let handled = !func(input).propagate;
 945        self.state.borrow_mut().callbacks.input = Some(func);
 946
 947        if handled { Some(0) } else { None }
 948    }
 949
 950    fn handle_nc_mouse_down_msg(
 951        &self,
 952        handle: HWND,
 953        button: MouseButton,
 954        wparam: WPARAM,
 955        lparam: LPARAM,
 956    ) -> Option<isize> {
 957        let mut lock = self.state.borrow_mut();
 958        if let Some(mut func) = lock.callbacks.input.take() {
 959            let scale_factor = lock.scale_factor;
 960            let mut cursor_point = POINT {
 961                x: lparam.signed_loword().into(),
 962                y: lparam.signed_hiword().into(),
 963            };
 964            unsafe { ScreenToClient(handle, &mut cursor_point).ok().log_err() };
 965            let physical_point = point(DevicePixels(cursor_point.x), DevicePixels(cursor_point.y));
 966            let click_count = lock.click_state.update(button, physical_point);
 967            drop(lock);
 968
 969            let input = PlatformInput::MouseDown(MouseDownEvent {
 970                button,
 971                position: logical_point(cursor_point.x as f32, cursor_point.y as f32, scale_factor),
 972                modifiers: current_modifiers(),
 973                click_count,
 974                first_mouse: false,
 975            });
 976            let result = func(input);
 977            let handled = !result.propagate || result.default_prevented;
 978            self.state.borrow_mut().callbacks.input = Some(func);
 979
 980            if handled {
 981                return Some(0);
 982            }
 983        } else {
 984            drop(lock);
 985        };
 986
 987        // Since these are handled in handle_nc_mouse_up_msg we must prevent the default window proc
 988        if button == MouseButton::Left {
 989            match wparam.0 as u32 {
 990                HTMINBUTTON => self.state.borrow_mut().nc_button_pressed = Some(HTMINBUTTON),
 991                HTMAXBUTTON => self.state.borrow_mut().nc_button_pressed = Some(HTMAXBUTTON),
 992                HTCLOSE => self.state.borrow_mut().nc_button_pressed = Some(HTCLOSE),
 993                _ => return None,
 994            };
 995            Some(0)
 996        } else {
 997            None
 998        }
 999    }
1000
1001    fn handle_nc_mouse_up_msg(
1002        &self,
1003        handle: HWND,
1004        button: MouseButton,
1005        wparam: WPARAM,
1006        lparam: LPARAM,
1007    ) -> Option<isize> {
1008        let mut lock = self.state.borrow_mut();
1009        if let Some(mut func) = lock.callbacks.input.take() {
1010            let scale_factor = lock.scale_factor;
1011            drop(lock);
1012
1013            let mut cursor_point = POINT {
1014                x: lparam.signed_loword().into(),
1015                y: lparam.signed_hiword().into(),
1016            };
1017            unsafe { ScreenToClient(handle, &mut cursor_point).ok().log_err() };
1018            let input = PlatformInput::MouseUp(MouseUpEvent {
1019                button,
1020                position: logical_point(cursor_point.x as f32, cursor_point.y as f32, scale_factor),
1021                modifiers: current_modifiers(),
1022                click_count: 1,
1023            });
1024            let handled = !func(input).propagate;
1025            self.state.borrow_mut().callbacks.input = Some(func);
1026
1027            if handled {
1028                return Some(0);
1029            }
1030        } else {
1031            drop(lock);
1032        }
1033
1034        let last_pressed = self.state.borrow_mut().nc_button_pressed.take();
1035        if button == MouseButton::Left
1036            && let Some(last_pressed) = last_pressed
1037        {
1038            let handled = match (wparam.0 as u32, last_pressed) {
1039                (HTMINBUTTON, HTMINBUTTON) => {
1040                    unsafe { ShowWindowAsync(handle, SW_MINIMIZE).ok().log_err() };
1041                    true
1042                }
1043                (HTMAXBUTTON, HTMAXBUTTON) => {
1044                    if self.state.borrow().is_maximized() {
1045                        unsafe { ShowWindowAsync(handle, SW_NORMAL).ok().log_err() };
1046                    } else {
1047                        unsafe { ShowWindowAsync(handle, SW_MAXIMIZE).ok().log_err() };
1048                    }
1049                    true
1050                }
1051                (HTCLOSE, HTCLOSE) => {
1052                    unsafe {
1053                        PostMessageW(Some(handle), WM_CLOSE, WPARAM::default(), LPARAM::default())
1054                            .log_err()
1055                    };
1056                    true
1057                }
1058                _ => false,
1059            };
1060            if handled {
1061                return Some(0);
1062            }
1063        }
1064
1065        None
1066    }
1067
1068    fn handle_cursor_changed(&self, lparam: LPARAM) -> Option<isize> {
1069        let mut state = self.state.borrow_mut();
1070        let had_cursor = state.current_cursor.is_some();
1071
1072        state.current_cursor = if lparam.0 == 0 {
1073            None
1074        } else {
1075            Some(HCURSOR(lparam.0 as _))
1076        };
1077
1078        if had_cursor != state.current_cursor.is_some() {
1079            unsafe { SetCursor(state.current_cursor) };
1080        }
1081
1082        Some(0)
1083    }
1084
1085    fn handle_set_cursor(&self, handle: HWND, lparam: LPARAM) -> Option<isize> {
1086        if unsafe { !IsWindowEnabled(handle).as_bool() }
1087            || matches!(
1088                lparam.loword() as u32,
1089                HTLEFT
1090                    | HTRIGHT
1091                    | HTTOP
1092                    | HTTOPLEFT
1093                    | HTTOPRIGHT
1094                    | HTBOTTOM
1095                    | HTBOTTOMLEFT
1096                    | HTBOTTOMRIGHT
1097            )
1098        {
1099            return None;
1100        }
1101        unsafe {
1102            SetCursor(self.state.borrow().current_cursor);
1103        };
1104        Some(1)
1105    }
1106
1107    fn handle_system_settings_changed(
1108        &self,
1109        handle: HWND,
1110        wparam: WPARAM,
1111        lparam: LPARAM,
1112    ) -> Option<isize> {
1113        if wparam.0 != 0 {
1114            let mut lock = self.state.borrow_mut();
1115            let display = lock.display;
1116            lock.click_state.system_update(wparam.0);
1117            lock.border_offset.update(handle).log_err();
1118            // system settings may emit a window message which wants to take the refcell lock, so drop it
1119            drop(lock);
1120            self.system_settings.borrow_mut().update(display, wparam.0);
1121        } else {
1122            self.handle_system_theme_changed(handle, lparam)?;
1123        };
1124        // Force to trigger WM_NCCALCSIZE event to ensure that we handle auto hide
1125        // taskbar correctly.
1126        notify_frame_changed(handle);
1127
1128        Some(0)
1129    }
1130
1131    fn handle_system_command(&self, wparam: WPARAM) -> Option<isize> {
1132        if wparam.0 == SC_KEYMENU as usize {
1133            let mut lock = self.state.borrow_mut();
1134            if lock.system_key_handled {
1135                lock.system_key_handled = false;
1136                return Some(0);
1137            }
1138        }
1139        None
1140    }
1141
1142    fn handle_system_theme_changed(&self, handle: HWND, lparam: LPARAM) -> Option<isize> {
1143        // lParam is a pointer to a string that indicates the area containing the system parameter
1144        // that was changed.
1145        let parameter = PCWSTR::from_raw(lparam.0 as _);
1146        if unsafe { !parameter.is_null() && !parameter.is_empty() }
1147            && let Some(parameter_string) = unsafe { parameter.to_string() }.log_err()
1148        {
1149            log::info!("System settings changed: {}", parameter_string);
1150            if parameter_string.as_str() == "ImmersiveColorSet" {
1151                let new_appearance = system_appearance()
1152                    .context("unable to get system appearance when handling ImmersiveColorSet")
1153                    .log_err()?;
1154                let mut lock = self.state.borrow_mut();
1155                if new_appearance != lock.appearance {
1156                    lock.appearance = new_appearance;
1157                    let mut callback = lock.callbacks.appearance_changed.take()?;
1158                    drop(lock);
1159                    callback();
1160                    self.state.borrow_mut().callbacks.appearance_changed = Some(callback);
1161                    configure_dwm_dark_mode(handle, new_appearance);
1162                }
1163            }
1164        }
1165        Some(0)
1166    }
1167
1168    fn handle_input_language_changed(&self) -> Option<isize> {
1169        unsafe {
1170            PostMessageW(
1171                Some(self.platform_window_handle),
1172                WM_GPUI_KEYBOARD_LAYOUT_CHANGED,
1173                WPARAM(self.validation_number),
1174                LPARAM(0),
1175            )
1176            .log_err();
1177        }
1178        Some(0)
1179    }
1180
1181    fn handle_window_visibility_changed(&self, handle: HWND, wparam: WPARAM) -> Option<isize> {
1182        if wparam.0 == 1 {
1183            self.draw_window(handle, false);
1184        }
1185        None
1186    }
1187
1188    fn handle_device_lost(&self, lparam: LPARAM) -> Option<isize> {
1189        let mut lock = self.state.borrow_mut();
1190        let devices = lparam.0 as *const DirectXDevices;
1191        let devices = unsafe { &*devices };
1192        lock.renderer.handle_device_lost(&devices);
1193        Some(0)
1194    }
1195
1196    #[inline]
1197    fn draw_window(&self, handle: HWND, force_render: bool) -> Option<isize> {
1198        let last_frame = FRAME_INDEX.fetch_add(1, std::sync::atomic::Ordering::SeqCst) % FRAME_RING;
1199        let cur_frame = (last_frame + 1) % FRAME_RING;
1200
1201        let start = Instant::now();
1202        let prev_frame_start = self.frame_start.replace(start);
1203
1204        FRAME_BUF[last_frame].lock().frame_time =
1205            start.duration_since(prev_frame_start).as_secs_f64();
1206        FRAME_BUF[cur_frame].lock().timings.clear();
1207
1208        let mut request_frame = self.state.borrow_mut().callbacks.request_frame.take()?;
1209        request_frame(RequestFrameOptions {
1210            require_presentation: false,
1211            force_render,
1212        });
1213
1214        self.state.borrow_mut().callbacks.request_frame = Some(request_frame);
1215        unsafe { ValidateRect(Some(handle), None).ok().log_err() };
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}