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