client.rs

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