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| url.to_file_path().log_err())
 912                        .collect();
 913                    let input = PlatformInput::FileDrop(FileDropEvent::Entered {
 914                        position: state.xdnd_state.position,
 915                        paths: gpui::ExternalPaths(paths),
 916                    });
 917                    drop(state);
 918                    window.handle_input(input);
 919                    self.0.borrow_mut().xdnd_state.retrieved = true;
 920                }
 921            }
 922            Event::ConfigureNotify(event) => {
 923                let bounds = Bounds {
 924                    origin: Point {
 925                        x: event.x.into(),
 926                        y: event.y.into(),
 927                    },
 928                    size: Size {
 929                        width: event.width.into(),
 930                        height: event.height.into(),
 931                    },
 932                };
 933                let window = self.get_window(event.window)?;
 934                window
 935                    .set_bounds(bounds)
 936                    .context("X11: Failed to set window bounds")
 937                    .log_err();
 938            }
 939            Event::PropertyNotify(event) => {
 940                let window = self.get_window(event.window)?;
 941                window
 942                    .property_notify(event)
 943                    .context("X11: Failed to handle property notify")
 944                    .log_err();
 945            }
 946            Event::FocusIn(event) => {
 947                let window = self.get_window(event.event)?;
 948                window.set_active(true);
 949                let mut state = self.0.borrow_mut();
 950                state.keyboard_focused_window = Some(event.event);
 951                if let Some(handler) = state.xim_handler.as_mut() {
 952                    handler.window = event.event;
 953                }
 954                drop(state);
 955                self.enable_ime();
 956            }
 957            Event::FocusOut(event) => {
 958                let window = self.get_window(event.event)?;
 959                window.set_active(false);
 960                let mut state = self.0.borrow_mut();
 961                // 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)
 962                reset_all_pointer_device_scroll_positions(&mut state.pointer_device_states);
 963                state.keyboard_focused_window = None;
 964                if let Some(compose_state) = state.compose_state.as_mut() {
 965                    compose_state.reset();
 966                }
 967                state.pre_edit_text.take();
 968                drop(state);
 969                self.reset_ime();
 970                window.handle_ime_delete();
 971            }
 972            Event::XkbNewKeyboardNotify(_) | Event::XkbMapNotify(_) => {
 973                let mut state = self.0.borrow_mut();
 974                let xkb_state = {
 975                    let xkb_keymap = xkbc::x11::keymap_new_from_device(
 976                        &state.xkb_context,
 977                        &state.xcb_connection,
 978                        state.xkb_device_id,
 979                        xkbc::KEYMAP_COMPILE_NO_FLAGS,
 980                    );
 981                    xkbc::x11::state_new_from_device(
 982                        &xkb_keymap,
 983                        &state.xcb_connection,
 984                        state.xkb_device_id,
 985                    )
 986                };
 987                state.xkb = xkb_state;
 988                drop(state);
 989                self.handle_keyboard_layout_change();
 990            }
 991            Event::XkbStateNotify(event) => {
 992                let mut state = self.0.borrow_mut();
 993                let old_layout = state.xkb.serialize_layout(STATE_LAYOUT_EFFECTIVE);
 994                let new_layout = u32::from(event.group);
 995                state.xkb.update_mask(
 996                    event.base_mods.into(),
 997                    event.latched_mods.into(),
 998                    event.locked_mods.into(),
 999                    event.base_group as u32,
1000                    event.latched_group as u32,
1001                    event.locked_group.into(),
1002                );
1003                let modifiers = modifiers_from_xkb(&state.xkb);
1004                let capslock = capslock_from_xkb(&state.xkb);
1005                if state.last_modifiers_changed_event == modifiers
1006                    && state.last_capslock_changed_event == capslock
1007                {
1008                    drop(state);
1009                } else {
1010                    let focused_window_id = state.keyboard_focused_window?;
1011                    state.modifiers = modifiers;
1012                    state.last_modifiers_changed_event = modifiers;
1013                    state.capslock = capslock;
1014                    state.last_capslock_changed_event = capslock;
1015                    drop(state);
1016
1017                    let focused_window = self.get_window(focused_window_id)?;
1018                    focused_window.handle_input(PlatformInput::ModifiersChanged(
1019                        ModifiersChangedEvent {
1020                            modifiers,
1021                            capslock,
1022                        },
1023                    ));
1024                }
1025
1026                if new_layout != old_layout {
1027                    self.handle_keyboard_layout_change();
1028                }
1029            }
1030            Event::KeyPress(event) => {
1031                let window = self.get_window(event.event)?;
1032                let mut state = self.0.borrow_mut();
1033
1034                let modifiers = modifiers_from_state(event.state);
1035                state.modifiers = modifiers;
1036                state.pre_key_char_down.take();
1037                let key_event_state = xkb_state_for_key_event(&state.xkb, event.state);
1038
1039                let keystroke = {
1040                    let code = event.detail.into();
1041                    let mut keystroke = keystroke_from_xkb(&key_event_state, modifiers, code);
1042                    let keysym = key_event_state.key_get_one_sym(code);
1043
1044                    if keysym.is_modifier_key() {
1045                        return Some(());
1046                    }
1047
1048                    if let Some(mut compose_state) = state.compose_state.take() {
1049                        compose_state.feed(keysym);
1050                        match compose_state.status() {
1051                            xkbc::Status::Composed => {
1052                                state.pre_edit_text.take();
1053                                keystroke.key_char = compose_state.utf8();
1054                                if let Some(keysym) = compose_state.keysym() {
1055                                    keystroke.key = xkbc::keysym_get_name(keysym);
1056                                }
1057                            }
1058                            xkbc::Status::Composing => {
1059                                keystroke.key_char = None;
1060                                state.pre_edit_text = compose_state
1061                                    .utf8()
1062                                    .or(keystroke_underlying_dead_key(keysym));
1063                                let pre_edit =
1064                                    state.pre_edit_text.clone().unwrap_or(String::default());
1065                                drop(state);
1066                                window.handle_ime_preedit(pre_edit);
1067                                state = self.0.borrow_mut();
1068                            }
1069                            xkbc::Status::Cancelled => {
1070                                let pre_edit = state.pre_edit_text.take();
1071                                drop(state);
1072                                if let Some(pre_edit) = pre_edit {
1073                                    window.handle_ime_commit(pre_edit);
1074                                }
1075                                if let Some(current_key) = keystroke_underlying_dead_key(keysym) {
1076                                    window.handle_ime_preedit(current_key);
1077                                }
1078                                state = self.0.borrow_mut();
1079                                compose_state.feed(keysym);
1080                            }
1081                            _ => {}
1082                        }
1083                        state.compose_state = Some(compose_state);
1084                    }
1085                    keystroke
1086                };
1087                drop(state);
1088                window.handle_input(PlatformInput::KeyDown(gpui::KeyDownEvent {
1089                    keystroke,
1090                    is_held: false,
1091                    prefer_character_input: false,
1092                }));
1093            }
1094            Event::KeyRelease(event) => {
1095                let window = self.get_window(event.event)?;
1096                let mut state = self.0.borrow_mut();
1097
1098                let modifiers = modifiers_from_state(event.state);
1099                state.modifiers = modifiers;
1100                let key_event_state = xkb_state_for_key_event(&state.xkb, event.state);
1101
1102                let keystroke = {
1103                    let code = event.detail.into();
1104                    let keystroke = keystroke_from_xkb(&key_event_state, modifiers, code);
1105                    let keysym = key_event_state.key_get_one_sym(code);
1106
1107                    if keysym.is_modifier_key() {
1108                        return Some(());
1109                    }
1110
1111                    keystroke
1112                };
1113                drop(state);
1114                window.handle_input(PlatformInput::KeyUp(gpui::KeyUpEvent { keystroke }));
1115            }
1116            Event::XinputButtonPress(event) => {
1117                let window = self.get_window(event.event)?;
1118                let mut state = self.0.borrow_mut();
1119
1120                let modifiers = modifiers_from_xinput_info(event.mods);
1121                state.modifiers = modifiers;
1122
1123                let position = point(
1124                    px(event.event_x as f32 / u16::MAX as f32 / state.scale_factor),
1125                    px(event.event_y as f32 / u16::MAX as f32 / state.scale_factor),
1126                );
1127
1128                if state.composing && state.ximc.is_some() {
1129                    drop(state);
1130                    self.reset_ime();
1131                    window.handle_ime_unmark();
1132                    state = self.0.borrow_mut();
1133                } else if let Some(text) = state.pre_edit_text.take() {
1134                    if let Some(compose_state) = state.compose_state.as_mut() {
1135                        compose_state.reset();
1136                    }
1137                    drop(state);
1138                    window.handle_ime_commit(text);
1139                    state = self.0.borrow_mut();
1140                }
1141                match button_or_scroll_from_event_detail(event.detail) {
1142                    Some(ButtonOrScroll::Button(button)) => {
1143                        let click_elapsed = state.last_click.elapsed();
1144                        if click_elapsed < DOUBLE_CLICK_INTERVAL
1145                            && state
1146                                .last_mouse_button
1147                                .is_some_and(|prev_button| prev_button == button)
1148                            && is_within_click_distance(state.last_location, position)
1149                        {
1150                            state.current_count += 1;
1151                        } else {
1152                            state.current_count = 1;
1153                        }
1154
1155                        state.last_click = Instant::now();
1156                        state.last_mouse_button = Some(button);
1157                        state.last_location = position;
1158                        let current_count = state.current_count;
1159
1160                        drop(state);
1161                        window.handle_input(PlatformInput::MouseDown(gpui::MouseDownEvent {
1162                            button,
1163                            position,
1164                            modifiers,
1165                            click_count: current_count,
1166                            first_mouse: false,
1167                        }));
1168                    }
1169                    Some(ButtonOrScroll::Scroll(direction)) => {
1170                        drop(state);
1171                        // Emulated scroll button presses are sent simultaneously with smooth scrolling XinputMotion events.
1172                        // Since handling those events does the scrolling, they are skipped here.
1173                        if !event
1174                            .flags
1175                            .contains(xinput::PointerEventFlags::POINTER_EMULATED)
1176                        {
1177                            let scroll_delta = match direction {
1178                                ScrollDirection::Up => Point::new(0.0, SCROLL_LINES),
1179                                ScrollDirection::Down => Point::new(0.0, -SCROLL_LINES),
1180                                ScrollDirection::Left => Point::new(SCROLL_LINES, 0.0),
1181                                ScrollDirection::Right => Point::new(-SCROLL_LINES, 0.0),
1182                            };
1183                            window.handle_input(PlatformInput::ScrollWheel(
1184                                make_scroll_wheel_event(position, scroll_delta, modifiers),
1185                            ));
1186                        }
1187                    }
1188                    None => {
1189                        log::error!("Unknown x11 button: {}", event.detail);
1190                    }
1191                }
1192            }
1193            Event::XinputButtonRelease(event) => {
1194                let window = self.get_window(event.event)?;
1195                let mut state = self.0.borrow_mut();
1196                let modifiers = modifiers_from_xinput_info(event.mods);
1197                state.modifiers = modifiers;
1198
1199                let position = point(
1200                    px(event.event_x as f32 / u16::MAX as f32 / state.scale_factor),
1201                    px(event.event_y as f32 / u16::MAX as f32 / state.scale_factor),
1202                );
1203                match button_or_scroll_from_event_detail(event.detail) {
1204                    Some(ButtonOrScroll::Button(button)) => {
1205                        let click_count = state.current_count;
1206                        drop(state);
1207                        window.handle_input(PlatformInput::MouseUp(gpui::MouseUpEvent {
1208                            button,
1209                            position,
1210                            modifiers,
1211                            click_count,
1212                        }));
1213                    }
1214                    Some(ButtonOrScroll::Scroll(_)) => {}
1215                    None => {}
1216                }
1217            }
1218            Event::XinputMotion(event) => {
1219                let window = self.get_window(event.event)?;
1220                let mut state = self.0.borrow_mut();
1221                if window.is_blocked() {
1222                    // We want to set the cursor to the default arrow
1223                    // when the window is blocked
1224                    let style = CursorStyle::Arrow;
1225
1226                    let current_style = state
1227                        .cursor_styles
1228                        .get(&window.x_window)
1229                        .unwrap_or(&CursorStyle::Arrow);
1230                    if *current_style != style
1231                        && let Some(cursor) = state.get_cursor_icon(style)
1232                    {
1233                        state.cursor_styles.insert(window.x_window, style);
1234                        check_reply(
1235                            || "Failed to set cursor style",
1236                            state.xcb_connection.change_window_attributes(
1237                                window.x_window,
1238                                &ChangeWindowAttributesAux {
1239                                    cursor: Some(cursor),
1240                                    ..Default::default()
1241                                },
1242                            ),
1243                        )
1244                        .log_err();
1245                        state.xcb_connection.flush().log_err();
1246                    };
1247                }
1248                let pressed_button = pressed_button_from_mask(event.button_mask[0]);
1249                let position = point(
1250                    px(event.event_x as f32 / u16::MAX as f32 / state.scale_factor),
1251                    px(event.event_y as f32 / u16::MAX as f32 / state.scale_factor),
1252                );
1253                let modifiers = modifiers_from_xinput_info(event.mods);
1254                state.modifiers = modifiers;
1255                drop(state);
1256
1257                if event.valuator_mask[0] & 3 != 0 {
1258                    window.handle_input(PlatformInput::MouseMove(gpui::MouseMoveEvent {
1259                        position,
1260                        pressed_button,
1261                        modifiers,
1262                    }));
1263                }
1264
1265                state = self.0.borrow_mut();
1266                if let Some(pointer) = state.pointer_device_states.get_mut(&event.sourceid) {
1267                    let scroll_delta = get_scroll_delta_and_update_state(pointer, &event);
1268                    drop(state);
1269                    if let Some(scroll_delta) = scroll_delta {
1270                        window.handle_input(PlatformInput::ScrollWheel(make_scroll_wheel_event(
1271                            position,
1272                            scroll_delta,
1273                            modifiers,
1274                        )));
1275                    }
1276                }
1277            }
1278            Event::XinputEnter(event) if event.mode == xinput::NotifyMode::NORMAL => {
1279                let window = self.get_window(event.event)?;
1280                window.set_hovered(true);
1281                let mut state = self.0.borrow_mut();
1282                state.mouse_focused_window = Some(event.event);
1283            }
1284            Event::XinputLeave(event) if event.mode == xinput::NotifyMode::NORMAL => {
1285                let mut state = self.0.borrow_mut();
1286
1287                // 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)
1288                reset_all_pointer_device_scroll_positions(&mut state.pointer_device_states);
1289                state.mouse_focused_window = None;
1290                let pressed_button = pressed_button_from_mask(event.buttons[0]);
1291                let position = point(
1292                    px(event.event_x as f32 / u16::MAX as f32 / state.scale_factor),
1293                    px(event.event_y as f32 / u16::MAX as f32 / state.scale_factor),
1294                );
1295                let modifiers = modifiers_from_xinput_info(event.mods);
1296                state.modifiers = modifiers;
1297                drop(state);
1298
1299                let window = self.get_window(event.event)?;
1300                window.handle_input(PlatformInput::MouseExited(gpui::MouseExitEvent {
1301                    pressed_button,
1302                    position,
1303                    modifiers,
1304                }));
1305                window.set_hovered(false);
1306            }
1307            Event::XinputHierarchy(event) => {
1308                let mut state = self.0.borrow_mut();
1309                // Temporarily use `state.pointer_device_states` to only store pointers that still have valid scroll values.
1310                // Any change to a device invalidates its scroll values.
1311                for info in event.infos {
1312                    if is_pointer_device(info.type_) {
1313                        state.pointer_device_states.remove(&info.deviceid);
1314                    }
1315                }
1316                if let Some(pointer_device_states) = current_pointer_device_states(
1317                    &state.xcb_connection,
1318                    &state.pointer_device_states,
1319                ) {
1320                    state.pointer_device_states = pointer_device_states;
1321                }
1322            }
1323            Event::XinputDeviceChanged(event) => {
1324                let mut state = self.0.borrow_mut();
1325                if let Some(pointer) = state.pointer_device_states.get_mut(&event.sourceid) {
1326                    reset_pointer_device_scroll_positions(pointer);
1327                }
1328            }
1329            Event::XinputGesturePinchBegin(event) => {
1330                let window = self.get_window(event.event)?;
1331                let mut state = self.0.borrow_mut();
1332                state.pinch_scale = 1.0;
1333                let modifiers = modifiers_from_xinput_info(event.mods);
1334                state.modifiers = modifiers;
1335                let position = point(
1336                    px(event.event_x as f32 / u16::MAX as f32 / state.scale_factor),
1337                    px(event.event_y as f32 / u16::MAX as f32 / state.scale_factor),
1338                );
1339                drop(state);
1340                window.handle_input(PlatformInput::Pinch(gpui::PinchEvent {
1341                    position,
1342                    delta: 0.0,
1343                    modifiers,
1344                    phase: gpui::TouchPhase::Started,
1345                }));
1346            }
1347            Event::XinputGesturePinchUpdate(event) => {
1348                let window = self.get_window(event.event)?;
1349                let mut state = self.0.borrow_mut();
1350                let modifiers = modifiers_from_xinput_info(event.mods);
1351                state.modifiers = modifiers;
1352                let position = point(
1353                    px(event.event_x as f32 / u16::MAX as f32 / state.scale_factor),
1354                    px(event.event_y as f32 / u16::MAX as f32 / state.scale_factor),
1355                );
1356                // scale is in FP16.16 format: divide by 65536 to get the float value
1357                let new_absolute_scale = event.scale as f32 / 65536.0;
1358                let previous_scale = state.pinch_scale;
1359                let zoom_delta = new_absolute_scale - previous_scale;
1360                state.pinch_scale = new_absolute_scale;
1361                drop(state);
1362                window.handle_input(PlatformInput::Pinch(gpui::PinchEvent {
1363                    position,
1364                    delta: zoom_delta,
1365                    modifiers,
1366                    phase: gpui::TouchPhase::Moved,
1367                }));
1368            }
1369            Event::XinputGesturePinchEnd(event) => {
1370                let window = self.get_window(event.event)?;
1371                let mut state = self.0.borrow_mut();
1372                state.pinch_scale = 1.0;
1373                let modifiers = modifiers_from_xinput_info(event.mods);
1374                state.modifiers = modifiers;
1375                let position = point(
1376                    px(event.event_x as f32 / u16::MAX as f32 / state.scale_factor),
1377                    px(event.event_y as f32 / u16::MAX as f32 / state.scale_factor),
1378                );
1379                drop(state);
1380                window.handle_input(PlatformInput::Pinch(gpui::PinchEvent {
1381                    position,
1382                    delta: 0.0,
1383                    modifiers,
1384                    phase: gpui::TouchPhase::Ended,
1385                }));
1386            }
1387            _ => {}
1388        };
1389
1390        Some(())
1391    }
1392
1393    fn handle_xim_callback_event(&self, event: XimCallbackEvent) {
1394        match event {
1395            XimCallbackEvent::XimXEvent(event) => {
1396                self.handle_event(event);
1397            }
1398            XimCallbackEvent::XimCommitEvent(window, text) => {
1399                self.xim_handle_commit(window, text);
1400            }
1401            XimCallbackEvent::XimPreeditEvent(window, text) => {
1402                self.xim_handle_preedit(window, text);
1403            }
1404        };
1405    }
1406
1407    fn xim_handle_event(&self, event: Event) -> Option<()> {
1408        match event {
1409            Event::KeyPress(event) | Event::KeyRelease(event) => {
1410                let mut state = self.0.borrow_mut();
1411                state.pre_key_char_down = Some(keystroke_from_xkb(
1412                    &state.xkb,
1413                    state.modifiers,
1414                    event.detail.into(),
1415                ));
1416                let (mut ximc, mut xim_handler) = state.take_xim()?;
1417                drop(state);
1418                xim_handler.window = event.event;
1419                ximc.forward_event(
1420                    xim_handler.im_id,
1421                    xim_handler.ic_id,
1422                    xim::ForwardEventFlag::empty(),
1423                    &event,
1424                )
1425                .context("X11: Failed to forward XIM event")
1426                .log_err();
1427                let mut state = self.0.borrow_mut();
1428                state.restore_xim(ximc, xim_handler);
1429                drop(state);
1430            }
1431            event => {
1432                self.handle_event(event);
1433            }
1434        }
1435        Some(())
1436    }
1437
1438    fn xim_handle_commit(&self, window: xproto::Window, text: String) -> Option<()> {
1439        let Some(window) = self.get_window(window) else {
1440            log::error!("bug: Failed to get window for XIM commit");
1441            return None;
1442        };
1443        let mut state = self.0.borrow_mut();
1444        state.composing = false;
1445        drop(state);
1446        window.handle_ime_commit(text);
1447        Some(())
1448    }
1449
1450    fn xim_handle_preedit(&self, window: xproto::Window, text: String) -> Option<()> {
1451        let Some(window) = self.get_window(window) else {
1452            log::error!("bug: Failed to get window for XIM preedit");
1453            return None;
1454        };
1455
1456        let mut state = self.0.borrow_mut();
1457        let (mut ximc, xim_handler) = state.take_xim()?;
1458        state.composing = !text.is_empty();
1459        drop(state);
1460        window.handle_ime_preedit(text);
1461
1462        if let Some(scaled_area) = window.get_ime_area() {
1463            let ic_attributes = ximc
1464                .build_ic_attributes()
1465                .push(
1466                    xim::AttributeName::InputStyle,
1467                    xim::InputStyle::PREEDIT_CALLBACKS,
1468                )
1469                .push(xim::AttributeName::ClientWindow, xim_handler.window)
1470                .push(xim::AttributeName::FocusWindow, xim_handler.window)
1471                .nested_list(xim::AttributeName::PreeditAttributes, |b| {
1472                    b.push(
1473                        xim::AttributeName::SpotLocation,
1474                        xim::Point {
1475                            x: u32::from(scaled_area.origin.x + scaled_area.size.width) as i16,
1476                            y: u32::from(scaled_area.origin.y + scaled_area.size.height) as i16,
1477                        },
1478                    );
1479                })
1480                .build();
1481            ximc.set_ic_values(xim_handler.im_id, xim_handler.ic_id, ic_attributes)
1482                .ok();
1483        }
1484        let mut state = self.0.borrow_mut();
1485        state.restore_xim(ximc, xim_handler);
1486        drop(state);
1487        Some(())
1488    }
1489
1490    fn handle_keyboard_layout_change(&self) {
1491        let mut state = self.0.borrow_mut();
1492        let layout_idx = state.xkb.serialize_layout(STATE_LAYOUT_EFFECTIVE);
1493        let keymap = state.xkb.get_keymap();
1494        let layout_name = keymap.layout_get_name(layout_idx);
1495        if layout_name != state.keyboard_layout.name() {
1496            state.keyboard_layout = LinuxKeyboardLayout::new(layout_name.to_string().into());
1497            if let Some(mut callback) = state.common.callbacks.keyboard_layout_change.take() {
1498                drop(state);
1499                callback();
1500                state = self.0.borrow_mut();
1501                state.common.callbacks.keyboard_layout_change = Some(callback);
1502            }
1503        }
1504    }
1505}
1506
1507impl LinuxClient for X11Client {
1508    fn compositor_name(&self) -> &'static str {
1509        "X11"
1510    }
1511
1512    fn with_common<R>(&self, f: impl FnOnce(&mut LinuxCommon) -> R) -> R {
1513        f(&mut self.0.borrow_mut().common)
1514    }
1515
1516    fn keyboard_layout(&self) -> Box<dyn PlatformKeyboardLayout> {
1517        let state = self.0.borrow();
1518        Box::new(state.keyboard_layout.clone())
1519    }
1520
1521    fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
1522        let state = self.0.borrow();
1523        let setup = state.xcb_connection.setup();
1524        setup
1525            .roots
1526            .iter()
1527            .enumerate()
1528            .filter_map(|(root_id, _)| {
1529                Some(Rc::new(
1530                    X11Display::new(&state.xcb_connection, state.scale_factor, root_id).ok()?,
1531                ) as Rc<dyn PlatformDisplay>)
1532            })
1533            .collect()
1534    }
1535
1536    fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
1537        let state = self.0.borrow();
1538        X11Display::new(
1539            &state.xcb_connection,
1540            state.scale_factor,
1541            state.x_root_index,
1542        )
1543        .log_err()
1544        .map(|display| Rc::new(display) as Rc<dyn PlatformDisplay>)
1545    }
1546
1547    fn display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>> {
1548        let state = self.0.borrow();
1549
1550        Some(Rc::new(
1551            X11Display::new(
1552                &state.xcb_connection,
1553                state.scale_factor,
1554                u32::from(id) as usize,
1555            )
1556            .ok()?,
1557        ))
1558    }
1559
1560    #[cfg(feature = "screen-capture")]
1561    fn is_screen_capture_supported(&self) -> bool {
1562        true
1563    }
1564
1565    #[cfg(feature = "screen-capture")]
1566    fn screen_capture_sources(
1567        &self,
1568    ) -> futures::channel::oneshot::Receiver<anyhow::Result<Vec<Rc<dyn gpui::ScreenCaptureSource>>>>
1569    {
1570        gpui::scap_screen_capture::scap_screen_sources(&self.0.borrow().common.foreground_executor)
1571    }
1572
1573    fn open_window(
1574        &self,
1575        handle: AnyWindowHandle,
1576        params: WindowParams,
1577    ) -> anyhow::Result<Box<dyn PlatformWindow>> {
1578        let mut state = self.0.borrow_mut();
1579        let parent_window = state
1580            .keyboard_focused_window
1581            .and_then(|focused_window| state.windows.get(&focused_window))
1582            .map(|w| w.window.clone());
1583        let x_window = state
1584            .xcb_connection
1585            .generate_id()
1586            .context("X11: Failed to generate window ID")?;
1587
1588        let xcb_connection = state.xcb_connection.clone();
1589        let client_side_decorations_supported = state.client_side_decorations_supported;
1590        let x_root_index = state.x_root_index;
1591        let atoms = state.atoms;
1592        let scale_factor = state.scale_factor;
1593        let appearance = state.common.appearance;
1594        let compositor_gpu = state.compositor_gpu.take();
1595        let supports_xinput_gestures = state.supports_xinput_gestures;
1596        let window = X11Window::new(
1597            handle,
1598            X11ClientStatePtr(Rc::downgrade(&self.0)),
1599            state.common.foreground_executor.clone(),
1600            state.gpu_context.clone(),
1601            compositor_gpu,
1602            params,
1603            &xcb_connection,
1604            client_side_decorations_supported,
1605            x_root_index,
1606            x_window,
1607            &atoms,
1608            scale_factor,
1609            appearance,
1610            parent_window,
1611            supports_xinput_gestures,
1612        )?;
1613        check_reply(
1614            || "Failed to set XdndAware property",
1615            state.xcb_connection.change_property32(
1616                xproto::PropMode::REPLACE,
1617                x_window,
1618                state.atoms.XdndAware,
1619                state.atoms.XA_ATOM,
1620                &[5],
1621            ),
1622        )
1623        .log_err();
1624        xcb_flush(&state.xcb_connection);
1625
1626        let window_ref = WindowRef {
1627            window: window.0.clone(),
1628            refresh_state: None,
1629            expose_event_received: false,
1630            last_visibility: Visibility::UNOBSCURED,
1631            is_mapped: false,
1632        };
1633
1634        state.windows.insert(x_window, window_ref);
1635        Ok(Box::new(window))
1636    }
1637
1638    fn set_cursor_style(&self, style: CursorStyle) {
1639        let mut state = self.0.borrow_mut();
1640        let Some(focused_window) = state.mouse_focused_window else {
1641            return;
1642        };
1643        let current_style = state
1644            .cursor_styles
1645            .get(&focused_window)
1646            .unwrap_or(&CursorStyle::Arrow);
1647
1648        let window = state
1649            .mouse_focused_window
1650            .and_then(|w| state.windows.get(&w));
1651
1652        let should_change = *current_style != style
1653            && (window.is_none() || window.is_some_and(|w| !w.is_blocked()));
1654
1655        if !should_change {
1656            return;
1657        }
1658
1659        let Some(cursor) = state.get_cursor_icon(style) else {
1660            return;
1661        };
1662
1663        state.cursor_styles.insert(focused_window, style);
1664        check_reply(
1665            || "Failed to set cursor style",
1666            state.xcb_connection.change_window_attributes(
1667                focused_window,
1668                &ChangeWindowAttributesAux {
1669                    cursor: Some(cursor),
1670                    ..Default::default()
1671                },
1672            ),
1673        )
1674        .log_err();
1675        state.xcb_connection.flush().log_err();
1676    }
1677
1678    fn open_uri(&self, uri: &str) {
1679        #[cfg(any(feature = "wayland", feature = "x11"))]
1680        open_uri_internal(
1681            self.with_common(|c| c.background_executor.clone()),
1682            uri,
1683            None,
1684        );
1685    }
1686
1687    fn reveal_path(&self, path: PathBuf) {
1688        #[cfg(any(feature = "x11", feature = "wayland"))]
1689        reveal_path_internal(
1690            self.with_common(|c| c.background_executor.clone()),
1691            path,
1692            None,
1693        );
1694    }
1695
1696    fn write_to_primary(&self, item: gpui::ClipboardItem) {
1697        let state = self.0.borrow_mut();
1698        state
1699            .clipboard
1700            .set_text(
1701                std::borrow::Cow::Owned(item.text().unwrap_or_default()),
1702                clipboard::ClipboardKind::Primary,
1703                clipboard::WaitConfig::None,
1704            )
1705            .context("X11 Failed to write to clipboard (primary)")
1706            .log_with_level(log::Level::Debug);
1707    }
1708
1709    fn write_to_clipboard(&self, item: gpui::ClipboardItem) {
1710        let mut state = self.0.borrow_mut();
1711        state
1712            .clipboard
1713            .set_text(
1714                std::borrow::Cow::Owned(item.text().unwrap_or_default()),
1715                clipboard::ClipboardKind::Clipboard,
1716                clipboard::WaitConfig::None,
1717            )
1718            .context("X11: Failed to write to clipboard (clipboard)")
1719            .log_with_level(log::Level::Debug);
1720        state.clipboard_item.replace(item);
1721    }
1722
1723    fn read_from_primary(&self) -> Option<gpui::ClipboardItem> {
1724        let state = self.0.borrow_mut();
1725        state
1726            .clipboard
1727            .get_any(clipboard::ClipboardKind::Primary)
1728            .context("X11: Failed to read from clipboard (primary)")
1729            .log_with_level(log::Level::Debug)
1730    }
1731
1732    fn read_from_clipboard(&self) -> Option<gpui::ClipboardItem> {
1733        let state = self.0.borrow_mut();
1734        // if the last copy was from this app, return our cached item
1735        // which has metadata attached.
1736        if state
1737            .clipboard
1738            .is_owner(clipboard::ClipboardKind::Clipboard)
1739        {
1740            return state.clipboard_item.clone();
1741        }
1742        state
1743            .clipboard
1744            .get_any(clipboard::ClipboardKind::Clipboard)
1745            .context("X11: Failed to read from clipboard (clipboard)")
1746            .log_with_level(log::Level::Debug)
1747    }
1748
1749    fn run(&self) {
1750        let Some(mut event_loop) = self
1751            .0
1752            .borrow_mut()
1753            .event_loop
1754            .take()
1755            .context("X11Client::run called but it's already running")
1756            .log_err()
1757        else {
1758            return;
1759        };
1760
1761        event_loop.run(None, &mut self.clone(), |_| {}).log_err();
1762    }
1763
1764    fn active_window(&self) -> Option<AnyWindowHandle> {
1765        let state = self.0.borrow();
1766        state.keyboard_focused_window.and_then(|focused_window| {
1767            state
1768                .windows
1769                .get(&focused_window)
1770                .map(|window| window.handle())
1771        })
1772    }
1773
1774    fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
1775        let state = self.0.borrow();
1776        let root = state.xcb_connection.setup().roots[state.x_root_index].root;
1777
1778        let reply = state
1779            .xcb_connection
1780            .get_property(
1781                false,
1782                root,
1783                state.atoms._NET_CLIENT_LIST_STACKING,
1784                xproto::AtomEnum::WINDOW,
1785                0,
1786                u32::MAX,
1787            )
1788            .ok()?
1789            .reply()
1790            .ok()?;
1791
1792        let window_ids = reply
1793            .value
1794            .chunks_exact(4)
1795            .filter_map(|chunk| chunk.try_into().ok().map(u32::from_ne_bytes))
1796            .collect::<Vec<xproto::Window>>();
1797
1798        let mut handles = Vec::new();
1799
1800        // We need to reverse, since _NET_CLIENT_LIST_STACKING has
1801        // a back-to-front order.
1802        // See: https://specifications.freedesktop.org/wm-spec/1.3/ar01s03.html
1803        for window_ref in window_ids
1804            .iter()
1805            .rev()
1806            .filter_map(|&win| state.windows.get(&win))
1807        {
1808            if !window_ref.window.state.borrow().destroyed {
1809                handles.push(window_ref.handle());
1810            }
1811        }
1812
1813        Some(handles)
1814    }
1815
1816    fn window_identifier(&self) -> impl Future<Output = Option<WindowIdentifier>> + Send + 'static {
1817        let state = self.0.borrow();
1818        state
1819            .keyboard_focused_window
1820            .and_then(|focused_window| state.windows.get(&focused_window))
1821            .map(|window| window.window.x_window as u64)
1822            .map(|x_window| std::future::ready(Some(WindowIdentifier::from_xid(x_window))))
1823            .unwrap_or(std::future::ready(None))
1824    }
1825}
1826
1827impl X11ClientState {
1828    fn has_xim(&self) -> bool {
1829        self.ximc.is_some() && self.xim_handler.is_some()
1830    }
1831
1832    fn take_xim(&mut self) -> Option<(X11rbClient<Rc<XCBConnection>>, XimHandler)> {
1833        let ximc = self
1834            .ximc
1835            .take()
1836            .ok_or(anyhow!("bug: XIM connection not set"))
1837            .log_err()?;
1838        if let Some(xim_handler) = self.xim_handler.take() {
1839            Some((ximc, xim_handler))
1840        } else {
1841            self.ximc = Some(ximc);
1842            log::error!("bug: XIM handler not set");
1843            None
1844        }
1845    }
1846
1847    fn restore_xim(&mut self, ximc: X11rbClient<Rc<XCBConnection>>, xim_handler: XimHandler) {
1848        self.ximc = Some(ximc);
1849        self.xim_handler = Some(xim_handler);
1850    }
1851
1852    fn update_refresh_loop(&mut self, x_window: xproto::Window) {
1853        let Some(window_ref) = self.windows.get_mut(&x_window) else {
1854            return;
1855        };
1856        let is_visible = window_ref.is_mapped
1857            && !matches!(window_ref.last_visibility, Visibility::FULLY_OBSCURED);
1858        match (is_visible, window_ref.refresh_state.take()) {
1859            (false, refresh_state @ Some(RefreshState::Hidden { .. }))
1860            | (false, refresh_state @ None)
1861            | (true, refresh_state @ Some(RefreshState::PeriodicRefresh { .. })) => {
1862                window_ref.refresh_state = refresh_state;
1863            }
1864            (
1865                false,
1866                Some(RefreshState::PeriodicRefresh {
1867                    refresh_rate,
1868                    event_loop_token,
1869                }),
1870            ) => {
1871                self.loop_handle.remove(event_loop_token);
1872                window_ref.refresh_state = Some(RefreshState::Hidden { refresh_rate });
1873            }
1874            (true, Some(RefreshState::Hidden { refresh_rate })) => {
1875                let event_loop_token = self.start_refresh_loop(x_window, refresh_rate);
1876                let Some(window_ref) = self.windows.get_mut(&x_window) else {
1877                    return;
1878                };
1879                window_ref.refresh_state = Some(RefreshState::PeriodicRefresh {
1880                    refresh_rate,
1881                    event_loop_token,
1882                });
1883            }
1884            (true, None) => {
1885                let Some(screen_resources) = get_reply(
1886                    || "Failed to get screen resources",
1887                    self.xcb_connection
1888                        .randr_get_screen_resources_current(x_window),
1889                )
1890                .log_err() else {
1891                    return;
1892                };
1893
1894                // Ideally this would be re-queried when the window changes screens, but there
1895                // doesn't seem to be an efficient / straightforward way to do this. Should also be
1896                // updated when screen configurations change.
1897                let mode_info = screen_resources.crtcs.iter().find_map(|crtc| {
1898                    let crtc_info = self
1899                        .xcb_connection
1900                        .randr_get_crtc_info(*crtc, x11rb::CURRENT_TIME)
1901                        .ok()?
1902                        .reply()
1903                        .ok()?;
1904
1905                    screen_resources
1906                        .modes
1907                        .iter()
1908                        .find(|m| m.id == crtc_info.mode)
1909                });
1910                let refresh_rate = match mode_info {
1911                    Some(mode_info) => mode_refresh_rate(mode_info),
1912                    None => {
1913                        log::error!(
1914                            "Failed to get screen mode info from xrandr, \
1915                            defaulting to 60hz refresh rate."
1916                        );
1917                        Duration::from_micros(1_000_000 / 60)
1918                    }
1919                };
1920
1921                let event_loop_token = self.start_refresh_loop(x_window, refresh_rate);
1922                let Some(window_ref) = self.windows.get_mut(&x_window) else {
1923                    return;
1924                };
1925                window_ref.refresh_state = Some(RefreshState::PeriodicRefresh {
1926                    refresh_rate,
1927                    event_loop_token,
1928                });
1929            }
1930        }
1931    }
1932
1933    #[must_use]
1934    fn start_refresh_loop(
1935        &self,
1936        x_window: xproto::Window,
1937        refresh_rate: Duration,
1938    ) -> RegistrationToken {
1939        self.loop_handle
1940            .insert_source(calloop::timer::Timer::immediate(), {
1941                move |mut instant, (), client| {
1942                    let xcb_connection = {
1943                        let mut state = client.0.borrow_mut();
1944                        let xcb_connection = state.xcb_connection.clone();
1945                        if let Some(window) = state.windows.get_mut(&x_window) {
1946                            let expose_event_received = window.expose_event_received;
1947                            window.expose_event_received = false;
1948                            let force_render = std::mem::take(
1949                                &mut window.window.state.borrow_mut().force_render_after_recovery,
1950                            );
1951                            let window = window.window.clone();
1952                            drop(state);
1953                            window.refresh(RequestFrameOptions {
1954                                require_presentation: expose_event_received,
1955                                force_render,
1956                            });
1957                        }
1958                        xcb_connection
1959                    };
1960                    client.process_x11_events(&xcb_connection).log_err();
1961
1962                    // Take into account that some frames have been skipped
1963                    let now = Instant::now();
1964                    while instant < now {
1965                        instant += refresh_rate;
1966                    }
1967                    calloop::timer::TimeoutAction::ToInstant(instant)
1968                }
1969            })
1970            .expect("Failed to initialize window refresh timer")
1971    }
1972
1973    fn get_cursor_icon(&mut self, style: CursorStyle) -> Option<xproto::Cursor> {
1974        if let Some(cursor) = self.cursor_cache.get(&style) {
1975            return *cursor;
1976        }
1977
1978        let result;
1979        match style {
1980            CursorStyle::None => match create_invisible_cursor(&self.xcb_connection) {
1981                Ok(loaded_cursor) => result = Ok(loaded_cursor),
1982                Err(err) => result = Err(err.context("X11: error while creating invisible cursor")),
1983            },
1984            _ => 'outer: {
1985                let mut errors = String::new();
1986                let cursor_icon_names = cursor_style_to_icon_names(style);
1987                for cursor_icon_name in cursor_icon_names {
1988                    match self
1989                        .cursor_handle
1990                        .load_cursor(&self.xcb_connection, cursor_icon_name)
1991                    {
1992                        Ok(loaded_cursor) => {
1993                            if loaded_cursor != x11rb::NONE {
1994                                result = Ok(loaded_cursor);
1995                                break 'outer;
1996                            }
1997                        }
1998                        Err(err) => {
1999                            errors.push_str(&err.to_string());
2000                            errors.push('\n');
2001                        }
2002                    }
2003                }
2004                if errors.is_empty() {
2005                    result = Err(anyhow!(
2006                        "errors while loading cursor icons {:?}:\n{}",
2007                        cursor_icon_names,
2008                        errors
2009                    ));
2010                } else {
2011                    result = Err(anyhow!("did not find cursor icons {:?}", cursor_icon_names));
2012                }
2013            }
2014        };
2015
2016        let cursor = match result {
2017            Ok(cursor) => Some(cursor),
2018            Err(err) => {
2019                match self
2020                    .cursor_handle
2021                    .load_cursor(&self.xcb_connection, DEFAULT_CURSOR_ICON_NAME)
2022                {
2023                    Ok(default) => {
2024                        log_cursor_icon_warning(err.context(format!(
2025                            "X11: error loading cursor icon, falling back on default icon '{}'",
2026                            DEFAULT_CURSOR_ICON_NAME
2027                        )));
2028                        Some(default)
2029                    }
2030                    Err(default_err) => {
2031                        log_cursor_icon_warning(err.context(default_err).context(format!(
2032                            "X11: error loading default cursor fallback '{}'",
2033                            DEFAULT_CURSOR_ICON_NAME
2034                        )));
2035                        None
2036                    }
2037                }
2038            }
2039        };
2040
2041        self.cursor_cache.insert(style, cursor);
2042        cursor
2043    }
2044}
2045
2046// Adapted from:
2047// https://docs.rs/winit/0.29.11/src/winit/platform_impl/linux/x11/monitor.rs.html#103-111
2048pub fn mode_refresh_rate(mode: &randr::ModeInfo) -> Duration {
2049    if mode.dot_clock == 0 || mode.htotal == 0 || mode.vtotal == 0 {
2050        return Duration::from_millis(16);
2051    }
2052
2053    let millihertz = mode.dot_clock as u64 * 1_000 / (mode.htotal as u64 * mode.vtotal as u64);
2054    let micros = 1_000_000_000 / millihertz;
2055    log::info!("Refreshing every {}ms", micros / 1_000);
2056    Duration::from_micros(micros)
2057}
2058
2059fn fp3232_to_f32(value: xinput::Fp3232) -> f32 {
2060    value.integral as f32 + value.frac as f32 / u32::MAX as f32
2061}
2062
2063fn detect_compositor_gpu(
2064    xcb_connection: &XCBConnection,
2065    screen: &xproto::Screen,
2066) -> Option<CompositorGpuHint> {
2067    use std::os::fd::AsRawFd;
2068    use std::os::unix::fs::MetadataExt;
2069
2070    xcb_connection
2071        .extension_information(dri3::X11_EXTENSION_NAME)
2072        .ok()??;
2073
2074    let reply = dri3::open(xcb_connection, screen.root, 0)
2075        .ok()?
2076        .reply()
2077        .ok()?;
2078    let fd = reply.device_fd;
2079
2080    let path = format!("/proc/self/fd/{}", fd.as_raw_fd());
2081    let metadata = std::fs::metadata(&path).ok()?;
2082
2083    crate::linux::compositor_gpu_hint_from_dev_t(metadata.rdev())
2084}
2085
2086fn check_compositor_present(xcb_connection: &XCBConnection, root: xproto::Window) -> bool {
2087    // Method 1: Check for _NET_WM_CM_S{root}
2088    let atom_name = format!("_NET_WM_CM_S{}", root);
2089    let atom1 = get_reply(
2090        || format!("Failed to intern {atom_name}"),
2091        xcb_connection.intern_atom(false, atom_name.as_bytes()),
2092    );
2093    let method1 = match atom1.log_with_level(Level::Debug) {
2094        Some(reply) if reply.atom != x11rb::NONE => {
2095            let atom = reply.atom;
2096            get_reply(
2097                || format!("Failed to get {atom_name} owner"),
2098                xcb_connection.get_selection_owner(atom),
2099            )
2100            .map(|reply| reply.owner != 0)
2101            .log_with_level(Level::Debug)
2102            .unwrap_or(false)
2103        }
2104        _ => false,
2105    };
2106
2107    // Method 2: Check for _NET_WM_CM_OWNER
2108    let atom_name = "_NET_WM_CM_OWNER";
2109    let atom2 = get_reply(
2110        || format!("Failed to intern {atom_name}"),
2111        xcb_connection.intern_atom(false, atom_name.as_bytes()),
2112    );
2113    let method2 = match atom2.log_with_level(Level::Debug) {
2114        Some(reply) if reply.atom != x11rb::NONE => {
2115            let atom = reply.atom;
2116            get_reply(
2117                || format!("Failed to get {atom_name}"),
2118                xcb_connection.get_property(false, root, atom, xproto::AtomEnum::WINDOW, 0, 1),
2119            )
2120            .map(|reply| reply.value_len > 0)
2121            .unwrap_or(false)
2122        }
2123        _ => return false,
2124    };
2125
2126    // Method 3: Check for _NET_SUPPORTING_WM_CHECK
2127    let atom_name = "_NET_SUPPORTING_WM_CHECK";
2128    let atom3 = get_reply(
2129        || format!("Failed to intern {atom_name}"),
2130        xcb_connection.intern_atom(false, atom_name.as_bytes()),
2131    );
2132    let method3 = match atom3.log_with_level(Level::Debug) {
2133        Some(reply) if reply.atom != x11rb::NONE => {
2134            let atom = reply.atom;
2135            get_reply(
2136                || format!("Failed to get {atom_name}"),
2137                xcb_connection.get_property(false, root, atom, xproto::AtomEnum::WINDOW, 0, 1),
2138            )
2139            .map(|reply| reply.value_len > 0)
2140            .unwrap_or(false)
2141        }
2142        _ => return false,
2143    };
2144
2145    log::debug!(
2146        "Compositor detection: _NET_WM_CM_S?={}, _NET_WM_CM_OWNER={}, _NET_SUPPORTING_WM_CHECK={}",
2147        method1,
2148        method2,
2149        method3
2150    );
2151
2152    method1 || method2 || method3
2153}
2154
2155fn check_gtk_frame_extents_supported(
2156    xcb_connection: &XCBConnection,
2157    atoms: &XcbAtoms,
2158    root: xproto::Window,
2159) -> bool {
2160    let Some(supported_atoms) = get_reply(
2161        || "Failed to get _NET_SUPPORTED",
2162        xcb_connection.get_property(
2163            false,
2164            root,
2165            atoms._NET_SUPPORTED,
2166            xproto::AtomEnum::ATOM,
2167            0,
2168            1024,
2169        ),
2170    )
2171    .log_with_level(Level::Debug) else {
2172        return false;
2173    };
2174
2175    let supported_atom_ids: Vec<u32> = supported_atoms
2176        .value
2177        .chunks_exact(4)
2178        .filter_map(|chunk| chunk.try_into().ok().map(u32::from_ne_bytes))
2179        .collect();
2180
2181    supported_atom_ids.contains(&atoms._GTK_FRAME_EXTENTS)
2182}
2183
2184fn xdnd_is_atom_supported(atom: u32, atoms: &XcbAtoms) -> bool {
2185    atom == atoms.TEXT
2186        || atom == atoms.STRING
2187        || atom == atoms.UTF8_STRING
2188        || atom == atoms.TEXT_PLAIN
2189        || atom == atoms.TEXT_PLAIN_UTF8
2190        || atom == atoms.TextUriList
2191}
2192
2193fn xdnd_get_supported_atom(
2194    xcb_connection: &XCBConnection,
2195    supported_atoms: &XcbAtoms,
2196    target: xproto::Window,
2197) -> u32 {
2198    if let Some(reply) = get_reply(
2199        || "Failed to get XDnD supported atoms",
2200        xcb_connection.get_property(
2201            false,
2202            target,
2203            supported_atoms.XdndTypeList,
2204            AtomEnum::ANY,
2205            0,
2206            1024,
2207        ),
2208    )
2209    .log_with_level(Level::Warn)
2210        && let Some(atoms) = reply.value32()
2211    {
2212        for atom in atoms {
2213            if xdnd_is_atom_supported(atom, supported_atoms) {
2214                return atom;
2215            }
2216        }
2217    }
2218    0
2219}
2220
2221fn xdnd_send_finished(
2222    xcb_connection: &XCBConnection,
2223    atoms: &XcbAtoms,
2224    source: xproto::Window,
2225    target: xproto::Window,
2226) {
2227    let message = ClientMessageEvent {
2228        format: 32,
2229        window: target,
2230        type_: atoms.XdndFinished,
2231        data: ClientMessageData::from([source, 1, atoms.XdndActionCopy, 0, 0]),
2232        sequence: 0,
2233        response_type: xproto::CLIENT_MESSAGE_EVENT,
2234    };
2235    check_reply(
2236        || "Failed to send XDnD finished event",
2237        xcb_connection.send_event(false, target, EventMask::default(), message),
2238    )
2239    .log_err();
2240    xcb_connection.flush().log_err();
2241}
2242
2243fn xdnd_send_status(
2244    xcb_connection: &XCBConnection,
2245    atoms: &XcbAtoms,
2246    source: xproto::Window,
2247    target: xproto::Window,
2248    action: u32,
2249) {
2250    let message = ClientMessageEvent {
2251        format: 32,
2252        window: target,
2253        type_: atoms.XdndStatus,
2254        data: ClientMessageData::from([source, 1, 0, 0, action]),
2255        sequence: 0,
2256        response_type: xproto::CLIENT_MESSAGE_EVENT,
2257    };
2258    check_reply(
2259        || "Failed to send XDnD status event",
2260        xcb_connection.send_event(false, target, EventMask::default(), message),
2261    )
2262    .log_err();
2263    xcb_connection.flush().log_err();
2264}
2265
2266/// Recomputes `pointer_device_states` by querying all pointer devices.
2267/// When a device is present in `scroll_values_to_preserve`, its value for `ScrollAxisState.scroll_value` is used.
2268fn current_pointer_device_states(
2269    xcb_connection: &XCBConnection,
2270    scroll_values_to_preserve: &BTreeMap<xinput::DeviceId, PointerDeviceState>,
2271) -> Option<BTreeMap<xinput::DeviceId, PointerDeviceState>> {
2272    let devices_query_result = get_reply(
2273        || "Failed to query XInput devices",
2274        xcb_connection.xinput_xi_query_device(XINPUT_ALL_DEVICES),
2275    )
2276    .log_err()?;
2277
2278    let mut pointer_device_states = BTreeMap::new();
2279    pointer_device_states.extend(
2280        devices_query_result
2281            .infos
2282            .iter()
2283            .filter(|info| is_pointer_device(info.type_))
2284            .filter_map(|info| {
2285                let scroll_data = info
2286                    .classes
2287                    .iter()
2288                    .filter_map(|class| class.data.as_scroll())
2289                    .copied()
2290                    .rev()
2291                    .collect::<Vec<_>>();
2292                let old_state = scroll_values_to_preserve.get(&info.deviceid);
2293                let old_horizontal = old_state.map(|state| &state.horizontal);
2294                let old_vertical = old_state.map(|state| &state.vertical);
2295                let horizontal = scroll_data
2296                    .iter()
2297                    .find(|data| data.scroll_type == xinput::ScrollType::HORIZONTAL)
2298                    .map(|data| scroll_data_to_axis_state(data, old_horizontal));
2299                let vertical = scroll_data
2300                    .iter()
2301                    .find(|data| data.scroll_type == xinput::ScrollType::VERTICAL)
2302                    .map(|data| scroll_data_to_axis_state(data, old_vertical));
2303                if horizontal.is_none() && vertical.is_none() {
2304                    None
2305                } else {
2306                    Some((
2307                        info.deviceid,
2308                        PointerDeviceState {
2309                            horizontal: horizontal.unwrap_or_else(Default::default),
2310                            vertical: vertical.unwrap_or_else(Default::default),
2311                        },
2312                    ))
2313                }
2314            }),
2315    );
2316    if pointer_device_states.is_empty() {
2317        log::error!("Found no xinput mouse pointers.");
2318    }
2319    Some(pointer_device_states)
2320}
2321
2322/// Returns true if the device is a pointer device. Does not include pointer device groups.
2323fn is_pointer_device(type_: xinput::DeviceType) -> bool {
2324    type_ == xinput::DeviceType::SLAVE_POINTER
2325}
2326
2327fn scroll_data_to_axis_state(
2328    data: &xinput::DeviceClassDataScroll,
2329    old_axis_state_with_valid_scroll_value: Option<&ScrollAxisState>,
2330) -> ScrollAxisState {
2331    ScrollAxisState {
2332        valuator_number: Some(data.number),
2333        multiplier: SCROLL_LINES / fp3232_to_f32(data.increment),
2334        scroll_value: old_axis_state_with_valid_scroll_value.and_then(|state| state.scroll_value),
2335    }
2336}
2337
2338fn reset_all_pointer_device_scroll_positions(
2339    pointer_device_states: &mut BTreeMap<xinput::DeviceId, PointerDeviceState>,
2340) {
2341    pointer_device_states
2342        .iter_mut()
2343        .for_each(|(_, device_state)| reset_pointer_device_scroll_positions(device_state));
2344}
2345
2346fn reset_pointer_device_scroll_positions(pointer: &mut PointerDeviceState) {
2347    pointer.horizontal.scroll_value = None;
2348    pointer.vertical.scroll_value = None;
2349}
2350
2351/// Returns the scroll delta for a smooth scrolling motion event, or `None` if no scroll data is present.
2352fn get_scroll_delta_and_update_state(
2353    pointer: &mut PointerDeviceState,
2354    event: &xinput::MotionEvent,
2355) -> Option<Point<f32>> {
2356    let delta_x = get_axis_scroll_delta_and_update_state(event, &mut pointer.horizontal);
2357    let delta_y = get_axis_scroll_delta_and_update_state(event, &mut pointer.vertical);
2358    if delta_x.is_some() || delta_y.is_some() {
2359        Some(Point::new(delta_x.unwrap_or(0.0), delta_y.unwrap_or(0.0)))
2360    } else {
2361        None
2362    }
2363}
2364
2365fn get_axis_scroll_delta_and_update_state(
2366    event: &xinput::MotionEvent,
2367    axis: &mut ScrollAxisState,
2368) -> Option<f32> {
2369    let axis_index = get_valuator_axis_index(&event.valuator_mask, axis.valuator_number?)?;
2370    if let Some(axis_value) = event.axisvalues.get(axis_index) {
2371        let new_scroll = fp3232_to_f32(*axis_value);
2372        let delta_scroll = axis
2373            .scroll_value
2374            .map(|old_scroll| (old_scroll - new_scroll) * axis.multiplier);
2375        axis.scroll_value = Some(new_scroll);
2376        delta_scroll
2377    } else {
2378        log::error!("Encountered invalid XInput valuator_mask, scrolling may not work properly.");
2379        None
2380    }
2381}
2382
2383fn make_scroll_wheel_event(
2384    position: Point<Pixels>,
2385    scroll_delta: Point<f32>,
2386    modifiers: Modifiers,
2387) -> gpui::ScrollWheelEvent {
2388    // When shift is held down, vertical scrolling turns into horizontal scrolling.
2389    let delta = if modifiers.shift {
2390        Point {
2391            x: scroll_delta.y,
2392            y: 0.0,
2393        }
2394    } else {
2395        scroll_delta
2396    };
2397    gpui::ScrollWheelEvent {
2398        position,
2399        delta: ScrollDelta::Lines(delta),
2400        modifiers,
2401        touch_phase: TouchPhase::default(),
2402    }
2403}
2404
2405fn create_invisible_cursor(
2406    connection: &XCBConnection,
2407) -> anyhow::Result<crate::linux::x11::client::xproto::Cursor> {
2408    let empty_pixmap = connection.generate_id()?;
2409    let root = connection.setup().roots[0].root;
2410    connection.create_pixmap(1, empty_pixmap, root, 1, 1)?;
2411
2412    let cursor = connection.generate_id()?;
2413    connection.create_cursor(cursor, empty_pixmap, empty_pixmap, 0, 0, 0, 0, 0, 0, 0, 0)?;
2414
2415    connection.free_pixmap(empty_pixmap)?;
2416
2417    xcb_flush(connection);
2418    Ok(cursor)
2419}
2420
2421enum DpiMode {
2422    Randr,
2423    Scale(f32),
2424    NotSet,
2425}
2426
2427fn get_scale_factor(
2428    connection: &XCBConnection,
2429    resource_database: &Database,
2430    screen_index: usize,
2431) -> f32 {
2432    let env_dpi = std::env::var(GPUI_X11_SCALE_FACTOR_ENV)
2433        .ok()
2434        .map(|var| {
2435            if var.to_lowercase() == "randr" {
2436                DpiMode::Randr
2437            } else if let Ok(scale) = var.parse::<f32>() {
2438                if valid_scale_factor(scale) {
2439                    DpiMode::Scale(scale)
2440                } else {
2441                    panic!(
2442                        "`{}` must be a positive normal number or `randr`. Got `{}`",
2443                        GPUI_X11_SCALE_FACTOR_ENV, var
2444                    );
2445                }
2446            } else if var.is_empty() {
2447                DpiMode::NotSet
2448            } else {
2449                panic!(
2450                    "`{}` must be a positive number or `randr`. Got `{}`",
2451                    GPUI_X11_SCALE_FACTOR_ENV, var
2452                );
2453            }
2454        })
2455        .unwrap_or(DpiMode::NotSet);
2456
2457    match env_dpi {
2458        DpiMode::Scale(scale) => {
2459            log::info!(
2460                "Using scale factor from {}: {}",
2461                GPUI_X11_SCALE_FACTOR_ENV,
2462                scale
2463            );
2464            return scale;
2465        }
2466        DpiMode::Randr => {
2467            if let Some(scale) = get_randr_scale_factor(connection, screen_index) {
2468                log::info!(
2469                    "Using RandR scale factor from {}=randr: {}",
2470                    GPUI_X11_SCALE_FACTOR_ENV,
2471                    scale
2472                );
2473                return scale;
2474            }
2475            log::warn!("Failed to calculate RandR scale factor, falling back to default");
2476            return 1.0;
2477        }
2478        DpiMode::NotSet => {}
2479    }
2480
2481    // TODO: Use scale factor from XSettings here
2482
2483    if let Some(dpi) = resource_database
2484        .get_value::<f32>("Xft.dpi", "Xft.dpi")
2485        .ok()
2486        .flatten()
2487    {
2488        let scale = dpi / 96.0; // base dpi
2489        log::info!("Using scale factor from Xft.dpi: {}", scale);
2490        return scale;
2491    }
2492
2493    if let Some(scale) = get_randr_scale_factor(connection, screen_index) {
2494        log::info!("Using RandR scale factor: {}", scale);
2495        return scale;
2496    }
2497
2498    log::info!("Using default scale factor: 1.0");
2499    1.0
2500}
2501
2502fn get_randr_scale_factor(connection: &XCBConnection, screen_index: usize) -> Option<f32> {
2503    let root = connection.setup().roots.get(screen_index)?.root;
2504
2505    let version_cookie = connection.randr_query_version(1, 6).ok()?;
2506    let version_reply = version_cookie.reply().ok()?;
2507    if version_reply.major_version < 1
2508        || (version_reply.major_version == 1 && version_reply.minor_version < 5)
2509    {
2510        return legacy_get_randr_scale_factor(connection, root); // for randr <1.5
2511    }
2512
2513    let monitors_cookie = connection.randr_get_monitors(root, true).ok()?; // true for active only
2514    let monitors_reply = monitors_cookie.reply().ok()?;
2515
2516    let mut fallback_scale: Option<f32> = None;
2517    for monitor in monitors_reply.monitors {
2518        if monitor.width_in_millimeters == 0 || monitor.height_in_millimeters == 0 {
2519            continue;
2520        }
2521        let scale_factor = get_dpi_factor(
2522            (monitor.width as u32, monitor.height as u32),
2523            (
2524                monitor.width_in_millimeters as u64,
2525                monitor.height_in_millimeters as u64,
2526            ),
2527        );
2528        if monitor.primary {
2529            return Some(scale_factor);
2530        } else if fallback_scale.is_none() {
2531            fallback_scale = Some(scale_factor);
2532        }
2533    }
2534
2535    fallback_scale
2536}
2537
2538fn legacy_get_randr_scale_factor(connection: &XCBConnection, root: u32) -> Option<f32> {
2539    let primary_cookie = connection.randr_get_output_primary(root).ok()?;
2540    let primary_reply = primary_cookie.reply().ok()?;
2541    let primary_output = primary_reply.output;
2542
2543    let primary_output_cookie = connection
2544        .randr_get_output_info(primary_output, x11rb::CURRENT_TIME)
2545        .ok()?;
2546    let primary_output_info = primary_output_cookie.reply().ok()?;
2547
2548    // try primary
2549    if primary_output_info.connection == randr::Connection::CONNECTED
2550        && primary_output_info.mm_width > 0
2551        && primary_output_info.mm_height > 0
2552        && primary_output_info.crtc != 0
2553    {
2554        let crtc_cookie = connection
2555            .randr_get_crtc_info(primary_output_info.crtc, x11rb::CURRENT_TIME)
2556            .ok()?;
2557        let crtc_info = crtc_cookie.reply().ok()?;
2558
2559        if crtc_info.width > 0 && crtc_info.height > 0 {
2560            let scale_factor = get_dpi_factor(
2561                (crtc_info.width as u32, crtc_info.height as u32),
2562                (
2563                    primary_output_info.mm_width as u64,
2564                    primary_output_info.mm_height as u64,
2565                ),
2566            );
2567            return Some(scale_factor);
2568        }
2569    }
2570
2571    // fallback: full scan
2572    let resources_cookie = connection.randr_get_screen_resources_current(root).ok()?;
2573    let screen_resources = resources_cookie.reply().ok()?;
2574
2575    let mut crtc_cookies = Vec::with_capacity(screen_resources.crtcs.len());
2576    for &crtc in &screen_resources.crtcs {
2577        if let Ok(cookie) = connection.randr_get_crtc_info(crtc, x11rb::CURRENT_TIME) {
2578            crtc_cookies.push((crtc, cookie));
2579        }
2580    }
2581
2582    let mut crtc_infos: HashMap<randr::Crtc, randr::GetCrtcInfoReply> = HashMap::default();
2583    let mut valid_outputs: HashSet<randr::Output> = HashSet::new();
2584    for (crtc, cookie) in crtc_cookies {
2585        if let Ok(reply) = cookie.reply()
2586            && reply.width > 0
2587            && reply.height > 0
2588            && !reply.outputs.is_empty()
2589        {
2590            crtc_infos.insert(crtc, reply.clone());
2591            valid_outputs.extend(&reply.outputs);
2592        }
2593    }
2594
2595    if valid_outputs.is_empty() {
2596        return None;
2597    }
2598
2599    let mut output_cookies = Vec::with_capacity(valid_outputs.len());
2600    for &output in &valid_outputs {
2601        if let Ok(cookie) = connection.randr_get_output_info(output, x11rb::CURRENT_TIME) {
2602            output_cookies.push((output, cookie));
2603        }
2604    }
2605    let mut output_infos: HashMap<randr::Output, randr::GetOutputInfoReply> = HashMap::default();
2606    for (output, cookie) in output_cookies {
2607        if let Ok(reply) = cookie.reply() {
2608            output_infos.insert(output, reply);
2609        }
2610    }
2611
2612    let mut fallback_scale: Option<f32> = None;
2613    for crtc_info in crtc_infos.values() {
2614        for &output in &crtc_info.outputs {
2615            if let Some(output_info) = output_infos.get(&output) {
2616                if output_info.connection != randr::Connection::CONNECTED {
2617                    continue;
2618                }
2619
2620                if output_info.mm_width == 0 || output_info.mm_height == 0 {
2621                    continue;
2622                }
2623
2624                let scale_factor = get_dpi_factor(
2625                    (crtc_info.width as u32, crtc_info.height as u32),
2626                    (output_info.mm_width as u64, output_info.mm_height as u64),
2627                );
2628
2629                if output != primary_output && fallback_scale.is_none() {
2630                    fallback_scale = Some(scale_factor);
2631                }
2632            }
2633        }
2634    }
2635
2636    fallback_scale
2637}
2638
2639fn get_dpi_factor((width_px, height_px): (u32, u32), (width_mm, height_mm): (u64, u64)) -> f32 {
2640    let ppmm = ((width_px as f64 * height_px as f64) / (width_mm as f64 * height_mm as f64)).sqrt(); // pixels per mm
2641
2642    const MM_PER_INCH: f64 = 25.4;
2643    const BASE_DPI: f64 = 96.0;
2644    const QUANTIZE_STEP: f64 = 12.0; // e.g. 1.25 = 15/12, 1.5 = 18/12, 1.75 = 21/12, 2.0 = 24/12
2645    const MIN_SCALE: f64 = 1.0;
2646    const MAX_SCALE: f64 = 20.0;
2647
2648    let dpi_factor =
2649        ((ppmm * (QUANTIZE_STEP * MM_PER_INCH / BASE_DPI)).round() / QUANTIZE_STEP).max(MIN_SCALE);
2650
2651    let validated_factor = if dpi_factor <= MAX_SCALE {
2652        dpi_factor
2653    } else {
2654        MIN_SCALE
2655    };
2656
2657    if valid_scale_factor(validated_factor as f32) {
2658        validated_factor as f32
2659    } else {
2660        log::warn!(
2661            "Calculated DPI factor {} is invalid, using 1.0",
2662            validated_factor
2663        );
2664        1.0
2665    }
2666}
2667
2668#[inline]
2669fn valid_scale_factor(scale_factor: f32) -> bool {
2670    scale_factor.is_sign_positive() && scale_factor.is_normal()
2671}
2672
2673#[inline]
2674fn xkb_state_for_key_event(xkb: &xkbc::State, event_state: xproto::KeyButMask) -> xkbc::State {
2675    let keymap = xkb.get_keymap();
2676    let mut key_event_state = xkbc::State::new(&keymap);
2677
2678    let latched_modifiers = xkb.serialize_mods(xkbc::STATE_MODS_LATCHED);
2679    let locked_modifiers = xkb.serialize_mods(xkbc::STATE_MODS_LOCKED);
2680    let active_modifier_mask: xkbc::ModMask = u16::from(
2681        event_state
2682            & (xproto::KeyButMask::SHIFT
2683                | xproto::KeyButMask::LOCK
2684                | xproto::KeyButMask::CONTROL
2685                | xproto::KeyButMask::MOD1
2686                | xproto::KeyButMask::MOD2
2687                | xproto::KeyButMask::MOD3
2688                | xproto::KeyButMask::MOD4
2689                | xproto::KeyButMask::MOD5),
2690    )
2691    .into();
2692    let depressed_modifiers = active_modifier_mask & !(latched_modifiers | locked_modifiers);
2693
2694    key_event_state.update_mask(
2695        depressed_modifiers,
2696        latched_modifiers,
2697        locked_modifiers,
2698        xkb.serialize_layout(xkbc::STATE_LAYOUT_DEPRESSED),
2699        xkb.serialize_layout(xkbc::STATE_LAYOUT_LATCHED),
2700        xkb.serialize_layout(xkbc::STATE_LAYOUT_LOCKED),
2701    );
2702
2703    key_event_state
2704}
2705
2706#[cfg(test)]
2707mod tests {
2708    use super::*;
2709
2710    fn test_keymap(layouts: &str) -> xkbc::Keymap {
2711        test_keymap_with_variant(layouts, "")
2712    }
2713
2714    fn test_keymap_with_variant(layouts: &str, variant: &str) -> xkbc::Keymap {
2715        let context = xkbc::Context::new(xkbc::CONTEXT_NO_FLAGS);
2716        xkbc::Keymap::new_from_names(
2717            &context,
2718            "",
2719            "pc105",
2720            layouts,
2721            variant,
2722            None,
2723            xkbc::COMPILE_NO_FLAGS,
2724        )
2725        .expect("test keymap should compile")
2726    }
2727
2728    // Returns a state where the second layout is active via a temporary
2729    // mechanism (holding a key down or one-shot), not a permanent toggle.
2730    fn state_with_non_locked_layout(keymap: &xkbc::Keymap) -> xkbc::State {
2731        let mut depressed_layout_state = xkbc::State::new(keymap);
2732        depressed_layout_state.update_mask(0, 0, 0, 1, 0, 0);
2733        if depressed_layout_state.serialize_layout(STATE_LAYOUT_EFFECTIVE) == 1 {
2734            return depressed_layout_state;
2735        }
2736
2737        let mut latched_layout_state = xkbc::State::new(keymap);
2738        latched_layout_state.update_mask(0, 0, 0, 0, 1, 0);
2739        if latched_layout_state.serialize_layout(STATE_LAYOUT_EFFECTIVE) == 1 {
2740            return latched_layout_state;
2741        }
2742
2743        panic!("test keymap should support a non-locked secondary layout");
2744    }
2745
2746    #[test]
2747    fn key_event_state_uses_event_modifiers_without_mutating_server_state() {
2748        let keymap = test_keymap("us");
2749        let server_state = xkbc::State::new(&keymap);
2750        // The "9" key on a US keyboard.
2751        let keycode = keymap
2752            .key_by_name("AE09")
2753            .expect("test key should exist in the keymap");
2754
2755        // Simulate pressing Shift+9 (which should produce "(").
2756        let key_event_state = xkb_state_for_key_event(&server_state, xproto::KeyButMask::SHIFT);
2757        let keystroke = keystroke_from_xkb(
2758            &key_event_state,
2759            modifiers_from_state(xproto::KeyButMask::SHIFT),
2760            keycode,
2761        );
2762
2763        // Assert Shift+9 produces "(" on US layout.
2764        assert_eq!(keystroke.key, "(");
2765        assert_eq!(keystroke.key_char.as_deref(), Some("("));
2766        // Assert the long-lived server state was not mutated by the key event.
2767        assert_eq!(server_state.key_get_utf8(keycode), "9");
2768    }
2769
2770    #[test]
2771    fn key_event_state_ignores_pointer_button_bits() {
2772        let keymap = test_keymap("us");
2773        let server_state = xkbc::State::new(&keymap);
2774        // The "9" key on a US keyboard.
2775        let keycode = keymap
2776            .key_by_name("AE09")
2777            .expect("test key should exist in the keymap");
2778
2779        // Simulate Shift held down.
2780        let shifted_state = xkb_state_for_key_event(&server_state, xproto::KeyButMask::SHIFT);
2781        // Simulate Shift held down while also clicking the left mouse button.
2782        let shifted_with_button_state = xkb_state_for_key_event(
2783            &server_state,
2784            xproto::KeyButMask::SHIFT | xproto::KeyButMask::BUTTON1,
2785        );
2786
2787        // Assert the mouse button has no effect on modifier state.
2788        assert_eq!(
2789            shifted_with_button_state.serialize_mods(xkbc::STATE_MODS_EFFECTIVE),
2790            shifted_state.serialize_mods(xkbc::STATE_MODS_EFFECTIVE)
2791        );
2792        // Assert both cases produce the same character.
2793        assert_eq!(
2794            shifted_with_button_state.key_get_utf8(keycode),
2795            shifted_state.key_get_utf8(keycode)
2796        );
2797    }
2798
2799    #[test]
2800    fn key_event_state_preserves_non_locked_layout_components() {
2801        // US + Russian dual-layout keyboard.
2802        let keymap = test_keymap("us,ru");
2803        // Simulate the Russian layout being active via a temporary layout
2804        // switch (holding a key), not a permanent toggle.
2805        let server_state = state_with_non_locked_layout(&keymap);
2806        // The "Q" key position, which produces a Cyrillic character in Russian layout.
2807        let keycode = keymap
2808            .key_by_name("AD01")
2809            .expect("test key should exist in the keymap");
2810
2811        let expected_text = server_state.key_get_utf8(keycode);
2812        let key_event_state = xkb_state_for_key_event(&server_state, xproto::KeyButMask::default());
2813
2814        // Assert the temporary layout switch is preserved.
2815        assert_eq!(
2816            key_event_state.serialize_layout(STATE_LAYOUT_EFFECTIVE),
2817            server_state.serialize_layout(STATE_LAYOUT_EFFECTIVE)
2818        );
2819        // Assert the key produces the same character as expected from the
2820        // Russian layout.
2821        assert_eq!(key_event_state.key_get_utf8(keycode), expected_text);
2822    }
2823
2824    // https://github.com/zed-industries/zed/issues/14282
2825    #[test]
2826    fn capslock_toggle_produces_uppercase() {
2827        let keymap = test_keymap("us");
2828        let mut server_state = xkbc::State::new(&keymap);
2829        // The "A" key position on a US keyboard.
2830        let keycode = keymap
2831            .key_by_name("AC01")
2832            .expect("'a' key should exist in the keymap");
2833
2834        // Simulate the user having toggled CapsLock on (it's now permanently
2835        // active until pressed again).
2836        let lock_mod = u16::from(xproto::KeyButMask::LOCK) as xkbc::ModMask;
2837        server_state.update_mask(0, 0, lock_mod, 0, 0, 0);
2838
2839        // Simulate pressing the "a" key while CapsLock is on.
2840        let key_event_state = xkb_state_for_key_event(&server_state, xproto::KeyButMask::LOCK);
2841
2842        // Assert CapsLock is treated as a toggle (locked), not as a held key
2843        // (depressed). This distinction matters because XKB only applies
2844        // capitalization when CapsLock is in the "locked" state.
2845        assert_eq!(
2846            key_event_state.serialize_mods(xkbc::STATE_MODS_LOCKED) & lock_mod,
2847            lock_mod,
2848        );
2849        // Assert typing "a" with CapsLock on produces "A".
2850        assert_eq!(key_event_state.key_get_utf8(keycode), "A");
2851    }
2852
2853    // https://github.com/zed-industries/zed/issues/14282
2854    #[test]
2855    fn neo2_level3_via_capslock_produces_ellipsis() {
2856        // Neo 2 is a German keyboard layout that repurposes CapsLock as a
2857        // "level 3" modifier key for accessing additional characters.
2858        let keymap = test_keymap_with_variant("de", "neo");
2859        let server_state = xkbc::State::new(&keymap);
2860        // The key in the "Q" position, which produces "x" on Neo 2 base layer.
2861        let keycode = keymap
2862            .key_by_name("AD01")
2863            .expect("test key should exist in the keymap");
2864
2865        // Simulate holding CapsLock, which in Neo 2 activates the "level 3"
2866        // layer (mapped to the Mod5 modifier internally).
2867        let key_event_state = xkb_state_for_key_event(&server_state, xproto::KeyButMask::MOD5);
2868
2869        // Assert holding CapsLock + pressing the "x" key produces "..."
2870        // (ellipsis), which is the level 3 character on that key in Neo 2.
2871        assert_eq!(key_event_state.key_get_utf8(keycode), "\u{2026}");
2872    }
2873
2874    // https://github.com/zed-industries/zed/issues/14282
2875    #[test]
2876    fn neo2_latched_mod5_preserved() {
2877        // Neo 2 also supports "latching" the level 3 modifier (via Caps+Tab),
2878        // which activates it for only the next keypress and then deactivates.
2879        let keymap = test_keymap_with_variant("de", "neo");
2880        let mut server_state = xkbc::State::new(&keymap);
2881        let keycode = keymap
2882            .key_by_name("AD01")
2883            .expect("test key should exist in the keymap");
2884
2885        // Simulate the level 3 modifier being latched (one-shot active).
2886        let mod5 = u16::from(xproto::KeyButMask::MOD5) as xkbc::ModMask;
2887        server_state.update_mask(0, mod5, 0, 0, 0, 0);
2888
2889        let key_event_state = xkb_state_for_key_event(&server_state, xproto::KeyButMask::MOD5);
2890
2891        // Assert the modifier stays classified as "latched" (one-shot) rather
2892        // than being reclassified as "depressed" (held down). This matters
2893        // because latched modifiers auto-deactivate after one keypress.
2894        assert_eq!(
2895            key_event_state.serialize_mods(xkbc::STATE_MODS_LATCHED) & mod5,
2896            mod5,
2897        );
2898        // Assert the latched level 3 still produces the ellipsis character.
2899        assert_eq!(key_event_state.key_get_utf8(keycode), "\u{2026}");
2900    }
2901
2902    // https://github.com/zed-industries/zed/pull/31193
2903    #[test]
2904    fn german_layout_correct_key_resolution() {
2905        // Standard German keyboard layout.
2906        let keymap = test_keymap("de");
2907        let server_state = xkbc::State::new(&keymap);
2908        // The "7" key on the number row.
2909        let keycode = keymap
2910            .key_by_name("AE07")
2911            .expect("'7' key should exist in the keymap");
2912
2913        let key_event_state = xkb_state_for_key_event(&server_state, xproto::KeyButMask::default());
2914
2915        // Assert pressing the "7" key on a German layout produces "7".
2916        assert_eq!(key_event_state.key_get_utf8(keycode), "7");
2917    }
2918
2919    // https://github.com/zed-industries/zed/issues/26468
2920    // https://github.com/zed-industries/zed/issues/16667
2921    #[test]
2922    fn space_works_with_cyrillic_layout_active() {
2923        // US + Russian dual-layout keyboard.
2924        let keymap = test_keymap("us,ru");
2925        let mut server_state = xkbc::State::new(&keymap);
2926        let space = keymap
2927            .key_by_name("SPCE")
2928            .expect("space key should exist in the keymap");
2929
2930        // Simulate the user having switched to the Russian layout
2931        // (e.g. via a keyboard shortcut like Super+Space).
2932        server_state.update_mask(0, 0, 0, 0, 0, 1);
2933
2934        let key_event_state = xkb_state_for_key_event(&server_state, xproto::KeyButMask::default());
2935
2936        // Assert the Russian layout is still active after constructing the
2937        // key event state (not accidentally reset to US).
2938        assert_eq!(key_event_state.serialize_layout(STATE_LAYOUT_EFFECTIVE), 1);
2939        // Assert pressing space while on the Russian layout still types a space.
2940        assert_eq!(key_event_state.key_get_utf8(space), " ");
2941    }
2942
2943    // https://github.com/zed-industries/zed/issues/40678
2944    #[test]
2945    fn macro_shift_bracket_produces_brace() {
2946        let keymap = test_keymap("us");
2947        let server_state = xkbc::State::new(&keymap);
2948        // The "]" key on a US keyboard.
2949        let bracket = keymap
2950            .key_by_name("AD12")
2951            .expect("']' key should exist in the keymap");
2952
2953        // Simulate a keyboard macro (e.g. from a ZMK/QMK firmware keyboard)
2954        // that sends Shift + "]" very rapidly. The modifier state notification
2955        // for Shift hasn't reached us yet, so the server state has no
2956        // modifiers. But the key event itself carries the correct Shift state.
2957        assert_eq!(server_state.serialize_mods(xkbc::STATE_MODS_EFFECTIVE), 0);
2958        let key_event_state = xkb_state_for_key_event(&server_state, xproto::KeyButMask::SHIFT);
2959
2960        // Assert Shift+"]" produces "}" even when the Shift notification
2961        // arrived late.
2962        assert_eq!(key_event_state.key_get_utf8(bracket), "}");
2963    }
2964
2965    // https://github.com/zed-industries/zed/issues/49329
2966    #[test]
2967    fn sequential_key_events_do_not_corrupt_state() {
2968        let keymap = test_keymap("us");
2969        let server_state = xkbc::State::new(&keymap);
2970
2971        // Simulate typing "a s d" with spaces in between, all without any
2972        // modifier keys held.
2973        let keys: &[(&str, &str)] = &[
2974            ("AC01", "a"),
2975            ("SPCE", " "),
2976            ("AC02", "s"),
2977            ("SPCE", " "),
2978            ("AC03", "d"),
2979        ];
2980
2981        for &(key_name, expected_utf8) in keys {
2982            let keycode = keymap
2983                .key_by_name(key_name)
2984                .expect("test key should exist in the keymap");
2985
2986            let key_event_state =
2987                xkb_state_for_key_event(&server_state, xproto::KeyButMask::default());
2988
2989            // Assert each key in the sequence produces the expected character
2990            // (no dropped or garbled input from state corruption).
2991            assert_eq!(
2992                key_event_state.key_get_utf8(keycode),
2993                expected_utf8,
2994                "key {key_name} should produce {expected_utf8:?}",
2995            );
2996        }
2997
2998        // Assert the server state is completely untouched after processing
2999        // all key events.
3000        assert_eq!(server_state.serialize_mods(xkbc::STATE_MODS_EFFECTIVE), 0);
3001        assert_eq!(server_state.serialize_layout(STATE_LAYOUT_EFFECTIVE), 0);
3002    }
3003
3004    // https://github.com/zed-industries/zed/issues/26468
3005    #[test]
3006    fn space_works_with_czech_layout_active() {
3007        // US + Czech dual-layout keyboard.
3008        let keymap = test_keymap("us,cz");
3009        let mut server_state = xkbc::State::new(&keymap);
3010        let space = keymap
3011            .key_by_name("SPCE")
3012            .expect("space key should exist in the keymap");
3013
3014        // Simulate the user having switched to the Czech layout.
3015        server_state.update_mask(0, 0, 0, 0, 0, 1);
3016
3017        let key_event_state = xkb_state_for_key_event(&server_state, xproto::KeyButMask::default());
3018
3019        // Assert pressing space while on the Czech layout still types a space.
3020        assert_eq!(key_event_state.key_get_utf8(space), " ");
3021    }
3022}