events.rs

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