client.rs

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