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                println!("\nX11 Key released: {:#?}", keystroke);
1132                drop(state);
1133                window.handle_input(PlatformInput::KeyUp(crate::KeyUpEvent { keystroke }));
1134            }
1135            Event::XinputButtonPress(event) => {
1136                let window = self.get_window(event.event)?;
1137                let mut state = self.0.borrow_mut();
1138
1139                let modifiers = modifiers_from_xinput_info(event.mods);
1140                state.modifiers = modifiers;
1141
1142                let position = point(
1143                    px(event.event_x as f32 / u16::MAX as f32 / state.scale_factor),
1144                    px(event.event_y as f32 / u16::MAX as f32 / state.scale_factor),
1145                );
1146
1147                if state.composing && state.ximc.is_some() {
1148                    drop(state);
1149                    self.reset_ime();
1150                    window.handle_ime_unmark();
1151                    state = self.0.borrow_mut();
1152                } else if let Some(text) = state.pre_edit_text.take() {
1153                    if let Some(compose_state) = state.compose_state.as_mut() {
1154                        compose_state.reset();
1155                    }
1156                    drop(state);
1157                    window.handle_ime_commit(text);
1158                    state = self.0.borrow_mut();
1159                }
1160                match button_or_scroll_from_event_detail(event.detail) {
1161                    Some(ButtonOrScroll::Button(button)) => {
1162                        let click_elapsed = state.last_click.elapsed();
1163                        if click_elapsed < DOUBLE_CLICK_INTERVAL
1164                            && state
1165                                .last_mouse_button
1166                                .is_some_and(|prev_button| prev_button == button)
1167                            && is_within_click_distance(state.last_location, position)
1168                        {
1169                            state.current_count += 1;
1170                        } else {
1171                            state.current_count = 1;
1172                        }
1173
1174                        state.last_click = Instant::now();
1175                        state.last_mouse_button = Some(button);
1176                        state.last_location = position;
1177                        let current_count = state.current_count;
1178
1179                        drop(state);
1180                        window.handle_input(PlatformInput::MouseDown(crate::MouseDownEvent {
1181                            button,
1182                            position,
1183                            modifiers,
1184                            click_count: current_count,
1185                            first_mouse: false,
1186                        }));
1187                    }
1188                    Some(ButtonOrScroll::Scroll(direction)) => {
1189                        drop(state);
1190                        // Emulated scroll button presses are sent simultaneously with smooth scrolling XinputMotion events.
1191                        // Since handling those events does the scrolling, they are skipped here.
1192                        if !event
1193                            .flags
1194                            .contains(xinput::PointerEventFlags::POINTER_EMULATED)
1195                        {
1196                            let scroll_delta = match direction {
1197                                ScrollDirection::Up => Point::new(0.0, SCROLL_LINES),
1198                                ScrollDirection::Down => Point::new(0.0, -SCROLL_LINES),
1199                                ScrollDirection::Left => Point::new(SCROLL_LINES, 0.0),
1200                                ScrollDirection::Right => Point::new(-SCROLL_LINES, 0.0),
1201                            };
1202                            window.handle_input(PlatformInput::ScrollWheel(
1203                                make_scroll_wheel_event(position, scroll_delta, modifiers),
1204                            ));
1205                        }
1206                    }
1207                    None => {
1208                        log::error!("Unknown x11 button: {}", event.detail);
1209                    }
1210                }
1211            }
1212            Event::XinputButtonRelease(event) => {
1213                let window = self.get_window(event.event)?;
1214                let mut state = self.0.borrow_mut();
1215                let modifiers = modifiers_from_xinput_info(event.mods);
1216                state.modifiers = modifiers;
1217
1218                let position = point(
1219                    px(event.event_x as f32 / u16::MAX as f32 / state.scale_factor),
1220                    px(event.event_y as f32 / u16::MAX as f32 / state.scale_factor),
1221                );
1222                match button_or_scroll_from_event_detail(event.detail) {
1223                    Some(ButtonOrScroll::Button(button)) => {
1224                        let click_count = state.current_count;
1225                        drop(state);
1226                        window.handle_input(PlatformInput::MouseUp(crate::MouseUpEvent {
1227                            button,
1228                            position,
1229                            modifiers,
1230                            click_count,
1231                        }));
1232                    }
1233                    Some(ButtonOrScroll::Scroll(_)) => {}
1234                    None => {}
1235                }
1236            }
1237            Event::XinputMotion(event) => {
1238                let window = self.get_window(event.event)?;
1239                let mut state = self.0.borrow_mut();
1240                let pressed_button = pressed_button_from_mask(event.button_mask[0]);
1241                let position = point(
1242                    px(event.event_x as f32 / u16::MAX as f32 / state.scale_factor),
1243                    px(event.event_y as f32 / u16::MAX as f32 / state.scale_factor),
1244                );
1245                let modifiers = modifiers_from_xinput_info(event.mods);
1246                state.modifiers = modifiers;
1247                drop(state);
1248
1249                if event.valuator_mask[0] & 3 != 0 {
1250                    window.handle_input(PlatformInput::MouseMove(crate::MouseMoveEvent {
1251                        position,
1252                        pressed_button,
1253                        modifiers,
1254                    }));
1255                }
1256
1257                state = self.0.borrow_mut();
1258                if let Some(mut pointer) = state.pointer_device_states.get_mut(&event.sourceid) {
1259                    let scroll_delta = get_scroll_delta_and_update_state(&mut pointer, &event);
1260                    drop(state);
1261                    if let Some(scroll_delta) = scroll_delta {
1262                        window.handle_input(PlatformInput::ScrollWheel(make_scroll_wheel_event(
1263                            position,
1264                            scroll_delta,
1265                            modifiers,
1266                        )));
1267                    }
1268                }
1269            }
1270            Event::XinputEnter(event) if event.mode == xinput::NotifyMode::NORMAL => {
1271                let window = self.get_window(event.event)?;
1272                window.set_hovered(true);
1273                let mut state = self.0.borrow_mut();
1274                state.mouse_focused_window = Some(event.event);
1275            }
1276            Event::XinputLeave(event) if event.mode == xinput::NotifyMode::NORMAL => {
1277                let mut state = self.0.borrow_mut();
1278
1279                // 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)
1280                reset_all_pointer_device_scroll_positions(&mut state.pointer_device_states);
1281                state.mouse_focused_window = None;
1282                let pressed_button = pressed_button_from_mask(event.buttons[0]);
1283                let position = point(
1284                    px(event.event_x as f32 / u16::MAX as f32 / state.scale_factor),
1285                    px(event.event_y as f32 / u16::MAX as f32 / state.scale_factor),
1286                );
1287                let modifiers = modifiers_from_xinput_info(event.mods);
1288                state.modifiers = modifiers;
1289                drop(state);
1290
1291                let window = self.get_window(event.event)?;
1292                window.handle_input(PlatformInput::MouseExited(crate::MouseExitEvent {
1293                    pressed_button,
1294                    position,
1295                    modifiers,
1296                }));
1297                window.set_hovered(false);
1298            }
1299            Event::XinputHierarchy(event) => {
1300                let mut state = self.0.borrow_mut();
1301                // Temporarily use `state.pointer_device_states` to only store pointers that still have valid scroll values.
1302                // Any change to a device invalidates its scroll values.
1303                for info in event.infos {
1304                    if is_pointer_device(info.type_) {
1305                        state.pointer_device_states.remove(&info.deviceid);
1306                    }
1307                }
1308                if let Some(pointer_device_states) = current_pointer_device_states(
1309                    &state.xcb_connection,
1310                    &state.pointer_device_states,
1311                ) {
1312                    state.pointer_device_states = pointer_device_states;
1313                }
1314            }
1315            Event::XinputDeviceChanged(event) => {
1316                let mut state = self.0.borrow_mut();
1317                if let Some(mut pointer) = state.pointer_device_states.get_mut(&event.sourceid) {
1318                    reset_pointer_device_scroll_positions(&mut pointer);
1319                }
1320            }
1321            _ => {}
1322        };
1323
1324        Some(())
1325    }
1326
1327    fn handle_xim_callback_event(&self, event: XimCallbackEvent) {
1328        match event {
1329            XimCallbackEvent::XimXEvent(event) => {
1330                self.handle_event(event);
1331            }
1332            XimCallbackEvent::XimCommitEvent(window, text) => {
1333                self.xim_handle_commit(window, text);
1334            }
1335            XimCallbackEvent::XimPreeditEvent(window, text) => {
1336                self.xim_handle_preedit(window, text);
1337            }
1338        };
1339    }
1340
1341    fn xim_handle_event(&self, event: Event) -> Option<()> {
1342        match event {
1343            Event::KeyPress(event) | Event::KeyRelease(event) => {
1344                let mut state = self.0.borrow_mut();
1345                state.pre_key_char_down = Some(Keystroke::from_xkb(
1346                    &state.keyboard_state,
1347                    state.modifiers,
1348                    event.detail.into(),
1349                ));
1350                let (mut ximc, mut xim_handler) = state.take_xim()?;
1351                drop(state);
1352                xim_handler.window = event.event;
1353                ximc.forward_event(
1354                    xim_handler.im_id,
1355                    xim_handler.ic_id,
1356                    xim::ForwardEventFlag::empty(),
1357                    &event,
1358                )
1359                .context("X11: Failed to forward XIM event")
1360                .log_err();
1361                let mut state = self.0.borrow_mut();
1362                state.restore_xim(ximc, xim_handler);
1363                drop(state);
1364            }
1365            event => {
1366                self.handle_event(event);
1367            }
1368        }
1369        Some(())
1370    }
1371
1372    fn xim_handle_commit(&self, window: xproto::Window, text: String) -> Option<()> {
1373        let Some(window) = self.get_window(window) else {
1374            log::error!("bug: Failed to get window for XIM commit");
1375            return None;
1376        };
1377        let mut state = self.0.borrow_mut();
1378        let keystroke = state.pre_key_char_down.take();
1379        state.composing = false;
1380        drop(state);
1381        if let Some(mut keystroke) = keystroke {
1382            keystroke.key_char = Some(text.clone());
1383            window.handle_input(PlatformInput::KeyDown(crate::KeyDownEvent {
1384                keystroke,
1385                is_held: false,
1386            }));
1387        }
1388
1389        Some(())
1390    }
1391
1392    fn xim_handle_preedit(&self, window: xproto::Window, text: String) -> Option<()> {
1393        let Some(window) = self.get_window(window) else {
1394            log::error!("bug: Failed to get window for XIM preedit");
1395            return None;
1396        };
1397
1398        let mut state = self.0.borrow_mut();
1399        let (mut ximc, mut xim_handler) = state.take_xim()?;
1400        state.composing = !text.is_empty();
1401        drop(state);
1402        window.handle_ime_preedit(text);
1403
1404        if let Some(area) = window.get_ime_area() {
1405            let ic_attributes = ximc
1406                .build_ic_attributes()
1407                .push(
1408                    xim::AttributeName::InputStyle,
1409                    xim::InputStyle::PREEDIT_CALLBACKS,
1410                )
1411                .push(xim::AttributeName::ClientWindow, xim_handler.window)
1412                .push(xim::AttributeName::FocusWindow, xim_handler.window)
1413                .nested_list(xim::AttributeName::PreeditAttributes, |b| {
1414                    b.push(
1415                        xim::AttributeName::SpotLocation,
1416                        xim::Point {
1417                            x: u32::from(area.origin.x + area.size.width) as i16,
1418                            y: u32::from(area.origin.y + area.size.height) as i16,
1419                        },
1420                    );
1421                })
1422                .build();
1423            ximc.set_ic_values(xim_handler.im_id, xim_handler.ic_id, ic_attributes)
1424                .ok();
1425        }
1426        let mut state = self.0.borrow_mut();
1427        state.restore_xim(ximc, xim_handler);
1428        drop(state);
1429        Some(())
1430    }
1431
1432    fn handle_keyboard_layout_change(&self) {
1433        let mut state = self.0.borrow_mut();
1434        let layout_idx = state.xkb.serialize_layout(STATE_LAYOUT_EFFECTIVE);
1435        let keymap = state.xkb.get_keymap();
1436        let layout_name = keymap.layout_get_name(layout_idx);
1437        if layout_name != state.keyboard_layout.name() {
1438            state.keyboard_layout = LinuxKeyboardLayout::new(layout_name.to_string().into());
1439            if let Some(mut callback) = state.common.callbacks.keyboard_layout_change.take() {
1440                drop(state);
1441                callback();
1442                state = self.0.borrow_mut();
1443                state.common.callbacks.keyboard_layout_change = Some(callback);
1444            }
1445        }
1446    }
1447}
1448
1449impl LinuxClient for X11Client {
1450    fn compositor_name(&self) -> &'static str {
1451        "X11"
1452    }
1453
1454    fn with_common<R>(&self, f: impl FnOnce(&mut LinuxCommon) -> R) -> R {
1455        f(&mut self.0.borrow_mut().common)
1456    }
1457
1458    fn keyboard_layout(&self) -> Box<dyn PlatformKeyboardLayout> {
1459        let state = self.0.borrow();
1460        Box::new(state.keyboard_layout.clone())
1461    }
1462
1463    fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
1464        let state = self.0.borrow();
1465        let setup = state.xcb_connection.setup();
1466        setup
1467            .roots
1468            .iter()
1469            .enumerate()
1470            .filter_map(|(root_id, _)| {
1471                Some(Rc::new(
1472                    X11Display::new(&state.xcb_connection, state.scale_factor, root_id).ok()?,
1473                ) as Rc<dyn PlatformDisplay>)
1474            })
1475            .collect()
1476    }
1477
1478    fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
1479        let state = self.0.borrow();
1480        X11Display::new(
1481            &state.xcb_connection,
1482            state.scale_factor,
1483            state.x_root_index,
1484        )
1485        .log_err()
1486        .map(|display| Rc::new(display) as Rc<dyn PlatformDisplay>)
1487    }
1488
1489    fn display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>> {
1490        let state = self.0.borrow();
1491
1492        Some(Rc::new(
1493            X11Display::new(&state.xcb_connection, state.scale_factor, id.0 as usize).ok()?,
1494        ))
1495    }
1496
1497    #[cfg(feature = "screen-capture")]
1498    fn is_screen_capture_supported(&self) -> bool {
1499        true
1500    }
1501
1502    #[cfg(feature = "screen-capture")]
1503    fn screen_capture_sources(
1504        &self,
1505    ) -> futures::channel::oneshot::Receiver<anyhow::Result<Vec<Box<dyn crate::ScreenCaptureSource>>>>
1506    {
1507        crate::platform::scap_screen_capture::scap_screen_sources(
1508            &self.0.borrow().common.foreground_executor,
1509        )
1510    }
1511
1512    fn open_window(
1513        &self,
1514        handle: AnyWindowHandle,
1515        params: WindowParams,
1516    ) -> anyhow::Result<Box<dyn PlatformWindow>> {
1517        let mut state = self.0.borrow_mut();
1518        let x_window = state
1519            .xcb_connection
1520            .generate_id()
1521            .context("X11: Failed to generate window ID")?;
1522
1523        let window = X11Window::new(
1524            handle,
1525            X11ClientStatePtr(Rc::downgrade(&self.0)),
1526            state.common.foreground_executor.clone(),
1527            &state.gpu_context,
1528            params,
1529            &state.xcb_connection,
1530            state.client_side_decorations_supported,
1531            state.x_root_index,
1532            x_window,
1533            &state.atoms,
1534            state.scale_factor,
1535            state.common.appearance,
1536        )?;
1537        check_reply(
1538            || "Failed to set XdndAware property",
1539            state.xcb_connection.change_property32(
1540                xproto::PropMode::REPLACE,
1541                x_window,
1542                state.atoms.XdndAware,
1543                state.atoms.XA_ATOM,
1544                &[5],
1545            ),
1546        )
1547        .log_err();
1548        xcb_flush(&state.xcb_connection);
1549
1550        let window_ref = WindowRef {
1551            window: window.0.clone(),
1552            refresh_state: None,
1553            expose_event_received: false,
1554            last_visibility: Visibility::UNOBSCURED,
1555            is_mapped: false,
1556        };
1557
1558        state.windows.insert(x_window, window_ref);
1559        Ok(Box::new(window))
1560    }
1561
1562    fn set_cursor_style(&self, style: CursorStyle) {
1563        let mut state = self.0.borrow_mut();
1564        let Some(focused_window) = state.mouse_focused_window else {
1565            return;
1566        };
1567        let current_style = state
1568            .cursor_styles
1569            .get(&focused_window)
1570            .unwrap_or(&CursorStyle::Arrow);
1571        if *current_style == style {
1572            return;
1573        }
1574
1575        let Some(cursor) = state.get_cursor_icon(style) else {
1576            return;
1577        };
1578
1579        state.cursor_styles.insert(focused_window, style);
1580        check_reply(
1581            || "Failed to set cursor style",
1582            state.xcb_connection.change_window_attributes(
1583                focused_window,
1584                &ChangeWindowAttributesAux {
1585                    cursor: Some(cursor),
1586                    ..Default::default()
1587                },
1588            ),
1589        )
1590        .log_err();
1591        state.xcb_connection.flush().log_err();
1592    }
1593
1594    fn open_uri(&self, uri: &str) {
1595        #[cfg(any(feature = "wayland", feature = "x11"))]
1596        open_uri_internal(self.background_executor(), uri, None);
1597    }
1598
1599    fn reveal_path(&self, path: PathBuf) {
1600        #[cfg(any(feature = "x11", feature = "wayland"))]
1601        reveal_path_internal(self.background_executor(), path, None);
1602    }
1603
1604    fn write_to_primary(&self, item: crate::ClipboardItem) {
1605        let state = self.0.borrow_mut();
1606        state
1607            .clipboard
1608            .set_text(
1609                std::borrow::Cow::Owned(item.text().unwrap_or_default()),
1610                clipboard::ClipboardKind::Primary,
1611                clipboard::WaitConfig::None,
1612            )
1613            .context("X11 Failed to write to clipboard (primary)")
1614            .log_with_level(log::Level::Debug);
1615    }
1616
1617    fn write_to_clipboard(&self, item: crate::ClipboardItem) {
1618        let mut state = self.0.borrow_mut();
1619        state
1620            .clipboard
1621            .set_text(
1622                std::borrow::Cow::Owned(item.text().unwrap_or_default()),
1623                clipboard::ClipboardKind::Clipboard,
1624                clipboard::WaitConfig::None,
1625            )
1626            .context("X11: Failed to write to clipboard (clipboard)")
1627            .log_with_level(log::Level::Debug);
1628        state.clipboard_item.replace(item);
1629    }
1630
1631    fn read_from_primary(&self) -> Option<crate::ClipboardItem> {
1632        let state = self.0.borrow_mut();
1633        return state
1634            .clipboard
1635            .get_any(clipboard::ClipboardKind::Primary)
1636            .context("X11: Failed to read from clipboard (primary)")
1637            .log_with_level(log::Level::Debug);
1638    }
1639
1640    fn read_from_clipboard(&self) -> Option<crate::ClipboardItem> {
1641        let state = self.0.borrow_mut();
1642        // if the last copy was from this app, return our cached item
1643        // which has metadata attached.
1644        if state
1645            .clipboard
1646            .is_owner(clipboard::ClipboardKind::Clipboard)
1647        {
1648            return state.clipboard_item.clone();
1649        }
1650        return state
1651            .clipboard
1652            .get_any(clipboard::ClipboardKind::Clipboard)
1653            .context("X11: Failed to read from clipboard (clipboard)")
1654            .log_with_level(log::Level::Debug);
1655    }
1656
1657    fn run(&self) {
1658        let Some(mut event_loop) = self
1659            .0
1660            .borrow_mut()
1661            .event_loop
1662            .take()
1663            .context("X11Client::run called but it's already running")
1664            .log_err()
1665        else {
1666            return;
1667        };
1668
1669        event_loop.run(None, &mut self.clone(), |_| {}).log_err();
1670    }
1671
1672    fn active_window(&self) -> Option<AnyWindowHandle> {
1673        let state = self.0.borrow();
1674        state.keyboard_focused_window.and_then(|focused_window| {
1675            state
1676                .windows
1677                .get(&focused_window)
1678                .map(|window| window.handle())
1679        })
1680    }
1681
1682    fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
1683        let state = self.0.borrow();
1684        let root = state.xcb_connection.setup().roots[state.x_root_index].root;
1685
1686        let reply = state
1687            .xcb_connection
1688            .get_property(
1689                false,
1690                root,
1691                state.atoms._NET_CLIENT_LIST_STACKING,
1692                xproto::AtomEnum::WINDOW,
1693                0,
1694                u32::MAX,
1695            )
1696            .ok()?
1697            .reply()
1698            .ok()?;
1699
1700        let window_ids = reply
1701            .value
1702            .chunks_exact(4)
1703            .filter_map(|chunk| chunk.try_into().ok().map(u32::from_ne_bytes))
1704            .collect::<Vec<xproto::Window>>();
1705
1706        let mut handles = Vec::new();
1707
1708        // We need to reverse, since _NET_CLIENT_LIST_STACKING has
1709        // a back-to-front order.
1710        // See: https://specifications.freedesktop.org/wm-spec/1.3/ar01s03.html
1711        for window_ref in window_ids
1712            .iter()
1713            .rev()
1714            .filter_map(|&win| state.windows.get(&win))
1715        {
1716            if !window_ref.window.state.borrow().destroyed {
1717                handles.push(window_ref.handle());
1718            }
1719        }
1720
1721        Some(handles)
1722    }
1723}
1724
1725impl X11ClientState {
1726    fn has_xim(&self) -> bool {
1727        self.ximc.is_some() && self.xim_handler.is_some()
1728    }
1729
1730    fn take_xim(&mut self) -> Option<(X11rbClient<Rc<XCBConnection>>, XimHandler)> {
1731        let ximc = self
1732            .ximc
1733            .take()
1734            .ok_or(anyhow!("bug: XIM connection not set"))
1735            .log_err()?;
1736        if let Some(xim_handler) = self.xim_handler.take() {
1737            Some((ximc, xim_handler))
1738        } else {
1739            self.ximc = Some(ximc);
1740            log::error!("bug: XIM handler not set");
1741            None
1742        }
1743    }
1744
1745    fn restore_xim(&mut self, ximc: X11rbClient<Rc<XCBConnection>>, xim_handler: XimHandler) {
1746        self.ximc = Some(ximc);
1747        self.xim_handler = Some(xim_handler);
1748    }
1749
1750    fn update_refresh_loop(&mut self, x_window: xproto::Window) {
1751        let Some(window_ref) = self.windows.get_mut(&x_window) else {
1752            return;
1753        };
1754        let is_visible = window_ref.is_mapped
1755            && !matches!(window_ref.last_visibility, Visibility::FULLY_OBSCURED);
1756        match (is_visible, window_ref.refresh_state.take()) {
1757            (false, refresh_state @ Some(RefreshState::Hidden { .. }))
1758            | (false, refresh_state @ None)
1759            | (true, refresh_state @ Some(RefreshState::PeriodicRefresh { .. })) => {
1760                window_ref.refresh_state = refresh_state;
1761            }
1762            (
1763                false,
1764                Some(RefreshState::PeriodicRefresh {
1765                    refresh_rate,
1766                    event_loop_token,
1767                }),
1768            ) => {
1769                self.loop_handle.remove(event_loop_token);
1770                window_ref.refresh_state = Some(RefreshState::Hidden { refresh_rate });
1771            }
1772            (true, Some(RefreshState::Hidden { refresh_rate })) => {
1773                let event_loop_token = self.start_refresh_loop(x_window, refresh_rate);
1774                let Some(window_ref) = self.windows.get_mut(&x_window) else {
1775                    return;
1776                };
1777                window_ref.refresh_state = Some(RefreshState::PeriodicRefresh {
1778                    refresh_rate,
1779                    event_loop_token,
1780                });
1781            }
1782            (true, None) => {
1783                let Some(screen_resources) = get_reply(
1784                    || "Failed to get screen resources",
1785                    self.xcb_connection
1786                        .randr_get_screen_resources_current(x_window),
1787                )
1788                .log_err() else {
1789                    return;
1790                };
1791
1792                // Ideally this would be re-queried when the window changes screens, but there
1793                // doesn't seem to be an efficient / straightforward way to do this. Should also be
1794                // updated when screen configurations change.
1795                let mode_info = screen_resources.crtcs.iter().find_map(|crtc| {
1796                    let crtc_info = self
1797                        .xcb_connection
1798                        .randr_get_crtc_info(*crtc, x11rb::CURRENT_TIME)
1799                        .ok()?
1800                        .reply()
1801                        .ok()?;
1802
1803                    screen_resources
1804                        .modes
1805                        .iter()
1806                        .find(|m| m.id == crtc_info.mode)
1807                });
1808                let refresh_rate = match mode_info {
1809                    Some(mode_info) => mode_refresh_rate(mode_info),
1810                    None => {
1811                        log::error!(
1812                            "Failed to get screen mode info from xrandr, \
1813                            defaulting to 60hz refresh rate."
1814                        );
1815                        Duration::from_micros(1_000_000 / 60)
1816                    }
1817                };
1818
1819                let event_loop_token = self.start_refresh_loop(x_window, refresh_rate);
1820                let Some(window_ref) = self.windows.get_mut(&x_window) else {
1821                    return;
1822                };
1823                window_ref.refresh_state = Some(RefreshState::PeriodicRefresh {
1824                    refresh_rate,
1825                    event_loop_token,
1826                });
1827            }
1828        }
1829    }
1830
1831    #[must_use]
1832    fn start_refresh_loop(
1833        &self,
1834        x_window: xproto::Window,
1835        refresh_rate: Duration,
1836    ) -> RegistrationToken {
1837        self.loop_handle
1838            .insert_source(calloop::timer::Timer::immediate(), {
1839                move |mut instant, (), client| {
1840                    let xcb_connection = {
1841                        let mut state = client.0.borrow_mut();
1842                        let xcb_connection = state.xcb_connection.clone();
1843                        if let Some(window) = state.windows.get_mut(&x_window) {
1844                            let expose_event_received = window.expose_event_received;
1845                            window.expose_event_received = false;
1846                            let window = window.window.clone();
1847                            drop(state);
1848                            window.refresh(RequestFrameOptions {
1849                                require_presentation: expose_event_received,
1850                            });
1851                        }
1852                        xcb_connection
1853                    };
1854                    client.process_x11_events(&xcb_connection).log_err();
1855
1856                    // Take into account that some frames have been skipped
1857                    let now = Instant::now();
1858                    while instant < now {
1859                        instant += refresh_rate;
1860                    }
1861                    calloop::timer::TimeoutAction::ToInstant(instant)
1862                }
1863            })
1864            .expect("Failed to initialize window refresh timer")
1865    }
1866
1867    fn get_cursor_icon(&mut self, style: CursorStyle) -> Option<xproto::Cursor> {
1868        if let Some(cursor) = self.cursor_cache.get(&style) {
1869            return *cursor;
1870        }
1871
1872        let mut result;
1873        match style {
1874            CursorStyle::None => match create_invisible_cursor(&self.xcb_connection) {
1875                Ok(loaded_cursor) => result = Ok(loaded_cursor),
1876                Err(err) => result = Err(err.context("X11: error while creating invisible cursor")),
1877            },
1878            _ => 'outer: {
1879                let mut errors = String::new();
1880                let cursor_icon_names = style.to_icon_names();
1881                for cursor_icon_name in cursor_icon_names {
1882                    match self
1883                        .cursor_handle
1884                        .load_cursor(&self.xcb_connection, cursor_icon_name)
1885                    {
1886                        Ok(loaded_cursor) => {
1887                            if loaded_cursor != x11rb::NONE {
1888                                result = Ok(loaded_cursor);
1889                                break 'outer;
1890                            }
1891                        }
1892                        Err(err) => {
1893                            errors.push_str(&err.to_string());
1894                            errors.push('\n');
1895                        }
1896                    }
1897                }
1898                if errors.is_empty() {
1899                    result = Err(anyhow!(
1900                        "errors while loading cursor icons {:?}:\n{}",
1901                        cursor_icon_names,
1902                        errors
1903                    ));
1904                } else {
1905                    result = Err(anyhow!("did not find cursor icons {:?}", cursor_icon_names));
1906                }
1907            }
1908        };
1909
1910        let cursor = match result {
1911            Ok(cursor) => Some(cursor),
1912            Err(err) => {
1913                match self
1914                    .cursor_handle
1915                    .load_cursor(&self.xcb_connection, DEFAULT_CURSOR_ICON_NAME)
1916                {
1917                    Ok(default) => {
1918                        log_cursor_icon_warning(err.context(format!(
1919                            "X11: error loading cursor icon, falling back on default icon '{}'",
1920                            DEFAULT_CURSOR_ICON_NAME
1921                        )));
1922                        Some(default)
1923                    }
1924                    Err(default_err) => {
1925                        log_cursor_icon_warning(err.context(default_err).context(format!(
1926                            "X11: error loading default cursor fallback '{}'",
1927                            DEFAULT_CURSOR_ICON_NAME
1928                        )));
1929                        None
1930                    }
1931                }
1932            }
1933        };
1934
1935        self.cursor_cache.insert(style, cursor);
1936        cursor
1937    }
1938}
1939
1940// Adapted from:
1941// https://docs.rs/winit/0.29.11/src/winit/platform_impl/linux/x11/monitor.rs.html#103-111
1942pub fn mode_refresh_rate(mode: &randr::ModeInfo) -> Duration {
1943    if mode.dot_clock == 0 || mode.htotal == 0 || mode.vtotal == 0 {
1944        return Duration::from_millis(16);
1945    }
1946
1947    let millihertz = mode.dot_clock as u64 * 1_000 / (mode.htotal as u64 * mode.vtotal as u64);
1948    let micros = 1_000_000_000 / millihertz;
1949    log::info!("Refreshing every {}ms", micros / 1_000);
1950    Duration::from_micros(micros)
1951}
1952
1953fn fp3232_to_f32(value: xinput::Fp3232) -> f32 {
1954    value.integral as f32 + value.frac as f32 / u32::MAX as f32
1955}
1956
1957fn check_compositor_present(xcb_connection: &XCBConnection, root: u32) -> bool {
1958    // Method 1: Check for _NET_WM_CM_S{root}
1959    let atom_name = format!("_NET_WM_CM_S{}", root);
1960    let atom1 = get_reply(
1961        || format!("Failed to intern {atom_name}"),
1962        xcb_connection.intern_atom(false, atom_name.as_bytes()),
1963    );
1964    let method1 = match atom1.log_with_level(Level::Debug) {
1965        Some(reply) if reply.atom != x11rb::NONE => {
1966            let atom = reply.atom;
1967            get_reply(
1968                || format!("Failed to get {atom_name} owner"),
1969                xcb_connection.get_selection_owner(atom),
1970            )
1971            .map(|reply| reply.owner != 0)
1972            .log_with_level(Level::Debug)
1973            .unwrap_or(false)
1974        }
1975        _ => false,
1976    };
1977
1978    // Method 2: Check for _NET_WM_CM_OWNER
1979    let atom_name = "_NET_WM_CM_OWNER";
1980    let atom2 = get_reply(
1981        || format!("Failed to intern {atom_name}"),
1982        xcb_connection.intern_atom(false, atom_name.as_bytes()),
1983    );
1984    let method2 = match atom2.log_with_level(Level::Debug) {
1985        Some(reply) if reply.atom != x11rb::NONE => {
1986            let atom = reply.atom;
1987            get_reply(
1988                || format!("Failed to get {atom_name}"),
1989                xcb_connection.get_property(false, root, atom, xproto::AtomEnum::WINDOW, 0, 1),
1990            )
1991            .map(|reply| reply.value_len > 0)
1992            .unwrap_or(false)
1993        }
1994        _ => return false,
1995    };
1996
1997    // Method 3: Check for _NET_SUPPORTING_WM_CHECK
1998    let atom_name = "_NET_SUPPORTING_WM_CHECK";
1999    let atom3 = get_reply(
2000        || format!("Failed to intern {atom_name}"),
2001        xcb_connection.intern_atom(false, atom_name.as_bytes()),
2002    );
2003    let method3 = match atom3.log_with_level(Level::Debug) {
2004        Some(reply) if reply.atom != x11rb::NONE => {
2005            let atom = reply.atom;
2006            get_reply(
2007                || format!("Failed to get {atom_name}"),
2008                xcb_connection.get_property(false, root, atom, xproto::AtomEnum::WINDOW, 0, 1),
2009            )
2010            .map(|reply| reply.value_len > 0)
2011            .unwrap_or(false)
2012        }
2013        _ => return false,
2014    };
2015
2016    log::debug!(
2017        "Compositor detection: _NET_WM_CM_S?={}, _NET_WM_CM_OWNER={}, _NET_SUPPORTING_WM_CHECK={}",
2018        method1,
2019        method2,
2020        method3
2021    );
2022
2023    method1 || method2 || method3
2024}
2025
2026fn check_gtk_frame_extents_supported(
2027    xcb_connection: &XCBConnection,
2028    atoms: &XcbAtoms,
2029    root: xproto::Window,
2030) -> bool {
2031    let Some(supported_atoms) = get_reply(
2032        || "Failed to get _NET_SUPPORTED",
2033        xcb_connection.get_property(
2034            false,
2035            root,
2036            atoms._NET_SUPPORTED,
2037            xproto::AtomEnum::ATOM,
2038            0,
2039            1024,
2040        ),
2041    )
2042    .log_with_level(Level::Debug) else {
2043        return false;
2044    };
2045
2046    let supported_atom_ids: Vec<u32> = supported_atoms
2047        .value
2048        .chunks_exact(4)
2049        .filter_map(|chunk| chunk.try_into().ok().map(u32::from_ne_bytes))
2050        .collect();
2051
2052    supported_atom_ids.contains(&atoms._GTK_FRAME_EXTENTS)
2053}
2054
2055fn xdnd_is_atom_supported(atom: u32, atoms: &XcbAtoms) -> bool {
2056    return atom == atoms.TEXT
2057        || atom == atoms.STRING
2058        || atom == atoms.UTF8_STRING
2059        || atom == atoms.TEXT_PLAIN
2060        || atom == atoms.TEXT_PLAIN_UTF8
2061        || atom == atoms.TextUriList;
2062}
2063
2064fn xdnd_get_supported_atom(
2065    xcb_connection: &XCBConnection,
2066    supported_atoms: &XcbAtoms,
2067    target: xproto::Window,
2068) -> u32 {
2069    if let Some(reply) = get_reply(
2070        || "Failed to get XDnD supported atoms",
2071        xcb_connection.get_property(
2072            false,
2073            target,
2074            supported_atoms.XdndTypeList,
2075            AtomEnum::ANY,
2076            0,
2077            1024,
2078        ),
2079    )
2080    .log_with_level(Level::Warn)
2081    {
2082        if let Some(atoms) = reply.value32() {
2083            for atom in atoms {
2084                if xdnd_is_atom_supported(atom, &supported_atoms) {
2085                    return atom;
2086                }
2087            }
2088        }
2089    }
2090    return 0;
2091}
2092
2093fn xdnd_send_finished(
2094    xcb_connection: &XCBConnection,
2095    atoms: &XcbAtoms,
2096    source: xproto::Window,
2097    target: xproto::Window,
2098) {
2099    let message = ClientMessageEvent {
2100        format: 32,
2101        window: target,
2102        type_: atoms.XdndFinished,
2103        data: ClientMessageData::from([source, 1, atoms.XdndActionCopy, 0, 0]),
2104        sequence: 0,
2105        response_type: xproto::CLIENT_MESSAGE_EVENT,
2106    };
2107    check_reply(
2108        || "Failed to send XDnD finished event",
2109        xcb_connection.send_event(false, target, EventMask::default(), message),
2110    )
2111    .log_err();
2112    xcb_connection.flush().log_err();
2113}
2114
2115fn xdnd_send_status(
2116    xcb_connection: &XCBConnection,
2117    atoms: &XcbAtoms,
2118    source: xproto::Window,
2119    target: xproto::Window,
2120    action: u32,
2121) {
2122    let message = ClientMessageEvent {
2123        format: 32,
2124        window: target,
2125        type_: atoms.XdndStatus,
2126        data: ClientMessageData::from([source, 1, 0, 0, action]),
2127        sequence: 0,
2128        response_type: xproto::CLIENT_MESSAGE_EVENT,
2129    };
2130    check_reply(
2131        || "Failed to send XDnD status event",
2132        xcb_connection.send_event(false, target, EventMask::default(), message),
2133    )
2134    .log_err();
2135    xcb_connection.flush().log_err();
2136}
2137
2138/// Recomputes `pointer_device_states` by querying all pointer devices.
2139/// When a device is present in `scroll_values_to_preserve`, its value for `ScrollAxisState.scroll_value` is used.
2140fn current_pointer_device_states(
2141    xcb_connection: &XCBConnection,
2142    scroll_values_to_preserve: &BTreeMap<xinput::DeviceId, PointerDeviceState>,
2143) -> Option<BTreeMap<xinput::DeviceId, PointerDeviceState>> {
2144    let devices_query_result = get_reply(
2145        || "Failed to query XInput devices",
2146        xcb_connection.xinput_xi_query_device(XINPUT_ALL_DEVICES),
2147    )
2148    .log_err()?;
2149
2150    let mut pointer_device_states = BTreeMap::new();
2151    pointer_device_states.extend(
2152        devices_query_result
2153            .infos
2154            .iter()
2155            .filter(|info| is_pointer_device(info.type_))
2156            .filter_map(|info| {
2157                let scroll_data = info
2158                    .classes
2159                    .iter()
2160                    .filter_map(|class| class.data.as_scroll())
2161                    .map(|class| *class)
2162                    .rev()
2163                    .collect::<Vec<_>>();
2164                let old_state = scroll_values_to_preserve.get(&info.deviceid);
2165                let old_horizontal = old_state.map(|state| &state.horizontal);
2166                let old_vertical = old_state.map(|state| &state.vertical);
2167                let horizontal = scroll_data
2168                    .iter()
2169                    .find(|data| data.scroll_type == xinput::ScrollType::HORIZONTAL)
2170                    .map(|data| scroll_data_to_axis_state(data, old_horizontal));
2171                let vertical = scroll_data
2172                    .iter()
2173                    .find(|data| data.scroll_type == xinput::ScrollType::VERTICAL)
2174                    .map(|data| scroll_data_to_axis_state(data, old_vertical));
2175                if horizontal.is_none() && vertical.is_none() {
2176                    None
2177                } else {
2178                    Some((
2179                        info.deviceid,
2180                        PointerDeviceState {
2181                            horizontal: horizontal.unwrap_or_else(Default::default),
2182                            vertical: vertical.unwrap_or_else(Default::default),
2183                        },
2184                    ))
2185                }
2186            }),
2187    );
2188    if pointer_device_states.is_empty() {
2189        log::error!("Found no xinput mouse pointers.");
2190    }
2191    return Some(pointer_device_states);
2192}
2193
2194/// Returns true if the device is a pointer device. Does not include pointer device groups.
2195fn is_pointer_device(type_: xinput::DeviceType) -> bool {
2196    type_ == xinput::DeviceType::SLAVE_POINTER
2197}
2198
2199fn scroll_data_to_axis_state(
2200    data: &xinput::DeviceClassDataScroll,
2201    old_axis_state_with_valid_scroll_value: Option<&ScrollAxisState>,
2202) -> ScrollAxisState {
2203    ScrollAxisState {
2204        valuator_number: Some(data.number),
2205        multiplier: SCROLL_LINES / fp3232_to_f32(data.increment),
2206        scroll_value: old_axis_state_with_valid_scroll_value.and_then(|state| state.scroll_value),
2207    }
2208}
2209
2210fn reset_all_pointer_device_scroll_positions(
2211    pointer_device_states: &mut BTreeMap<xinput::DeviceId, PointerDeviceState>,
2212) {
2213    pointer_device_states
2214        .iter_mut()
2215        .for_each(|(_, device_state)| reset_pointer_device_scroll_positions(device_state));
2216}
2217
2218fn reset_pointer_device_scroll_positions(pointer: &mut PointerDeviceState) {
2219    pointer.horizontal.scroll_value = None;
2220    pointer.vertical.scroll_value = None;
2221}
2222
2223/// Returns the scroll delta for a smooth scrolling motion event, or `None` if no scroll data is present.
2224fn get_scroll_delta_and_update_state(
2225    pointer: &mut PointerDeviceState,
2226    event: &xinput::MotionEvent,
2227) -> Option<Point<f32>> {
2228    let delta_x = get_axis_scroll_delta_and_update_state(event, &mut pointer.horizontal);
2229    let delta_y = get_axis_scroll_delta_and_update_state(event, &mut pointer.vertical);
2230    if delta_x.is_some() || delta_y.is_some() {
2231        Some(Point::new(delta_x.unwrap_or(0.0), delta_y.unwrap_or(0.0)))
2232    } else {
2233        None
2234    }
2235}
2236
2237fn get_axis_scroll_delta_and_update_state(
2238    event: &xinput::MotionEvent,
2239    axis: &mut ScrollAxisState,
2240) -> Option<f32> {
2241    let axis_index = get_valuator_axis_index(&event.valuator_mask, axis.valuator_number?)?;
2242    if let Some(axis_value) = event.axisvalues.get(axis_index) {
2243        let new_scroll = fp3232_to_f32(*axis_value);
2244        let delta_scroll = axis
2245            .scroll_value
2246            .map(|old_scroll| (old_scroll - new_scroll) * axis.multiplier);
2247        axis.scroll_value = Some(new_scroll);
2248        delta_scroll
2249    } else {
2250        log::error!("Encountered invalid XInput valuator_mask, scrolling may not work properly.");
2251        None
2252    }
2253}
2254
2255fn make_scroll_wheel_event(
2256    position: Point<Pixels>,
2257    scroll_delta: Point<f32>,
2258    modifiers: Modifiers,
2259) -> crate::ScrollWheelEvent {
2260    // When shift is held down, vertical scrolling turns into horizontal scrolling.
2261    let delta = if modifiers.shift {
2262        Point {
2263            x: scroll_delta.y,
2264            y: 0.0,
2265        }
2266    } else {
2267        scroll_delta
2268    };
2269    crate::ScrollWheelEvent {
2270        position,
2271        delta: ScrollDelta::Lines(delta),
2272        modifiers,
2273        touch_phase: TouchPhase::default(),
2274    }
2275}
2276
2277fn create_invisible_cursor(
2278    connection: &XCBConnection,
2279) -> anyhow::Result<crate::platform::linux::x11::client::xproto::Cursor> {
2280    let empty_pixmap = connection.generate_id()?;
2281    let root = connection.setup().roots[0].root;
2282    connection.create_pixmap(1, empty_pixmap, root, 1, 1)?;
2283
2284    let cursor = connection.generate_id()?;
2285    connection.create_cursor(cursor, empty_pixmap, empty_pixmap, 0, 0, 0, 0, 0, 0, 0, 0)?;
2286
2287    connection.free_pixmap(empty_pixmap)?;
2288
2289    xcb_flush(connection);
2290    Ok(cursor)
2291}