client.rs

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