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