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