client.rs

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