client.rs

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