client.rs

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