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