client.rs

   1use crate::{Capslock, 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;
  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, Visibility,
  33    },
  34    protocol::{Event, randr, render, xinput, xkb, xproto},
  35    resource_manager::Database,
  36    wrapper::ConnectionExt as _,
  37    xcb_ffi::XCBConnection,
  38};
  39use xim::{AttributeName, Client, InputStyle, x11rb::X11rbClient};
  40use xkbc::x11::ffi::{XKB_X11_MIN_MAJOR_XKB_VERSION, XKB_X11_MIN_MINOR_XKB_VERSION};
  41use xkbcommon::xkb::{self as xkbc, STATE_LAYOUT_EFFECTIVE};
  42
  43use super::{
  44    ButtonOrScroll, ScrollDirection, X11Display, X11WindowStatePtr, XcbAtoms, XimCallbackEvent,
  45    XimHandler, button_or_scroll_from_event_detail, check_reply,
  46    clipboard::{self, Clipboard},
  47    get_reply, get_valuator_axis_index, handle_connection_error, modifiers_from_state,
  48    pressed_button_from_mask,
  49};
  50
  51use crate::platform::{
  52    LinuxCommon, PlatformWindow,
  53    blade::BladeContext,
  54    linux::{
  55        DEFAULT_CURSOR_ICON_NAME, LinuxClient, get_xkb_compose_state, is_within_click_distance,
  56        log_cursor_icon_warning, open_uri_internal,
  57        platform::{DOUBLE_CLICK_INTERVAL, SCROLL_LINES},
  58        reveal_path_internal,
  59        xdg_desktop_portal::{Event as XDPEvent, XDPEventSource},
  60    },
  61};
  62use crate::{
  63    AnyWindowHandle, Bounds, ClipboardItem, CursorStyle, DisplayId, FileDropEvent, Keystroke,
  64    LinuxKeyboardLayout, Modifiers, ModifiersChangedEvent, MouseButton, Pixels, Platform,
  65    PlatformDisplay, PlatformInput, PlatformKeyboardLayout, Point, RequestFrameOptions,
  66    ScrollDelta, Size, TouchPhase, WindowParams, X11Window, modifiers_from_xinput_info, point, px,
  67};
  68
  69/// Value for DeviceId parameters which selects all devices.
  70pub(crate) const XINPUT_ALL_DEVICES: xinput::DeviceId = 0;
  71
  72/// Value for DeviceId parameters which selects all device groups. Events that
  73/// occur within the group are emitted by the group itself.
  74///
  75/// In XInput 2's interface, these are referred to as "master devices", but that
  76/// terminology is both archaic and unclear.
  77pub(crate) const XINPUT_ALL_DEVICE_GROUPS: xinput::DeviceId = 1;
  78
  79const GPUI_X11_SCALE_FACTOR_ENV: &str = "GPUI_X11_SCALE_FACTOR";
  80
  81pub(crate) struct WindowRef {
  82    window: X11WindowStatePtr,
  83    refresh_state: Option<RefreshState>,
  84    expose_event_received: bool,
  85    last_visibility: Visibility,
  86    is_mapped: bool,
  87}
  88
  89impl WindowRef {
  90    pub fn handle(&self) -> AnyWindowHandle {
  91        self.window.state.borrow().handle
  92    }
  93}
  94
  95impl Deref for WindowRef {
  96    type Target = X11WindowStatePtr;
  97
  98    fn deref(&self) -> &Self::Target {
  99        &self.window
 100    }
 101}
 102
 103enum RefreshState {
 104    Hidden {
 105        refresh_rate: Duration,
 106    },
 107    PeriodicRefresh {
 108        refresh_rate: Duration,
 109        event_loop_token: RegistrationToken,
 110    },
 111}
 112
 113#[derive(Debug)]
 114#[non_exhaustive]
 115pub enum EventHandlerError {
 116    XCBConnectionError(ConnectionError),
 117    XIMClientError(xim::ClientError),
 118}
 119
 120impl std::error::Error for EventHandlerError {}
 121
 122impl std::fmt::Display for EventHandlerError {
 123    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 124        match self {
 125            EventHandlerError::XCBConnectionError(err) => err.fmt(f),
 126            EventHandlerError::XIMClientError(err) => err.fmt(f),
 127        }
 128    }
 129}
 130
 131impl From<ConnectionError> for EventHandlerError {
 132    fn from(err: ConnectionError) -> Self {
 133        EventHandlerError::XCBConnectionError(err)
 134    }
 135}
 136
 137impl From<xim::ClientError> for EventHandlerError {
 138    fn from(err: xim::ClientError) -> Self {
 139        EventHandlerError::XIMClientError(err)
 140    }
 141}
 142
 143#[derive(Debug, Default)]
 144pub struct Xdnd {
 145    other_window: xproto::Window,
 146    drag_type: u32,
 147    retrieved: bool,
 148    position: Point<Pixels>,
 149}
 150
 151#[derive(Debug)]
 152struct PointerDeviceState {
 153    horizontal: ScrollAxisState,
 154    vertical: ScrollAxisState,
 155}
 156
 157#[derive(Debug, Default)]
 158struct ScrollAxisState {
 159    /// Valuator number for looking up this axis's scroll value.
 160    valuator_number: Option<u16>,
 161    /// Conversion factor from scroll units to lines.
 162    multiplier: f32,
 163    /// Last scroll value for calculating scroll delta.
 164    ///
 165    /// This gets set to `None` whenever it might be invalid - when devices change or when window focus changes.
 166    /// The logic errs on the side of invalidating this, since the consequence is just skipping the delta of one scroll event.
 167    /// The consequence of not invalidating it can be large invalid deltas, which are much more user visible.
 168    scroll_value: Option<f32>,
 169}
 170
 171pub struct X11ClientState {
 172    pub(crate) loop_handle: LoopHandle<'static, X11Client>,
 173    pub(crate) event_loop: Option<calloop::EventLoop<'static, X11Client>>,
 174
 175    pub(crate) last_click: Instant,
 176    pub(crate) last_mouse_button: Option<MouseButton>,
 177    pub(crate) last_location: Point<Pixels>,
 178    pub(crate) current_count: usize,
 179
 180    gpu_context: BladeContext,
 181
 182    pub(crate) scale_factor: f32,
 183
 184    xkb_context: xkbc::Context,
 185    pub(crate) xcb_connection: Rc<XCBConnection>,
 186    xkb_device_id: i32,
 187    client_side_decorations_supported: bool,
 188    pub(crate) x_root_index: usize,
 189    pub(crate) _resource_database: Database,
 190    pub(crate) atoms: XcbAtoms,
 191    pub(crate) windows: HashMap<xproto::Window, WindowRef>,
 192    pub(crate) mouse_focused_window: Option<xproto::Window>,
 193    pub(crate) keyboard_focused_window: Option<xproto::Window>,
 194    pub(crate) xkb: xkbc::State,
 195    keyboard_layout: LinuxKeyboardLayout,
 196    pub(crate) ximc: Option<X11rbClient<Rc<XCBConnection>>>,
 197    pub(crate) xim_handler: Option<XimHandler>,
 198    pub modifiers: Modifiers,
 199    pub capslock: Capslock,
 200    // TODO: Can the other updates to `modifiers` be removed so that this is unnecessary?
 201    // capslock logic was done analog to modifiers
 202    pub last_modifiers_changed_event: Modifiers,
 203    pub last_capslock_changed_event: Capslock,
 204
 205    pub(crate) compose_state: Option<xkbc::compose::State>,
 206    pub(crate) pre_edit_text: Option<String>,
 207    pub(crate) composing: bool,
 208    pub(crate) pre_key_char_down: Option<Keystroke>,
 209    pub(crate) cursor_handle: cursor::Handle,
 210    pub(crate) cursor_styles: HashMap<xproto::Window, CursorStyle>,
 211    pub(crate) cursor_cache: HashMap<CursorStyle, Option<xproto::Cursor>>,
 212
 213    pointer_device_states: BTreeMap<xinput::DeviceId, PointerDeviceState>,
 214
 215    pub(crate) common: LinuxCommon,
 216    pub(crate) clipboard: Clipboard,
 217    pub(crate) clipboard_item: Option<ClipboardItem>,
 218    pub(crate) xdnd_state: Xdnd,
 219}
 220
 221#[derive(Clone)]
 222pub struct X11ClientStatePtr(pub Weak<RefCell<X11ClientState>>);
 223
 224impl X11ClientStatePtr {
 225    fn get_client(&self) -> Option<X11Client> {
 226        self.0.upgrade().map(X11Client)
 227    }
 228
 229    pub fn drop_window(&self, x_window: u32) {
 230        let Some(client) = self.get_client() else {
 231            return;
 232        };
 233        let mut state = client.0.borrow_mut();
 234
 235        if let Some(window_ref) = state.windows.remove(&x_window)
 236            && let Some(RefreshState::PeriodicRefresh {
 237                event_loop_token, ..
 238            }) = window_ref.refresh_state
 239        {
 240            state.loop_handle.remove(event_loop_token);
 241        }
 242        if state.mouse_focused_window == Some(x_window) {
 243            state.mouse_focused_window = None;
 244        }
 245        if state.keyboard_focused_window == Some(x_window) {
 246            state.keyboard_focused_window = None;
 247        }
 248        state.cursor_styles.remove(&x_window);
 249    }
 250
 251    pub fn update_ime_position(&self, bounds: Bounds<Pixels>) {
 252        let Some(client) = self.get_client() else {
 253            return;
 254        };
 255        let mut state = client.0.borrow_mut();
 256        if state.composing || state.ximc.is_none() {
 257            return;
 258        }
 259
 260        let Some(mut ximc) = state.ximc.take() else {
 261            log::error!("bug: xim connection not set");
 262            return;
 263        };
 264        let Some(xim_handler) = state.xim_handler.take() else {
 265            log::error!("bug: xim handler not set");
 266            state.ximc = Some(ximc);
 267            return;
 268        };
 269        let scaled_bounds = bounds.scale(state.scale_factor);
 270        let ic_attributes = ximc
 271            .build_ic_attributes()
 272            .push(
 273                xim::AttributeName::InputStyle,
 274                xim::InputStyle::PREEDIT_CALLBACKS,
 275            )
 276            .push(xim::AttributeName::ClientWindow, xim_handler.window)
 277            .push(xim::AttributeName::FocusWindow, xim_handler.window)
 278            .nested_list(xim::AttributeName::PreeditAttributes, |b| {
 279                b.push(
 280                    xim::AttributeName::SpotLocation,
 281                    xim::Point {
 282                        x: u32::from(scaled_bounds.origin.x + scaled_bounds.size.width) as i16,
 283                        y: u32::from(scaled_bounds.origin.y + scaled_bounds.size.height) as i16,
 284                    },
 285                );
 286            })
 287            .build();
 288        let _ = ximc
 289            .set_ic_values(xim_handler.im_id, xim_handler.ic_id, ic_attributes)
 290            .log_err();
 291        state.ximc = Some(ximc);
 292        state.xim_handler = Some(xim_handler);
 293    }
 294}
 295
 296#[derive(Clone)]
 297pub(crate) struct X11Client(Rc<RefCell<X11ClientState>>);
 298
 299impl X11Client {
 300    pub(crate) fn new() -> anyhow::Result<Self> {
 301        let event_loop = EventLoop::try_new()?;
 302
 303        let (common, main_receiver) = LinuxCommon::new(event_loop.get_signal());
 304
 305        let handle = event_loop.handle();
 306
 307        handle
 308            .insert_source(main_receiver, {
 309                let handle = handle.clone();
 310                move |event, _, _: &mut X11Client| {
 311                    if let calloop::channel::Event::Msg(runnable) = event {
 312                        // Insert the runnables as idle callbacks, so we make sure that user-input and X11
 313                        // events have higher priority and runnables are only worked off after the event
 314                        // callbacks.
 315                        handle.insert_idle(|_| {
 316                            runnable.run();
 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().context("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    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 {
 763                    // window "x" button clicked by user
 764                    if window.should_close() {
 765                        // Rest of the close logic is handled in drop_window()
 766                        window.close();
 767                    }
 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                state.keyboard_focused_window = None;
 918                if let Some(compose_state) = state.compose_state.as_mut() {
 919                    compose_state.reset();
 920                }
 921                state.pre_edit_text.take();
 922                drop(state);
 923                self.reset_ime();
 924                window.handle_ime_delete();
 925            }
 926            Event::XkbNewKeyboardNotify(_) | Event::XkbMapNotify(_) => {
 927                let mut state = self.0.borrow_mut();
 928                let xkb_state = {
 929                    let xkb_keymap = xkbc::x11::keymap_new_from_device(
 930                        &state.xkb_context,
 931                        &state.xcb_connection,
 932                        state.xkb_device_id,
 933                        xkbc::KEYMAP_COMPILE_NO_FLAGS,
 934                    );
 935                    xkbc::x11::state_new_from_device(
 936                        &xkb_keymap,
 937                        &state.xcb_connection,
 938                        state.xkb_device_id,
 939                    )
 940                };
 941                state.xkb = xkb_state;
 942                drop(state);
 943                self.handle_keyboard_layout_change();
 944            }
 945            Event::XkbStateNotify(event) => {
 946                let mut state = self.0.borrow_mut();
 947                let old_layout = state.xkb.serialize_layout(STATE_LAYOUT_EFFECTIVE);
 948                let new_layout = u32::from(event.group);
 949                state.xkb.update_mask(
 950                    event.base_mods.into(),
 951                    event.latched_mods.into(),
 952                    event.locked_mods.into(),
 953                    event.base_group as u32,
 954                    event.latched_group as u32,
 955                    event.locked_group.into(),
 956                );
 957                let modifiers = Modifiers::from_xkb(&state.xkb);
 958                let capslock = Capslock::from_xkb(&state.xkb);
 959                if state.last_modifiers_changed_event == modifiers
 960                    && state.last_capslock_changed_event == capslock
 961                {
 962                    drop(state);
 963                } else {
 964                    let focused_window_id = state.keyboard_focused_window?;
 965                    state.modifiers = modifiers;
 966                    state.last_modifiers_changed_event = modifiers;
 967                    state.capslock = capslock;
 968                    state.last_capslock_changed_event = capslock;
 969                    drop(state);
 970
 971                    let focused_window = self.get_window(focused_window_id)?;
 972                    focused_window.handle_input(PlatformInput::ModifiersChanged(
 973                        ModifiersChangedEvent {
 974                            modifiers,
 975                            capslock,
 976                        },
 977                    ));
 978                }
 979
 980                if new_layout != old_layout {
 981                    self.handle_keyboard_layout_change();
 982                }
 983            }
 984            Event::KeyPress(event) => {
 985                let window = self.get_window(event.event)?;
 986                let mut state = self.0.borrow_mut();
 987
 988                let modifiers = modifiers_from_state(event.state);
 989                state.modifiers = modifiers;
 990                state.pre_key_char_down.take();
 991                let keystroke = {
 992                    let code = event.detail.into();
 993                    let mut keystroke = crate::Keystroke::from_xkb(&state.xkb, modifiers, code);
 994                    let keysym = state.xkb.key_get_one_sym(code);
 995
 996                    if keysym.is_modifier_key() {
 997                        return Some(());
 998                    }
 999
1000                    // should be called after key_get_one_sym
1001                    state.xkb.update_key(code, xkbc::KeyDirection::Down);
1002
1003                    if let Some(mut compose_state) = state.compose_state.take() {
1004                        compose_state.feed(keysym);
1005                        match compose_state.status() {
1006                            xkbc::Status::Composed => {
1007                                state.pre_edit_text.take();
1008                                keystroke.key_char = compose_state.utf8();
1009                                if let Some(keysym) = compose_state.keysym() {
1010                                    keystroke.key = xkbc::keysym_get_name(keysym);
1011                                }
1012                            }
1013                            xkbc::Status::Composing => {
1014                                keystroke.key_char = None;
1015                                state.pre_edit_text = compose_state
1016                                    .utf8()
1017                                    .or(crate::Keystroke::underlying_dead_key(keysym));
1018                                let pre_edit =
1019                                    state.pre_edit_text.clone().unwrap_or(String::default());
1020                                drop(state);
1021                                window.handle_ime_preedit(pre_edit);
1022                                state = self.0.borrow_mut();
1023                            }
1024                            xkbc::Status::Cancelled => {
1025                                let pre_edit = state.pre_edit_text.take();
1026                                drop(state);
1027                                if let Some(pre_edit) = pre_edit {
1028                                    window.handle_ime_commit(pre_edit);
1029                                }
1030                                if let Some(current_key) = Keystroke::underlying_dead_key(keysym) {
1031                                    window.handle_ime_preedit(current_key);
1032                                }
1033                                state = self.0.borrow_mut();
1034                                compose_state.feed(keysym);
1035                            }
1036                            _ => {}
1037                        }
1038                        state.compose_state = Some(compose_state);
1039                    }
1040                    keystroke
1041                };
1042                drop(state);
1043                window.handle_input(PlatformInput::KeyDown(crate::KeyDownEvent {
1044                    keystroke,
1045                    is_held: false,
1046                    prefer_character_input: false,
1047                }));
1048            }
1049            Event::KeyRelease(event) => {
1050                let window = self.get_window(event.event)?;
1051                let mut state = self.0.borrow_mut();
1052
1053                let modifiers = modifiers_from_state(event.state);
1054                state.modifiers = modifiers;
1055
1056                let keystroke = {
1057                    let code = event.detail.into();
1058                    let keystroke = crate::Keystroke::from_xkb(&state.xkb, modifiers, code);
1059                    let keysym = state.xkb.key_get_one_sym(code);
1060
1061                    if keysym.is_modifier_key() {
1062                        return Some(());
1063                    }
1064
1065                    // should be called after key_get_one_sym
1066                    state.xkb.update_key(code, xkbc::KeyDirection::Up);
1067
1068                    keystroke
1069                };
1070                drop(state);
1071                window.handle_input(PlatformInput::KeyUp(crate::KeyUpEvent { keystroke }));
1072            }
1073            Event::XinputButtonPress(event) => {
1074                let window = self.get_window(event.event)?;
1075                let mut state = self.0.borrow_mut();
1076
1077                let modifiers = modifiers_from_xinput_info(event.mods);
1078                state.modifiers = modifiers;
1079
1080                let position = point(
1081                    px(event.event_x as f32 / u16::MAX as f32 / state.scale_factor),
1082                    px(event.event_y as f32 / u16::MAX as f32 / state.scale_factor),
1083                );
1084
1085                if state.composing && state.ximc.is_some() {
1086                    drop(state);
1087                    self.reset_ime();
1088                    window.handle_ime_unmark();
1089                    state = self.0.borrow_mut();
1090                } else if let Some(text) = state.pre_edit_text.take() {
1091                    if let Some(compose_state) = state.compose_state.as_mut() {
1092                        compose_state.reset();
1093                    }
1094                    drop(state);
1095                    window.handle_ime_commit(text);
1096                    state = self.0.borrow_mut();
1097                }
1098                match button_or_scroll_from_event_detail(event.detail) {
1099                    Some(ButtonOrScroll::Button(button)) => {
1100                        let click_elapsed = state.last_click.elapsed();
1101                        if click_elapsed < DOUBLE_CLICK_INTERVAL
1102                            && state
1103                                .last_mouse_button
1104                                .is_some_and(|prev_button| prev_button == button)
1105                            && is_within_click_distance(state.last_location, position)
1106                        {
1107                            state.current_count += 1;
1108                        } else {
1109                            state.current_count = 1;
1110                        }
1111
1112                        state.last_click = Instant::now();
1113                        state.last_mouse_button = Some(button);
1114                        state.last_location = position;
1115                        let current_count = state.current_count;
1116
1117                        drop(state);
1118                        window.handle_input(PlatformInput::MouseDown(crate::MouseDownEvent {
1119                            button,
1120                            position,
1121                            modifiers,
1122                            click_count: current_count,
1123                            first_mouse: false,
1124                        }));
1125                    }
1126                    Some(ButtonOrScroll::Scroll(direction)) => {
1127                        drop(state);
1128                        // Emulated scroll button presses are sent simultaneously with smooth scrolling XinputMotion events.
1129                        // Since handling those events does the scrolling, they are skipped here.
1130                        if !event
1131                            .flags
1132                            .contains(xinput::PointerEventFlags::POINTER_EMULATED)
1133                        {
1134                            let scroll_delta = match direction {
1135                                ScrollDirection::Up => Point::new(0.0, SCROLL_LINES),
1136                                ScrollDirection::Down => Point::new(0.0, -SCROLL_LINES),
1137                                ScrollDirection::Left => Point::new(SCROLL_LINES, 0.0),
1138                                ScrollDirection::Right => Point::new(-SCROLL_LINES, 0.0),
1139                            };
1140                            window.handle_input(PlatformInput::ScrollWheel(
1141                                make_scroll_wheel_event(position, scroll_delta, modifiers),
1142                            ));
1143                        }
1144                    }
1145                    None => {
1146                        log::error!("Unknown x11 button: {}", event.detail);
1147                    }
1148                }
1149            }
1150            Event::XinputButtonRelease(event) => {
1151                let window = self.get_window(event.event)?;
1152                let mut state = self.0.borrow_mut();
1153                let modifiers = modifiers_from_xinput_info(event.mods);
1154                state.modifiers = modifiers;
1155
1156                let position = point(
1157                    px(event.event_x as f32 / u16::MAX as f32 / state.scale_factor),
1158                    px(event.event_y as f32 / u16::MAX as f32 / state.scale_factor),
1159                );
1160                match button_or_scroll_from_event_detail(event.detail) {
1161                    Some(ButtonOrScroll::Button(button)) => {
1162                        let click_count = state.current_count;
1163                        drop(state);
1164                        window.handle_input(PlatformInput::MouseUp(crate::MouseUpEvent {
1165                            button,
1166                            position,
1167                            modifiers,
1168                            click_count,
1169                        }));
1170                    }
1171                    Some(ButtonOrScroll::Scroll(_)) => {}
1172                    None => {}
1173                }
1174            }
1175            Event::XinputMotion(event) => {
1176                let window = self.get_window(event.event)?;
1177                let mut state = self.0.borrow_mut();
1178                let pressed_button = pressed_button_from_mask(event.button_mask[0]);
1179                let position = point(
1180                    px(event.event_x as f32 / u16::MAX as f32 / state.scale_factor),
1181                    px(event.event_y as f32 / u16::MAX as f32 / state.scale_factor),
1182                );
1183                let modifiers = modifiers_from_xinput_info(event.mods);
1184                state.modifiers = modifiers;
1185                drop(state);
1186
1187                if event.valuator_mask[0] & 3 != 0 {
1188                    window.handle_input(PlatformInput::MouseMove(crate::MouseMoveEvent {
1189                        position,
1190                        pressed_button,
1191                        modifiers,
1192                    }));
1193                }
1194
1195                state = self.0.borrow_mut();
1196                if let Some(mut pointer) = state.pointer_device_states.get_mut(&event.sourceid) {
1197                    let scroll_delta = get_scroll_delta_and_update_state(pointer, &event);
1198                    drop(state);
1199                    if let Some(scroll_delta) = scroll_delta {
1200                        window.handle_input(PlatformInput::ScrollWheel(make_scroll_wheel_event(
1201                            position,
1202                            scroll_delta,
1203                            modifiers,
1204                        )));
1205                    }
1206                }
1207            }
1208            Event::XinputEnter(event) if event.mode == xinput::NotifyMode::NORMAL => {
1209                let window = self.get_window(event.event)?;
1210                window.set_hovered(true);
1211                let mut state = self.0.borrow_mut();
1212                state.mouse_focused_window = Some(event.event);
1213            }
1214            Event::XinputLeave(event) if event.mode == xinput::NotifyMode::NORMAL => {
1215                let mut state = self.0.borrow_mut();
1216
1217                // 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)
1218                reset_all_pointer_device_scroll_positions(&mut state.pointer_device_states);
1219                state.mouse_focused_window = None;
1220                let pressed_button = pressed_button_from_mask(event.buttons[0]);
1221                let position = point(
1222                    px(event.event_x as f32 / u16::MAX as f32 / state.scale_factor),
1223                    px(event.event_y as f32 / u16::MAX as f32 / state.scale_factor),
1224                );
1225                let modifiers = modifiers_from_xinput_info(event.mods);
1226                state.modifiers = modifiers;
1227                drop(state);
1228
1229                let window = self.get_window(event.event)?;
1230                window.handle_input(PlatformInput::MouseExited(crate::MouseExitEvent {
1231                    pressed_button,
1232                    position,
1233                    modifiers,
1234                }));
1235                window.set_hovered(false);
1236            }
1237            Event::XinputHierarchy(event) => {
1238                let mut state = self.0.borrow_mut();
1239                // Temporarily use `state.pointer_device_states` to only store pointers that still have valid scroll values.
1240                // Any change to a device invalidates its scroll values.
1241                for info in event.infos {
1242                    if is_pointer_device(info.type_) {
1243                        state.pointer_device_states.remove(&info.deviceid);
1244                    }
1245                }
1246                if let Some(pointer_device_states) = current_pointer_device_states(
1247                    &state.xcb_connection,
1248                    &state.pointer_device_states,
1249                ) {
1250                    state.pointer_device_states = pointer_device_states;
1251                }
1252            }
1253            Event::XinputDeviceChanged(event) => {
1254                let mut state = self.0.borrow_mut();
1255                if let Some(mut pointer) = state.pointer_device_states.get_mut(&event.sourceid) {
1256                    reset_pointer_device_scroll_positions(pointer);
1257                }
1258            }
1259            _ => {}
1260        };
1261
1262        Some(())
1263    }
1264
1265    fn handle_xim_callback_event(&self, event: XimCallbackEvent) {
1266        match event {
1267            XimCallbackEvent::XimXEvent(event) => {
1268                self.handle_event(event);
1269            }
1270            XimCallbackEvent::XimCommitEvent(window, text) => {
1271                self.xim_handle_commit(window, text);
1272            }
1273            XimCallbackEvent::XimPreeditEvent(window, text) => {
1274                self.xim_handle_preedit(window, text);
1275            }
1276        };
1277    }
1278
1279    fn xim_handle_event(&self, event: Event) -> Option<()> {
1280        match event {
1281            Event::KeyPress(event) | Event::KeyRelease(event) => {
1282                let mut state = self.0.borrow_mut();
1283                state.pre_key_char_down = Some(Keystroke::from_xkb(
1284                    &state.xkb,
1285                    state.modifiers,
1286                    event.detail.into(),
1287                ));
1288                let (mut ximc, mut xim_handler) = state.take_xim()?;
1289                drop(state);
1290                xim_handler.window = event.event;
1291                ximc.forward_event(
1292                    xim_handler.im_id,
1293                    xim_handler.ic_id,
1294                    xim::ForwardEventFlag::empty(),
1295                    &event,
1296                )
1297                .context("X11: Failed to forward XIM event")
1298                .log_err();
1299                let mut state = self.0.borrow_mut();
1300                state.restore_xim(ximc, xim_handler);
1301                drop(state);
1302            }
1303            event => {
1304                self.handle_event(event);
1305            }
1306        }
1307        Some(())
1308    }
1309
1310    fn xim_handle_commit(&self, window: xproto::Window, text: String) -> Option<()> {
1311        let Some(window) = self.get_window(window) else {
1312            log::error!("bug: Failed to get window for XIM commit");
1313            return None;
1314        };
1315        let mut state = self.0.borrow_mut();
1316        state.composing = false;
1317        drop(state);
1318        window.handle_ime_commit(text);
1319        Some(())
1320    }
1321
1322    fn xim_handle_preedit(&self, window: xproto::Window, text: String) -> Option<()> {
1323        let Some(window) = self.get_window(window) else {
1324            log::error!("bug: Failed to get window for XIM preedit");
1325            return None;
1326        };
1327
1328        let mut state = self.0.borrow_mut();
1329        let (mut ximc, mut xim_handler) = state.take_xim()?;
1330        state.composing = !text.is_empty();
1331        drop(state);
1332        window.handle_ime_preedit(text);
1333
1334        if let Some(scaled_area) = window.get_ime_area() {
1335            let ic_attributes = ximc
1336                .build_ic_attributes()
1337                .push(
1338                    xim::AttributeName::InputStyle,
1339                    xim::InputStyle::PREEDIT_CALLBACKS,
1340                )
1341                .push(xim::AttributeName::ClientWindow, xim_handler.window)
1342                .push(xim::AttributeName::FocusWindow, xim_handler.window)
1343                .nested_list(xim::AttributeName::PreeditAttributes, |b| {
1344                    b.push(
1345                        xim::AttributeName::SpotLocation,
1346                        xim::Point {
1347                            x: u32::from(scaled_area.origin.x + scaled_area.size.width) as i16,
1348                            y: u32::from(scaled_area.origin.y + scaled_area.size.height) as i16,
1349                        },
1350                    );
1351                })
1352                .build();
1353            ximc.set_ic_values(xim_handler.im_id, xim_handler.ic_id, ic_attributes)
1354                .ok();
1355        }
1356        let mut state = self.0.borrow_mut();
1357        state.restore_xim(ximc, xim_handler);
1358        drop(state);
1359        Some(())
1360    }
1361
1362    fn handle_keyboard_layout_change(&self) {
1363        let mut state = self.0.borrow_mut();
1364        let layout_idx = state.xkb.serialize_layout(STATE_LAYOUT_EFFECTIVE);
1365        let keymap = state.xkb.get_keymap();
1366        let layout_name = keymap.layout_get_name(layout_idx);
1367        if layout_name != state.keyboard_layout.name() {
1368            state.keyboard_layout = LinuxKeyboardLayout::new(layout_name.to_string().into());
1369            if let Some(mut callback) = state.common.callbacks.keyboard_layout_change.take() {
1370                drop(state);
1371                callback();
1372                state = self.0.borrow_mut();
1373                state.common.callbacks.keyboard_layout_change = Some(callback);
1374            }
1375        }
1376    }
1377}
1378
1379impl LinuxClient for X11Client {
1380    fn compositor_name(&self) -> &'static str {
1381        "X11"
1382    }
1383
1384    fn with_common<R>(&self, f: impl FnOnce(&mut LinuxCommon) -> R) -> R {
1385        f(&mut self.0.borrow_mut().common)
1386    }
1387
1388    fn keyboard_layout(&self) -> Box<dyn PlatformKeyboardLayout> {
1389        let state = self.0.borrow();
1390        Box::new(state.keyboard_layout.clone())
1391    }
1392
1393    fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
1394        let state = self.0.borrow();
1395        let setup = state.xcb_connection.setup();
1396        setup
1397            .roots
1398            .iter()
1399            .enumerate()
1400            .filter_map(|(root_id, _)| {
1401                Some(Rc::new(
1402                    X11Display::new(&state.xcb_connection, state.scale_factor, root_id).ok()?,
1403                ) as Rc<dyn PlatformDisplay>)
1404            })
1405            .collect()
1406    }
1407
1408    fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
1409        let state = self.0.borrow();
1410        X11Display::new(
1411            &state.xcb_connection,
1412            state.scale_factor,
1413            state.x_root_index,
1414        )
1415        .log_err()
1416        .map(|display| Rc::new(display) as Rc<dyn PlatformDisplay>)
1417    }
1418
1419    fn display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>> {
1420        let state = self.0.borrow();
1421
1422        Some(Rc::new(
1423            X11Display::new(&state.xcb_connection, state.scale_factor, id.0 as usize).ok()?,
1424        ))
1425    }
1426
1427    #[cfg(feature = "screen-capture")]
1428    fn is_screen_capture_supported(&self) -> bool {
1429        true
1430    }
1431
1432    #[cfg(feature = "screen-capture")]
1433    fn screen_capture_sources(
1434        &self,
1435    ) -> futures::channel::oneshot::Receiver<anyhow::Result<Vec<Rc<dyn crate::ScreenCaptureSource>>>>
1436    {
1437        crate::platform::scap_screen_capture::scap_screen_sources(
1438            &self.0.borrow().common.foreground_executor,
1439        )
1440    }
1441
1442    fn open_window(
1443        &self,
1444        handle: AnyWindowHandle,
1445        params: WindowParams,
1446    ) -> anyhow::Result<Box<dyn PlatformWindow>> {
1447        let mut state = self.0.borrow_mut();
1448        let parent_window = state
1449            .keyboard_focused_window
1450            .and_then(|focused_window| state.windows.get(&focused_window))
1451            .map(|window| window.window.x_window);
1452        let x_window = state
1453            .xcb_connection
1454            .generate_id()
1455            .context("X11: Failed to generate window ID")?;
1456
1457        let window = X11Window::new(
1458            handle,
1459            X11ClientStatePtr(Rc::downgrade(&self.0)),
1460            state.common.foreground_executor.clone(),
1461            &state.gpu_context,
1462            params,
1463            &state.xcb_connection,
1464            state.client_side_decorations_supported,
1465            state.x_root_index,
1466            x_window,
1467            &state.atoms,
1468            state.scale_factor,
1469            state.common.appearance,
1470            parent_window,
1471        )?;
1472        check_reply(
1473            || "Failed to set XdndAware property",
1474            state.xcb_connection.change_property32(
1475                xproto::PropMode::REPLACE,
1476                x_window,
1477                state.atoms.XdndAware,
1478                state.atoms.XA_ATOM,
1479                &[5],
1480            ),
1481        )
1482        .log_err();
1483        xcb_flush(&state.xcb_connection);
1484
1485        let window_ref = WindowRef {
1486            window: window.0.clone(),
1487            refresh_state: None,
1488            expose_event_received: false,
1489            last_visibility: Visibility::UNOBSCURED,
1490            is_mapped: false,
1491        };
1492
1493        state.windows.insert(x_window, window_ref);
1494        Ok(Box::new(window))
1495    }
1496
1497    fn set_cursor_style(&self, style: CursorStyle) {
1498        let mut state = self.0.borrow_mut();
1499        let Some(focused_window) = state.mouse_focused_window else {
1500            return;
1501        };
1502        let current_style = state
1503            .cursor_styles
1504            .get(&focused_window)
1505            .unwrap_or(&CursorStyle::Arrow);
1506        if *current_style == style {
1507            return;
1508        }
1509
1510        let Some(cursor) = state.get_cursor_icon(style) else {
1511            return;
1512        };
1513
1514        state.cursor_styles.insert(focused_window, style);
1515        check_reply(
1516            || "Failed to set cursor style",
1517            state.xcb_connection.change_window_attributes(
1518                focused_window,
1519                &ChangeWindowAttributesAux {
1520                    cursor: Some(cursor),
1521                    ..Default::default()
1522                },
1523            ),
1524        )
1525        .log_err();
1526        state.xcb_connection.flush().log_err();
1527    }
1528
1529    fn open_uri(&self, uri: &str) {
1530        #[cfg(any(feature = "wayland", feature = "x11"))]
1531        open_uri_internal(self.background_executor(), uri, None);
1532    }
1533
1534    fn reveal_path(&self, path: PathBuf) {
1535        #[cfg(any(feature = "x11", feature = "wayland"))]
1536        reveal_path_internal(self.background_executor(), path, None);
1537    }
1538
1539    fn write_to_primary(&self, item: crate::ClipboardItem) {
1540        let state = self.0.borrow_mut();
1541        state
1542            .clipboard
1543            .set_text(
1544                std::borrow::Cow::Owned(item.text().unwrap_or_default()),
1545                clipboard::ClipboardKind::Primary,
1546                clipboard::WaitConfig::None,
1547            )
1548            .context("X11 Failed to write to clipboard (primary)")
1549            .log_with_level(log::Level::Debug);
1550    }
1551
1552    fn write_to_clipboard(&self, item: crate::ClipboardItem) {
1553        let mut state = self.0.borrow_mut();
1554        state
1555            .clipboard
1556            .set_text(
1557                std::borrow::Cow::Owned(item.text().unwrap_or_default()),
1558                clipboard::ClipboardKind::Clipboard,
1559                clipboard::WaitConfig::None,
1560            )
1561            .context("X11: Failed to write to clipboard (clipboard)")
1562            .log_with_level(log::Level::Debug);
1563        state.clipboard_item.replace(item);
1564    }
1565
1566    fn read_from_primary(&self) -> Option<crate::ClipboardItem> {
1567        let state = self.0.borrow_mut();
1568        state
1569            .clipboard
1570            .get_any(clipboard::ClipboardKind::Primary)
1571            .context("X11: Failed to read from clipboard (primary)")
1572            .log_with_level(log::Level::Debug)
1573    }
1574
1575    fn read_from_clipboard(&self) -> Option<crate::ClipboardItem> {
1576        let state = self.0.borrow_mut();
1577        // if the last copy was from this app, return our cached item
1578        // which has metadata attached.
1579        if state
1580            .clipboard
1581            .is_owner(clipboard::ClipboardKind::Clipboard)
1582        {
1583            return state.clipboard_item.clone();
1584        }
1585        state
1586            .clipboard
1587            .get_any(clipboard::ClipboardKind::Clipboard)
1588            .context("X11: Failed to read from clipboard (clipboard)")
1589            .log_with_level(log::Level::Debug)
1590    }
1591
1592    fn run(&self) {
1593        let Some(mut event_loop) = self
1594            .0
1595            .borrow_mut()
1596            .event_loop
1597            .take()
1598            .context("X11Client::run called but it's already running")
1599            .log_err()
1600        else {
1601            return;
1602        };
1603
1604        event_loop.run(None, &mut self.clone(), |_| {}).log_err();
1605    }
1606
1607    fn active_window(&self) -> Option<AnyWindowHandle> {
1608        let state = self.0.borrow();
1609        state.keyboard_focused_window.and_then(|focused_window| {
1610            state
1611                .windows
1612                .get(&focused_window)
1613                .map(|window| window.handle())
1614        })
1615    }
1616
1617    fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
1618        let state = self.0.borrow();
1619        let root = state.xcb_connection.setup().roots[state.x_root_index].root;
1620
1621        let reply = state
1622            .xcb_connection
1623            .get_property(
1624                false,
1625                root,
1626                state.atoms._NET_CLIENT_LIST_STACKING,
1627                xproto::AtomEnum::WINDOW,
1628                0,
1629                u32::MAX,
1630            )
1631            .ok()?
1632            .reply()
1633            .ok()?;
1634
1635        let window_ids = reply
1636            .value
1637            .chunks_exact(4)
1638            .filter_map(|chunk| chunk.try_into().ok().map(u32::from_ne_bytes))
1639            .collect::<Vec<xproto::Window>>();
1640
1641        let mut handles = Vec::new();
1642
1643        // We need to reverse, since _NET_CLIENT_LIST_STACKING has
1644        // a back-to-front order.
1645        // See: https://specifications.freedesktop.org/wm-spec/1.3/ar01s03.html
1646        for window_ref in window_ids
1647            .iter()
1648            .rev()
1649            .filter_map(|&win| state.windows.get(&win))
1650        {
1651            if !window_ref.window.state.borrow().destroyed {
1652                handles.push(window_ref.handle());
1653            }
1654        }
1655
1656        Some(handles)
1657    }
1658
1659    fn window_identifier(&self) -> impl Future<Output = Option<WindowIdentifier>> + Send + 'static {
1660        let state = self.0.borrow();
1661        state
1662            .keyboard_focused_window
1663            .and_then(|focused_window| state.windows.get(&focused_window))
1664            .map(|window| window.window.x_window as u64)
1665            .map(|x_window| std::future::ready(Some(WindowIdentifier::from_xid(x_window))))
1666            .unwrap_or(std::future::ready(None))
1667    }
1668}
1669
1670impl X11ClientState {
1671    fn has_xim(&self) -> bool {
1672        self.ximc.is_some() && self.xim_handler.is_some()
1673    }
1674
1675    fn take_xim(&mut self) -> Option<(X11rbClient<Rc<XCBConnection>>, XimHandler)> {
1676        let ximc = self
1677            .ximc
1678            .take()
1679            .ok_or(anyhow!("bug: XIM connection not set"))
1680            .log_err()?;
1681        if let Some(xim_handler) = self.xim_handler.take() {
1682            Some((ximc, xim_handler))
1683        } else {
1684            self.ximc = Some(ximc);
1685            log::error!("bug: XIM handler not set");
1686            None
1687        }
1688    }
1689
1690    fn restore_xim(&mut self, ximc: X11rbClient<Rc<XCBConnection>>, xim_handler: XimHandler) {
1691        self.ximc = Some(ximc);
1692        self.xim_handler = Some(xim_handler);
1693    }
1694
1695    fn update_refresh_loop(&mut self, x_window: xproto::Window) {
1696        let Some(window_ref) = self.windows.get_mut(&x_window) else {
1697            return;
1698        };
1699        let is_visible = window_ref.is_mapped
1700            && !matches!(window_ref.last_visibility, Visibility::FULLY_OBSCURED);
1701        match (is_visible, window_ref.refresh_state.take()) {
1702            (false, refresh_state @ Some(RefreshState::Hidden { .. }))
1703            | (false, refresh_state @ None)
1704            | (true, refresh_state @ Some(RefreshState::PeriodicRefresh { .. })) => {
1705                window_ref.refresh_state = refresh_state;
1706            }
1707            (
1708                false,
1709                Some(RefreshState::PeriodicRefresh {
1710                    refresh_rate,
1711                    event_loop_token,
1712                }),
1713            ) => {
1714                self.loop_handle.remove(event_loop_token);
1715                window_ref.refresh_state = Some(RefreshState::Hidden { refresh_rate });
1716            }
1717            (true, Some(RefreshState::Hidden { refresh_rate })) => {
1718                let event_loop_token = self.start_refresh_loop(x_window, refresh_rate);
1719                let Some(window_ref) = self.windows.get_mut(&x_window) else {
1720                    return;
1721                };
1722                window_ref.refresh_state = Some(RefreshState::PeriodicRefresh {
1723                    refresh_rate,
1724                    event_loop_token,
1725                });
1726            }
1727            (true, None) => {
1728                let Some(screen_resources) = get_reply(
1729                    || "Failed to get screen resources",
1730                    self.xcb_connection
1731                        .randr_get_screen_resources_current(x_window),
1732                )
1733                .log_err() else {
1734                    return;
1735                };
1736
1737                // Ideally this would be re-queried when the window changes screens, but there
1738                // doesn't seem to be an efficient / straightforward way to do this. Should also be
1739                // updated when screen configurations change.
1740                let mode_info = screen_resources.crtcs.iter().find_map(|crtc| {
1741                    let crtc_info = self
1742                        .xcb_connection
1743                        .randr_get_crtc_info(*crtc, x11rb::CURRENT_TIME)
1744                        .ok()?
1745                        .reply()
1746                        .ok()?;
1747
1748                    screen_resources
1749                        .modes
1750                        .iter()
1751                        .find(|m| m.id == crtc_info.mode)
1752                });
1753                let refresh_rate = match mode_info {
1754                    Some(mode_info) => mode_refresh_rate(mode_info),
1755                    None => {
1756                        log::error!(
1757                            "Failed to get screen mode info from xrandr, \
1758                            defaulting to 60hz refresh rate."
1759                        );
1760                        Duration::from_micros(1_000_000 / 60)
1761                    }
1762                };
1763
1764                let event_loop_token = self.start_refresh_loop(x_window, refresh_rate);
1765                let Some(window_ref) = self.windows.get_mut(&x_window) else {
1766                    return;
1767                };
1768                window_ref.refresh_state = Some(RefreshState::PeriodicRefresh {
1769                    refresh_rate,
1770                    event_loop_token,
1771                });
1772            }
1773        }
1774    }
1775
1776    #[must_use]
1777    fn start_refresh_loop(
1778        &self,
1779        x_window: xproto::Window,
1780        refresh_rate: Duration,
1781    ) -> RegistrationToken {
1782        self.loop_handle
1783            .insert_source(calloop::timer::Timer::immediate(), {
1784                move |mut instant, (), client| {
1785                    let xcb_connection = {
1786                        let mut state = client.0.borrow_mut();
1787                        let xcb_connection = state.xcb_connection.clone();
1788                        if let Some(window) = state.windows.get_mut(&x_window) {
1789                            let expose_event_received = window.expose_event_received;
1790                            window.expose_event_received = false;
1791                            let window = window.window.clone();
1792                            drop(state);
1793                            window.refresh(RequestFrameOptions {
1794                                require_presentation: expose_event_received,
1795                                force_render: false,
1796                            });
1797                        }
1798                        xcb_connection
1799                    };
1800                    client.process_x11_events(&xcb_connection).log_err();
1801
1802                    // Take into account that some frames have been skipped
1803                    let now = Instant::now();
1804                    while instant < now {
1805                        instant += refresh_rate;
1806                    }
1807                    calloop::timer::TimeoutAction::ToInstant(instant)
1808                }
1809            })
1810            .expect("Failed to initialize window refresh timer")
1811    }
1812
1813    fn get_cursor_icon(&mut self, style: CursorStyle) -> Option<xproto::Cursor> {
1814        if let Some(cursor) = self.cursor_cache.get(&style) {
1815            return *cursor;
1816        }
1817
1818        let mut result;
1819        match style {
1820            CursorStyle::None => match create_invisible_cursor(&self.xcb_connection) {
1821                Ok(loaded_cursor) => result = Ok(loaded_cursor),
1822                Err(err) => result = Err(err.context("X11: error while creating invisible cursor")),
1823            },
1824            _ => 'outer: {
1825                let mut errors = String::new();
1826                let cursor_icon_names = style.to_icon_names();
1827                for cursor_icon_name in cursor_icon_names {
1828                    match self
1829                        .cursor_handle
1830                        .load_cursor(&self.xcb_connection, cursor_icon_name)
1831                    {
1832                        Ok(loaded_cursor) => {
1833                            if loaded_cursor != x11rb::NONE {
1834                                result = Ok(loaded_cursor);
1835                                break 'outer;
1836                            }
1837                        }
1838                        Err(err) => {
1839                            errors.push_str(&err.to_string());
1840                            errors.push('\n');
1841                        }
1842                    }
1843                }
1844                if errors.is_empty() {
1845                    result = Err(anyhow!(
1846                        "errors while loading cursor icons {:?}:\n{}",
1847                        cursor_icon_names,
1848                        errors
1849                    ));
1850                } else {
1851                    result = Err(anyhow!("did not find cursor icons {:?}", cursor_icon_names));
1852                }
1853            }
1854        };
1855
1856        let cursor = match result {
1857            Ok(cursor) => Some(cursor),
1858            Err(err) => {
1859                match self
1860                    .cursor_handle
1861                    .load_cursor(&self.xcb_connection, DEFAULT_CURSOR_ICON_NAME)
1862                {
1863                    Ok(default) => {
1864                        log_cursor_icon_warning(err.context(format!(
1865                            "X11: error loading cursor icon, falling back on default icon '{}'",
1866                            DEFAULT_CURSOR_ICON_NAME
1867                        )));
1868                        Some(default)
1869                    }
1870                    Err(default_err) => {
1871                        log_cursor_icon_warning(err.context(default_err).context(format!(
1872                            "X11: error loading default cursor fallback '{}'",
1873                            DEFAULT_CURSOR_ICON_NAME
1874                        )));
1875                        None
1876                    }
1877                }
1878            }
1879        };
1880
1881        self.cursor_cache.insert(style, cursor);
1882        cursor
1883    }
1884}
1885
1886// Adapted from:
1887// https://docs.rs/winit/0.29.11/src/winit/platform_impl/linux/x11/monitor.rs.html#103-111
1888pub fn mode_refresh_rate(mode: &randr::ModeInfo) -> Duration {
1889    if mode.dot_clock == 0 || mode.htotal == 0 || mode.vtotal == 0 {
1890        return Duration::from_millis(16);
1891    }
1892
1893    let millihertz = mode.dot_clock as u64 * 1_000 / (mode.htotal as u64 * mode.vtotal as u64);
1894    let micros = 1_000_000_000 / millihertz;
1895    log::info!("Refreshing every {}ms", micros / 1_000);
1896    Duration::from_micros(micros)
1897}
1898
1899fn fp3232_to_f32(value: xinput::Fp3232) -> f32 {
1900    value.integral as f32 + value.frac as f32 / u32::MAX as f32
1901}
1902
1903fn check_compositor_present(xcb_connection: &XCBConnection, root: u32) -> bool {
1904    // Method 1: Check for _NET_WM_CM_S{root}
1905    let atom_name = format!("_NET_WM_CM_S{}", root);
1906    let atom1 = get_reply(
1907        || format!("Failed to intern {atom_name}"),
1908        xcb_connection.intern_atom(false, atom_name.as_bytes()),
1909    );
1910    let method1 = match atom1.log_with_level(Level::Debug) {
1911        Some(reply) if reply.atom != x11rb::NONE => {
1912            let atom = reply.atom;
1913            get_reply(
1914                || format!("Failed to get {atom_name} owner"),
1915                xcb_connection.get_selection_owner(atom),
1916            )
1917            .map(|reply| reply.owner != 0)
1918            .log_with_level(Level::Debug)
1919            .unwrap_or(false)
1920        }
1921        _ => false,
1922    };
1923
1924    // Method 2: Check for _NET_WM_CM_OWNER
1925    let atom_name = "_NET_WM_CM_OWNER";
1926    let atom2 = get_reply(
1927        || format!("Failed to intern {atom_name}"),
1928        xcb_connection.intern_atom(false, atom_name.as_bytes()),
1929    );
1930    let method2 = match atom2.log_with_level(Level::Debug) {
1931        Some(reply) if reply.atom != x11rb::NONE => {
1932            let atom = reply.atom;
1933            get_reply(
1934                || format!("Failed to get {atom_name}"),
1935                xcb_connection.get_property(false, root, atom, xproto::AtomEnum::WINDOW, 0, 1),
1936            )
1937            .map(|reply| reply.value_len > 0)
1938            .unwrap_or(false)
1939        }
1940        _ => return false,
1941    };
1942
1943    // Method 3: Check for _NET_SUPPORTING_WM_CHECK
1944    let atom_name = "_NET_SUPPORTING_WM_CHECK";
1945    let atom3 = get_reply(
1946        || format!("Failed to intern {atom_name}"),
1947        xcb_connection.intern_atom(false, atom_name.as_bytes()),
1948    );
1949    let method3 = match atom3.log_with_level(Level::Debug) {
1950        Some(reply) if reply.atom != x11rb::NONE => {
1951            let atom = reply.atom;
1952            get_reply(
1953                || format!("Failed to get {atom_name}"),
1954                xcb_connection.get_property(false, root, atom, xproto::AtomEnum::WINDOW, 0, 1),
1955            )
1956            .map(|reply| reply.value_len > 0)
1957            .unwrap_or(false)
1958        }
1959        _ => return false,
1960    };
1961
1962    log::debug!(
1963        "Compositor detection: _NET_WM_CM_S?={}, _NET_WM_CM_OWNER={}, _NET_SUPPORTING_WM_CHECK={}",
1964        method1,
1965        method2,
1966        method3
1967    );
1968
1969    method1 || method2 || method3
1970}
1971
1972fn check_gtk_frame_extents_supported(
1973    xcb_connection: &XCBConnection,
1974    atoms: &XcbAtoms,
1975    root: xproto::Window,
1976) -> bool {
1977    let Some(supported_atoms) = get_reply(
1978        || "Failed to get _NET_SUPPORTED",
1979        xcb_connection.get_property(
1980            false,
1981            root,
1982            atoms._NET_SUPPORTED,
1983            xproto::AtomEnum::ATOM,
1984            0,
1985            1024,
1986        ),
1987    )
1988    .log_with_level(Level::Debug) else {
1989        return false;
1990    };
1991
1992    let supported_atom_ids: Vec<u32> = supported_atoms
1993        .value
1994        .chunks_exact(4)
1995        .filter_map(|chunk| chunk.try_into().ok().map(u32::from_ne_bytes))
1996        .collect();
1997
1998    supported_atom_ids.contains(&atoms._GTK_FRAME_EXTENTS)
1999}
2000
2001fn xdnd_is_atom_supported(atom: u32, atoms: &XcbAtoms) -> bool {
2002    atom == atoms.TEXT
2003        || atom == atoms.STRING
2004        || atom == atoms.UTF8_STRING
2005        || atom == atoms.TEXT_PLAIN
2006        || atom == atoms.TEXT_PLAIN_UTF8
2007        || atom == atoms.TextUriList
2008}
2009
2010fn xdnd_get_supported_atom(
2011    xcb_connection: &XCBConnection,
2012    supported_atoms: &XcbAtoms,
2013    target: xproto::Window,
2014) -> u32 {
2015    if let Some(reply) = get_reply(
2016        || "Failed to get XDnD supported atoms",
2017        xcb_connection.get_property(
2018            false,
2019            target,
2020            supported_atoms.XdndTypeList,
2021            AtomEnum::ANY,
2022            0,
2023            1024,
2024        ),
2025    )
2026    .log_with_level(Level::Warn)
2027        && let Some(atoms) = reply.value32()
2028    {
2029        for atom in atoms {
2030            if xdnd_is_atom_supported(atom, supported_atoms) {
2031                return atom;
2032            }
2033        }
2034    }
2035    0
2036}
2037
2038fn xdnd_send_finished(
2039    xcb_connection: &XCBConnection,
2040    atoms: &XcbAtoms,
2041    source: xproto::Window,
2042    target: xproto::Window,
2043) {
2044    let message = ClientMessageEvent {
2045        format: 32,
2046        window: target,
2047        type_: atoms.XdndFinished,
2048        data: ClientMessageData::from([source, 1, atoms.XdndActionCopy, 0, 0]),
2049        sequence: 0,
2050        response_type: xproto::CLIENT_MESSAGE_EVENT,
2051    };
2052    check_reply(
2053        || "Failed to send XDnD finished event",
2054        xcb_connection.send_event(false, target, EventMask::default(), message),
2055    )
2056    .log_err();
2057    xcb_connection.flush().log_err();
2058}
2059
2060fn xdnd_send_status(
2061    xcb_connection: &XCBConnection,
2062    atoms: &XcbAtoms,
2063    source: xproto::Window,
2064    target: xproto::Window,
2065    action: u32,
2066) {
2067    let message = ClientMessageEvent {
2068        format: 32,
2069        window: target,
2070        type_: atoms.XdndStatus,
2071        data: ClientMessageData::from([source, 1, 0, 0, action]),
2072        sequence: 0,
2073        response_type: xproto::CLIENT_MESSAGE_EVENT,
2074    };
2075    check_reply(
2076        || "Failed to send XDnD status event",
2077        xcb_connection.send_event(false, target, EventMask::default(), message),
2078    )
2079    .log_err();
2080    xcb_connection.flush().log_err();
2081}
2082
2083/// Recomputes `pointer_device_states` by querying all pointer devices.
2084/// When a device is present in `scroll_values_to_preserve`, its value for `ScrollAxisState.scroll_value` is used.
2085fn current_pointer_device_states(
2086    xcb_connection: &XCBConnection,
2087    scroll_values_to_preserve: &BTreeMap<xinput::DeviceId, PointerDeviceState>,
2088) -> Option<BTreeMap<xinput::DeviceId, PointerDeviceState>> {
2089    let devices_query_result = get_reply(
2090        || "Failed to query XInput devices",
2091        xcb_connection.xinput_xi_query_device(XINPUT_ALL_DEVICES),
2092    )
2093    .log_err()?;
2094
2095    let mut pointer_device_states = BTreeMap::new();
2096    pointer_device_states.extend(
2097        devices_query_result
2098            .infos
2099            .iter()
2100            .filter(|info| is_pointer_device(info.type_))
2101            .filter_map(|info| {
2102                let scroll_data = info
2103                    .classes
2104                    .iter()
2105                    .filter_map(|class| class.data.as_scroll())
2106                    .copied()
2107                    .rev()
2108                    .collect::<Vec<_>>();
2109                let old_state = scroll_values_to_preserve.get(&info.deviceid);
2110                let old_horizontal = old_state.map(|state| &state.horizontal);
2111                let old_vertical = old_state.map(|state| &state.vertical);
2112                let horizontal = scroll_data
2113                    .iter()
2114                    .find(|data| data.scroll_type == xinput::ScrollType::HORIZONTAL)
2115                    .map(|data| scroll_data_to_axis_state(data, old_horizontal));
2116                let vertical = scroll_data
2117                    .iter()
2118                    .find(|data| data.scroll_type == xinput::ScrollType::VERTICAL)
2119                    .map(|data| scroll_data_to_axis_state(data, old_vertical));
2120                if horizontal.is_none() && vertical.is_none() {
2121                    None
2122                } else {
2123                    Some((
2124                        info.deviceid,
2125                        PointerDeviceState {
2126                            horizontal: horizontal.unwrap_or_else(Default::default),
2127                            vertical: vertical.unwrap_or_else(Default::default),
2128                        },
2129                    ))
2130                }
2131            }),
2132    );
2133    if pointer_device_states.is_empty() {
2134        log::error!("Found no xinput mouse pointers.");
2135    }
2136    Some(pointer_device_states)
2137}
2138
2139/// Returns true if the device is a pointer device. Does not include pointer device groups.
2140fn is_pointer_device(type_: xinput::DeviceType) -> bool {
2141    type_ == xinput::DeviceType::SLAVE_POINTER
2142}
2143
2144fn scroll_data_to_axis_state(
2145    data: &xinput::DeviceClassDataScroll,
2146    old_axis_state_with_valid_scroll_value: Option<&ScrollAxisState>,
2147) -> ScrollAxisState {
2148    ScrollAxisState {
2149        valuator_number: Some(data.number),
2150        multiplier: SCROLL_LINES / fp3232_to_f32(data.increment),
2151        scroll_value: old_axis_state_with_valid_scroll_value.and_then(|state| state.scroll_value),
2152    }
2153}
2154
2155fn reset_all_pointer_device_scroll_positions(
2156    pointer_device_states: &mut BTreeMap<xinput::DeviceId, PointerDeviceState>,
2157) {
2158    pointer_device_states
2159        .iter_mut()
2160        .for_each(|(_, device_state)| reset_pointer_device_scroll_positions(device_state));
2161}
2162
2163fn reset_pointer_device_scroll_positions(pointer: &mut PointerDeviceState) {
2164    pointer.horizontal.scroll_value = None;
2165    pointer.vertical.scroll_value = None;
2166}
2167
2168/// Returns the scroll delta for a smooth scrolling motion event, or `None` if no scroll data is present.
2169fn get_scroll_delta_and_update_state(
2170    pointer: &mut PointerDeviceState,
2171    event: &xinput::MotionEvent,
2172) -> Option<Point<f32>> {
2173    let delta_x = get_axis_scroll_delta_and_update_state(event, &mut pointer.horizontal);
2174    let delta_y = get_axis_scroll_delta_and_update_state(event, &mut pointer.vertical);
2175    if delta_x.is_some() || delta_y.is_some() {
2176        Some(Point::new(delta_x.unwrap_or(0.0), delta_y.unwrap_or(0.0)))
2177    } else {
2178        None
2179    }
2180}
2181
2182fn get_axis_scroll_delta_and_update_state(
2183    event: &xinput::MotionEvent,
2184    axis: &mut ScrollAxisState,
2185) -> Option<f32> {
2186    let axis_index = get_valuator_axis_index(&event.valuator_mask, axis.valuator_number?)?;
2187    if let Some(axis_value) = event.axisvalues.get(axis_index) {
2188        let new_scroll = fp3232_to_f32(*axis_value);
2189        let delta_scroll = axis
2190            .scroll_value
2191            .map(|old_scroll| (old_scroll - new_scroll) * axis.multiplier);
2192        axis.scroll_value = Some(new_scroll);
2193        delta_scroll
2194    } else {
2195        log::error!("Encountered invalid XInput valuator_mask, scrolling may not work properly.");
2196        None
2197    }
2198}
2199
2200fn make_scroll_wheel_event(
2201    position: Point<Pixels>,
2202    scroll_delta: Point<f32>,
2203    modifiers: Modifiers,
2204) -> crate::ScrollWheelEvent {
2205    // When shift is held down, vertical scrolling turns into horizontal scrolling.
2206    let delta = if modifiers.shift {
2207        Point {
2208            x: scroll_delta.y,
2209            y: 0.0,
2210        }
2211    } else {
2212        scroll_delta
2213    };
2214    crate::ScrollWheelEvent {
2215        position,
2216        delta: ScrollDelta::Lines(delta),
2217        modifiers,
2218        touch_phase: TouchPhase::default(),
2219    }
2220}
2221
2222fn create_invisible_cursor(
2223    connection: &XCBConnection,
2224) -> anyhow::Result<crate::platform::linux::x11::client::xproto::Cursor> {
2225    let empty_pixmap = connection.generate_id()?;
2226    let root = connection.setup().roots[0].root;
2227    connection.create_pixmap(1, empty_pixmap, root, 1, 1)?;
2228
2229    let cursor = connection.generate_id()?;
2230    connection.create_cursor(cursor, empty_pixmap, empty_pixmap, 0, 0, 0, 0, 0, 0, 0, 0)?;
2231
2232    connection.free_pixmap(empty_pixmap)?;
2233
2234    xcb_flush(connection);
2235    Ok(cursor)
2236}
2237
2238enum DpiMode {
2239    Randr,
2240    Scale(f32),
2241    NotSet,
2242}
2243
2244fn get_scale_factor(
2245    connection: &XCBConnection,
2246    resource_database: &Database,
2247    screen_index: usize,
2248) -> f32 {
2249    let env_dpi = std::env::var(GPUI_X11_SCALE_FACTOR_ENV)
2250        .ok()
2251        .map(|var| {
2252            if var.to_lowercase() == "randr" {
2253                DpiMode::Randr
2254            } else if let Ok(scale) = var.parse::<f32>() {
2255                if valid_scale_factor(scale) {
2256                    DpiMode::Scale(scale)
2257                } else {
2258                    panic!(
2259                        "`{}` must be a positive normal number or `randr`. Got `{}`",
2260                        GPUI_X11_SCALE_FACTOR_ENV, var
2261                    );
2262                }
2263            } else if var.is_empty() {
2264                DpiMode::NotSet
2265            } else {
2266                panic!(
2267                    "`{}` must be a positive number or `randr`. Got `{}`",
2268                    GPUI_X11_SCALE_FACTOR_ENV, var
2269                );
2270            }
2271        })
2272        .unwrap_or(DpiMode::NotSet);
2273
2274    match env_dpi {
2275        DpiMode::Scale(scale) => {
2276            log::info!(
2277                "Using scale factor from {}: {}",
2278                GPUI_X11_SCALE_FACTOR_ENV,
2279                scale
2280            );
2281            return scale;
2282        }
2283        DpiMode::Randr => {
2284            if let Some(scale) = get_randr_scale_factor(connection, screen_index) {
2285                log::info!(
2286                    "Using RandR scale factor from {}=randr: {}",
2287                    GPUI_X11_SCALE_FACTOR_ENV,
2288                    scale
2289                );
2290                return scale;
2291            }
2292            log::warn!("Failed to calculate RandR scale factor, falling back to default");
2293            return 1.0;
2294        }
2295        DpiMode::NotSet => {}
2296    }
2297
2298    // TODO: Use scale factor from XSettings here
2299
2300    if let Some(dpi) = resource_database
2301        .get_value::<f32>("Xft.dpi", "Xft.dpi")
2302        .ok()
2303        .flatten()
2304    {
2305        let scale = dpi / 96.0; // base dpi
2306        log::info!("Using scale factor from Xft.dpi: {}", scale);
2307        return scale;
2308    }
2309
2310    if let Some(scale) = get_randr_scale_factor(connection, screen_index) {
2311        log::info!("Using RandR scale factor: {}", scale);
2312        return scale;
2313    }
2314
2315    log::info!("Using default scale factor: 1.0");
2316    1.0
2317}
2318
2319fn get_randr_scale_factor(connection: &XCBConnection, screen_index: usize) -> Option<f32> {
2320    let root = connection.setup().roots.get(screen_index)?.root;
2321
2322    let version_cookie = connection.randr_query_version(1, 6).ok()?;
2323    let version_reply = version_cookie.reply().ok()?;
2324    if version_reply.major_version < 1
2325        || (version_reply.major_version == 1 && version_reply.minor_version < 5)
2326    {
2327        return legacy_get_randr_scale_factor(connection, root); // for randr <1.5
2328    }
2329
2330    let monitors_cookie = connection.randr_get_monitors(root, true).ok()?; // true for active only
2331    let monitors_reply = monitors_cookie.reply().ok()?;
2332
2333    let mut fallback_scale: Option<f32> = None;
2334    for monitor in monitors_reply.monitors {
2335        if monitor.width_in_millimeters == 0 || monitor.height_in_millimeters == 0 {
2336            continue;
2337        }
2338        let scale_factor = get_dpi_factor(
2339            (monitor.width as u32, monitor.height as u32),
2340            (
2341                monitor.width_in_millimeters as u64,
2342                monitor.height_in_millimeters as u64,
2343            ),
2344        );
2345        if monitor.primary {
2346            return Some(scale_factor);
2347        } else if fallback_scale.is_none() {
2348            fallback_scale = Some(scale_factor);
2349        }
2350    }
2351
2352    fallback_scale
2353}
2354
2355fn legacy_get_randr_scale_factor(connection: &XCBConnection, root: u32) -> Option<f32> {
2356    let primary_cookie = connection.randr_get_output_primary(root).ok()?;
2357    let primary_reply = primary_cookie.reply().ok()?;
2358    let primary_output = primary_reply.output;
2359
2360    let primary_output_cookie = connection
2361        .randr_get_output_info(primary_output, x11rb::CURRENT_TIME)
2362        .ok()?;
2363    let primary_output_info = primary_output_cookie.reply().ok()?;
2364
2365    // try primary
2366    if primary_output_info.connection == randr::Connection::CONNECTED
2367        && primary_output_info.mm_width > 0
2368        && primary_output_info.mm_height > 0
2369        && primary_output_info.crtc != 0
2370    {
2371        let crtc_cookie = connection
2372            .randr_get_crtc_info(primary_output_info.crtc, x11rb::CURRENT_TIME)
2373            .ok()?;
2374        let crtc_info = crtc_cookie.reply().ok()?;
2375
2376        if crtc_info.width > 0 && crtc_info.height > 0 {
2377            let scale_factor = get_dpi_factor(
2378                (crtc_info.width as u32, crtc_info.height as u32),
2379                (
2380                    primary_output_info.mm_width as u64,
2381                    primary_output_info.mm_height as u64,
2382                ),
2383            );
2384            return Some(scale_factor);
2385        }
2386    }
2387
2388    // fallback: full scan
2389    let resources_cookie = connection.randr_get_screen_resources_current(root).ok()?;
2390    let screen_resources = resources_cookie.reply().ok()?;
2391
2392    let mut crtc_cookies = Vec::with_capacity(screen_resources.crtcs.len());
2393    for &crtc in &screen_resources.crtcs {
2394        if let Ok(cookie) = connection.randr_get_crtc_info(crtc, x11rb::CURRENT_TIME) {
2395            crtc_cookies.push((crtc, cookie));
2396        }
2397    }
2398
2399    let mut crtc_infos: HashMap<randr::Crtc, randr::GetCrtcInfoReply> = HashMap::default();
2400    let mut valid_outputs: HashSet<randr::Output> = HashSet::new();
2401    for (crtc, cookie) in crtc_cookies {
2402        if let Ok(reply) = cookie.reply()
2403            && reply.width > 0
2404            && reply.height > 0
2405            && !reply.outputs.is_empty()
2406        {
2407            crtc_infos.insert(crtc, reply.clone());
2408            valid_outputs.extend(&reply.outputs);
2409        }
2410    }
2411
2412    if valid_outputs.is_empty() {
2413        return None;
2414    }
2415
2416    let mut output_cookies = Vec::with_capacity(valid_outputs.len());
2417    for &output in &valid_outputs {
2418        if let Ok(cookie) = connection.randr_get_output_info(output, x11rb::CURRENT_TIME) {
2419            output_cookies.push((output, cookie));
2420        }
2421    }
2422    let mut output_infos: HashMap<randr::Output, randr::GetOutputInfoReply> = HashMap::default();
2423    for (output, cookie) in output_cookies {
2424        if let Ok(reply) = cookie.reply() {
2425            output_infos.insert(output, reply);
2426        }
2427    }
2428
2429    let mut fallback_scale: Option<f32> = None;
2430    for crtc_info in crtc_infos.values() {
2431        for &output in &crtc_info.outputs {
2432            if let Some(output_info) = output_infos.get(&output) {
2433                if output_info.connection != randr::Connection::CONNECTED {
2434                    continue;
2435                }
2436
2437                if output_info.mm_width == 0 || output_info.mm_height == 0 {
2438                    continue;
2439                }
2440
2441                let scale_factor = get_dpi_factor(
2442                    (crtc_info.width as u32, crtc_info.height as u32),
2443                    (output_info.mm_width as u64, output_info.mm_height as u64),
2444                );
2445
2446                if output != primary_output && fallback_scale.is_none() {
2447                    fallback_scale = Some(scale_factor);
2448                }
2449            }
2450        }
2451    }
2452
2453    fallback_scale
2454}
2455
2456fn get_dpi_factor((width_px, height_px): (u32, u32), (width_mm, height_mm): (u64, u64)) -> f32 {
2457    let ppmm = ((width_px as f64 * height_px as f64) / (width_mm as f64 * height_mm as f64)).sqrt(); // pixels per mm
2458
2459    const MM_PER_INCH: f64 = 25.4;
2460    const BASE_DPI: f64 = 96.0;
2461    const QUANTIZE_STEP: f64 = 12.0; // e.g. 1.25 = 15/12, 1.5 = 18/12, 1.75 = 21/12, 2.0 = 24/12
2462    const MIN_SCALE: f64 = 1.0;
2463    const MAX_SCALE: f64 = 20.0;
2464
2465    let dpi_factor =
2466        ((ppmm * (QUANTIZE_STEP * MM_PER_INCH / BASE_DPI)).round() / QUANTIZE_STEP).max(MIN_SCALE);
2467
2468    let validated_factor = if dpi_factor <= MAX_SCALE {
2469        dpi_factor
2470    } else {
2471        MIN_SCALE
2472    };
2473
2474    if valid_scale_factor(validated_factor as f32) {
2475        validated_factor as f32
2476    } else {
2477        log::warn!(
2478            "Calculated DPI factor {} is invalid, using 1.0",
2479            validated_factor
2480        );
2481        1.0
2482    }
2483}
2484
2485#[inline]
2486fn valid_scale_factor(scale_factor: f32) -> bool {
2487    scale_factor.is_sign_positive() && scale_factor.is_normal()
2488}