client.rs

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