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).log_err()?;
 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        if is_maximized {
 744            // Get the monitor and its work area at the new DPI
 745            let monitor = unsafe { MonitorFromWindow(handle, MONITOR_DEFAULTTONEAREST) };
 746            let mut monitor_info: MONITORINFO = unsafe { std::mem::zeroed() };
 747            monitor_info.cbSize = std::mem::size_of::<MONITORINFO>() as u32;
 748            if unsafe { GetMonitorInfoW(monitor, &mut monitor_info) }.as_bool() {
 749                let work_area = monitor_info.rcWork;
 750                let width = work_area.right - work_area.left;
 751                let height = work_area.bottom - work_area.top;
 752
 753                // Update the window size to match the new monitor work area
 754                // This will trigger WM_SIZE which will handle the size change
 755                unsafe {
 756                    SetWindowPos(
 757                        handle,
 758                        None,
 759                        work_area.left,
 760                        work_area.top,
 761                        width,
 762                        height,
 763                        SWP_NOZORDER | SWP_NOACTIVATE | SWP_FRAMECHANGED,
 764                    )
 765                    .context("unable to set maximized window position after dpi has changed")
 766                    .log_err();
 767                }
 768
 769                // SetWindowPos may not send WM_SIZE for maximized windows in some cases,
 770                // so we manually update the size to ensure proper rendering
 771                let device_size = size(DevicePixels(width), DevicePixels(height));
 772                self.handle_size_change(device_size, new_scale_factor, true);
 773            }
 774        } else {
 775            // For non-maximized windows, use the suggested RECT from the system
 776            let rect = unsafe { &*(lparam.0 as *const RECT) };
 777            let width = rect.right - rect.left;
 778            let height = rect.bottom - rect.top;
 779            // this will emit `WM_SIZE` and `WM_MOVE` right here
 780            // even before this function returns
 781            // the new size is handled in `WM_SIZE`
 782            unsafe {
 783                SetWindowPos(
 784                    handle,
 785                    None,
 786                    rect.left,
 787                    rect.top,
 788                    width,
 789                    height,
 790                    SWP_NOZORDER | SWP_NOACTIVATE,
 791                )
 792                .context("unable to set window position after dpi has changed")
 793                .log_err();
 794            }
 795        }
 796
 797        Some(0)
 798    }
 799
 800    /// The following conditions will trigger this event:
 801    /// 1. The monitor on which the window is located goes offline or changes resolution.
 802    /// 2. Another monitor goes offline, is plugged in, or changes resolution.
 803    ///
 804    /// In either case, the window will only receive information from the monitor on which
 805    /// it is located.
 806    ///
 807    /// For example, in the case of condition 2, where the monitor on which the window is
 808    /// located has actually changed nothing, it will still receive this event.
 809    fn handle_display_change_msg(&self, handle: HWND) -> Option<isize> {
 810        // NOTE:
 811        // Even the `lParam` holds the resolution of the screen, we just ignore it.
 812        // Because WM_DPICHANGED, WM_MOVE, WM_SIZE will come first, window reposition and resize
 813        // are handled there.
 814        // So we only care about if monitor is disconnected.
 815        let previous_monitor = self.state.borrow().display;
 816        if WindowsDisplay::is_connected(previous_monitor.handle) {
 817            // we are fine, other display changed
 818            return None;
 819        }
 820        // display disconnected
 821        // in this case, the OS will move our window to another monitor, and minimize it.
 822        // we deminimize the window and query the monitor after moving
 823        unsafe {
 824            let _ = ShowWindow(handle, SW_SHOWNORMAL);
 825        };
 826        let new_monitor = unsafe { MonitorFromWindow(handle, MONITOR_DEFAULTTONULL) };
 827        // all monitors disconnected
 828        if new_monitor.is_invalid() {
 829            log::error!("No monitor detected!");
 830            return None;
 831        }
 832        let new_display = WindowsDisplay::new_with_handle(new_monitor).log_err()?;
 833        self.state.borrow_mut().display = new_display;
 834        Some(0)
 835    }
 836
 837    fn handle_hit_test_msg(
 838        &self,
 839        handle: HWND,
 840        msg: u32,
 841        wparam: WPARAM,
 842        lparam: LPARAM,
 843    ) -> Option<isize> {
 844        if !self.is_movable || self.state.borrow().is_fullscreen() {
 845            return None;
 846        }
 847
 848        let mut lock = self.state.borrow_mut();
 849        if let Some(mut callback) = lock.callbacks.hit_test_window_control.take() {
 850            drop(lock);
 851            let area = callback();
 852            self.state.borrow_mut().callbacks.hit_test_window_control = Some(callback);
 853            if let Some(area) = area {
 854                return match area {
 855                    WindowControlArea::Drag => Some(HTCAPTION as _),
 856                    WindowControlArea::Close => Some(HTCLOSE as _),
 857                    WindowControlArea::Max => Some(HTMAXBUTTON as _),
 858                    WindowControlArea::Min => Some(HTMINBUTTON as _),
 859                };
 860            }
 861        } else {
 862            drop(lock);
 863        }
 864
 865        if !self.hide_title_bar {
 866            // If the OS draws the title bar, we don't need to handle hit test messages.
 867            return None;
 868        }
 869
 870        // default handler for resize areas
 871        let hit = unsafe { DefWindowProcW(handle, msg, wparam, lparam) };
 872        if matches!(
 873            hit.0 as u32,
 874            HTNOWHERE
 875                | HTRIGHT
 876                | HTLEFT
 877                | HTTOPLEFT
 878                | HTTOP
 879                | HTTOPRIGHT
 880                | HTBOTTOMRIGHT
 881                | HTBOTTOM
 882                | HTBOTTOMLEFT
 883        ) {
 884            return Some(hit.0);
 885        }
 886
 887        if self.state.borrow().is_fullscreen() {
 888            return Some(HTCLIENT as _);
 889        }
 890
 891        let dpi = unsafe { GetDpiForWindow(handle) };
 892        let frame_y = unsafe { GetSystemMetricsForDpi(SM_CYFRAME, dpi) };
 893
 894        let mut cursor_point = POINT {
 895            x: lparam.signed_loword().into(),
 896            y: lparam.signed_hiword().into(),
 897        };
 898        unsafe { ScreenToClient(handle, &mut cursor_point).ok().log_err() };
 899        if !self.state.borrow().is_maximized() && cursor_point.y >= 0 && cursor_point.y <= frame_y {
 900            return Some(HTTOP as _);
 901        }
 902
 903        Some(HTCLIENT as _)
 904    }
 905
 906    fn handle_nc_mouse_move_msg(&self, handle: HWND, lparam: LPARAM) -> Option<isize> {
 907        self.start_tracking_mouse(handle, TME_LEAVE | TME_NONCLIENT);
 908
 909        let mut lock = self.state.borrow_mut();
 910        let mut func = lock.callbacks.input.take()?;
 911        let scale_factor = lock.scale_factor;
 912        drop(lock);
 913
 914        let mut cursor_point = POINT {
 915            x: lparam.signed_loword().into(),
 916            y: lparam.signed_hiword().into(),
 917        };
 918        unsafe { ScreenToClient(handle, &mut cursor_point).ok().log_err() };
 919        let input = PlatformInput::MouseMove(MouseMoveEvent {
 920            position: logical_point(cursor_point.x as f32, cursor_point.y as f32, scale_factor),
 921            pressed_button: None,
 922            modifiers: current_modifiers(),
 923        });
 924        let handled = !func(input).propagate;
 925        self.state.borrow_mut().callbacks.input = Some(func);
 926
 927        if handled { Some(0) } else { None }
 928    }
 929
 930    fn handle_nc_mouse_down_msg(
 931        &self,
 932        handle: HWND,
 933        button: MouseButton,
 934        wparam: WPARAM,
 935        lparam: LPARAM,
 936    ) -> Option<isize> {
 937        let mut lock = self.state.borrow_mut();
 938        if let Some(mut func) = lock.callbacks.input.take() {
 939            let scale_factor = lock.scale_factor;
 940            let mut cursor_point = POINT {
 941                x: lparam.signed_loword().into(),
 942                y: lparam.signed_hiword().into(),
 943            };
 944            unsafe { ScreenToClient(handle, &mut cursor_point).ok().log_err() };
 945            let physical_point = point(DevicePixels(cursor_point.x), DevicePixels(cursor_point.y));
 946            let click_count = lock.click_state.update(button, physical_point);
 947            drop(lock);
 948
 949            let input = PlatformInput::MouseDown(MouseDownEvent {
 950                button,
 951                position: logical_point(cursor_point.x as f32, cursor_point.y as f32, scale_factor),
 952                modifiers: current_modifiers(),
 953                click_count,
 954                first_mouse: false,
 955            });
 956            let result = func(input);
 957            let handled = !result.propagate || result.default_prevented;
 958            self.state.borrow_mut().callbacks.input = Some(func);
 959
 960            if handled {
 961                return Some(0);
 962            }
 963        } else {
 964            drop(lock);
 965        };
 966
 967        // Since these are handled in handle_nc_mouse_up_msg we must prevent the default window proc
 968        if button == MouseButton::Left {
 969            match wparam.0 as u32 {
 970                HTMINBUTTON => self.state.borrow_mut().nc_button_pressed = Some(HTMINBUTTON),
 971                HTMAXBUTTON => self.state.borrow_mut().nc_button_pressed = Some(HTMAXBUTTON),
 972                HTCLOSE => self.state.borrow_mut().nc_button_pressed = Some(HTCLOSE),
 973                _ => return None,
 974            };
 975            Some(0)
 976        } else {
 977            None
 978        }
 979    }
 980
 981    fn handle_nc_mouse_up_msg(
 982        &self,
 983        handle: HWND,
 984        button: MouseButton,
 985        wparam: WPARAM,
 986        lparam: LPARAM,
 987    ) -> Option<isize> {
 988        let mut lock = self.state.borrow_mut();
 989        if let Some(mut func) = lock.callbacks.input.take() {
 990            let scale_factor = lock.scale_factor;
 991            drop(lock);
 992
 993            let mut cursor_point = POINT {
 994                x: lparam.signed_loword().into(),
 995                y: lparam.signed_hiword().into(),
 996            };
 997            unsafe { ScreenToClient(handle, &mut cursor_point).ok().log_err() };
 998            let input = PlatformInput::MouseUp(MouseUpEvent {
 999                button,
1000                position: logical_point(cursor_point.x as f32, cursor_point.y as f32, scale_factor),
1001                modifiers: current_modifiers(),
1002                click_count: 1,
1003            });
1004            let handled = !func(input).propagate;
1005            self.state.borrow_mut().callbacks.input = Some(func);
1006
1007            if handled {
1008                return Some(0);
1009            }
1010        } else {
1011            drop(lock);
1012        }
1013
1014        let last_pressed = self.state.borrow_mut().nc_button_pressed.take();
1015        if button == MouseButton::Left
1016            && let Some(last_pressed) = last_pressed
1017        {
1018            let handled = match (wparam.0 as u32, last_pressed) {
1019                (HTMINBUTTON, HTMINBUTTON) => {
1020                    unsafe { ShowWindowAsync(handle, SW_MINIMIZE).ok().log_err() };
1021                    true
1022                }
1023                (HTMAXBUTTON, HTMAXBUTTON) => {
1024                    if self.state.borrow().is_maximized() {
1025                        unsafe { ShowWindowAsync(handle, SW_NORMAL).ok().log_err() };
1026                    } else {
1027                        unsafe { ShowWindowAsync(handle, SW_MAXIMIZE).ok().log_err() };
1028                    }
1029                    true
1030                }
1031                (HTCLOSE, HTCLOSE) => {
1032                    unsafe {
1033                        PostMessageW(Some(handle), WM_CLOSE, WPARAM::default(), LPARAM::default())
1034                            .log_err()
1035                    };
1036                    true
1037                }
1038                _ => false,
1039            };
1040            if handled {
1041                return Some(0);
1042            }
1043        }
1044
1045        None
1046    }
1047
1048    fn handle_cursor_changed(&self, lparam: LPARAM) -> Option<isize> {
1049        let mut state = self.state.borrow_mut();
1050        let had_cursor = state.current_cursor.is_some();
1051
1052        state.current_cursor = if lparam.0 == 0 {
1053            None
1054        } else {
1055            Some(HCURSOR(lparam.0 as _))
1056        };
1057
1058        if had_cursor != state.current_cursor.is_some() {
1059            unsafe { SetCursor(state.current_cursor) };
1060        }
1061
1062        Some(0)
1063    }
1064
1065    fn handle_set_cursor(&self, handle: HWND, lparam: LPARAM) -> Option<isize> {
1066        if unsafe { !IsWindowEnabled(handle).as_bool() }
1067            || matches!(
1068                lparam.loword() as u32,
1069                HTLEFT
1070                    | HTRIGHT
1071                    | HTTOP
1072                    | HTTOPLEFT
1073                    | HTTOPRIGHT
1074                    | HTBOTTOM
1075                    | HTBOTTOMLEFT
1076                    | HTBOTTOMRIGHT
1077            )
1078        {
1079            return None;
1080        }
1081        unsafe {
1082            SetCursor(self.state.borrow().current_cursor);
1083        };
1084        Some(1)
1085    }
1086
1087    fn handle_system_settings_changed(
1088        &self,
1089        handle: HWND,
1090        wparam: WPARAM,
1091        lparam: LPARAM,
1092    ) -> Option<isize> {
1093        if wparam.0 != 0 {
1094            let mut lock = self.state.borrow_mut();
1095            let display = lock.display;
1096            lock.click_state.system_update(wparam.0);
1097            lock.border_offset.update(handle).log_err();
1098            // system settings may emit a window message which wants to take the refcell lock, so drop it
1099            drop(lock);
1100            self.system_settings_mut().update(display, wparam.0);
1101        } else {
1102            self.handle_system_theme_changed(handle, lparam)?;
1103        };
1104        // Force to trigger WM_NCCALCSIZE event to ensure that we handle auto hide
1105        // taskbar correctly.
1106        notify_frame_changed(handle);
1107
1108        Some(0)
1109    }
1110
1111    fn handle_system_theme_changed(&self, handle: HWND, lparam: LPARAM) -> Option<isize> {
1112        // lParam is a pointer to a string that indicates the area containing the system parameter
1113        // that was changed.
1114        let parameter = PCWSTR::from_raw(lparam.0 as _);
1115        if unsafe { !parameter.is_null() && !parameter.is_empty() }
1116            && let Some(parameter_string) = unsafe { parameter.to_string() }.log_err()
1117        {
1118            log::info!("System settings changed: {}", parameter_string);
1119            if parameter_string.as_str() == "ImmersiveColorSet" {
1120                let new_appearance = system_appearance()
1121                    .context("unable to get system appearance when handling ImmersiveColorSet")
1122                    .log_err()?;
1123                let mut lock = self.state.borrow_mut();
1124                if new_appearance != lock.appearance {
1125                    lock.appearance = new_appearance;
1126                    let mut callback = lock.callbacks.appearance_changed.take()?;
1127                    drop(lock);
1128                    callback();
1129                    self.state.borrow_mut().callbacks.appearance_changed = Some(callback);
1130                    configure_dwm_dark_mode(handle, new_appearance);
1131                }
1132            }
1133        }
1134        Some(0)
1135    }
1136
1137    fn handle_input_language_changed(&self) -> Option<isize> {
1138        unsafe {
1139            PostMessageW(
1140                Some(self.platform_window_handle),
1141                WM_GPUI_KEYBOARD_LAYOUT_CHANGED,
1142                WPARAM(self.validation_number),
1143                LPARAM(0),
1144            )
1145            .log_err();
1146        }
1147        Some(0)
1148    }
1149
1150    fn handle_window_visibility_changed(&self, handle: HWND, wparam: WPARAM) -> Option<isize> {
1151        if wparam.0 == 1 {
1152            self.draw_window(handle, false);
1153        }
1154        None
1155    }
1156
1157    fn handle_device_lost(&self, lparam: LPARAM) -> Option<isize> {
1158        let mut lock = self.state.borrow_mut();
1159        let devices = lparam.0 as *const DirectXDevices;
1160        let devices = unsafe { &*devices };
1161        if let Err(err) = lock.renderer.handle_device_lost(&devices) {
1162            panic!("Device lost: {err}");
1163        }
1164        Some(0)
1165    }
1166
1167    #[inline]
1168    fn draw_window(&self, handle: HWND, force_render: bool) -> Option<isize> {
1169        let mut request_frame = self.state.borrow_mut().callbacks.request_frame.take()?;
1170
1171        // we are instructing gpui to force render a frame, this will
1172        // re-populate all the gpu textures for us so we can resume drawing in
1173        // case we disabled drawing earlier due to a device loss
1174        self.state.borrow_mut().renderer.mark_drawable();
1175        request_frame(RequestFrameOptions {
1176            require_presentation: false,
1177            force_render,
1178        });
1179
1180        self.state.borrow_mut().callbacks.request_frame = Some(request_frame);
1181        unsafe { ValidateRect(Some(handle), None).ok().log_err() };
1182
1183        Some(0)
1184    }
1185
1186    #[inline]
1187    fn parse_char_message(&self, wparam: WPARAM) -> Option<String> {
1188        let code_point = wparam.loword();
1189        let mut lock = self.state.borrow_mut();
1190        // https://www.unicode.org/versions/Unicode16.0.0/core-spec/chapter-3/#G2630
1191        match code_point {
1192            0xD800..=0xDBFF => {
1193                // High surrogate, wait for low surrogate
1194                lock.pending_surrogate = Some(code_point);
1195                None
1196            }
1197            0xDC00..=0xDFFF => {
1198                if let Some(high_surrogate) = lock.pending_surrogate.take() {
1199                    // Low surrogate, combine with pending high surrogate
1200                    String::from_utf16(&[high_surrogate, code_point]).ok()
1201                } else {
1202                    // Invalid low surrogate without a preceding high surrogate
1203                    log::warn!(
1204                        "Received low surrogate without a preceding high surrogate: {code_point:x}"
1205                    );
1206                    None
1207                }
1208            }
1209            _ => {
1210                lock.pending_surrogate = None;
1211                char::from_u32(code_point as u32)
1212                    .filter(|c| !c.is_control())
1213                    .map(|c| c.to_string())
1214            }
1215        }
1216    }
1217
1218    fn start_tracking_mouse(&self, handle: HWND, flags: TRACKMOUSEEVENT_FLAGS) {
1219        let mut lock = self.state.borrow_mut();
1220        if !lock.hovered {
1221            lock.hovered = true;
1222            unsafe {
1223                TrackMouseEvent(&mut TRACKMOUSEEVENT {
1224                    cbSize: std::mem::size_of::<TRACKMOUSEEVENT>() as u32,
1225                    dwFlags: flags,
1226                    hwndTrack: handle,
1227                    dwHoverTime: HOVER_DEFAULT,
1228                })
1229                .log_err()
1230            };
1231            if let Some(mut callback) = lock.callbacks.hovered_status_change.take() {
1232                drop(lock);
1233                callback(true);
1234                self.state.borrow_mut().callbacks.hovered_status_change = Some(callback);
1235            }
1236        }
1237    }
1238
1239    fn with_input_handler<F, R>(&self, f: F) -> Option<R>
1240    where
1241        F: FnOnce(&mut PlatformInputHandler) -> R,
1242    {
1243        let mut input_handler = self.state.borrow_mut().input_handler.take()?;
1244        let result = f(&mut input_handler);
1245        self.state.borrow_mut().input_handler = Some(input_handler);
1246        Some(result)
1247    }
1248
1249    fn with_input_handler_and_scale_factor<F, R>(&self, f: F) -> Option<R>
1250    where
1251        F: FnOnce(&mut PlatformInputHandler, f32) -> Option<R>,
1252    {
1253        let mut lock = self.state.borrow_mut();
1254        let mut input_handler = lock.input_handler.take()?;
1255        let scale_factor = lock.scale_factor;
1256        drop(lock);
1257        let result = f(&mut input_handler, scale_factor);
1258        self.state.borrow_mut().input_handler = Some(input_handler);
1259        result
1260    }
1261}
1262
1263fn handle_key_event<F>(
1264    wparam: WPARAM,
1265    lparam: LPARAM,
1266    state: &mut WindowsWindowState,
1267    f: F,
1268) -> Option<PlatformInput>
1269where
1270    F: FnOnce(Keystroke, bool) -> PlatformInput,
1271{
1272    let virtual_key = VIRTUAL_KEY(wparam.loword());
1273    let modifiers = current_modifiers();
1274
1275    match virtual_key {
1276        VK_SHIFT | VK_CONTROL | VK_MENU | VK_LMENU | VK_RMENU | VK_LWIN | VK_RWIN => {
1277            if state
1278                .last_reported_modifiers
1279                .is_some_and(|prev_modifiers| prev_modifiers == modifiers)
1280            {
1281                return None;
1282            }
1283            state.last_reported_modifiers = Some(modifiers);
1284            Some(PlatformInput::ModifiersChanged(ModifiersChangedEvent {
1285                modifiers,
1286                capslock: current_capslock(),
1287            }))
1288        }
1289        VK_PACKET => None,
1290        VK_CAPITAL => {
1291            let capslock = current_capslock();
1292            if state
1293                .last_reported_capslock
1294                .is_some_and(|prev_capslock| prev_capslock == capslock)
1295            {
1296                return None;
1297            }
1298            state.last_reported_capslock = Some(capslock);
1299            Some(PlatformInput::ModifiersChanged(ModifiersChangedEvent {
1300                modifiers,
1301                capslock,
1302            }))
1303        }
1304        vkey => {
1305            let keystroke = parse_normal_key(vkey, lparam, modifiers)?;
1306            Some(f(keystroke.0, keystroke.1))
1307        }
1308    }
1309}
1310
1311fn parse_immutable(vkey: VIRTUAL_KEY) -> Option<String> {
1312    Some(
1313        match vkey {
1314            VK_SPACE => "space",
1315            VK_BACK => "backspace",
1316            VK_RETURN => "enter",
1317            VK_TAB => "tab",
1318            VK_UP => "up",
1319            VK_DOWN => "down",
1320            VK_RIGHT => "right",
1321            VK_LEFT => "left",
1322            VK_HOME => "home",
1323            VK_END => "end",
1324            VK_PRIOR => "pageup",
1325            VK_NEXT => "pagedown",
1326            VK_BROWSER_BACK => "back",
1327            VK_BROWSER_FORWARD => "forward",
1328            VK_ESCAPE => "escape",
1329            VK_INSERT => "insert",
1330            VK_DELETE => "delete",
1331            VK_APPS => "menu",
1332            VK_F1 => "f1",
1333            VK_F2 => "f2",
1334            VK_F3 => "f3",
1335            VK_F4 => "f4",
1336            VK_F5 => "f5",
1337            VK_F6 => "f6",
1338            VK_F7 => "f7",
1339            VK_F8 => "f8",
1340            VK_F9 => "f9",
1341            VK_F10 => "f10",
1342            VK_F11 => "f11",
1343            VK_F12 => "f12",
1344            VK_F13 => "f13",
1345            VK_F14 => "f14",
1346            VK_F15 => "f15",
1347            VK_F16 => "f16",
1348            VK_F17 => "f17",
1349            VK_F18 => "f18",
1350            VK_F19 => "f19",
1351            VK_F20 => "f20",
1352            VK_F21 => "f21",
1353            VK_F22 => "f22",
1354            VK_F23 => "f23",
1355            VK_F24 => "f24",
1356            _ => return None,
1357        }
1358        .to_string(),
1359    )
1360}
1361
1362fn parse_normal_key(
1363    vkey: VIRTUAL_KEY,
1364    lparam: LPARAM,
1365    mut modifiers: Modifiers,
1366) -> Option<(Keystroke, bool)> {
1367    let (key_char, prefer_character_input) = process_key(vkey, lparam.hiword());
1368
1369    let key = parse_immutable(vkey).or_else(|| {
1370        let scan_code = lparam.hiword() & 0xFF;
1371        get_keystroke_key(vkey, scan_code as u32, &mut modifiers)
1372    })?;
1373
1374    Some((
1375        Keystroke {
1376            modifiers,
1377            key,
1378            key_char,
1379        },
1380        prefer_character_input,
1381    ))
1382}
1383
1384fn process_key(vkey: VIRTUAL_KEY, scan_code: u16) -> (Option<String>, bool) {
1385    let mut keyboard_state = [0u8; 256];
1386    unsafe {
1387        if GetKeyboardState(&mut keyboard_state).is_err() {
1388            return (None, false);
1389        }
1390    }
1391
1392    let mut buffer_c = [0u16; 8];
1393    let result_c = unsafe {
1394        ToUnicode(
1395            vkey.0 as u32,
1396            scan_code as u32,
1397            Some(&keyboard_state),
1398            &mut buffer_c,
1399            0x4,
1400        )
1401    };
1402
1403    if result_c == 0 {
1404        return (None, false);
1405    }
1406
1407    let c = &buffer_c[..result_c.unsigned_abs() as usize];
1408    let key_char = String::from_utf16(c)
1409        .ok()
1410        .filter(|s| !s.is_empty() && !s.chars().next().unwrap().is_control());
1411
1412    if result_c < 0 {
1413        return (key_char, true);
1414    }
1415
1416    if key_char.is_none() {
1417        return (None, false);
1418    }
1419
1420    // Workaround for some bug that makes the compiler think keyboard_state is still zeroed out
1421    let keyboard_state = std::hint::black_box(keyboard_state);
1422    let ctrl_down = (keyboard_state[VK_CONTROL.0 as usize] & 0x80) != 0;
1423    let alt_down = (keyboard_state[VK_MENU.0 as usize] & 0x80) != 0;
1424    let win_down = (keyboard_state[VK_LWIN.0 as usize] & 0x80) != 0
1425        || (keyboard_state[VK_RWIN.0 as usize] & 0x80) != 0;
1426
1427    let has_modifiers = ctrl_down || alt_down || win_down;
1428    if !has_modifiers {
1429        return (key_char, false);
1430    }
1431
1432    let mut state_no_modifiers = keyboard_state;
1433    state_no_modifiers[VK_CONTROL.0 as usize] = 0;
1434    state_no_modifiers[VK_LCONTROL.0 as usize] = 0;
1435    state_no_modifiers[VK_RCONTROL.0 as usize] = 0;
1436    state_no_modifiers[VK_MENU.0 as usize] = 0;
1437    state_no_modifiers[VK_LMENU.0 as usize] = 0;
1438    state_no_modifiers[VK_RMENU.0 as usize] = 0;
1439    state_no_modifiers[VK_LWIN.0 as usize] = 0;
1440    state_no_modifiers[VK_RWIN.0 as usize] = 0;
1441
1442    let mut buffer_c_no_modifiers = [0u16; 8];
1443    let result_c_no_modifiers = unsafe {
1444        ToUnicode(
1445            vkey.0 as u32,
1446            scan_code as u32,
1447            Some(&state_no_modifiers),
1448            &mut buffer_c_no_modifiers,
1449            0x4,
1450        )
1451    };
1452
1453    let c_no_modifiers = &buffer_c_no_modifiers[..result_c_no_modifiers.unsigned_abs() as usize];
1454    (
1455        key_char,
1456        result_c != result_c_no_modifiers || c != c_no_modifiers,
1457    )
1458}
1459
1460fn parse_ime_composition_string(ctx: HIMC, comp_type: IME_COMPOSITION_STRING) -> Option<String> {
1461    unsafe {
1462        let string_len = ImmGetCompositionStringW(ctx, comp_type, None, 0);
1463        if string_len >= 0 {
1464            let mut buffer = vec![0u8; string_len as usize + 2];
1465            ImmGetCompositionStringW(
1466                ctx,
1467                comp_type,
1468                Some(buffer.as_mut_ptr() as _),
1469                string_len as _,
1470            );
1471            let wstring = std::slice::from_raw_parts::<u16>(
1472                buffer.as_mut_ptr().cast::<u16>(),
1473                string_len as usize / 2,
1474            );
1475            Some(String::from_utf16_lossy(wstring))
1476        } else {
1477            None
1478        }
1479    }
1480}
1481
1482#[inline]
1483fn retrieve_composition_cursor_position(ctx: HIMC) -> usize {
1484    unsafe { ImmGetCompositionStringW(ctx, GCS_CURSORPOS, None, 0) as usize }
1485}
1486
1487#[inline]
1488fn is_virtual_key_pressed(vkey: VIRTUAL_KEY) -> bool {
1489    unsafe { GetKeyState(vkey.0 as i32) < 0 }
1490}
1491
1492#[inline]
1493pub(crate) fn current_modifiers() -> Modifiers {
1494    Modifiers {
1495        control: is_virtual_key_pressed(VK_CONTROL),
1496        alt: is_virtual_key_pressed(VK_MENU),
1497        shift: is_virtual_key_pressed(VK_SHIFT),
1498        platform: is_virtual_key_pressed(VK_LWIN) || is_virtual_key_pressed(VK_RWIN),
1499        function: false,
1500    }
1501}
1502
1503#[inline]
1504pub(crate) fn current_capslock() -> Capslock {
1505    let on = unsafe { GetKeyState(VK_CAPITAL.0 as i32) & 1 } > 0;
1506    Capslock { on }
1507}
1508
1509fn get_client_area_insets(
1510    handle: HWND,
1511    is_maximized: bool,
1512    windows_version: WindowsVersion,
1513) -> RECT {
1514    // For maximized windows, Windows outdents the window rect from the screen's client rect
1515    // by `frame_thickness` on each edge, meaning `insets` must contain `frame_thickness`
1516    // on all sides (including the top) to avoid the client area extending onto adjacent
1517    // monitors.
1518    //
1519    // For non-maximized windows, things become complicated:
1520    //
1521    // - On Windows 10
1522    // The top inset must be zero, since if there is any nonclient area, Windows will draw
1523    // a full native titlebar outside the client area. (This doesn't occur in the maximized
1524    // case.)
1525    //
1526    // - On Windows 11
1527    // The top inset is calculated using an empirical formula that I derived through various
1528    // tests. Without this, the top 1-2 rows of pixels in our window would be obscured.
1529    let dpi = unsafe { GetDpiForWindow(handle) };
1530    let frame_thickness = get_frame_thickness(dpi);
1531    let top_insets = if is_maximized {
1532        frame_thickness
1533    } else {
1534        match windows_version {
1535            WindowsVersion::Win10 => 0,
1536            WindowsVersion::Win11 => (dpi as f32 / USER_DEFAULT_SCREEN_DPI as f32).round() as i32,
1537        }
1538    };
1539    RECT {
1540        left: frame_thickness,
1541        top: top_insets,
1542        right: frame_thickness,
1543        bottom: frame_thickness,
1544    }
1545}
1546
1547// there is some additional non-visible space when talking about window
1548// borders on Windows:
1549// - SM_CXSIZEFRAME: The resize handle.
1550// - SM_CXPADDEDBORDER: Additional border space that isn't part of the resize handle.
1551fn get_frame_thickness(dpi: u32) -> i32 {
1552    let resize_frame_thickness = unsafe { GetSystemMetricsForDpi(SM_CXSIZEFRAME, dpi) };
1553    let padding_thickness = unsafe { GetSystemMetricsForDpi(SM_CXPADDEDBORDER, dpi) };
1554    resize_frame_thickness + padding_thickness
1555}
1556
1557fn notify_frame_changed(handle: HWND) {
1558    unsafe {
1559        SetWindowPos(
1560            handle,
1561            None,
1562            0,
1563            0,
1564            0,
1565            0,
1566            SWP_FRAMECHANGED
1567                | SWP_NOACTIVATE
1568                | SWP_NOCOPYBITS
1569                | SWP_NOMOVE
1570                | SWP_NOOWNERZORDER
1571                | SWP_NOREPOSITION
1572                | SWP_NOSENDCHANGING
1573                | SWP_NOSIZE
1574                | SWP_NOZORDER,
1575        )
1576        .log_err();
1577    }
1578}