client.rs

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