client.rs

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