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        let keystroke = state.pre_key_char_down.take();
1320        state.composing = false;
1321        drop(state);
1322        if let Some(mut keystroke) = keystroke {
1323            keystroke.key_char = Some(text);
1324            window.handle_input(PlatformInput::KeyDown(crate::KeyDownEvent {
1325                keystroke,
1326                is_held: false,
1327            }));
1328        }
1329
1330        Some(())
1331    }
1332
1333    fn xim_handle_preedit(&self, window: xproto::Window, text: String) -> Option<()> {
1334        let Some(window) = self.get_window(window) else {
1335            log::error!("bug: Failed to get window for XIM preedit");
1336            return None;
1337        };
1338
1339        let mut state = self.0.borrow_mut();
1340        let (mut ximc, mut xim_handler) = state.take_xim()?;
1341        state.composing = !text.is_empty();
1342        drop(state);
1343        window.handle_ime_preedit(text);
1344
1345        if let Some(scaled_area) = window.get_ime_area() {
1346            let ic_attributes = ximc
1347                .build_ic_attributes()
1348                .push(
1349                    xim::AttributeName::InputStyle,
1350                    xim::InputStyle::PREEDIT_CALLBACKS,
1351                )
1352                .push(xim::AttributeName::ClientWindow, xim_handler.window)
1353                .push(xim::AttributeName::FocusWindow, xim_handler.window)
1354                .nested_list(xim::AttributeName::PreeditAttributes, |b| {
1355                    b.push(
1356                        xim::AttributeName::SpotLocation,
1357                        xim::Point {
1358                            x: u32::from(scaled_area.origin.x + scaled_area.size.width) as i16,
1359                            y: u32::from(scaled_area.origin.y + scaled_area.size.height) as i16,
1360                        },
1361                    );
1362                })
1363                .build();
1364            ximc.set_ic_values(xim_handler.im_id, xim_handler.ic_id, ic_attributes)
1365                .ok();
1366        }
1367        let mut state = self.0.borrow_mut();
1368        state.restore_xim(ximc, xim_handler);
1369        drop(state);
1370        Some(())
1371    }
1372
1373    fn handle_keyboard_layout_change(&self) {
1374        let mut state = self.0.borrow_mut();
1375        let layout_idx = state.xkb.serialize_layout(STATE_LAYOUT_EFFECTIVE);
1376        let keymap = state.xkb.get_keymap();
1377        let layout_name = keymap.layout_get_name(layout_idx);
1378        if layout_name != state.keyboard_layout.name() {
1379            state.keyboard_layout = LinuxKeyboardLayout::new(layout_name.to_string().into());
1380            if let Some(mut callback) = state.common.callbacks.keyboard_layout_change.take() {
1381                drop(state);
1382                callback();
1383                state = self.0.borrow_mut();
1384                state.common.callbacks.keyboard_layout_change = Some(callback);
1385            }
1386        }
1387    }
1388}
1389
1390impl LinuxClient for X11Client {
1391    fn compositor_name(&self) -> &'static str {
1392        "X11"
1393    }
1394
1395    fn with_common<R>(&self, f: impl FnOnce(&mut LinuxCommon) -> R) -> R {
1396        f(&mut self.0.borrow_mut().common)
1397    }
1398
1399    fn keyboard_layout(&self) -> Box<dyn PlatformKeyboardLayout> {
1400        let state = self.0.borrow();
1401        Box::new(state.keyboard_layout.clone())
1402    }
1403
1404    fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
1405        let state = self.0.borrow();
1406        let setup = state.xcb_connection.setup();
1407        setup
1408            .roots
1409            .iter()
1410            .enumerate()
1411            .filter_map(|(root_id, _)| {
1412                Some(Rc::new(
1413                    X11Display::new(&state.xcb_connection, state.scale_factor, root_id).ok()?,
1414                ) as Rc<dyn PlatformDisplay>)
1415            })
1416            .collect()
1417    }
1418
1419    fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
1420        let state = self.0.borrow();
1421        X11Display::new(
1422            &state.xcb_connection,
1423            state.scale_factor,
1424            state.x_root_index,
1425        )
1426        .log_err()
1427        .map(|display| Rc::new(display) as Rc<dyn PlatformDisplay>)
1428    }
1429
1430    fn display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>> {
1431        let state = self.0.borrow();
1432
1433        Some(Rc::new(
1434            X11Display::new(&state.xcb_connection, state.scale_factor, id.0 as usize).ok()?,
1435        ))
1436    }
1437
1438    #[cfg(feature = "screen-capture")]
1439    fn is_screen_capture_supported(&self) -> bool {
1440        true
1441    }
1442
1443    #[cfg(feature = "screen-capture")]
1444    fn screen_capture_sources(
1445        &self,
1446    ) -> futures::channel::oneshot::Receiver<anyhow::Result<Vec<Rc<dyn crate::ScreenCaptureSource>>>>
1447    {
1448        crate::platform::scap_screen_capture::scap_screen_sources(
1449            &self.0.borrow().common.foreground_executor,
1450        )
1451    }
1452
1453    fn open_window(
1454        &self,
1455        handle: AnyWindowHandle,
1456        params: WindowParams,
1457    ) -> anyhow::Result<Box<dyn PlatformWindow>> {
1458        let mut state = self.0.borrow_mut();
1459        let x_window = state
1460            .xcb_connection
1461            .generate_id()
1462            .context("X11: Failed to generate window ID")?;
1463
1464        let window = X11Window::new(
1465            handle,
1466            X11ClientStatePtr(Rc::downgrade(&self.0)),
1467            state.common.foreground_executor.clone(),
1468            &state.gpu_context,
1469            params,
1470            &state.xcb_connection,
1471            state.client_side_decorations_supported,
1472            state.x_root_index,
1473            x_window,
1474            &state.atoms,
1475            state.scale_factor,
1476            state.common.appearance,
1477        )?;
1478        check_reply(
1479            || "Failed to set XdndAware property",
1480            state.xcb_connection.change_property32(
1481                xproto::PropMode::REPLACE,
1482                x_window,
1483                state.atoms.XdndAware,
1484                state.atoms.XA_ATOM,
1485                &[5],
1486            ),
1487        )
1488        .log_err();
1489        xcb_flush(&state.xcb_connection);
1490
1491        let window_ref = WindowRef {
1492            window: window.0.clone(),
1493            refresh_state: None,
1494            expose_event_received: false,
1495            last_visibility: Visibility::UNOBSCURED,
1496            is_mapped: false,
1497        };
1498
1499        state.windows.insert(x_window, window_ref);
1500        Ok(Box::new(window))
1501    }
1502
1503    fn set_cursor_style(&self, style: CursorStyle) {
1504        let mut state = self.0.borrow_mut();
1505        let Some(focused_window) = state.mouse_focused_window else {
1506            return;
1507        };
1508        let current_style = state
1509            .cursor_styles
1510            .get(&focused_window)
1511            .unwrap_or(&CursorStyle::Arrow);
1512        if *current_style == style {
1513            return;
1514        }
1515
1516        let Some(cursor) = state.get_cursor_icon(style) else {
1517            return;
1518        };
1519
1520        state.cursor_styles.insert(focused_window, style);
1521        check_reply(
1522            || "Failed to set cursor style",
1523            state.xcb_connection.change_window_attributes(
1524                focused_window,
1525                &ChangeWindowAttributesAux {
1526                    cursor: Some(cursor),
1527                    ..Default::default()
1528                },
1529            ),
1530        )
1531        .log_err();
1532        state.xcb_connection.flush().log_err();
1533    }
1534
1535    fn open_uri(&self, uri: &str) {
1536        #[cfg(any(feature = "wayland", feature = "x11"))]
1537        open_uri_internal(self.background_executor(), uri, None);
1538    }
1539
1540    fn reveal_path(&self, path: PathBuf) {
1541        #[cfg(any(feature = "x11", feature = "wayland"))]
1542        reveal_path_internal(self.background_executor(), path, None);
1543    }
1544
1545    fn write_to_primary(&self, item: crate::ClipboardItem) {
1546        let state = self.0.borrow_mut();
1547        state
1548            .clipboard
1549            .set_text(
1550                std::borrow::Cow::Owned(item.text().unwrap_or_default()),
1551                clipboard::ClipboardKind::Primary,
1552                clipboard::WaitConfig::None,
1553            )
1554            .context("X11 Failed to write to clipboard (primary)")
1555            .log_with_level(log::Level::Debug);
1556    }
1557
1558    fn write_to_clipboard(&self, item: crate::ClipboardItem) {
1559        let mut state = self.0.borrow_mut();
1560        state
1561            .clipboard
1562            .set_text(
1563                std::borrow::Cow::Owned(item.text().unwrap_or_default()),
1564                clipboard::ClipboardKind::Clipboard,
1565                clipboard::WaitConfig::None,
1566            )
1567            .context("X11: Failed to write to clipboard (clipboard)")
1568            .log_with_level(log::Level::Debug);
1569        state.clipboard_item.replace(item);
1570    }
1571
1572    fn read_from_primary(&self) -> Option<crate::ClipboardItem> {
1573        let state = self.0.borrow_mut();
1574        state
1575            .clipboard
1576            .get_any(clipboard::ClipboardKind::Primary)
1577            .context("X11: Failed to read from clipboard (primary)")
1578            .log_with_level(log::Level::Debug)
1579    }
1580
1581    fn read_from_clipboard(&self) -> Option<crate::ClipboardItem> {
1582        let state = self.0.borrow_mut();
1583        // if the last copy was from this app, return our cached item
1584        // which has metadata attached.
1585        if state
1586            .clipboard
1587            .is_owner(clipboard::ClipboardKind::Clipboard)
1588        {
1589            return state.clipboard_item.clone();
1590        }
1591        state
1592            .clipboard
1593            .get_any(clipboard::ClipboardKind::Clipboard)
1594            .context("X11: Failed to read from clipboard (clipboard)")
1595            .log_with_level(log::Level::Debug)
1596    }
1597
1598    fn run(&self) {
1599        let Some(mut event_loop) = self
1600            .0
1601            .borrow_mut()
1602            .event_loop
1603            .take()
1604            .context("X11Client::run called but it's already running")
1605            .log_err()
1606        else {
1607            return;
1608        };
1609
1610        event_loop.run(None, &mut self.clone(), |_| {}).log_err();
1611    }
1612
1613    fn active_window(&self) -> Option<AnyWindowHandle> {
1614        let state = self.0.borrow();
1615        state.keyboard_focused_window.and_then(|focused_window| {
1616            state
1617                .windows
1618                .get(&focused_window)
1619                .map(|window| window.handle())
1620        })
1621    }
1622
1623    fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
1624        let state = self.0.borrow();
1625        let root = state.xcb_connection.setup().roots[state.x_root_index].root;
1626
1627        let reply = state
1628            .xcb_connection
1629            .get_property(
1630                false,
1631                root,
1632                state.atoms._NET_CLIENT_LIST_STACKING,
1633                xproto::AtomEnum::WINDOW,
1634                0,
1635                u32::MAX,
1636            )
1637            .ok()?
1638            .reply()
1639            .ok()?;
1640
1641        let window_ids = reply
1642            .value
1643            .chunks_exact(4)
1644            .filter_map(|chunk| chunk.try_into().ok().map(u32::from_ne_bytes))
1645            .collect::<Vec<xproto::Window>>();
1646
1647        let mut handles = Vec::new();
1648
1649        // We need to reverse, since _NET_CLIENT_LIST_STACKING has
1650        // a back-to-front order.
1651        // See: https://specifications.freedesktop.org/wm-spec/1.3/ar01s03.html
1652        for window_ref in window_ids
1653            .iter()
1654            .rev()
1655            .filter_map(|&win| state.windows.get(&win))
1656        {
1657            if !window_ref.window.state.borrow().destroyed {
1658                handles.push(window_ref.handle());
1659            }
1660        }
1661
1662        Some(handles)
1663    }
1664
1665    fn window_identifier(&self) -> impl Future<Output = Option<WindowIdentifier>> + Send + 'static {
1666        let state = self.0.borrow();
1667        state
1668            .keyboard_focused_window
1669            .and_then(|focused_window| state.windows.get(&focused_window))
1670            .map(|window| window.window.x_window as u64)
1671            .map(|x_window| std::future::ready(Some(WindowIdentifier::from_xid(x_window))))
1672            .unwrap_or(std::future::ready(None))
1673    }
1674}
1675
1676impl X11ClientState {
1677    fn has_xim(&self) -> bool {
1678        self.ximc.is_some() && self.xim_handler.is_some()
1679    }
1680
1681    fn take_xim(&mut self) -> Option<(X11rbClient<Rc<XCBConnection>>, XimHandler)> {
1682        let ximc = self
1683            .ximc
1684            .take()
1685            .ok_or(anyhow!("bug: XIM connection not set"))
1686            .log_err()?;
1687        if let Some(xim_handler) = self.xim_handler.take() {
1688            Some((ximc, xim_handler))
1689        } else {
1690            self.ximc = Some(ximc);
1691            log::error!("bug: XIM handler not set");
1692            None
1693        }
1694    }
1695
1696    fn restore_xim(&mut self, ximc: X11rbClient<Rc<XCBConnection>>, xim_handler: XimHandler) {
1697        self.ximc = Some(ximc);
1698        self.xim_handler = Some(xim_handler);
1699    }
1700
1701    fn update_refresh_loop(&mut self, x_window: xproto::Window) {
1702        let Some(window_ref) = self.windows.get_mut(&x_window) else {
1703            return;
1704        };
1705        let is_visible = window_ref.is_mapped
1706            && !matches!(window_ref.last_visibility, Visibility::FULLY_OBSCURED);
1707        match (is_visible, window_ref.refresh_state.take()) {
1708            (false, refresh_state @ Some(RefreshState::Hidden { .. }))
1709            | (false, refresh_state @ None)
1710            | (true, refresh_state @ Some(RefreshState::PeriodicRefresh { .. })) => {
1711                window_ref.refresh_state = refresh_state;
1712            }
1713            (
1714                false,
1715                Some(RefreshState::PeriodicRefresh {
1716                    refresh_rate,
1717                    event_loop_token,
1718                }),
1719            ) => {
1720                self.loop_handle.remove(event_loop_token);
1721                window_ref.refresh_state = Some(RefreshState::Hidden { refresh_rate });
1722            }
1723            (true, Some(RefreshState::Hidden { refresh_rate })) => {
1724                let event_loop_token = self.start_refresh_loop(x_window, refresh_rate);
1725                let Some(window_ref) = self.windows.get_mut(&x_window) else {
1726                    return;
1727                };
1728                window_ref.refresh_state = Some(RefreshState::PeriodicRefresh {
1729                    refresh_rate,
1730                    event_loop_token,
1731                });
1732            }
1733            (true, None) => {
1734                let Some(screen_resources) = get_reply(
1735                    || "Failed to get screen resources",
1736                    self.xcb_connection
1737                        .randr_get_screen_resources_current(x_window),
1738                )
1739                .log_err() else {
1740                    return;
1741                };
1742
1743                // Ideally this would be re-queried when the window changes screens, but there
1744                // doesn't seem to be an efficient / straightforward way to do this. Should also be
1745                // updated when screen configurations change.
1746                let mode_info = screen_resources.crtcs.iter().find_map(|crtc| {
1747                    let crtc_info = self
1748                        .xcb_connection
1749                        .randr_get_crtc_info(*crtc, x11rb::CURRENT_TIME)
1750                        .ok()?
1751                        .reply()
1752                        .ok()?;
1753
1754                    screen_resources
1755                        .modes
1756                        .iter()
1757                        .find(|m| m.id == crtc_info.mode)
1758                });
1759                let refresh_rate = match mode_info {
1760                    Some(mode_info) => mode_refresh_rate(mode_info),
1761                    None => {
1762                        log::error!(
1763                            "Failed to get screen mode info from xrandr, \
1764                            defaulting to 60hz refresh rate."
1765                        );
1766                        Duration::from_micros(1_000_000 / 60)
1767                    }
1768                };
1769
1770                let event_loop_token = self.start_refresh_loop(x_window, refresh_rate);
1771                let Some(window_ref) = self.windows.get_mut(&x_window) else {
1772                    return;
1773                };
1774                window_ref.refresh_state = Some(RefreshState::PeriodicRefresh {
1775                    refresh_rate,
1776                    event_loop_token,
1777                });
1778            }
1779        }
1780    }
1781
1782    #[must_use]
1783    fn start_refresh_loop(
1784        &self,
1785        x_window: xproto::Window,
1786        refresh_rate: Duration,
1787    ) -> RegistrationToken {
1788        self.loop_handle
1789            .insert_source(calloop::timer::Timer::immediate(), {
1790                move |mut instant, (), client| {
1791                    let xcb_connection = {
1792                        let mut state = client.0.borrow_mut();
1793                        let xcb_connection = state.xcb_connection.clone();
1794                        if let Some(window) = state.windows.get_mut(&x_window) {
1795                            let expose_event_received = window.expose_event_received;
1796                            window.expose_event_received = false;
1797                            let window = window.window.clone();
1798                            drop(state);
1799                            window.refresh(RequestFrameOptions {
1800                                require_presentation: expose_event_received,
1801                                force_render: false,
1802                            });
1803                        }
1804                        xcb_connection
1805                    };
1806                    client.process_x11_events(&xcb_connection).log_err();
1807
1808                    // Take into account that some frames have been skipped
1809                    let now = Instant::now();
1810                    while instant < now {
1811                        instant += refresh_rate;
1812                    }
1813                    calloop::timer::TimeoutAction::ToInstant(instant)
1814                }
1815            })
1816            .expect("Failed to initialize window refresh timer")
1817    }
1818
1819    fn get_cursor_icon(&mut self, style: CursorStyle) -> Option<xproto::Cursor> {
1820        if let Some(cursor) = self.cursor_cache.get(&style) {
1821            return *cursor;
1822        }
1823
1824        let mut result;
1825        match style {
1826            CursorStyle::None => match create_invisible_cursor(&self.xcb_connection) {
1827                Ok(loaded_cursor) => result = Ok(loaded_cursor),
1828                Err(err) => result = Err(err.context("X11: error while creating invisible cursor")),
1829            },
1830            _ => 'outer: {
1831                let mut errors = String::new();
1832                let cursor_icon_names = style.to_icon_names();
1833                for cursor_icon_name in cursor_icon_names {
1834                    match self
1835                        .cursor_handle
1836                        .load_cursor(&self.xcb_connection, cursor_icon_name)
1837                    {
1838                        Ok(loaded_cursor) => {
1839                            if loaded_cursor != x11rb::NONE {
1840                                result = Ok(loaded_cursor);
1841                                break 'outer;
1842                            }
1843                        }
1844                        Err(err) => {
1845                            errors.push_str(&err.to_string());
1846                            errors.push('\n');
1847                        }
1848                    }
1849                }
1850                if errors.is_empty() {
1851                    result = Err(anyhow!(
1852                        "errors while loading cursor icons {:?}:\n{}",
1853                        cursor_icon_names,
1854                        errors
1855                    ));
1856                } else {
1857                    result = Err(anyhow!("did not find cursor icons {:?}", cursor_icon_names));
1858                }
1859            }
1860        };
1861
1862        let cursor = match result {
1863            Ok(cursor) => Some(cursor),
1864            Err(err) => {
1865                match self
1866                    .cursor_handle
1867                    .load_cursor(&self.xcb_connection, DEFAULT_CURSOR_ICON_NAME)
1868                {
1869                    Ok(default) => {
1870                        log_cursor_icon_warning(err.context(format!(
1871                            "X11: error loading cursor icon, falling back on default icon '{}'",
1872                            DEFAULT_CURSOR_ICON_NAME
1873                        )));
1874                        Some(default)
1875                    }
1876                    Err(default_err) => {
1877                        log_cursor_icon_warning(err.context(default_err).context(format!(
1878                            "X11: error loading default cursor fallback '{}'",
1879                            DEFAULT_CURSOR_ICON_NAME
1880                        )));
1881                        None
1882                    }
1883                }
1884            }
1885        };
1886
1887        self.cursor_cache.insert(style, cursor);
1888        cursor
1889    }
1890}
1891
1892// Adapted from:
1893// https://docs.rs/winit/0.29.11/src/winit/platform_impl/linux/x11/monitor.rs.html#103-111
1894pub fn mode_refresh_rate(mode: &randr::ModeInfo) -> Duration {
1895    if mode.dot_clock == 0 || mode.htotal == 0 || mode.vtotal == 0 {
1896        return Duration::from_millis(16);
1897    }
1898
1899    let millihertz = mode.dot_clock as u64 * 1_000 / (mode.htotal as u64 * mode.vtotal as u64);
1900    let micros = 1_000_000_000 / millihertz;
1901    log::info!("Refreshing every {}ms", micros / 1_000);
1902    Duration::from_micros(micros)
1903}
1904
1905fn fp3232_to_f32(value: xinput::Fp3232) -> f32 {
1906    value.integral as f32 + value.frac as f32 / u32::MAX as f32
1907}
1908
1909fn check_compositor_present(xcb_connection: &XCBConnection, root: u32) -> bool {
1910    // Method 1: Check for _NET_WM_CM_S{root}
1911    let atom_name = format!("_NET_WM_CM_S{}", root);
1912    let atom1 = get_reply(
1913        || format!("Failed to intern {atom_name}"),
1914        xcb_connection.intern_atom(false, atom_name.as_bytes()),
1915    );
1916    let method1 = match atom1.log_with_level(Level::Debug) {
1917        Some(reply) if reply.atom != x11rb::NONE => {
1918            let atom = reply.atom;
1919            get_reply(
1920                || format!("Failed to get {atom_name} owner"),
1921                xcb_connection.get_selection_owner(atom),
1922            )
1923            .map(|reply| reply.owner != 0)
1924            .log_with_level(Level::Debug)
1925            .unwrap_or(false)
1926        }
1927        _ => false,
1928    };
1929
1930    // Method 2: Check for _NET_WM_CM_OWNER
1931    let atom_name = "_NET_WM_CM_OWNER";
1932    let atom2 = get_reply(
1933        || format!("Failed to intern {atom_name}"),
1934        xcb_connection.intern_atom(false, atom_name.as_bytes()),
1935    );
1936    let method2 = match atom2.log_with_level(Level::Debug) {
1937        Some(reply) if reply.atom != x11rb::NONE => {
1938            let atom = reply.atom;
1939            get_reply(
1940                || format!("Failed to get {atom_name}"),
1941                xcb_connection.get_property(false, root, atom, xproto::AtomEnum::WINDOW, 0, 1),
1942            )
1943            .map(|reply| reply.value_len > 0)
1944            .unwrap_or(false)
1945        }
1946        _ => return false,
1947    };
1948
1949    // Method 3: Check for _NET_SUPPORTING_WM_CHECK
1950    let atom_name = "_NET_SUPPORTING_WM_CHECK";
1951    let atom3 = get_reply(
1952        || format!("Failed to intern {atom_name}"),
1953        xcb_connection.intern_atom(false, atom_name.as_bytes()),
1954    );
1955    let method3 = match atom3.log_with_level(Level::Debug) {
1956        Some(reply) if reply.atom != x11rb::NONE => {
1957            let atom = reply.atom;
1958            get_reply(
1959                || format!("Failed to get {atom_name}"),
1960                xcb_connection.get_property(false, root, atom, xproto::AtomEnum::WINDOW, 0, 1),
1961            )
1962            .map(|reply| reply.value_len > 0)
1963            .unwrap_or(false)
1964        }
1965        _ => return false,
1966    };
1967
1968    log::debug!(
1969        "Compositor detection: _NET_WM_CM_S?={}, _NET_WM_CM_OWNER={}, _NET_SUPPORTING_WM_CHECK={}",
1970        method1,
1971        method2,
1972        method3
1973    );
1974
1975    method1 || method2 || method3
1976}
1977
1978fn check_gtk_frame_extents_supported(
1979    xcb_connection: &XCBConnection,
1980    atoms: &XcbAtoms,
1981    root: xproto::Window,
1982) -> bool {
1983    let Some(supported_atoms) = get_reply(
1984        || "Failed to get _NET_SUPPORTED",
1985        xcb_connection.get_property(
1986            false,
1987            root,
1988            atoms._NET_SUPPORTED,
1989            xproto::AtomEnum::ATOM,
1990            0,
1991            1024,
1992        ),
1993    )
1994    .log_with_level(Level::Debug) else {
1995        return false;
1996    };
1997
1998    let supported_atom_ids: Vec<u32> = supported_atoms
1999        .value
2000        .chunks_exact(4)
2001        .filter_map(|chunk| chunk.try_into().ok().map(u32::from_ne_bytes))
2002        .collect();
2003
2004    supported_atom_ids.contains(&atoms._GTK_FRAME_EXTENTS)
2005}
2006
2007fn xdnd_is_atom_supported(atom: u32, atoms: &XcbAtoms) -> bool {
2008    atom == atoms.TEXT
2009        || atom == atoms.STRING
2010        || atom == atoms.UTF8_STRING
2011        || atom == atoms.TEXT_PLAIN
2012        || atom == atoms.TEXT_PLAIN_UTF8
2013        || atom == atoms.TextUriList
2014}
2015
2016fn xdnd_get_supported_atom(
2017    xcb_connection: &XCBConnection,
2018    supported_atoms: &XcbAtoms,
2019    target: xproto::Window,
2020) -> u32 {
2021    if let Some(reply) = get_reply(
2022        || "Failed to get XDnD supported atoms",
2023        xcb_connection.get_property(
2024            false,
2025            target,
2026            supported_atoms.XdndTypeList,
2027            AtomEnum::ANY,
2028            0,
2029            1024,
2030        ),
2031    )
2032    .log_with_level(Level::Warn)
2033        && let Some(atoms) = reply.value32()
2034    {
2035        for atom in atoms {
2036            if xdnd_is_atom_supported(atom, supported_atoms) {
2037                return atom;
2038            }
2039        }
2040    }
2041    0
2042}
2043
2044fn xdnd_send_finished(
2045    xcb_connection: &XCBConnection,
2046    atoms: &XcbAtoms,
2047    source: xproto::Window,
2048    target: xproto::Window,
2049) {
2050    let message = ClientMessageEvent {
2051        format: 32,
2052        window: target,
2053        type_: atoms.XdndFinished,
2054        data: ClientMessageData::from([source, 1, atoms.XdndActionCopy, 0, 0]),
2055        sequence: 0,
2056        response_type: xproto::CLIENT_MESSAGE_EVENT,
2057    };
2058    check_reply(
2059        || "Failed to send XDnD finished event",
2060        xcb_connection.send_event(false, target, EventMask::default(), message),
2061    )
2062    .log_err();
2063    xcb_connection.flush().log_err();
2064}
2065
2066fn xdnd_send_status(
2067    xcb_connection: &XCBConnection,
2068    atoms: &XcbAtoms,
2069    source: xproto::Window,
2070    target: xproto::Window,
2071    action: u32,
2072) {
2073    let message = ClientMessageEvent {
2074        format: 32,
2075        window: target,
2076        type_: atoms.XdndStatus,
2077        data: ClientMessageData::from([source, 1, 0, 0, action]),
2078        sequence: 0,
2079        response_type: xproto::CLIENT_MESSAGE_EVENT,
2080    };
2081    check_reply(
2082        || "Failed to send XDnD status event",
2083        xcb_connection.send_event(false, target, EventMask::default(), message),
2084    )
2085    .log_err();
2086    xcb_connection.flush().log_err();
2087}
2088
2089/// Recomputes `pointer_device_states` by querying all pointer devices.
2090/// When a device is present in `scroll_values_to_preserve`, its value for `ScrollAxisState.scroll_value` is used.
2091fn current_pointer_device_states(
2092    xcb_connection: &XCBConnection,
2093    scroll_values_to_preserve: &BTreeMap<xinput::DeviceId, PointerDeviceState>,
2094) -> Option<BTreeMap<xinput::DeviceId, PointerDeviceState>> {
2095    let devices_query_result = get_reply(
2096        || "Failed to query XInput devices",
2097        xcb_connection.xinput_xi_query_device(XINPUT_ALL_DEVICES),
2098    )
2099    .log_err()?;
2100
2101    let mut pointer_device_states = BTreeMap::new();
2102    pointer_device_states.extend(
2103        devices_query_result
2104            .infos
2105            .iter()
2106            .filter(|info| is_pointer_device(info.type_))
2107            .filter_map(|info| {
2108                let scroll_data = info
2109                    .classes
2110                    .iter()
2111                    .filter_map(|class| class.data.as_scroll())
2112                    .copied()
2113                    .rev()
2114                    .collect::<Vec<_>>();
2115                let old_state = scroll_values_to_preserve.get(&info.deviceid);
2116                let old_horizontal = old_state.map(|state| &state.horizontal);
2117                let old_vertical = old_state.map(|state| &state.vertical);
2118                let horizontal = scroll_data
2119                    .iter()
2120                    .find(|data| data.scroll_type == xinput::ScrollType::HORIZONTAL)
2121                    .map(|data| scroll_data_to_axis_state(data, old_horizontal));
2122                let vertical = scroll_data
2123                    .iter()
2124                    .find(|data| data.scroll_type == xinput::ScrollType::VERTICAL)
2125                    .map(|data| scroll_data_to_axis_state(data, old_vertical));
2126                if horizontal.is_none() && vertical.is_none() {
2127                    None
2128                } else {
2129                    Some((
2130                        info.deviceid,
2131                        PointerDeviceState {
2132                            horizontal: horizontal.unwrap_or_else(Default::default),
2133                            vertical: vertical.unwrap_or_else(Default::default),
2134                        },
2135                    ))
2136                }
2137            }),
2138    );
2139    if pointer_device_states.is_empty() {
2140        log::error!("Found no xinput mouse pointers.");
2141    }
2142    Some(pointer_device_states)
2143}
2144
2145/// Returns true if the device is a pointer device. Does not include pointer device groups.
2146fn is_pointer_device(type_: xinput::DeviceType) -> bool {
2147    type_ == xinput::DeviceType::SLAVE_POINTER
2148}
2149
2150fn scroll_data_to_axis_state(
2151    data: &xinput::DeviceClassDataScroll,
2152    old_axis_state_with_valid_scroll_value: Option<&ScrollAxisState>,
2153) -> ScrollAxisState {
2154    ScrollAxisState {
2155        valuator_number: Some(data.number),
2156        multiplier: SCROLL_LINES / fp3232_to_f32(data.increment),
2157        scroll_value: old_axis_state_with_valid_scroll_value.and_then(|state| state.scroll_value),
2158    }
2159}
2160
2161fn reset_all_pointer_device_scroll_positions(
2162    pointer_device_states: &mut BTreeMap<xinput::DeviceId, PointerDeviceState>,
2163) {
2164    pointer_device_states
2165        .iter_mut()
2166        .for_each(|(_, device_state)| reset_pointer_device_scroll_positions(device_state));
2167}
2168
2169fn reset_pointer_device_scroll_positions(pointer: &mut PointerDeviceState) {
2170    pointer.horizontal.scroll_value = None;
2171    pointer.vertical.scroll_value = None;
2172}
2173
2174/// Returns the scroll delta for a smooth scrolling motion event, or `None` if no scroll data is present.
2175fn get_scroll_delta_and_update_state(
2176    pointer: &mut PointerDeviceState,
2177    event: &xinput::MotionEvent,
2178) -> Option<Point<f32>> {
2179    let delta_x = get_axis_scroll_delta_and_update_state(event, &mut pointer.horizontal);
2180    let delta_y = get_axis_scroll_delta_and_update_state(event, &mut pointer.vertical);
2181    if delta_x.is_some() || delta_y.is_some() {
2182        Some(Point::new(delta_x.unwrap_or(0.0), delta_y.unwrap_or(0.0)))
2183    } else {
2184        None
2185    }
2186}
2187
2188fn get_axis_scroll_delta_and_update_state(
2189    event: &xinput::MotionEvent,
2190    axis: &mut ScrollAxisState,
2191) -> Option<f32> {
2192    let axis_index = get_valuator_axis_index(&event.valuator_mask, axis.valuator_number?)?;
2193    if let Some(axis_value) = event.axisvalues.get(axis_index) {
2194        let new_scroll = fp3232_to_f32(*axis_value);
2195        let delta_scroll = axis
2196            .scroll_value
2197            .map(|old_scroll| (old_scroll - new_scroll) * axis.multiplier);
2198        axis.scroll_value = Some(new_scroll);
2199        delta_scroll
2200    } else {
2201        log::error!("Encountered invalid XInput valuator_mask, scrolling may not work properly.");
2202        None
2203    }
2204}
2205
2206fn make_scroll_wheel_event(
2207    position: Point<Pixels>,
2208    scroll_delta: Point<f32>,
2209    modifiers: Modifiers,
2210) -> crate::ScrollWheelEvent {
2211    // When shift is held down, vertical scrolling turns into horizontal scrolling.
2212    let delta = if modifiers.shift {
2213        Point {
2214            x: scroll_delta.y,
2215            y: 0.0,
2216        }
2217    } else {
2218        scroll_delta
2219    };
2220    crate::ScrollWheelEvent {
2221        position,
2222        delta: ScrollDelta::Lines(delta),
2223        modifiers,
2224        touch_phase: TouchPhase::default(),
2225    }
2226}
2227
2228fn create_invisible_cursor(
2229    connection: &XCBConnection,
2230) -> anyhow::Result<crate::platform::linux::x11::client::xproto::Cursor> {
2231    let empty_pixmap = connection.generate_id()?;
2232    let root = connection.setup().roots[0].root;
2233    connection.create_pixmap(1, empty_pixmap, root, 1, 1)?;
2234
2235    let cursor = connection.generate_id()?;
2236    connection.create_cursor(cursor, empty_pixmap, empty_pixmap, 0, 0, 0, 0, 0, 0, 0, 0)?;
2237
2238    connection.free_pixmap(empty_pixmap)?;
2239
2240    xcb_flush(connection);
2241    Ok(cursor)
2242}
2243
2244enum DpiMode {
2245    Randr,
2246    Scale(f32),
2247    NotSet,
2248}
2249
2250fn get_scale_factor(
2251    connection: &XCBConnection,
2252    resource_database: &Database,
2253    screen_index: usize,
2254) -> f32 {
2255    let env_dpi = std::env::var(GPUI_X11_SCALE_FACTOR_ENV)
2256        .ok()
2257        .map(|var| {
2258            if var.to_lowercase() == "randr" {
2259                DpiMode::Randr
2260            } else if let Ok(scale) = var.parse::<f32>() {
2261                if valid_scale_factor(scale) {
2262                    DpiMode::Scale(scale)
2263                } else {
2264                    panic!(
2265                        "`{}` must be a positive normal number or `randr`. Got `{}`",
2266                        GPUI_X11_SCALE_FACTOR_ENV, var
2267                    );
2268                }
2269            } else if var.is_empty() {
2270                DpiMode::NotSet
2271            } else {
2272                panic!(
2273                    "`{}` must be a positive number or `randr`. Got `{}`",
2274                    GPUI_X11_SCALE_FACTOR_ENV, var
2275                );
2276            }
2277        })
2278        .unwrap_or(DpiMode::NotSet);
2279
2280    match env_dpi {
2281        DpiMode::Scale(scale) => {
2282            log::info!(
2283                "Using scale factor from {}: {}",
2284                GPUI_X11_SCALE_FACTOR_ENV,
2285                scale
2286            );
2287            return scale;
2288        }
2289        DpiMode::Randr => {
2290            if let Some(scale) = get_randr_scale_factor(connection, screen_index) {
2291                log::info!(
2292                    "Using RandR scale factor from {}=randr: {}",
2293                    GPUI_X11_SCALE_FACTOR_ENV,
2294                    scale
2295                );
2296                return scale;
2297            }
2298            log::warn!("Failed to calculate RandR scale factor, falling back to default");
2299            return 1.0;
2300        }
2301        DpiMode::NotSet => {}
2302    }
2303
2304    // TODO: Use scale factor from XSettings here
2305
2306    if let Some(dpi) = resource_database
2307        .get_value::<f32>("Xft.dpi", "Xft.dpi")
2308        .ok()
2309        .flatten()
2310    {
2311        let scale = dpi / 96.0; // base dpi
2312        log::info!("Using scale factor from Xft.dpi: {}", scale);
2313        return scale;
2314    }
2315
2316    if let Some(scale) = get_randr_scale_factor(connection, screen_index) {
2317        log::info!("Using RandR scale factor: {}", scale);
2318        return scale;
2319    }
2320
2321    log::info!("Using default scale factor: 1.0");
2322    1.0
2323}
2324
2325fn get_randr_scale_factor(connection: &XCBConnection, screen_index: usize) -> Option<f32> {
2326    let root = connection.setup().roots.get(screen_index)?.root;
2327
2328    let version_cookie = connection.randr_query_version(1, 6).ok()?;
2329    let version_reply = version_cookie.reply().ok()?;
2330    if version_reply.major_version < 1
2331        || (version_reply.major_version == 1 && version_reply.minor_version < 5)
2332    {
2333        return legacy_get_randr_scale_factor(connection, root); // for randr <1.5
2334    }
2335
2336    let monitors_cookie = connection.randr_get_monitors(root, true).ok()?; // true for active only
2337    let monitors_reply = monitors_cookie.reply().ok()?;
2338
2339    let mut fallback_scale: Option<f32> = None;
2340    for monitor in monitors_reply.monitors {
2341        if monitor.width_in_millimeters == 0 || monitor.height_in_millimeters == 0 {
2342            continue;
2343        }
2344        let scale_factor = get_dpi_factor(
2345            (monitor.width as u32, monitor.height as u32),
2346            (
2347                monitor.width_in_millimeters as u64,
2348                monitor.height_in_millimeters as u64,
2349            ),
2350        );
2351        if monitor.primary {
2352            return Some(scale_factor);
2353        } else if fallback_scale.is_none() {
2354            fallback_scale = Some(scale_factor);
2355        }
2356    }
2357
2358    fallback_scale
2359}
2360
2361fn legacy_get_randr_scale_factor(connection: &XCBConnection, root: u32) -> Option<f32> {
2362    let primary_cookie = connection.randr_get_output_primary(root).ok()?;
2363    let primary_reply = primary_cookie.reply().ok()?;
2364    let primary_output = primary_reply.output;
2365
2366    let primary_output_cookie = connection
2367        .randr_get_output_info(primary_output, x11rb::CURRENT_TIME)
2368        .ok()?;
2369    let primary_output_info = primary_output_cookie.reply().ok()?;
2370
2371    // try primary
2372    if primary_output_info.connection == randr::Connection::CONNECTED
2373        && primary_output_info.mm_width > 0
2374        && primary_output_info.mm_height > 0
2375        && primary_output_info.crtc != 0
2376    {
2377        let crtc_cookie = connection
2378            .randr_get_crtc_info(primary_output_info.crtc, x11rb::CURRENT_TIME)
2379            .ok()?;
2380        let crtc_info = crtc_cookie.reply().ok()?;
2381
2382        if crtc_info.width > 0 && crtc_info.height > 0 {
2383            let scale_factor = get_dpi_factor(
2384                (crtc_info.width as u32, crtc_info.height as u32),
2385                (
2386                    primary_output_info.mm_width as u64,
2387                    primary_output_info.mm_height as u64,
2388                ),
2389            );
2390            return Some(scale_factor);
2391        }
2392    }
2393
2394    // fallback: full scan
2395    let resources_cookie = connection.randr_get_screen_resources_current(root).ok()?;
2396    let screen_resources = resources_cookie.reply().ok()?;
2397
2398    let mut crtc_cookies = Vec::with_capacity(screen_resources.crtcs.len());
2399    for &crtc in &screen_resources.crtcs {
2400        if let Ok(cookie) = connection.randr_get_crtc_info(crtc, x11rb::CURRENT_TIME) {
2401            crtc_cookies.push((crtc, cookie));
2402        }
2403    }
2404
2405    let mut crtc_infos: HashMap<randr::Crtc, randr::GetCrtcInfoReply> = HashMap::default();
2406    let mut valid_outputs: HashSet<randr::Output> = HashSet::new();
2407    for (crtc, cookie) in crtc_cookies {
2408        if let Ok(reply) = cookie.reply()
2409            && reply.width > 0
2410            && reply.height > 0
2411            && !reply.outputs.is_empty()
2412        {
2413            crtc_infos.insert(crtc, reply.clone());
2414            valid_outputs.extend(&reply.outputs);
2415        }
2416    }
2417
2418    if valid_outputs.is_empty() {
2419        return None;
2420    }
2421
2422    let mut output_cookies = Vec::with_capacity(valid_outputs.len());
2423    for &output in &valid_outputs {
2424        if let Ok(cookie) = connection.randr_get_output_info(output, x11rb::CURRENT_TIME) {
2425            output_cookies.push((output, cookie));
2426        }
2427    }
2428    let mut output_infos: HashMap<randr::Output, randr::GetOutputInfoReply> = HashMap::default();
2429    for (output, cookie) in output_cookies {
2430        if let Ok(reply) = cookie.reply() {
2431            output_infos.insert(output, reply);
2432        }
2433    }
2434
2435    let mut fallback_scale: Option<f32> = None;
2436    for crtc_info in crtc_infos.values() {
2437        for &output in &crtc_info.outputs {
2438            if let Some(output_info) = output_infos.get(&output) {
2439                if output_info.connection != randr::Connection::CONNECTED {
2440                    continue;
2441                }
2442
2443                if output_info.mm_width == 0 || output_info.mm_height == 0 {
2444                    continue;
2445                }
2446
2447                let scale_factor = get_dpi_factor(
2448                    (crtc_info.width as u32, crtc_info.height as u32),
2449                    (output_info.mm_width as u64, output_info.mm_height as u64),
2450                );
2451
2452                if output != primary_output && fallback_scale.is_none() {
2453                    fallback_scale = Some(scale_factor);
2454                }
2455            }
2456        }
2457    }
2458
2459    fallback_scale
2460}
2461
2462fn get_dpi_factor((width_px, height_px): (u32, u32), (width_mm, height_mm): (u64, u64)) -> f32 {
2463    let ppmm = ((width_px as f64 * height_px as f64) / (width_mm as f64 * height_mm as f64)).sqrt(); // pixels per mm
2464
2465    const MM_PER_INCH: f64 = 25.4;
2466    const BASE_DPI: f64 = 96.0;
2467    const QUANTIZE_STEP: f64 = 12.0; // e.g. 1.25 = 15/12, 1.5 = 18/12, 1.75 = 21/12, 2.0 = 24/12
2468    const MIN_SCALE: f64 = 1.0;
2469    const MAX_SCALE: f64 = 20.0;
2470
2471    let dpi_factor =
2472        ((ppmm * (QUANTIZE_STEP * MM_PER_INCH / BASE_DPI)).round() / QUANTIZE_STEP).max(MIN_SCALE);
2473
2474    let validated_factor = if dpi_factor <= MAX_SCALE {
2475        dpi_factor
2476    } else {
2477        MIN_SCALE
2478    };
2479
2480    if valid_scale_factor(validated_factor as f32) {
2481        validated_factor as f32
2482    } else {
2483        log::warn!(
2484            "Calculated DPI factor {} is invalid, using 1.0",
2485            validated_factor
2486        );
2487        1.0
2488    }
2489}
2490
2491#[inline]
2492fn valid_scale_factor(scale_factor: f32) -> bool {
2493    scale_factor.is_sign_positive() && scale_factor.is_normal()
2494}