client.rs

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