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