client.rs

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