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, ScaledPixels, ScrollDelta, Size, TouchPhase,
  42    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_ime_key_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_ime_key_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();
 535                }
 536            }
 537
 538            for event in events.into_iter() {
 539                let mut state = self.0.borrow_mut();
 540                if state.ximc.is_none() || state.xim_handler.is_none() {
 541                    drop(state);
 542                    self.handle_event(event);
 543                    continue;
 544                }
 545
 546                let mut ximc = state.ximc.take().unwrap();
 547                let mut xim_handler = state.xim_handler.take().unwrap();
 548                let xim_connected = xim_handler.connected;
 549                drop(state);
 550
 551                let xim_filtered = match ximc.filter_event(&event, &mut xim_handler) {
 552                    Ok(handled) => handled,
 553                    Err(err) => {
 554                        log::error!("XIMClientError: {}", err);
 555                        false
 556                    }
 557                };
 558                let xim_callback_event = xim_handler.last_callback_event.take();
 559
 560                let mut state = self.0.borrow_mut();
 561                state.ximc = Some(ximc);
 562                state.xim_handler = Some(xim_handler);
 563                drop(state);
 564
 565                if let Some(event) = xim_callback_event {
 566                    self.handle_xim_callback_event(event);
 567                }
 568
 569                if xim_filtered {
 570                    continue;
 571                }
 572
 573                if xim_connected {
 574                    self.xim_handle_event(event);
 575                } else {
 576                    self.handle_event(event);
 577                }
 578            }
 579        }
 580        Ok(())
 581    }
 582
 583    pub fn enable_ime(&self) {
 584        let mut state = self.0.borrow_mut();
 585        if state.ximc.is_none() {
 586            return;
 587        }
 588
 589        let mut ximc = state.ximc.take().unwrap();
 590        let mut xim_handler = state.xim_handler.take().unwrap();
 591        let mut ic_attributes = ximc
 592            .build_ic_attributes()
 593            .push(AttributeName::InputStyle, InputStyle::PREEDIT_CALLBACKS)
 594            .push(AttributeName::ClientWindow, xim_handler.window)
 595            .push(AttributeName::FocusWindow, xim_handler.window);
 596
 597        let window_id = state.keyboard_focused_window;
 598        drop(state);
 599        if let Some(window_id) = window_id {
 600            let window = self.get_window(window_id).unwrap();
 601            if let Some(area) = window.get_ime_area() {
 602                ic_attributes =
 603                    ic_attributes.nested_list(xim::AttributeName::PreeditAttributes, |b| {
 604                        b.push(
 605                            xim::AttributeName::SpotLocation,
 606                            xim::Point {
 607                                x: u32::from(area.origin.x + area.size.width) as i16,
 608                                y: u32::from(area.origin.y + area.size.height) as i16,
 609                            },
 610                        );
 611                    });
 612            }
 613        }
 614        ximc.create_ic(xim_handler.im_id, ic_attributes.build())
 615            .ok();
 616        state = self.0.borrow_mut();
 617        state.xim_handler = Some(xim_handler);
 618        state.ximc = Some(ximc);
 619    }
 620
 621    pub fn reset_ime(&self) {
 622        let mut state = self.0.borrow_mut();
 623        state.composing = false;
 624        if let Some(mut ximc) = state.ximc.take() {
 625            let xim_handler = state.xim_handler.as_ref().unwrap();
 626            ximc.reset_ic(xim_handler.im_id, xim_handler.ic_id).ok();
 627            state.ximc = Some(ximc);
 628        }
 629    }
 630
 631    fn get_window(&self, win: xproto::Window) -> Option<X11WindowStatePtr> {
 632        let state = self.0.borrow();
 633        state
 634            .windows
 635            .get(&win)
 636            .filter(|window_reference| !window_reference.window.state.borrow().destroyed)
 637            .map(|window_reference| window_reference.window.clone())
 638    }
 639
 640    fn handle_event(&self, event: Event) -> Option<()> {
 641        match event {
 642            Event::ClientMessage(event) => {
 643                let window = self.get_window(event.window)?;
 644                let [atom, arg1, arg2, arg3, arg4] = event.data.as_data32();
 645                let mut state = self.0.borrow_mut();
 646
 647                if atom == state.atoms.WM_DELETE_WINDOW {
 648                    // window "x" button clicked by user
 649                    if window.should_close() {
 650                        // Rest of the close logic is handled in drop_window()
 651                        window.close();
 652                    }
 653                } else if atom == state.atoms._NET_WM_SYNC_REQUEST {
 654                    window.state.borrow_mut().last_sync_counter =
 655                        Some(x11rb::protocol::sync::Int64 {
 656                            lo: arg2,
 657                            hi: arg3 as i32,
 658                        })
 659                }
 660
 661                if event.type_ == state.atoms.XdndEnter {
 662                    state.xdnd_state.other_window = atom;
 663                    if (arg1 & 0x1) == 0x1 {
 664                        state.xdnd_state.drag_type = xdnd_get_supported_atom(
 665                            &state.xcb_connection,
 666                            &state.atoms,
 667                            state.xdnd_state.other_window,
 668                        );
 669                    } else {
 670                        if let Some(atom) = [arg2, arg3, arg4]
 671                            .into_iter()
 672                            .find(|atom| xdnd_is_atom_supported(*atom, &state.atoms))
 673                        {
 674                            state.xdnd_state.drag_type = atom;
 675                        }
 676                    }
 677                } else if event.type_ == state.atoms.XdndLeave {
 678                    let position = state.xdnd_state.position;
 679                    drop(state);
 680                    window
 681                        .handle_input(PlatformInput::FileDrop(FileDropEvent::Pending { position }));
 682                    window.handle_input(PlatformInput::FileDrop(FileDropEvent::Exited {}));
 683                    self.0.borrow_mut().xdnd_state = Xdnd::default();
 684                } else if event.type_ == state.atoms.XdndPosition {
 685                    if let Ok(pos) = state
 686                        .xcb_connection
 687                        .query_pointer(event.window)
 688                        .unwrap()
 689                        .reply()
 690                    {
 691                        state.xdnd_state.position =
 692                            Point::new(Pixels(pos.win_x as f32), Pixels(pos.win_y as f32));
 693                    }
 694                    if !state.xdnd_state.retrieved {
 695                        state
 696                            .xcb_connection
 697                            .convert_selection(
 698                                event.window,
 699                                state.atoms.XdndSelection,
 700                                state.xdnd_state.drag_type,
 701                                state.atoms.XDND_DATA,
 702                                arg3,
 703                            )
 704                            .unwrap();
 705                    }
 706                    xdnd_send_status(
 707                        &state.xcb_connection,
 708                        &state.atoms,
 709                        event.window,
 710                        state.xdnd_state.other_window,
 711                        arg4,
 712                    );
 713                    let position = state.xdnd_state.position;
 714                    drop(state);
 715                    window
 716                        .handle_input(PlatformInput::FileDrop(FileDropEvent::Pending { position }));
 717                } else if event.type_ == state.atoms.XdndDrop {
 718                    xdnd_send_finished(
 719                        &state.xcb_connection,
 720                        &state.atoms,
 721                        event.window,
 722                        state.xdnd_state.other_window,
 723                    );
 724                    let position = state.xdnd_state.position;
 725                    drop(state);
 726                    window
 727                        .handle_input(PlatformInput::FileDrop(FileDropEvent::Submit { position }));
 728                    self.0.borrow_mut().xdnd_state = Xdnd::default();
 729                }
 730            }
 731            Event::SelectionNotify(event) => {
 732                let window = self.get_window(event.requestor)?;
 733                let mut state = self.0.borrow_mut();
 734                let property = state.xcb_connection.get_property(
 735                    false,
 736                    event.requestor,
 737                    state.atoms.XDND_DATA,
 738                    AtomEnum::ANY,
 739                    0,
 740                    1024,
 741                );
 742                if property.as_ref().log_err().is_none() {
 743                    return Some(());
 744                }
 745                if let Ok(reply) = property.unwrap().reply() {
 746                    match str::from_utf8(&reply.value) {
 747                        Ok(file_list) => {
 748                            let paths: SmallVec<[_; 2]> = file_list
 749                                .lines()
 750                                .filter_map(|path| Url::parse(path).log_err())
 751                                .filter_map(|url| url.to_file_path().log_err())
 752                                .collect();
 753                            let input = PlatformInput::FileDrop(FileDropEvent::Entered {
 754                                position: state.xdnd_state.position,
 755                                paths: crate::ExternalPaths(paths),
 756                            });
 757                            drop(state);
 758                            window.handle_input(input);
 759                            self.0.borrow_mut().xdnd_state.retrieved = true;
 760                        }
 761                        Err(_) => {}
 762                    }
 763                }
 764            }
 765            Event::ConfigureNotify(event) => {
 766                let bounds = Bounds {
 767                    origin: Point {
 768                        x: event.x.into(),
 769                        y: event.y.into(),
 770                    },
 771                    size: Size {
 772                        width: event.width.into(),
 773                        height: event.height.into(),
 774                    },
 775                };
 776                let window = self.get_window(event.window)?;
 777                window.configure(bounds);
 778            }
 779            Event::PropertyNotify(event) => {
 780                let window = self.get_window(event.window)?;
 781                window.property_notify(event);
 782            }
 783            Event::FocusIn(event) => {
 784                let window = self.get_window(event.event)?;
 785                window.set_active(true);
 786                let mut state = self.0.borrow_mut();
 787                state.keyboard_focused_window = Some(event.event);
 788                if let Some(handler) = state.xim_handler.as_mut() {
 789                    handler.window = event.event;
 790                }
 791                drop(state);
 792                self.enable_ime();
 793            }
 794            Event::FocusOut(event) => {
 795                let window = self.get_window(event.event)?;
 796                window.set_active(false);
 797                let mut state = self.0.borrow_mut();
 798                state.keyboard_focused_window = None;
 799                if let Some(compose_state) = state.compose_state.as_mut() {
 800                    compose_state.reset();
 801                }
 802                state.pre_edit_text.take();
 803                drop(state);
 804                self.reset_ime();
 805                window.handle_ime_delete();
 806            }
 807            Event::XkbNewKeyboardNotify(_) | Event::MapNotify(_) => {
 808                let mut state = self.0.borrow_mut();
 809                let xkb_state = {
 810                    let xkb_keymap = xkbc::x11::keymap_new_from_device(
 811                        &state.xkb_context,
 812                        &state.xcb_connection,
 813                        state.xkb_device_id,
 814                        xkbc::KEYMAP_COMPILE_NO_FLAGS,
 815                    );
 816                    xkbc::x11::state_new_from_device(
 817                        &xkb_keymap,
 818                        &state.xcb_connection,
 819                        state.xkb_device_id,
 820                    )
 821                };
 822                state.xkb = xkb_state;
 823            }
 824            Event::XkbStateNotify(event) => {
 825                let mut state = self.0.borrow_mut();
 826                state.xkb.update_mask(
 827                    event.base_mods.into(),
 828                    event.latched_mods.into(),
 829                    event.locked_mods.into(),
 830                    event.base_group as u32,
 831                    event.latched_group as u32,
 832                    event.locked_group.into(),
 833                );
 834                state.previous_xkb_state = XKBStateNotiy {
 835                    depressed_layout: event.base_group as u32,
 836                    latched_layout: event.latched_group as u32,
 837                    locked_layout: event.locked_group.into(),
 838                };
 839                let modifiers = Modifiers::from_xkb(&state.xkb);
 840                if state.modifiers == modifiers {
 841                    drop(state);
 842                } else {
 843                    let focused_window_id = state.keyboard_focused_window?;
 844                    state.modifiers = modifiers;
 845                    drop(state);
 846
 847                    let focused_window = self.get_window(focused_window_id)?;
 848                    focused_window.handle_input(PlatformInput::ModifiersChanged(
 849                        ModifiersChangedEvent { modifiers },
 850                    ));
 851                }
 852            }
 853            Event::KeyPress(event) => {
 854                let window = self.get_window(event.event)?;
 855                let mut state = self.0.borrow_mut();
 856
 857                let modifiers = modifiers_from_state(event.state);
 858                state.modifiers = modifiers;
 859                state.pre_ime_key_down.take();
 860                let keystroke = {
 861                    let code = event.detail.into();
 862                    let xkb_state = state.previous_xkb_state.clone();
 863                    state.xkb.update_mask(
 864                        event.state.bits() as ModMask,
 865                        0,
 866                        0,
 867                        xkb_state.depressed_layout,
 868                        xkb_state.latched_layout,
 869                        xkb_state.locked_layout,
 870                    );
 871                    let mut keystroke = crate::Keystroke::from_xkb(&state.xkb, modifiers, code);
 872                    let keysym = state.xkb.key_get_one_sym(code);
 873                    if keysym.is_modifier_key() {
 874                        return Some(());
 875                    }
 876                    if let Some(mut compose_state) = state.compose_state.take() {
 877                        compose_state.feed(keysym);
 878                        match compose_state.status() {
 879                            xkbc::Status::Composed => {
 880                                state.pre_edit_text.take();
 881                                keystroke.ime_key = compose_state.utf8();
 882                                if let Some(keysym) = compose_state.keysym() {
 883                                    keystroke.key = xkbc::keysym_get_name(keysym);
 884                                }
 885                            }
 886                            xkbc::Status::Composing => {
 887                                keystroke.ime_key = None;
 888                                state.pre_edit_text = compose_state
 889                                    .utf8()
 890                                    .or(crate::Keystroke::underlying_dead_key(keysym));
 891                                let pre_edit =
 892                                    state.pre_edit_text.clone().unwrap_or(String::default());
 893                                drop(state);
 894                                window.handle_ime_preedit(pre_edit);
 895                                state = self.0.borrow_mut();
 896                            }
 897                            xkbc::Status::Cancelled => {
 898                                let pre_edit = state.pre_edit_text.take();
 899                                drop(state);
 900                                if let Some(pre_edit) = pre_edit {
 901                                    window.handle_ime_commit(pre_edit);
 902                                }
 903                                if let Some(current_key) = Keystroke::underlying_dead_key(keysym) {
 904                                    window.handle_ime_preedit(current_key);
 905                                }
 906                                state = self.0.borrow_mut();
 907                                compose_state.feed(keysym);
 908                            }
 909                            _ => {}
 910                        }
 911                        state.compose_state = Some(compose_state);
 912                    }
 913                    keystroke
 914                };
 915                drop(state);
 916                window.handle_input(PlatformInput::KeyDown(crate::KeyDownEvent {
 917                    keystroke,
 918                    is_held: false,
 919                }));
 920            }
 921            Event::KeyRelease(event) => {
 922                let window = self.get_window(event.event)?;
 923                let mut state = self.0.borrow_mut();
 924
 925                let modifiers = modifiers_from_state(event.state);
 926                state.modifiers = modifiers;
 927
 928                let keystroke = {
 929                    let code = event.detail.into();
 930                    let xkb_state = state.previous_xkb_state.clone();
 931                    state.xkb.update_mask(
 932                        event.state.bits() as ModMask,
 933                        0,
 934                        0,
 935                        xkb_state.depressed_layout,
 936                        xkb_state.latched_layout,
 937                        xkb_state.locked_layout,
 938                    );
 939                    let keystroke = crate::Keystroke::from_xkb(&state.xkb, modifiers, code);
 940                    let keysym = state.xkb.key_get_one_sym(code);
 941                    if keysym.is_modifier_key() {
 942                        return Some(());
 943                    }
 944                    keystroke
 945                };
 946                drop(state);
 947                window.handle_input(PlatformInput::KeyUp(crate::KeyUpEvent { keystroke }));
 948            }
 949            Event::XinputButtonPress(event) => {
 950                let window = self.get_window(event.event)?;
 951                let mut state = self.0.borrow_mut();
 952
 953                let modifiers = modifiers_from_xinput_info(event.mods);
 954                state.modifiers = modifiers;
 955
 956                let position = point(
 957                    px(event.event_x as f32 / u16::MAX as f32 / state.scale_factor),
 958                    px(event.event_y as f32 / u16::MAX as f32 / state.scale_factor),
 959                );
 960
 961                if state.composing && state.ximc.is_some() {
 962                    drop(state);
 963                    self.reset_ime();
 964                    window.handle_ime_unmark();
 965                    state = self.0.borrow_mut();
 966                } else if let Some(text) = state.pre_edit_text.take() {
 967                    if let Some(compose_state) = state.compose_state.as_mut() {
 968                        compose_state.reset();
 969                    }
 970                    drop(state);
 971                    window.handle_ime_commit(text);
 972                    state = self.0.borrow_mut();
 973                }
 974                match button_or_scroll_from_event_detail(event.detail) {
 975                    Some(ButtonOrScroll::Button(button)) => {
 976                        let click_elapsed = state.last_click.elapsed();
 977                        if click_elapsed < DOUBLE_CLICK_INTERVAL
 978                            && state
 979                                .last_mouse_button
 980                                .is_some_and(|prev_button| prev_button == button)
 981                            && is_within_click_distance(state.last_location, position)
 982                        {
 983                            state.current_count += 1;
 984                        } else {
 985                            state.current_count = 1;
 986                        }
 987
 988                        state.last_click = Instant::now();
 989                        state.last_mouse_button = Some(button);
 990                        state.last_location = position;
 991                        let current_count = state.current_count;
 992
 993                        drop(state);
 994                        window.handle_input(PlatformInput::MouseDown(crate::MouseDownEvent {
 995                            button,
 996                            position,
 997                            modifiers,
 998                            click_count: current_count,
 999                            first_mouse: false,
1000                        }));
1001                    }
1002                    Some(ButtonOrScroll::Scroll(direction)) => {
1003                        drop(state);
1004                        // Emulated scroll button presses are sent simultaneously with smooth scrolling XinputMotion events.
1005                        // Since handling those events does the scrolling, they are skipped here.
1006                        if !event
1007                            .flags
1008                            .contains(xinput::PointerEventFlags::POINTER_EMULATED)
1009                        {
1010                            let scroll_delta = match direction {
1011                                ScrollDirection::Up => Point::new(0.0, SCROLL_LINES),
1012                                ScrollDirection::Down => Point::new(0.0, -SCROLL_LINES),
1013                                ScrollDirection::Left => Point::new(SCROLL_LINES, 0.0),
1014                                ScrollDirection::Right => Point::new(-SCROLL_LINES, 0.0),
1015                            };
1016                            window.handle_input(PlatformInput::ScrollWheel(
1017                                make_scroll_wheel_event(position, scroll_delta, modifiers),
1018                            ));
1019                        }
1020                    }
1021                    None => {
1022                        log::error!("Unknown x11 button: {}", event.detail);
1023                    }
1024                }
1025            }
1026            Event::XinputButtonRelease(event) => {
1027                let window = self.get_window(event.event)?;
1028                let mut state = self.0.borrow_mut();
1029                let modifiers = modifiers_from_xinput_info(event.mods);
1030                state.modifiers = modifiers;
1031
1032                let position = point(
1033                    px(event.event_x as f32 / u16::MAX as f32 / state.scale_factor),
1034                    px(event.event_y as f32 / u16::MAX as f32 / state.scale_factor),
1035                );
1036                match button_or_scroll_from_event_detail(event.detail) {
1037                    Some(ButtonOrScroll::Button(button)) => {
1038                        let click_count = state.current_count;
1039                        drop(state);
1040                        window.handle_input(PlatformInput::MouseUp(crate::MouseUpEvent {
1041                            button,
1042                            position,
1043                            modifiers,
1044                            click_count,
1045                        }));
1046                    }
1047                    Some(ButtonOrScroll::Scroll(_)) => {}
1048                    None => {}
1049                }
1050            }
1051            Event::XinputMotion(event) => {
1052                let window = self.get_window(event.event)?;
1053                let mut state = self.0.borrow_mut();
1054                let pressed_button = pressed_button_from_mask(event.button_mask[0]);
1055                let position = point(
1056                    px(event.event_x as f32 / u16::MAX as f32 / state.scale_factor),
1057                    px(event.event_y as f32 / u16::MAX as f32 / state.scale_factor),
1058                );
1059                let modifiers = modifiers_from_xinput_info(event.mods);
1060                state.modifiers = modifiers;
1061                drop(state);
1062
1063                if event.valuator_mask[0] & 3 != 0 {
1064                    window.handle_input(PlatformInput::MouseMove(crate::MouseMoveEvent {
1065                        position,
1066                        pressed_button,
1067                        modifiers,
1068                    }));
1069                }
1070
1071                state = self.0.borrow_mut();
1072                if let Some(mut pointer) = state.pointer_device_states.get_mut(&event.sourceid) {
1073                    let scroll_delta = get_scroll_delta_and_update_state(&mut pointer, &event);
1074                    drop(state);
1075                    if let Some(scroll_delta) = scroll_delta {
1076                        window.handle_input(PlatformInput::ScrollWheel(make_scroll_wheel_event(
1077                            position,
1078                            scroll_delta,
1079                            modifiers,
1080                        )));
1081                    }
1082                }
1083            }
1084            Event::XinputEnter(event) if event.mode == xinput::NotifyMode::NORMAL => {
1085                let window = self.get_window(event.event)?;
1086                window.set_hovered(true);
1087                let mut state = self.0.borrow_mut();
1088                state.mouse_focused_window = Some(event.event);
1089            }
1090            Event::XinputLeave(event) if event.mode == xinput::NotifyMode::NORMAL => {
1091                let mut state = self.0.borrow_mut();
1092
1093                // 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)
1094                reset_all_pointer_device_scroll_positions(&mut state.pointer_device_states);
1095                state.mouse_focused_window = None;
1096                let pressed_button = pressed_button_from_mask(event.buttons[0]);
1097                let position = point(
1098                    px(event.event_x as f32 / u16::MAX as f32 / state.scale_factor),
1099                    px(event.event_y as f32 / u16::MAX as f32 / state.scale_factor),
1100                );
1101                let modifiers = modifiers_from_xinput_info(event.mods);
1102                state.modifiers = modifiers;
1103                drop(state);
1104
1105                let window = self.get_window(event.event)?;
1106                window.handle_input(PlatformInput::MouseExited(crate::MouseExitEvent {
1107                    pressed_button,
1108                    position,
1109                    modifiers,
1110                }));
1111                window.set_hovered(false);
1112            }
1113            Event::XinputHierarchy(event) => {
1114                let mut state = self.0.borrow_mut();
1115                // Temporarily use `state.pointer_device_states` to only store pointers that still have valid scroll values.
1116                // Any change to a device invalidates its scroll values.
1117                for info in event.infos {
1118                    if is_pointer_device(info.type_) {
1119                        state.pointer_device_states.remove(&info.deviceid);
1120                    }
1121                }
1122                state.pointer_device_states = get_new_pointer_device_states(
1123                    &state.xcb_connection,
1124                    &state.pointer_device_states,
1125                );
1126            }
1127            Event::XinputDeviceChanged(event) => {
1128                let mut state = self.0.borrow_mut();
1129                if let Some(mut pointer) = state.pointer_device_states.get_mut(&event.sourceid) {
1130                    reset_pointer_device_scroll_positions(&mut pointer);
1131                }
1132            }
1133            _ => {}
1134        };
1135
1136        Some(())
1137    }
1138
1139    fn handle_xim_callback_event(&self, event: XimCallbackEvent) {
1140        match event {
1141            XimCallbackEvent::XimXEvent(event) => {
1142                self.handle_event(event);
1143            }
1144            XimCallbackEvent::XimCommitEvent(window, text) => {
1145                self.xim_handle_commit(window, text);
1146            }
1147            XimCallbackEvent::XimPreeditEvent(window, text) => {
1148                self.xim_handle_preedit(window, text);
1149            }
1150        };
1151    }
1152
1153    fn xim_handle_event(&self, event: Event) -> Option<()> {
1154        match event {
1155            Event::KeyPress(event) | Event::KeyRelease(event) => {
1156                let mut state = self.0.borrow_mut();
1157                state.pre_ime_key_down = Some(Keystroke::from_xkb(
1158                    &state.xkb,
1159                    state.modifiers,
1160                    event.detail.into(),
1161                ));
1162                let mut ximc = state.ximc.take().unwrap();
1163                let mut xim_handler = state.xim_handler.take().unwrap();
1164                drop(state);
1165                xim_handler.window = event.event;
1166                ximc.forward_event(
1167                    xim_handler.im_id,
1168                    xim_handler.ic_id,
1169                    xim::ForwardEventFlag::empty(),
1170                    &event,
1171                )
1172                .unwrap();
1173                let mut state = self.0.borrow_mut();
1174                state.ximc = Some(ximc);
1175                state.xim_handler = Some(xim_handler);
1176                drop(state);
1177            }
1178            event => {
1179                self.handle_event(event);
1180            }
1181        }
1182        Some(())
1183    }
1184
1185    fn xim_handle_commit(&self, window: xproto::Window, text: String) -> Option<()> {
1186        let window = self.get_window(window).unwrap();
1187        let mut state = self.0.borrow_mut();
1188        let keystroke = state.pre_ime_key_down.take();
1189        state.composing = false;
1190        drop(state);
1191        if let Some(mut keystroke) = keystroke {
1192            keystroke.ime_key = Some(text.clone());
1193            window.handle_input(PlatformInput::KeyDown(crate::KeyDownEvent {
1194                keystroke,
1195                is_held: false,
1196            }));
1197        }
1198
1199        Some(())
1200    }
1201
1202    fn xim_handle_preedit(&self, window: xproto::Window, text: String) -> Option<()> {
1203        let window = self.get_window(window).unwrap();
1204
1205        let mut state = self.0.borrow_mut();
1206        let mut ximc = state.ximc.take().unwrap();
1207        let mut xim_handler = state.xim_handler.take().unwrap();
1208        state.composing = !text.is_empty();
1209        drop(state);
1210        window.handle_ime_preedit(text);
1211
1212        if let Some(area) = window.get_ime_area() {
1213            let ic_attributes = ximc
1214                .build_ic_attributes()
1215                .push(
1216                    xim::AttributeName::InputStyle,
1217                    xim::InputStyle::PREEDIT_CALLBACKS,
1218                )
1219                .push(xim::AttributeName::ClientWindow, xim_handler.window)
1220                .push(xim::AttributeName::FocusWindow, xim_handler.window)
1221                .nested_list(xim::AttributeName::PreeditAttributes, |b| {
1222                    b.push(
1223                        xim::AttributeName::SpotLocation,
1224                        xim::Point {
1225                            x: u32::from(area.origin.x + area.size.width) as i16,
1226                            y: u32::from(area.origin.y + area.size.height) as i16,
1227                        },
1228                    );
1229                })
1230                .build();
1231            ximc.set_ic_values(xim_handler.im_id, xim_handler.ic_id, ic_attributes)
1232                .ok();
1233        }
1234        let mut state = self.0.borrow_mut();
1235        state.ximc = Some(ximc);
1236        state.xim_handler = Some(xim_handler);
1237        drop(state);
1238        Some(())
1239    }
1240}
1241
1242impl LinuxClient for X11Client {
1243    fn compositor_name(&self) -> &'static str {
1244        "X11"
1245    }
1246
1247    fn with_common<R>(&self, f: impl FnOnce(&mut LinuxCommon) -> R) -> R {
1248        f(&mut self.0.borrow_mut().common)
1249    }
1250
1251    fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
1252        let state = self.0.borrow();
1253        let setup = state.xcb_connection.setup();
1254        setup
1255            .roots
1256            .iter()
1257            .enumerate()
1258            .filter_map(|(root_id, _)| {
1259                Some(Rc::new(X11Display::new(
1260                    &state.xcb_connection,
1261                    state.scale_factor,
1262                    root_id,
1263                )?) as Rc<dyn PlatformDisplay>)
1264            })
1265            .collect()
1266    }
1267
1268    fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
1269        let state = self.0.borrow();
1270
1271        Some(Rc::new(
1272            X11Display::new(
1273                &state.xcb_connection,
1274                state.scale_factor,
1275                state.x_root_index,
1276            )
1277            .expect("There should always be a root index"),
1278        ))
1279    }
1280
1281    fn display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>> {
1282        let state = self.0.borrow();
1283
1284        Some(Rc::new(X11Display::new(
1285            &state.xcb_connection,
1286            state.scale_factor,
1287            id.0 as usize,
1288        )?))
1289    }
1290
1291    fn open_window(
1292        &self,
1293        handle: AnyWindowHandle,
1294        params: WindowParams,
1295    ) -> anyhow::Result<Box<dyn PlatformWindow>> {
1296        let mut state = self.0.borrow_mut();
1297        let x_window = state.xcb_connection.generate_id().unwrap();
1298
1299        let window = X11Window::new(
1300            handle,
1301            X11ClientStatePtr(Rc::downgrade(&self.0)),
1302            state.common.foreground_executor.clone(),
1303            params,
1304            &state.xcb_connection,
1305            state.client_side_decorations_supported,
1306            state.x_root_index,
1307            x_window,
1308            &state.atoms,
1309            state.scale_factor,
1310            state.common.appearance,
1311        )?;
1312        state
1313            .xcb_connection
1314            .change_property32(
1315                xproto::PropMode::REPLACE,
1316                x_window,
1317                state.atoms.XdndAware,
1318                state.atoms.XA_ATOM,
1319                &[5],
1320            )
1321            .unwrap();
1322
1323        let screen_resources = state
1324            .xcb_connection
1325            .randr_get_screen_resources(x_window)
1326            .unwrap()
1327            .reply()
1328            .expect("Could not find available screens");
1329
1330        let mode = screen_resources
1331            .crtcs
1332            .iter()
1333            .find_map(|crtc| {
1334                let crtc_info = state
1335                    .xcb_connection
1336                    .randr_get_crtc_info(*crtc, x11rb::CURRENT_TIME)
1337                    .ok()?
1338                    .reply()
1339                    .ok()?;
1340
1341                screen_resources
1342                    .modes
1343                    .iter()
1344                    .find(|m| m.id == crtc_info.mode)
1345            })
1346            .expect("Unable to find screen refresh rate");
1347
1348        let refresh_event_token = state
1349            .loop_handle
1350            .insert_source(calloop::timer::Timer::immediate(), {
1351                let refresh_duration = mode_refresh_rate(mode);
1352                move |mut instant, (), client| {
1353                    let xcb_connection = {
1354                        let state = client.0.borrow_mut();
1355                        let xcb_connection = state.xcb_connection.clone();
1356                        if let Some(window) = state.windows.get(&x_window) {
1357                            let window = window.window.clone();
1358                            drop(state);
1359                            window.refresh();
1360                        }
1361                        xcb_connection
1362                    };
1363                    client.process_x11_events(&xcb_connection).log_err();
1364
1365                    // Take into account that some frames have been skipped
1366                    let now = Instant::now();
1367                    while instant < now {
1368                        instant += refresh_duration;
1369                    }
1370                    calloop::timer::TimeoutAction::ToInstant(instant)
1371                }
1372            })
1373            .expect("Failed to initialize refresh timer");
1374
1375        let window_ref = WindowRef {
1376            window: window.0.clone(),
1377            refresh_event_token,
1378        };
1379
1380        state.windows.insert(x_window, window_ref);
1381        Ok(Box::new(window))
1382    }
1383
1384    fn set_cursor_style(&self, style: CursorStyle) {
1385        let mut state = self.0.borrow_mut();
1386        let Some(focused_window) = state.mouse_focused_window else {
1387            return;
1388        };
1389        let current_style = state
1390            .cursor_styles
1391            .get(&focused_window)
1392            .unwrap_or(&CursorStyle::Arrow);
1393        if *current_style == style {
1394            return;
1395        }
1396
1397        let cursor = match state.cursor_cache.get(&style) {
1398            Some(cursor) => *cursor,
1399            None => {
1400                let Some(cursor) = state
1401                    .cursor_handle
1402                    .load_cursor(&state.xcb_connection, &style.to_icon_name())
1403                    .log_err()
1404                else {
1405                    return;
1406                };
1407                state.cursor_cache.insert(style, cursor);
1408                cursor
1409            }
1410        };
1411
1412        state.cursor_styles.insert(focused_window, style);
1413        state
1414            .xcb_connection
1415            .change_window_attributes(
1416                focused_window,
1417                &ChangeWindowAttributesAux {
1418                    cursor: Some(cursor),
1419                    ..Default::default()
1420                },
1421            )
1422            .expect("failed to change window cursor")
1423            .check()
1424            .unwrap();
1425    }
1426
1427    fn open_uri(&self, uri: &str) {
1428        #[cfg(any(feature = "wayland", feature = "x11"))]
1429        open_uri_internal(self.background_executor(), uri, None);
1430    }
1431
1432    fn reveal_path(&self, path: PathBuf) {
1433        #[cfg(any(feature = "x11", feature = "wayland"))]
1434        reveal_path_internal(self.background_executor(), path, None);
1435    }
1436
1437    fn write_to_primary(&self, item: crate::ClipboardItem) {
1438        let state = self.0.borrow_mut();
1439        state
1440            .clipboard
1441            .store(
1442                state.clipboard.setter.atoms.primary,
1443                state.clipboard.setter.atoms.utf8_string,
1444                item.text().unwrap_or_default().as_bytes(),
1445            )
1446            .ok();
1447    }
1448
1449    fn write_to_clipboard(&self, item: crate::ClipboardItem) {
1450        let mut state = self.0.borrow_mut();
1451        state
1452            .clipboard
1453            .store(
1454                state.clipboard.setter.atoms.clipboard,
1455                state.clipboard.setter.atoms.utf8_string,
1456                item.text().unwrap_or_default().as_bytes(),
1457            )
1458            .ok();
1459        state.clipboard_item.replace(item);
1460    }
1461
1462    fn read_from_primary(&self) -> Option<crate::ClipboardItem> {
1463        let state = self.0.borrow_mut();
1464        state
1465            .clipboard
1466            .load(
1467                state.clipboard.getter.atoms.primary,
1468                state.clipboard.getter.atoms.utf8_string,
1469                state.clipboard.getter.atoms.property,
1470                Duration::from_secs(3),
1471            )
1472            .map(|text| crate::ClipboardItem::new_string(String::from_utf8(text).unwrap()))
1473            .ok()
1474    }
1475
1476    fn read_from_clipboard(&self) -> Option<crate::ClipboardItem> {
1477        let state = self.0.borrow_mut();
1478        // if the last copy was from this app, return our cached item
1479        // which has metadata attached.
1480        if state
1481            .clipboard
1482            .setter
1483            .connection
1484            .get_selection_owner(state.clipboard.setter.atoms.clipboard)
1485            .ok()
1486            .and_then(|r| r.reply().ok())
1487            .map(|reply| reply.owner == state.clipboard.setter.window)
1488            .unwrap_or(false)
1489        {
1490            return state.clipboard_item.clone();
1491        }
1492        state
1493            .clipboard
1494            .load(
1495                state.clipboard.getter.atoms.clipboard,
1496                state.clipboard.getter.atoms.utf8_string,
1497                state.clipboard.getter.atoms.property,
1498                Duration::from_secs(3),
1499            )
1500            .map(|text| crate::ClipboardItem::new_string(String::from_utf8(text).unwrap()))
1501            .ok()
1502    }
1503
1504    fn run(&self) {
1505        let mut event_loop = self
1506            .0
1507            .borrow_mut()
1508            .event_loop
1509            .take()
1510            .expect("App is already running");
1511
1512        event_loop.run(None, &mut self.clone(), |_| {}).log_err();
1513    }
1514
1515    fn active_window(&self) -> Option<AnyWindowHandle> {
1516        let state = self.0.borrow();
1517        state.keyboard_focused_window.and_then(|focused_window| {
1518            state
1519                .windows
1520                .get(&focused_window)
1521                .map(|window| window.handle())
1522        })
1523    }
1524
1525    fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
1526        let state = self.0.borrow();
1527        let root = state.xcb_connection.setup().roots[state.x_root_index].root;
1528
1529        let reply = state
1530            .xcb_connection
1531            .get_property(
1532                false,
1533                root,
1534                state.atoms._NET_CLIENT_LIST_STACKING,
1535                xproto::AtomEnum::WINDOW,
1536                0,
1537                u32::MAX,
1538            )
1539            .ok()?
1540            .reply()
1541            .ok()?;
1542
1543        let window_ids = reply
1544            .value
1545            .chunks_exact(4)
1546            .map(|chunk| u32::from_ne_bytes(chunk.try_into().unwrap()))
1547            .collect::<Vec<xproto::Window>>();
1548
1549        let mut handles = Vec::new();
1550
1551        // We need to reverse, since _NET_CLIENT_LIST_STACKING has
1552        // a back-to-front order.
1553        // See: https://specifications.freedesktop.org/wm-spec/1.3/ar01s03.html
1554        for window_ref in window_ids
1555            .iter()
1556            .rev()
1557            .filter_map(|&win| state.windows.get(&win))
1558        {
1559            if !window_ref.window.state.borrow().destroyed {
1560                handles.push(window_ref.handle());
1561            }
1562        }
1563
1564        Some(handles)
1565    }
1566}
1567
1568// Adatpted from:
1569// https://docs.rs/winit/0.29.11/src/winit/platform_impl/linux/x11/monitor.rs.html#103-111
1570pub fn mode_refresh_rate(mode: &randr::ModeInfo) -> Duration {
1571    if mode.dot_clock == 0 || mode.htotal == 0 || mode.vtotal == 0 {
1572        return Duration::from_millis(16);
1573    }
1574
1575    let millihertz = mode.dot_clock as u64 * 1_000 / (mode.htotal as u64 * mode.vtotal as u64);
1576    let micros = 1_000_000_000 / millihertz;
1577    log::info!("Refreshing at {} micros", micros);
1578    Duration::from_micros(micros)
1579}
1580
1581fn fp3232_to_f32(value: xinput::Fp3232) -> f32 {
1582    value.integral as f32 + value.frac as f32 / u32::MAX as f32
1583}
1584
1585fn check_compositor_present(xcb_connection: &XCBConnection, root: u32) -> bool {
1586    // Method 1: Check for _NET_WM_CM_S{root}
1587    let atom_name = format!("_NET_WM_CM_S{}", root);
1588    let atom = xcb_connection
1589        .intern_atom(false, atom_name.as_bytes())
1590        .unwrap()
1591        .reply()
1592        .map(|reply| reply.atom)
1593        .unwrap_or(0);
1594
1595    let method1 = if atom != 0 {
1596        xcb_connection
1597            .get_selection_owner(atom)
1598            .unwrap()
1599            .reply()
1600            .map(|reply| reply.owner != 0)
1601            .unwrap_or(false)
1602    } else {
1603        false
1604    };
1605
1606    // Method 2: Check for _NET_WM_CM_OWNER
1607    let atom_name = "_NET_WM_CM_OWNER";
1608    let atom = xcb_connection
1609        .intern_atom(false, atom_name.as_bytes())
1610        .unwrap()
1611        .reply()
1612        .map(|reply| reply.atom)
1613        .unwrap_or(0);
1614
1615    let method2 = if atom != 0 {
1616        xcb_connection
1617            .get_property(false, root, atom, xproto::AtomEnum::WINDOW, 0, 1)
1618            .unwrap()
1619            .reply()
1620            .map(|reply| reply.value_len > 0)
1621            .unwrap_or(false)
1622    } else {
1623        false
1624    };
1625
1626    // Method 3: Check for _NET_SUPPORTING_WM_CHECK
1627    let atom_name = "_NET_SUPPORTING_WM_CHECK";
1628    let atom = xcb_connection
1629        .intern_atom(false, atom_name.as_bytes())
1630        .unwrap()
1631        .reply()
1632        .map(|reply| reply.atom)
1633        .unwrap_or(0);
1634
1635    let method3 = if atom != 0 {
1636        xcb_connection
1637            .get_property(false, root, atom, xproto::AtomEnum::WINDOW, 0, 1)
1638            .unwrap()
1639            .reply()
1640            .map(|reply| reply.value_len > 0)
1641            .unwrap_or(false)
1642    } else {
1643        false
1644    };
1645
1646    // TODO: Remove this
1647    log::info!(
1648        "Compositor detection: _NET_WM_CM_S?={}, _NET_WM_CM_OWNER={}, _NET_SUPPORTING_WM_CHECK={}",
1649        method1,
1650        method2,
1651        method3
1652    );
1653
1654    method1 || method2 || method3
1655}
1656
1657fn check_gtk_frame_extents_supported(
1658    xcb_connection: &XCBConnection,
1659    atoms: &XcbAtoms,
1660    root: xproto::Window,
1661) -> bool {
1662    let supported_atoms = xcb_connection
1663        .get_property(
1664            false,
1665            root,
1666            atoms._NET_SUPPORTED,
1667            xproto::AtomEnum::ATOM,
1668            0,
1669            1024,
1670        )
1671        .unwrap()
1672        .reply()
1673        .map(|reply| {
1674            // Convert Vec<u8> to Vec<u32>
1675            reply
1676                .value
1677                .chunks_exact(4)
1678                .map(|chunk| u32::from_ne_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]))
1679                .collect::<Vec<u32>>()
1680        })
1681        .unwrap_or_default();
1682
1683    supported_atoms.contains(&atoms._GTK_FRAME_EXTENTS)
1684}
1685
1686fn xdnd_is_atom_supported(atom: u32, atoms: &XcbAtoms) -> bool {
1687    return atom == atoms.TEXT
1688        || atom == atoms.STRING
1689        || atom == atoms.UTF8_STRING
1690        || atom == atoms.TEXT_PLAIN
1691        || atom == atoms.TEXT_PLAIN_UTF8
1692        || atom == atoms.TextUriList;
1693}
1694
1695fn xdnd_get_supported_atom(
1696    xcb_connection: &XCBConnection,
1697    supported_atoms: &XcbAtoms,
1698    target: xproto::Window,
1699) -> u32 {
1700    let property = xcb_connection
1701        .get_property(
1702            false,
1703            target,
1704            supported_atoms.XdndTypeList,
1705            AtomEnum::ANY,
1706            0,
1707            1024,
1708        )
1709        .unwrap();
1710    if let Ok(reply) = property.reply() {
1711        if let Some(atoms) = reply.value32() {
1712            for atom in atoms {
1713                if xdnd_is_atom_supported(atom, &supported_atoms) {
1714                    return atom;
1715                }
1716            }
1717        }
1718    }
1719    return 0;
1720}
1721
1722fn xdnd_send_finished(
1723    xcb_connection: &XCBConnection,
1724    atoms: &XcbAtoms,
1725    source: xproto::Window,
1726    target: xproto::Window,
1727) {
1728    let message = ClientMessageEvent {
1729        format: 32,
1730        window: target,
1731        type_: atoms.XdndFinished,
1732        data: ClientMessageData::from([source, 1, atoms.XdndActionCopy, 0, 0]),
1733        sequence: 0,
1734        response_type: xproto::CLIENT_MESSAGE_EVENT,
1735    };
1736    xcb_connection
1737        .send_event(false, target, EventMask::default(), message)
1738        .unwrap();
1739}
1740
1741fn xdnd_send_status(
1742    xcb_connection: &XCBConnection,
1743    atoms: &XcbAtoms,
1744    source: xproto::Window,
1745    target: xproto::Window,
1746    action: u32,
1747) {
1748    let message = ClientMessageEvent {
1749        format: 32,
1750        window: target,
1751        type_: atoms.XdndStatus,
1752        data: ClientMessageData::from([source, 1, 0, 0, action]),
1753        sequence: 0,
1754        response_type: xproto::CLIENT_MESSAGE_EVENT,
1755    };
1756    xcb_connection
1757        .send_event(false, target, EventMask::default(), message)
1758        .unwrap();
1759}
1760
1761/// Recomputes `pointer_device_states` by querying all pointer devices.
1762/// When a device is present in `scroll_values_to_preserve`, its value for `ScrollAxisState.scroll_value` is used.
1763fn get_new_pointer_device_states(
1764    xcb_connection: &XCBConnection,
1765    scroll_values_to_preserve: &BTreeMap<xinput::DeviceId, PointerDeviceState>,
1766) -> BTreeMap<xinput::DeviceId, PointerDeviceState> {
1767    let devices_query_result = xcb_connection
1768        .xinput_xi_query_device(XINPUT_ALL_DEVICES)
1769        .unwrap()
1770        .reply()
1771        .unwrap();
1772
1773    let mut pointer_device_states = BTreeMap::new();
1774    pointer_device_states.extend(
1775        devices_query_result
1776            .infos
1777            .iter()
1778            .filter(|info| is_pointer_device(info.type_))
1779            .filter_map(|info| {
1780                let scroll_data = info
1781                    .classes
1782                    .iter()
1783                    .filter_map(|class| class.data.as_scroll())
1784                    .map(|class| *class)
1785                    .rev()
1786                    .collect::<Vec<_>>();
1787                let old_state = scroll_values_to_preserve.get(&info.deviceid);
1788                let old_horizontal = old_state.map(|state| &state.horizontal);
1789                let old_vertical = old_state.map(|state| &state.vertical);
1790                let horizontal = scroll_data
1791                    .iter()
1792                    .find(|data| data.scroll_type == xinput::ScrollType::HORIZONTAL)
1793                    .map(|data| scroll_data_to_axis_state(data, old_horizontal));
1794                let vertical = scroll_data
1795                    .iter()
1796                    .find(|data| data.scroll_type == xinput::ScrollType::VERTICAL)
1797                    .map(|data| scroll_data_to_axis_state(data, old_vertical));
1798                if horizontal.is_none() && vertical.is_none() {
1799                    None
1800                } else {
1801                    Some((
1802                        info.deviceid,
1803                        PointerDeviceState {
1804                            horizontal: horizontal.unwrap_or_else(Default::default),
1805                            vertical: vertical.unwrap_or_else(Default::default),
1806                        },
1807                    ))
1808                }
1809            }),
1810    );
1811    if pointer_device_states.is_empty() {
1812        log::error!("Found no xinput mouse pointers.");
1813    }
1814    return pointer_device_states;
1815}
1816
1817/// Returns true if the device is a pointer device. Does not include pointer device groups.
1818fn is_pointer_device(type_: xinput::DeviceType) -> bool {
1819    type_ == xinput::DeviceType::SLAVE_POINTER
1820}
1821
1822fn scroll_data_to_axis_state(
1823    data: &xinput::DeviceClassDataScroll,
1824    old_axis_state_with_valid_scroll_value: Option<&ScrollAxisState>,
1825) -> ScrollAxisState {
1826    ScrollAxisState {
1827        valuator_number: Some(data.number),
1828        multiplier: SCROLL_LINES / fp3232_to_f32(data.increment),
1829        scroll_value: old_axis_state_with_valid_scroll_value.and_then(|state| state.scroll_value),
1830    }
1831}
1832
1833fn reset_all_pointer_device_scroll_positions(
1834    pointer_device_states: &mut BTreeMap<xinput::DeviceId, PointerDeviceState>,
1835) {
1836    pointer_device_states
1837        .iter_mut()
1838        .for_each(|(_, device_state)| reset_pointer_device_scroll_positions(device_state));
1839}
1840
1841fn reset_pointer_device_scroll_positions(pointer: &mut PointerDeviceState) {
1842    pointer.horizontal.scroll_value = None;
1843    pointer.vertical.scroll_value = None;
1844}
1845
1846/// Returns the scroll delta for a smooth scrolling motion event, or `None` if no scroll data is present.
1847fn get_scroll_delta_and_update_state(
1848    pointer: &mut PointerDeviceState,
1849    event: &xinput::MotionEvent,
1850) -> Option<Point<f32>> {
1851    let delta_x = get_axis_scroll_delta_and_update_state(event, &mut pointer.horizontal);
1852    let delta_y = get_axis_scroll_delta_and_update_state(event, &mut pointer.vertical);
1853    if delta_x.is_some() || delta_y.is_some() {
1854        Some(Point::new(delta_x.unwrap_or(0.0), delta_y.unwrap_or(0.0)))
1855    } else {
1856        None
1857    }
1858}
1859
1860fn get_axis_scroll_delta_and_update_state(
1861    event: &xinput::MotionEvent,
1862    axis: &mut ScrollAxisState,
1863) -> Option<f32> {
1864    let axis_index = get_valuator_axis_index(&event.valuator_mask, axis.valuator_number?)?;
1865    if let Some(axis_value) = event.axisvalues.get(axis_index) {
1866        let new_scroll = fp3232_to_f32(*axis_value);
1867        let delta_scroll = axis
1868            .scroll_value
1869            .map(|old_scroll| (old_scroll - new_scroll) * axis.multiplier);
1870        axis.scroll_value = Some(new_scroll);
1871        delta_scroll
1872    } else {
1873        log::error!("Encountered invalid XInput valuator_mask, scrolling may not work properly.");
1874        None
1875    }
1876}
1877
1878fn make_scroll_wheel_event(
1879    position: Point<Pixels>,
1880    scroll_delta: Point<f32>,
1881    modifiers: Modifiers,
1882) -> crate::ScrollWheelEvent {
1883    // When shift is held down, vertical scrolling turns into horizontal scrolling.
1884    let delta = if modifiers.shift {
1885        Point {
1886            x: scroll_delta.y,
1887            y: 0.0,
1888        }
1889    } else {
1890        scroll_delta
1891    };
1892    crate::ScrollWheelEvent {
1893        position,
1894        delta: ScrollDelta::Lines(delta),
1895        modifiers,
1896        touch_phase: TouchPhase::default(),
1897    }
1898}