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