client.rs

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