client.rs

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