client.rs

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