client.rs

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