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