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