client.rs

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