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