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);
 780            }
 781            Event::PropertyNotify(event) => {
 782                let window = self.get_window(event.window)?;
 783                window.property_notify(event);
 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(X11Display::new(
1262                    &state.xcb_connection,
1263                    state.scale_factor,
1264                    root_id,
1265                )?) as Rc<dyn PlatformDisplay>)
1266            })
1267            .collect()
1268    }
1269
1270    fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
1271        let state = self.0.borrow();
1272
1273        Some(Rc::new(
1274            X11Display::new(
1275                &state.xcb_connection,
1276                state.scale_factor,
1277                state.x_root_index,
1278            )
1279            .expect("There should always be a root index"),
1280        ))
1281    }
1282
1283    fn display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>> {
1284        let state = self.0.borrow();
1285
1286        Some(Rc::new(X11Display::new(
1287            &state.xcb_connection,
1288            state.scale_factor,
1289            id.0 as usize,
1290        )?))
1291    }
1292
1293    fn open_window(
1294        &self,
1295        handle: AnyWindowHandle,
1296        params: WindowParams,
1297    ) -> anyhow::Result<Box<dyn PlatformWindow>> {
1298        let mut state = self.0.borrow_mut();
1299        let x_window = state.xcb_connection.generate_id().unwrap();
1300
1301        let window = X11Window::new(
1302            handle,
1303            X11ClientStatePtr(Rc::downgrade(&self.0)),
1304            state.common.foreground_executor.clone(),
1305            params,
1306            &state.xcb_connection,
1307            state.client_side_decorations_supported,
1308            state.x_root_index,
1309            x_window,
1310            &state.atoms,
1311            state.scale_factor,
1312            state.common.appearance,
1313        )?;
1314        state
1315            .xcb_connection
1316            .change_property32(
1317                xproto::PropMode::REPLACE,
1318                x_window,
1319                state.atoms.XdndAware,
1320                state.atoms.XA_ATOM,
1321                &[5],
1322            )
1323            .unwrap();
1324
1325        let screen_resources = state
1326            .xcb_connection
1327            .randr_get_screen_resources(x_window)
1328            .unwrap()
1329            .reply()
1330            .expect("Could not find available screens");
1331
1332        let mode = screen_resources
1333            .crtcs
1334            .iter()
1335            .find_map(|crtc| {
1336                let crtc_info = state
1337                    .xcb_connection
1338                    .randr_get_crtc_info(*crtc, x11rb::CURRENT_TIME)
1339                    .ok()?
1340                    .reply()
1341                    .ok()?;
1342
1343                screen_resources
1344                    .modes
1345                    .iter()
1346                    .find(|m| m.id == crtc_info.mode)
1347            })
1348            .expect("Unable to find screen refresh rate");
1349
1350        let refresh_event_token = state
1351            .loop_handle
1352            .insert_source(calloop::timer::Timer::immediate(), {
1353                let refresh_duration = mode_refresh_rate(mode);
1354                move |mut instant, (), client| {
1355                    let xcb_connection = {
1356                        let state = client.0.borrow_mut();
1357                        let xcb_connection = state.xcb_connection.clone();
1358                        if let Some(window) = state.windows.get(&x_window) {
1359                            let window = window.window.clone();
1360                            drop(state);
1361                            window.refresh(Default::default());
1362                        }
1363                        xcb_connection
1364                    };
1365                    client.process_x11_events(&xcb_connection).log_err();
1366
1367                    // Take into account that some frames have been skipped
1368                    let now = Instant::now();
1369                    while instant < now {
1370                        instant += refresh_duration;
1371                    }
1372                    calloop::timer::TimeoutAction::ToInstant(instant)
1373                }
1374            })
1375            .expect("Failed to initialize refresh timer");
1376
1377        let window_ref = WindowRef {
1378            window: window.0.clone(),
1379            refresh_event_token,
1380        };
1381
1382        state.windows.insert(x_window, window_ref);
1383        Ok(Box::new(window))
1384    }
1385
1386    fn set_cursor_style(&self, style: CursorStyle) {
1387        let mut state = self.0.borrow_mut();
1388        let Some(focused_window) = state.mouse_focused_window else {
1389            return;
1390        };
1391        let current_style = state
1392            .cursor_styles
1393            .get(&focused_window)
1394            .unwrap_or(&CursorStyle::Arrow);
1395        if *current_style == style {
1396            return;
1397        }
1398
1399        let cursor = match state.cursor_cache.get(&style) {
1400            Some(cursor) => *cursor,
1401            None => {
1402                let Some(cursor) = state
1403                    .cursor_handle
1404                    .load_cursor(&state.xcb_connection, &style.to_icon_name())
1405                    .log_err()
1406                else {
1407                    return;
1408                };
1409                state.cursor_cache.insert(style, cursor);
1410                cursor
1411            }
1412        };
1413
1414        state.cursor_styles.insert(focused_window, style);
1415        state
1416            .xcb_connection
1417            .change_window_attributes(
1418                focused_window,
1419                &ChangeWindowAttributesAux {
1420                    cursor: Some(cursor),
1421                    ..Default::default()
1422                },
1423            )
1424            .expect("failed to change window cursor")
1425            .check()
1426            .unwrap();
1427    }
1428
1429    fn open_uri(&self, uri: &str) {
1430        #[cfg(any(feature = "wayland", feature = "x11"))]
1431        open_uri_internal(self.background_executor(), uri, None);
1432    }
1433
1434    fn reveal_path(&self, path: PathBuf) {
1435        #[cfg(any(feature = "x11", feature = "wayland"))]
1436        reveal_path_internal(self.background_executor(), path, None);
1437    }
1438
1439    fn write_to_primary(&self, item: crate::ClipboardItem) {
1440        let state = self.0.borrow_mut();
1441        state
1442            .clipboard
1443            .store(
1444                state.clipboard.setter.atoms.primary,
1445                state.clipboard.setter.atoms.utf8_string,
1446                item.text().unwrap_or_default().as_bytes(),
1447            )
1448            .ok();
1449    }
1450
1451    fn write_to_clipboard(&self, item: crate::ClipboardItem) {
1452        let mut state = self.0.borrow_mut();
1453        state
1454            .clipboard
1455            .store(
1456                state.clipboard.setter.atoms.clipboard,
1457                state.clipboard.setter.atoms.utf8_string,
1458                item.text().unwrap_or_default().as_bytes(),
1459            )
1460            .ok();
1461        state.clipboard_item.replace(item);
1462    }
1463
1464    fn read_from_primary(&self) -> Option<crate::ClipboardItem> {
1465        let state = self.0.borrow_mut();
1466        state
1467            .clipboard
1468            .load(
1469                state.clipboard.getter.atoms.primary,
1470                state.clipboard.getter.atoms.utf8_string,
1471                state.clipboard.getter.atoms.property,
1472                Duration::from_secs(3),
1473            )
1474            .map(|text| crate::ClipboardItem::new_string(String::from_utf8(text).unwrap()))
1475            .ok()
1476    }
1477
1478    fn read_from_clipboard(&self) -> Option<crate::ClipboardItem> {
1479        let state = self.0.borrow_mut();
1480        // if the last copy was from this app, return our cached item
1481        // which has metadata attached.
1482        if state
1483            .clipboard
1484            .setter
1485            .connection
1486            .get_selection_owner(state.clipboard.setter.atoms.clipboard)
1487            .ok()
1488            .and_then(|r| r.reply().ok())
1489            .map(|reply| reply.owner == state.clipboard.setter.window)
1490            .unwrap_or(false)
1491        {
1492            return state.clipboard_item.clone();
1493        }
1494        state
1495            .clipboard
1496            .load(
1497                state.clipboard.getter.atoms.clipboard,
1498                state.clipboard.getter.atoms.utf8_string,
1499                state.clipboard.getter.atoms.property,
1500                Duration::from_secs(3),
1501            )
1502            .map(|text| crate::ClipboardItem::new_string(String::from_utf8(text).unwrap()))
1503            .ok()
1504    }
1505
1506    fn run(&self) {
1507        let mut event_loop = self
1508            .0
1509            .borrow_mut()
1510            .event_loop
1511            .take()
1512            .expect("App is already running");
1513
1514        event_loop.run(None, &mut self.clone(), |_| {}).log_err();
1515    }
1516
1517    fn active_window(&self) -> Option<AnyWindowHandle> {
1518        let state = self.0.borrow();
1519        state.keyboard_focused_window.and_then(|focused_window| {
1520            state
1521                .windows
1522                .get(&focused_window)
1523                .map(|window| window.handle())
1524        })
1525    }
1526
1527    fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
1528        let state = self.0.borrow();
1529        let root = state.xcb_connection.setup().roots[state.x_root_index].root;
1530
1531        let reply = state
1532            .xcb_connection
1533            .get_property(
1534                false,
1535                root,
1536                state.atoms._NET_CLIENT_LIST_STACKING,
1537                xproto::AtomEnum::WINDOW,
1538                0,
1539                u32::MAX,
1540            )
1541            .ok()?
1542            .reply()
1543            .ok()?;
1544
1545        let window_ids = reply
1546            .value
1547            .chunks_exact(4)
1548            .map(|chunk| u32::from_ne_bytes(chunk.try_into().unwrap()))
1549            .collect::<Vec<xproto::Window>>();
1550
1551        let mut handles = Vec::new();
1552
1553        // We need to reverse, since _NET_CLIENT_LIST_STACKING has
1554        // a back-to-front order.
1555        // See: https://specifications.freedesktop.org/wm-spec/1.3/ar01s03.html
1556        for window_ref in window_ids
1557            .iter()
1558            .rev()
1559            .filter_map(|&win| state.windows.get(&win))
1560        {
1561            if !window_ref.window.state.borrow().destroyed {
1562                handles.push(window_ref.handle());
1563            }
1564        }
1565
1566        Some(handles)
1567    }
1568}
1569
1570// Adatpted from:
1571// https://docs.rs/winit/0.29.11/src/winit/platform_impl/linux/x11/monitor.rs.html#103-111
1572pub fn mode_refresh_rate(mode: &randr::ModeInfo) -> Duration {
1573    if mode.dot_clock == 0 || mode.htotal == 0 || mode.vtotal == 0 {
1574        return Duration::from_millis(16);
1575    }
1576
1577    let millihertz = mode.dot_clock as u64 * 1_000 / (mode.htotal as u64 * mode.vtotal as u64);
1578    let micros = 1_000_000_000 / millihertz;
1579    log::info!("Refreshing at {} micros", micros);
1580    Duration::from_micros(micros)
1581}
1582
1583fn fp3232_to_f32(value: xinput::Fp3232) -> f32 {
1584    value.integral as f32 + value.frac as f32 / u32::MAX as f32
1585}
1586
1587fn check_compositor_present(xcb_connection: &XCBConnection, root: u32) -> bool {
1588    // Method 1: Check for _NET_WM_CM_S{root}
1589    let atom_name = format!("_NET_WM_CM_S{}", root);
1590    let atom = xcb_connection
1591        .intern_atom(false, atom_name.as_bytes())
1592        .unwrap()
1593        .reply()
1594        .map(|reply| reply.atom)
1595        .unwrap_or(0);
1596
1597    let method1 = if atom != 0 {
1598        xcb_connection
1599            .get_selection_owner(atom)
1600            .unwrap()
1601            .reply()
1602            .map(|reply| reply.owner != 0)
1603            .unwrap_or(false)
1604    } else {
1605        false
1606    };
1607
1608    // Method 2: Check for _NET_WM_CM_OWNER
1609    let atom_name = "_NET_WM_CM_OWNER";
1610    let atom = xcb_connection
1611        .intern_atom(false, atom_name.as_bytes())
1612        .unwrap()
1613        .reply()
1614        .map(|reply| reply.atom)
1615        .unwrap_or(0);
1616
1617    let method2 = if atom != 0 {
1618        xcb_connection
1619            .get_property(false, root, atom, xproto::AtomEnum::WINDOW, 0, 1)
1620            .unwrap()
1621            .reply()
1622            .map(|reply| reply.value_len > 0)
1623            .unwrap_or(false)
1624    } else {
1625        false
1626    };
1627
1628    // Method 3: Check for _NET_SUPPORTING_WM_CHECK
1629    let atom_name = "_NET_SUPPORTING_WM_CHECK";
1630    let atom = xcb_connection
1631        .intern_atom(false, atom_name.as_bytes())
1632        .unwrap()
1633        .reply()
1634        .map(|reply| reply.atom)
1635        .unwrap_or(0);
1636
1637    let method3 = if atom != 0 {
1638        xcb_connection
1639            .get_property(false, root, atom, xproto::AtomEnum::WINDOW, 0, 1)
1640            .unwrap()
1641            .reply()
1642            .map(|reply| reply.value_len > 0)
1643            .unwrap_or(false)
1644    } else {
1645        false
1646    };
1647
1648    // TODO: Remove this
1649    log::info!(
1650        "Compositor detection: _NET_WM_CM_S?={}, _NET_WM_CM_OWNER={}, _NET_SUPPORTING_WM_CHECK={}",
1651        method1,
1652        method2,
1653        method3
1654    );
1655
1656    method1 || method2 || method3
1657}
1658
1659fn check_gtk_frame_extents_supported(
1660    xcb_connection: &XCBConnection,
1661    atoms: &XcbAtoms,
1662    root: xproto::Window,
1663) -> bool {
1664    let supported_atoms = xcb_connection
1665        .get_property(
1666            false,
1667            root,
1668            atoms._NET_SUPPORTED,
1669            xproto::AtomEnum::ATOM,
1670            0,
1671            1024,
1672        )
1673        .unwrap()
1674        .reply()
1675        .map(|reply| {
1676            // Convert Vec<u8> to Vec<u32>
1677            reply
1678                .value
1679                .chunks_exact(4)
1680                .map(|chunk| u32::from_ne_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]))
1681                .collect::<Vec<u32>>()
1682        })
1683        .unwrap_or_default();
1684
1685    supported_atoms.contains(&atoms._GTK_FRAME_EXTENTS)
1686}
1687
1688fn xdnd_is_atom_supported(atom: u32, atoms: &XcbAtoms) -> bool {
1689    return atom == atoms.TEXT
1690        || atom == atoms.STRING
1691        || atom == atoms.UTF8_STRING
1692        || atom == atoms.TEXT_PLAIN
1693        || atom == atoms.TEXT_PLAIN_UTF8
1694        || atom == atoms.TextUriList;
1695}
1696
1697fn xdnd_get_supported_atom(
1698    xcb_connection: &XCBConnection,
1699    supported_atoms: &XcbAtoms,
1700    target: xproto::Window,
1701) -> u32 {
1702    let property = xcb_connection
1703        .get_property(
1704            false,
1705            target,
1706            supported_atoms.XdndTypeList,
1707            AtomEnum::ANY,
1708            0,
1709            1024,
1710        )
1711        .unwrap();
1712    if let Ok(reply) = property.reply() {
1713        if let Some(atoms) = reply.value32() {
1714            for atom in atoms {
1715                if xdnd_is_atom_supported(atom, &supported_atoms) {
1716                    return atom;
1717                }
1718            }
1719        }
1720    }
1721    return 0;
1722}
1723
1724fn xdnd_send_finished(
1725    xcb_connection: &XCBConnection,
1726    atoms: &XcbAtoms,
1727    source: xproto::Window,
1728    target: xproto::Window,
1729) {
1730    let message = ClientMessageEvent {
1731        format: 32,
1732        window: target,
1733        type_: atoms.XdndFinished,
1734        data: ClientMessageData::from([source, 1, atoms.XdndActionCopy, 0, 0]),
1735        sequence: 0,
1736        response_type: xproto::CLIENT_MESSAGE_EVENT,
1737    };
1738    xcb_connection
1739        .send_event(false, target, EventMask::default(), message)
1740        .unwrap();
1741}
1742
1743fn xdnd_send_status(
1744    xcb_connection: &XCBConnection,
1745    atoms: &XcbAtoms,
1746    source: xproto::Window,
1747    target: xproto::Window,
1748    action: u32,
1749) {
1750    let message = ClientMessageEvent {
1751        format: 32,
1752        window: target,
1753        type_: atoms.XdndStatus,
1754        data: ClientMessageData::from([source, 1, 0, 0, action]),
1755        sequence: 0,
1756        response_type: xproto::CLIENT_MESSAGE_EVENT,
1757    };
1758    xcb_connection
1759        .send_event(false, target, EventMask::default(), message)
1760        .unwrap();
1761}
1762
1763/// Recomputes `pointer_device_states` by querying all pointer devices.
1764/// When a device is present in `scroll_values_to_preserve`, its value for `ScrollAxisState.scroll_value` is used.
1765fn get_new_pointer_device_states(
1766    xcb_connection: &XCBConnection,
1767    scroll_values_to_preserve: &BTreeMap<xinput::DeviceId, PointerDeviceState>,
1768) -> BTreeMap<xinput::DeviceId, PointerDeviceState> {
1769    let devices_query_result = xcb_connection
1770        .xinput_xi_query_device(XINPUT_ALL_DEVICES)
1771        .unwrap()
1772        .reply()
1773        .unwrap();
1774
1775    let mut pointer_device_states = BTreeMap::new();
1776    pointer_device_states.extend(
1777        devices_query_result
1778            .infos
1779            .iter()
1780            .filter(|info| is_pointer_device(info.type_))
1781            .filter_map(|info| {
1782                let scroll_data = info
1783                    .classes
1784                    .iter()
1785                    .filter_map(|class| class.data.as_scroll())
1786                    .map(|class| *class)
1787                    .rev()
1788                    .collect::<Vec<_>>();
1789                let old_state = scroll_values_to_preserve.get(&info.deviceid);
1790                let old_horizontal = old_state.map(|state| &state.horizontal);
1791                let old_vertical = old_state.map(|state| &state.vertical);
1792                let horizontal = scroll_data
1793                    .iter()
1794                    .find(|data| data.scroll_type == xinput::ScrollType::HORIZONTAL)
1795                    .map(|data| scroll_data_to_axis_state(data, old_horizontal));
1796                let vertical = scroll_data
1797                    .iter()
1798                    .find(|data| data.scroll_type == xinput::ScrollType::VERTICAL)
1799                    .map(|data| scroll_data_to_axis_state(data, old_vertical));
1800                if horizontal.is_none() && vertical.is_none() {
1801                    None
1802                } else {
1803                    Some((
1804                        info.deviceid,
1805                        PointerDeviceState {
1806                            horizontal: horizontal.unwrap_or_else(Default::default),
1807                            vertical: vertical.unwrap_or_else(Default::default),
1808                        },
1809                    ))
1810                }
1811            }),
1812    );
1813    if pointer_device_states.is_empty() {
1814        log::error!("Found no xinput mouse pointers.");
1815    }
1816    return pointer_device_states;
1817}
1818
1819/// Returns true if the device is a pointer device. Does not include pointer device groups.
1820fn is_pointer_device(type_: xinput::DeviceType) -> bool {
1821    type_ == xinput::DeviceType::SLAVE_POINTER
1822}
1823
1824fn scroll_data_to_axis_state(
1825    data: &xinput::DeviceClassDataScroll,
1826    old_axis_state_with_valid_scroll_value: Option<&ScrollAxisState>,
1827) -> ScrollAxisState {
1828    ScrollAxisState {
1829        valuator_number: Some(data.number),
1830        multiplier: SCROLL_LINES / fp3232_to_f32(data.increment),
1831        scroll_value: old_axis_state_with_valid_scroll_value.and_then(|state| state.scroll_value),
1832    }
1833}
1834
1835fn reset_all_pointer_device_scroll_positions(
1836    pointer_device_states: &mut BTreeMap<xinput::DeviceId, PointerDeviceState>,
1837) {
1838    pointer_device_states
1839        .iter_mut()
1840        .for_each(|(_, device_state)| reset_pointer_device_scroll_positions(device_state));
1841}
1842
1843fn reset_pointer_device_scroll_positions(pointer: &mut PointerDeviceState) {
1844    pointer.horizontal.scroll_value = None;
1845    pointer.vertical.scroll_value = None;
1846}
1847
1848/// Returns the scroll delta for a smooth scrolling motion event, or `None` if no scroll data is present.
1849fn get_scroll_delta_and_update_state(
1850    pointer: &mut PointerDeviceState,
1851    event: &xinput::MotionEvent,
1852) -> Option<Point<f32>> {
1853    let delta_x = get_axis_scroll_delta_and_update_state(event, &mut pointer.horizontal);
1854    let delta_y = get_axis_scroll_delta_and_update_state(event, &mut pointer.vertical);
1855    if delta_x.is_some() || delta_y.is_some() {
1856        Some(Point::new(delta_x.unwrap_or(0.0), delta_y.unwrap_or(0.0)))
1857    } else {
1858        None
1859    }
1860}
1861
1862fn get_axis_scroll_delta_and_update_state(
1863    event: &xinput::MotionEvent,
1864    axis: &mut ScrollAxisState,
1865) -> Option<f32> {
1866    let axis_index = get_valuator_axis_index(&event.valuator_mask, axis.valuator_number?)?;
1867    if let Some(axis_value) = event.axisvalues.get(axis_index) {
1868        let new_scroll = fp3232_to_f32(*axis_value);
1869        let delta_scroll = axis
1870            .scroll_value
1871            .map(|old_scroll| (old_scroll - new_scroll) * axis.multiplier);
1872        axis.scroll_value = Some(new_scroll);
1873        delta_scroll
1874    } else {
1875        log::error!("Encountered invalid XInput valuator_mask, scrolling may not work properly.");
1876        None
1877    }
1878}
1879
1880fn make_scroll_wheel_event(
1881    position: Point<Pixels>,
1882    scroll_delta: Point<f32>,
1883    modifiers: Modifiers,
1884) -> crate::ScrollWheelEvent {
1885    // When shift is held down, vertical scrolling turns into horizontal scrolling.
1886    let delta = if modifiers.shift {
1887        Point {
1888            x: scroll_delta.y,
1889            y: 0.0,
1890        }
1891    } else {
1892        scroll_delta
1893    };
1894    crate::ScrollWheelEvent {
1895        position,
1896        delta: ScrollDelta::Lines(delta),
1897        modifiers,
1898        touch_phase: TouchPhase::default(),
1899    }
1900}