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