client.rs

   1use anyhow::{Context as _, anyhow};
   2use ashpd::WindowIdentifier;
   3use calloop::{
   4    EventLoop, LoopHandle, RegistrationToken,
   5    generic::{FdWrapper, Generic},
   6};
   7use collections::HashMap;
   8use core::str;
   9use gpui::{Capslock, TaskTiming, profiler};
  10use http_client::Url;
  11use log::Level;
  12use smallvec::SmallVec;
  13use std::{
  14    cell::RefCell,
  15    collections::{BTreeMap, HashSet},
  16    ops::Deref,
  17    path::PathBuf,
  18    rc::{Rc, Weak},
  19    time::{Duration, Instant},
  20};
  21use util::ResultExt as _;
  22
  23use x11rb::{
  24    connection::{Connection, RequestConnection},
  25    cursor,
  26    errors::ConnectionError,
  27    protocol::randr::ConnectionExt as _,
  28    protocol::xinput::ConnectionExt,
  29    protocol::xkb::ConnectionExt as _,
  30    protocol::xproto::{
  31        AtomEnum, ChangeWindowAttributesAux, ClientMessageData, ClientMessageEvent,
  32        ConnectionExt as _, EventMask, ModMask, Visibility,
  33    },
  34    protocol::{Event, dri3, randr, render, xinput, xkb, xproto},
  35    resource_manager::Database,
  36    wrapper::ConnectionExt as _,
  37    xcb_ffi::XCBConnection,
  38};
  39use xim::{AttributeName, Client, InputStyle, x11rb::X11rbClient};
  40use xkbc::x11::ffi::{XKB_X11_MIN_MAJOR_XKB_VERSION, XKB_X11_MIN_MINOR_XKB_VERSION};
  41use xkbcommon::xkb::{self as xkbc, STATE_LAYOUT_EFFECTIVE};
  42
  43use super::{
  44    ButtonOrScroll, ScrollDirection, X11Display, X11WindowStatePtr, XcbAtoms, XimCallbackEvent,
  45    XimHandler, button_or_scroll_from_event_detail, check_reply,
  46    clipboard::{self, Clipboard},
  47    get_reply, get_valuator_axis_index, handle_connection_error, modifiers_from_state,
  48    pressed_button_from_mask, xcb_flush,
  49};
  50
  51use crate::linux::{
  52    DEFAULT_CURSOR_ICON_NAME, LinuxClient, capslock_from_xkb, cursor_style_to_icon_names,
  53    get_xkb_compose_state, is_within_click_distance, keystroke_from_xkb,
  54    keystroke_underlying_dead_key, log_cursor_icon_warning, modifiers_from_xkb, open_uri_internal,
  55    platform::{DOUBLE_CLICK_INTERVAL, SCROLL_LINES},
  56    reveal_path_internal,
  57    xdg_desktop_portal::{Event as XDPEvent, XDPEventSource},
  58};
  59use crate::linux::{LinuxCommon, LinuxKeyboardLayout, X11Window, modifiers_from_xinput_info};
  60
  61use gpui::{
  62    AnyWindowHandle, Bounds, ClipboardItem, CursorStyle, DisplayId, FileDropEvent, Keystroke,
  63    Modifiers, ModifiersChangedEvent, MouseButton, Pixels, PlatformDisplay, PlatformInput,
  64    PlatformKeyboardLayout, PlatformWindow, Point, RequestFrameOptions, ScrollDelta, Size,
  65    TouchPhase, 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
1038                // Macros containing modifiers might result in
1039                // the modifiers missing from the event.
1040                // We therefore update the mask from the global state.
1041                update_xkb_mask_from_event_state(&mut state.xkb, event.state);
1042
1043                let keystroke = {
1044                    let code = event.detail.into();
1045                    let mut keystroke = keystroke_from_xkb(&state.xkb, modifiers, code);
1046                    let keysym = state.xkb.key_get_one_sym(code);
1047
1048                    if keysym.is_modifier_key() {
1049                        return Some(());
1050                    }
1051
1052                    // should be called after key_get_one_sym
1053                    state.xkb.update_key(code, xkbc::KeyDirection::Down);
1054
1055                    if let Some(mut compose_state) = state.compose_state.take() {
1056                        compose_state.feed(keysym);
1057                        match compose_state.status() {
1058                            xkbc::Status::Composed => {
1059                                state.pre_edit_text.take();
1060                                keystroke.key_char = compose_state.utf8();
1061                                if let Some(keysym) = compose_state.keysym() {
1062                                    keystroke.key = xkbc::keysym_get_name(keysym);
1063                                }
1064                            }
1065                            xkbc::Status::Composing => {
1066                                keystroke.key_char = None;
1067                                state.pre_edit_text = compose_state
1068                                    .utf8()
1069                                    .or(keystroke_underlying_dead_key(keysym));
1070                                let pre_edit =
1071                                    state.pre_edit_text.clone().unwrap_or(String::default());
1072                                drop(state);
1073                                window.handle_ime_preedit(pre_edit);
1074                                state = self.0.borrow_mut();
1075                            }
1076                            xkbc::Status::Cancelled => {
1077                                let pre_edit = state.pre_edit_text.take();
1078                                drop(state);
1079                                if let Some(pre_edit) = pre_edit {
1080                                    window.handle_ime_commit(pre_edit);
1081                                }
1082                                if let Some(current_key) = keystroke_underlying_dead_key(keysym) {
1083                                    window.handle_ime_preedit(current_key);
1084                                }
1085                                state = self.0.borrow_mut();
1086                                compose_state.feed(keysym);
1087                            }
1088                            _ => {}
1089                        }
1090                        state.compose_state = Some(compose_state);
1091                    }
1092                    keystroke
1093                };
1094                drop(state);
1095                window.handle_input(PlatformInput::KeyDown(gpui::KeyDownEvent {
1096                    keystroke,
1097                    is_held: false,
1098                    prefer_character_input: false,
1099                }));
1100            }
1101            Event::KeyRelease(event) => {
1102                let window = self.get_window(event.event)?;
1103                let mut state = self.0.borrow_mut();
1104
1105                let modifiers = modifiers_from_state(event.state);
1106                state.modifiers = modifiers;
1107
1108                // Macros containing modifiers might result in
1109                // the modifiers missing from the event.
1110                // We therefore update the mask from the global state.
1111                update_xkb_mask_from_event_state(&mut state.xkb, event.state);
1112
1113                let keystroke = {
1114                    let code = event.detail.into();
1115                    let keystroke = keystroke_from_xkb(&state.xkb, modifiers, code);
1116                    let keysym = state.xkb.key_get_one_sym(code);
1117
1118                    if keysym.is_modifier_key() {
1119                        return Some(());
1120                    }
1121
1122                    // should be called after key_get_one_sym
1123                    state.xkb.update_key(code, xkbc::KeyDirection::Up);
1124
1125                    keystroke
1126                };
1127                drop(state);
1128                window.handle_input(PlatformInput::KeyUp(gpui::KeyUpEvent { keystroke }));
1129            }
1130            Event::XinputButtonPress(event) => {
1131                let window = self.get_window(event.event)?;
1132                let mut state = self.0.borrow_mut();
1133
1134                let modifiers = modifiers_from_xinput_info(event.mods);
1135                state.modifiers = modifiers;
1136
1137                let position = point(
1138                    px(event.event_x as f32 / u16::MAX as f32 / state.scale_factor),
1139                    px(event.event_y as f32 / u16::MAX as f32 / state.scale_factor),
1140                );
1141
1142                if state.composing && state.ximc.is_some() {
1143                    drop(state);
1144                    self.reset_ime();
1145                    window.handle_ime_unmark();
1146                    state = self.0.borrow_mut();
1147                } else if let Some(text) = state.pre_edit_text.take() {
1148                    if let Some(compose_state) = state.compose_state.as_mut() {
1149                        compose_state.reset();
1150                    }
1151                    drop(state);
1152                    window.handle_ime_commit(text);
1153                    state = self.0.borrow_mut();
1154                }
1155                match button_or_scroll_from_event_detail(event.detail) {
1156                    Some(ButtonOrScroll::Button(button)) => {
1157                        let click_elapsed = state.last_click.elapsed();
1158                        if click_elapsed < DOUBLE_CLICK_INTERVAL
1159                            && state
1160                                .last_mouse_button
1161                                .is_some_and(|prev_button| prev_button == button)
1162                            && is_within_click_distance(state.last_location, position)
1163                        {
1164                            state.current_count += 1;
1165                        } else {
1166                            state.current_count = 1;
1167                        }
1168
1169                        state.last_click = Instant::now();
1170                        state.last_mouse_button = Some(button);
1171                        state.last_location = position;
1172                        let current_count = state.current_count;
1173
1174                        drop(state);
1175                        window.handle_input(PlatformInput::MouseDown(gpui::MouseDownEvent {
1176                            button,
1177                            position,
1178                            modifiers,
1179                            click_count: current_count,
1180                            first_mouse: false,
1181                        }));
1182                    }
1183                    Some(ButtonOrScroll::Scroll(direction)) => {
1184                        drop(state);
1185                        // Emulated scroll button presses are sent simultaneously with smooth scrolling XinputMotion events.
1186                        // Since handling those events does the scrolling, they are skipped here.
1187                        if !event
1188                            .flags
1189                            .contains(xinput::PointerEventFlags::POINTER_EMULATED)
1190                        {
1191                            let scroll_delta = match direction {
1192                                ScrollDirection::Up => Point::new(0.0, SCROLL_LINES),
1193                                ScrollDirection::Down => Point::new(0.0, -SCROLL_LINES),
1194                                ScrollDirection::Left => Point::new(SCROLL_LINES, 0.0),
1195                                ScrollDirection::Right => Point::new(-SCROLL_LINES, 0.0),
1196                            };
1197                            window.handle_input(PlatformInput::ScrollWheel(
1198                                make_scroll_wheel_event(position, scroll_delta, modifiers),
1199                            ));
1200                        }
1201                    }
1202                    None => {
1203                        log::error!("Unknown x11 button: {}", event.detail);
1204                    }
1205                }
1206            }
1207            Event::XinputButtonRelease(event) => {
1208                let window = self.get_window(event.event)?;
1209                let mut state = self.0.borrow_mut();
1210                let modifiers = modifiers_from_xinput_info(event.mods);
1211                state.modifiers = modifiers;
1212
1213                let position = point(
1214                    px(event.event_x as f32 / u16::MAX as f32 / state.scale_factor),
1215                    px(event.event_y as f32 / u16::MAX as f32 / state.scale_factor),
1216                );
1217                match button_or_scroll_from_event_detail(event.detail) {
1218                    Some(ButtonOrScroll::Button(button)) => {
1219                        let click_count = state.current_count;
1220                        drop(state);
1221                        window.handle_input(PlatformInput::MouseUp(gpui::MouseUpEvent {
1222                            button,
1223                            position,
1224                            modifiers,
1225                            click_count,
1226                        }));
1227                    }
1228                    Some(ButtonOrScroll::Scroll(_)) => {}
1229                    None => {}
1230                }
1231            }
1232            Event::XinputMotion(event) => {
1233                let window = self.get_window(event.event)?;
1234                let mut state = self.0.borrow_mut();
1235                if window.is_blocked() {
1236                    // We want to set the cursor to the default arrow
1237                    // when the window is blocked
1238                    let style = CursorStyle::Arrow;
1239
1240                    let current_style = state
1241                        .cursor_styles
1242                        .get(&window.x_window)
1243                        .unwrap_or(&CursorStyle::Arrow);
1244                    if *current_style != style
1245                        && let Some(cursor) = state.get_cursor_icon(style)
1246                    {
1247                        state.cursor_styles.insert(window.x_window, style);
1248                        check_reply(
1249                            || "Failed to set cursor style",
1250                            state.xcb_connection.change_window_attributes(
1251                                window.x_window,
1252                                &ChangeWindowAttributesAux {
1253                                    cursor: Some(cursor),
1254                                    ..Default::default()
1255                                },
1256                            ),
1257                        )
1258                        .log_err();
1259                        state.xcb_connection.flush().log_err();
1260                    };
1261                }
1262                let pressed_button = pressed_button_from_mask(event.button_mask[0]);
1263                let position = point(
1264                    px(event.event_x as f32 / u16::MAX as f32 / state.scale_factor),
1265                    px(event.event_y as f32 / u16::MAX as f32 / state.scale_factor),
1266                );
1267                let modifiers = modifiers_from_xinput_info(event.mods);
1268                state.modifiers = modifiers;
1269                drop(state);
1270
1271                if event.valuator_mask[0] & 3 != 0 {
1272                    window.handle_input(PlatformInput::MouseMove(gpui::MouseMoveEvent {
1273                        position,
1274                        pressed_button,
1275                        modifiers,
1276                    }));
1277                }
1278
1279                state = self.0.borrow_mut();
1280                if let Some(pointer) = state.pointer_device_states.get_mut(&event.sourceid) {
1281                    let scroll_delta = get_scroll_delta_and_update_state(pointer, &event);
1282                    drop(state);
1283                    if let Some(scroll_delta) = scroll_delta {
1284                        window.handle_input(PlatformInput::ScrollWheel(make_scroll_wheel_event(
1285                            position,
1286                            scroll_delta,
1287                            modifiers,
1288                        )));
1289                    }
1290                }
1291            }
1292            Event::XinputEnter(event) if event.mode == xinput::NotifyMode::NORMAL => {
1293                let window = self.get_window(event.event)?;
1294                window.set_hovered(true);
1295                let mut state = self.0.borrow_mut();
1296                state.mouse_focused_window = Some(event.event);
1297            }
1298            Event::XinputLeave(event) if event.mode == xinput::NotifyMode::NORMAL => {
1299                let mut state = self.0.borrow_mut();
1300
1301                // 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)
1302                reset_all_pointer_device_scroll_positions(&mut state.pointer_device_states);
1303                state.mouse_focused_window = None;
1304                let pressed_button = pressed_button_from_mask(event.buttons[0]);
1305                let position = point(
1306                    px(event.event_x as f32 / u16::MAX as f32 / state.scale_factor),
1307                    px(event.event_y as f32 / u16::MAX as f32 / state.scale_factor),
1308                );
1309                let modifiers = modifiers_from_xinput_info(event.mods);
1310                state.modifiers = modifiers;
1311                drop(state);
1312
1313                let window = self.get_window(event.event)?;
1314                window.handle_input(PlatformInput::MouseExited(gpui::MouseExitEvent {
1315                    pressed_button,
1316                    position,
1317                    modifiers,
1318                }));
1319                window.set_hovered(false);
1320            }
1321            Event::XinputHierarchy(event) => {
1322                let mut state = self.0.borrow_mut();
1323                // Temporarily use `state.pointer_device_states` to only store pointers that still have valid scroll values.
1324                // Any change to a device invalidates its scroll values.
1325                for info in event.infos {
1326                    if is_pointer_device(info.type_) {
1327                        state.pointer_device_states.remove(&info.deviceid);
1328                    }
1329                }
1330                if let Some(pointer_device_states) = current_pointer_device_states(
1331                    &state.xcb_connection,
1332                    &state.pointer_device_states,
1333                ) {
1334                    state.pointer_device_states = pointer_device_states;
1335                }
1336            }
1337            Event::XinputDeviceChanged(event) => {
1338                let mut state = self.0.borrow_mut();
1339                if let Some(pointer) = state.pointer_device_states.get_mut(&event.sourceid) {
1340                    reset_pointer_device_scroll_positions(pointer);
1341                }
1342            }
1343            Event::XinputGesturePinchBegin(event) => {
1344                let window = self.get_window(event.event)?;
1345                let mut state = self.0.borrow_mut();
1346                state.pinch_scale = 1.0;
1347                let modifiers = modifiers_from_xinput_info(event.mods);
1348                state.modifiers = modifiers;
1349                let position = point(
1350                    px(event.event_x as f32 / u16::MAX as f32 / state.scale_factor),
1351                    px(event.event_y as f32 / u16::MAX as f32 / state.scale_factor),
1352                );
1353                drop(state);
1354                window.handle_input(PlatformInput::Pinch(gpui::PinchEvent {
1355                    position,
1356                    delta: 0.0,
1357                    modifiers,
1358                    phase: gpui::TouchPhase::Started,
1359                }));
1360            }
1361            Event::XinputGesturePinchUpdate(event) => {
1362                let window = self.get_window(event.event)?;
1363                let mut state = self.0.borrow_mut();
1364                let modifiers = modifiers_from_xinput_info(event.mods);
1365                state.modifiers = modifiers;
1366                let position = point(
1367                    px(event.event_x as f32 / u16::MAX as f32 / state.scale_factor),
1368                    px(event.event_y as f32 / u16::MAX as f32 / state.scale_factor),
1369                );
1370                // scale is in FP16.16 format: divide by 65536 to get the float value
1371                let new_absolute_scale = event.scale as f32 / 65536.0;
1372                let previous_scale = state.pinch_scale;
1373                let zoom_delta = new_absolute_scale - previous_scale;
1374                state.pinch_scale = new_absolute_scale;
1375                drop(state);
1376                window.handle_input(PlatformInput::Pinch(gpui::PinchEvent {
1377                    position,
1378                    delta: zoom_delta,
1379                    modifiers,
1380                    phase: gpui::TouchPhase::Moved,
1381                }));
1382            }
1383            Event::XinputGesturePinchEnd(event) => {
1384                let window = self.get_window(event.event)?;
1385                let mut state = self.0.borrow_mut();
1386                state.pinch_scale = 1.0;
1387                let modifiers = modifiers_from_xinput_info(event.mods);
1388                state.modifiers = modifiers;
1389                let position = point(
1390                    px(event.event_x as f32 / u16::MAX as f32 / state.scale_factor),
1391                    px(event.event_y as f32 / u16::MAX as f32 / state.scale_factor),
1392                );
1393                drop(state);
1394                window.handle_input(PlatformInput::Pinch(gpui::PinchEvent {
1395                    position,
1396                    delta: 0.0,
1397                    modifiers,
1398                    phase: gpui::TouchPhase::Ended,
1399                }));
1400            }
1401            _ => {}
1402        };
1403
1404        Some(())
1405    }
1406
1407    fn handle_xim_callback_event(&self, event: XimCallbackEvent) {
1408        match event {
1409            XimCallbackEvent::XimXEvent(event) => {
1410                self.handle_event(event);
1411            }
1412            XimCallbackEvent::XimCommitEvent(window, text) => {
1413                self.xim_handle_commit(window, text);
1414            }
1415            XimCallbackEvent::XimPreeditEvent(window, text) => {
1416                self.xim_handle_preedit(window, text);
1417            }
1418        };
1419    }
1420
1421    fn xim_handle_event(&self, event: Event) -> Option<()> {
1422        match event {
1423            Event::KeyPress(event) | Event::KeyRelease(event) => {
1424                let mut state = self.0.borrow_mut();
1425                state.pre_key_char_down = Some(keystroke_from_xkb(
1426                    &state.xkb,
1427                    state.modifiers,
1428                    event.detail.into(),
1429                ));
1430                let (mut ximc, mut xim_handler) = state.take_xim()?;
1431                drop(state);
1432                xim_handler.window = event.event;
1433                ximc.forward_event(
1434                    xim_handler.im_id,
1435                    xim_handler.ic_id,
1436                    xim::ForwardEventFlag::empty(),
1437                    &event,
1438                )
1439                .context("X11: Failed to forward XIM event")
1440                .log_err();
1441                let mut state = self.0.borrow_mut();
1442                state.restore_xim(ximc, xim_handler);
1443                drop(state);
1444            }
1445            event => {
1446                self.handle_event(event);
1447            }
1448        }
1449        Some(())
1450    }
1451
1452    fn xim_handle_commit(&self, window: xproto::Window, text: String) -> Option<()> {
1453        let Some(window) = self.get_window(window) else {
1454            log::error!("bug: Failed to get window for XIM commit");
1455            return None;
1456        };
1457        let mut state = self.0.borrow_mut();
1458        state.composing = false;
1459        drop(state);
1460        window.handle_ime_commit(text);
1461        Some(())
1462    }
1463
1464    fn xim_handle_preedit(&self, window: xproto::Window, text: String) -> Option<()> {
1465        let Some(window) = self.get_window(window) else {
1466            log::error!("bug: Failed to get window for XIM preedit");
1467            return None;
1468        };
1469
1470        let mut state = self.0.borrow_mut();
1471        let (mut ximc, xim_handler) = state.take_xim()?;
1472        state.composing = !text.is_empty();
1473        drop(state);
1474        window.handle_ime_preedit(text);
1475
1476        if let Some(scaled_area) = window.get_ime_area() {
1477            let ic_attributes = ximc
1478                .build_ic_attributes()
1479                .push(
1480                    xim::AttributeName::InputStyle,
1481                    xim::InputStyle::PREEDIT_CALLBACKS,
1482                )
1483                .push(xim::AttributeName::ClientWindow, xim_handler.window)
1484                .push(xim::AttributeName::FocusWindow, xim_handler.window)
1485                .nested_list(xim::AttributeName::PreeditAttributes, |b| {
1486                    b.push(
1487                        xim::AttributeName::SpotLocation,
1488                        xim::Point {
1489                            x: u32::from(scaled_area.origin.x + scaled_area.size.width) as i16,
1490                            y: u32::from(scaled_area.origin.y + scaled_area.size.height) as i16,
1491                        },
1492                    );
1493                })
1494                .build();
1495            ximc.set_ic_values(xim_handler.im_id, xim_handler.ic_id, ic_attributes)
1496                .ok();
1497        }
1498        let mut state = self.0.borrow_mut();
1499        state.restore_xim(ximc, xim_handler);
1500        drop(state);
1501        Some(())
1502    }
1503
1504    fn handle_keyboard_layout_change(&self) {
1505        let mut state = self.0.borrow_mut();
1506        let layout_idx = state.xkb.serialize_layout(STATE_LAYOUT_EFFECTIVE);
1507        let keymap = state.xkb.get_keymap();
1508        let layout_name = keymap.layout_get_name(layout_idx);
1509        if layout_name != state.keyboard_layout.name() {
1510            state.keyboard_layout = LinuxKeyboardLayout::new(layout_name.to_string().into());
1511            if let Some(mut callback) = state.common.callbacks.keyboard_layout_change.take() {
1512                drop(state);
1513                callback();
1514                state = self.0.borrow_mut();
1515                state.common.callbacks.keyboard_layout_change = Some(callback);
1516            }
1517        }
1518    }
1519}
1520
1521impl LinuxClient for X11Client {
1522    fn compositor_name(&self) -> &'static str {
1523        "X11"
1524    }
1525
1526    fn with_common<R>(&self, f: impl FnOnce(&mut LinuxCommon) -> R) -> R {
1527        f(&mut self.0.borrow_mut().common)
1528    }
1529
1530    fn keyboard_layout(&self) -> Box<dyn PlatformKeyboardLayout> {
1531        let state = self.0.borrow();
1532        Box::new(state.keyboard_layout.clone())
1533    }
1534
1535    fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
1536        let state = self.0.borrow();
1537        let setup = state.xcb_connection.setup();
1538        setup
1539            .roots
1540            .iter()
1541            .enumerate()
1542            .filter_map(|(root_id, _)| {
1543                Some(Rc::new(
1544                    X11Display::new(&state.xcb_connection, state.scale_factor, root_id).ok()?,
1545                ) as Rc<dyn PlatformDisplay>)
1546            })
1547            .collect()
1548    }
1549
1550    fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
1551        let state = self.0.borrow();
1552        X11Display::new(
1553            &state.xcb_connection,
1554            state.scale_factor,
1555            state.x_root_index,
1556        )
1557        .log_err()
1558        .map(|display| Rc::new(display) as Rc<dyn PlatformDisplay>)
1559    }
1560
1561    fn display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>> {
1562        let state = self.0.borrow();
1563
1564        Some(Rc::new(
1565            X11Display::new(
1566                &state.xcb_connection,
1567                state.scale_factor,
1568                u32::from(id) as usize,
1569            )
1570            .ok()?,
1571        ))
1572    }
1573
1574    #[cfg(feature = "screen-capture")]
1575    fn is_screen_capture_supported(&self) -> bool {
1576        true
1577    }
1578
1579    #[cfg(feature = "screen-capture")]
1580    fn screen_capture_sources(
1581        &self,
1582    ) -> futures::channel::oneshot::Receiver<anyhow::Result<Vec<Rc<dyn gpui::ScreenCaptureSource>>>>
1583    {
1584        gpui::scap_screen_capture::scap_screen_sources(&self.0.borrow().common.foreground_executor)
1585    }
1586
1587    fn open_window(
1588        &self,
1589        handle: AnyWindowHandle,
1590        params: WindowParams,
1591    ) -> anyhow::Result<Box<dyn PlatformWindow>> {
1592        let mut state = self.0.borrow_mut();
1593        let parent_window = state
1594            .keyboard_focused_window
1595            .and_then(|focused_window| state.windows.get(&focused_window))
1596            .map(|w| w.window.clone());
1597        let x_window = state
1598            .xcb_connection
1599            .generate_id()
1600            .context("X11: Failed to generate window ID")?;
1601
1602        let xcb_connection = state.xcb_connection.clone();
1603        let client_side_decorations_supported = state.client_side_decorations_supported;
1604        let x_root_index = state.x_root_index;
1605        let atoms = state.atoms;
1606        let scale_factor = state.scale_factor;
1607        let appearance = state.common.appearance;
1608        let compositor_gpu = state.compositor_gpu.take();
1609        let supports_xinput_gestures = state.supports_xinput_gestures;
1610        let window = X11Window::new(
1611            handle,
1612            X11ClientStatePtr(Rc::downgrade(&self.0)),
1613            state.common.foreground_executor.clone(),
1614            state.gpu_context.clone(),
1615            compositor_gpu,
1616            params,
1617            &xcb_connection,
1618            client_side_decorations_supported,
1619            x_root_index,
1620            x_window,
1621            &atoms,
1622            scale_factor,
1623            appearance,
1624            parent_window,
1625            supports_xinput_gestures,
1626        )?;
1627        check_reply(
1628            || "Failed to set XdndAware property",
1629            state.xcb_connection.change_property32(
1630                xproto::PropMode::REPLACE,
1631                x_window,
1632                state.atoms.XdndAware,
1633                state.atoms.XA_ATOM,
1634                &[5],
1635            ),
1636        )
1637        .log_err();
1638        xcb_flush(&state.xcb_connection);
1639
1640        let window_ref = WindowRef {
1641            window: window.0.clone(),
1642            refresh_state: None,
1643            expose_event_received: false,
1644            last_visibility: Visibility::UNOBSCURED,
1645            is_mapped: false,
1646        };
1647
1648        state.windows.insert(x_window, window_ref);
1649        Ok(Box::new(window))
1650    }
1651
1652    fn set_cursor_style(&self, style: CursorStyle) {
1653        let mut state = self.0.borrow_mut();
1654        let Some(focused_window) = state.mouse_focused_window else {
1655            return;
1656        };
1657        let current_style = state
1658            .cursor_styles
1659            .get(&focused_window)
1660            .unwrap_or(&CursorStyle::Arrow);
1661
1662        let window = state
1663            .mouse_focused_window
1664            .and_then(|w| state.windows.get(&w));
1665
1666        let should_change = *current_style != style
1667            && (window.is_none() || window.is_some_and(|w| !w.is_blocked()));
1668
1669        if !should_change {
1670            return;
1671        }
1672
1673        let Some(cursor) = state.get_cursor_icon(style) else {
1674            return;
1675        };
1676
1677        state.cursor_styles.insert(focused_window, style);
1678        check_reply(
1679            || "Failed to set cursor style",
1680            state.xcb_connection.change_window_attributes(
1681                focused_window,
1682                &ChangeWindowAttributesAux {
1683                    cursor: Some(cursor),
1684                    ..Default::default()
1685                },
1686            ),
1687        )
1688        .log_err();
1689        state.xcb_connection.flush().log_err();
1690    }
1691
1692    fn open_uri(&self, uri: &str) {
1693        #[cfg(any(feature = "wayland", feature = "x11"))]
1694        open_uri_internal(
1695            self.with_common(|c| c.background_executor.clone()),
1696            uri,
1697            None,
1698        );
1699    }
1700
1701    fn reveal_path(&self, path: PathBuf) {
1702        #[cfg(any(feature = "x11", feature = "wayland"))]
1703        reveal_path_internal(
1704            self.with_common(|c| c.background_executor.clone()),
1705            path,
1706            None,
1707        );
1708    }
1709
1710    fn write_to_primary(&self, item: gpui::ClipboardItem) {
1711        let state = self.0.borrow_mut();
1712        state
1713            .clipboard
1714            .set_text(
1715                std::borrow::Cow::Owned(item.text().unwrap_or_default()),
1716                clipboard::ClipboardKind::Primary,
1717                clipboard::WaitConfig::None,
1718            )
1719            .context("X11 Failed to write to clipboard (primary)")
1720            .log_with_level(log::Level::Debug);
1721    }
1722
1723    fn write_to_clipboard(&self, item: gpui::ClipboardItem) {
1724        let mut state = self.0.borrow_mut();
1725        state
1726            .clipboard
1727            .set_text(
1728                std::borrow::Cow::Owned(item.text().unwrap_or_default()),
1729                clipboard::ClipboardKind::Clipboard,
1730                clipboard::WaitConfig::None,
1731            )
1732            .context("X11: Failed to write to clipboard (clipboard)")
1733            .log_with_level(log::Level::Debug);
1734        state.clipboard_item.replace(item);
1735    }
1736
1737    fn read_from_primary(&self) -> Option<gpui::ClipboardItem> {
1738        let state = self.0.borrow_mut();
1739        state
1740            .clipboard
1741            .get_any(clipboard::ClipboardKind::Primary)
1742            .context("X11: Failed to read from clipboard (primary)")
1743            .log_with_level(log::Level::Debug)
1744    }
1745
1746    fn read_from_clipboard(&self) -> Option<gpui::ClipboardItem> {
1747        let state = self.0.borrow_mut();
1748        // if the last copy was from this app, return our cached item
1749        // which has metadata attached.
1750        if state
1751            .clipboard
1752            .is_owner(clipboard::ClipboardKind::Clipboard)
1753        {
1754            return state.clipboard_item.clone();
1755        }
1756        state
1757            .clipboard
1758            .get_any(clipboard::ClipboardKind::Clipboard)
1759            .context("X11: Failed to read from clipboard (clipboard)")
1760            .log_with_level(log::Level::Debug)
1761    }
1762
1763    fn run(&self) {
1764        let Some(mut event_loop) = self
1765            .0
1766            .borrow_mut()
1767            .event_loop
1768            .take()
1769            .context("X11Client::run called but it's already running")
1770            .log_err()
1771        else {
1772            return;
1773        };
1774
1775        event_loop.run(None, &mut self.clone(), |_| {}).log_err();
1776    }
1777
1778    fn active_window(&self) -> Option<AnyWindowHandle> {
1779        let state = self.0.borrow();
1780        state.keyboard_focused_window.and_then(|focused_window| {
1781            state
1782                .windows
1783                .get(&focused_window)
1784                .map(|window| window.handle())
1785        })
1786    }
1787
1788    fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
1789        let state = self.0.borrow();
1790        let root = state.xcb_connection.setup().roots[state.x_root_index].root;
1791
1792        let reply = state
1793            .xcb_connection
1794            .get_property(
1795                false,
1796                root,
1797                state.atoms._NET_CLIENT_LIST_STACKING,
1798                xproto::AtomEnum::WINDOW,
1799                0,
1800                u32::MAX,
1801            )
1802            .ok()?
1803            .reply()
1804            .ok()?;
1805
1806        let window_ids = reply
1807            .value
1808            .chunks_exact(4)
1809            .filter_map(|chunk| chunk.try_into().ok().map(u32::from_ne_bytes))
1810            .collect::<Vec<xproto::Window>>();
1811
1812        let mut handles = Vec::new();
1813
1814        // We need to reverse, since _NET_CLIENT_LIST_STACKING has
1815        // a back-to-front order.
1816        // See: https://specifications.freedesktop.org/wm-spec/1.3/ar01s03.html
1817        for window_ref in window_ids
1818            .iter()
1819            .rev()
1820            .filter_map(|&win| state.windows.get(&win))
1821        {
1822            if !window_ref.window.state.borrow().destroyed {
1823                handles.push(window_ref.handle());
1824            }
1825        }
1826
1827        Some(handles)
1828    }
1829
1830    fn window_identifier(&self) -> impl Future<Output = Option<WindowIdentifier>> + Send + 'static {
1831        let state = self.0.borrow();
1832        state
1833            .keyboard_focused_window
1834            .and_then(|focused_window| state.windows.get(&focused_window))
1835            .map(|window| window.window.x_window as u64)
1836            .map(|x_window| std::future::ready(Some(WindowIdentifier::from_xid(x_window))))
1837            .unwrap_or(std::future::ready(None))
1838    }
1839}
1840
1841impl X11ClientState {
1842    fn has_xim(&self) -> bool {
1843        self.ximc.is_some() && self.xim_handler.is_some()
1844    }
1845
1846    fn take_xim(&mut self) -> Option<(X11rbClient<Rc<XCBConnection>>, XimHandler)> {
1847        let ximc = self
1848            .ximc
1849            .take()
1850            .ok_or(anyhow!("bug: XIM connection not set"))
1851            .log_err()?;
1852        if let Some(xim_handler) = self.xim_handler.take() {
1853            Some((ximc, xim_handler))
1854        } else {
1855            self.ximc = Some(ximc);
1856            log::error!("bug: XIM handler not set");
1857            None
1858        }
1859    }
1860
1861    fn restore_xim(&mut self, ximc: X11rbClient<Rc<XCBConnection>>, xim_handler: XimHandler) {
1862        self.ximc = Some(ximc);
1863        self.xim_handler = Some(xim_handler);
1864    }
1865
1866    fn update_refresh_loop(&mut self, x_window: xproto::Window) {
1867        let Some(window_ref) = self.windows.get_mut(&x_window) else {
1868            return;
1869        };
1870        let is_visible = window_ref.is_mapped
1871            && !matches!(window_ref.last_visibility, Visibility::FULLY_OBSCURED);
1872        match (is_visible, window_ref.refresh_state.take()) {
1873            (false, refresh_state @ Some(RefreshState::Hidden { .. }))
1874            | (false, refresh_state @ None)
1875            | (true, refresh_state @ Some(RefreshState::PeriodicRefresh { .. })) => {
1876                window_ref.refresh_state = refresh_state;
1877            }
1878            (
1879                false,
1880                Some(RefreshState::PeriodicRefresh {
1881                    refresh_rate,
1882                    event_loop_token,
1883                }),
1884            ) => {
1885                self.loop_handle.remove(event_loop_token);
1886                window_ref.refresh_state = Some(RefreshState::Hidden { refresh_rate });
1887            }
1888            (true, Some(RefreshState::Hidden { refresh_rate })) => {
1889                let event_loop_token = self.start_refresh_loop(x_window, refresh_rate);
1890                let Some(window_ref) = self.windows.get_mut(&x_window) else {
1891                    return;
1892                };
1893                window_ref.refresh_state = Some(RefreshState::PeriodicRefresh {
1894                    refresh_rate,
1895                    event_loop_token,
1896                });
1897            }
1898            (true, None) => {
1899                let Some(screen_resources) = get_reply(
1900                    || "Failed to get screen resources",
1901                    self.xcb_connection
1902                        .randr_get_screen_resources_current(x_window),
1903                )
1904                .log_err() else {
1905                    return;
1906                };
1907
1908                // Ideally this would be re-queried when the window changes screens, but there
1909                // doesn't seem to be an efficient / straightforward way to do this. Should also be
1910                // updated when screen configurations change.
1911                let mode_info = screen_resources.crtcs.iter().find_map(|crtc| {
1912                    let crtc_info = self
1913                        .xcb_connection
1914                        .randr_get_crtc_info(*crtc, x11rb::CURRENT_TIME)
1915                        .ok()?
1916                        .reply()
1917                        .ok()?;
1918
1919                    screen_resources
1920                        .modes
1921                        .iter()
1922                        .find(|m| m.id == crtc_info.mode)
1923                });
1924                let refresh_rate = match mode_info {
1925                    Some(mode_info) => mode_refresh_rate(mode_info),
1926                    None => {
1927                        log::error!(
1928                            "Failed to get screen mode info from xrandr, \
1929                            defaulting to 60hz refresh rate."
1930                        );
1931                        Duration::from_micros(1_000_000 / 60)
1932                    }
1933                };
1934
1935                let event_loop_token = self.start_refresh_loop(x_window, refresh_rate);
1936                let Some(window_ref) = self.windows.get_mut(&x_window) else {
1937                    return;
1938                };
1939                window_ref.refresh_state = Some(RefreshState::PeriodicRefresh {
1940                    refresh_rate,
1941                    event_loop_token,
1942                });
1943            }
1944        }
1945    }
1946
1947    #[must_use]
1948    fn start_refresh_loop(
1949        &self,
1950        x_window: xproto::Window,
1951        refresh_rate: Duration,
1952    ) -> RegistrationToken {
1953        self.loop_handle
1954            .insert_source(calloop::timer::Timer::immediate(), {
1955                move |mut instant, (), client| {
1956                    let xcb_connection = {
1957                        let mut state = client.0.borrow_mut();
1958                        let xcb_connection = state.xcb_connection.clone();
1959                        if let Some(window) = state.windows.get_mut(&x_window) {
1960                            let expose_event_received = window.expose_event_received;
1961                            window.expose_event_received = false;
1962                            let force_render = std::mem::take(
1963                                &mut window.window.state.borrow_mut().force_render_after_recovery,
1964                            );
1965                            let window = window.window.clone();
1966                            drop(state);
1967                            window.refresh(RequestFrameOptions {
1968                                require_presentation: expose_event_received,
1969                                force_render,
1970                            });
1971                        }
1972                        xcb_connection
1973                    };
1974                    client.process_x11_events(&xcb_connection).log_err();
1975
1976                    // Take into account that some frames have been skipped
1977                    let now = Instant::now();
1978                    while instant < now {
1979                        instant += refresh_rate;
1980                    }
1981                    calloop::timer::TimeoutAction::ToInstant(instant)
1982                }
1983            })
1984            .expect("Failed to initialize window refresh timer")
1985    }
1986
1987    fn get_cursor_icon(&mut self, style: CursorStyle) -> Option<xproto::Cursor> {
1988        if let Some(cursor) = self.cursor_cache.get(&style) {
1989            return *cursor;
1990        }
1991
1992        let result;
1993        match style {
1994            CursorStyle::None => match create_invisible_cursor(&self.xcb_connection) {
1995                Ok(loaded_cursor) => result = Ok(loaded_cursor),
1996                Err(err) => result = Err(err.context("X11: error while creating invisible cursor")),
1997            },
1998            _ => 'outer: {
1999                let mut errors = String::new();
2000                let cursor_icon_names = cursor_style_to_icon_names(style);
2001                for cursor_icon_name in cursor_icon_names {
2002                    match self
2003                        .cursor_handle
2004                        .load_cursor(&self.xcb_connection, cursor_icon_name)
2005                    {
2006                        Ok(loaded_cursor) => {
2007                            if loaded_cursor != x11rb::NONE {
2008                                result = Ok(loaded_cursor);
2009                                break 'outer;
2010                            }
2011                        }
2012                        Err(err) => {
2013                            errors.push_str(&err.to_string());
2014                            errors.push('\n');
2015                        }
2016                    }
2017                }
2018                if errors.is_empty() {
2019                    result = Err(anyhow!(
2020                        "errors while loading cursor icons {:?}:\n{}",
2021                        cursor_icon_names,
2022                        errors
2023                    ));
2024                } else {
2025                    result = Err(anyhow!("did not find cursor icons {:?}", cursor_icon_names));
2026                }
2027            }
2028        };
2029
2030        let cursor = match result {
2031            Ok(cursor) => Some(cursor),
2032            Err(err) => {
2033                match self
2034                    .cursor_handle
2035                    .load_cursor(&self.xcb_connection, DEFAULT_CURSOR_ICON_NAME)
2036                {
2037                    Ok(default) => {
2038                        log_cursor_icon_warning(err.context(format!(
2039                            "X11: error loading cursor icon, falling back on default icon '{}'",
2040                            DEFAULT_CURSOR_ICON_NAME
2041                        )));
2042                        Some(default)
2043                    }
2044                    Err(default_err) => {
2045                        log_cursor_icon_warning(err.context(default_err).context(format!(
2046                            "X11: error loading default cursor fallback '{}'",
2047                            DEFAULT_CURSOR_ICON_NAME
2048                        )));
2049                        None
2050                    }
2051                }
2052            }
2053        };
2054
2055        self.cursor_cache.insert(style, cursor);
2056        cursor
2057    }
2058}
2059
2060// Adapted from:
2061// https://docs.rs/winit/0.29.11/src/winit/platform_impl/linux/x11/monitor.rs.html#103-111
2062pub fn mode_refresh_rate(mode: &randr::ModeInfo) -> Duration {
2063    if mode.dot_clock == 0 || mode.htotal == 0 || mode.vtotal == 0 {
2064        return Duration::from_millis(16);
2065    }
2066
2067    let millihertz = mode.dot_clock as u64 * 1_000 / (mode.htotal as u64 * mode.vtotal as u64);
2068    let micros = 1_000_000_000 / millihertz;
2069    log::info!("Refreshing every {}ms", micros / 1_000);
2070    Duration::from_micros(micros)
2071}
2072
2073fn fp3232_to_f32(value: xinput::Fp3232) -> f32 {
2074    value.integral as f32 + value.frac as f32 / u32::MAX as f32
2075}
2076
2077fn detect_compositor_gpu(
2078    xcb_connection: &XCBConnection,
2079    screen: &xproto::Screen,
2080) -> Option<CompositorGpuHint> {
2081    use std::os::fd::AsRawFd;
2082    use std::os::unix::fs::MetadataExt;
2083
2084    xcb_connection
2085        .extension_information(dri3::X11_EXTENSION_NAME)
2086        .ok()??;
2087
2088    let reply = dri3::open(xcb_connection, screen.root, 0)
2089        .ok()?
2090        .reply()
2091        .ok()?;
2092    let fd = reply.device_fd;
2093
2094    let path = format!("/proc/self/fd/{}", fd.as_raw_fd());
2095    let metadata = std::fs::metadata(&path).ok()?;
2096
2097    crate::linux::compositor_gpu_hint_from_dev_t(metadata.rdev())
2098}
2099
2100fn check_compositor_present(xcb_connection: &XCBConnection, root: xproto::Window) -> bool {
2101    // Method 1: Check for _NET_WM_CM_S{root}
2102    let atom_name = format!("_NET_WM_CM_S{}", root);
2103    let atom1 = get_reply(
2104        || format!("Failed to intern {atom_name}"),
2105        xcb_connection.intern_atom(false, atom_name.as_bytes()),
2106    );
2107    let method1 = match atom1.log_with_level(Level::Debug) {
2108        Some(reply) if reply.atom != x11rb::NONE => {
2109            let atom = reply.atom;
2110            get_reply(
2111                || format!("Failed to get {atom_name} owner"),
2112                xcb_connection.get_selection_owner(atom),
2113            )
2114            .map(|reply| reply.owner != 0)
2115            .log_with_level(Level::Debug)
2116            .unwrap_or(false)
2117        }
2118        _ => false,
2119    };
2120
2121    // Method 2: Check for _NET_WM_CM_OWNER
2122    let atom_name = "_NET_WM_CM_OWNER";
2123    let atom2 = get_reply(
2124        || format!("Failed to intern {atom_name}"),
2125        xcb_connection.intern_atom(false, atom_name.as_bytes()),
2126    );
2127    let method2 = match atom2.log_with_level(Level::Debug) {
2128        Some(reply) if reply.atom != x11rb::NONE => {
2129            let atom = reply.atom;
2130            get_reply(
2131                || format!("Failed to get {atom_name}"),
2132                xcb_connection.get_property(false, root, atom, xproto::AtomEnum::WINDOW, 0, 1),
2133            )
2134            .map(|reply| reply.value_len > 0)
2135            .unwrap_or(false)
2136        }
2137        _ => return false,
2138    };
2139
2140    // Method 3: Check for _NET_SUPPORTING_WM_CHECK
2141    let atom_name = "_NET_SUPPORTING_WM_CHECK";
2142    let atom3 = get_reply(
2143        || format!("Failed to intern {atom_name}"),
2144        xcb_connection.intern_atom(false, atom_name.as_bytes()),
2145    );
2146    let method3 = match atom3.log_with_level(Level::Debug) {
2147        Some(reply) if reply.atom != x11rb::NONE => {
2148            let atom = reply.atom;
2149            get_reply(
2150                || format!("Failed to get {atom_name}"),
2151                xcb_connection.get_property(false, root, atom, xproto::AtomEnum::WINDOW, 0, 1),
2152            )
2153            .map(|reply| reply.value_len > 0)
2154            .unwrap_or(false)
2155        }
2156        _ => return false,
2157    };
2158
2159    log::debug!(
2160        "Compositor detection: _NET_WM_CM_S?={}, _NET_WM_CM_OWNER={}, _NET_SUPPORTING_WM_CHECK={}",
2161        method1,
2162        method2,
2163        method3
2164    );
2165
2166    method1 || method2 || method3
2167}
2168
2169fn check_gtk_frame_extents_supported(
2170    xcb_connection: &XCBConnection,
2171    atoms: &XcbAtoms,
2172    root: xproto::Window,
2173) -> bool {
2174    let Some(supported_atoms) = get_reply(
2175        || "Failed to get _NET_SUPPORTED",
2176        xcb_connection.get_property(
2177            false,
2178            root,
2179            atoms._NET_SUPPORTED,
2180            xproto::AtomEnum::ATOM,
2181            0,
2182            1024,
2183        ),
2184    )
2185    .log_with_level(Level::Debug) else {
2186        return false;
2187    };
2188
2189    let supported_atom_ids: Vec<u32> = supported_atoms
2190        .value
2191        .chunks_exact(4)
2192        .filter_map(|chunk| chunk.try_into().ok().map(u32::from_ne_bytes))
2193        .collect();
2194
2195    supported_atom_ids.contains(&atoms._GTK_FRAME_EXTENTS)
2196}
2197
2198fn xdnd_is_atom_supported(atom: u32, atoms: &XcbAtoms) -> bool {
2199    atom == atoms.TEXT
2200        || atom == atoms.STRING
2201        || atom == atoms.UTF8_STRING
2202        || atom == atoms.TEXT_PLAIN
2203        || atom == atoms.TEXT_PLAIN_UTF8
2204        || atom == atoms.TextUriList
2205}
2206
2207fn xdnd_get_supported_atom(
2208    xcb_connection: &XCBConnection,
2209    supported_atoms: &XcbAtoms,
2210    target: xproto::Window,
2211) -> u32 {
2212    if let Some(reply) = get_reply(
2213        || "Failed to get XDnD supported atoms",
2214        xcb_connection.get_property(
2215            false,
2216            target,
2217            supported_atoms.XdndTypeList,
2218            AtomEnum::ANY,
2219            0,
2220            1024,
2221        ),
2222    )
2223    .log_with_level(Level::Warn)
2224        && let Some(atoms) = reply.value32()
2225    {
2226        for atom in atoms {
2227            if xdnd_is_atom_supported(atom, supported_atoms) {
2228                return atom;
2229            }
2230        }
2231    }
2232    0
2233}
2234
2235fn xdnd_send_finished(
2236    xcb_connection: &XCBConnection,
2237    atoms: &XcbAtoms,
2238    source: xproto::Window,
2239    target: xproto::Window,
2240) {
2241    let message = ClientMessageEvent {
2242        format: 32,
2243        window: target,
2244        type_: atoms.XdndFinished,
2245        data: ClientMessageData::from([source, 1, atoms.XdndActionCopy, 0, 0]),
2246        sequence: 0,
2247        response_type: xproto::CLIENT_MESSAGE_EVENT,
2248    };
2249    check_reply(
2250        || "Failed to send XDnD finished event",
2251        xcb_connection.send_event(false, target, EventMask::default(), message),
2252    )
2253    .log_err();
2254    xcb_connection.flush().log_err();
2255}
2256
2257fn xdnd_send_status(
2258    xcb_connection: &XCBConnection,
2259    atoms: &XcbAtoms,
2260    source: xproto::Window,
2261    target: xproto::Window,
2262    action: u32,
2263) {
2264    let message = ClientMessageEvent {
2265        format: 32,
2266        window: target,
2267        type_: atoms.XdndStatus,
2268        data: ClientMessageData::from([source, 1, 0, 0, action]),
2269        sequence: 0,
2270        response_type: xproto::CLIENT_MESSAGE_EVENT,
2271    };
2272    check_reply(
2273        || "Failed to send XDnD status event",
2274        xcb_connection.send_event(false, target, EventMask::default(), message),
2275    )
2276    .log_err();
2277    xcb_connection.flush().log_err();
2278}
2279
2280/// Recomputes `pointer_device_states` by querying all pointer devices.
2281/// When a device is present in `scroll_values_to_preserve`, its value for `ScrollAxisState.scroll_value` is used.
2282fn current_pointer_device_states(
2283    xcb_connection: &XCBConnection,
2284    scroll_values_to_preserve: &BTreeMap<xinput::DeviceId, PointerDeviceState>,
2285) -> Option<BTreeMap<xinput::DeviceId, PointerDeviceState>> {
2286    let devices_query_result = get_reply(
2287        || "Failed to query XInput devices",
2288        xcb_connection.xinput_xi_query_device(XINPUT_ALL_DEVICES),
2289    )
2290    .log_err()?;
2291
2292    let mut pointer_device_states = BTreeMap::new();
2293    pointer_device_states.extend(
2294        devices_query_result
2295            .infos
2296            .iter()
2297            .filter(|info| is_pointer_device(info.type_))
2298            .filter_map(|info| {
2299                let scroll_data = info
2300                    .classes
2301                    .iter()
2302                    .filter_map(|class| class.data.as_scroll())
2303                    .copied()
2304                    .rev()
2305                    .collect::<Vec<_>>();
2306                let old_state = scroll_values_to_preserve.get(&info.deviceid);
2307                let old_horizontal = old_state.map(|state| &state.horizontal);
2308                let old_vertical = old_state.map(|state| &state.vertical);
2309                let horizontal = scroll_data
2310                    .iter()
2311                    .find(|data| data.scroll_type == xinput::ScrollType::HORIZONTAL)
2312                    .map(|data| scroll_data_to_axis_state(data, old_horizontal));
2313                let vertical = scroll_data
2314                    .iter()
2315                    .find(|data| data.scroll_type == xinput::ScrollType::VERTICAL)
2316                    .map(|data| scroll_data_to_axis_state(data, old_vertical));
2317                if horizontal.is_none() && vertical.is_none() {
2318                    None
2319                } else {
2320                    Some((
2321                        info.deviceid,
2322                        PointerDeviceState {
2323                            horizontal: horizontal.unwrap_or_else(Default::default),
2324                            vertical: vertical.unwrap_or_else(Default::default),
2325                        },
2326                    ))
2327                }
2328            }),
2329    );
2330    if pointer_device_states.is_empty() {
2331        log::error!("Found no xinput mouse pointers.");
2332    }
2333    Some(pointer_device_states)
2334}
2335
2336/// Returns true if the device is a pointer device. Does not include pointer device groups.
2337fn is_pointer_device(type_: xinput::DeviceType) -> bool {
2338    type_ == xinput::DeviceType::SLAVE_POINTER
2339}
2340
2341fn scroll_data_to_axis_state(
2342    data: &xinput::DeviceClassDataScroll,
2343    old_axis_state_with_valid_scroll_value: Option<&ScrollAxisState>,
2344) -> ScrollAxisState {
2345    ScrollAxisState {
2346        valuator_number: Some(data.number),
2347        multiplier: SCROLL_LINES / fp3232_to_f32(data.increment),
2348        scroll_value: old_axis_state_with_valid_scroll_value.and_then(|state| state.scroll_value),
2349    }
2350}
2351
2352fn reset_all_pointer_device_scroll_positions(
2353    pointer_device_states: &mut BTreeMap<xinput::DeviceId, PointerDeviceState>,
2354) {
2355    pointer_device_states
2356        .iter_mut()
2357        .for_each(|(_, device_state)| reset_pointer_device_scroll_positions(device_state));
2358}
2359
2360fn reset_pointer_device_scroll_positions(pointer: &mut PointerDeviceState) {
2361    pointer.horizontal.scroll_value = None;
2362    pointer.vertical.scroll_value = None;
2363}
2364
2365/// Returns the scroll delta for a smooth scrolling motion event, or `None` if no scroll data is present.
2366fn get_scroll_delta_and_update_state(
2367    pointer: &mut PointerDeviceState,
2368    event: &xinput::MotionEvent,
2369) -> Option<Point<f32>> {
2370    let delta_x = get_axis_scroll_delta_and_update_state(event, &mut pointer.horizontal);
2371    let delta_y = get_axis_scroll_delta_and_update_state(event, &mut pointer.vertical);
2372    if delta_x.is_some() || delta_y.is_some() {
2373        Some(Point::new(delta_x.unwrap_or(0.0), delta_y.unwrap_or(0.0)))
2374    } else {
2375        None
2376    }
2377}
2378
2379fn get_axis_scroll_delta_and_update_state(
2380    event: &xinput::MotionEvent,
2381    axis: &mut ScrollAxisState,
2382) -> Option<f32> {
2383    let axis_index = get_valuator_axis_index(&event.valuator_mask, axis.valuator_number?)?;
2384    if let Some(axis_value) = event.axisvalues.get(axis_index) {
2385        let new_scroll = fp3232_to_f32(*axis_value);
2386        let delta_scroll = axis
2387            .scroll_value
2388            .map(|old_scroll| (old_scroll - new_scroll) * axis.multiplier);
2389        axis.scroll_value = Some(new_scroll);
2390        delta_scroll
2391    } else {
2392        log::error!("Encountered invalid XInput valuator_mask, scrolling may not work properly.");
2393        None
2394    }
2395}
2396
2397fn make_scroll_wheel_event(
2398    position: Point<Pixels>,
2399    scroll_delta: Point<f32>,
2400    modifiers: Modifiers,
2401) -> gpui::ScrollWheelEvent {
2402    // When shift is held down, vertical scrolling turns into horizontal scrolling.
2403    let delta = if modifiers.shift {
2404        Point {
2405            x: scroll_delta.y,
2406            y: 0.0,
2407        }
2408    } else {
2409        scroll_delta
2410    };
2411    gpui::ScrollWheelEvent {
2412        position,
2413        delta: ScrollDelta::Lines(delta),
2414        modifiers,
2415        touch_phase: TouchPhase::default(),
2416    }
2417}
2418
2419fn create_invisible_cursor(
2420    connection: &XCBConnection,
2421) -> anyhow::Result<crate::linux::x11::client::xproto::Cursor> {
2422    let empty_pixmap = connection.generate_id()?;
2423    let root = connection.setup().roots[0].root;
2424    connection.create_pixmap(1, empty_pixmap, root, 1, 1)?;
2425
2426    let cursor = connection.generate_id()?;
2427    connection.create_cursor(cursor, empty_pixmap, empty_pixmap, 0, 0, 0, 0, 0, 0, 0, 0)?;
2428
2429    connection.free_pixmap(empty_pixmap)?;
2430
2431    xcb_flush(connection);
2432    Ok(cursor)
2433}
2434
2435enum DpiMode {
2436    Randr,
2437    Scale(f32),
2438    NotSet,
2439}
2440
2441fn get_scale_factor(
2442    connection: &XCBConnection,
2443    resource_database: &Database,
2444    screen_index: usize,
2445) -> f32 {
2446    let env_dpi = std::env::var(GPUI_X11_SCALE_FACTOR_ENV)
2447        .ok()
2448        .map(|var| {
2449            if var.to_lowercase() == "randr" {
2450                DpiMode::Randr
2451            } else if let Ok(scale) = var.parse::<f32>() {
2452                if valid_scale_factor(scale) {
2453                    DpiMode::Scale(scale)
2454                } else {
2455                    panic!(
2456                        "`{}` must be a positive normal number or `randr`. Got `{}`",
2457                        GPUI_X11_SCALE_FACTOR_ENV, var
2458                    );
2459                }
2460            } else if var.is_empty() {
2461                DpiMode::NotSet
2462            } else {
2463                panic!(
2464                    "`{}` must be a positive number or `randr`. Got `{}`",
2465                    GPUI_X11_SCALE_FACTOR_ENV, var
2466                );
2467            }
2468        })
2469        .unwrap_or(DpiMode::NotSet);
2470
2471    match env_dpi {
2472        DpiMode::Scale(scale) => {
2473            log::info!(
2474                "Using scale factor from {}: {}",
2475                GPUI_X11_SCALE_FACTOR_ENV,
2476                scale
2477            );
2478            return scale;
2479        }
2480        DpiMode::Randr => {
2481            if let Some(scale) = get_randr_scale_factor(connection, screen_index) {
2482                log::info!(
2483                    "Using RandR scale factor from {}=randr: {}",
2484                    GPUI_X11_SCALE_FACTOR_ENV,
2485                    scale
2486                );
2487                return scale;
2488            }
2489            log::warn!("Failed to calculate RandR scale factor, falling back to default");
2490            return 1.0;
2491        }
2492        DpiMode::NotSet => {}
2493    }
2494
2495    // TODO: Use scale factor from XSettings here
2496
2497    if let Some(dpi) = resource_database
2498        .get_value::<f32>("Xft.dpi", "Xft.dpi")
2499        .ok()
2500        .flatten()
2501    {
2502        let scale = dpi / 96.0; // base dpi
2503        log::info!("Using scale factor from Xft.dpi: {}", scale);
2504        return scale;
2505    }
2506
2507    if let Some(scale) = get_randr_scale_factor(connection, screen_index) {
2508        log::info!("Using RandR scale factor: {}", scale);
2509        return scale;
2510    }
2511
2512    log::info!("Using default scale factor: 1.0");
2513    1.0
2514}
2515
2516fn get_randr_scale_factor(connection: &XCBConnection, screen_index: usize) -> Option<f32> {
2517    let root = connection.setup().roots.get(screen_index)?.root;
2518
2519    let version_cookie = connection.randr_query_version(1, 6).ok()?;
2520    let version_reply = version_cookie.reply().ok()?;
2521    if version_reply.major_version < 1
2522        || (version_reply.major_version == 1 && version_reply.minor_version < 5)
2523    {
2524        return legacy_get_randr_scale_factor(connection, root); // for randr <1.5
2525    }
2526
2527    let monitors_cookie = connection.randr_get_monitors(root, true).ok()?; // true for active only
2528    let monitors_reply = monitors_cookie.reply().ok()?;
2529
2530    let mut fallback_scale: Option<f32> = None;
2531    for monitor in monitors_reply.monitors {
2532        if monitor.width_in_millimeters == 0 || monitor.height_in_millimeters == 0 {
2533            continue;
2534        }
2535        let scale_factor = get_dpi_factor(
2536            (monitor.width as u32, monitor.height as u32),
2537            (
2538                monitor.width_in_millimeters as u64,
2539                monitor.height_in_millimeters as u64,
2540            ),
2541        );
2542        if monitor.primary {
2543            return Some(scale_factor);
2544        } else if fallback_scale.is_none() {
2545            fallback_scale = Some(scale_factor);
2546        }
2547    }
2548
2549    fallback_scale
2550}
2551
2552fn legacy_get_randr_scale_factor(connection: &XCBConnection, root: u32) -> Option<f32> {
2553    let primary_cookie = connection.randr_get_output_primary(root).ok()?;
2554    let primary_reply = primary_cookie.reply().ok()?;
2555    let primary_output = primary_reply.output;
2556
2557    let primary_output_cookie = connection
2558        .randr_get_output_info(primary_output, x11rb::CURRENT_TIME)
2559        .ok()?;
2560    let primary_output_info = primary_output_cookie.reply().ok()?;
2561
2562    // try primary
2563    if primary_output_info.connection == randr::Connection::CONNECTED
2564        && primary_output_info.mm_width > 0
2565        && primary_output_info.mm_height > 0
2566        && primary_output_info.crtc != 0
2567    {
2568        let crtc_cookie = connection
2569            .randr_get_crtc_info(primary_output_info.crtc, x11rb::CURRENT_TIME)
2570            .ok()?;
2571        let crtc_info = crtc_cookie.reply().ok()?;
2572
2573        if crtc_info.width > 0 && crtc_info.height > 0 {
2574            let scale_factor = get_dpi_factor(
2575                (crtc_info.width as u32, crtc_info.height as u32),
2576                (
2577                    primary_output_info.mm_width as u64,
2578                    primary_output_info.mm_height as u64,
2579                ),
2580            );
2581            return Some(scale_factor);
2582        }
2583    }
2584
2585    // fallback: full scan
2586    let resources_cookie = connection.randr_get_screen_resources_current(root).ok()?;
2587    let screen_resources = resources_cookie.reply().ok()?;
2588
2589    let mut crtc_cookies = Vec::with_capacity(screen_resources.crtcs.len());
2590    for &crtc in &screen_resources.crtcs {
2591        if let Ok(cookie) = connection.randr_get_crtc_info(crtc, x11rb::CURRENT_TIME) {
2592            crtc_cookies.push((crtc, cookie));
2593        }
2594    }
2595
2596    let mut crtc_infos: HashMap<randr::Crtc, randr::GetCrtcInfoReply> = HashMap::default();
2597    let mut valid_outputs: HashSet<randr::Output> = HashSet::new();
2598    for (crtc, cookie) in crtc_cookies {
2599        if let Ok(reply) = cookie.reply()
2600            && reply.width > 0
2601            && reply.height > 0
2602            && !reply.outputs.is_empty()
2603        {
2604            crtc_infos.insert(crtc, reply.clone());
2605            valid_outputs.extend(&reply.outputs);
2606        }
2607    }
2608
2609    if valid_outputs.is_empty() {
2610        return None;
2611    }
2612
2613    let mut output_cookies = Vec::with_capacity(valid_outputs.len());
2614    for &output in &valid_outputs {
2615        if let Ok(cookie) = connection.randr_get_output_info(output, x11rb::CURRENT_TIME) {
2616            output_cookies.push((output, cookie));
2617        }
2618    }
2619    let mut output_infos: HashMap<randr::Output, randr::GetOutputInfoReply> = HashMap::default();
2620    for (output, cookie) in output_cookies {
2621        if let Ok(reply) = cookie.reply() {
2622            output_infos.insert(output, reply);
2623        }
2624    }
2625
2626    let mut fallback_scale: Option<f32> = None;
2627    for crtc_info in crtc_infos.values() {
2628        for &output in &crtc_info.outputs {
2629            if let Some(output_info) = output_infos.get(&output) {
2630                if output_info.connection != randr::Connection::CONNECTED {
2631                    continue;
2632                }
2633
2634                if output_info.mm_width == 0 || output_info.mm_height == 0 {
2635                    continue;
2636                }
2637
2638                let scale_factor = get_dpi_factor(
2639                    (crtc_info.width as u32, crtc_info.height as u32),
2640                    (output_info.mm_width as u64, output_info.mm_height as u64),
2641                );
2642
2643                if output != primary_output && fallback_scale.is_none() {
2644                    fallback_scale = Some(scale_factor);
2645                }
2646            }
2647        }
2648    }
2649
2650    fallback_scale
2651}
2652
2653fn get_dpi_factor((width_px, height_px): (u32, u32), (width_mm, height_mm): (u64, u64)) -> f32 {
2654    let ppmm = ((width_px as f64 * height_px as f64) / (width_mm as f64 * height_mm as f64)).sqrt(); // pixels per mm
2655
2656    const MM_PER_INCH: f64 = 25.4;
2657    const BASE_DPI: f64 = 96.0;
2658    const QUANTIZE_STEP: f64 = 12.0; // e.g. 1.25 = 15/12, 1.5 = 18/12, 1.75 = 21/12, 2.0 = 24/12
2659    const MIN_SCALE: f64 = 1.0;
2660    const MAX_SCALE: f64 = 20.0;
2661
2662    let dpi_factor =
2663        ((ppmm * (QUANTIZE_STEP * MM_PER_INCH / BASE_DPI)).round() / QUANTIZE_STEP).max(MIN_SCALE);
2664
2665    let validated_factor = if dpi_factor <= MAX_SCALE {
2666        dpi_factor
2667    } else {
2668        MIN_SCALE
2669    };
2670
2671    if valid_scale_factor(validated_factor as f32) {
2672        validated_factor as f32
2673    } else {
2674        log::warn!(
2675            "Calculated DPI factor {} is invalid, using 1.0",
2676            validated_factor
2677        );
2678        1.0
2679    }
2680}
2681
2682#[inline]
2683fn valid_scale_factor(scale_factor: f32) -> bool {
2684    scale_factor.is_sign_positive() && scale_factor.is_normal()
2685}
2686
2687#[inline]
2688fn update_xkb_mask_from_event_state(xkb: &mut xkbc::State, event_state: xproto::KeyButMask) {
2689    let depressed_mods = event_state.remove((ModMask::LOCK | ModMask::M2).bits());
2690    let latched_mods = xkb.serialize_mods(xkbc::STATE_MODS_LATCHED);
2691    let locked_mods = xkb.serialize_mods(xkbc::STATE_MODS_LOCKED);
2692    let locked_layout = xkb.serialize_layout(xkbc::STATE_LAYOUT_LOCKED);
2693    xkb.update_mask(
2694        depressed_mods.into(),
2695        latched_mods,
2696        locked_mods,
2697        0,
2698        0,
2699        locked_layout,
2700    );
2701}