client.rs

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