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