client.rs

   1use anyhow::{Context as _, anyhow};
   2use ashpd::WindowIdentifier;
   3use calloop::{
   4    EventLoop, LoopHandle, RegistrationToken,
   5    generic::{FdWrapper, Generic},
   6};
   7use collections::HashMap;
   8use core::str;
   9use gpui::{Capslock, TaskTiming, profiler};
  10use http_client::Url;
  11use log::Level;
  12use smallvec::SmallVec;
  13use std::{
  14    cell::RefCell,
  15    collections::{BTreeMap, HashSet},
  16    ops::Deref,
  17    path::PathBuf,
  18    rc::{Rc, Weak},
  19    time::{Duration, Instant},
  20};
  21use util::ResultExt as _;
  22
  23use x11rb::{
  24    connection::{Connection, RequestConnection},
  25    cursor,
  26    errors::ConnectionError,
  27    protocol::randr::ConnectionExt as _,
  28    protocol::xinput::ConnectionExt,
  29    protocol::xkb::ConnectionExt as _,
  30    protocol::xproto::{
  31        AtomEnum, ChangeWindowAttributesAux, ClientMessageData, ClientMessageEvent,
  32        ConnectionExt as _, EventMask, ModMask, Visibility,
  33    },
  34    protocol::{Event, dri3, randr, render, xinput, xkb, xproto},
  35    resource_manager::Database,
  36    wrapper::ConnectionExt as _,
  37    xcb_ffi::XCBConnection,
  38};
  39use xim::{AttributeName, Client, InputStyle, x11rb::X11rbClient};
  40use xkbc::x11::ffi::{XKB_X11_MIN_MAJOR_XKB_VERSION, XKB_X11_MIN_MINOR_XKB_VERSION};
  41use xkbcommon::xkb::{self as xkbc, STATE_LAYOUT_EFFECTIVE};
  42
  43use super::{
  44    ButtonOrScroll, ScrollDirection, X11Display, X11WindowStatePtr, XcbAtoms, XimCallbackEvent,
  45    XimHandler, button_or_scroll_from_event_detail, check_reply,
  46    clipboard::{self, Clipboard},
  47    get_reply, get_valuator_axis_index, handle_connection_error, modifiers_from_state,
  48    pressed_button_from_mask, xcb_flush,
  49};
  50
  51use crate::linux::{
  52    DEFAULT_CURSOR_ICON_NAME, LinuxClient, capslock_from_xkb, cursor_style_to_icon_names,
  53    get_xkb_compose_state, is_within_click_distance, keystroke_from_xkb,
  54    keystroke_underlying_dead_key, log_cursor_icon_warning, modifiers_from_xkb, open_uri_internal,
  55    platform::{DOUBLE_CLICK_INTERVAL, SCROLL_LINES},
  56    reveal_path_internal,
  57    xdg_desktop_portal::{Event as XDPEvent, XDPEventSource},
  58};
  59use crate::linux::{LinuxCommon, LinuxKeyboardLayout, X11Window, modifiers_from_xinput_info};
  60
  61use gpui::{
  62    AnyWindowHandle, Bounds, ClipboardItem, CursorStyle, DisplayId, FileDropEvent, Keystroke,
  63    Modifiers, ModifiersChangedEvent, MouseButton, Pixels, PlatformDisplay, PlatformInput,
  64    PlatformKeyboardLayout, PlatformWindow, Point, RequestFrameOptions, ScrollDelta, Size,
  65    TouchPhase, WindowParams, point, px,
  66};
  67use gpui_wgpu::{CompositorGpuHint, GpuContext};
  68
  69/// Value for DeviceId parameters which selects all devices.
  70pub(crate) const XINPUT_ALL_DEVICES: xinput::DeviceId = 0;
  71
  72/// Value for DeviceId parameters which selects all device groups. Events that
  73/// occur within the group are emitted by the group itself.
  74///
  75/// In XInput 2's interface, these are referred to as "master devices", but that
  76/// terminology is both archaic and unclear.
  77pub(crate) const XINPUT_ALL_DEVICE_GROUPS: xinput::DeviceId = 1;
  78
  79const GPUI_X11_SCALE_FACTOR_ENV: &str = "GPUI_X11_SCALE_FACTOR";
  80
  81pub(crate) struct WindowRef {
  82    window: X11WindowStatePtr,
  83    refresh_state: Option<RefreshState>,
  84    expose_event_received: bool,
  85    last_visibility: Visibility,
  86    is_mapped: bool,
  87}
  88
  89impl WindowRef {
  90    pub fn handle(&self) -> AnyWindowHandle {
  91        self.window.state.borrow().handle
  92    }
  93}
  94
  95impl Deref for WindowRef {
  96    type Target = X11WindowStatePtr;
  97
  98    fn deref(&self) -> &Self::Target {
  99        &self.window
 100    }
 101}
 102
 103enum RefreshState {
 104    Hidden {
 105        refresh_rate: Duration,
 106    },
 107    PeriodicRefresh {
 108        refresh_rate: Duration,
 109        event_loop_token: RegistrationToken,
 110    },
 111}
 112
 113#[derive(Debug)]
 114#[non_exhaustive]
 115pub enum EventHandlerError {
 116    XCBConnectionError(ConnectionError),
 117    XIMClientError(xim::ClientError),
 118}
 119
 120impl std::error::Error for EventHandlerError {}
 121
 122impl std::fmt::Display for EventHandlerError {
 123    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 124        match self {
 125            EventHandlerError::XCBConnectionError(err) => err.fmt(f),
 126            EventHandlerError::XIMClientError(err) => err.fmt(f),
 127        }
 128    }
 129}
 130
 131impl From<ConnectionError> for EventHandlerError {
 132    fn from(err: ConnectionError) -> Self {
 133        EventHandlerError::XCBConnectionError(err)
 134    }
 135}
 136
 137impl From<xim::ClientError> for EventHandlerError {
 138    fn from(err: xim::ClientError) -> Self {
 139        EventHandlerError::XIMClientError(err)
 140    }
 141}
 142
 143#[derive(Debug, Default)]
 144pub struct Xdnd {
 145    other_window: xproto::Window,
 146    drag_type: u32,
 147    retrieved: bool,
 148    position: Point<Pixels>,
 149}
 150
 151#[derive(Debug)]
 152struct PointerDeviceState {
 153    horizontal: ScrollAxisState,
 154    vertical: ScrollAxisState,
 155}
 156
 157#[derive(Debug, Default)]
 158struct ScrollAxisState {
 159    /// Valuator number for looking up this axis's scroll value.
 160    valuator_number: Option<u16>,
 161    /// Conversion factor from scroll units to lines.
 162    multiplier: f32,
 163    /// Last scroll value for calculating scroll delta.
 164    ///
 165    /// This gets set to `None` whenever it might be invalid - when devices change or when window focus changes.
 166    /// The logic errs on the side of invalidating this, since the consequence is just skipping the delta of one scroll event.
 167    /// The consequence of not invalidating it can be large invalid deltas, which are much more user visible.
 168    scroll_value: Option<f32>,
 169}
 170
 171pub struct X11ClientState {
 172    pub(crate) loop_handle: LoopHandle<'static, X11Client>,
 173    pub(crate) event_loop: Option<calloop::EventLoop<'static, X11Client>>,
 174
 175    pub(crate) last_click: Instant,
 176    pub(crate) last_mouse_button: Option<MouseButton>,
 177    pub(crate) last_location: Point<Pixels>,
 178    pub(crate) current_count: usize,
 179
 180    pub(crate) gpu_context: GpuContext,
 181    pub(crate) compositor_gpu: Option<CompositorGpuHint>,
 182
 183    pub(crate) scale_factor: f32,
 184
 185    xkb_context: xkbc::Context,
 186    pub(crate) xcb_connection: Rc<XCBConnection>,
 187    xkb_device_id: i32,
 188    client_side_decorations_supported: bool,
 189    pub(crate) x_root_index: usize,
 190    pub(crate) _resource_database: Database,
 191    pub(crate) atoms: XcbAtoms,
 192    pub(crate) windows: HashMap<xproto::Window, WindowRef>,
 193    pub(crate) mouse_focused_window: Option<xproto::Window>,
 194    pub(crate) keyboard_focused_window: Option<xproto::Window>,
 195    pub(crate) xkb: xkbc::State,
 196    keyboard_layout: LinuxKeyboardLayout,
 197    pub(crate) ximc: Option<X11rbClient<Rc<XCBConnection>>>,
 198    pub(crate) xim_handler: Option<XimHandler>,
 199    pub modifiers: Modifiers,
 200    pub capslock: Capslock,
 201    // TODO: Can the other updates to `modifiers` be removed so that this is unnecessary?
 202    // capslock logic was done analog to modifiers
 203    pub last_modifiers_changed_event: Modifiers,
 204    pub last_capslock_changed_event: Capslock,
 205
 206    pub(crate) compose_state: Option<xkbc::compose::State>,
 207    pub(crate) pre_edit_text: Option<String>,
 208    pub(crate) composing: bool,
 209    pub(crate) pre_key_char_down: Option<Keystroke>,
 210    pub(crate) cursor_handle: cursor::Handle,
 211    pub(crate) cursor_styles: HashMap<xproto::Window, CursorStyle>,
 212    pub(crate) cursor_cache: HashMap<CursorStyle, Option<xproto::Cursor>>,
 213
 214    pointer_device_states: BTreeMap<xinput::DeviceId, PointerDeviceState>,
 215
 216    pub(crate) common: LinuxCommon,
 217    pub(crate) clipboard: Clipboard,
 218    pub(crate) clipboard_item: Option<ClipboardItem>,
 219    pub(crate) xdnd_state: Xdnd,
 220}
 221
 222#[derive(Clone)]
 223pub struct X11ClientStatePtr(pub Weak<RefCell<X11ClientState>>);
 224
 225impl X11ClientStatePtr {
 226    pub fn get_client(&self) -> Option<X11Client> {
 227        self.0.upgrade().map(X11Client)
 228    }
 229
 230    pub fn drop_window(&self, x_window: u32) {
 231        let Some(client) = self.get_client() else {
 232            return;
 233        };
 234        let mut state = client.0.borrow_mut();
 235
 236        if let Some(window_ref) = state.windows.remove(&x_window)
 237            && let Some(RefreshState::PeriodicRefresh {
 238                event_loop_token, ..
 239            }) = window_ref.refresh_state
 240        {
 241            state.loop_handle.remove(event_loop_token);
 242        }
 243        if state.mouse_focused_window == Some(x_window) {
 244            state.mouse_focused_window = None;
 245        }
 246        if state.keyboard_focused_window == Some(x_window) {
 247            state.keyboard_focused_window = None;
 248        }
 249        state.cursor_styles.remove(&x_window);
 250    }
 251
 252    pub fn update_ime_position(&self, bounds: Bounds<Pixels>) {
 253        let Some(client) = self.get_client() else {
 254            return;
 255        };
 256        let mut state = client.0.borrow_mut();
 257        if state.composing || state.ximc.is_none() {
 258            return;
 259        }
 260
 261        let Some(mut ximc) = state.ximc.take() else {
 262            log::error!("bug: xim connection not set");
 263            return;
 264        };
 265        let Some(xim_handler) = state.xim_handler.take() else {
 266            log::error!("bug: xim handler not set");
 267            state.ximc = Some(ximc);
 268            return;
 269        };
 270        let scaled_bounds = bounds.scale(state.scale_factor);
 271        let ic_attributes = ximc
 272            .build_ic_attributes()
 273            .push(
 274                xim::AttributeName::InputStyle,
 275                xim::InputStyle::PREEDIT_CALLBACKS,
 276            )
 277            .push(xim::AttributeName::ClientWindow, xim_handler.window)
 278            .push(xim::AttributeName::FocusWindow, xim_handler.window)
 279            .nested_list(xim::AttributeName::PreeditAttributes, |b| {
 280                b.push(
 281                    xim::AttributeName::SpotLocation,
 282                    xim::Point {
 283                        x: u32::from(scaled_bounds.origin.x + scaled_bounds.size.width) as i16,
 284                        y: u32::from(scaled_bounds.origin.y + scaled_bounds.size.height) as i16,
 285                    },
 286                );
 287            })
 288            .build();
 289        let _ = ximc
 290            .set_ic_values(xim_handler.im_id, xim_handler.ic_id, ic_attributes)
 291            .log_err();
 292        state.ximc = Some(ximc);
 293        state.xim_handler = Some(xim_handler);
 294    }
 295}
 296
 297#[derive(Clone)]
 298pub(crate) struct X11Client(pub(crate) Rc<RefCell<X11ClientState>>);
 299
 300impl X11Client {
 301    pub(crate) fn new() -> anyhow::Result<Self> {
 302        let event_loop = EventLoop::try_new()?;
 303
 304        let (common, main_receiver) = LinuxCommon::new(event_loop.get_signal());
 305
 306        let handle = event_loop.handle();
 307
 308        handle
 309            .insert_source(main_receiver, {
 310                let handle = handle.clone();
 311                move |event, _, _: &mut X11Client| {
 312                    if let calloop::channel::Event::Msg(runnable) = event {
 313                        // Insert the runnables as idle callbacks, so we make sure that user-input and X11
 314                        // events have higher priority and runnables are only worked off after the event
 315                        // callbacks.
 316                        handle.insert_idle(|_| {
 317                            let start = Instant::now();
 318                            let location = runnable.metadata().location;
 319                            let mut timing = TaskTiming {
 320                                location,
 321                                start,
 322                                end: None,
 323                            };
 324                            profiler::add_task_timing(timing);
 325
 326                            runnable.run();
 327
 328                            let end = Instant::now();
 329                            timing.end = Some(end);
 330                            profiler::add_task_timing(timing);
 331                        });
 332                    }
 333                }
 334            })
 335            .map_err(|err| {
 336                anyhow!("Failed to initialize event loop handling of foreground tasks: {err:?}")
 337            })?;
 338
 339        let (xcb_connection, x_root_index) = XCBConnection::connect(None)?;
 340        xcb_connection.prefetch_extension_information(xkb::X11_EXTENSION_NAME)?;
 341        xcb_connection.prefetch_extension_information(randr::X11_EXTENSION_NAME)?;
 342        xcb_connection.prefetch_extension_information(render::X11_EXTENSION_NAME)?;
 343        xcb_connection.prefetch_extension_information(xinput::X11_EXTENSION_NAME)?;
 344
 345        // Announce to X server that XInput up to 2.1 is supported. To increase this to 2.2 and
 346        // beyond, support for touch events would need to be added.
 347        let xinput_version = get_reply(
 348            || "XInput XiQueryVersion failed",
 349            xcb_connection.xinput_xi_query_version(2, 1),
 350        )?;
 351        assert!(
 352            xinput_version.major_version >= 2,
 353            "XInput version >= 2 required."
 354        );
 355
 356        let pointer_device_states =
 357            current_pointer_device_states(&xcb_connection, &BTreeMap::new()).unwrap_or_default();
 358
 359        let atoms = XcbAtoms::new(&xcb_connection)
 360            .context("Failed to get XCB atoms")?
 361            .reply()
 362            .context("Failed to get XCB atoms")?;
 363
 364        let root = xcb_connection.setup().roots[0].root;
 365        let compositor_present = check_compositor_present(&xcb_connection, root);
 366        let gtk_frame_extents_supported =
 367            check_gtk_frame_extents_supported(&xcb_connection, &atoms, root);
 368        let client_side_decorations_supported = compositor_present && gtk_frame_extents_supported;
 369        log::info!(
 370            "x11: compositor present: {}, gtk_frame_extents_supported: {}",
 371            compositor_present,
 372            gtk_frame_extents_supported
 373        );
 374
 375        let xkb = get_reply(
 376            || "Failed to initialize XKB extension",
 377            xcb_connection
 378                .xkb_use_extension(XKB_X11_MIN_MAJOR_XKB_VERSION, XKB_X11_MIN_MINOR_XKB_VERSION),
 379        )?;
 380        assert!(xkb.supported);
 381
 382        let events = xkb::EventType::STATE_NOTIFY
 383            | xkb::EventType::MAP_NOTIFY
 384            | xkb::EventType::NEW_KEYBOARD_NOTIFY;
 385        let map_notify_parts = xkb::MapPart::KEY_TYPES
 386            | xkb::MapPart::KEY_SYMS
 387            | xkb::MapPart::MODIFIER_MAP
 388            | xkb::MapPart::EXPLICIT_COMPONENTS
 389            | xkb::MapPart::KEY_ACTIONS
 390            | xkb::MapPart::KEY_BEHAVIORS
 391            | xkb::MapPart::VIRTUAL_MODS
 392            | xkb::MapPart::VIRTUAL_MOD_MAP;
 393        check_reply(
 394            || "Failed to select XKB events",
 395            xcb_connection.xkb_select_events(
 396                xkb::ID::USE_CORE_KBD.into(),
 397                0u8.into(),
 398                events,
 399                map_notify_parts,
 400                map_notify_parts,
 401                &xkb::SelectEventsAux::new(),
 402            ),
 403        )?;
 404
 405        let xkb_context = xkbc::Context::new(xkbc::CONTEXT_NO_FLAGS);
 406        let xkb_device_id = xkbc::x11::get_core_keyboard_device_id(&xcb_connection);
 407        let xkb_state = {
 408            let xkb_keymap = xkbc::x11::keymap_new_from_device(
 409                &xkb_context,
 410                &xcb_connection,
 411                xkb_device_id,
 412                xkbc::KEYMAP_COMPILE_NO_FLAGS,
 413            );
 414            xkbc::x11::state_new_from_device(&xkb_keymap, &xcb_connection, xkb_device_id)
 415        };
 416        let compose_state = get_xkb_compose_state(&xkb_context);
 417        let layout_idx = xkb_state.serialize_layout(STATE_LAYOUT_EFFECTIVE);
 418        let layout_name = xkb_state
 419            .get_keymap()
 420            .layout_get_name(layout_idx)
 421            .to_string();
 422        let keyboard_layout = LinuxKeyboardLayout::new(layout_name.into());
 423
 424        let resource_database = x11rb::resource_manager::new_from_default(&xcb_connection)
 425            .context("Failed to create resource database")?;
 426        let scale_factor = get_scale_factor(&xcb_connection, &resource_database, x_root_index);
 427        let cursor_handle = cursor::Handle::new(&xcb_connection, x_root_index, &resource_database)
 428            .context("Failed to initialize cursor theme handler")?
 429            .reply()
 430            .context("Failed to initialize cursor theme handler")?;
 431
 432        let clipboard = Clipboard::new().context("Failed to initialize clipboard")?;
 433
 434        let screen = &xcb_connection.setup().roots[x_root_index];
 435        let compositor_gpu = detect_compositor_gpu(&xcb_connection, screen);
 436
 437        let xcb_connection = Rc::new(xcb_connection);
 438
 439        let ximc = X11rbClient::init(Rc::clone(&xcb_connection), x_root_index, None).ok();
 440        let xim_handler = if ximc.is_some() {
 441            Some(XimHandler::new())
 442        } else {
 443            None
 444        };
 445
 446        // Safety: Safe if xcb::Connection always returns a valid fd
 447        let fd = unsafe { FdWrapper::new(Rc::clone(&xcb_connection)) };
 448
 449        handle
 450            .insert_source(
 451                Generic::new_with_error::<EventHandlerError>(
 452                    fd,
 453                    calloop::Interest::READ,
 454                    calloop::Mode::Level,
 455                ),
 456                {
 457                    let xcb_connection = xcb_connection.clone();
 458                    move |_readiness, _, client| {
 459                        client.process_x11_events(&xcb_connection)?;
 460                        Ok(calloop::PostAction::Continue)
 461                    }
 462                },
 463            )
 464            .map_err(|err| anyhow!("Failed to initialize X11 event source: {err:?}"))?;
 465
 466        handle
 467            .insert_source(XDPEventSource::new(&common.background_executor), {
 468                move |event, _, client| match event {
 469                    XDPEvent::WindowAppearance(appearance) => {
 470                        client.with_common(|common| common.appearance = appearance);
 471                        for window in client.0.borrow_mut().windows.values_mut() {
 472                            window.window.set_appearance(appearance);
 473                        }
 474                    }
 475                    XDPEvent::CursorTheme(_) | XDPEvent::CursorSize(_) => {
 476                        // noop, X11 manages this for us.
 477                    }
 478                }
 479            })
 480            .map_err(|err| anyhow!("Failed to initialize XDP event source: {err:?}"))?;
 481
 482        xcb_flush(&xcb_connection);
 483
 484        Ok(X11Client(Rc::new(RefCell::new(X11ClientState {
 485            modifiers: Modifiers::default(),
 486            capslock: Capslock::default(),
 487            last_modifiers_changed_event: Modifiers::default(),
 488            last_capslock_changed_event: Capslock::default(),
 489            event_loop: Some(event_loop),
 490            loop_handle: handle,
 491            common,
 492            last_click: Instant::now(),
 493            last_mouse_button: None,
 494            last_location: Point::new(px(0.0), px(0.0)),
 495            current_count: 0,
 496            gpu_context: Rc::new(RefCell::new(None)),
 497            compositor_gpu,
 498            scale_factor,
 499
 500            xkb_context,
 501            xcb_connection,
 502            xkb_device_id,
 503            client_side_decorations_supported,
 504            x_root_index,
 505            _resource_database: resource_database,
 506            atoms,
 507            windows: HashMap::default(),
 508            mouse_focused_window: None,
 509            keyboard_focused_window: None,
 510            xkb: xkb_state,
 511            keyboard_layout,
 512            ximc,
 513            xim_handler,
 514
 515            compose_state,
 516            pre_edit_text: None,
 517            pre_key_char_down: None,
 518            composing: false,
 519
 520            cursor_handle,
 521            cursor_styles: HashMap::default(),
 522            cursor_cache: HashMap::default(),
 523
 524            pointer_device_states,
 525
 526            clipboard,
 527            clipboard_item: None,
 528            xdnd_state: Xdnd::default(),
 529        }))))
 530    }
 531
 532    pub fn process_x11_events(
 533        &self,
 534        xcb_connection: &XCBConnection,
 535    ) -> Result<(), EventHandlerError> {
 536        loop {
 537            let mut events = Vec::new();
 538            let mut windows_to_refresh = HashSet::new();
 539
 540            let mut last_key_release = None;
 541
 542            // event handlers for new keyboard / remapping refresh the state without using event
 543            // details, this deduplicates them.
 544            let mut last_keymap_change_event: Option<Event> = None;
 545
 546            loop {
 547                match xcb_connection.poll_for_event() {
 548                    Ok(Some(event)) => {
 549                        match event {
 550                            Event::Expose(expose_event) => {
 551                                windows_to_refresh.insert(expose_event.window);
 552                            }
 553                            Event::KeyRelease(_) => {
 554                                if let Some(last_keymap_change_event) =
 555                                    last_keymap_change_event.take()
 556                                {
 557                                    if let Some(last_key_release) = last_key_release.take() {
 558                                        events.push(last_key_release);
 559                                    }
 560                                    events.push(last_keymap_change_event);
 561                                }
 562
 563                                last_key_release = Some(event);
 564                            }
 565                            Event::KeyPress(key_press) => {
 566                                if let Some(last_keymap_change_event) =
 567                                    last_keymap_change_event.take()
 568                                {
 569                                    if let Some(last_key_release) = last_key_release.take() {
 570                                        events.push(last_key_release);
 571                                    }
 572                                    events.push(last_keymap_change_event);
 573                                }
 574
 575                                if let Some(Event::KeyRelease(key_release)) =
 576                                    last_key_release.take()
 577                                {
 578                                    // We ignore that last KeyRelease if it's too close to this KeyPress,
 579                                    // suggesting that it's auto-generated by X11 as a key-repeat event.
 580                                    if key_release.detail != key_press.detail
 581                                        || key_press.time.saturating_sub(key_release.time) > 20
 582                                    {
 583                                        events.push(Event::KeyRelease(key_release));
 584                                    }
 585                                }
 586                                events.push(Event::KeyPress(key_press));
 587                            }
 588                            Event::XkbNewKeyboardNotify(_) | Event::XkbMapNotify(_) => {
 589                                if let Some(release_event) = last_key_release.take() {
 590                                    events.push(release_event);
 591                                }
 592                                last_keymap_change_event = Some(event);
 593                            }
 594                            _ => {
 595                                if let Some(release_event) = last_key_release.take() {
 596                                    events.push(release_event);
 597                                }
 598                                events.push(event);
 599                            }
 600                        }
 601                    }
 602                    Ok(None) => {
 603                        break;
 604                    }
 605                    Err(err) => {
 606                        let err = handle_connection_error(err);
 607                        log::warn!("error while polling for X11 events: {err:?}");
 608                        break;
 609                    }
 610                }
 611            }
 612
 613            if let Some(release_event) = last_key_release.take() {
 614                events.push(release_event);
 615            }
 616            if let Some(keymap_change_event) = last_keymap_change_event.take() {
 617                events.push(keymap_change_event);
 618            }
 619
 620            if events.is_empty() && windows_to_refresh.is_empty() {
 621                break;
 622            }
 623
 624            for window in windows_to_refresh.into_iter() {
 625                let mut state = self.0.borrow_mut();
 626                if let Some(window) = state.windows.get_mut(&window) {
 627                    window.expose_event_received = true;
 628                }
 629            }
 630
 631            for event in events.into_iter() {
 632                let mut state = self.0.borrow_mut();
 633                if !state.has_xim() {
 634                    drop(state);
 635                    self.handle_event(event);
 636                    continue;
 637                }
 638
 639                let Some((mut ximc, mut xim_handler)) = state.take_xim() else {
 640                    continue;
 641                };
 642                let xim_connected = xim_handler.connected;
 643                drop(state);
 644
 645                let xim_filtered = ximc.filter_event(&event, &mut xim_handler);
 646                let xim_callback_event = xim_handler.last_callback_event.take();
 647
 648                let mut state = self.0.borrow_mut();
 649                state.restore_xim(ximc, xim_handler);
 650                drop(state);
 651
 652                if let Some(event) = xim_callback_event {
 653                    self.handle_xim_callback_event(event);
 654                }
 655
 656                match xim_filtered {
 657                    Ok(handled) => {
 658                        if handled {
 659                            continue;
 660                        }
 661                        if xim_connected {
 662                            self.xim_handle_event(event);
 663                        } else {
 664                            self.handle_event(event);
 665                        }
 666                    }
 667                    Err(err) => {
 668                        // this might happen when xim server crashes on one of the events
 669                        // we do lose 1-2 keys when crash happens since there is no reliable way to get that info
 670                        // luckily, x11 sends us window not found error when xim server crashes upon further key press
 671                        // hence we fall back to handle_event
 672                        log::error!("XIMClientError: {}", err);
 673                        let mut state = self.0.borrow_mut();
 674                        state.take_xim();
 675                        drop(state);
 676                        self.handle_event(event);
 677                    }
 678                }
 679            }
 680        }
 681        Ok(())
 682    }
 683
 684    pub fn enable_ime(&self) {
 685        let mut state = self.0.borrow_mut();
 686        if !state.has_xim() {
 687            return;
 688        }
 689
 690        let Some((mut ximc, xim_handler)) = state.take_xim() else {
 691            return;
 692        };
 693        let mut ic_attributes = ximc
 694            .build_ic_attributes()
 695            .push(AttributeName::InputStyle, InputStyle::PREEDIT_CALLBACKS)
 696            .push(AttributeName::ClientWindow, xim_handler.window)
 697            .push(AttributeName::FocusWindow, xim_handler.window);
 698
 699        let window_id = state.keyboard_focused_window;
 700        drop(state);
 701        if let Some(window_id) = window_id {
 702            let Some(window) = self.get_window(window_id) else {
 703                log::error!("Failed to get window for IME positioning");
 704                let mut state = self.0.borrow_mut();
 705                state.ximc = Some(ximc);
 706                state.xim_handler = Some(xim_handler);
 707                return;
 708            };
 709            if let Some(scaled_area) = window.get_ime_area() {
 710                ic_attributes =
 711                    ic_attributes.nested_list(xim::AttributeName::PreeditAttributes, |b| {
 712                        b.push(
 713                            xim::AttributeName::SpotLocation,
 714                            xim::Point {
 715                                x: u32::from(scaled_area.origin.x + scaled_area.size.width) as i16,
 716                                y: u32::from(scaled_area.origin.y + scaled_area.size.height) as i16,
 717                            },
 718                        );
 719                    });
 720            }
 721        }
 722        ximc.create_ic(xim_handler.im_id, ic_attributes.build())
 723            .ok();
 724        let mut state = self.0.borrow_mut();
 725        state.restore_xim(ximc, xim_handler);
 726    }
 727
 728    pub fn reset_ime(&self) {
 729        let mut state = self.0.borrow_mut();
 730        state.composing = false;
 731        if let Some(mut ximc) = state.ximc.take() {
 732            if let Some(xim_handler) = state.xim_handler.as_ref() {
 733                ximc.reset_ic(xim_handler.im_id, xim_handler.ic_id).ok();
 734            } else {
 735                log::error!("bug: xim handler not set in reset_ime");
 736            }
 737            state.ximc = Some(ximc);
 738        }
 739    }
 740
 741    pub(crate) fn get_window(&self, win: xproto::Window) -> Option<X11WindowStatePtr> {
 742        let state = self.0.borrow();
 743        state
 744            .windows
 745            .get(&win)
 746            .filter(|window_reference| !window_reference.window.state.borrow().destroyed)
 747            .map(|window_reference| window_reference.window.clone())
 748    }
 749
 750    fn handle_event(&self, event: Event) -> Option<()> {
 751        match event {
 752            Event::UnmapNotify(event) => {
 753                let mut state = self.0.borrow_mut();
 754                if let Some(window_ref) = state.windows.get_mut(&event.window) {
 755                    window_ref.is_mapped = false;
 756                }
 757                state.update_refresh_loop(event.window);
 758            }
 759            Event::MapNotify(event) => {
 760                let mut state = self.0.borrow_mut();
 761                if let Some(window_ref) = state.windows.get_mut(&event.window) {
 762                    window_ref.is_mapped = true;
 763                }
 764                state.update_refresh_loop(event.window);
 765            }
 766            Event::VisibilityNotify(event) => {
 767                let mut state = self.0.borrow_mut();
 768                if let Some(window_ref) = state.windows.get_mut(&event.window) {
 769                    window_ref.last_visibility = event.state;
 770                }
 771                state.update_refresh_loop(event.window);
 772            }
 773            Event::ClientMessage(event) => {
 774                let window = self.get_window(event.window)?;
 775                let [atom, arg1, arg2, arg3, arg4] = event.data.as_data32();
 776                let mut state = self.0.borrow_mut();
 777
 778                if atom == state.atoms.WM_DELETE_WINDOW && window.should_close() {
 779                    // window "x" button clicked by user
 780                    // Rest of the close logic is handled in drop_window()
 781                    drop(state);
 782                    window.close();
 783                    state = self.0.borrow_mut();
 784                } else if atom == state.atoms._NET_WM_SYNC_REQUEST {
 785                    window.state.borrow_mut().last_sync_counter =
 786                        Some(x11rb::protocol::sync::Int64 {
 787                            lo: arg2,
 788                            hi: arg3 as i32,
 789                        })
 790                }
 791
 792                if event.type_ == state.atoms.XdndEnter {
 793                    state.xdnd_state.other_window = atom;
 794                    if (arg1 & 0x1) == 0x1 {
 795                        state.xdnd_state.drag_type = xdnd_get_supported_atom(
 796                            &state.xcb_connection,
 797                            &state.atoms,
 798                            state.xdnd_state.other_window,
 799                        );
 800                    } else {
 801                        if let Some(atom) = [arg2, arg3, arg4]
 802                            .into_iter()
 803                            .find(|atom| xdnd_is_atom_supported(*atom, &state.atoms))
 804                        {
 805                            state.xdnd_state.drag_type = atom;
 806                        }
 807                    }
 808                } else if event.type_ == state.atoms.XdndLeave {
 809                    let position = state.xdnd_state.position;
 810                    drop(state);
 811                    window
 812                        .handle_input(PlatformInput::FileDrop(FileDropEvent::Pending { position }));
 813                    window.handle_input(PlatformInput::FileDrop(FileDropEvent::Exited {}));
 814                    self.0.borrow_mut().xdnd_state = Xdnd::default();
 815                } else if event.type_ == state.atoms.XdndPosition {
 816                    if let Ok(pos) = get_reply(
 817                        || "Failed to query pointer position",
 818                        state.xcb_connection.query_pointer(event.window),
 819                    ) {
 820                        state.xdnd_state.position =
 821                            Point::new(px(pos.win_x as f32), px(pos.win_y as f32));
 822                    }
 823                    if !state.xdnd_state.retrieved {
 824                        check_reply(
 825                            || "Failed to convert selection for drag and drop",
 826                            state.xcb_connection.convert_selection(
 827                                event.window,
 828                                state.atoms.XdndSelection,
 829                                state.xdnd_state.drag_type,
 830                                state.atoms.XDND_DATA,
 831                                arg3,
 832                            ),
 833                        )
 834                        .log_err();
 835                    }
 836                    xdnd_send_status(
 837                        &state.xcb_connection,
 838                        &state.atoms,
 839                        event.window,
 840                        state.xdnd_state.other_window,
 841                        arg4,
 842                    );
 843                    let position = state.xdnd_state.position;
 844                    drop(state);
 845                    window
 846                        .handle_input(PlatformInput::FileDrop(FileDropEvent::Pending { position }));
 847                } else if event.type_ == state.atoms.XdndDrop {
 848                    xdnd_send_finished(
 849                        &state.xcb_connection,
 850                        &state.atoms,
 851                        event.window,
 852                        state.xdnd_state.other_window,
 853                    );
 854                    let position = state.xdnd_state.position;
 855                    drop(state);
 856                    window
 857                        .handle_input(PlatformInput::FileDrop(FileDropEvent::Submit { position }));
 858                    self.0.borrow_mut().xdnd_state = Xdnd::default();
 859                }
 860            }
 861            Event::SelectionNotify(event) => {
 862                let window = self.get_window(event.requestor)?;
 863                let state = self.0.borrow_mut();
 864                let reply = get_reply(
 865                    || "Failed to get XDND_DATA",
 866                    state.xcb_connection.get_property(
 867                        false,
 868                        event.requestor,
 869                        state.atoms.XDND_DATA,
 870                        AtomEnum::ANY,
 871                        0,
 872                        1024,
 873                    ),
 874                )
 875                .log_err();
 876                let Some(reply) = reply else {
 877                    return Some(());
 878                };
 879                if let Ok(file_list) = str::from_utf8(&reply.value) {
 880                    let paths: SmallVec<[_; 2]> = file_list
 881                        .lines()
 882                        .filter_map(|path| Url::parse(path).log_err())
 883                        .filter_map(|url| url.to_file_path().log_err())
 884                        .collect();
 885                    let input = PlatformInput::FileDrop(FileDropEvent::Entered {
 886                        position: state.xdnd_state.position,
 887                        paths: gpui::ExternalPaths(paths),
 888                    });
 889                    drop(state);
 890                    window.handle_input(input);
 891                    self.0.borrow_mut().xdnd_state.retrieved = true;
 892                }
 893            }
 894            Event::ConfigureNotify(event) => {
 895                let bounds = Bounds {
 896                    origin: Point {
 897                        x: event.x.into(),
 898                        y: event.y.into(),
 899                    },
 900                    size: Size {
 901                        width: event.width.into(),
 902                        height: event.height.into(),
 903                    },
 904                };
 905                let window = self.get_window(event.window)?;
 906                window
 907                    .set_bounds(bounds)
 908                    .context("X11: Failed to set window bounds")
 909                    .log_err();
 910            }
 911            Event::PropertyNotify(event) => {
 912                let window = self.get_window(event.window)?;
 913                window
 914                    .property_notify(event)
 915                    .context("X11: Failed to handle property notify")
 916                    .log_err();
 917            }
 918            Event::FocusIn(event) => {
 919                let window = self.get_window(event.event)?;
 920                window.set_active(true);
 921                let mut state = self.0.borrow_mut();
 922                state.keyboard_focused_window = Some(event.event);
 923                if let Some(handler) = state.xim_handler.as_mut() {
 924                    handler.window = event.event;
 925                }
 926                drop(state);
 927                self.enable_ime();
 928            }
 929            Event::FocusOut(event) => {
 930                let window = self.get_window(event.event)?;
 931                window.set_active(false);
 932                let mut state = self.0.borrow_mut();
 933                // Set last scroll values to `None` so that a large delta isn't created if scrolling is done outside the window (the valuator is global)
 934                reset_all_pointer_device_scroll_positions(&mut state.pointer_device_states);
 935                state.keyboard_focused_window = None;
 936                if let Some(compose_state) = state.compose_state.as_mut() {
 937                    compose_state.reset();
 938                }
 939                state.pre_edit_text.take();
 940                drop(state);
 941                self.reset_ime();
 942                window.handle_ime_delete();
 943            }
 944            Event::XkbNewKeyboardNotify(_) | Event::XkbMapNotify(_) => {
 945                let mut state = self.0.borrow_mut();
 946                let xkb_state = {
 947                    let xkb_keymap = xkbc::x11::keymap_new_from_device(
 948                        &state.xkb_context,
 949                        &state.xcb_connection,
 950                        state.xkb_device_id,
 951                        xkbc::KEYMAP_COMPILE_NO_FLAGS,
 952                    );
 953                    xkbc::x11::state_new_from_device(
 954                        &xkb_keymap,
 955                        &state.xcb_connection,
 956                        state.xkb_device_id,
 957                    )
 958                };
 959                state.xkb = xkb_state;
 960                drop(state);
 961                self.handle_keyboard_layout_change();
 962            }
 963            Event::XkbStateNotify(event) => {
 964                let mut state = self.0.borrow_mut();
 965                let old_layout = state.xkb.serialize_layout(STATE_LAYOUT_EFFECTIVE);
 966                let new_layout = u32::from(event.group);
 967                state.xkb.update_mask(
 968                    event.base_mods.into(),
 969                    event.latched_mods.into(),
 970                    event.locked_mods.into(),
 971                    event.base_group as u32,
 972                    event.latched_group as u32,
 973                    event.locked_group.into(),
 974                );
 975                let modifiers = modifiers_from_xkb(&state.xkb);
 976                let capslock = capslock_from_xkb(&state.xkb);
 977                if state.last_modifiers_changed_event == modifiers
 978                    && state.last_capslock_changed_event == capslock
 979                {
 980                    drop(state);
 981                } else {
 982                    let focused_window_id = state.keyboard_focused_window?;
 983                    state.modifiers = modifiers;
 984                    state.last_modifiers_changed_event = modifiers;
 985                    state.capslock = capslock;
 986                    state.last_capslock_changed_event = capslock;
 987                    drop(state);
 988
 989                    let focused_window = self.get_window(focused_window_id)?;
 990                    focused_window.handle_input(PlatformInput::ModifiersChanged(
 991                        ModifiersChangedEvent {
 992                            modifiers,
 993                            capslock,
 994                        },
 995                    ));
 996                }
 997
 998                if new_layout != old_layout {
 999                    self.handle_keyboard_layout_change();
1000                }
1001            }
1002            Event::KeyPress(event) => {
1003                let window = self.get_window(event.event)?;
1004                let mut state = self.0.borrow_mut();
1005
1006                let modifiers = modifiers_from_state(event.state);
1007                state.modifiers = modifiers;
1008                state.pre_key_char_down.take();
1009
1010                // Macros containing modifiers might result in
1011                // the modifiers missing from the event.
1012                // We therefore update the mask from the global state.
1013                update_xkb_mask_from_event_state(&mut state.xkb, event.state);
1014
1015                let keystroke = {
1016                    let code = event.detail.into();
1017                    let mut keystroke = keystroke_from_xkb(&state.xkb, modifiers, code);
1018                    let keysym = state.xkb.key_get_one_sym(code);
1019
1020                    if keysym.is_modifier_key() {
1021                        return Some(());
1022                    }
1023
1024                    // should be called after key_get_one_sym
1025                    state.xkb.update_key(code, xkbc::KeyDirection::Down);
1026
1027                    if let Some(mut compose_state) = state.compose_state.take() {
1028                        compose_state.feed(keysym);
1029                        match compose_state.status() {
1030                            xkbc::Status::Composed => {
1031                                state.pre_edit_text.take();
1032                                keystroke.key_char = compose_state.utf8();
1033                                if let Some(keysym) = compose_state.keysym() {
1034                                    keystroke.key = xkbc::keysym_get_name(keysym);
1035                                }
1036                            }
1037                            xkbc::Status::Composing => {
1038                                keystroke.key_char = None;
1039                                state.pre_edit_text = compose_state
1040                                    .utf8()
1041                                    .or(keystroke_underlying_dead_key(keysym));
1042                                let pre_edit =
1043                                    state.pre_edit_text.clone().unwrap_or(String::default());
1044                                drop(state);
1045                                window.handle_ime_preedit(pre_edit);
1046                                state = self.0.borrow_mut();
1047                            }
1048                            xkbc::Status::Cancelled => {
1049                                let pre_edit = state.pre_edit_text.take();
1050                                drop(state);
1051                                if let Some(pre_edit) = pre_edit {
1052                                    window.handle_ime_commit(pre_edit);
1053                                }
1054                                if let Some(current_key) = keystroke_underlying_dead_key(keysym) {
1055                                    window.handle_ime_preedit(current_key);
1056                                }
1057                                state = self.0.borrow_mut();
1058                                compose_state.feed(keysym);
1059                            }
1060                            _ => {}
1061                        }
1062                        state.compose_state = Some(compose_state);
1063                    }
1064                    keystroke
1065                };
1066                drop(state);
1067                window.handle_input(PlatformInput::KeyDown(gpui::KeyDownEvent {
1068                    keystroke,
1069                    is_held: false,
1070                    prefer_character_input: false,
1071                }));
1072            }
1073            Event::KeyRelease(event) => {
1074                let window = self.get_window(event.event)?;
1075                let mut state = self.0.borrow_mut();
1076
1077                let modifiers = modifiers_from_state(event.state);
1078                state.modifiers = modifiers;
1079
1080                // Macros containing modifiers might result in
1081                // the modifiers missing from the event.
1082                // We therefore update the mask from the global state.
1083                update_xkb_mask_from_event_state(&mut state.xkb, event.state);
1084
1085                let keystroke = {
1086                    let code = event.detail.into();
1087                    let keystroke = keystroke_from_xkb(&state.xkb, modifiers, code);
1088                    let keysym = state.xkb.key_get_one_sym(code);
1089
1090                    if keysym.is_modifier_key() {
1091                        return Some(());
1092                    }
1093
1094                    // should be called after key_get_one_sym
1095                    state.xkb.update_key(code, xkbc::KeyDirection::Up);
1096
1097                    keystroke
1098                };
1099                drop(state);
1100                window.handle_input(PlatformInput::KeyUp(gpui::KeyUpEvent { keystroke }));
1101            }
1102            Event::XinputButtonPress(event) => {
1103                let window = self.get_window(event.event)?;
1104                let mut state = self.0.borrow_mut();
1105
1106                let modifiers = modifiers_from_xinput_info(event.mods);
1107                state.modifiers = modifiers;
1108
1109                let position = point(
1110                    px(event.event_x as f32 / u16::MAX as f32 / state.scale_factor),
1111                    px(event.event_y as f32 / u16::MAX as f32 / state.scale_factor),
1112                );
1113
1114                if state.composing && state.ximc.is_some() {
1115                    drop(state);
1116                    self.reset_ime();
1117                    window.handle_ime_unmark();
1118                    state = self.0.borrow_mut();
1119                } else if let Some(text) = state.pre_edit_text.take() {
1120                    if let Some(compose_state) = state.compose_state.as_mut() {
1121                        compose_state.reset();
1122                    }
1123                    drop(state);
1124                    window.handle_ime_commit(text);
1125                    state = self.0.borrow_mut();
1126                }
1127                match button_or_scroll_from_event_detail(event.detail) {
1128                    Some(ButtonOrScroll::Button(button)) => {
1129                        let click_elapsed = state.last_click.elapsed();
1130                        if click_elapsed < DOUBLE_CLICK_INTERVAL
1131                            && state
1132                                .last_mouse_button
1133                                .is_some_and(|prev_button| prev_button == button)
1134                            && is_within_click_distance(state.last_location, position)
1135                        {
1136                            state.current_count += 1;
1137                        } else {
1138                            state.current_count = 1;
1139                        }
1140
1141                        state.last_click = Instant::now();
1142                        state.last_mouse_button = Some(button);
1143                        state.last_location = position;
1144                        let current_count = state.current_count;
1145
1146                        drop(state);
1147                        window.handle_input(PlatformInput::MouseDown(gpui::MouseDownEvent {
1148                            button,
1149                            position,
1150                            modifiers,
1151                            click_count: current_count,
1152                            first_mouse: false,
1153                        }));
1154                    }
1155                    Some(ButtonOrScroll::Scroll(direction)) => {
1156                        drop(state);
1157                        // Emulated scroll button presses are sent simultaneously with smooth scrolling XinputMotion events.
1158                        // Since handling those events does the scrolling, they are skipped here.
1159                        if !event
1160                            .flags
1161                            .contains(xinput::PointerEventFlags::POINTER_EMULATED)
1162                        {
1163                            let scroll_delta = match direction {
1164                                ScrollDirection::Up => Point::new(0.0, SCROLL_LINES),
1165                                ScrollDirection::Down => Point::new(0.0, -SCROLL_LINES),
1166                                ScrollDirection::Left => Point::new(SCROLL_LINES, 0.0),
1167                                ScrollDirection::Right => Point::new(-SCROLL_LINES, 0.0),
1168                            };
1169                            window.handle_input(PlatformInput::ScrollWheel(
1170                                make_scroll_wheel_event(position, scroll_delta, modifiers),
1171                            ));
1172                        }
1173                    }
1174                    None => {
1175                        log::error!("Unknown x11 button: {}", event.detail);
1176                    }
1177                }
1178            }
1179            Event::XinputButtonRelease(event) => {
1180                let window = self.get_window(event.event)?;
1181                let mut state = self.0.borrow_mut();
1182                let modifiers = modifiers_from_xinput_info(event.mods);
1183                state.modifiers = modifiers;
1184
1185                let position = point(
1186                    px(event.event_x as f32 / u16::MAX as f32 / state.scale_factor),
1187                    px(event.event_y as f32 / u16::MAX as f32 / state.scale_factor),
1188                );
1189                match button_or_scroll_from_event_detail(event.detail) {
1190                    Some(ButtonOrScroll::Button(button)) => {
1191                        let click_count = state.current_count;
1192                        drop(state);
1193                        window.handle_input(PlatformInput::MouseUp(gpui::MouseUpEvent {
1194                            button,
1195                            position,
1196                            modifiers,
1197                            click_count,
1198                        }));
1199                    }
1200                    Some(ButtonOrScroll::Scroll(_)) => {}
1201                    None => {}
1202                }
1203            }
1204            Event::XinputMotion(event) => {
1205                let window = self.get_window(event.event)?;
1206                let mut state = self.0.borrow_mut();
1207                if window.is_blocked() {
1208                    // We want to set the cursor to the default arrow
1209                    // when the window is blocked
1210                    let style = CursorStyle::Arrow;
1211
1212                    let current_style = state
1213                        .cursor_styles
1214                        .get(&window.x_window)
1215                        .unwrap_or(&CursorStyle::Arrow);
1216                    if *current_style != style
1217                        && let Some(cursor) = state.get_cursor_icon(style)
1218                    {
1219                        state.cursor_styles.insert(window.x_window, style);
1220                        check_reply(
1221                            || "Failed to set cursor style",
1222                            state.xcb_connection.change_window_attributes(
1223                                window.x_window,
1224                                &ChangeWindowAttributesAux {
1225                                    cursor: Some(cursor),
1226                                    ..Default::default()
1227                                },
1228                            ),
1229                        )
1230                        .log_err();
1231                        state.xcb_connection.flush().log_err();
1232                    };
1233                }
1234                let pressed_button = pressed_button_from_mask(event.button_mask[0]);
1235                let position = point(
1236                    px(event.event_x as f32 / u16::MAX as f32 / state.scale_factor),
1237                    px(event.event_y as f32 / u16::MAX as f32 / state.scale_factor),
1238                );
1239                let modifiers = modifiers_from_xinput_info(event.mods);
1240                state.modifiers = modifiers;
1241                drop(state);
1242
1243                if event.valuator_mask[0] & 3 != 0 {
1244                    window.handle_input(PlatformInput::MouseMove(gpui::MouseMoveEvent {
1245                        position,
1246                        pressed_button,
1247                        modifiers,
1248                    }));
1249                }
1250
1251                state = self.0.borrow_mut();
1252                if let Some(pointer) = state.pointer_device_states.get_mut(&event.sourceid) {
1253                    let scroll_delta = get_scroll_delta_and_update_state(pointer, &event);
1254                    drop(state);
1255                    if let Some(scroll_delta) = scroll_delta {
1256                        window.handle_input(PlatformInput::ScrollWheel(make_scroll_wheel_event(
1257                            position,
1258                            scroll_delta,
1259                            modifiers,
1260                        )));
1261                    }
1262                }
1263            }
1264            Event::XinputEnter(event) if event.mode == xinput::NotifyMode::NORMAL => {
1265                let window = self.get_window(event.event)?;
1266                window.set_hovered(true);
1267                let mut state = self.0.borrow_mut();
1268                state.mouse_focused_window = Some(event.event);
1269            }
1270            Event::XinputLeave(event) if event.mode == xinput::NotifyMode::NORMAL => {
1271                let mut state = self.0.borrow_mut();
1272
1273                // Set last scroll values to `None` so that a large delta isn't created if scrolling is done outside the window (the valuator is global)
1274                reset_all_pointer_device_scroll_positions(&mut state.pointer_device_states);
1275                state.mouse_focused_window = None;
1276                let pressed_button = pressed_button_from_mask(event.buttons[0]);
1277                let position = point(
1278                    px(event.event_x as f32 / u16::MAX as f32 / state.scale_factor),
1279                    px(event.event_y as f32 / u16::MAX as f32 / state.scale_factor),
1280                );
1281                let modifiers = modifiers_from_xinput_info(event.mods);
1282                state.modifiers = modifiers;
1283                drop(state);
1284
1285                let window = self.get_window(event.event)?;
1286                window.handle_input(PlatformInput::MouseExited(gpui::MouseExitEvent {
1287                    pressed_button,
1288                    position,
1289                    modifiers,
1290                }));
1291                window.set_hovered(false);
1292            }
1293            Event::XinputHierarchy(event) => {
1294                let mut state = self.0.borrow_mut();
1295                // Temporarily use `state.pointer_device_states` to only store pointers that still have valid scroll values.
1296                // Any change to a device invalidates its scroll values.
1297                for info in event.infos {
1298                    if is_pointer_device(info.type_) {
1299                        state.pointer_device_states.remove(&info.deviceid);
1300                    }
1301                }
1302                if let Some(pointer_device_states) = current_pointer_device_states(
1303                    &state.xcb_connection,
1304                    &state.pointer_device_states,
1305                ) {
1306                    state.pointer_device_states = pointer_device_states;
1307                }
1308            }
1309            Event::XinputDeviceChanged(event) => {
1310                let mut state = self.0.borrow_mut();
1311                if let Some(pointer) = state.pointer_device_states.get_mut(&event.sourceid) {
1312                    reset_pointer_device_scroll_positions(pointer);
1313                }
1314            }
1315            _ => {}
1316        };
1317
1318        Some(())
1319    }
1320
1321    fn handle_xim_callback_event(&self, event: XimCallbackEvent) {
1322        match event {
1323            XimCallbackEvent::XimXEvent(event) => {
1324                self.handle_event(event);
1325            }
1326            XimCallbackEvent::XimCommitEvent(window, text) => {
1327                self.xim_handle_commit(window, text);
1328            }
1329            XimCallbackEvent::XimPreeditEvent(window, text) => {
1330                self.xim_handle_preedit(window, text);
1331            }
1332        };
1333    }
1334
1335    fn xim_handle_event(&self, event: Event) -> Option<()> {
1336        match event {
1337            Event::KeyPress(event) | Event::KeyRelease(event) => {
1338                let mut state = self.0.borrow_mut();
1339                state.pre_key_char_down = Some(keystroke_from_xkb(
1340                    &state.xkb,
1341                    state.modifiers,
1342                    event.detail.into(),
1343                ));
1344                let (mut ximc, mut xim_handler) = state.take_xim()?;
1345                drop(state);
1346                xim_handler.window = event.event;
1347                ximc.forward_event(
1348                    xim_handler.im_id,
1349                    xim_handler.ic_id,
1350                    xim::ForwardEventFlag::empty(),
1351                    &event,
1352                )
1353                .context("X11: Failed to forward XIM event")
1354                .log_err();
1355                let mut state = self.0.borrow_mut();
1356                state.restore_xim(ximc, xim_handler);
1357                drop(state);
1358            }
1359            event => {
1360                self.handle_event(event);
1361            }
1362        }
1363        Some(())
1364    }
1365
1366    fn xim_handle_commit(&self, window: xproto::Window, text: String) -> Option<()> {
1367        let Some(window) = self.get_window(window) else {
1368            log::error!("bug: Failed to get window for XIM commit");
1369            return None;
1370        };
1371        let mut state = self.0.borrow_mut();
1372        state.composing = false;
1373        drop(state);
1374        window.handle_ime_commit(text);
1375        Some(())
1376    }
1377
1378    fn xim_handle_preedit(&self, window: xproto::Window, text: String) -> Option<()> {
1379        let Some(window) = self.get_window(window) else {
1380            log::error!("bug: Failed to get window for XIM preedit");
1381            return None;
1382        };
1383
1384        let mut state = self.0.borrow_mut();
1385        let (mut ximc, xim_handler) = state.take_xim()?;
1386        state.composing = !text.is_empty();
1387        drop(state);
1388        window.handle_ime_preedit(text);
1389
1390        if let Some(scaled_area) = window.get_ime_area() {
1391            let ic_attributes = ximc
1392                .build_ic_attributes()
1393                .push(
1394                    xim::AttributeName::InputStyle,
1395                    xim::InputStyle::PREEDIT_CALLBACKS,
1396                )
1397                .push(xim::AttributeName::ClientWindow, xim_handler.window)
1398                .push(xim::AttributeName::FocusWindow, xim_handler.window)
1399                .nested_list(xim::AttributeName::PreeditAttributes, |b| {
1400                    b.push(
1401                        xim::AttributeName::SpotLocation,
1402                        xim::Point {
1403                            x: u32::from(scaled_area.origin.x + scaled_area.size.width) as i16,
1404                            y: u32::from(scaled_area.origin.y + scaled_area.size.height) as i16,
1405                        },
1406                    );
1407                })
1408                .build();
1409            ximc.set_ic_values(xim_handler.im_id, xim_handler.ic_id, ic_attributes)
1410                .ok();
1411        }
1412        let mut state = self.0.borrow_mut();
1413        state.restore_xim(ximc, xim_handler);
1414        drop(state);
1415        Some(())
1416    }
1417
1418    fn handle_keyboard_layout_change(&self) {
1419        let mut state = self.0.borrow_mut();
1420        let layout_idx = state.xkb.serialize_layout(STATE_LAYOUT_EFFECTIVE);
1421        let keymap = state.xkb.get_keymap();
1422        let layout_name = keymap.layout_get_name(layout_idx);
1423        if layout_name != state.keyboard_layout.name() {
1424            state.keyboard_layout = LinuxKeyboardLayout::new(layout_name.to_string().into());
1425            if let Some(mut callback) = state.common.callbacks.keyboard_layout_change.take() {
1426                drop(state);
1427                callback();
1428                state = self.0.borrow_mut();
1429                state.common.callbacks.keyboard_layout_change = Some(callback);
1430            }
1431        }
1432    }
1433}
1434
1435impl LinuxClient for X11Client {
1436    fn compositor_name(&self) -> &'static str {
1437        "X11"
1438    }
1439
1440    fn with_common<R>(&self, f: impl FnOnce(&mut LinuxCommon) -> R) -> R {
1441        f(&mut self.0.borrow_mut().common)
1442    }
1443
1444    fn keyboard_layout(&self) -> Box<dyn PlatformKeyboardLayout> {
1445        let state = self.0.borrow();
1446        Box::new(state.keyboard_layout.clone())
1447    }
1448
1449    fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
1450        let state = self.0.borrow();
1451        let setup = state.xcb_connection.setup();
1452        setup
1453            .roots
1454            .iter()
1455            .enumerate()
1456            .filter_map(|(root_id, _)| {
1457                Some(Rc::new(
1458                    X11Display::new(&state.xcb_connection, state.scale_factor, root_id).ok()?,
1459                ) as Rc<dyn PlatformDisplay>)
1460            })
1461            .collect()
1462    }
1463
1464    fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
1465        let state = self.0.borrow();
1466        X11Display::new(
1467            &state.xcb_connection,
1468            state.scale_factor,
1469            state.x_root_index,
1470        )
1471        .log_err()
1472        .map(|display| Rc::new(display) as Rc<dyn PlatformDisplay>)
1473    }
1474
1475    fn display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>> {
1476        let state = self.0.borrow();
1477
1478        Some(Rc::new(
1479            X11Display::new(
1480                &state.xcb_connection,
1481                state.scale_factor,
1482                u32::from(id) as usize,
1483            )
1484            .ok()?,
1485        ))
1486    }
1487
1488    #[cfg(feature = "screen-capture")]
1489    fn is_screen_capture_supported(&self) -> bool {
1490        true
1491    }
1492
1493    #[cfg(feature = "screen-capture")]
1494    fn screen_capture_sources(
1495        &self,
1496    ) -> futures::channel::oneshot::Receiver<anyhow::Result<Vec<Rc<dyn gpui::ScreenCaptureSource>>>>
1497    {
1498        gpui::scap_screen_capture::scap_screen_sources(&self.0.borrow().common.foreground_executor)
1499    }
1500
1501    fn open_window(
1502        &self,
1503        handle: AnyWindowHandle,
1504        params: WindowParams,
1505    ) -> anyhow::Result<Box<dyn PlatformWindow>> {
1506        let mut state = self.0.borrow_mut();
1507        let parent_window = state
1508            .keyboard_focused_window
1509            .and_then(|focused_window| state.windows.get(&focused_window))
1510            .map(|w| w.window.clone());
1511        let x_window = state
1512            .xcb_connection
1513            .generate_id()
1514            .context("X11: Failed to generate window ID")?;
1515
1516        let xcb_connection = state.xcb_connection.clone();
1517        let client_side_decorations_supported = state.client_side_decorations_supported;
1518        let x_root_index = state.x_root_index;
1519        let atoms = state.atoms;
1520        let scale_factor = state.scale_factor;
1521        let appearance = state.common.appearance;
1522        let compositor_gpu = state.compositor_gpu.take();
1523        let window = X11Window::new(
1524            handle,
1525            X11ClientStatePtr(Rc::downgrade(&self.0)),
1526            state.common.foreground_executor.clone(),
1527            state.gpu_context.clone(),
1528            compositor_gpu,
1529            params,
1530            &xcb_connection,
1531            client_side_decorations_supported,
1532            x_root_index,
1533            x_window,
1534            &atoms,
1535            scale_factor,
1536            appearance,
1537            parent_window,
1538        )?;
1539        check_reply(
1540            || "Failed to set XdndAware property",
1541            state.xcb_connection.change_property32(
1542                xproto::PropMode::REPLACE,
1543                x_window,
1544                state.atoms.XdndAware,
1545                state.atoms.XA_ATOM,
1546                &[5],
1547            ),
1548        )
1549        .log_err();
1550        xcb_flush(&state.xcb_connection);
1551
1552        let window_ref = WindowRef {
1553            window: window.0.clone(),
1554            refresh_state: None,
1555            expose_event_received: false,
1556            last_visibility: Visibility::UNOBSCURED,
1557            is_mapped: false,
1558        };
1559
1560        state.windows.insert(x_window, window_ref);
1561        Ok(Box::new(window))
1562    }
1563
1564    fn set_cursor_style(&self, style: CursorStyle) {
1565        let mut state = self.0.borrow_mut();
1566        let Some(focused_window) = state.mouse_focused_window else {
1567            return;
1568        };
1569        let current_style = state
1570            .cursor_styles
1571            .get(&focused_window)
1572            .unwrap_or(&CursorStyle::Arrow);
1573
1574        let window = state
1575            .mouse_focused_window
1576            .and_then(|w| state.windows.get(&w));
1577
1578        let should_change = *current_style != style
1579            && (window.is_none() || window.is_some_and(|w| !w.is_blocked()));
1580
1581        if !should_change {
1582            return;
1583        }
1584
1585        let Some(cursor) = state.get_cursor_icon(style) else {
1586            return;
1587        };
1588
1589        state.cursor_styles.insert(focused_window, style);
1590        check_reply(
1591            || "Failed to set cursor style",
1592            state.xcb_connection.change_window_attributes(
1593                focused_window,
1594                &ChangeWindowAttributesAux {
1595                    cursor: Some(cursor),
1596                    ..Default::default()
1597                },
1598            ),
1599        )
1600        .log_err();
1601        state.xcb_connection.flush().log_err();
1602    }
1603
1604    fn open_uri(&self, uri: &str) {
1605        #[cfg(any(feature = "wayland", feature = "x11"))]
1606        open_uri_internal(
1607            self.with_common(|c| c.background_executor.clone()),
1608            uri,
1609            None,
1610        );
1611    }
1612
1613    fn reveal_path(&self, path: PathBuf) {
1614        #[cfg(any(feature = "x11", feature = "wayland"))]
1615        reveal_path_internal(
1616            self.with_common(|c| c.background_executor.clone()),
1617            path,
1618            None,
1619        );
1620    }
1621
1622    fn write_to_primary(&self, item: gpui::ClipboardItem) {
1623        let state = self.0.borrow_mut();
1624        state
1625            .clipboard
1626            .set_text(
1627                std::borrow::Cow::Owned(item.text().unwrap_or_default()),
1628                clipboard::ClipboardKind::Primary,
1629                clipboard::WaitConfig::None,
1630            )
1631            .context("X11 Failed to write to clipboard (primary)")
1632            .log_with_level(log::Level::Debug);
1633    }
1634
1635    fn write_to_clipboard(&self, item: gpui::ClipboardItem) {
1636        let mut state = self.0.borrow_mut();
1637        state
1638            .clipboard
1639            .set_text(
1640                std::borrow::Cow::Owned(item.text().unwrap_or_default()),
1641                clipboard::ClipboardKind::Clipboard,
1642                clipboard::WaitConfig::None,
1643            )
1644            .context("X11: Failed to write to clipboard (clipboard)")
1645            .log_with_level(log::Level::Debug);
1646        state.clipboard_item.replace(item);
1647    }
1648
1649    fn read_from_primary(&self) -> Option<gpui::ClipboardItem> {
1650        let state = self.0.borrow_mut();
1651        state
1652            .clipboard
1653            .get_any(clipboard::ClipboardKind::Primary)
1654            .context("X11: Failed to read from clipboard (primary)")
1655            .log_with_level(log::Level::Debug)
1656    }
1657
1658    fn read_from_clipboard(&self) -> Option<gpui::ClipboardItem> {
1659        let state = self.0.borrow_mut();
1660        // if the last copy was from this app, return our cached item
1661        // which has metadata attached.
1662        if state
1663            .clipboard
1664            .is_owner(clipboard::ClipboardKind::Clipboard)
1665        {
1666            return state.clipboard_item.clone();
1667        }
1668        state
1669            .clipboard
1670            .get_any(clipboard::ClipboardKind::Clipboard)
1671            .context("X11: Failed to read from clipboard (clipboard)")
1672            .log_with_level(log::Level::Debug)
1673    }
1674
1675    fn run(&self) {
1676        let Some(mut event_loop) = self
1677            .0
1678            .borrow_mut()
1679            .event_loop
1680            .take()
1681            .context("X11Client::run called but it's already running")
1682            .log_err()
1683        else {
1684            return;
1685        };
1686
1687        event_loop.run(None, &mut self.clone(), |_| {}).log_err();
1688    }
1689
1690    fn active_window(&self) -> Option<AnyWindowHandle> {
1691        let state = self.0.borrow();
1692        state.keyboard_focused_window.and_then(|focused_window| {
1693            state
1694                .windows
1695                .get(&focused_window)
1696                .map(|window| window.handle())
1697        })
1698    }
1699
1700    fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
1701        let state = self.0.borrow();
1702        let root = state.xcb_connection.setup().roots[state.x_root_index].root;
1703
1704        let reply = state
1705            .xcb_connection
1706            .get_property(
1707                false,
1708                root,
1709                state.atoms._NET_CLIENT_LIST_STACKING,
1710                xproto::AtomEnum::WINDOW,
1711                0,
1712                u32::MAX,
1713            )
1714            .ok()?
1715            .reply()
1716            .ok()?;
1717
1718        let window_ids = reply
1719            .value
1720            .chunks_exact(4)
1721            .filter_map(|chunk| chunk.try_into().ok().map(u32::from_ne_bytes))
1722            .collect::<Vec<xproto::Window>>();
1723
1724        let mut handles = Vec::new();
1725
1726        // We need to reverse, since _NET_CLIENT_LIST_STACKING has
1727        // a back-to-front order.
1728        // See: https://specifications.freedesktop.org/wm-spec/1.3/ar01s03.html
1729        for window_ref in window_ids
1730            .iter()
1731            .rev()
1732            .filter_map(|&win| state.windows.get(&win))
1733        {
1734            if !window_ref.window.state.borrow().destroyed {
1735                handles.push(window_ref.handle());
1736            }
1737        }
1738
1739        Some(handles)
1740    }
1741
1742    fn window_identifier(&self) -> impl Future<Output = Option<WindowIdentifier>> + Send + 'static {
1743        let state = self.0.borrow();
1744        state
1745            .keyboard_focused_window
1746            .and_then(|focused_window| state.windows.get(&focused_window))
1747            .map(|window| window.window.x_window as u64)
1748            .map(|x_window| std::future::ready(Some(WindowIdentifier::from_xid(x_window))))
1749            .unwrap_or(std::future::ready(None))
1750    }
1751}
1752
1753impl X11ClientState {
1754    fn has_xim(&self) -> bool {
1755        self.ximc.is_some() && self.xim_handler.is_some()
1756    }
1757
1758    fn take_xim(&mut self) -> Option<(X11rbClient<Rc<XCBConnection>>, XimHandler)> {
1759        let ximc = self
1760            .ximc
1761            .take()
1762            .ok_or(anyhow!("bug: XIM connection not set"))
1763            .log_err()?;
1764        if let Some(xim_handler) = self.xim_handler.take() {
1765            Some((ximc, xim_handler))
1766        } else {
1767            self.ximc = Some(ximc);
1768            log::error!("bug: XIM handler not set");
1769            None
1770        }
1771    }
1772
1773    fn restore_xim(&mut self, ximc: X11rbClient<Rc<XCBConnection>>, xim_handler: XimHandler) {
1774        self.ximc = Some(ximc);
1775        self.xim_handler = Some(xim_handler);
1776    }
1777
1778    fn update_refresh_loop(&mut self, x_window: xproto::Window) {
1779        let Some(window_ref) = self.windows.get_mut(&x_window) else {
1780            return;
1781        };
1782        let is_visible = window_ref.is_mapped
1783            && !matches!(window_ref.last_visibility, Visibility::FULLY_OBSCURED);
1784        match (is_visible, window_ref.refresh_state.take()) {
1785            (false, refresh_state @ Some(RefreshState::Hidden { .. }))
1786            | (false, refresh_state @ None)
1787            | (true, refresh_state @ Some(RefreshState::PeriodicRefresh { .. })) => {
1788                window_ref.refresh_state = refresh_state;
1789            }
1790            (
1791                false,
1792                Some(RefreshState::PeriodicRefresh {
1793                    refresh_rate,
1794                    event_loop_token,
1795                }),
1796            ) => {
1797                self.loop_handle.remove(event_loop_token);
1798                window_ref.refresh_state = Some(RefreshState::Hidden { refresh_rate });
1799            }
1800            (true, Some(RefreshState::Hidden { refresh_rate })) => {
1801                let event_loop_token = self.start_refresh_loop(x_window, refresh_rate);
1802                let Some(window_ref) = self.windows.get_mut(&x_window) else {
1803                    return;
1804                };
1805                window_ref.refresh_state = Some(RefreshState::PeriodicRefresh {
1806                    refresh_rate,
1807                    event_loop_token,
1808                });
1809            }
1810            (true, None) => {
1811                let Some(screen_resources) = get_reply(
1812                    || "Failed to get screen resources",
1813                    self.xcb_connection
1814                        .randr_get_screen_resources_current(x_window),
1815                )
1816                .log_err() else {
1817                    return;
1818                };
1819
1820                // Ideally this would be re-queried when the window changes screens, but there
1821                // doesn't seem to be an efficient / straightforward way to do this. Should also be
1822                // updated when screen configurations change.
1823                let mode_info = screen_resources.crtcs.iter().find_map(|crtc| {
1824                    let crtc_info = self
1825                        .xcb_connection
1826                        .randr_get_crtc_info(*crtc, x11rb::CURRENT_TIME)
1827                        .ok()?
1828                        .reply()
1829                        .ok()?;
1830
1831                    screen_resources
1832                        .modes
1833                        .iter()
1834                        .find(|m| m.id == crtc_info.mode)
1835                });
1836                let refresh_rate = match mode_info {
1837                    Some(mode_info) => mode_refresh_rate(mode_info),
1838                    None => {
1839                        log::error!(
1840                            "Failed to get screen mode info from xrandr, \
1841                            defaulting to 60hz refresh rate."
1842                        );
1843                        Duration::from_micros(1_000_000 / 60)
1844                    }
1845                };
1846
1847                let event_loop_token = self.start_refresh_loop(x_window, refresh_rate);
1848                let Some(window_ref) = self.windows.get_mut(&x_window) else {
1849                    return;
1850                };
1851                window_ref.refresh_state = Some(RefreshState::PeriodicRefresh {
1852                    refresh_rate,
1853                    event_loop_token,
1854                });
1855            }
1856        }
1857    }
1858
1859    #[must_use]
1860    fn start_refresh_loop(
1861        &self,
1862        x_window: xproto::Window,
1863        refresh_rate: Duration,
1864    ) -> RegistrationToken {
1865        self.loop_handle
1866            .insert_source(calloop::timer::Timer::immediate(), {
1867                move |mut instant, (), client| {
1868                    let xcb_connection = {
1869                        let mut state = client.0.borrow_mut();
1870                        let xcb_connection = state.xcb_connection.clone();
1871                        if let Some(window) = state.windows.get_mut(&x_window) {
1872                            let expose_event_received = window.expose_event_received;
1873                            window.expose_event_received = false;
1874                            let window = window.window.clone();
1875                            drop(state);
1876                            window.refresh(RequestFrameOptions {
1877                                require_presentation: expose_event_received,
1878                                force_render: false,
1879                            });
1880                        }
1881                        xcb_connection
1882                    };
1883                    client.process_x11_events(&xcb_connection).log_err();
1884
1885                    // Take into account that some frames have been skipped
1886                    let now = Instant::now();
1887                    while instant < now {
1888                        instant += refresh_rate;
1889                    }
1890                    calloop::timer::TimeoutAction::ToInstant(instant)
1891                }
1892            })
1893            .expect("Failed to initialize window refresh timer")
1894    }
1895
1896    fn get_cursor_icon(&mut self, style: CursorStyle) -> Option<xproto::Cursor> {
1897        if let Some(cursor) = self.cursor_cache.get(&style) {
1898            return *cursor;
1899        }
1900
1901        let result;
1902        match style {
1903            CursorStyle::None => match create_invisible_cursor(&self.xcb_connection) {
1904                Ok(loaded_cursor) => result = Ok(loaded_cursor),
1905                Err(err) => result = Err(err.context("X11: error while creating invisible cursor")),
1906            },
1907            _ => 'outer: {
1908                let mut errors = String::new();
1909                let cursor_icon_names = cursor_style_to_icon_names(style);
1910                for cursor_icon_name in cursor_icon_names {
1911                    match self
1912                        .cursor_handle
1913                        .load_cursor(&self.xcb_connection, cursor_icon_name)
1914                    {
1915                        Ok(loaded_cursor) => {
1916                            if loaded_cursor != x11rb::NONE {
1917                                result = Ok(loaded_cursor);
1918                                break 'outer;
1919                            }
1920                        }
1921                        Err(err) => {
1922                            errors.push_str(&err.to_string());
1923                            errors.push('\n');
1924                        }
1925                    }
1926                }
1927                if errors.is_empty() {
1928                    result = Err(anyhow!(
1929                        "errors while loading cursor icons {:?}:\n{}",
1930                        cursor_icon_names,
1931                        errors
1932                    ));
1933                } else {
1934                    result = Err(anyhow!("did not find cursor icons {:?}", cursor_icon_names));
1935                }
1936            }
1937        };
1938
1939        let cursor = match result {
1940            Ok(cursor) => Some(cursor),
1941            Err(err) => {
1942                match self
1943                    .cursor_handle
1944                    .load_cursor(&self.xcb_connection, DEFAULT_CURSOR_ICON_NAME)
1945                {
1946                    Ok(default) => {
1947                        log_cursor_icon_warning(err.context(format!(
1948                            "X11: error loading cursor icon, falling back on default icon '{}'",
1949                            DEFAULT_CURSOR_ICON_NAME
1950                        )));
1951                        Some(default)
1952                    }
1953                    Err(default_err) => {
1954                        log_cursor_icon_warning(err.context(default_err).context(format!(
1955                            "X11: error loading default cursor fallback '{}'",
1956                            DEFAULT_CURSOR_ICON_NAME
1957                        )));
1958                        None
1959                    }
1960                }
1961            }
1962        };
1963
1964        self.cursor_cache.insert(style, cursor);
1965        cursor
1966    }
1967}
1968
1969// Adapted from:
1970// https://docs.rs/winit/0.29.11/src/winit/platform_impl/linux/x11/monitor.rs.html#103-111
1971pub fn mode_refresh_rate(mode: &randr::ModeInfo) -> Duration {
1972    if mode.dot_clock == 0 || mode.htotal == 0 || mode.vtotal == 0 {
1973        return Duration::from_millis(16);
1974    }
1975
1976    let millihertz = mode.dot_clock as u64 * 1_000 / (mode.htotal as u64 * mode.vtotal as u64);
1977    let micros = 1_000_000_000 / millihertz;
1978    log::info!("Refreshing every {}ms", micros / 1_000);
1979    Duration::from_micros(micros)
1980}
1981
1982fn fp3232_to_f32(value: xinput::Fp3232) -> f32 {
1983    value.integral as f32 + value.frac as f32 / u32::MAX as f32
1984}
1985
1986fn detect_compositor_gpu(
1987    xcb_connection: &XCBConnection,
1988    screen: &xproto::Screen,
1989) -> Option<CompositorGpuHint> {
1990    use std::os::fd::AsRawFd;
1991    use std::os::unix::fs::MetadataExt;
1992
1993    xcb_connection
1994        .extension_information(dri3::X11_EXTENSION_NAME)
1995        .ok()??;
1996
1997    let reply = dri3::open(xcb_connection, screen.root, 0)
1998        .ok()?
1999        .reply()
2000        .ok()?;
2001    let fd = reply.device_fd;
2002
2003    let path = format!("/proc/self/fd/{}", fd.as_raw_fd());
2004    let metadata = std::fs::metadata(&path).ok()?;
2005
2006    crate::linux::compositor_gpu_hint_from_dev_t(metadata.rdev())
2007}
2008
2009fn check_compositor_present(xcb_connection: &XCBConnection, root: xproto::Window) -> bool {
2010    // Method 1: Check for _NET_WM_CM_S{root}
2011    let atom_name = format!("_NET_WM_CM_S{}", root);
2012    let atom1 = get_reply(
2013        || format!("Failed to intern {atom_name}"),
2014        xcb_connection.intern_atom(false, atom_name.as_bytes()),
2015    );
2016    let method1 = match atom1.log_with_level(Level::Debug) {
2017        Some(reply) if reply.atom != x11rb::NONE => {
2018            let atom = reply.atom;
2019            get_reply(
2020                || format!("Failed to get {atom_name} owner"),
2021                xcb_connection.get_selection_owner(atom),
2022            )
2023            .map(|reply| reply.owner != 0)
2024            .log_with_level(Level::Debug)
2025            .unwrap_or(false)
2026        }
2027        _ => false,
2028    };
2029
2030    // Method 2: Check for _NET_WM_CM_OWNER
2031    let atom_name = "_NET_WM_CM_OWNER";
2032    let atom2 = get_reply(
2033        || format!("Failed to intern {atom_name}"),
2034        xcb_connection.intern_atom(false, atom_name.as_bytes()),
2035    );
2036    let method2 = match atom2.log_with_level(Level::Debug) {
2037        Some(reply) if reply.atom != x11rb::NONE => {
2038            let atom = reply.atom;
2039            get_reply(
2040                || format!("Failed to get {atom_name}"),
2041                xcb_connection.get_property(false, root, atom, xproto::AtomEnum::WINDOW, 0, 1),
2042            )
2043            .map(|reply| reply.value_len > 0)
2044            .unwrap_or(false)
2045        }
2046        _ => return false,
2047    };
2048
2049    // Method 3: Check for _NET_SUPPORTING_WM_CHECK
2050    let atom_name = "_NET_SUPPORTING_WM_CHECK";
2051    let atom3 = get_reply(
2052        || format!("Failed to intern {atom_name}"),
2053        xcb_connection.intern_atom(false, atom_name.as_bytes()),
2054    );
2055    let method3 = match atom3.log_with_level(Level::Debug) {
2056        Some(reply) if reply.atom != x11rb::NONE => {
2057            let atom = reply.atom;
2058            get_reply(
2059                || format!("Failed to get {atom_name}"),
2060                xcb_connection.get_property(false, root, atom, xproto::AtomEnum::WINDOW, 0, 1),
2061            )
2062            .map(|reply| reply.value_len > 0)
2063            .unwrap_or(false)
2064        }
2065        _ => return false,
2066    };
2067
2068    log::debug!(
2069        "Compositor detection: _NET_WM_CM_S?={}, _NET_WM_CM_OWNER={}, _NET_SUPPORTING_WM_CHECK={}",
2070        method1,
2071        method2,
2072        method3
2073    );
2074
2075    method1 || method2 || method3
2076}
2077
2078fn check_gtk_frame_extents_supported(
2079    xcb_connection: &XCBConnection,
2080    atoms: &XcbAtoms,
2081    root: xproto::Window,
2082) -> bool {
2083    let Some(supported_atoms) = get_reply(
2084        || "Failed to get _NET_SUPPORTED",
2085        xcb_connection.get_property(
2086            false,
2087            root,
2088            atoms._NET_SUPPORTED,
2089            xproto::AtomEnum::ATOM,
2090            0,
2091            1024,
2092        ),
2093    )
2094    .log_with_level(Level::Debug) else {
2095        return false;
2096    };
2097
2098    let supported_atom_ids: Vec<u32> = supported_atoms
2099        .value
2100        .chunks_exact(4)
2101        .filter_map(|chunk| chunk.try_into().ok().map(u32::from_ne_bytes))
2102        .collect();
2103
2104    supported_atom_ids.contains(&atoms._GTK_FRAME_EXTENTS)
2105}
2106
2107fn xdnd_is_atom_supported(atom: u32, atoms: &XcbAtoms) -> bool {
2108    atom == atoms.TEXT
2109        || atom == atoms.STRING
2110        || atom == atoms.UTF8_STRING
2111        || atom == atoms.TEXT_PLAIN
2112        || atom == atoms.TEXT_PLAIN_UTF8
2113        || atom == atoms.TextUriList
2114}
2115
2116fn xdnd_get_supported_atom(
2117    xcb_connection: &XCBConnection,
2118    supported_atoms: &XcbAtoms,
2119    target: xproto::Window,
2120) -> u32 {
2121    if let Some(reply) = get_reply(
2122        || "Failed to get XDnD supported atoms",
2123        xcb_connection.get_property(
2124            false,
2125            target,
2126            supported_atoms.XdndTypeList,
2127            AtomEnum::ANY,
2128            0,
2129            1024,
2130        ),
2131    )
2132    .log_with_level(Level::Warn)
2133        && let Some(atoms) = reply.value32()
2134    {
2135        for atom in atoms {
2136            if xdnd_is_atom_supported(atom, supported_atoms) {
2137                return atom;
2138            }
2139        }
2140    }
2141    0
2142}
2143
2144fn xdnd_send_finished(
2145    xcb_connection: &XCBConnection,
2146    atoms: &XcbAtoms,
2147    source: xproto::Window,
2148    target: xproto::Window,
2149) {
2150    let message = ClientMessageEvent {
2151        format: 32,
2152        window: target,
2153        type_: atoms.XdndFinished,
2154        data: ClientMessageData::from([source, 1, atoms.XdndActionCopy, 0, 0]),
2155        sequence: 0,
2156        response_type: xproto::CLIENT_MESSAGE_EVENT,
2157    };
2158    check_reply(
2159        || "Failed to send XDnD finished event",
2160        xcb_connection.send_event(false, target, EventMask::default(), message),
2161    )
2162    .log_err();
2163    xcb_connection.flush().log_err();
2164}
2165
2166fn xdnd_send_status(
2167    xcb_connection: &XCBConnection,
2168    atoms: &XcbAtoms,
2169    source: xproto::Window,
2170    target: xproto::Window,
2171    action: u32,
2172) {
2173    let message = ClientMessageEvent {
2174        format: 32,
2175        window: target,
2176        type_: atoms.XdndStatus,
2177        data: ClientMessageData::from([source, 1, 0, 0, action]),
2178        sequence: 0,
2179        response_type: xproto::CLIENT_MESSAGE_EVENT,
2180    };
2181    check_reply(
2182        || "Failed to send XDnD status event",
2183        xcb_connection.send_event(false, target, EventMask::default(), message),
2184    )
2185    .log_err();
2186    xcb_connection.flush().log_err();
2187}
2188
2189/// Recomputes `pointer_device_states` by querying all pointer devices.
2190/// When a device is present in `scroll_values_to_preserve`, its value for `ScrollAxisState.scroll_value` is used.
2191fn current_pointer_device_states(
2192    xcb_connection: &XCBConnection,
2193    scroll_values_to_preserve: &BTreeMap<xinput::DeviceId, PointerDeviceState>,
2194) -> Option<BTreeMap<xinput::DeviceId, PointerDeviceState>> {
2195    let devices_query_result = get_reply(
2196        || "Failed to query XInput devices",
2197        xcb_connection.xinput_xi_query_device(XINPUT_ALL_DEVICES),
2198    )
2199    .log_err()?;
2200
2201    let mut pointer_device_states = BTreeMap::new();
2202    pointer_device_states.extend(
2203        devices_query_result
2204            .infos
2205            .iter()
2206            .filter(|info| is_pointer_device(info.type_))
2207            .filter_map(|info| {
2208                let scroll_data = info
2209                    .classes
2210                    .iter()
2211                    .filter_map(|class| class.data.as_scroll())
2212                    .copied()
2213                    .rev()
2214                    .collect::<Vec<_>>();
2215                let old_state = scroll_values_to_preserve.get(&info.deviceid);
2216                let old_horizontal = old_state.map(|state| &state.horizontal);
2217                let old_vertical = old_state.map(|state| &state.vertical);
2218                let horizontal = scroll_data
2219                    .iter()
2220                    .find(|data| data.scroll_type == xinput::ScrollType::HORIZONTAL)
2221                    .map(|data| scroll_data_to_axis_state(data, old_horizontal));
2222                let vertical = scroll_data
2223                    .iter()
2224                    .find(|data| data.scroll_type == xinput::ScrollType::VERTICAL)
2225                    .map(|data| scroll_data_to_axis_state(data, old_vertical));
2226                if horizontal.is_none() && vertical.is_none() {
2227                    None
2228                } else {
2229                    Some((
2230                        info.deviceid,
2231                        PointerDeviceState {
2232                            horizontal: horizontal.unwrap_or_else(Default::default),
2233                            vertical: vertical.unwrap_or_else(Default::default),
2234                        },
2235                    ))
2236                }
2237            }),
2238    );
2239    if pointer_device_states.is_empty() {
2240        log::error!("Found no xinput mouse pointers.");
2241    }
2242    Some(pointer_device_states)
2243}
2244
2245/// Returns true if the device is a pointer device. Does not include pointer device groups.
2246fn is_pointer_device(type_: xinput::DeviceType) -> bool {
2247    type_ == xinput::DeviceType::SLAVE_POINTER
2248}
2249
2250fn scroll_data_to_axis_state(
2251    data: &xinput::DeviceClassDataScroll,
2252    old_axis_state_with_valid_scroll_value: Option<&ScrollAxisState>,
2253) -> ScrollAxisState {
2254    ScrollAxisState {
2255        valuator_number: Some(data.number),
2256        multiplier: SCROLL_LINES / fp3232_to_f32(data.increment),
2257        scroll_value: old_axis_state_with_valid_scroll_value.and_then(|state| state.scroll_value),
2258    }
2259}
2260
2261fn reset_all_pointer_device_scroll_positions(
2262    pointer_device_states: &mut BTreeMap<xinput::DeviceId, PointerDeviceState>,
2263) {
2264    pointer_device_states
2265        .iter_mut()
2266        .for_each(|(_, device_state)| reset_pointer_device_scroll_positions(device_state));
2267}
2268
2269fn reset_pointer_device_scroll_positions(pointer: &mut PointerDeviceState) {
2270    pointer.horizontal.scroll_value = None;
2271    pointer.vertical.scroll_value = None;
2272}
2273
2274/// Returns the scroll delta for a smooth scrolling motion event, or `None` if no scroll data is present.
2275fn get_scroll_delta_and_update_state(
2276    pointer: &mut PointerDeviceState,
2277    event: &xinput::MotionEvent,
2278) -> Option<Point<f32>> {
2279    let delta_x = get_axis_scroll_delta_and_update_state(event, &mut pointer.horizontal);
2280    let delta_y = get_axis_scroll_delta_and_update_state(event, &mut pointer.vertical);
2281    if delta_x.is_some() || delta_y.is_some() {
2282        Some(Point::new(delta_x.unwrap_or(0.0), delta_y.unwrap_or(0.0)))
2283    } else {
2284        None
2285    }
2286}
2287
2288fn get_axis_scroll_delta_and_update_state(
2289    event: &xinput::MotionEvent,
2290    axis: &mut ScrollAxisState,
2291) -> Option<f32> {
2292    let axis_index = get_valuator_axis_index(&event.valuator_mask, axis.valuator_number?)?;
2293    if let Some(axis_value) = event.axisvalues.get(axis_index) {
2294        let new_scroll = fp3232_to_f32(*axis_value);
2295        let delta_scroll = axis
2296            .scroll_value
2297            .map(|old_scroll| (old_scroll - new_scroll) * axis.multiplier);
2298        axis.scroll_value = Some(new_scroll);
2299        delta_scroll
2300    } else {
2301        log::error!("Encountered invalid XInput valuator_mask, scrolling may not work properly.");
2302        None
2303    }
2304}
2305
2306fn make_scroll_wheel_event(
2307    position: Point<Pixels>,
2308    scroll_delta: Point<f32>,
2309    modifiers: Modifiers,
2310) -> gpui::ScrollWheelEvent {
2311    // When shift is held down, vertical scrolling turns into horizontal scrolling.
2312    let delta = if modifiers.shift {
2313        Point {
2314            x: scroll_delta.y,
2315            y: 0.0,
2316        }
2317    } else {
2318        scroll_delta
2319    };
2320    gpui::ScrollWheelEvent {
2321        position,
2322        delta: ScrollDelta::Lines(delta),
2323        modifiers,
2324        touch_phase: TouchPhase::default(),
2325    }
2326}
2327
2328fn create_invisible_cursor(
2329    connection: &XCBConnection,
2330) -> anyhow::Result<crate::linux::x11::client::xproto::Cursor> {
2331    let empty_pixmap = connection.generate_id()?;
2332    let root = connection.setup().roots[0].root;
2333    connection.create_pixmap(1, empty_pixmap, root, 1, 1)?;
2334
2335    let cursor = connection.generate_id()?;
2336    connection.create_cursor(cursor, empty_pixmap, empty_pixmap, 0, 0, 0, 0, 0, 0, 0, 0)?;
2337
2338    connection.free_pixmap(empty_pixmap)?;
2339
2340    xcb_flush(connection);
2341    Ok(cursor)
2342}
2343
2344enum DpiMode {
2345    Randr,
2346    Scale(f32),
2347    NotSet,
2348}
2349
2350fn get_scale_factor(
2351    connection: &XCBConnection,
2352    resource_database: &Database,
2353    screen_index: usize,
2354) -> f32 {
2355    let env_dpi = std::env::var(GPUI_X11_SCALE_FACTOR_ENV)
2356        .ok()
2357        .map(|var| {
2358            if var.to_lowercase() == "randr" {
2359                DpiMode::Randr
2360            } else if let Ok(scale) = var.parse::<f32>() {
2361                if valid_scale_factor(scale) {
2362                    DpiMode::Scale(scale)
2363                } else {
2364                    panic!(
2365                        "`{}` must be a positive normal number or `randr`. Got `{}`",
2366                        GPUI_X11_SCALE_FACTOR_ENV, var
2367                    );
2368                }
2369            } else if var.is_empty() {
2370                DpiMode::NotSet
2371            } else {
2372                panic!(
2373                    "`{}` must be a positive number or `randr`. Got `{}`",
2374                    GPUI_X11_SCALE_FACTOR_ENV, var
2375                );
2376            }
2377        })
2378        .unwrap_or(DpiMode::NotSet);
2379
2380    match env_dpi {
2381        DpiMode::Scale(scale) => {
2382            log::info!(
2383                "Using scale factor from {}: {}",
2384                GPUI_X11_SCALE_FACTOR_ENV,
2385                scale
2386            );
2387            return scale;
2388        }
2389        DpiMode::Randr => {
2390            if let Some(scale) = get_randr_scale_factor(connection, screen_index) {
2391                log::info!(
2392                    "Using RandR scale factor from {}=randr: {}",
2393                    GPUI_X11_SCALE_FACTOR_ENV,
2394                    scale
2395                );
2396                return scale;
2397            }
2398            log::warn!("Failed to calculate RandR scale factor, falling back to default");
2399            return 1.0;
2400        }
2401        DpiMode::NotSet => {}
2402    }
2403
2404    // TODO: Use scale factor from XSettings here
2405
2406    if let Some(dpi) = resource_database
2407        .get_value::<f32>("Xft.dpi", "Xft.dpi")
2408        .ok()
2409        .flatten()
2410    {
2411        let scale = dpi / 96.0; // base dpi
2412        log::info!("Using scale factor from Xft.dpi: {}", scale);
2413        return scale;
2414    }
2415
2416    if let Some(scale) = get_randr_scale_factor(connection, screen_index) {
2417        log::info!("Using RandR scale factor: {}", scale);
2418        return scale;
2419    }
2420
2421    log::info!("Using default scale factor: 1.0");
2422    1.0
2423}
2424
2425fn get_randr_scale_factor(connection: &XCBConnection, screen_index: usize) -> Option<f32> {
2426    let root = connection.setup().roots.get(screen_index)?.root;
2427
2428    let version_cookie = connection.randr_query_version(1, 6).ok()?;
2429    let version_reply = version_cookie.reply().ok()?;
2430    if version_reply.major_version < 1
2431        || (version_reply.major_version == 1 && version_reply.minor_version < 5)
2432    {
2433        return legacy_get_randr_scale_factor(connection, root); // for randr <1.5
2434    }
2435
2436    let monitors_cookie = connection.randr_get_monitors(root, true).ok()?; // true for active only
2437    let monitors_reply = monitors_cookie.reply().ok()?;
2438
2439    let mut fallback_scale: Option<f32> = None;
2440    for monitor in monitors_reply.monitors {
2441        if monitor.width_in_millimeters == 0 || monitor.height_in_millimeters == 0 {
2442            continue;
2443        }
2444        let scale_factor = get_dpi_factor(
2445            (monitor.width as u32, monitor.height as u32),
2446            (
2447                monitor.width_in_millimeters as u64,
2448                monitor.height_in_millimeters as u64,
2449            ),
2450        );
2451        if monitor.primary {
2452            return Some(scale_factor);
2453        } else if fallback_scale.is_none() {
2454            fallback_scale = Some(scale_factor);
2455        }
2456    }
2457
2458    fallback_scale
2459}
2460
2461fn legacy_get_randr_scale_factor(connection: &XCBConnection, root: u32) -> Option<f32> {
2462    let primary_cookie = connection.randr_get_output_primary(root).ok()?;
2463    let primary_reply = primary_cookie.reply().ok()?;
2464    let primary_output = primary_reply.output;
2465
2466    let primary_output_cookie = connection
2467        .randr_get_output_info(primary_output, x11rb::CURRENT_TIME)
2468        .ok()?;
2469    let primary_output_info = primary_output_cookie.reply().ok()?;
2470
2471    // try primary
2472    if primary_output_info.connection == randr::Connection::CONNECTED
2473        && primary_output_info.mm_width > 0
2474        && primary_output_info.mm_height > 0
2475        && primary_output_info.crtc != 0
2476    {
2477        let crtc_cookie = connection
2478            .randr_get_crtc_info(primary_output_info.crtc, x11rb::CURRENT_TIME)
2479            .ok()?;
2480        let crtc_info = crtc_cookie.reply().ok()?;
2481
2482        if crtc_info.width > 0 && crtc_info.height > 0 {
2483            let scale_factor = get_dpi_factor(
2484                (crtc_info.width as u32, crtc_info.height as u32),
2485                (
2486                    primary_output_info.mm_width as u64,
2487                    primary_output_info.mm_height as u64,
2488                ),
2489            );
2490            return Some(scale_factor);
2491        }
2492    }
2493
2494    // fallback: full scan
2495    let resources_cookie = connection.randr_get_screen_resources_current(root).ok()?;
2496    let screen_resources = resources_cookie.reply().ok()?;
2497
2498    let mut crtc_cookies = Vec::with_capacity(screen_resources.crtcs.len());
2499    for &crtc in &screen_resources.crtcs {
2500        if let Ok(cookie) = connection.randr_get_crtc_info(crtc, x11rb::CURRENT_TIME) {
2501            crtc_cookies.push((crtc, cookie));
2502        }
2503    }
2504
2505    let mut crtc_infos: HashMap<randr::Crtc, randr::GetCrtcInfoReply> = HashMap::default();
2506    let mut valid_outputs: HashSet<randr::Output> = HashSet::new();
2507    for (crtc, cookie) in crtc_cookies {
2508        if let Ok(reply) = cookie.reply()
2509            && reply.width > 0
2510            && reply.height > 0
2511            && !reply.outputs.is_empty()
2512        {
2513            crtc_infos.insert(crtc, reply.clone());
2514            valid_outputs.extend(&reply.outputs);
2515        }
2516    }
2517
2518    if valid_outputs.is_empty() {
2519        return None;
2520    }
2521
2522    let mut output_cookies = Vec::with_capacity(valid_outputs.len());
2523    for &output in &valid_outputs {
2524        if let Ok(cookie) = connection.randr_get_output_info(output, x11rb::CURRENT_TIME) {
2525            output_cookies.push((output, cookie));
2526        }
2527    }
2528    let mut output_infos: HashMap<randr::Output, randr::GetOutputInfoReply> = HashMap::default();
2529    for (output, cookie) in output_cookies {
2530        if let Ok(reply) = cookie.reply() {
2531            output_infos.insert(output, reply);
2532        }
2533    }
2534
2535    let mut fallback_scale: Option<f32> = None;
2536    for crtc_info in crtc_infos.values() {
2537        for &output in &crtc_info.outputs {
2538            if let Some(output_info) = output_infos.get(&output) {
2539                if output_info.connection != randr::Connection::CONNECTED {
2540                    continue;
2541                }
2542
2543                if output_info.mm_width == 0 || output_info.mm_height == 0 {
2544                    continue;
2545                }
2546
2547                let scale_factor = get_dpi_factor(
2548                    (crtc_info.width as u32, crtc_info.height as u32),
2549                    (output_info.mm_width as u64, output_info.mm_height as u64),
2550                );
2551
2552                if output != primary_output && fallback_scale.is_none() {
2553                    fallback_scale = Some(scale_factor);
2554                }
2555            }
2556        }
2557    }
2558
2559    fallback_scale
2560}
2561
2562fn get_dpi_factor((width_px, height_px): (u32, u32), (width_mm, height_mm): (u64, u64)) -> f32 {
2563    let ppmm = ((width_px as f64 * height_px as f64) / (width_mm as f64 * height_mm as f64)).sqrt(); // pixels per mm
2564
2565    const MM_PER_INCH: f64 = 25.4;
2566    const BASE_DPI: f64 = 96.0;
2567    const QUANTIZE_STEP: f64 = 12.0; // e.g. 1.25 = 15/12, 1.5 = 18/12, 1.75 = 21/12, 2.0 = 24/12
2568    const MIN_SCALE: f64 = 1.0;
2569    const MAX_SCALE: f64 = 20.0;
2570
2571    let dpi_factor =
2572        ((ppmm * (QUANTIZE_STEP * MM_PER_INCH / BASE_DPI)).round() / QUANTIZE_STEP).max(MIN_SCALE);
2573
2574    let validated_factor = if dpi_factor <= MAX_SCALE {
2575        dpi_factor
2576    } else {
2577        MIN_SCALE
2578    };
2579
2580    if valid_scale_factor(validated_factor as f32) {
2581        validated_factor as f32
2582    } else {
2583        log::warn!(
2584            "Calculated DPI factor {} is invalid, using 1.0",
2585            validated_factor
2586        );
2587        1.0
2588    }
2589}
2590
2591#[inline]
2592fn valid_scale_factor(scale_factor: f32) -> bool {
2593    scale_factor.is_sign_positive() && scale_factor.is_normal()
2594}
2595
2596#[inline]
2597fn update_xkb_mask_from_event_state(xkb: &mut xkbc::State, event_state: xproto::KeyButMask) {
2598    let depressed_mods = event_state.remove((ModMask::LOCK | ModMask::M2).bits());
2599    let latched_mods = xkb.serialize_mods(xkbc::STATE_MODS_LATCHED);
2600    let locked_mods = xkb.serialize_mods(xkbc::STATE_MODS_LOCKED);
2601    let locked_layout = xkb.serialize_layout(xkbc::STATE_LAYOUT_LOCKED);
2602    xkb.update_mask(
2603        depressed_mods.into(),
2604        latched_mods,
2605        locked_mods,
2606        0,
2607        0,
2608        locked_layout,
2609    );
2610}