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