client.rs

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