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                let depressed_layout = xkb_state.serialize_layout(xkbc::STATE_LAYOUT_DEPRESSED);
 845                let latched_layout = xkb_state.serialize_layout(xkbc::STATE_LAYOUT_LATCHED);
 846                let locked_layout = xkb_state.serialize_layout(xkbc::ffi::XKB_STATE_LAYOUT_LOCKED);
 847                state.previous_xkb_state = XKBStateNotiy {
 848                    depressed_layout,
 849                    latched_layout,
 850                    locked_layout,
 851                };
 852                state.xkb = xkb_state;
 853            }
 854            Event::XkbStateNotify(event) => {
 855                let mut state = self.0.borrow_mut();
 856                let old_layout = state.xkb.serialize_layout(STATE_LAYOUT_EFFECTIVE);
 857                let new_layout = u32::from(event.group);
 858                state.xkb.update_mask(
 859                    event.base_mods.into(),
 860                    event.latched_mods.into(),
 861                    event.locked_mods.into(),
 862                    event.base_group as u32,
 863                    event.latched_group as u32,
 864                    event.locked_group.into(),
 865                );
 866                state.previous_xkb_state = XKBStateNotiy {
 867                    depressed_layout: event.base_group as u32,
 868                    latched_layout: event.latched_group as u32,
 869                    locked_layout: event.locked_group.into(),
 870                };
 871
 872                if new_layout != old_layout {
 873                    if let Some(mut callback) = state.common.callbacks.keyboard_layout_change.take()
 874                    {
 875                        drop(state);
 876                        callback();
 877                        state = self.0.borrow_mut();
 878                        state.common.callbacks.keyboard_layout_change = Some(callback);
 879                    }
 880                }
 881
 882                let modifiers = Modifiers::from_xkb(&state.xkb);
 883                if state.last_modifiers_changed_event == modifiers {
 884                    drop(state);
 885                } else {
 886                    let focused_window_id = state.keyboard_focused_window?;
 887                    state.modifiers = modifiers;
 888                    state.last_modifiers_changed_event = modifiers;
 889                    drop(state);
 890
 891                    let focused_window = self.get_window(focused_window_id)?;
 892                    focused_window.handle_input(PlatformInput::ModifiersChanged(
 893                        ModifiersChangedEvent { modifiers },
 894                    ));
 895                }
 896            }
 897            Event::KeyPress(event) => {
 898                let window = self.get_window(event.event)?;
 899                let mut state = self.0.borrow_mut();
 900
 901                let modifiers = modifiers_from_state(event.state);
 902                state.modifiers = modifiers;
 903                state.pre_key_char_down.take();
 904                let keystroke = {
 905                    let code = event.detail.into();
 906                    let xkb_state = state.previous_xkb_state.clone();
 907                    state.xkb.update_mask(
 908                        event.state.bits() as ModMask,
 909                        0,
 910                        0,
 911                        xkb_state.depressed_layout,
 912                        xkb_state.latched_layout,
 913                        xkb_state.locked_layout,
 914                    );
 915                    let mut keystroke = crate::Keystroke::from_xkb(&state.xkb, modifiers, code);
 916                    let keysym = state.xkb.key_get_one_sym(code);
 917                    if keysym.is_modifier_key() {
 918                        return Some(());
 919                    }
 920                    if let Some(mut compose_state) = state.compose_state.take() {
 921                        compose_state.feed(keysym);
 922                        match compose_state.status() {
 923                            xkbc::Status::Composed => {
 924                                state.pre_edit_text.take();
 925                                keystroke.key_char = compose_state.utf8();
 926                                if let Some(keysym) = compose_state.keysym() {
 927                                    keystroke.key = xkbc::keysym_get_name(keysym);
 928                                }
 929                            }
 930                            xkbc::Status::Composing => {
 931                                keystroke.key_char = None;
 932                                state.pre_edit_text = compose_state
 933                                    .utf8()
 934                                    .or(crate::Keystroke::underlying_dead_key(keysym));
 935                                let pre_edit =
 936                                    state.pre_edit_text.clone().unwrap_or(String::default());
 937                                drop(state);
 938                                window.handle_ime_preedit(pre_edit);
 939                                state = self.0.borrow_mut();
 940                            }
 941                            xkbc::Status::Cancelled => {
 942                                let pre_edit = state.pre_edit_text.take();
 943                                drop(state);
 944                                if let Some(pre_edit) = pre_edit {
 945                                    window.handle_ime_commit(pre_edit);
 946                                }
 947                                if let Some(current_key) = Keystroke::underlying_dead_key(keysym) {
 948                                    window.handle_ime_preedit(current_key);
 949                                }
 950                                state = self.0.borrow_mut();
 951                                compose_state.feed(keysym);
 952                            }
 953                            _ => {}
 954                        }
 955                        state.compose_state = Some(compose_state);
 956                    }
 957                    keystroke
 958                };
 959                drop(state);
 960                window.handle_input(PlatformInput::KeyDown(crate::KeyDownEvent {
 961                    keystroke,
 962                    is_held: false,
 963                }));
 964            }
 965            Event::KeyRelease(event) => {
 966                let window = self.get_window(event.event)?;
 967                let mut state = self.0.borrow_mut();
 968
 969                let modifiers = modifiers_from_state(event.state);
 970                state.modifiers = modifiers;
 971
 972                let keystroke = {
 973                    let code = event.detail.into();
 974                    let xkb_state = state.previous_xkb_state.clone();
 975                    state.xkb.update_mask(
 976                        event.state.bits() as ModMask,
 977                        0,
 978                        0,
 979                        xkb_state.depressed_layout,
 980                        xkb_state.latched_layout,
 981                        xkb_state.locked_layout,
 982                    );
 983                    let keystroke = crate::Keystroke::from_xkb(&state.xkb, modifiers, code);
 984                    let keysym = state.xkb.key_get_one_sym(code);
 985                    if keysym.is_modifier_key() {
 986                        return Some(());
 987                    }
 988                    keystroke
 989                };
 990                drop(state);
 991                window.handle_input(PlatformInput::KeyUp(crate::KeyUpEvent { keystroke }));
 992            }
 993            Event::XinputButtonPress(event) => {
 994                let window = self.get_window(event.event)?;
 995                let mut state = self.0.borrow_mut();
 996
 997                let modifiers = modifiers_from_xinput_info(event.mods);
 998                state.modifiers = modifiers;
 999
1000                let position = point(
1001                    px(event.event_x as f32 / u16::MAX as f32 / state.scale_factor),
1002                    px(event.event_y as f32 / u16::MAX as f32 / state.scale_factor),
1003                );
1004
1005                if state.composing && state.ximc.is_some() {
1006                    drop(state);
1007                    self.reset_ime();
1008                    window.handle_ime_unmark();
1009                    state = self.0.borrow_mut();
1010                } else if let Some(text) = state.pre_edit_text.take() {
1011                    if let Some(compose_state) = state.compose_state.as_mut() {
1012                        compose_state.reset();
1013                    }
1014                    drop(state);
1015                    window.handle_ime_commit(text);
1016                    state = self.0.borrow_mut();
1017                }
1018                match button_or_scroll_from_event_detail(event.detail) {
1019                    Some(ButtonOrScroll::Button(button)) => {
1020                        let click_elapsed = state.last_click.elapsed();
1021                        if click_elapsed < DOUBLE_CLICK_INTERVAL
1022                            && state
1023                                .last_mouse_button
1024                                .is_some_and(|prev_button| prev_button == button)
1025                            && is_within_click_distance(state.last_location, position)
1026                        {
1027                            state.current_count += 1;
1028                        } else {
1029                            state.current_count = 1;
1030                        }
1031
1032                        state.last_click = Instant::now();
1033                        state.last_mouse_button = Some(button);
1034                        state.last_location = position;
1035                        let current_count = state.current_count;
1036
1037                        drop(state);
1038                        window.handle_input(PlatformInput::MouseDown(crate::MouseDownEvent {
1039                            button,
1040                            position,
1041                            modifiers,
1042                            click_count: current_count,
1043                            first_mouse: false,
1044                        }));
1045                    }
1046                    Some(ButtonOrScroll::Scroll(direction)) => {
1047                        drop(state);
1048                        // Emulated scroll button presses are sent simultaneously with smooth scrolling XinputMotion events.
1049                        // Since handling those events does the scrolling, they are skipped here.
1050                        if !event
1051                            .flags
1052                            .contains(xinput::PointerEventFlags::POINTER_EMULATED)
1053                        {
1054                            let scroll_delta = match direction {
1055                                ScrollDirection::Up => Point::new(0.0, SCROLL_LINES),
1056                                ScrollDirection::Down => Point::new(0.0, -SCROLL_LINES),
1057                                ScrollDirection::Left => Point::new(SCROLL_LINES, 0.0),
1058                                ScrollDirection::Right => Point::new(-SCROLL_LINES, 0.0),
1059                            };
1060                            window.handle_input(PlatformInput::ScrollWheel(
1061                                make_scroll_wheel_event(position, scroll_delta, modifiers),
1062                            ));
1063                        }
1064                    }
1065                    None => {
1066                        log::error!("Unknown x11 button: {}", event.detail);
1067                    }
1068                }
1069            }
1070            Event::XinputButtonRelease(event) => {
1071                let window = self.get_window(event.event)?;
1072                let mut state = self.0.borrow_mut();
1073                let modifiers = modifiers_from_xinput_info(event.mods);
1074                state.modifiers = modifiers;
1075
1076                let position = point(
1077                    px(event.event_x as f32 / u16::MAX as f32 / state.scale_factor),
1078                    px(event.event_y as f32 / u16::MAX as f32 / state.scale_factor),
1079                );
1080                match button_or_scroll_from_event_detail(event.detail) {
1081                    Some(ButtonOrScroll::Button(button)) => {
1082                        let click_count = state.current_count;
1083                        drop(state);
1084                        window.handle_input(PlatformInput::MouseUp(crate::MouseUpEvent {
1085                            button,
1086                            position,
1087                            modifiers,
1088                            click_count,
1089                        }));
1090                    }
1091                    Some(ButtonOrScroll::Scroll(_)) => {}
1092                    None => {}
1093                }
1094            }
1095            Event::XinputMotion(event) => {
1096                let window = self.get_window(event.event)?;
1097                let mut state = self.0.borrow_mut();
1098                let pressed_button = pressed_button_from_mask(event.button_mask[0]);
1099                let position = point(
1100                    px(event.event_x as f32 / u16::MAX as f32 / state.scale_factor),
1101                    px(event.event_y as f32 / u16::MAX as f32 / state.scale_factor),
1102                );
1103                let modifiers = modifiers_from_xinput_info(event.mods);
1104                state.modifiers = modifiers;
1105                drop(state);
1106
1107                if event.valuator_mask[0] & 3 != 0 {
1108                    window.handle_input(PlatformInput::MouseMove(crate::MouseMoveEvent {
1109                        position,
1110                        pressed_button,
1111                        modifiers,
1112                    }));
1113                }
1114
1115                state = self.0.borrow_mut();
1116                if let Some(mut pointer) = state.pointer_device_states.get_mut(&event.sourceid) {
1117                    let scroll_delta = get_scroll_delta_and_update_state(&mut pointer, &event);
1118                    drop(state);
1119                    if let Some(scroll_delta) = scroll_delta {
1120                        window.handle_input(PlatformInput::ScrollWheel(make_scroll_wheel_event(
1121                            position,
1122                            scroll_delta,
1123                            modifiers,
1124                        )));
1125                    }
1126                }
1127            }
1128            Event::XinputEnter(event) if event.mode == xinput::NotifyMode::NORMAL => {
1129                let window = self.get_window(event.event)?;
1130                window.set_hovered(true);
1131                let mut state = self.0.borrow_mut();
1132                state.mouse_focused_window = Some(event.event);
1133            }
1134            Event::XinputLeave(event) if event.mode == xinput::NotifyMode::NORMAL => {
1135                let mut state = self.0.borrow_mut();
1136
1137                // 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)
1138                reset_all_pointer_device_scroll_positions(&mut state.pointer_device_states);
1139                state.mouse_focused_window = None;
1140                let pressed_button = pressed_button_from_mask(event.buttons[0]);
1141                let position = point(
1142                    px(event.event_x as f32 / u16::MAX as f32 / state.scale_factor),
1143                    px(event.event_y as f32 / u16::MAX as f32 / state.scale_factor),
1144                );
1145                let modifiers = modifiers_from_xinput_info(event.mods);
1146                state.modifiers = modifiers;
1147                drop(state);
1148
1149                let window = self.get_window(event.event)?;
1150                window.handle_input(PlatformInput::MouseExited(crate::MouseExitEvent {
1151                    pressed_button,
1152                    position,
1153                    modifiers,
1154                }));
1155                window.set_hovered(false);
1156            }
1157            Event::XinputHierarchy(event) => {
1158                let mut state = self.0.borrow_mut();
1159                // Temporarily use `state.pointer_device_states` to only store pointers that still have valid scroll values.
1160                // Any change to a device invalidates its scroll values.
1161                for info in event.infos {
1162                    if is_pointer_device(info.type_) {
1163                        state.pointer_device_states.remove(&info.deviceid);
1164                    }
1165                }
1166                state.pointer_device_states = get_new_pointer_device_states(
1167                    &state.xcb_connection,
1168                    &state.pointer_device_states,
1169                );
1170            }
1171            Event::XinputDeviceChanged(event) => {
1172                let mut state = self.0.borrow_mut();
1173                if let Some(mut pointer) = state.pointer_device_states.get_mut(&event.sourceid) {
1174                    reset_pointer_device_scroll_positions(&mut pointer);
1175                }
1176            }
1177            _ => {}
1178        };
1179
1180        Some(())
1181    }
1182
1183    fn handle_xim_callback_event(&self, event: XimCallbackEvent) {
1184        match event {
1185            XimCallbackEvent::XimXEvent(event) => {
1186                self.handle_event(event);
1187            }
1188            XimCallbackEvent::XimCommitEvent(window, text) => {
1189                self.xim_handle_commit(window, text);
1190            }
1191            XimCallbackEvent::XimPreeditEvent(window, text) => {
1192                self.xim_handle_preedit(window, text);
1193            }
1194        };
1195    }
1196
1197    fn xim_handle_event(&self, event: Event) -> Option<()> {
1198        match event {
1199            Event::KeyPress(event) | Event::KeyRelease(event) => {
1200                let mut state = self.0.borrow_mut();
1201                state.pre_key_char_down = Some(Keystroke::from_xkb(
1202                    &state.xkb,
1203                    state.modifiers,
1204                    event.detail.into(),
1205                ));
1206                let mut ximc = state.ximc.take().unwrap();
1207                let mut xim_handler = state.xim_handler.take().unwrap();
1208                drop(state);
1209                xim_handler.window = event.event;
1210                ximc.forward_event(
1211                    xim_handler.im_id,
1212                    xim_handler.ic_id,
1213                    xim::ForwardEventFlag::empty(),
1214                    &event,
1215                )
1216                .unwrap();
1217                let mut state = self.0.borrow_mut();
1218                state.ximc = Some(ximc);
1219                state.xim_handler = Some(xim_handler);
1220                drop(state);
1221            }
1222            event => {
1223                self.handle_event(event);
1224            }
1225        }
1226        Some(())
1227    }
1228
1229    fn xim_handle_commit(&self, window: xproto::Window, text: String) -> Option<()> {
1230        let window = self.get_window(window).unwrap();
1231        let mut state = self.0.borrow_mut();
1232        let keystroke = state.pre_key_char_down.take();
1233        state.composing = false;
1234        drop(state);
1235        if let Some(mut keystroke) = keystroke {
1236            keystroke.key_char = Some(text.clone());
1237            window.handle_input(PlatformInput::KeyDown(crate::KeyDownEvent {
1238                keystroke,
1239                is_held: false,
1240            }));
1241        }
1242
1243        Some(())
1244    }
1245
1246    fn xim_handle_preedit(&self, window: xproto::Window, text: String) -> Option<()> {
1247        let window = self.get_window(window).unwrap();
1248
1249        let mut state = self.0.borrow_mut();
1250        let mut ximc = state.ximc.take().unwrap();
1251        let mut xim_handler = state.xim_handler.take().unwrap();
1252        state.composing = !text.is_empty();
1253        drop(state);
1254        window.handle_ime_preedit(text);
1255
1256        if let Some(area) = window.get_ime_area() {
1257            let ic_attributes = ximc
1258                .build_ic_attributes()
1259                .push(
1260                    xim::AttributeName::InputStyle,
1261                    xim::InputStyle::PREEDIT_CALLBACKS,
1262                )
1263                .push(xim::AttributeName::ClientWindow, xim_handler.window)
1264                .push(xim::AttributeName::FocusWindow, xim_handler.window)
1265                .nested_list(xim::AttributeName::PreeditAttributes, |b| {
1266                    b.push(
1267                        xim::AttributeName::SpotLocation,
1268                        xim::Point {
1269                            x: u32::from(area.origin.x + area.size.width) as i16,
1270                            y: u32::from(area.origin.y + area.size.height) as i16,
1271                        },
1272                    );
1273                })
1274                .build();
1275            ximc.set_ic_values(xim_handler.im_id, xim_handler.ic_id, ic_attributes)
1276                .ok();
1277        }
1278        let mut state = self.0.borrow_mut();
1279        state.ximc = Some(ximc);
1280        state.xim_handler = Some(xim_handler);
1281        drop(state);
1282        Some(())
1283    }
1284}
1285
1286impl LinuxClient for X11Client {
1287    fn compositor_name(&self) -> &'static str {
1288        "X11"
1289    }
1290
1291    fn with_common<R>(&self, f: impl FnOnce(&mut LinuxCommon) -> R) -> R {
1292        f(&mut self.0.borrow_mut().common)
1293    }
1294
1295    fn keyboard_layout(&self) -> Box<dyn PlatformKeyboardLayout> {
1296        let state = self.0.borrow();
1297        let layout_idx = state.xkb.serialize_layout(STATE_LAYOUT_EFFECTIVE);
1298        Box::new(LinuxKeyboardLayout::new(
1299            state
1300                .xkb
1301                .get_keymap()
1302                .layout_get_name(layout_idx)
1303                .to_string(),
1304        ))
1305    }
1306
1307    fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
1308        let state = self.0.borrow();
1309        let setup = state.xcb_connection.setup();
1310        setup
1311            .roots
1312            .iter()
1313            .enumerate()
1314            .filter_map(|(root_id, _)| {
1315                Some(Rc::new(
1316                    X11Display::new(&state.xcb_connection, state.scale_factor, root_id).ok()?,
1317                ) as Rc<dyn PlatformDisplay>)
1318            })
1319            .collect()
1320    }
1321
1322    fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
1323        let state = self.0.borrow();
1324
1325        Some(Rc::new(
1326            X11Display::new(
1327                &state.xcb_connection,
1328                state.scale_factor,
1329                state.x_root_index,
1330            )
1331            .expect("There should always be a root index"),
1332        ))
1333    }
1334
1335    fn display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>> {
1336        let state = self.0.borrow();
1337
1338        Some(Rc::new(
1339            X11Display::new(&state.xcb_connection, state.scale_factor, id.0 as usize).ok()?,
1340        ))
1341    }
1342
1343    fn is_screen_capture_supported(&self) -> bool {
1344        true
1345    }
1346
1347    fn screen_capture_sources(
1348        &self,
1349    ) -> oneshot::Receiver<anyhow::Result<Vec<Box<dyn ScreenCaptureSource>>>> {
1350        scap_screen_sources(&self.0.borrow().common.foreground_executor)
1351    }
1352
1353    fn open_window(
1354        &self,
1355        handle: AnyWindowHandle,
1356        params: WindowParams,
1357    ) -> anyhow::Result<Box<dyn PlatformWindow>> {
1358        let mut state = self.0.borrow_mut();
1359        let x_window = state.xcb_connection.generate_id().unwrap();
1360
1361        let window = X11Window::new(
1362            handle,
1363            X11ClientStatePtr(Rc::downgrade(&self.0)),
1364            state.common.foreground_executor.clone(),
1365            &state.gpu_context,
1366            params,
1367            &state.xcb_connection,
1368            state.client_side_decorations_supported,
1369            state.x_root_index,
1370            x_window,
1371            &state.atoms,
1372            state.scale_factor,
1373            state.common.appearance,
1374        )?;
1375        state
1376            .xcb_connection
1377            .change_property32(
1378                xproto::PropMode::REPLACE,
1379                x_window,
1380                state.atoms.XdndAware,
1381                state.atoms.XA_ATOM,
1382                &[5],
1383            )
1384            .unwrap();
1385
1386        let screen_resources = state
1387            .xcb_connection
1388            .randr_get_screen_resources(x_window)
1389            .unwrap()
1390            .reply()
1391            .expect("Could not find available screens");
1392
1393        let mode = screen_resources
1394            .crtcs
1395            .iter()
1396            .find_map(|crtc| {
1397                let crtc_info = state
1398                    .xcb_connection
1399                    .randr_get_crtc_info(*crtc, x11rb::CURRENT_TIME)
1400                    .ok()?
1401                    .reply()
1402                    .ok()?;
1403
1404                screen_resources
1405                    .modes
1406                    .iter()
1407                    .find(|m| m.id == crtc_info.mode)
1408            })
1409            .expect("Unable to find screen refresh rate");
1410
1411        let refresh_event_token = state
1412            .loop_handle
1413            .insert_source(calloop::timer::Timer::immediate(), {
1414                let refresh_duration = mode_refresh_rate(mode);
1415                move |mut instant, (), client| {
1416                    let xcb_connection = {
1417                        let state = client.0.borrow_mut();
1418                        let xcb_connection = state.xcb_connection.clone();
1419                        if let Some(window) = state.windows.get(&x_window) {
1420                            let window = window.window.clone();
1421                            drop(state);
1422                            window.refresh(Default::default());
1423                        }
1424                        xcb_connection
1425                    };
1426                    client.process_x11_events(&xcb_connection).log_err();
1427
1428                    // Take into account that some frames have been skipped
1429                    let now = Instant::now();
1430                    while instant < now {
1431                        instant += refresh_duration;
1432                    }
1433                    calloop::timer::TimeoutAction::ToInstant(instant)
1434                }
1435            })
1436            .expect("Failed to initialize refresh timer");
1437
1438        let window_ref = WindowRef {
1439            window: window.0.clone(),
1440            refresh_event_token,
1441        };
1442
1443        state.windows.insert(x_window, window_ref);
1444        Ok(Box::new(window))
1445    }
1446
1447    fn set_cursor_style(&self, style: CursorStyle) {
1448        let mut state = self.0.borrow_mut();
1449        let Some(focused_window) = state.mouse_focused_window else {
1450            return;
1451        };
1452        let current_style = state
1453            .cursor_styles
1454            .get(&focused_window)
1455            .unwrap_or(&CursorStyle::Arrow);
1456        if *current_style == style {
1457            return;
1458        }
1459
1460        let cursor = match state.cursor_cache.get(&style) {
1461            Some(cursor) => *cursor,
1462            None => {
1463                let Some(cursor) = (match style {
1464                    CursorStyle::None => create_invisible_cursor(&state.xcb_connection).log_err(),
1465                    _ => state
1466                        .cursor_handle
1467                        .load_cursor(&state.xcb_connection, style.to_icon_name())
1468                        .log_err(),
1469                }) else {
1470                    return;
1471                };
1472
1473                state.cursor_cache.insert(style, cursor);
1474                cursor
1475            }
1476        };
1477
1478        state.cursor_styles.insert(focused_window, style);
1479        state
1480            .xcb_connection
1481            .change_window_attributes(
1482                focused_window,
1483                &ChangeWindowAttributesAux {
1484                    cursor: Some(cursor),
1485                    ..Default::default()
1486                },
1487            )
1488            .anyhow()
1489            .and_then(|cookie| cookie.check().anyhow())
1490            .context("setting cursor style")
1491            .log_err();
1492    }
1493
1494    fn open_uri(&self, uri: &str) {
1495        #[cfg(any(feature = "wayland", feature = "x11"))]
1496        open_uri_internal(self.background_executor(), uri, None);
1497    }
1498
1499    fn reveal_path(&self, path: PathBuf) {
1500        #[cfg(any(feature = "x11", feature = "wayland"))]
1501        reveal_path_internal(self.background_executor(), path, None);
1502    }
1503
1504    fn write_to_primary(&self, item: crate::ClipboardItem) {
1505        let state = self.0.borrow_mut();
1506        state
1507            .clipboard
1508            .set_text(
1509                std::borrow::Cow::Owned(item.text().unwrap_or_default()),
1510                clipboard::ClipboardKind::Primary,
1511                clipboard::WaitConfig::None,
1512            )
1513            .context("Failed to write to clipboard (primary)")
1514            .log_with_level(log::Level::Debug);
1515    }
1516
1517    fn write_to_clipboard(&self, item: crate::ClipboardItem) {
1518        let mut state = self.0.borrow_mut();
1519        state
1520            .clipboard
1521            .set_text(
1522                std::borrow::Cow::Owned(item.text().unwrap_or_default()),
1523                clipboard::ClipboardKind::Clipboard,
1524                clipboard::WaitConfig::None,
1525            )
1526            .context("Failed to write to clipboard (clipboard)")
1527            .log_with_level(log::Level::Debug);
1528        state.clipboard_item.replace(item);
1529    }
1530
1531    fn read_from_primary(&self) -> Option<crate::ClipboardItem> {
1532        let state = self.0.borrow_mut();
1533        return state
1534            .clipboard
1535            .get_any(clipboard::ClipboardKind::Primary)
1536            .context("Failed to read from clipboard (primary)")
1537            .log_with_level(log::Level::Debug);
1538    }
1539
1540    fn read_from_clipboard(&self) -> Option<crate::ClipboardItem> {
1541        let state = self.0.borrow_mut();
1542        // if the last copy was from this app, return our cached item
1543        // which has metadata attached.
1544        if state
1545            .clipboard
1546            .is_owner(clipboard::ClipboardKind::Clipboard)
1547        {
1548            return state.clipboard_item.clone();
1549        }
1550        return state
1551            .clipboard
1552            .get_any(clipboard::ClipboardKind::Clipboard)
1553            .context("Failed to read from clipboard (clipboard)")
1554            .log_with_level(log::Level::Debug);
1555    }
1556
1557    fn run(&self) {
1558        let mut event_loop = self
1559            .0
1560            .borrow_mut()
1561            .event_loop
1562            .take()
1563            .expect("App is already running");
1564
1565        event_loop.run(None, &mut self.clone(), |_| {}).log_err();
1566    }
1567
1568    fn active_window(&self) -> Option<AnyWindowHandle> {
1569        let state = self.0.borrow();
1570        state.keyboard_focused_window.and_then(|focused_window| {
1571            state
1572                .windows
1573                .get(&focused_window)
1574                .map(|window| window.handle())
1575        })
1576    }
1577
1578    fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
1579        let state = self.0.borrow();
1580        let root = state.xcb_connection.setup().roots[state.x_root_index].root;
1581
1582        let reply = state
1583            .xcb_connection
1584            .get_property(
1585                false,
1586                root,
1587                state.atoms._NET_CLIENT_LIST_STACKING,
1588                xproto::AtomEnum::WINDOW,
1589                0,
1590                u32::MAX,
1591            )
1592            .ok()?
1593            .reply()
1594            .ok()?;
1595
1596        let window_ids = reply
1597            .value
1598            .chunks_exact(4)
1599            .map(|chunk| u32::from_ne_bytes(chunk.try_into().unwrap()))
1600            .collect::<Vec<xproto::Window>>();
1601
1602        let mut handles = Vec::new();
1603
1604        // We need to reverse, since _NET_CLIENT_LIST_STACKING has
1605        // a back-to-front order.
1606        // See: https://specifications.freedesktop.org/wm-spec/1.3/ar01s03.html
1607        for window_ref in window_ids
1608            .iter()
1609            .rev()
1610            .filter_map(|&win| state.windows.get(&win))
1611        {
1612            if !window_ref.window.state.borrow().destroyed {
1613                handles.push(window_ref.handle());
1614            }
1615        }
1616
1617        Some(handles)
1618    }
1619}
1620
1621// Adapted from:
1622// https://docs.rs/winit/0.29.11/src/winit/platform_impl/linux/x11/monitor.rs.html#103-111
1623pub fn mode_refresh_rate(mode: &randr::ModeInfo) -> Duration {
1624    if mode.dot_clock == 0 || mode.htotal == 0 || mode.vtotal == 0 {
1625        return Duration::from_millis(16);
1626    }
1627
1628    let millihertz = mode.dot_clock as u64 * 1_000 / (mode.htotal as u64 * mode.vtotal as u64);
1629    let micros = 1_000_000_000 / millihertz;
1630    log::info!("Refreshing at {} micros", micros);
1631    Duration::from_micros(micros)
1632}
1633
1634fn fp3232_to_f32(value: xinput::Fp3232) -> f32 {
1635    value.integral as f32 + value.frac as f32 / u32::MAX as f32
1636}
1637
1638fn check_compositor_present(xcb_connection: &XCBConnection, root: u32) -> bool {
1639    // Method 1: Check for _NET_WM_CM_S{root}
1640    let atom_name = format!("_NET_WM_CM_S{}", root);
1641    let atom = xcb_connection
1642        .intern_atom(false, atom_name.as_bytes())
1643        .unwrap()
1644        .reply()
1645        .map(|reply| reply.atom)
1646        .unwrap_or(0);
1647
1648    let method1 = if atom != 0 {
1649        xcb_connection
1650            .get_selection_owner(atom)
1651            .unwrap()
1652            .reply()
1653            .map(|reply| reply.owner != 0)
1654            .unwrap_or(false)
1655    } else {
1656        false
1657    };
1658
1659    // Method 2: Check for _NET_WM_CM_OWNER
1660    let atom_name = "_NET_WM_CM_OWNER";
1661    let atom = xcb_connection
1662        .intern_atom(false, atom_name.as_bytes())
1663        .unwrap()
1664        .reply()
1665        .map(|reply| reply.atom)
1666        .unwrap_or(0);
1667
1668    let method2 = if atom != 0 {
1669        xcb_connection
1670            .get_property(false, root, atom, xproto::AtomEnum::WINDOW, 0, 1)
1671            .unwrap()
1672            .reply()
1673            .map(|reply| reply.value_len > 0)
1674            .unwrap_or(false)
1675    } else {
1676        false
1677    };
1678
1679    // Method 3: Check for _NET_SUPPORTING_WM_CHECK
1680    let atom_name = "_NET_SUPPORTING_WM_CHECK";
1681    let atom = xcb_connection
1682        .intern_atom(false, atom_name.as_bytes())
1683        .unwrap()
1684        .reply()
1685        .map(|reply| reply.atom)
1686        .unwrap_or(0);
1687
1688    let method3 = if atom != 0 {
1689        xcb_connection
1690            .get_property(false, root, atom, xproto::AtomEnum::WINDOW, 0, 1)
1691            .unwrap()
1692            .reply()
1693            .map(|reply| reply.value_len > 0)
1694            .unwrap_or(false)
1695    } else {
1696        false
1697    };
1698
1699    // TODO: Remove this
1700    log::info!(
1701        "Compositor detection: _NET_WM_CM_S?={}, _NET_WM_CM_OWNER={}, _NET_SUPPORTING_WM_CHECK={}",
1702        method1,
1703        method2,
1704        method3
1705    );
1706
1707    method1 || method2 || method3
1708}
1709
1710fn check_gtk_frame_extents_supported(
1711    xcb_connection: &XCBConnection,
1712    atoms: &XcbAtoms,
1713    root: xproto::Window,
1714) -> bool {
1715    let supported_atoms = xcb_connection
1716        .get_property(
1717            false,
1718            root,
1719            atoms._NET_SUPPORTED,
1720            xproto::AtomEnum::ATOM,
1721            0,
1722            1024,
1723        )
1724        .unwrap()
1725        .reply()
1726        .map(|reply| {
1727            // Convert Vec<u8> to Vec<u32>
1728            reply
1729                .value
1730                .chunks_exact(4)
1731                .map(|chunk| u32::from_ne_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]))
1732                .collect::<Vec<u32>>()
1733        })
1734        .unwrap_or_default();
1735
1736    supported_atoms.contains(&atoms._GTK_FRAME_EXTENTS)
1737}
1738
1739fn xdnd_is_atom_supported(atom: u32, atoms: &XcbAtoms) -> bool {
1740    return atom == atoms.TEXT
1741        || atom == atoms.STRING
1742        || atom == atoms.UTF8_STRING
1743        || atom == atoms.TEXT_PLAIN
1744        || atom == atoms.TEXT_PLAIN_UTF8
1745        || atom == atoms.TextUriList;
1746}
1747
1748fn xdnd_get_supported_atom(
1749    xcb_connection: &XCBConnection,
1750    supported_atoms: &XcbAtoms,
1751    target: xproto::Window,
1752) -> u32 {
1753    let property = xcb_connection
1754        .get_property(
1755            false,
1756            target,
1757            supported_atoms.XdndTypeList,
1758            AtomEnum::ANY,
1759            0,
1760            1024,
1761        )
1762        .unwrap();
1763    if let Ok(reply) = property.reply() {
1764        if let Some(atoms) = reply.value32() {
1765            for atom in atoms {
1766                if xdnd_is_atom_supported(atom, &supported_atoms) {
1767                    return atom;
1768                }
1769            }
1770        }
1771    }
1772    return 0;
1773}
1774
1775fn xdnd_send_finished(
1776    xcb_connection: &XCBConnection,
1777    atoms: &XcbAtoms,
1778    source: xproto::Window,
1779    target: xproto::Window,
1780) {
1781    let message = ClientMessageEvent {
1782        format: 32,
1783        window: target,
1784        type_: atoms.XdndFinished,
1785        data: ClientMessageData::from([source, 1, atoms.XdndActionCopy, 0, 0]),
1786        sequence: 0,
1787        response_type: xproto::CLIENT_MESSAGE_EVENT,
1788    };
1789    xcb_connection
1790        .send_event(false, target, EventMask::default(), message)
1791        .unwrap();
1792}
1793
1794fn xdnd_send_status(
1795    xcb_connection: &XCBConnection,
1796    atoms: &XcbAtoms,
1797    source: xproto::Window,
1798    target: xproto::Window,
1799    action: u32,
1800) {
1801    let message = ClientMessageEvent {
1802        format: 32,
1803        window: target,
1804        type_: atoms.XdndStatus,
1805        data: ClientMessageData::from([source, 1, 0, 0, action]),
1806        sequence: 0,
1807        response_type: xproto::CLIENT_MESSAGE_EVENT,
1808    };
1809    xcb_connection
1810        .send_event(false, target, EventMask::default(), message)
1811        .unwrap();
1812}
1813
1814/// Recomputes `pointer_device_states` by querying all pointer devices.
1815/// When a device is present in `scroll_values_to_preserve`, its value for `ScrollAxisState.scroll_value` is used.
1816fn get_new_pointer_device_states(
1817    xcb_connection: &XCBConnection,
1818    scroll_values_to_preserve: &BTreeMap<xinput::DeviceId, PointerDeviceState>,
1819) -> BTreeMap<xinput::DeviceId, PointerDeviceState> {
1820    let devices_query_result = xcb_connection
1821        .xinput_xi_query_device(XINPUT_ALL_DEVICES)
1822        .unwrap()
1823        .reply()
1824        .unwrap();
1825
1826    let mut pointer_device_states = BTreeMap::new();
1827    pointer_device_states.extend(
1828        devices_query_result
1829            .infos
1830            .iter()
1831            .filter(|info| is_pointer_device(info.type_))
1832            .filter_map(|info| {
1833                let scroll_data = info
1834                    .classes
1835                    .iter()
1836                    .filter_map(|class| class.data.as_scroll())
1837                    .map(|class| *class)
1838                    .rev()
1839                    .collect::<Vec<_>>();
1840                let old_state = scroll_values_to_preserve.get(&info.deviceid);
1841                let old_horizontal = old_state.map(|state| &state.horizontal);
1842                let old_vertical = old_state.map(|state| &state.vertical);
1843                let horizontal = scroll_data
1844                    .iter()
1845                    .find(|data| data.scroll_type == xinput::ScrollType::HORIZONTAL)
1846                    .map(|data| scroll_data_to_axis_state(data, old_horizontal));
1847                let vertical = scroll_data
1848                    .iter()
1849                    .find(|data| data.scroll_type == xinput::ScrollType::VERTICAL)
1850                    .map(|data| scroll_data_to_axis_state(data, old_vertical));
1851                if horizontal.is_none() && vertical.is_none() {
1852                    None
1853                } else {
1854                    Some((
1855                        info.deviceid,
1856                        PointerDeviceState {
1857                            horizontal: horizontal.unwrap_or_else(Default::default),
1858                            vertical: vertical.unwrap_or_else(Default::default),
1859                        },
1860                    ))
1861                }
1862            }),
1863    );
1864    if pointer_device_states.is_empty() {
1865        log::error!("Found no xinput mouse pointers.");
1866    }
1867    return pointer_device_states;
1868}
1869
1870/// Returns true if the device is a pointer device. Does not include pointer device groups.
1871fn is_pointer_device(type_: xinput::DeviceType) -> bool {
1872    type_ == xinput::DeviceType::SLAVE_POINTER
1873}
1874
1875fn scroll_data_to_axis_state(
1876    data: &xinput::DeviceClassDataScroll,
1877    old_axis_state_with_valid_scroll_value: Option<&ScrollAxisState>,
1878) -> ScrollAxisState {
1879    ScrollAxisState {
1880        valuator_number: Some(data.number),
1881        multiplier: SCROLL_LINES / fp3232_to_f32(data.increment),
1882        scroll_value: old_axis_state_with_valid_scroll_value.and_then(|state| state.scroll_value),
1883    }
1884}
1885
1886fn reset_all_pointer_device_scroll_positions(
1887    pointer_device_states: &mut BTreeMap<xinput::DeviceId, PointerDeviceState>,
1888) {
1889    pointer_device_states
1890        .iter_mut()
1891        .for_each(|(_, device_state)| reset_pointer_device_scroll_positions(device_state));
1892}
1893
1894fn reset_pointer_device_scroll_positions(pointer: &mut PointerDeviceState) {
1895    pointer.horizontal.scroll_value = None;
1896    pointer.vertical.scroll_value = None;
1897}
1898
1899/// Returns the scroll delta for a smooth scrolling motion event, or `None` if no scroll data is present.
1900fn get_scroll_delta_and_update_state(
1901    pointer: &mut PointerDeviceState,
1902    event: &xinput::MotionEvent,
1903) -> Option<Point<f32>> {
1904    let delta_x = get_axis_scroll_delta_and_update_state(event, &mut pointer.horizontal);
1905    let delta_y = get_axis_scroll_delta_and_update_state(event, &mut pointer.vertical);
1906    if delta_x.is_some() || delta_y.is_some() {
1907        Some(Point::new(delta_x.unwrap_or(0.0), delta_y.unwrap_or(0.0)))
1908    } else {
1909        None
1910    }
1911}
1912
1913fn get_axis_scroll_delta_and_update_state(
1914    event: &xinput::MotionEvent,
1915    axis: &mut ScrollAxisState,
1916) -> Option<f32> {
1917    let axis_index = get_valuator_axis_index(&event.valuator_mask, axis.valuator_number?)?;
1918    if let Some(axis_value) = event.axisvalues.get(axis_index) {
1919        let new_scroll = fp3232_to_f32(*axis_value);
1920        let delta_scroll = axis
1921            .scroll_value
1922            .map(|old_scroll| (old_scroll - new_scroll) * axis.multiplier);
1923        axis.scroll_value = Some(new_scroll);
1924        delta_scroll
1925    } else {
1926        log::error!("Encountered invalid XInput valuator_mask, scrolling may not work properly.");
1927        None
1928    }
1929}
1930
1931fn make_scroll_wheel_event(
1932    position: Point<Pixels>,
1933    scroll_delta: Point<f32>,
1934    modifiers: Modifiers,
1935) -> crate::ScrollWheelEvent {
1936    // When shift is held down, vertical scrolling turns into horizontal scrolling.
1937    let delta = if modifiers.shift {
1938        Point {
1939            x: scroll_delta.y,
1940            y: 0.0,
1941        }
1942    } else {
1943        scroll_delta
1944    };
1945    crate::ScrollWheelEvent {
1946        position,
1947        delta: ScrollDelta::Lines(delta),
1948        modifiers,
1949        touch_phase: TouchPhase::default(),
1950    }
1951}
1952
1953fn create_invisible_cursor(
1954    connection: &XCBConnection,
1955) -> anyhow::Result<crate::platform::linux::x11::client::xproto::Cursor> {
1956    let empty_pixmap = connection.generate_id()?;
1957    let root = connection.setup().roots[0].root;
1958    connection.create_pixmap(1, empty_pixmap, root, 1, 1)?;
1959
1960    let cursor = connection.generate_id()?;
1961    connection.create_cursor(cursor, empty_pixmap, empty_pixmap, 0, 0, 0, 0, 0, 0, 0, 0)?;
1962
1963    connection.free_pixmap(empty_pixmap)?;
1964
1965    connection.flush()?;
1966    Ok(cursor)
1967}