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