client.rs

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