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