client.rs

   1use crate::{Capslock, ResultExt as _, RunnableVariant, TaskTiming, profiler, xcb_flush};
   2use anyhow::{Context as _, anyhow};
   3use ashpd::WindowIdentifier;
   4use calloop::{
   5    EventLoop, LoopHandle, RegistrationToken,
   6    generic::{FdWrapper, Generic},
   7};
   8use collections::HashMap;
   9use core::str;
  10use http_client::Url;
  11use log::Level;
  12use smallvec::SmallVec;
  13use std::{
  14    cell::RefCell,
  15    collections::{BTreeMap, HashSet},
  16    ops::Deref,
  17    path::PathBuf,
  18    rc::{Rc, Weak},
  19    time::{Duration, Instant},
  20};
  21use util::ResultExt as _;
  22
  23use x11rb::{
  24    connection::{Connection, RequestConnection},
  25    cursor,
  26    errors::ConnectionError,
  27    protocol::randr::ConnectionExt as _,
  28    protocol::xinput::ConnectionExt,
  29    protocol::xkb::ConnectionExt as _,
  30    protocol::xproto::{
  31        AtomEnum, ChangeWindowAttributesAux, ClientMessageData, ClientMessageEvent,
  32        ConnectionExt as _, EventMask, ModMask, Visibility,
  33    },
  34    protocol::{Event, randr, render, xinput, xkb, xproto},
  35    resource_manager::Database,
  36    wrapper::ConnectionExt as _,
  37    xcb_ffi::XCBConnection,
  38};
  39use xim::{AttributeName, Client, InputStyle, x11rb::X11rbClient};
  40use xkbc::x11::ffi::{XKB_X11_MIN_MAJOR_XKB_VERSION, XKB_X11_MIN_MINOR_XKB_VERSION};
  41use xkbcommon::xkb::{self as xkbc, STATE_LAYOUT_EFFECTIVE};
  42
  43use super::{
  44    ButtonOrScroll, ScrollDirection, X11Display, X11WindowStatePtr, XcbAtoms, XimCallbackEvent,
  45    XimHandler, button_or_scroll_from_event_detail, check_reply,
  46    clipboard::{self, Clipboard},
  47    get_reply, get_valuator_axis_index, handle_connection_error, modifiers_from_state,
  48    pressed_button_from_mask,
  49};
  50
  51use crate::platform::{
  52    LinuxCommon, PlatformWindow,
  53    blade::BladeContext,
  54    linux::{
  55        DEFAULT_CURSOR_ICON_NAME, LinuxClient, get_xkb_compose_state, is_within_click_distance,
  56        log_cursor_icon_warning, open_uri_internal,
  57        platform::{DOUBLE_CLICK_INTERVAL, SCROLL_LINES},
  58        reveal_path_internal,
  59        xdg_desktop_portal::{Event as XDPEvent, XDPEventSource},
  60    },
  61};
  62use crate::{
  63    AnyWindowHandle, Bounds, ClipboardItem, CursorStyle, DisplayId, FileDropEvent, Keystroke,
  64    LinuxKeyboardLayout, Modifiers, ModifiersChangedEvent, MouseButton, Pixels, Platform,
  65    PlatformDisplay, PlatformInput, PlatformKeyboardLayout, Point, RequestFrameOptions,
  66    ScrollDelta, Size, TouchPhase, WindowParams, X11Window, modifiers_from_xinput_info, point, px,
  67};
  68
  69/// Value for DeviceId parameters which selects all devices.
  70pub(crate) const XINPUT_ALL_DEVICES: xinput::DeviceId = 0;
  71
  72/// Value for DeviceId parameters which selects all device groups. Events that
  73/// occur within the group are emitted by the group itself.
  74///
  75/// In XInput 2's interface, these are referred to as "master devices", but that
  76/// terminology is both archaic and unclear.
  77pub(crate) const XINPUT_ALL_DEVICE_GROUPS: xinput::DeviceId = 1;
  78
  79const GPUI_X11_SCALE_FACTOR_ENV: &str = "GPUI_X11_SCALE_FACTOR";
  80
  81pub(crate) struct WindowRef {
  82    window: X11WindowStatePtr,
  83    refresh_state: Option<RefreshState>,
  84    expose_event_received: bool,
  85    last_visibility: Visibility,
  86    is_mapped: bool,
  87}
  88
  89impl WindowRef {
  90    pub fn handle(&self) -> AnyWindowHandle {
  91        self.window.state.borrow().handle
  92    }
  93}
  94
  95impl Deref for WindowRef {
  96    type Target = X11WindowStatePtr;
  97
  98    fn deref(&self) -> &Self::Target {
  99        &self.window
 100    }
 101}
 102
 103enum RefreshState {
 104    Hidden {
 105        refresh_rate: Duration,
 106    },
 107    PeriodicRefresh {
 108        refresh_rate: Duration,
 109        event_loop_token: RegistrationToken,
 110    },
 111}
 112
 113#[derive(Debug)]
 114#[non_exhaustive]
 115pub enum EventHandlerError {
 116    XCBConnectionError(ConnectionError),
 117    XIMClientError(xim::ClientError),
 118}
 119
 120impl std::error::Error for EventHandlerError {}
 121
 122impl std::fmt::Display for EventHandlerError {
 123    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 124        match self {
 125            EventHandlerError::XCBConnectionError(err) => err.fmt(f),
 126            EventHandlerError::XIMClientError(err) => err.fmt(f),
 127        }
 128    }
 129}
 130
 131impl From<ConnectionError> for EventHandlerError {
 132    fn from(err: ConnectionError) -> Self {
 133        EventHandlerError::XCBConnectionError(err)
 134    }
 135}
 136
 137impl From<xim::ClientError> for EventHandlerError {
 138    fn from(err: xim::ClientError) -> Self {
 139        EventHandlerError::XIMClientError(err)
 140    }
 141}
 142
 143#[derive(Debug, Default)]
 144pub struct Xdnd {
 145    other_window: xproto::Window,
 146    drag_type: u32,
 147    retrieved: bool,
 148    position: Point<Pixels>,
 149}
 150
 151#[derive(Debug)]
 152struct PointerDeviceState {
 153    horizontal: ScrollAxisState,
 154    vertical: ScrollAxisState,
 155}
 156
 157#[derive(Debug, Default)]
 158struct ScrollAxisState {
 159    /// Valuator number for looking up this axis's scroll value.
 160    valuator_number: Option<u16>,
 161    /// Conversion factor from scroll units to lines.
 162    multiplier: f32,
 163    /// Last scroll value for calculating scroll delta.
 164    ///
 165    /// This gets set to `None` whenever it might be invalid - when devices change or when window focus changes.
 166    /// The logic errs on the side of invalidating this, since the consequence is just skipping the delta of one scroll event.
 167    /// The consequence of not invalidating it can be large invalid deltas, which are much more user visible.
 168    scroll_value: Option<f32>,
 169}
 170
 171pub struct X11ClientState {
 172    pub(crate) loop_handle: LoopHandle<'static, X11Client>,
 173    pub(crate) event_loop: Option<calloop::EventLoop<'static, X11Client>>,
 174
 175    pub(crate) last_click: Instant,
 176    pub(crate) last_mouse_button: Option<MouseButton>,
 177    pub(crate) last_location: Point<Pixels>,
 178    pub(crate) current_count: usize,
 179
 180    gpu_context: BladeContext,
 181
 182    pub(crate) scale_factor: f32,
 183
 184    xkb_context: xkbc::Context,
 185    pub(crate) xcb_connection: Rc<XCBConnection>,
 186    xkb_device_id: i32,
 187    client_side_decorations_supported: bool,
 188    pub(crate) x_root_index: usize,
 189    pub(crate) _resource_database: Database,
 190    pub(crate) atoms: XcbAtoms,
 191    pub(crate) windows: HashMap<xproto::Window, WindowRef>,
 192    pub(crate) mouse_focused_window: Option<xproto::Window>,
 193    pub(crate) keyboard_focused_window: Option<xproto::Window>,
 194    pub(crate) xkb: xkbc::State,
 195    keyboard_layout: LinuxKeyboardLayout,
 196    pub(crate) ximc: Option<X11rbClient<Rc<XCBConnection>>>,
 197    pub(crate) xim_handler: Option<XimHandler>,
 198    pub modifiers: Modifiers,
 199    pub capslock: Capslock,
 200    // TODO: Can the other updates to `modifiers` be removed so that this is unnecessary?
 201    // capslock logic was done analog to modifiers
 202    pub last_modifiers_changed_event: Modifiers,
 203    pub last_capslock_changed_event: Capslock,
 204
 205    pub(crate) compose_state: Option<xkbc::compose::State>,
 206    pub(crate) pre_edit_text: Option<String>,
 207    pub(crate) composing: bool,
 208    pub(crate) pre_key_char_down: Option<Keystroke>,
 209    pub(crate) cursor_handle: cursor::Handle,
 210    pub(crate) cursor_styles: HashMap<xproto::Window, CursorStyle>,
 211    pub(crate) cursor_cache: HashMap<CursorStyle, Option<xproto::Cursor>>,
 212
 213    pointer_device_states: BTreeMap<xinput::DeviceId, PointerDeviceState>,
 214
 215    pub(crate) common: LinuxCommon,
 216    pub(crate) clipboard: Clipboard,
 217    pub(crate) clipboard_item: Option<ClipboardItem>,
 218    pub(crate) xdnd_state: Xdnd,
 219}
 220
 221#[derive(Clone)]
 222pub struct X11ClientStatePtr(pub Weak<RefCell<X11ClientState>>);
 223
 224impl X11ClientStatePtr {
 225    pub fn get_client(&self) -> Option<X11Client> {
 226        self.0.upgrade().map(X11Client)
 227    }
 228
 229    pub fn drop_window(&self, x_window: u32) {
 230        let Some(client) = self.get_client() else {
 231            return;
 232        };
 233        let mut state = client.0.borrow_mut();
 234
 235        if let Some(window_ref) = state.windows.remove(&x_window)
 236            && let Some(RefreshState::PeriodicRefresh {
 237                event_loop_token, ..
 238            }) = window_ref.refresh_state
 239        {
 240            state.loop_handle.remove(event_loop_token);
 241        }
 242        if state.mouse_focused_window == Some(x_window) {
 243            state.mouse_focused_window = None;
 244        }
 245        if state.keyboard_focused_window == Some(x_window) {
 246            state.keyboard_focused_window = None;
 247        }
 248        state.cursor_styles.remove(&x_window);
 249    }
 250
 251    pub fn update_ime_position(&self, bounds: Bounds<Pixels>) {
 252        let Some(client) = self.get_client() else {
 253            return;
 254        };
 255        let mut state = client.0.borrow_mut();
 256        if state.composing || state.ximc.is_none() {
 257            return;
 258        }
 259
 260        let Some(mut ximc) = state.ximc.take() else {
 261            log::error!("bug: xim connection not set");
 262            return;
 263        };
 264        let Some(xim_handler) = state.xim_handler.take() else {
 265            log::error!("bug: xim handler not set");
 266            state.ximc = Some(ximc);
 267            return;
 268        };
 269        let scaled_bounds = bounds.scale(state.scale_factor);
 270        let ic_attributes = ximc
 271            .build_ic_attributes()
 272            .push(
 273                xim::AttributeName::InputStyle,
 274                xim::InputStyle::PREEDIT_CALLBACKS,
 275            )
 276            .push(xim::AttributeName::ClientWindow, xim_handler.window)
 277            .push(xim::AttributeName::FocusWindow, xim_handler.window)
 278            .nested_list(xim::AttributeName::PreeditAttributes, |b| {
 279                b.push(
 280                    xim::AttributeName::SpotLocation,
 281                    xim::Point {
 282                        x: u32::from(scaled_bounds.origin.x + scaled_bounds.size.width) as i16,
 283                        y: u32::from(scaled_bounds.origin.y + scaled_bounds.size.height) as i16,
 284                    },
 285                );
 286            })
 287            .build();
 288        let _ = ximc
 289            .set_ic_values(xim_handler.im_id, xim_handler.ic_id, ic_attributes)
 290            .log_err();
 291        state.ximc = Some(ximc);
 292        state.xim_handler = Some(xim_handler);
 293    }
 294}
 295
 296#[derive(Clone)]
 297pub(crate) struct X11Client(Rc<RefCell<X11ClientState>>);
 298
 299impl X11Client {
 300    pub(crate) fn new() -> anyhow::Result<Self> {
 301        let event_loop = EventLoop::try_new()?;
 302
 303        let (common, main_receiver) = LinuxCommon::new(event_loop.get_signal());
 304
 305        let handle = event_loop.handle();
 306
 307        handle
 308            .insert_source(main_receiver, {
 309                let handle = handle.clone();
 310                move |event, _, _: &mut X11Client| {
 311                    if let calloop::channel::Event::Msg(runnable) = event {
 312                        // Insert the runnables as idle callbacks, so we make sure that user-input and X11
 313                        // events have higher priority and runnables are only worked off after the event
 314                        // callbacks.
 315                        handle.insert_idle(|_| {
 316                            let start = Instant::now();
 317                            let mut timing = match runnable {
 318                                RunnableVariant::Meta(runnable) => {
 319                                    let metadata = runnable.metadata();
 320                                    let location = metadata.location;
 321
 322                                    if !metadata.is_app_alive() {
 323                                        drop(runnable);
 324                                        return;
 325                                    }
 326
 327                                    let timing = TaskTiming {
 328                                        location,
 329                                        start,
 330                                        end: None,
 331                                    };
 332                                    profiler::add_task_timing(timing);
 333
 334                                    runnable.run();
 335                                    timing
 336                                }
 337                                RunnableVariant::Compat(runnable) => {
 338                                    let location = core::panic::Location::caller();
 339                                    let timing = TaskTiming {
 340                                        location,
 341                                        start,
 342                                        end: None,
 343                                    };
 344                                    profiler::add_task_timing(timing);
 345
 346                                    runnable.run();
 347                                    timing
 348                                }
 349                            };
 350
 351                            let end = Instant::now();
 352                            timing.end = Some(end);
 353                            profiler::add_task_timing(timing);
 354                        });
 355                    }
 356                }
 357            })
 358            .map_err(|err| {
 359                anyhow!("Failed to initialize event loop handling of foreground tasks: {err:?}")
 360            })?;
 361
 362        let (xcb_connection, x_root_index) = XCBConnection::connect(None)?;
 363        xcb_connection.prefetch_extension_information(xkb::X11_EXTENSION_NAME)?;
 364        xcb_connection.prefetch_extension_information(randr::X11_EXTENSION_NAME)?;
 365        xcb_connection.prefetch_extension_information(render::X11_EXTENSION_NAME)?;
 366        xcb_connection.prefetch_extension_information(xinput::X11_EXTENSION_NAME)?;
 367
 368        // Announce to X server that XInput up to 2.1 is supported. To increase this to 2.2 and
 369        // beyond, support for touch events would need to be added.
 370        let xinput_version = get_reply(
 371            || "XInput XiQueryVersion failed",
 372            xcb_connection.xinput_xi_query_version(2, 1),
 373        )?;
 374        assert!(
 375            xinput_version.major_version >= 2,
 376            "XInput version >= 2 required."
 377        );
 378
 379        let pointer_device_states =
 380            current_pointer_device_states(&xcb_connection, &BTreeMap::new()).unwrap_or_default();
 381
 382        let atoms = XcbAtoms::new(&xcb_connection)
 383            .context("Failed to get XCB atoms")?
 384            .reply()
 385            .context("Failed to get XCB atoms")?;
 386
 387        let root = xcb_connection.setup().roots[0].root;
 388        let compositor_present = check_compositor_present(&xcb_connection, root);
 389        let gtk_frame_extents_supported =
 390            check_gtk_frame_extents_supported(&xcb_connection, &atoms, root);
 391        let client_side_decorations_supported = compositor_present && gtk_frame_extents_supported;
 392        log::info!(
 393            "x11: compositor present: {}, gtk_frame_extents_supported: {}",
 394            compositor_present,
 395            gtk_frame_extents_supported
 396        );
 397
 398        let xkb = get_reply(
 399            || "Failed to initialize XKB extension",
 400            xcb_connection
 401                .xkb_use_extension(XKB_X11_MIN_MAJOR_XKB_VERSION, XKB_X11_MIN_MINOR_XKB_VERSION),
 402        )?;
 403        assert!(xkb.supported);
 404
 405        let events = xkb::EventType::STATE_NOTIFY
 406            | xkb::EventType::MAP_NOTIFY
 407            | xkb::EventType::NEW_KEYBOARD_NOTIFY;
 408        let map_notify_parts = xkb::MapPart::KEY_TYPES
 409            | xkb::MapPart::KEY_SYMS
 410            | xkb::MapPart::MODIFIER_MAP
 411            | xkb::MapPart::EXPLICIT_COMPONENTS
 412            | xkb::MapPart::KEY_ACTIONS
 413            | xkb::MapPart::KEY_BEHAVIORS
 414            | xkb::MapPart::VIRTUAL_MODS
 415            | xkb::MapPart::VIRTUAL_MOD_MAP;
 416        check_reply(
 417            || "Failed to select XKB events",
 418            xcb_connection.xkb_select_events(
 419                xkb::ID::USE_CORE_KBD.into(),
 420                0u8.into(),
 421                events,
 422                map_notify_parts,
 423                map_notify_parts,
 424                &xkb::SelectEventsAux::new(),
 425            ),
 426        )?;
 427
 428        let xkb_context = xkbc::Context::new(xkbc::CONTEXT_NO_FLAGS);
 429        let xkb_device_id = xkbc::x11::get_core_keyboard_device_id(&xcb_connection);
 430        let xkb_state = {
 431            let xkb_keymap = xkbc::x11::keymap_new_from_device(
 432                &xkb_context,
 433                &xcb_connection,
 434                xkb_device_id,
 435                xkbc::KEYMAP_COMPILE_NO_FLAGS,
 436            );
 437            xkbc::x11::state_new_from_device(&xkb_keymap, &xcb_connection, xkb_device_id)
 438        };
 439        let compose_state = get_xkb_compose_state(&xkb_context);
 440        let layout_idx = xkb_state.serialize_layout(STATE_LAYOUT_EFFECTIVE);
 441        let layout_name = xkb_state
 442            .get_keymap()
 443            .layout_get_name(layout_idx)
 444            .to_string();
 445        let keyboard_layout = LinuxKeyboardLayout::new(layout_name.into());
 446
 447        let gpu_context = BladeContext::new().notify_err("Unable to init GPU context");
 448
 449        let resource_database = x11rb::resource_manager::new_from_default(&xcb_connection)
 450            .context("Failed to create resource database")?;
 451        let scale_factor = get_scale_factor(&xcb_connection, &resource_database, x_root_index);
 452        let cursor_handle = cursor::Handle::new(&xcb_connection, x_root_index, &resource_database)
 453            .context("Failed to initialize cursor theme handler")?
 454            .reply()
 455            .context("Failed to initialize cursor theme handler")?;
 456
 457        let clipboard = Clipboard::new().context("Failed to initialize clipboard")?;
 458
 459        let xcb_connection = Rc::new(xcb_connection);
 460
 461        let ximc = X11rbClient::init(Rc::clone(&xcb_connection), x_root_index, None).ok();
 462        let xim_handler = if ximc.is_some() {
 463            Some(XimHandler::new())
 464        } else {
 465            None
 466        };
 467
 468        // Safety: Safe if xcb::Connection always returns a valid fd
 469        let fd = unsafe { FdWrapper::new(Rc::clone(&xcb_connection)) };
 470
 471        handle
 472            .insert_source(
 473                Generic::new_with_error::<EventHandlerError>(
 474                    fd,
 475                    calloop::Interest::READ,
 476                    calloop::Mode::Level,
 477                ),
 478                {
 479                    let xcb_connection = xcb_connection.clone();
 480                    move |_readiness, _, client| {
 481                        client.process_x11_events(&xcb_connection)?;
 482                        Ok(calloop::PostAction::Continue)
 483                    }
 484                },
 485            )
 486            .map_err(|err| anyhow!("Failed to initialize X11 event source: {err:?}"))?;
 487
 488        handle
 489            .insert_source(XDPEventSource::new(&common.background_executor), {
 490                move |event, _, client| match event {
 491                    XDPEvent::WindowAppearance(appearance) => {
 492                        client.with_common(|common| common.appearance = appearance);
 493                        for window in client.0.borrow_mut().windows.values_mut() {
 494                            window.window.set_appearance(appearance);
 495                        }
 496                    }
 497                    XDPEvent::CursorTheme(_) | XDPEvent::CursorSize(_) => {
 498                        // noop, X11 manages this for us.
 499                    }
 500                }
 501            })
 502            .map_err(|err| anyhow!("Failed to initialize XDP event source: {err:?}"))?;
 503
 504        xcb_flush(&xcb_connection);
 505
 506        Ok(X11Client(Rc::new(RefCell::new(X11ClientState {
 507            modifiers: Modifiers::default(),
 508            capslock: Capslock::default(),
 509            last_modifiers_changed_event: Modifiers::default(),
 510            last_capslock_changed_event: Capslock::default(),
 511            event_loop: Some(event_loop),
 512            loop_handle: handle,
 513            common,
 514            last_click: Instant::now(),
 515            last_mouse_button: None,
 516            last_location: Point::new(px(0.0), px(0.0)),
 517            current_count: 0,
 518            gpu_context,
 519            scale_factor,
 520
 521            xkb_context,
 522            xcb_connection,
 523            xkb_device_id,
 524            client_side_decorations_supported,
 525            x_root_index,
 526            _resource_database: resource_database,
 527            atoms,
 528            windows: HashMap::default(),
 529            mouse_focused_window: None,
 530            keyboard_focused_window: None,
 531            xkb: xkb_state,
 532            keyboard_layout,
 533            ximc,
 534            xim_handler,
 535
 536            compose_state,
 537            pre_edit_text: None,
 538            pre_key_char_down: None,
 539            composing: false,
 540
 541            cursor_handle,
 542            cursor_styles: HashMap::default(),
 543            cursor_cache: HashMap::default(),
 544
 545            pointer_device_states,
 546
 547            clipboard,
 548            clipboard_item: None,
 549            xdnd_state: Xdnd::default(),
 550        }))))
 551    }
 552
 553    pub fn process_x11_events(
 554        &self,
 555        xcb_connection: &XCBConnection,
 556    ) -> Result<(), EventHandlerError> {
 557        loop {
 558            let mut events = Vec::new();
 559            let mut windows_to_refresh = HashSet::new();
 560
 561            let mut last_key_release = None;
 562
 563            // event handlers for new keyboard / remapping refresh the state without using event
 564            // details, this deduplicates them.
 565            let mut last_keymap_change_event: Option<Event> = None;
 566
 567            loop {
 568                match xcb_connection.poll_for_event() {
 569                    Ok(Some(event)) => {
 570                        match event {
 571                            Event::Expose(expose_event) => {
 572                                windows_to_refresh.insert(expose_event.window);
 573                            }
 574                            Event::KeyRelease(_) => {
 575                                if let Some(last_keymap_change_event) =
 576                                    last_keymap_change_event.take()
 577                                {
 578                                    if let Some(last_key_release) = last_key_release.take() {
 579                                        events.push(last_key_release);
 580                                    }
 581                                    events.push(last_keymap_change_event);
 582                                }
 583
 584                                last_key_release = Some(event);
 585                            }
 586                            Event::KeyPress(key_press) => {
 587                                if let Some(last_keymap_change_event) =
 588                                    last_keymap_change_event.take()
 589                                {
 590                                    if let Some(last_key_release) = last_key_release.take() {
 591                                        events.push(last_key_release);
 592                                    }
 593                                    events.push(last_keymap_change_event);
 594                                }
 595
 596                                if let Some(Event::KeyRelease(key_release)) =
 597                                    last_key_release.take()
 598                                {
 599                                    // We ignore that last KeyRelease if it's too close to this KeyPress,
 600                                    // suggesting that it's auto-generated by X11 as a key-repeat event.
 601                                    if key_release.detail != key_press.detail
 602                                        || key_press.time.saturating_sub(key_release.time) > 20
 603                                    {
 604                                        events.push(Event::KeyRelease(key_release));
 605                                    }
 606                                }
 607                                events.push(Event::KeyPress(key_press));
 608                            }
 609                            Event::XkbNewKeyboardNotify(_) | Event::XkbMapNotify(_) => {
 610                                if let Some(release_event) = last_key_release.take() {
 611                                    events.push(release_event);
 612                                }
 613                                last_keymap_change_event = Some(event);
 614                            }
 615                            _ => {
 616                                if let Some(release_event) = last_key_release.take() {
 617                                    events.push(release_event);
 618                                }
 619                                events.push(event);
 620                            }
 621                        }
 622                    }
 623                    Ok(None) => {
 624                        break;
 625                    }
 626                    Err(err) => {
 627                        let err = handle_connection_error(err);
 628                        log::warn!("error while polling for X11 events: {err:?}");
 629                        break;
 630                    }
 631                }
 632            }
 633
 634            if let Some(release_event) = last_key_release.take() {
 635                events.push(release_event);
 636            }
 637            if let Some(keymap_change_event) = last_keymap_change_event.take() {
 638                events.push(keymap_change_event);
 639            }
 640
 641            if events.is_empty() && windows_to_refresh.is_empty() {
 642                break;
 643            }
 644
 645            for window in windows_to_refresh.into_iter() {
 646                let mut state = self.0.borrow_mut();
 647                if let Some(window) = state.windows.get_mut(&window) {
 648                    window.expose_event_received = true;
 649                }
 650            }
 651
 652            for event in events.into_iter() {
 653                let mut state = self.0.borrow_mut();
 654                if !state.has_xim() {
 655                    drop(state);
 656                    self.handle_event(event);
 657                    continue;
 658                }
 659
 660                let Some((mut ximc, mut xim_handler)) = state.take_xim() else {
 661                    continue;
 662                };
 663                let xim_connected = xim_handler.connected;
 664                drop(state);
 665
 666                let xim_filtered = ximc.filter_event(&event, &mut xim_handler);
 667                let xim_callback_event = xim_handler.last_callback_event.take();
 668
 669                let mut state = self.0.borrow_mut();
 670                state.restore_xim(ximc, xim_handler);
 671                drop(state);
 672
 673                if let Some(event) = xim_callback_event {
 674                    self.handle_xim_callback_event(event);
 675                }
 676
 677                match xim_filtered {
 678                    Ok(handled) => {
 679                        if handled {
 680                            continue;
 681                        }
 682                        if xim_connected {
 683                            self.xim_handle_event(event);
 684                        } else {
 685                            self.handle_event(event);
 686                        }
 687                    }
 688                    Err(err) => {
 689                        // this might happen when xim server crashes on one of the events
 690                        // we do lose 1-2 keys when crash happens since there is no reliable way to get that info
 691                        // luckily, x11 sends us window not found error when xim server crashes upon further key press
 692                        // hence we fall back to handle_event
 693                        log::error!("XIMClientError: {}", err);
 694                        let mut state = self.0.borrow_mut();
 695                        state.take_xim();
 696                        drop(state);
 697                        self.handle_event(event);
 698                    }
 699                }
 700            }
 701        }
 702        Ok(())
 703    }
 704
 705    pub fn enable_ime(&self) {
 706        let mut state = self.0.borrow_mut();
 707        if !state.has_xim() {
 708            return;
 709        }
 710
 711        let Some((mut ximc, mut xim_handler)) = state.take_xim() else {
 712            return;
 713        };
 714        let mut ic_attributes = ximc
 715            .build_ic_attributes()
 716            .push(AttributeName::InputStyle, InputStyle::PREEDIT_CALLBACKS)
 717            .push(AttributeName::ClientWindow, xim_handler.window)
 718            .push(AttributeName::FocusWindow, xim_handler.window);
 719
 720        let window_id = state.keyboard_focused_window;
 721        drop(state);
 722        if let Some(window_id) = window_id {
 723            let Some(window) = self.get_window(window_id) else {
 724                log::error!("Failed to get window for IME positioning");
 725                let mut state = self.0.borrow_mut();
 726                state.ximc = Some(ximc);
 727                state.xim_handler = Some(xim_handler);
 728                return;
 729            };
 730            if let Some(scaled_area) = window.get_ime_area() {
 731                ic_attributes =
 732                    ic_attributes.nested_list(xim::AttributeName::PreeditAttributes, |b| {
 733                        b.push(
 734                            xim::AttributeName::SpotLocation,
 735                            xim::Point {
 736                                x: u32::from(scaled_area.origin.x + scaled_area.size.width) as i16,
 737                                y: u32::from(scaled_area.origin.y + scaled_area.size.height) as i16,
 738                            },
 739                        );
 740                    });
 741            }
 742        }
 743        ximc.create_ic(xim_handler.im_id, ic_attributes.build())
 744            .ok();
 745        let mut state = self.0.borrow_mut();
 746        state.restore_xim(ximc, xim_handler);
 747    }
 748
 749    pub fn reset_ime(&self) {
 750        let mut state = self.0.borrow_mut();
 751        state.composing = false;
 752        if let Some(mut ximc) = state.ximc.take() {
 753            if let Some(xim_handler) = state.xim_handler.as_ref() {
 754                ximc.reset_ic(xim_handler.im_id, xim_handler.ic_id).ok();
 755            } else {
 756                log::error!("bug: xim handler not set in reset_ime");
 757            }
 758            state.ximc = Some(ximc);
 759        }
 760    }
 761
 762    pub(crate) fn get_window(&self, win: xproto::Window) -> Option<X11WindowStatePtr> {
 763        let state = self.0.borrow();
 764        state
 765            .windows
 766            .get(&win)
 767            .filter(|window_reference| !window_reference.window.state.borrow().destroyed)
 768            .map(|window_reference| window_reference.window.clone())
 769    }
 770
 771    fn handle_event(&self, event: Event) -> Option<()> {
 772        match event {
 773            Event::UnmapNotify(event) => {
 774                let mut state = self.0.borrow_mut();
 775                if let Some(window_ref) = state.windows.get_mut(&event.window) {
 776                    window_ref.is_mapped = false;
 777                }
 778                state.update_refresh_loop(event.window);
 779            }
 780            Event::MapNotify(event) => {
 781                let mut state = self.0.borrow_mut();
 782                if let Some(window_ref) = state.windows.get_mut(&event.window) {
 783                    window_ref.is_mapped = true;
 784                }
 785                state.update_refresh_loop(event.window);
 786            }
 787            Event::VisibilityNotify(event) => {
 788                let mut state = self.0.borrow_mut();
 789                if let Some(window_ref) = state.windows.get_mut(&event.window) {
 790                    window_ref.last_visibility = event.state;
 791                }
 792                state.update_refresh_loop(event.window);
 793            }
 794            Event::ClientMessage(event) => {
 795                let window = self.get_window(event.window)?;
 796                let [atom, arg1, arg2, arg3, arg4] = event.data.as_data32();
 797                let mut state = self.0.borrow_mut();
 798
 799                if atom == state.atoms.WM_DELETE_WINDOW && window.should_close() {
 800                    // window "x" button clicked by user
 801                    // Rest of the close logic is handled in drop_window()
 802                    drop(state);
 803                    window.close();
 804                    state = self.0.borrow_mut();
 805                } else if atom == state.atoms._NET_WM_SYNC_REQUEST {
 806                    window.state.borrow_mut().last_sync_counter =
 807                        Some(x11rb::protocol::sync::Int64 {
 808                            lo: arg2,
 809                            hi: arg3 as i32,
 810                        })
 811                }
 812
 813                if event.type_ == state.atoms.XdndEnter {
 814                    state.xdnd_state.other_window = atom;
 815                    if (arg1 & 0x1) == 0x1 {
 816                        state.xdnd_state.drag_type = xdnd_get_supported_atom(
 817                            &state.xcb_connection,
 818                            &state.atoms,
 819                            state.xdnd_state.other_window,
 820                        );
 821                    } else {
 822                        if let Some(atom) = [arg2, arg3, arg4]
 823                            .into_iter()
 824                            .find(|atom| xdnd_is_atom_supported(*atom, &state.atoms))
 825                        {
 826                            state.xdnd_state.drag_type = atom;
 827                        }
 828                    }
 829                } else if event.type_ == state.atoms.XdndLeave {
 830                    let position = state.xdnd_state.position;
 831                    drop(state);
 832                    window
 833                        .handle_input(PlatformInput::FileDrop(FileDropEvent::Pending { position }));
 834                    window.handle_input(PlatformInput::FileDrop(FileDropEvent::Exited {}));
 835                    self.0.borrow_mut().xdnd_state = Xdnd::default();
 836                } else if event.type_ == state.atoms.XdndPosition {
 837                    if let Ok(pos) = get_reply(
 838                        || "Failed to query pointer position",
 839                        state.xcb_connection.query_pointer(event.window),
 840                    ) {
 841                        state.xdnd_state.position =
 842                            Point::new(Pixels(pos.win_x as f32), Pixels(pos.win_y as f32));
 843                    }
 844                    if !state.xdnd_state.retrieved {
 845                        check_reply(
 846                            || "Failed to convert selection for drag and drop",
 847                            state.xcb_connection.convert_selection(
 848                                event.window,
 849                                state.atoms.XdndSelection,
 850                                state.xdnd_state.drag_type,
 851                                state.atoms.XDND_DATA,
 852                                arg3,
 853                            ),
 854                        )
 855                        .log_err();
 856                    }
 857                    xdnd_send_status(
 858                        &state.xcb_connection,
 859                        &state.atoms,
 860                        event.window,
 861                        state.xdnd_state.other_window,
 862                        arg4,
 863                    );
 864                    let position = state.xdnd_state.position;
 865                    drop(state);
 866                    window
 867                        .handle_input(PlatformInput::FileDrop(FileDropEvent::Pending { position }));
 868                } else if event.type_ == state.atoms.XdndDrop {
 869                    xdnd_send_finished(
 870                        &state.xcb_connection,
 871                        &state.atoms,
 872                        event.window,
 873                        state.xdnd_state.other_window,
 874                    );
 875                    let position = state.xdnd_state.position;
 876                    drop(state);
 877                    window
 878                        .handle_input(PlatformInput::FileDrop(FileDropEvent::Submit { position }));
 879                    self.0.borrow_mut().xdnd_state = Xdnd::default();
 880                }
 881            }
 882            Event::SelectionNotify(event) => {
 883                let window = self.get_window(event.requestor)?;
 884                let mut state = self.0.borrow_mut();
 885                let reply = get_reply(
 886                    || "Failed to get XDND_DATA",
 887                    state.xcb_connection.get_property(
 888                        false,
 889                        event.requestor,
 890                        state.atoms.XDND_DATA,
 891                        AtomEnum::ANY,
 892                        0,
 893                        1024,
 894                    ),
 895                )
 896                .log_err();
 897                let Some(reply) = reply else {
 898                    return Some(());
 899                };
 900                if let Ok(file_list) = str::from_utf8(&reply.value) {
 901                    let paths: SmallVec<[_; 2]> = file_list
 902                        .lines()
 903                        .filter_map(|path| Url::parse(path).log_err())
 904                        .filter_map(|url| url.to_file_path().log_err())
 905                        .collect();
 906                    let input = PlatformInput::FileDrop(FileDropEvent::Entered {
 907                        position: state.xdnd_state.position,
 908                        paths: crate::ExternalPaths(paths),
 909                    });
 910                    drop(state);
 911                    window.handle_input(input);
 912                    self.0.borrow_mut().xdnd_state.retrieved = true;
 913                }
 914            }
 915            Event::ConfigureNotify(event) => {
 916                let bounds = Bounds {
 917                    origin: Point {
 918                        x: event.x.into(),
 919                        y: event.y.into(),
 920                    },
 921                    size: Size {
 922                        width: event.width.into(),
 923                        height: event.height.into(),
 924                    },
 925                };
 926                let window = self.get_window(event.window)?;
 927                window
 928                    .set_bounds(bounds)
 929                    .context("X11: Failed to set window bounds")
 930                    .log_err();
 931            }
 932            Event::PropertyNotify(event) => {
 933                let window = self.get_window(event.window)?;
 934                window
 935                    .property_notify(event)
 936                    .context("X11: Failed to handle property notify")
 937                    .log_err();
 938            }
 939            Event::FocusIn(event) => {
 940                let window = self.get_window(event.event)?;
 941                window.set_active(true);
 942                let mut state = self.0.borrow_mut();
 943                state.keyboard_focused_window = Some(event.event);
 944                if let Some(handler) = state.xim_handler.as_mut() {
 945                    handler.window = event.event;
 946                }
 947                drop(state);
 948                self.enable_ime();
 949            }
 950            Event::FocusOut(event) => {
 951                let window = self.get_window(event.event)?;
 952                window.set_active(false);
 953                let mut state = self.0.borrow_mut();
 954                // 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)
 955                reset_all_pointer_device_scroll_positions(&mut state.pointer_device_states);
 956                state.keyboard_focused_window = None;
 957                if let Some(compose_state) = state.compose_state.as_mut() {
 958                    compose_state.reset();
 959                }
 960                state.pre_edit_text.take();
 961                drop(state);
 962                self.reset_ime();
 963                window.handle_ime_delete();
 964            }
 965            Event::XkbNewKeyboardNotify(_) | Event::XkbMapNotify(_) => {
 966                let mut state = self.0.borrow_mut();
 967                let xkb_state = {
 968                    let xkb_keymap = xkbc::x11::keymap_new_from_device(
 969                        &state.xkb_context,
 970                        &state.xcb_connection,
 971                        state.xkb_device_id,
 972                        xkbc::KEYMAP_COMPILE_NO_FLAGS,
 973                    );
 974                    xkbc::x11::state_new_from_device(
 975                        &xkb_keymap,
 976                        &state.xcb_connection,
 977                        state.xkb_device_id,
 978                    )
 979                };
 980                state.xkb = xkb_state;
 981                drop(state);
 982                self.handle_keyboard_layout_change();
 983            }
 984            Event::XkbStateNotify(event) => {
 985                let mut state = self.0.borrow_mut();
 986                let old_layout = state.xkb.serialize_layout(STATE_LAYOUT_EFFECTIVE);
 987                let new_layout = u32::from(event.group);
 988                state.xkb.update_mask(
 989                    event.base_mods.into(),
 990                    event.latched_mods.into(),
 991                    event.locked_mods.into(),
 992                    event.base_group as u32,
 993                    event.latched_group as u32,
 994                    event.locked_group.into(),
 995                );
 996                let modifiers = Modifiers::from_xkb(&state.xkb);
 997                let capslock = Capslock::from_xkb(&state.xkb);
 998                if state.last_modifiers_changed_event == modifiers
 999                    && state.last_capslock_changed_event == capslock
1000                {
1001                    drop(state);
1002                } else {
1003                    let focused_window_id = state.keyboard_focused_window?;
1004                    state.modifiers = modifiers;
1005                    state.last_modifiers_changed_event = modifiers;
1006                    state.capslock = capslock;
1007                    state.last_capslock_changed_event = capslock;
1008                    drop(state);
1009
1010                    let focused_window = self.get_window(focused_window_id)?;
1011                    focused_window.handle_input(PlatformInput::ModifiersChanged(
1012                        ModifiersChangedEvent {
1013                            modifiers,
1014                            capslock,
1015                        },
1016                    ));
1017                }
1018
1019                if new_layout != old_layout {
1020                    self.handle_keyboard_layout_change();
1021                }
1022            }
1023            Event::KeyPress(event) => {
1024                let window = self.get_window(event.event)?;
1025                let mut state = self.0.borrow_mut();
1026
1027                let modifiers = modifiers_from_state(event.state);
1028                state.modifiers = modifiers;
1029                state.pre_key_char_down.take();
1030
1031                // Macros containing modifiers might result in
1032                // the modifiers missing from the event.
1033                // We therefore update the mask from the global state.
1034                update_xkb_mask_from_event_state(&mut state.xkb, event.state);
1035
1036                let keystroke = {
1037                    let code = event.detail.into();
1038                    let mut keystroke = crate::Keystroke::from_xkb(&state.xkb, modifiers, code);
1039                    let keysym = state.xkb.key_get_one_sym(code);
1040
1041                    if keysym.is_modifier_key() {
1042                        return Some(());
1043                    }
1044
1045                    // should be called after key_get_one_sym
1046                    state.xkb.update_key(code, xkbc::KeyDirection::Down);
1047
1048                    if let Some(mut compose_state) = state.compose_state.take() {
1049                        compose_state.feed(keysym);
1050                        match compose_state.status() {
1051                            xkbc::Status::Composed => {
1052                                state.pre_edit_text.take();
1053                                keystroke.key_char = compose_state.utf8();
1054                                if let Some(keysym) = compose_state.keysym() {
1055                                    keystroke.key = xkbc::keysym_get_name(keysym);
1056                                }
1057                            }
1058                            xkbc::Status::Composing => {
1059                                keystroke.key_char = None;
1060                                state.pre_edit_text = compose_state
1061                                    .utf8()
1062                                    .or(crate::Keystroke::underlying_dead_key(keysym));
1063                                let pre_edit =
1064                                    state.pre_edit_text.clone().unwrap_or(String::default());
1065                                drop(state);
1066                                window.handle_ime_preedit(pre_edit);
1067                                state = self.0.borrow_mut();
1068                            }
1069                            xkbc::Status::Cancelled => {
1070                                let pre_edit = state.pre_edit_text.take();
1071                                drop(state);
1072                                if let Some(pre_edit) = pre_edit {
1073                                    window.handle_ime_commit(pre_edit);
1074                                }
1075                                if let Some(current_key) = Keystroke::underlying_dead_key(keysym) {
1076                                    window.handle_ime_preedit(current_key);
1077                                }
1078                                state = self.0.borrow_mut();
1079                                compose_state.feed(keysym);
1080                            }
1081                            _ => {}
1082                        }
1083                        state.compose_state = Some(compose_state);
1084                    }
1085                    keystroke
1086                };
1087                drop(state);
1088                window.handle_input(PlatformInput::KeyDown(crate::KeyDownEvent {
1089                    keystroke,
1090                    is_held: false,
1091                    prefer_character_input: false,
1092                }));
1093            }
1094            Event::KeyRelease(event) => {
1095                let window = self.get_window(event.event)?;
1096                let mut state = self.0.borrow_mut();
1097
1098                let modifiers = modifiers_from_state(event.state);
1099                state.modifiers = modifiers;
1100
1101                // Macros containing modifiers might result in
1102                // the modifiers missing from the event.
1103                // We therefore update the mask from the global state.
1104                update_xkb_mask_from_event_state(&mut state.xkb, event.state);
1105
1106                let keystroke = {
1107                    let code = event.detail.into();
1108                    let keystroke = crate::Keystroke::from_xkb(&state.xkb, modifiers, code);
1109                    let keysym = state.xkb.key_get_one_sym(code);
1110
1111                    if keysym.is_modifier_key() {
1112                        return Some(());
1113                    }
1114
1115                    // should be called after key_get_one_sym
1116                    state.xkb.update_key(code, xkbc::KeyDirection::Up);
1117
1118                    keystroke
1119                };
1120                drop(state);
1121                window.handle_input(PlatformInput::KeyUp(crate::KeyUpEvent { keystroke }));
1122            }
1123            Event::XinputButtonPress(event) => {
1124                let window = self.get_window(event.event)?;
1125                let mut state = self.0.borrow_mut();
1126
1127                let modifiers = modifiers_from_xinput_info(event.mods);
1128                state.modifiers = modifiers;
1129
1130                let position = point(
1131                    px(event.event_x as f32 / u16::MAX as f32 / state.scale_factor),
1132                    px(event.event_y as f32 / u16::MAX as f32 / state.scale_factor),
1133                );
1134
1135                if state.composing && state.ximc.is_some() {
1136                    drop(state);
1137                    self.reset_ime();
1138                    window.handle_ime_unmark();
1139                    state = self.0.borrow_mut();
1140                } else if let Some(text) = state.pre_edit_text.take() {
1141                    if let Some(compose_state) = state.compose_state.as_mut() {
1142                        compose_state.reset();
1143                    }
1144                    drop(state);
1145                    window.handle_ime_commit(text);
1146                    state = self.0.borrow_mut();
1147                }
1148                match button_or_scroll_from_event_detail(event.detail) {
1149                    Some(ButtonOrScroll::Button(button)) => {
1150                        let click_elapsed = state.last_click.elapsed();
1151                        if click_elapsed < DOUBLE_CLICK_INTERVAL
1152                            && state
1153                                .last_mouse_button
1154                                .is_some_and(|prev_button| prev_button == button)
1155                            && is_within_click_distance(state.last_location, position)
1156                        {
1157                            state.current_count += 1;
1158                        } else {
1159                            state.current_count = 1;
1160                        }
1161
1162                        state.last_click = Instant::now();
1163                        state.last_mouse_button = Some(button);
1164                        state.last_location = position;
1165                        let current_count = state.current_count;
1166
1167                        drop(state);
1168                        window.handle_input(PlatformInput::MouseDown(crate::MouseDownEvent {
1169                            button,
1170                            position,
1171                            modifiers,
1172                            click_count: current_count,
1173                            first_mouse: false,
1174                        }));
1175                    }
1176                    Some(ButtonOrScroll::Scroll(direction)) => {
1177                        drop(state);
1178                        // Emulated scroll button presses are sent simultaneously with smooth scrolling XinputMotion events.
1179                        // Since handling those events does the scrolling, they are skipped here.
1180                        if !event
1181                            .flags
1182                            .contains(xinput::PointerEventFlags::POINTER_EMULATED)
1183                        {
1184                            let scroll_delta = match direction {
1185                                ScrollDirection::Up => Point::new(0.0, SCROLL_LINES),
1186                                ScrollDirection::Down => Point::new(0.0, -SCROLL_LINES),
1187                                ScrollDirection::Left => Point::new(SCROLL_LINES, 0.0),
1188                                ScrollDirection::Right => Point::new(-SCROLL_LINES, 0.0),
1189                            };
1190                            window.handle_input(PlatformInput::ScrollWheel(
1191                                make_scroll_wheel_event(position, scroll_delta, modifiers),
1192                            ));
1193                        }
1194                    }
1195                    None => {
1196                        log::error!("Unknown x11 button: {}", event.detail);
1197                    }
1198                }
1199            }
1200            Event::XinputButtonRelease(event) => {
1201                let window = self.get_window(event.event)?;
1202                let mut state = self.0.borrow_mut();
1203                let modifiers = modifiers_from_xinput_info(event.mods);
1204                state.modifiers = modifiers;
1205
1206                let position = point(
1207                    px(event.event_x as f32 / u16::MAX as f32 / state.scale_factor),
1208                    px(event.event_y as f32 / u16::MAX as f32 / state.scale_factor),
1209                );
1210                match button_or_scroll_from_event_detail(event.detail) {
1211                    Some(ButtonOrScroll::Button(button)) => {
1212                        let click_count = state.current_count;
1213                        drop(state);
1214                        window.handle_input(PlatformInput::MouseUp(crate::MouseUpEvent {
1215                            button,
1216                            position,
1217                            modifiers,
1218                            click_count,
1219                        }));
1220                    }
1221                    Some(ButtonOrScroll::Scroll(_)) => {}
1222                    None => {}
1223                }
1224            }
1225            Event::XinputMotion(event) => {
1226                let window = self.get_window(event.event)?;
1227                let mut state = self.0.borrow_mut();
1228                if window.is_blocked() {
1229                    // We want to set the cursor to the default arrow
1230                    // when the window is blocked
1231                    let style = CursorStyle::Arrow;
1232
1233                    let current_style = state
1234                        .cursor_styles
1235                        .get(&window.x_window)
1236                        .unwrap_or(&CursorStyle::Arrow);
1237                    if *current_style != style
1238                        && let Some(cursor) = state.get_cursor_icon(style)
1239                    {
1240                        state.cursor_styles.insert(window.x_window, style);
1241                        check_reply(
1242                            || "Failed to set cursor style",
1243                            state.xcb_connection.change_window_attributes(
1244                                window.x_window,
1245                                &ChangeWindowAttributesAux {
1246                                    cursor: Some(cursor),
1247                                    ..Default::default()
1248                                },
1249                            ),
1250                        )
1251                        .log_err();
1252                        state.xcb_connection.flush().log_err();
1253                    };
1254                }
1255                let pressed_button = pressed_button_from_mask(event.button_mask[0]);
1256                let position = point(
1257                    px(event.event_x as f32 / u16::MAX as f32 / state.scale_factor),
1258                    px(event.event_y as f32 / u16::MAX as f32 / state.scale_factor),
1259                );
1260                let modifiers = modifiers_from_xinput_info(event.mods);
1261                state.modifiers = modifiers;
1262                drop(state);
1263
1264                if event.valuator_mask[0] & 3 != 0 {
1265                    window.handle_input(PlatformInput::MouseMove(crate::MouseMoveEvent {
1266                        position,
1267                        pressed_button,
1268                        modifiers,
1269                    }));
1270                }
1271
1272                state = self.0.borrow_mut();
1273                if let Some(mut pointer) = state.pointer_device_states.get_mut(&event.sourceid) {
1274                    let scroll_delta = get_scroll_delta_and_update_state(pointer, &event);
1275                    drop(state);
1276                    if let Some(scroll_delta) = scroll_delta {
1277                        window.handle_input(PlatformInput::ScrollWheel(make_scroll_wheel_event(
1278                            position,
1279                            scroll_delta,
1280                            modifiers,
1281                        )));
1282                    }
1283                }
1284            }
1285            Event::XinputEnter(event) if event.mode == xinput::NotifyMode::NORMAL => {
1286                let window = self.get_window(event.event)?;
1287                window.set_hovered(true);
1288                let mut state = self.0.borrow_mut();
1289                state.mouse_focused_window = Some(event.event);
1290            }
1291            Event::XinputLeave(event) if event.mode == xinput::NotifyMode::NORMAL => {
1292                let mut state = self.0.borrow_mut();
1293
1294                // 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)
1295                reset_all_pointer_device_scroll_positions(&mut state.pointer_device_states);
1296                state.mouse_focused_window = None;
1297                let pressed_button = pressed_button_from_mask(event.buttons[0]);
1298                let position = point(
1299                    px(event.event_x as f32 / u16::MAX as f32 / state.scale_factor),
1300                    px(event.event_y as f32 / u16::MAX as f32 / state.scale_factor),
1301                );
1302                let modifiers = modifiers_from_xinput_info(event.mods);
1303                state.modifiers = modifiers;
1304                drop(state);
1305
1306                let window = self.get_window(event.event)?;
1307                window.handle_input(PlatformInput::MouseExited(crate::MouseExitEvent {
1308                    pressed_button,
1309                    position,
1310                    modifiers,
1311                }));
1312                window.set_hovered(false);
1313            }
1314            Event::XinputHierarchy(event) => {
1315                let mut state = self.0.borrow_mut();
1316                // Temporarily use `state.pointer_device_states` to only store pointers that still have valid scroll values.
1317                // Any change to a device invalidates its scroll values.
1318                for info in event.infos {
1319                    if is_pointer_device(info.type_) {
1320                        state.pointer_device_states.remove(&info.deviceid);
1321                    }
1322                }
1323                if let Some(pointer_device_states) = current_pointer_device_states(
1324                    &state.xcb_connection,
1325                    &state.pointer_device_states,
1326                ) {
1327                    state.pointer_device_states = pointer_device_states;
1328                }
1329            }
1330            Event::XinputDeviceChanged(event) => {
1331                let mut state = self.0.borrow_mut();
1332                if let Some(mut pointer) = state.pointer_device_states.get_mut(&event.sourceid) {
1333                    reset_pointer_device_scroll_positions(pointer);
1334                }
1335            }
1336            _ => {}
1337        };
1338
1339        Some(())
1340    }
1341
1342    fn handle_xim_callback_event(&self, event: XimCallbackEvent) {
1343        match event {
1344            XimCallbackEvent::XimXEvent(event) => {
1345                self.handle_event(event);
1346            }
1347            XimCallbackEvent::XimCommitEvent(window, text) => {
1348                self.xim_handle_commit(window, text);
1349            }
1350            XimCallbackEvent::XimPreeditEvent(window, text) => {
1351                self.xim_handle_preedit(window, text);
1352            }
1353        };
1354    }
1355
1356    fn xim_handle_event(&self, event: Event) -> Option<()> {
1357        match event {
1358            Event::KeyPress(event) | Event::KeyRelease(event) => {
1359                let mut state = self.0.borrow_mut();
1360                state.pre_key_char_down = Some(Keystroke::from_xkb(
1361                    &state.xkb,
1362                    state.modifiers,
1363                    event.detail.into(),
1364                ));
1365                let (mut ximc, mut xim_handler) = state.take_xim()?;
1366                drop(state);
1367                xim_handler.window = event.event;
1368                ximc.forward_event(
1369                    xim_handler.im_id,
1370                    xim_handler.ic_id,
1371                    xim::ForwardEventFlag::empty(),
1372                    &event,
1373                )
1374                .context("X11: Failed to forward XIM event")
1375                .log_err();
1376                let mut state = self.0.borrow_mut();
1377                state.restore_xim(ximc, xim_handler);
1378                drop(state);
1379            }
1380            event => {
1381                self.handle_event(event);
1382            }
1383        }
1384        Some(())
1385    }
1386
1387    fn xim_handle_commit(&self, window: xproto::Window, text: String) -> Option<()> {
1388        let Some(window) = self.get_window(window) else {
1389            log::error!("bug: Failed to get window for XIM commit");
1390            return None;
1391        };
1392        let mut state = self.0.borrow_mut();
1393        state.composing = false;
1394        drop(state);
1395        window.handle_ime_commit(text);
1396        Some(())
1397    }
1398
1399    fn xim_handle_preedit(&self, window: xproto::Window, text: String) -> Option<()> {
1400        let Some(window) = self.get_window(window) else {
1401            log::error!("bug: Failed to get window for XIM preedit");
1402            return None;
1403        };
1404
1405        let mut state = self.0.borrow_mut();
1406        let (mut ximc, mut xim_handler) = state.take_xim()?;
1407        state.composing = !text.is_empty();
1408        drop(state);
1409        window.handle_ime_preedit(text);
1410
1411        if let Some(scaled_area) = window.get_ime_area() {
1412            let ic_attributes = ximc
1413                .build_ic_attributes()
1414                .push(
1415                    xim::AttributeName::InputStyle,
1416                    xim::InputStyle::PREEDIT_CALLBACKS,
1417                )
1418                .push(xim::AttributeName::ClientWindow, xim_handler.window)
1419                .push(xim::AttributeName::FocusWindow, xim_handler.window)
1420                .nested_list(xim::AttributeName::PreeditAttributes, |b| {
1421                    b.push(
1422                        xim::AttributeName::SpotLocation,
1423                        xim::Point {
1424                            x: u32::from(scaled_area.origin.x + scaled_area.size.width) as i16,
1425                            y: u32::from(scaled_area.origin.y + scaled_area.size.height) as i16,
1426                        },
1427                    );
1428                })
1429                .build();
1430            ximc.set_ic_values(xim_handler.im_id, xim_handler.ic_id, ic_attributes)
1431                .ok();
1432        }
1433        let mut state = self.0.borrow_mut();
1434        state.restore_xim(ximc, xim_handler);
1435        drop(state);
1436        Some(())
1437    }
1438
1439    fn handle_keyboard_layout_change(&self) {
1440        let mut state = self.0.borrow_mut();
1441        let layout_idx = state.xkb.serialize_layout(STATE_LAYOUT_EFFECTIVE);
1442        let keymap = state.xkb.get_keymap();
1443        let layout_name = keymap.layout_get_name(layout_idx);
1444        if layout_name != state.keyboard_layout.name() {
1445            state.keyboard_layout = LinuxKeyboardLayout::new(layout_name.to_string().into());
1446            if let Some(mut callback) = state.common.callbacks.keyboard_layout_change.take() {
1447                drop(state);
1448                callback();
1449                state = self.0.borrow_mut();
1450                state.common.callbacks.keyboard_layout_change = Some(callback);
1451            }
1452        }
1453    }
1454}
1455
1456impl LinuxClient for X11Client {
1457    fn compositor_name(&self) -> &'static str {
1458        "X11"
1459    }
1460
1461    fn with_common<R>(&self, f: impl FnOnce(&mut LinuxCommon) -> R) -> R {
1462        f(&mut self.0.borrow_mut().common)
1463    }
1464
1465    fn keyboard_layout(&self) -> Box<dyn PlatformKeyboardLayout> {
1466        let state = self.0.borrow();
1467        Box::new(state.keyboard_layout.clone())
1468    }
1469
1470    fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
1471        let state = self.0.borrow();
1472        let setup = state.xcb_connection.setup();
1473        setup
1474            .roots
1475            .iter()
1476            .enumerate()
1477            .filter_map(|(root_id, _)| {
1478                Some(Rc::new(
1479                    X11Display::new(&state.xcb_connection, state.scale_factor, root_id).ok()?,
1480                ) as Rc<dyn PlatformDisplay>)
1481            })
1482            .collect()
1483    }
1484
1485    fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
1486        let state = self.0.borrow();
1487        X11Display::new(
1488            &state.xcb_connection,
1489            state.scale_factor,
1490            state.x_root_index,
1491        )
1492        .log_err()
1493        .map(|display| Rc::new(display) as Rc<dyn PlatformDisplay>)
1494    }
1495
1496    fn display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>> {
1497        let state = self.0.borrow();
1498
1499        Some(Rc::new(
1500            X11Display::new(&state.xcb_connection, state.scale_factor, id.0 as usize).ok()?,
1501        ))
1502    }
1503
1504    #[cfg(feature = "screen-capture")]
1505    fn is_screen_capture_supported(&self) -> bool {
1506        true
1507    }
1508
1509    #[cfg(feature = "screen-capture")]
1510    fn screen_capture_sources(
1511        &self,
1512    ) -> futures::channel::oneshot::Receiver<anyhow::Result<Vec<Rc<dyn crate::ScreenCaptureSource>>>>
1513    {
1514        crate::platform::scap_screen_capture::scap_screen_sources(
1515            &self.0.borrow().common.foreground_executor,
1516        )
1517    }
1518
1519    fn open_window(
1520        &self,
1521        handle: AnyWindowHandle,
1522        params: WindowParams,
1523    ) -> anyhow::Result<Box<dyn PlatformWindow>> {
1524        let mut state = self.0.borrow_mut();
1525        let parent_window = state
1526            .keyboard_focused_window
1527            .and_then(|focused_window| state.windows.get(&focused_window))
1528            .map(|w| w.window.clone());
1529        let x_window = state
1530            .xcb_connection
1531            .generate_id()
1532            .context("X11: Failed to generate window ID")?;
1533
1534        let window = X11Window::new(
1535            handle,
1536            X11ClientStatePtr(Rc::downgrade(&self.0)),
1537            state.common.foreground_executor.clone(),
1538            &state.gpu_context,
1539            params,
1540            &state.xcb_connection,
1541            state.client_side_decorations_supported,
1542            state.x_root_index,
1543            x_window,
1544            &state.atoms,
1545            state.scale_factor,
1546            state.common.appearance,
1547            parent_window,
1548        )?;
1549        check_reply(
1550            || "Failed to set XdndAware property",
1551            state.xcb_connection.change_property32(
1552                xproto::PropMode::REPLACE,
1553                x_window,
1554                state.atoms.XdndAware,
1555                state.atoms.XA_ATOM,
1556                &[5],
1557            ),
1558        )
1559        .log_err();
1560        xcb_flush(&state.xcb_connection);
1561
1562        let window_ref = WindowRef {
1563            window: window.0.clone(),
1564            refresh_state: None,
1565            expose_event_received: false,
1566            last_visibility: Visibility::UNOBSCURED,
1567            is_mapped: false,
1568        };
1569
1570        state.windows.insert(x_window, window_ref);
1571        Ok(Box::new(window))
1572    }
1573
1574    fn set_cursor_style(&self, style: CursorStyle) {
1575        let mut state = self.0.borrow_mut();
1576        let Some(focused_window) = state.mouse_focused_window else {
1577            return;
1578        };
1579        let current_style = state
1580            .cursor_styles
1581            .get(&focused_window)
1582            .unwrap_or(&CursorStyle::Arrow);
1583
1584        let window = state
1585            .mouse_focused_window
1586            .and_then(|w| state.windows.get(&w));
1587
1588        let should_change = *current_style != style
1589            && (window.is_none() || window.is_some_and(|w| !w.is_blocked()));
1590
1591        if !should_change {
1592            return;
1593        }
1594
1595        let Some(cursor) = state.get_cursor_icon(style) else {
1596            return;
1597        };
1598
1599        state.cursor_styles.insert(focused_window, style);
1600        check_reply(
1601            || "Failed to set cursor style",
1602            state.xcb_connection.change_window_attributes(
1603                focused_window,
1604                &ChangeWindowAttributesAux {
1605                    cursor: Some(cursor),
1606                    ..Default::default()
1607                },
1608            ),
1609        )
1610        .log_err();
1611        state.xcb_connection.flush().log_err();
1612    }
1613
1614    fn open_uri(&self, uri: &str) {
1615        #[cfg(any(feature = "wayland", feature = "x11"))]
1616        open_uri_internal(self.background_executor(), uri, None);
1617    }
1618
1619    fn reveal_path(&self, path: PathBuf) {
1620        #[cfg(any(feature = "x11", feature = "wayland"))]
1621        reveal_path_internal(self.background_executor(), path, None);
1622    }
1623
1624    fn write_to_primary(&self, item: crate::ClipboardItem) {
1625        let state = self.0.borrow_mut();
1626        state
1627            .clipboard
1628            .set_text(
1629                std::borrow::Cow::Owned(item.text().unwrap_or_default()),
1630                clipboard::ClipboardKind::Primary,
1631                clipboard::WaitConfig::None,
1632            )
1633            .context("X11 Failed to write to clipboard (primary)")
1634            .log_with_level(log::Level::Debug);
1635    }
1636
1637    fn write_to_clipboard(&self, item: crate::ClipboardItem) {
1638        let mut state = self.0.borrow_mut();
1639        state
1640            .clipboard
1641            .set_text(
1642                std::borrow::Cow::Owned(item.text().unwrap_or_default()),
1643                clipboard::ClipboardKind::Clipboard,
1644                clipboard::WaitConfig::None,
1645            )
1646            .context("X11: Failed to write to clipboard (clipboard)")
1647            .log_with_level(log::Level::Debug);
1648        state.clipboard_item.replace(item);
1649    }
1650
1651    fn read_from_primary(&self) -> Option<crate::ClipboardItem> {
1652        let state = self.0.borrow_mut();
1653        state
1654            .clipboard
1655            .get_any(clipboard::ClipboardKind::Primary)
1656            .context("X11: Failed to read from clipboard (primary)")
1657            .log_with_level(log::Level::Debug)
1658    }
1659
1660    fn read_from_clipboard(&self) -> Option<crate::ClipboardItem> {
1661        let state = self.0.borrow_mut();
1662        // if the last copy was from this app, return our cached item
1663        // which has metadata attached.
1664        if state
1665            .clipboard
1666            .is_owner(clipboard::ClipboardKind::Clipboard)
1667        {
1668            return state.clipboard_item.clone();
1669        }
1670        state
1671            .clipboard
1672            .get_any(clipboard::ClipboardKind::Clipboard)
1673            .context("X11: Failed to read from clipboard (clipboard)")
1674            .log_with_level(log::Level::Debug)
1675    }
1676
1677    fn run(&self) {
1678        let Some(mut event_loop) = self
1679            .0
1680            .borrow_mut()
1681            .event_loop
1682            .take()
1683            .context("X11Client::run called but it's already running")
1684            .log_err()
1685        else {
1686            return;
1687        };
1688
1689        event_loop.run(None, &mut self.clone(), |_| {}).log_err();
1690    }
1691
1692    fn active_window(&self) -> Option<AnyWindowHandle> {
1693        let state = self.0.borrow();
1694        state.keyboard_focused_window.and_then(|focused_window| {
1695            state
1696                .windows
1697                .get(&focused_window)
1698                .map(|window| window.handle())
1699        })
1700    }
1701
1702    fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
1703        let state = self.0.borrow();
1704        let root = state.xcb_connection.setup().roots[state.x_root_index].root;
1705
1706        let reply = state
1707            .xcb_connection
1708            .get_property(
1709                false,
1710                root,
1711                state.atoms._NET_CLIENT_LIST_STACKING,
1712                xproto::AtomEnum::WINDOW,
1713                0,
1714                u32::MAX,
1715            )
1716            .ok()?
1717            .reply()
1718            .ok()?;
1719
1720        let window_ids = reply
1721            .value
1722            .chunks_exact(4)
1723            .filter_map(|chunk| chunk.try_into().ok().map(u32::from_ne_bytes))
1724            .collect::<Vec<xproto::Window>>();
1725
1726        let mut handles = Vec::new();
1727
1728        // We need to reverse, since _NET_CLIENT_LIST_STACKING has
1729        // a back-to-front order.
1730        // See: https://specifications.freedesktop.org/wm-spec/1.3/ar01s03.html
1731        for window_ref in window_ids
1732            .iter()
1733            .rev()
1734            .filter_map(|&win| state.windows.get(&win))
1735        {
1736            if !window_ref.window.state.borrow().destroyed {
1737                handles.push(window_ref.handle());
1738            }
1739        }
1740
1741        Some(handles)
1742    }
1743
1744    fn window_identifier(&self) -> impl Future<Output = Option<WindowIdentifier>> + Send + 'static {
1745        let state = self.0.borrow();
1746        state
1747            .keyboard_focused_window
1748            .and_then(|focused_window| state.windows.get(&focused_window))
1749            .map(|window| window.window.x_window as u64)
1750            .map(|x_window| std::future::ready(Some(WindowIdentifier::from_xid(x_window))))
1751            .unwrap_or(std::future::ready(None))
1752    }
1753}
1754
1755impl X11ClientState {
1756    fn has_xim(&self) -> bool {
1757        self.ximc.is_some() && self.xim_handler.is_some()
1758    }
1759
1760    fn take_xim(&mut self) -> Option<(X11rbClient<Rc<XCBConnection>>, XimHandler)> {
1761        let ximc = self
1762            .ximc
1763            .take()
1764            .ok_or(anyhow!("bug: XIM connection not set"))
1765            .log_err()?;
1766        if let Some(xim_handler) = self.xim_handler.take() {
1767            Some((ximc, xim_handler))
1768        } else {
1769            self.ximc = Some(ximc);
1770            log::error!("bug: XIM handler not set");
1771            None
1772        }
1773    }
1774
1775    fn restore_xim(&mut self, ximc: X11rbClient<Rc<XCBConnection>>, xim_handler: XimHandler) {
1776        self.ximc = Some(ximc);
1777        self.xim_handler = Some(xim_handler);
1778    }
1779
1780    fn update_refresh_loop(&mut self, x_window: xproto::Window) {
1781        let Some(window_ref) = self.windows.get_mut(&x_window) else {
1782            return;
1783        };
1784        let is_visible = window_ref.is_mapped
1785            && !matches!(window_ref.last_visibility, Visibility::FULLY_OBSCURED);
1786        match (is_visible, window_ref.refresh_state.take()) {
1787            (false, refresh_state @ Some(RefreshState::Hidden { .. }))
1788            | (false, refresh_state @ None)
1789            | (true, refresh_state @ Some(RefreshState::PeriodicRefresh { .. })) => {
1790                window_ref.refresh_state = refresh_state;
1791            }
1792            (
1793                false,
1794                Some(RefreshState::PeriodicRefresh {
1795                    refresh_rate,
1796                    event_loop_token,
1797                }),
1798            ) => {
1799                self.loop_handle.remove(event_loop_token);
1800                window_ref.refresh_state = Some(RefreshState::Hidden { refresh_rate });
1801            }
1802            (true, Some(RefreshState::Hidden { refresh_rate })) => {
1803                let event_loop_token = self.start_refresh_loop(x_window, refresh_rate);
1804                let Some(window_ref) = self.windows.get_mut(&x_window) else {
1805                    return;
1806                };
1807                window_ref.refresh_state = Some(RefreshState::PeriodicRefresh {
1808                    refresh_rate,
1809                    event_loop_token,
1810                });
1811            }
1812            (true, None) => {
1813                let Some(screen_resources) = get_reply(
1814                    || "Failed to get screen resources",
1815                    self.xcb_connection
1816                        .randr_get_screen_resources_current(x_window),
1817                )
1818                .log_err() else {
1819                    return;
1820                };
1821
1822                // Ideally this would be re-queried when the window changes screens, but there
1823                // doesn't seem to be an efficient / straightforward way to do this. Should also be
1824                // updated when screen configurations change.
1825                let mode_info = screen_resources.crtcs.iter().find_map(|crtc| {
1826                    let crtc_info = self
1827                        .xcb_connection
1828                        .randr_get_crtc_info(*crtc, x11rb::CURRENT_TIME)
1829                        .ok()?
1830                        .reply()
1831                        .ok()?;
1832
1833                    screen_resources
1834                        .modes
1835                        .iter()
1836                        .find(|m| m.id == crtc_info.mode)
1837                });
1838                let refresh_rate = match mode_info {
1839                    Some(mode_info) => mode_refresh_rate(mode_info),
1840                    None => {
1841                        log::error!(
1842                            "Failed to get screen mode info from xrandr, \
1843                            defaulting to 60hz refresh rate."
1844                        );
1845                        Duration::from_micros(1_000_000 / 60)
1846                    }
1847                };
1848
1849                let event_loop_token = self.start_refresh_loop(x_window, refresh_rate);
1850                let Some(window_ref) = self.windows.get_mut(&x_window) else {
1851                    return;
1852                };
1853                window_ref.refresh_state = Some(RefreshState::PeriodicRefresh {
1854                    refresh_rate,
1855                    event_loop_token,
1856                });
1857            }
1858        }
1859    }
1860
1861    #[must_use]
1862    fn start_refresh_loop(
1863        &self,
1864        x_window: xproto::Window,
1865        refresh_rate: Duration,
1866    ) -> RegistrationToken {
1867        self.loop_handle
1868            .insert_source(calloop::timer::Timer::immediate(), {
1869                move |mut instant, (), client| {
1870                    let xcb_connection = {
1871                        let mut state = client.0.borrow_mut();
1872                        let xcb_connection = state.xcb_connection.clone();
1873                        if let Some(window) = state.windows.get_mut(&x_window) {
1874                            let expose_event_received = window.expose_event_received;
1875                            window.expose_event_received = false;
1876                            let window = window.window.clone();
1877                            drop(state);
1878                            window.refresh(RequestFrameOptions {
1879                                require_presentation: expose_event_received,
1880                                force_render: false,
1881                            });
1882                        }
1883                        xcb_connection
1884                    };
1885                    client.process_x11_events(&xcb_connection).log_err();
1886
1887                    // Take into account that some frames have been skipped
1888                    let now = Instant::now();
1889                    while instant < now {
1890                        instant += refresh_rate;
1891                    }
1892                    calloop::timer::TimeoutAction::ToInstant(instant)
1893                }
1894            })
1895            .expect("Failed to initialize window refresh timer")
1896    }
1897
1898    fn get_cursor_icon(&mut self, style: CursorStyle) -> Option<xproto::Cursor> {
1899        if let Some(cursor) = self.cursor_cache.get(&style) {
1900            return *cursor;
1901        }
1902
1903        let mut result;
1904        match style {
1905            CursorStyle::None => match create_invisible_cursor(&self.xcb_connection) {
1906                Ok(loaded_cursor) => result = Ok(loaded_cursor),
1907                Err(err) => result = Err(err.context("X11: error while creating invisible cursor")),
1908            },
1909            _ => 'outer: {
1910                let mut errors = String::new();
1911                let cursor_icon_names = style.to_icon_names();
1912                for cursor_icon_name in cursor_icon_names {
1913                    match self
1914                        .cursor_handle
1915                        .load_cursor(&self.xcb_connection, cursor_icon_name)
1916                    {
1917                        Ok(loaded_cursor) => {
1918                            if loaded_cursor != x11rb::NONE {
1919                                result = Ok(loaded_cursor);
1920                                break 'outer;
1921                            }
1922                        }
1923                        Err(err) => {
1924                            errors.push_str(&err.to_string());
1925                            errors.push('\n');
1926                        }
1927                    }
1928                }
1929                if errors.is_empty() {
1930                    result = Err(anyhow!(
1931                        "errors while loading cursor icons {:?}:\n{}",
1932                        cursor_icon_names,
1933                        errors
1934                    ));
1935                } else {
1936                    result = Err(anyhow!("did not find cursor icons {:?}", cursor_icon_names));
1937                }
1938            }
1939        };
1940
1941        let cursor = match result {
1942            Ok(cursor) => Some(cursor),
1943            Err(err) => {
1944                match self
1945                    .cursor_handle
1946                    .load_cursor(&self.xcb_connection, DEFAULT_CURSOR_ICON_NAME)
1947                {
1948                    Ok(default) => {
1949                        log_cursor_icon_warning(err.context(format!(
1950                            "X11: error loading cursor icon, falling back on default icon '{}'",
1951                            DEFAULT_CURSOR_ICON_NAME
1952                        )));
1953                        Some(default)
1954                    }
1955                    Err(default_err) => {
1956                        log_cursor_icon_warning(err.context(default_err).context(format!(
1957                            "X11: error loading default cursor fallback '{}'",
1958                            DEFAULT_CURSOR_ICON_NAME
1959                        )));
1960                        None
1961                    }
1962                }
1963            }
1964        };
1965
1966        self.cursor_cache.insert(style, cursor);
1967        cursor
1968    }
1969}
1970
1971// Adapted from:
1972// https://docs.rs/winit/0.29.11/src/winit/platform_impl/linux/x11/monitor.rs.html#103-111
1973pub fn mode_refresh_rate(mode: &randr::ModeInfo) -> Duration {
1974    if mode.dot_clock == 0 || mode.htotal == 0 || mode.vtotal == 0 {
1975        return Duration::from_millis(16);
1976    }
1977
1978    let millihertz = mode.dot_clock as u64 * 1_000 / (mode.htotal as u64 * mode.vtotal as u64);
1979    let micros = 1_000_000_000 / millihertz;
1980    log::info!("Refreshing every {}ms", micros / 1_000);
1981    Duration::from_micros(micros)
1982}
1983
1984fn fp3232_to_f32(value: xinput::Fp3232) -> f32 {
1985    value.integral as f32 + value.frac as f32 / u32::MAX as f32
1986}
1987
1988fn check_compositor_present(xcb_connection: &XCBConnection, root: u32) -> bool {
1989    // Method 1: Check for _NET_WM_CM_S{root}
1990    let atom_name = format!("_NET_WM_CM_S{}", root);
1991    let atom1 = get_reply(
1992        || format!("Failed to intern {atom_name}"),
1993        xcb_connection.intern_atom(false, atom_name.as_bytes()),
1994    );
1995    let method1 = match atom1.log_with_level(Level::Debug) {
1996        Some(reply) if reply.atom != x11rb::NONE => {
1997            let atom = reply.atom;
1998            get_reply(
1999                || format!("Failed to get {atom_name} owner"),
2000                xcb_connection.get_selection_owner(atom),
2001            )
2002            .map(|reply| reply.owner != 0)
2003            .log_with_level(Level::Debug)
2004            .unwrap_or(false)
2005        }
2006        _ => false,
2007    };
2008
2009    // Method 2: Check for _NET_WM_CM_OWNER
2010    let atom_name = "_NET_WM_CM_OWNER";
2011    let atom2 = get_reply(
2012        || format!("Failed to intern {atom_name}"),
2013        xcb_connection.intern_atom(false, atom_name.as_bytes()),
2014    );
2015    let method2 = match atom2.log_with_level(Level::Debug) {
2016        Some(reply) if reply.atom != x11rb::NONE => {
2017            let atom = reply.atom;
2018            get_reply(
2019                || format!("Failed to get {atom_name}"),
2020                xcb_connection.get_property(false, root, atom, xproto::AtomEnum::WINDOW, 0, 1),
2021            )
2022            .map(|reply| reply.value_len > 0)
2023            .unwrap_or(false)
2024        }
2025        _ => return false,
2026    };
2027
2028    // Method 3: Check for _NET_SUPPORTING_WM_CHECK
2029    let atom_name = "_NET_SUPPORTING_WM_CHECK";
2030    let atom3 = get_reply(
2031        || format!("Failed to intern {atom_name}"),
2032        xcb_connection.intern_atom(false, atom_name.as_bytes()),
2033    );
2034    let method3 = match atom3.log_with_level(Level::Debug) {
2035        Some(reply) if reply.atom != x11rb::NONE => {
2036            let atom = reply.atom;
2037            get_reply(
2038                || format!("Failed to get {atom_name}"),
2039                xcb_connection.get_property(false, root, atom, xproto::AtomEnum::WINDOW, 0, 1),
2040            )
2041            .map(|reply| reply.value_len > 0)
2042            .unwrap_or(false)
2043        }
2044        _ => return false,
2045    };
2046
2047    log::debug!(
2048        "Compositor detection: _NET_WM_CM_S?={}, _NET_WM_CM_OWNER={}, _NET_SUPPORTING_WM_CHECK={}",
2049        method1,
2050        method2,
2051        method3
2052    );
2053
2054    method1 || method2 || method3
2055}
2056
2057fn check_gtk_frame_extents_supported(
2058    xcb_connection: &XCBConnection,
2059    atoms: &XcbAtoms,
2060    root: xproto::Window,
2061) -> bool {
2062    let Some(supported_atoms) = get_reply(
2063        || "Failed to get _NET_SUPPORTED",
2064        xcb_connection.get_property(
2065            false,
2066            root,
2067            atoms._NET_SUPPORTED,
2068            xproto::AtomEnum::ATOM,
2069            0,
2070            1024,
2071        ),
2072    )
2073    .log_with_level(Level::Debug) else {
2074        return false;
2075    };
2076
2077    let supported_atom_ids: Vec<u32> = supported_atoms
2078        .value
2079        .chunks_exact(4)
2080        .filter_map(|chunk| chunk.try_into().ok().map(u32::from_ne_bytes))
2081        .collect();
2082
2083    supported_atom_ids.contains(&atoms._GTK_FRAME_EXTENTS)
2084}
2085
2086fn xdnd_is_atom_supported(atom: u32, atoms: &XcbAtoms) -> bool {
2087    atom == atoms.TEXT
2088        || atom == atoms.STRING
2089        || atom == atoms.UTF8_STRING
2090        || atom == atoms.TEXT_PLAIN
2091        || atom == atoms.TEXT_PLAIN_UTF8
2092        || atom == atoms.TextUriList
2093}
2094
2095fn xdnd_get_supported_atom(
2096    xcb_connection: &XCBConnection,
2097    supported_atoms: &XcbAtoms,
2098    target: xproto::Window,
2099) -> u32 {
2100    if let Some(reply) = get_reply(
2101        || "Failed to get XDnD supported atoms",
2102        xcb_connection.get_property(
2103            false,
2104            target,
2105            supported_atoms.XdndTypeList,
2106            AtomEnum::ANY,
2107            0,
2108            1024,
2109        ),
2110    )
2111    .log_with_level(Level::Warn)
2112        && let Some(atoms) = reply.value32()
2113    {
2114        for atom in atoms {
2115            if xdnd_is_atom_supported(atom, supported_atoms) {
2116                return atom;
2117            }
2118        }
2119    }
2120    0
2121}
2122
2123fn xdnd_send_finished(
2124    xcb_connection: &XCBConnection,
2125    atoms: &XcbAtoms,
2126    source: xproto::Window,
2127    target: xproto::Window,
2128) {
2129    let message = ClientMessageEvent {
2130        format: 32,
2131        window: target,
2132        type_: atoms.XdndFinished,
2133        data: ClientMessageData::from([source, 1, atoms.XdndActionCopy, 0, 0]),
2134        sequence: 0,
2135        response_type: xproto::CLIENT_MESSAGE_EVENT,
2136    };
2137    check_reply(
2138        || "Failed to send XDnD finished event",
2139        xcb_connection.send_event(false, target, EventMask::default(), message),
2140    )
2141    .log_err();
2142    xcb_connection.flush().log_err();
2143}
2144
2145fn xdnd_send_status(
2146    xcb_connection: &XCBConnection,
2147    atoms: &XcbAtoms,
2148    source: xproto::Window,
2149    target: xproto::Window,
2150    action: u32,
2151) {
2152    let message = ClientMessageEvent {
2153        format: 32,
2154        window: target,
2155        type_: atoms.XdndStatus,
2156        data: ClientMessageData::from([source, 1, 0, 0, action]),
2157        sequence: 0,
2158        response_type: xproto::CLIENT_MESSAGE_EVENT,
2159    };
2160    check_reply(
2161        || "Failed to send XDnD status event",
2162        xcb_connection.send_event(false, target, EventMask::default(), message),
2163    )
2164    .log_err();
2165    xcb_connection.flush().log_err();
2166}
2167
2168/// Recomputes `pointer_device_states` by querying all pointer devices.
2169/// When a device is present in `scroll_values_to_preserve`, its value for `ScrollAxisState.scroll_value` is used.
2170fn current_pointer_device_states(
2171    xcb_connection: &XCBConnection,
2172    scroll_values_to_preserve: &BTreeMap<xinput::DeviceId, PointerDeviceState>,
2173) -> Option<BTreeMap<xinput::DeviceId, PointerDeviceState>> {
2174    let devices_query_result = get_reply(
2175        || "Failed to query XInput devices",
2176        xcb_connection.xinput_xi_query_device(XINPUT_ALL_DEVICES),
2177    )
2178    .log_err()?;
2179
2180    let mut pointer_device_states = BTreeMap::new();
2181    pointer_device_states.extend(
2182        devices_query_result
2183            .infos
2184            .iter()
2185            .filter(|info| is_pointer_device(info.type_))
2186            .filter_map(|info| {
2187                let scroll_data = info
2188                    .classes
2189                    .iter()
2190                    .filter_map(|class| class.data.as_scroll())
2191                    .copied()
2192                    .rev()
2193                    .collect::<Vec<_>>();
2194                let old_state = scroll_values_to_preserve.get(&info.deviceid);
2195                let old_horizontal = old_state.map(|state| &state.horizontal);
2196                let old_vertical = old_state.map(|state| &state.vertical);
2197                let horizontal = scroll_data
2198                    .iter()
2199                    .find(|data| data.scroll_type == xinput::ScrollType::HORIZONTAL)
2200                    .map(|data| scroll_data_to_axis_state(data, old_horizontal));
2201                let vertical = scroll_data
2202                    .iter()
2203                    .find(|data| data.scroll_type == xinput::ScrollType::VERTICAL)
2204                    .map(|data| scroll_data_to_axis_state(data, old_vertical));
2205                if horizontal.is_none() && vertical.is_none() {
2206                    None
2207                } else {
2208                    Some((
2209                        info.deviceid,
2210                        PointerDeviceState {
2211                            horizontal: horizontal.unwrap_or_else(Default::default),
2212                            vertical: vertical.unwrap_or_else(Default::default),
2213                        },
2214                    ))
2215                }
2216            }),
2217    );
2218    if pointer_device_states.is_empty() {
2219        log::error!("Found no xinput mouse pointers.");
2220    }
2221    Some(pointer_device_states)
2222}
2223
2224/// Returns true if the device is a pointer device. Does not include pointer device groups.
2225fn is_pointer_device(type_: xinput::DeviceType) -> bool {
2226    type_ == xinput::DeviceType::SLAVE_POINTER
2227}
2228
2229fn scroll_data_to_axis_state(
2230    data: &xinput::DeviceClassDataScroll,
2231    old_axis_state_with_valid_scroll_value: Option<&ScrollAxisState>,
2232) -> ScrollAxisState {
2233    ScrollAxisState {
2234        valuator_number: Some(data.number),
2235        multiplier: SCROLL_LINES / fp3232_to_f32(data.increment),
2236        scroll_value: old_axis_state_with_valid_scroll_value.and_then(|state| state.scroll_value),
2237    }
2238}
2239
2240fn reset_all_pointer_device_scroll_positions(
2241    pointer_device_states: &mut BTreeMap<xinput::DeviceId, PointerDeviceState>,
2242) {
2243    pointer_device_states
2244        .iter_mut()
2245        .for_each(|(_, device_state)| reset_pointer_device_scroll_positions(device_state));
2246}
2247
2248fn reset_pointer_device_scroll_positions(pointer: &mut PointerDeviceState) {
2249    pointer.horizontal.scroll_value = None;
2250    pointer.vertical.scroll_value = None;
2251}
2252
2253/// Returns the scroll delta for a smooth scrolling motion event, or `None` if no scroll data is present.
2254fn get_scroll_delta_and_update_state(
2255    pointer: &mut PointerDeviceState,
2256    event: &xinput::MotionEvent,
2257) -> Option<Point<f32>> {
2258    let delta_x = get_axis_scroll_delta_and_update_state(event, &mut pointer.horizontal);
2259    let delta_y = get_axis_scroll_delta_and_update_state(event, &mut pointer.vertical);
2260    if delta_x.is_some() || delta_y.is_some() {
2261        Some(Point::new(delta_x.unwrap_or(0.0), delta_y.unwrap_or(0.0)))
2262    } else {
2263        None
2264    }
2265}
2266
2267fn get_axis_scroll_delta_and_update_state(
2268    event: &xinput::MotionEvent,
2269    axis: &mut ScrollAxisState,
2270) -> Option<f32> {
2271    let axis_index = get_valuator_axis_index(&event.valuator_mask, axis.valuator_number?)?;
2272    if let Some(axis_value) = event.axisvalues.get(axis_index) {
2273        let new_scroll = fp3232_to_f32(*axis_value);
2274        let delta_scroll = axis
2275            .scroll_value
2276            .map(|old_scroll| (old_scroll - new_scroll) * axis.multiplier);
2277        axis.scroll_value = Some(new_scroll);
2278        delta_scroll
2279    } else {
2280        log::error!("Encountered invalid XInput valuator_mask, scrolling may not work properly.");
2281        None
2282    }
2283}
2284
2285fn make_scroll_wheel_event(
2286    position: Point<Pixels>,
2287    scroll_delta: Point<f32>,
2288    modifiers: Modifiers,
2289) -> crate::ScrollWheelEvent {
2290    // When shift is held down, vertical scrolling turns into horizontal scrolling.
2291    let delta = if modifiers.shift {
2292        Point {
2293            x: scroll_delta.y,
2294            y: 0.0,
2295        }
2296    } else {
2297        scroll_delta
2298    };
2299    crate::ScrollWheelEvent {
2300        position,
2301        delta: ScrollDelta::Lines(delta),
2302        modifiers,
2303        touch_phase: TouchPhase::default(),
2304    }
2305}
2306
2307fn create_invisible_cursor(
2308    connection: &XCBConnection,
2309) -> anyhow::Result<crate::platform::linux::x11::client::xproto::Cursor> {
2310    let empty_pixmap = connection.generate_id()?;
2311    let root = connection.setup().roots[0].root;
2312    connection.create_pixmap(1, empty_pixmap, root, 1, 1)?;
2313
2314    let cursor = connection.generate_id()?;
2315    connection.create_cursor(cursor, empty_pixmap, empty_pixmap, 0, 0, 0, 0, 0, 0, 0, 0)?;
2316
2317    connection.free_pixmap(empty_pixmap)?;
2318
2319    xcb_flush(connection);
2320    Ok(cursor)
2321}
2322
2323enum DpiMode {
2324    Randr,
2325    Scale(f32),
2326    NotSet,
2327}
2328
2329fn get_scale_factor(
2330    connection: &XCBConnection,
2331    resource_database: &Database,
2332    screen_index: usize,
2333) -> f32 {
2334    let env_dpi = std::env::var(GPUI_X11_SCALE_FACTOR_ENV)
2335        .ok()
2336        .map(|var| {
2337            if var.to_lowercase() == "randr" {
2338                DpiMode::Randr
2339            } else if let Ok(scale) = var.parse::<f32>() {
2340                if valid_scale_factor(scale) {
2341                    DpiMode::Scale(scale)
2342                } else {
2343                    panic!(
2344                        "`{}` must be a positive normal number or `randr`. Got `{}`",
2345                        GPUI_X11_SCALE_FACTOR_ENV, var
2346                    );
2347                }
2348            } else if var.is_empty() {
2349                DpiMode::NotSet
2350            } else {
2351                panic!(
2352                    "`{}` must be a positive number or `randr`. Got `{}`",
2353                    GPUI_X11_SCALE_FACTOR_ENV, var
2354                );
2355            }
2356        })
2357        .unwrap_or(DpiMode::NotSet);
2358
2359    match env_dpi {
2360        DpiMode::Scale(scale) => {
2361            log::info!(
2362                "Using scale factor from {}: {}",
2363                GPUI_X11_SCALE_FACTOR_ENV,
2364                scale
2365            );
2366            return scale;
2367        }
2368        DpiMode::Randr => {
2369            if let Some(scale) = get_randr_scale_factor(connection, screen_index) {
2370                log::info!(
2371                    "Using RandR scale factor from {}=randr: {}",
2372                    GPUI_X11_SCALE_FACTOR_ENV,
2373                    scale
2374                );
2375                return scale;
2376            }
2377            log::warn!("Failed to calculate RandR scale factor, falling back to default");
2378            return 1.0;
2379        }
2380        DpiMode::NotSet => {}
2381    }
2382
2383    // TODO: Use scale factor from XSettings here
2384
2385    if let Some(dpi) = resource_database
2386        .get_value::<f32>("Xft.dpi", "Xft.dpi")
2387        .ok()
2388        .flatten()
2389    {
2390        let scale = dpi / 96.0; // base dpi
2391        log::info!("Using scale factor from Xft.dpi: {}", scale);
2392        return scale;
2393    }
2394
2395    if let Some(scale) = get_randr_scale_factor(connection, screen_index) {
2396        log::info!("Using RandR scale factor: {}", scale);
2397        return scale;
2398    }
2399
2400    log::info!("Using default scale factor: 1.0");
2401    1.0
2402}
2403
2404fn get_randr_scale_factor(connection: &XCBConnection, screen_index: usize) -> Option<f32> {
2405    let root = connection.setup().roots.get(screen_index)?.root;
2406
2407    let version_cookie = connection.randr_query_version(1, 6).ok()?;
2408    let version_reply = version_cookie.reply().ok()?;
2409    if version_reply.major_version < 1
2410        || (version_reply.major_version == 1 && version_reply.minor_version < 5)
2411    {
2412        return legacy_get_randr_scale_factor(connection, root); // for randr <1.5
2413    }
2414
2415    let monitors_cookie = connection.randr_get_monitors(root, true).ok()?; // true for active only
2416    let monitors_reply = monitors_cookie.reply().ok()?;
2417
2418    let mut fallback_scale: Option<f32> = None;
2419    for monitor in monitors_reply.monitors {
2420        if monitor.width_in_millimeters == 0 || monitor.height_in_millimeters == 0 {
2421            continue;
2422        }
2423        let scale_factor = get_dpi_factor(
2424            (monitor.width as u32, monitor.height as u32),
2425            (
2426                monitor.width_in_millimeters as u64,
2427                monitor.height_in_millimeters as u64,
2428            ),
2429        );
2430        if monitor.primary {
2431            return Some(scale_factor);
2432        } else if fallback_scale.is_none() {
2433            fallback_scale = Some(scale_factor);
2434        }
2435    }
2436
2437    fallback_scale
2438}
2439
2440fn legacy_get_randr_scale_factor(connection: &XCBConnection, root: u32) -> Option<f32> {
2441    let primary_cookie = connection.randr_get_output_primary(root).ok()?;
2442    let primary_reply = primary_cookie.reply().ok()?;
2443    let primary_output = primary_reply.output;
2444
2445    let primary_output_cookie = connection
2446        .randr_get_output_info(primary_output, x11rb::CURRENT_TIME)
2447        .ok()?;
2448    let primary_output_info = primary_output_cookie.reply().ok()?;
2449
2450    // try primary
2451    if primary_output_info.connection == randr::Connection::CONNECTED
2452        && primary_output_info.mm_width > 0
2453        && primary_output_info.mm_height > 0
2454        && primary_output_info.crtc != 0
2455    {
2456        let crtc_cookie = connection
2457            .randr_get_crtc_info(primary_output_info.crtc, x11rb::CURRENT_TIME)
2458            .ok()?;
2459        let crtc_info = crtc_cookie.reply().ok()?;
2460
2461        if crtc_info.width > 0 && crtc_info.height > 0 {
2462            let scale_factor = get_dpi_factor(
2463                (crtc_info.width as u32, crtc_info.height as u32),
2464                (
2465                    primary_output_info.mm_width as u64,
2466                    primary_output_info.mm_height as u64,
2467                ),
2468            );
2469            return Some(scale_factor);
2470        }
2471    }
2472
2473    // fallback: full scan
2474    let resources_cookie = connection.randr_get_screen_resources_current(root).ok()?;
2475    let screen_resources = resources_cookie.reply().ok()?;
2476
2477    let mut crtc_cookies = Vec::with_capacity(screen_resources.crtcs.len());
2478    for &crtc in &screen_resources.crtcs {
2479        if let Ok(cookie) = connection.randr_get_crtc_info(crtc, x11rb::CURRENT_TIME) {
2480            crtc_cookies.push((crtc, cookie));
2481        }
2482    }
2483
2484    let mut crtc_infos: HashMap<randr::Crtc, randr::GetCrtcInfoReply> = HashMap::default();
2485    let mut valid_outputs: HashSet<randr::Output> = HashSet::new();
2486    for (crtc, cookie) in crtc_cookies {
2487        if let Ok(reply) = cookie.reply()
2488            && reply.width > 0
2489            && reply.height > 0
2490            && !reply.outputs.is_empty()
2491        {
2492            crtc_infos.insert(crtc, reply.clone());
2493            valid_outputs.extend(&reply.outputs);
2494        }
2495    }
2496
2497    if valid_outputs.is_empty() {
2498        return None;
2499    }
2500
2501    let mut output_cookies = Vec::with_capacity(valid_outputs.len());
2502    for &output in &valid_outputs {
2503        if let Ok(cookie) = connection.randr_get_output_info(output, x11rb::CURRENT_TIME) {
2504            output_cookies.push((output, cookie));
2505        }
2506    }
2507    let mut output_infos: HashMap<randr::Output, randr::GetOutputInfoReply> = HashMap::default();
2508    for (output, cookie) in output_cookies {
2509        if let Ok(reply) = cookie.reply() {
2510            output_infos.insert(output, reply);
2511        }
2512    }
2513
2514    let mut fallback_scale: Option<f32> = None;
2515    for crtc_info in crtc_infos.values() {
2516        for &output in &crtc_info.outputs {
2517            if let Some(output_info) = output_infos.get(&output) {
2518                if output_info.connection != randr::Connection::CONNECTED {
2519                    continue;
2520                }
2521
2522                if output_info.mm_width == 0 || output_info.mm_height == 0 {
2523                    continue;
2524                }
2525
2526                let scale_factor = get_dpi_factor(
2527                    (crtc_info.width as u32, crtc_info.height as u32),
2528                    (output_info.mm_width as u64, output_info.mm_height as u64),
2529                );
2530
2531                if output != primary_output && fallback_scale.is_none() {
2532                    fallback_scale = Some(scale_factor);
2533                }
2534            }
2535        }
2536    }
2537
2538    fallback_scale
2539}
2540
2541fn get_dpi_factor((width_px, height_px): (u32, u32), (width_mm, height_mm): (u64, u64)) -> f32 {
2542    let ppmm = ((width_px as f64 * height_px as f64) / (width_mm as f64 * height_mm as f64)).sqrt(); // pixels per mm
2543
2544    const MM_PER_INCH: f64 = 25.4;
2545    const BASE_DPI: f64 = 96.0;
2546    const QUANTIZE_STEP: f64 = 12.0; // e.g. 1.25 = 15/12, 1.5 = 18/12, 1.75 = 21/12, 2.0 = 24/12
2547    const MIN_SCALE: f64 = 1.0;
2548    const MAX_SCALE: f64 = 20.0;
2549
2550    let dpi_factor =
2551        ((ppmm * (QUANTIZE_STEP * MM_PER_INCH / BASE_DPI)).round() / QUANTIZE_STEP).max(MIN_SCALE);
2552
2553    let validated_factor = if dpi_factor <= MAX_SCALE {
2554        dpi_factor
2555    } else {
2556        MIN_SCALE
2557    };
2558
2559    if valid_scale_factor(validated_factor as f32) {
2560        validated_factor as f32
2561    } else {
2562        log::warn!(
2563            "Calculated DPI factor {} is invalid, using 1.0",
2564            validated_factor
2565        );
2566        1.0
2567    }
2568}
2569
2570#[inline]
2571fn valid_scale_factor(scale_factor: f32) -> bool {
2572    scale_factor.is_sign_positive() && scale_factor.is_normal()
2573}
2574
2575#[inline]
2576fn update_xkb_mask_from_event_state(xkb: &mut xkbc::State, event_state: xproto::KeyButMask) {
2577    let depressed_mods = event_state.remove((ModMask::LOCK | ModMask::M2).bits());
2578    let latched_mods = xkb.serialize_mods(xkbc::STATE_MODS_LATCHED);
2579    let locked_mods = xkb.serialize_mods(xkbc::STATE_MODS_LOCKED);
2580    let locked_layout = xkb.serialize_layout(xkbc::STATE_LAYOUT_LOCKED);
2581    xkb.update_mask(
2582        depressed_mods.into(),
2583        latched_mods,
2584        locked_mods,
2585        0,
2586        0,
2587        locked_layout,
2588    );
2589}