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