client.rs

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