client.rs

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