client.rs

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