client.rs

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