client.rs

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