client.rs

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