client.rs

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