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