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