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                    // should be called after key_get_one_sym
1008                    state.xkb.update_key(code, xkbc::KeyDirection::Down);
1009
1010                    if keysym.is_modifier_key() {
1011                        return Some(());
1012                    }
1013                    if let Some(mut compose_state) = state.compose_state.take() {
1014                        compose_state.feed(keysym);
1015                        match compose_state.status() {
1016                            xkbc::Status::Composed => {
1017                                state.pre_edit_text.take();
1018                                keystroke.key_char = compose_state.utf8();
1019                                if let Some(keysym) = compose_state.keysym() {
1020                                    keystroke.key = xkbc::keysym_get_name(keysym);
1021                                }
1022                            }
1023                            xkbc::Status::Composing => {
1024                                keystroke.key_char = None;
1025                                state.pre_edit_text = compose_state
1026                                    .utf8()
1027                                    .or(crate::Keystroke::underlying_dead_key(keysym));
1028                                let pre_edit =
1029                                    state.pre_edit_text.clone().unwrap_or(String::default());
1030                                drop(state);
1031                                window.handle_ime_preedit(pre_edit);
1032                                state = self.0.borrow_mut();
1033                            }
1034                            xkbc::Status::Cancelled => {
1035                                let pre_edit = state.pre_edit_text.take();
1036                                drop(state);
1037                                if let Some(pre_edit) = pre_edit {
1038                                    window.handle_ime_commit(pre_edit);
1039                                }
1040                                if let Some(current_key) = Keystroke::underlying_dead_key(keysym) {
1041                                    window.handle_ime_preedit(current_key);
1042                                }
1043                                state = self.0.borrow_mut();
1044                                compose_state.feed(keysym);
1045                            }
1046                            _ => {}
1047                        }
1048                        state.compose_state = Some(compose_state);
1049                    }
1050                    keystroke
1051                };
1052                drop(state);
1053                window.handle_input(PlatformInput::KeyDown(crate::KeyDownEvent {
1054                    keystroke,
1055                    is_held: false,
1056                }));
1057            }
1058            Event::KeyRelease(event) => {
1059                let window = self.get_window(event.event)?;
1060                let mut state = self.0.borrow_mut();
1061
1062                let modifiers = modifiers_from_state(event.state);
1063                state.modifiers = modifiers;
1064
1065                let keystroke = {
1066                    let code = event.detail.into();
1067                    let keystroke = crate::Keystroke::from_xkb(&state.xkb, modifiers, code);
1068                    let keysym = state.xkb.key_get_one_sym(code);
1069
1070                    // should be called after key_get_one_sym
1071                    state.xkb.update_key(code, xkbc::KeyDirection::Up);
1072
1073                    if keysym.is_modifier_key() {
1074                        return Some(());
1075                    }
1076                    keystroke
1077                };
1078                drop(state);
1079                window.handle_input(PlatformInput::KeyUp(crate::KeyUpEvent { keystroke }));
1080            }
1081            Event::XinputButtonPress(event) => {
1082                let window = self.get_window(event.event)?;
1083                let mut state = self.0.borrow_mut();
1084
1085                let modifiers = modifiers_from_xinput_info(event.mods);
1086                state.modifiers = modifiers;
1087
1088                let position = point(
1089                    px(event.event_x as f32 / u16::MAX as f32 / state.scale_factor),
1090                    px(event.event_y as f32 / u16::MAX as f32 / state.scale_factor),
1091                );
1092
1093                if state.composing && state.ximc.is_some() {
1094                    drop(state);
1095                    self.reset_ime();
1096                    window.handle_ime_unmark();
1097                    state = self.0.borrow_mut();
1098                } else if let Some(text) = state.pre_edit_text.take() {
1099                    if let Some(compose_state) = state.compose_state.as_mut() {
1100                        compose_state.reset();
1101                    }
1102                    drop(state);
1103                    window.handle_ime_commit(text);
1104                    state = self.0.borrow_mut();
1105                }
1106                match button_or_scroll_from_event_detail(event.detail) {
1107                    Some(ButtonOrScroll::Button(button)) => {
1108                        let click_elapsed = state.last_click.elapsed();
1109                        if click_elapsed < DOUBLE_CLICK_INTERVAL
1110                            && state
1111                                .last_mouse_button
1112                                .is_some_and(|prev_button| prev_button == button)
1113                            && is_within_click_distance(state.last_location, position)
1114                        {
1115                            state.current_count += 1;
1116                        } else {
1117                            state.current_count = 1;
1118                        }
1119
1120                        state.last_click = Instant::now();
1121                        state.last_mouse_button = Some(button);
1122                        state.last_location = position;
1123                        let current_count = state.current_count;
1124
1125                        drop(state);
1126                        window.handle_input(PlatformInput::MouseDown(crate::MouseDownEvent {
1127                            button,
1128                            position,
1129                            modifiers,
1130                            click_count: current_count,
1131                            first_mouse: false,
1132                        }));
1133                    }
1134                    Some(ButtonOrScroll::Scroll(direction)) => {
1135                        drop(state);
1136                        // Emulated scroll button presses are sent simultaneously with smooth scrolling XinputMotion events.
1137                        // Since handling those events does the scrolling, they are skipped here.
1138                        if !event
1139                            .flags
1140                            .contains(xinput::PointerEventFlags::POINTER_EMULATED)
1141                        {
1142                            let scroll_delta = match direction {
1143                                ScrollDirection::Up => Point::new(0.0, SCROLL_LINES),
1144                                ScrollDirection::Down => Point::new(0.0, -SCROLL_LINES),
1145                                ScrollDirection::Left => Point::new(SCROLL_LINES, 0.0),
1146                                ScrollDirection::Right => Point::new(-SCROLL_LINES, 0.0),
1147                            };
1148                            window.handle_input(PlatformInput::ScrollWheel(
1149                                make_scroll_wheel_event(position, scroll_delta, modifiers),
1150                            ));
1151                        }
1152                    }
1153                    None => {
1154                        log::error!("Unknown x11 button: {}", event.detail);
1155                    }
1156                }
1157            }
1158            Event::XinputButtonRelease(event) => {
1159                let window = self.get_window(event.event)?;
1160                let mut state = self.0.borrow_mut();
1161                let modifiers = modifiers_from_xinput_info(event.mods);
1162                state.modifiers = modifiers;
1163
1164                let position = point(
1165                    px(event.event_x as f32 / u16::MAX as f32 / state.scale_factor),
1166                    px(event.event_y as f32 / u16::MAX as f32 / state.scale_factor),
1167                );
1168                match button_or_scroll_from_event_detail(event.detail) {
1169                    Some(ButtonOrScroll::Button(button)) => {
1170                        let click_count = state.current_count;
1171                        drop(state);
1172                        window.handle_input(PlatformInput::MouseUp(crate::MouseUpEvent {
1173                            button,
1174                            position,
1175                            modifiers,
1176                            click_count,
1177                        }));
1178                    }
1179                    Some(ButtonOrScroll::Scroll(_)) => {}
1180                    None => {}
1181                }
1182            }
1183            Event::XinputMotion(event) => {
1184                let window = self.get_window(event.event)?;
1185                let mut state = self.0.borrow_mut();
1186                let pressed_button = pressed_button_from_mask(event.button_mask[0]);
1187                let position = point(
1188                    px(event.event_x as f32 / u16::MAX as f32 / state.scale_factor),
1189                    px(event.event_y as f32 / u16::MAX as f32 / state.scale_factor),
1190                );
1191                let modifiers = modifiers_from_xinput_info(event.mods);
1192                state.modifiers = modifiers;
1193                drop(state);
1194
1195                if event.valuator_mask[0] & 3 != 0 {
1196                    window.handle_input(PlatformInput::MouseMove(crate::MouseMoveEvent {
1197                        position,
1198                        pressed_button,
1199                        modifiers,
1200                    }));
1201                }
1202
1203                state = self.0.borrow_mut();
1204                if let Some(mut pointer) = state.pointer_device_states.get_mut(&event.sourceid) {
1205                    let scroll_delta = get_scroll_delta_and_update_state(&mut pointer, &event);
1206                    drop(state);
1207                    if let Some(scroll_delta) = scroll_delta {
1208                        window.handle_input(PlatformInput::ScrollWheel(make_scroll_wheel_event(
1209                            position,
1210                            scroll_delta,
1211                            modifiers,
1212                        )));
1213                    }
1214                }
1215            }
1216            Event::XinputEnter(event) if event.mode == xinput::NotifyMode::NORMAL => {
1217                let window = self.get_window(event.event)?;
1218                window.set_hovered(true);
1219                let mut state = self.0.borrow_mut();
1220                state.mouse_focused_window = Some(event.event);
1221            }
1222            Event::XinputLeave(event) if event.mode == xinput::NotifyMode::NORMAL => {
1223                let mut state = self.0.borrow_mut();
1224
1225                // 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)
1226                reset_all_pointer_device_scroll_positions(&mut state.pointer_device_states);
1227                state.mouse_focused_window = None;
1228                let pressed_button = pressed_button_from_mask(event.buttons[0]);
1229                let position = point(
1230                    px(event.event_x as f32 / u16::MAX as f32 / state.scale_factor),
1231                    px(event.event_y as f32 / u16::MAX as f32 / state.scale_factor),
1232                );
1233                let modifiers = modifiers_from_xinput_info(event.mods);
1234                state.modifiers = modifiers;
1235                drop(state);
1236
1237                let window = self.get_window(event.event)?;
1238                window.handle_input(PlatformInput::MouseExited(crate::MouseExitEvent {
1239                    pressed_button,
1240                    position,
1241                    modifiers,
1242                }));
1243                window.set_hovered(false);
1244            }
1245            Event::XinputHierarchy(event) => {
1246                let mut state = self.0.borrow_mut();
1247                // Temporarily use `state.pointer_device_states` to only store pointers that still have valid scroll values.
1248                // Any change to a device invalidates its scroll values.
1249                for info in event.infos {
1250                    if is_pointer_device(info.type_) {
1251                        state.pointer_device_states.remove(&info.deviceid);
1252                    }
1253                }
1254                if let Some(pointer_device_states) = current_pointer_device_states(
1255                    &state.xcb_connection,
1256                    &state.pointer_device_states,
1257                ) {
1258                    state.pointer_device_states = pointer_device_states;
1259                }
1260            }
1261            Event::XinputDeviceChanged(event) => {
1262                let mut state = self.0.borrow_mut();
1263                if let Some(mut pointer) = state.pointer_device_states.get_mut(&event.sourceid) {
1264                    reset_pointer_device_scroll_positions(&mut pointer);
1265                }
1266            }
1267            _ => {}
1268        };
1269
1270        Some(())
1271    }
1272
1273    fn handle_xim_callback_event(&self, event: XimCallbackEvent) {
1274        match event {
1275            XimCallbackEvent::XimXEvent(event) => {
1276                self.handle_event(event);
1277            }
1278            XimCallbackEvent::XimCommitEvent(window, text) => {
1279                self.xim_handle_commit(window, text);
1280            }
1281            XimCallbackEvent::XimPreeditEvent(window, text) => {
1282                self.xim_handle_preedit(window, text);
1283            }
1284        };
1285    }
1286
1287    fn xim_handle_event(&self, event: Event) -> Option<()> {
1288        match event {
1289            Event::KeyPress(event) | Event::KeyRelease(event) => {
1290                let mut state = self.0.borrow_mut();
1291                state.pre_key_char_down = Some(Keystroke::from_xkb(
1292                    &state.xkb,
1293                    state.modifiers,
1294                    event.detail.into(),
1295                ));
1296                let (mut ximc, mut xim_handler) = state.take_xim()?;
1297                drop(state);
1298                xim_handler.window = event.event;
1299                ximc.forward_event(
1300                    xim_handler.im_id,
1301                    xim_handler.ic_id,
1302                    xim::ForwardEventFlag::empty(),
1303                    &event,
1304                )
1305                .context("X11: Failed to forward XIM event")
1306                .log_err();
1307                let mut state = self.0.borrow_mut();
1308                state.restore_xim(ximc, xim_handler);
1309                drop(state);
1310            }
1311            event => {
1312                self.handle_event(event);
1313            }
1314        }
1315        Some(())
1316    }
1317
1318    fn xim_handle_commit(&self, window: xproto::Window, text: String) -> Option<()> {
1319        let Some(window) = self.get_window(window) else {
1320            log::error!("bug: Failed to get window for XIM commit");
1321            return None;
1322        };
1323        let mut state = self.0.borrow_mut();
1324        let keystroke = state.pre_key_char_down.take();
1325        state.composing = false;
1326        drop(state);
1327        if let Some(mut keystroke) = keystroke {
1328            keystroke.key_char = Some(text.clone());
1329            window.handle_input(PlatformInput::KeyDown(crate::KeyDownEvent {
1330                keystroke,
1331                is_held: false,
1332            }));
1333        }
1334
1335        Some(())
1336    }
1337
1338    fn xim_handle_preedit(&self, window: xproto::Window, text: String) -> Option<()> {
1339        let Some(window) = self.get_window(window) else {
1340            log::error!("bug: Failed to get window for XIM preedit");
1341            return None;
1342        };
1343
1344        let mut state = self.0.borrow_mut();
1345        let (mut ximc, mut xim_handler) = state.take_xim()?;
1346        state.composing = !text.is_empty();
1347        drop(state);
1348        window.handle_ime_preedit(text);
1349
1350        if let Some(area) = window.get_ime_area() {
1351            let ic_attributes = ximc
1352                .build_ic_attributes()
1353                .push(
1354                    xim::AttributeName::InputStyle,
1355                    xim::InputStyle::PREEDIT_CALLBACKS,
1356                )
1357                .push(xim::AttributeName::ClientWindow, xim_handler.window)
1358                .push(xim::AttributeName::FocusWindow, xim_handler.window)
1359                .nested_list(xim::AttributeName::PreeditAttributes, |b| {
1360                    b.push(
1361                        xim::AttributeName::SpotLocation,
1362                        xim::Point {
1363                            x: u32::from(area.origin.x + area.size.width) as i16,
1364                            y: u32::from(area.origin.y + area.size.height) as i16,
1365                        },
1366                    );
1367                })
1368                .build();
1369            ximc.set_ic_values(xim_handler.im_id, xim_handler.ic_id, ic_attributes)
1370                .ok();
1371        }
1372        let mut state = self.0.borrow_mut();
1373        state.restore_xim(ximc, xim_handler);
1374        drop(state);
1375        Some(())
1376    }
1377
1378    fn handle_keyboard_layout_change(&self) {
1379        let mut state = self.0.borrow_mut();
1380        let layout_idx = state.xkb.serialize_layout(STATE_LAYOUT_EFFECTIVE);
1381        let keymap = state.xkb.get_keymap();
1382        let layout_name = keymap.layout_get_name(layout_idx);
1383        if layout_name != state.keyboard_layout.name() {
1384            state.keyboard_layout = LinuxKeyboardLayout::new(layout_name.to_string().into());
1385            if let Some(mut callback) = state.common.callbacks.keyboard_layout_change.take() {
1386                drop(state);
1387                callback();
1388                state = self.0.borrow_mut();
1389                state.common.callbacks.keyboard_layout_change = Some(callback);
1390            }
1391        }
1392    }
1393}
1394
1395impl LinuxClient for X11Client {
1396    fn compositor_name(&self) -> &'static str {
1397        "X11"
1398    }
1399
1400    fn with_common<R>(&self, f: impl FnOnce(&mut LinuxCommon) -> R) -> R {
1401        f(&mut self.0.borrow_mut().common)
1402    }
1403
1404    fn keyboard_layout(&self) -> Box<dyn PlatformKeyboardLayout> {
1405        let state = self.0.borrow();
1406        Box::new(state.keyboard_layout.clone())
1407    }
1408
1409    fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
1410        let state = self.0.borrow();
1411        let setup = state.xcb_connection.setup();
1412        setup
1413            .roots
1414            .iter()
1415            .enumerate()
1416            .filter_map(|(root_id, _)| {
1417                Some(Rc::new(
1418                    X11Display::new(&state.xcb_connection, state.scale_factor, root_id).ok()?,
1419                ) as Rc<dyn PlatformDisplay>)
1420            })
1421            .collect()
1422    }
1423
1424    fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
1425        let state = self.0.borrow();
1426        X11Display::new(
1427            &state.xcb_connection,
1428            state.scale_factor,
1429            state.x_root_index,
1430        )
1431        .log_err()
1432        .map(|display| Rc::new(display) as Rc<dyn PlatformDisplay>)
1433    }
1434
1435    fn display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>> {
1436        let state = self.0.borrow();
1437
1438        Some(Rc::new(
1439            X11Display::new(&state.xcb_connection, state.scale_factor, id.0 as usize).ok()?,
1440        ))
1441    }
1442
1443    #[cfg(feature = "screen-capture")]
1444    fn is_screen_capture_supported(&self) -> bool {
1445        true
1446    }
1447
1448    #[cfg(feature = "screen-capture")]
1449    fn screen_capture_sources(
1450        &self,
1451    ) -> futures::channel::oneshot::Receiver<anyhow::Result<Vec<Rc<dyn crate::ScreenCaptureSource>>>>
1452    {
1453        crate::platform::scap_screen_capture::scap_screen_sources(
1454            &self.0.borrow().common.foreground_executor,
1455        )
1456    }
1457
1458    fn open_window(
1459        &self,
1460        handle: AnyWindowHandle,
1461        params: WindowParams,
1462    ) -> anyhow::Result<Box<dyn PlatformWindow>> {
1463        let mut state = self.0.borrow_mut();
1464        let x_window = state
1465            .xcb_connection
1466            .generate_id()
1467            .context("X11: Failed to generate window ID")?;
1468
1469        let window = X11Window::new(
1470            handle,
1471            X11ClientStatePtr(Rc::downgrade(&self.0)),
1472            state.common.foreground_executor.clone(),
1473            &state.gpu_context,
1474            params,
1475            &state.xcb_connection,
1476            state.client_side_decorations_supported,
1477            state.x_root_index,
1478            x_window,
1479            &state.atoms,
1480            state.scale_factor,
1481            state.common.appearance,
1482        )?;
1483        check_reply(
1484            || "Failed to set XdndAware property",
1485            state.xcb_connection.change_property32(
1486                xproto::PropMode::REPLACE,
1487                x_window,
1488                state.atoms.XdndAware,
1489                state.atoms.XA_ATOM,
1490                &[5],
1491            ),
1492        )
1493        .log_err();
1494        xcb_flush(&state.xcb_connection);
1495
1496        let window_ref = WindowRef {
1497            window: window.0.clone(),
1498            refresh_state: None,
1499            expose_event_received: false,
1500            last_visibility: Visibility::UNOBSCURED,
1501            is_mapped: false,
1502        };
1503
1504        state.windows.insert(x_window, window_ref);
1505        Ok(Box::new(window))
1506    }
1507
1508    fn set_cursor_style(&self, style: CursorStyle) {
1509        let mut state = self.0.borrow_mut();
1510        let Some(focused_window) = state.mouse_focused_window else {
1511            return;
1512        };
1513        let current_style = state
1514            .cursor_styles
1515            .get(&focused_window)
1516            .unwrap_or(&CursorStyle::Arrow);
1517        if *current_style == style {
1518            return;
1519        }
1520
1521        let Some(cursor) = state.get_cursor_icon(style) else {
1522            return;
1523        };
1524
1525        state.cursor_styles.insert(focused_window, style);
1526        check_reply(
1527            || "Failed to set cursor style",
1528            state.xcb_connection.change_window_attributes(
1529                focused_window,
1530                &ChangeWindowAttributesAux {
1531                    cursor: Some(cursor),
1532                    ..Default::default()
1533                },
1534            ),
1535        )
1536        .log_err();
1537        state.xcb_connection.flush().log_err();
1538    }
1539
1540    fn open_uri(&self, uri: &str) {
1541        #[cfg(any(feature = "wayland", feature = "x11"))]
1542        open_uri_internal(self.background_executor(), uri, None);
1543    }
1544
1545    fn reveal_path(&self, path: PathBuf) {
1546        #[cfg(any(feature = "x11", feature = "wayland"))]
1547        reveal_path_internal(self.background_executor(), path, None);
1548    }
1549
1550    fn write_to_primary(&self, item: crate::ClipboardItem) {
1551        let state = self.0.borrow_mut();
1552        state
1553            .clipboard
1554            .set_text(
1555                std::borrow::Cow::Owned(item.text().unwrap_or_default()),
1556                clipboard::ClipboardKind::Primary,
1557                clipboard::WaitConfig::None,
1558            )
1559            .context("X11 Failed to write to clipboard (primary)")
1560            .log_with_level(log::Level::Debug);
1561    }
1562
1563    fn write_to_clipboard(&self, item: crate::ClipboardItem) {
1564        let mut state = self.0.borrow_mut();
1565        state
1566            .clipboard
1567            .set_text(
1568                std::borrow::Cow::Owned(item.text().unwrap_or_default()),
1569                clipboard::ClipboardKind::Clipboard,
1570                clipboard::WaitConfig::None,
1571            )
1572            .context("X11: Failed to write to clipboard (clipboard)")
1573            .log_with_level(log::Level::Debug);
1574        state.clipboard_item.replace(item);
1575    }
1576
1577    fn read_from_primary(&self) -> Option<crate::ClipboardItem> {
1578        let state = self.0.borrow_mut();
1579        return state
1580            .clipboard
1581            .get_any(clipboard::ClipboardKind::Primary)
1582            .context("X11: Failed to read from clipboard (primary)")
1583            .log_with_level(log::Level::Debug);
1584    }
1585
1586    fn read_from_clipboard(&self) -> Option<crate::ClipboardItem> {
1587        let state = self.0.borrow_mut();
1588        // if the last copy was from this app, return our cached item
1589        // which has metadata attached.
1590        if state
1591            .clipboard
1592            .is_owner(clipboard::ClipboardKind::Clipboard)
1593        {
1594            return state.clipboard_item.clone();
1595        }
1596        return state
1597            .clipboard
1598            .get_any(clipboard::ClipboardKind::Clipboard)
1599            .context("X11: Failed to read from clipboard (clipboard)")
1600            .log_with_level(log::Level::Debug);
1601    }
1602
1603    fn run(&self) {
1604        let Some(mut event_loop) = self
1605            .0
1606            .borrow_mut()
1607            .event_loop
1608            .take()
1609            .context("X11Client::run called but it's already running")
1610            .log_err()
1611        else {
1612            return;
1613        };
1614
1615        event_loop.run(None, &mut self.clone(), |_| {}).log_err();
1616    }
1617
1618    fn active_window(&self) -> Option<AnyWindowHandle> {
1619        let state = self.0.borrow();
1620        state.keyboard_focused_window.and_then(|focused_window| {
1621            state
1622                .windows
1623                .get(&focused_window)
1624                .map(|window| window.handle())
1625        })
1626    }
1627
1628    fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
1629        let state = self.0.borrow();
1630        let root = state.xcb_connection.setup().roots[state.x_root_index].root;
1631
1632        let reply = state
1633            .xcb_connection
1634            .get_property(
1635                false,
1636                root,
1637                state.atoms._NET_CLIENT_LIST_STACKING,
1638                xproto::AtomEnum::WINDOW,
1639                0,
1640                u32::MAX,
1641            )
1642            .ok()?
1643            .reply()
1644            .ok()?;
1645
1646        let window_ids = reply
1647            .value
1648            .chunks_exact(4)
1649            .filter_map(|chunk| chunk.try_into().ok().map(u32::from_ne_bytes))
1650            .collect::<Vec<xproto::Window>>();
1651
1652        let mut handles = Vec::new();
1653
1654        // We need to reverse, since _NET_CLIENT_LIST_STACKING has
1655        // a back-to-front order.
1656        // See: https://specifications.freedesktop.org/wm-spec/1.3/ar01s03.html
1657        for window_ref in window_ids
1658            .iter()
1659            .rev()
1660            .filter_map(|&win| state.windows.get(&win))
1661        {
1662            if !window_ref.window.state.borrow().destroyed {
1663                handles.push(window_ref.handle());
1664            }
1665        }
1666
1667        Some(handles)
1668    }
1669}
1670
1671impl X11ClientState {
1672    fn has_xim(&self) -> bool {
1673        self.ximc.is_some() && self.xim_handler.is_some()
1674    }
1675
1676    fn take_xim(&mut self) -> Option<(X11rbClient<Rc<XCBConnection>>, XimHandler)> {
1677        let ximc = self
1678            .ximc
1679            .take()
1680            .ok_or(anyhow!("bug: XIM connection not set"))
1681            .log_err()?;
1682        if let Some(xim_handler) = self.xim_handler.take() {
1683            Some((ximc, xim_handler))
1684        } else {
1685            self.ximc = Some(ximc);
1686            log::error!("bug: XIM handler not set");
1687            None
1688        }
1689    }
1690
1691    fn restore_xim(&mut self, ximc: X11rbClient<Rc<XCBConnection>>, xim_handler: XimHandler) {
1692        self.ximc = Some(ximc);
1693        self.xim_handler = Some(xim_handler);
1694    }
1695
1696    fn update_refresh_loop(&mut self, x_window: xproto::Window) {
1697        let Some(window_ref) = self.windows.get_mut(&x_window) else {
1698            return;
1699        };
1700        let is_visible = window_ref.is_mapped
1701            && !matches!(window_ref.last_visibility, Visibility::FULLY_OBSCURED);
1702        match (is_visible, window_ref.refresh_state.take()) {
1703            (false, refresh_state @ Some(RefreshState::Hidden { .. }))
1704            | (false, refresh_state @ None)
1705            | (true, refresh_state @ Some(RefreshState::PeriodicRefresh { .. })) => {
1706                window_ref.refresh_state = refresh_state;
1707            }
1708            (
1709                false,
1710                Some(RefreshState::PeriodicRefresh {
1711                    refresh_rate,
1712                    event_loop_token,
1713                }),
1714            ) => {
1715                self.loop_handle.remove(event_loop_token);
1716                window_ref.refresh_state = Some(RefreshState::Hidden { refresh_rate });
1717            }
1718            (true, Some(RefreshState::Hidden { refresh_rate })) => {
1719                let event_loop_token = self.start_refresh_loop(x_window, refresh_rate);
1720                let Some(window_ref) = self.windows.get_mut(&x_window) else {
1721                    return;
1722                };
1723                window_ref.refresh_state = Some(RefreshState::PeriodicRefresh {
1724                    refresh_rate,
1725                    event_loop_token,
1726                });
1727            }
1728            (true, None) => {
1729                let Some(screen_resources) = get_reply(
1730                    || "Failed to get screen resources",
1731                    self.xcb_connection
1732                        .randr_get_screen_resources_current(x_window),
1733                )
1734                .log_err() else {
1735                    return;
1736                };
1737
1738                // Ideally this would be re-queried when the window changes screens, but there
1739                // doesn't seem to be an efficient / straightforward way to do this. Should also be
1740                // updated when screen configurations change.
1741                let mode_info = screen_resources.crtcs.iter().find_map(|crtc| {
1742                    let crtc_info = self
1743                        .xcb_connection
1744                        .randr_get_crtc_info(*crtc, x11rb::CURRENT_TIME)
1745                        .ok()?
1746                        .reply()
1747                        .ok()?;
1748
1749                    screen_resources
1750                        .modes
1751                        .iter()
1752                        .find(|m| m.id == crtc_info.mode)
1753                });
1754                let refresh_rate = match mode_info {
1755                    Some(mode_info) => mode_refresh_rate(mode_info),
1756                    None => {
1757                        log::error!(
1758                            "Failed to get screen mode info from xrandr, \
1759                            defaulting to 60hz refresh rate."
1760                        );
1761                        Duration::from_micros(1_000_000 / 60)
1762                    }
1763                };
1764
1765                let event_loop_token = self.start_refresh_loop(x_window, refresh_rate);
1766                let Some(window_ref) = self.windows.get_mut(&x_window) else {
1767                    return;
1768                };
1769                window_ref.refresh_state = Some(RefreshState::PeriodicRefresh {
1770                    refresh_rate,
1771                    event_loop_token,
1772                });
1773            }
1774        }
1775    }
1776
1777    #[must_use]
1778    fn start_refresh_loop(
1779        &self,
1780        x_window: xproto::Window,
1781        refresh_rate: Duration,
1782    ) -> RegistrationToken {
1783        self.loop_handle
1784            .insert_source(calloop::timer::Timer::immediate(), {
1785                move |mut instant, (), client| {
1786                    let xcb_connection = {
1787                        let mut state = client.0.borrow_mut();
1788                        let xcb_connection = state.xcb_connection.clone();
1789                        if let Some(window) = state.windows.get_mut(&x_window) {
1790                            let expose_event_received = window.expose_event_received;
1791                            window.expose_event_received = false;
1792                            let window = window.window.clone();
1793                            drop(state);
1794                            window.refresh(RequestFrameOptions {
1795                                require_presentation: expose_event_received,
1796                            });
1797                        }
1798                        xcb_connection
1799                    };
1800                    client.process_x11_events(&xcb_connection).log_err();
1801
1802                    // Take into account that some frames have been skipped
1803                    let now = Instant::now();
1804                    while instant < now {
1805                        instant += refresh_rate;
1806                    }
1807                    calloop::timer::TimeoutAction::ToInstant(instant)
1808                }
1809            })
1810            .expect("Failed to initialize window refresh timer")
1811    }
1812
1813    fn get_cursor_icon(&mut self, style: CursorStyle) -> Option<xproto::Cursor> {
1814        if let Some(cursor) = self.cursor_cache.get(&style) {
1815            return *cursor;
1816        }
1817
1818        let mut result;
1819        match style {
1820            CursorStyle::None => match create_invisible_cursor(&self.xcb_connection) {
1821                Ok(loaded_cursor) => result = Ok(loaded_cursor),
1822                Err(err) => result = Err(err.context("X11: error while creating invisible cursor")),
1823            },
1824            _ => 'outer: {
1825                let mut errors = String::new();
1826                let cursor_icon_names = style.to_icon_names();
1827                for cursor_icon_name in cursor_icon_names {
1828                    match self
1829                        .cursor_handle
1830                        .load_cursor(&self.xcb_connection, cursor_icon_name)
1831                    {
1832                        Ok(loaded_cursor) => {
1833                            if loaded_cursor != x11rb::NONE {
1834                                result = Ok(loaded_cursor);
1835                                break 'outer;
1836                            }
1837                        }
1838                        Err(err) => {
1839                            errors.push_str(&err.to_string());
1840                            errors.push('\n');
1841                        }
1842                    }
1843                }
1844                if errors.is_empty() {
1845                    result = Err(anyhow!(
1846                        "errors while loading cursor icons {:?}:\n{}",
1847                        cursor_icon_names,
1848                        errors
1849                    ));
1850                } else {
1851                    result = Err(anyhow!("did not find cursor icons {:?}", cursor_icon_names));
1852                }
1853            }
1854        };
1855
1856        let cursor = match result {
1857            Ok(cursor) => Some(cursor),
1858            Err(err) => {
1859                match self
1860                    .cursor_handle
1861                    .load_cursor(&self.xcb_connection, DEFAULT_CURSOR_ICON_NAME)
1862                {
1863                    Ok(default) => {
1864                        log_cursor_icon_warning(err.context(format!(
1865                            "X11: error loading cursor icon, falling back on default icon '{}'",
1866                            DEFAULT_CURSOR_ICON_NAME
1867                        )));
1868                        Some(default)
1869                    }
1870                    Err(default_err) => {
1871                        log_cursor_icon_warning(err.context(default_err).context(format!(
1872                            "X11: error loading default cursor fallback '{}'",
1873                            DEFAULT_CURSOR_ICON_NAME
1874                        )));
1875                        None
1876                    }
1877                }
1878            }
1879        };
1880
1881        self.cursor_cache.insert(style, cursor);
1882        cursor
1883    }
1884}
1885
1886// Adapted from:
1887// https://docs.rs/winit/0.29.11/src/winit/platform_impl/linux/x11/monitor.rs.html#103-111
1888pub fn mode_refresh_rate(mode: &randr::ModeInfo) -> Duration {
1889    if mode.dot_clock == 0 || mode.htotal == 0 || mode.vtotal == 0 {
1890        return Duration::from_millis(16);
1891    }
1892
1893    let millihertz = mode.dot_clock as u64 * 1_000 / (mode.htotal as u64 * mode.vtotal as u64);
1894    let micros = 1_000_000_000 / millihertz;
1895    log::info!("Refreshing every {}ms", micros / 1_000);
1896    Duration::from_micros(micros)
1897}
1898
1899fn fp3232_to_f32(value: xinput::Fp3232) -> f32 {
1900    value.integral as f32 + value.frac as f32 / u32::MAX as f32
1901}
1902
1903fn check_compositor_present(xcb_connection: &XCBConnection, root: u32) -> bool {
1904    // Method 1: Check for _NET_WM_CM_S{root}
1905    let atom_name = format!("_NET_WM_CM_S{}", root);
1906    let atom1 = get_reply(
1907        || format!("Failed to intern {atom_name}"),
1908        xcb_connection.intern_atom(false, atom_name.as_bytes()),
1909    );
1910    let method1 = match atom1.log_with_level(Level::Debug) {
1911        Some(reply) if reply.atom != x11rb::NONE => {
1912            let atom = reply.atom;
1913            get_reply(
1914                || format!("Failed to get {atom_name} owner"),
1915                xcb_connection.get_selection_owner(atom),
1916            )
1917            .map(|reply| reply.owner != 0)
1918            .log_with_level(Level::Debug)
1919            .unwrap_or(false)
1920        }
1921        _ => false,
1922    };
1923
1924    // Method 2: Check for _NET_WM_CM_OWNER
1925    let atom_name = "_NET_WM_CM_OWNER";
1926    let atom2 = get_reply(
1927        || format!("Failed to intern {atom_name}"),
1928        xcb_connection.intern_atom(false, atom_name.as_bytes()),
1929    );
1930    let method2 = match atom2.log_with_level(Level::Debug) {
1931        Some(reply) if reply.atom != x11rb::NONE => {
1932            let atom = reply.atom;
1933            get_reply(
1934                || format!("Failed to get {atom_name}"),
1935                xcb_connection.get_property(false, root, atom, xproto::AtomEnum::WINDOW, 0, 1),
1936            )
1937            .map(|reply| reply.value_len > 0)
1938            .unwrap_or(false)
1939        }
1940        _ => return false,
1941    };
1942
1943    // Method 3: Check for _NET_SUPPORTING_WM_CHECK
1944    let atom_name = "_NET_SUPPORTING_WM_CHECK";
1945    let atom3 = get_reply(
1946        || format!("Failed to intern {atom_name}"),
1947        xcb_connection.intern_atom(false, atom_name.as_bytes()),
1948    );
1949    let method3 = match atom3.log_with_level(Level::Debug) {
1950        Some(reply) if reply.atom != x11rb::NONE => {
1951            let atom = reply.atom;
1952            get_reply(
1953                || format!("Failed to get {atom_name}"),
1954                xcb_connection.get_property(false, root, atom, xproto::AtomEnum::WINDOW, 0, 1),
1955            )
1956            .map(|reply| reply.value_len > 0)
1957            .unwrap_or(false)
1958        }
1959        _ => return false,
1960    };
1961
1962    log::debug!(
1963        "Compositor detection: _NET_WM_CM_S?={}, _NET_WM_CM_OWNER={}, _NET_SUPPORTING_WM_CHECK={}",
1964        method1,
1965        method2,
1966        method3
1967    );
1968
1969    method1 || method2 || method3
1970}
1971
1972fn check_gtk_frame_extents_supported(
1973    xcb_connection: &XCBConnection,
1974    atoms: &XcbAtoms,
1975    root: xproto::Window,
1976) -> bool {
1977    let Some(supported_atoms) = get_reply(
1978        || "Failed to get _NET_SUPPORTED",
1979        xcb_connection.get_property(
1980            false,
1981            root,
1982            atoms._NET_SUPPORTED,
1983            xproto::AtomEnum::ATOM,
1984            0,
1985            1024,
1986        ),
1987    )
1988    .log_with_level(Level::Debug) else {
1989        return false;
1990    };
1991
1992    let supported_atom_ids: Vec<u32> = supported_atoms
1993        .value
1994        .chunks_exact(4)
1995        .filter_map(|chunk| chunk.try_into().ok().map(u32::from_ne_bytes))
1996        .collect();
1997
1998    supported_atom_ids.contains(&atoms._GTK_FRAME_EXTENTS)
1999}
2000
2001fn xdnd_is_atom_supported(atom: u32, atoms: &XcbAtoms) -> bool {
2002    return atom == atoms.TEXT
2003        || atom == atoms.STRING
2004        || atom == atoms.UTF8_STRING
2005        || atom == atoms.TEXT_PLAIN
2006        || atom == atoms.TEXT_PLAIN_UTF8
2007        || atom == atoms.TextUriList;
2008}
2009
2010fn xdnd_get_supported_atom(
2011    xcb_connection: &XCBConnection,
2012    supported_atoms: &XcbAtoms,
2013    target: xproto::Window,
2014) -> u32 {
2015    if let Some(reply) = get_reply(
2016        || "Failed to get XDnD supported atoms",
2017        xcb_connection.get_property(
2018            false,
2019            target,
2020            supported_atoms.XdndTypeList,
2021            AtomEnum::ANY,
2022            0,
2023            1024,
2024        ),
2025    )
2026    .log_with_level(Level::Warn)
2027    {
2028        if let Some(atoms) = reply.value32() {
2029            for atom in atoms {
2030                if xdnd_is_atom_supported(atom, &supported_atoms) {
2031                    return atom;
2032                }
2033            }
2034        }
2035    }
2036    return 0;
2037}
2038
2039fn xdnd_send_finished(
2040    xcb_connection: &XCBConnection,
2041    atoms: &XcbAtoms,
2042    source: xproto::Window,
2043    target: xproto::Window,
2044) {
2045    let message = ClientMessageEvent {
2046        format: 32,
2047        window: target,
2048        type_: atoms.XdndFinished,
2049        data: ClientMessageData::from([source, 1, atoms.XdndActionCopy, 0, 0]),
2050        sequence: 0,
2051        response_type: xproto::CLIENT_MESSAGE_EVENT,
2052    };
2053    check_reply(
2054        || "Failed to send XDnD finished event",
2055        xcb_connection.send_event(false, target, EventMask::default(), message),
2056    )
2057    .log_err();
2058    xcb_connection.flush().log_err();
2059}
2060
2061fn xdnd_send_status(
2062    xcb_connection: &XCBConnection,
2063    atoms: &XcbAtoms,
2064    source: xproto::Window,
2065    target: xproto::Window,
2066    action: u32,
2067) {
2068    let message = ClientMessageEvent {
2069        format: 32,
2070        window: target,
2071        type_: atoms.XdndStatus,
2072        data: ClientMessageData::from([source, 1, 0, 0, action]),
2073        sequence: 0,
2074        response_type: xproto::CLIENT_MESSAGE_EVENT,
2075    };
2076    check_reply(
2077        || "Failed to send XDnD status event",
2078        xcb_connection.send_event(false, target, EventMask::default(), message),
2079    )
2080    .log_err();
2081    xcb_connection.flush().log_err();
2082}
2083
2084/// Recomputes `pointer_device_states` by querying all pointer devices.
2085/// When a device is present in `scroll_values_to_preserve`, its value for `ScrollAxisState.scroll_value` is used.
2086fn current_pointer_device_states(
2087    xcb_connection: &XCBConnection,
2088    scroll_values_to_preserve: &BTreeMap<xinput::DeviceId, PointerDeviceState>,
2089) -> Option<BTreeMap<xinput::DeviceId, PointerDeviceState>> {
2090    let devices_query_result = get_reply(
2091        || "Failed to query XInput devices",
2092        xcb_connection.xinput_xi_query_device(XINPUT_ALL_DEVICES),
2093    )
2094    .log_err()?;
2095
2096    let mut pointer_device_states = BTreeMap::new();
2097    pointer_device_states.extend(
2098        devices_query_result
2099            .infos
2100            .iter()
2101            .filter(|info| is_pointer_device(info.type_))
2102            .filter_map(|info| {
2103                let scroll_data = info
2104                    .classes
2105                    .iter()
2106                    .filter_map(|class| class.data.as_scroll())
2107                    .map(|class| *class)
2108                    .rev()
2109                    .collect::<Vec<_>>();
2110                let old_state = scroll_values_to_preserve.get(&info.deviceid);
2111                let old_horizontal = old_state.map(|state| &state.horizontal);
2112                let old_vertical = old_state.map(|state| &state.vertical);
2113                let horizontal = scroll_data
2114                    .iter()
2115                    .find(|data| data.scroll_type == xinput::ScrollType::HORIZONTAL)
2116                    .map(|data| scroll_data_to_axis_state(data, old_horizontal));
2117                let vertical = scroll_data
2118                    .iter()
2119                    .find(|data| data.scroll_type == xinput::ScrollType::VERTICAL)
2120                    .map(|data| scroll_data_to_axis_state(data, old_vertical));
2121                if horizontal.is_none() && vertical.is_none() {
2122                    None
2123                } else {
2124                    Some((
2125                        info.deviceid,
2126                        PointerDeviceState {
2127                            horizontal: horizontal.unwrap_or_else(Default::default),
2128                            vertical: vertical.unwrap_or_else(Default::default),
2129                        },
2130                    ))
2131                }
2132            }),
2133    );
2134    if pointer_device_states.is_empty() {
2135        log::error!("Found no xinput mouse pointers.");
2136    }
2137    return Some(pointer_device_states);
2138}
2139
2140/// Returns true if the device is a pointer device. Does not include pointer device groups.
2141fn is_pointer_device(type_: xinput::DeviceType) -> bool {
2142    type_ == xinput::DeviceType::SLAVE_POINTER
2143}
2144
2145fn scroll_data_to_axis_state(
2146    data: &xinput::DeviceClassDataScroll,
2147    old_axis_state_with_valid_scroll_value: Option<&ScrollAxisState>,
2148) -> ScrollAxisState {
2149    ScrollAxisState {
2150        valuator_number: Some(data.number),
2151        multiplier: SCROLL_LINES / fp3232_to_f32(data.increment),
2152        scroll_value: old_axis_state_with_valid_scroll_value.and_then(|state| state.scroll_value),
2153    }
2154}
2155
2156fn reset_all_pointer_device_scroll_positions(
2157    pointer_device_states: &mut BTreeMap<xinput::DeviceId, PointerDeviceState>,
2158) {
2159    pointer_device_states
2160        .iter_mut()
2161        .for_each(|(_, device_state)| reset_pointer_device_scroll_positions(device_state));
2162}
2163
2164fn reset_pointer_device_scroll_positions(pointer: &mut PointerDeviceState) {
2165    pointer.horizontal.scroll_value = None;
2166    pointer.vertical.scroll_value = None;
2167}
2168
2169/// Returns the scroll delta for a smooth scrolling motion event, or `None` if no scroll data is present.
2170fn get_scroll_delta_and_update_state(
2171    pointer: &mut PointerDeviceState,
2172    event: &xinput::MotionEvent,
2173) -> Option<Point<f32>> {
2174    let delta_x = get_axis_scroll_delta_and_update_state(event, &mut pointer.horizontal);
2175    let delta_y = get_axis_scroll_delta_and_update_state(event, &mut pointer.vertical);
2176    if delta_x.is_some() || delta_y.is_some() {
2177        Some(Point::new(delta_x.unwrap_or(0.0), delta_y.unwrap_or(0.0)))
2178    } else {
2179        None
2180    }
2181}
2182
2183fn get_axis_scroll_delta_and_update_state(
2184    event: &xinput::MotionEvent,
2185    axis: &mut ScrollAxisState,
2186) -> Option<f32> {
2187    let axis_index = get_valuator_axis_index(&event.valuator_mask, axis.valuator_number?)?;
2188    if let Some(axis_value) = event.axisvalues.get(axis_index) {
2189        let new_scroll = fp3232_to_f32(*axis_value);
2190        let delta_scroll = axis
2191            .scroll_value
2192            .map(|old_scroll| (old_scroll - new_scroll) * axis.multiplier);
2193        axis.scroll_value = Some(new_scroll);
2194        delta_scroll
2195    } else {
2196        log::error!("Encountered invalid XInput valuator_mask, scrolling may not work properly.");
2197        None
2198    }
2199}
2200
2201fn make_scroll_wheel_event(
2202    position: Point<Pixels>,
2203    scroll_delta: Point<f32>,
2204    modifiers: Modifiers,
2205) -> crate::ScrollWheelEvent {
2206    // When shift is held down, vertical scrolling turns into horizontal scrolling.
2207    let delta = if modifiers.shift {
2208        Point {
2209            x: scroll_delta.y,
2210            y: 0.0,
2211        }
2212    } else {
2213        scroll_delta
2214    };
2215    crate::ScrollWheelEvent {
2216        position,
2217        delta: ScrollDelta::Lines(delta),
2218        modifiers,
2219        touch_phase: TouchPhase::default(),
2220    }
2221}
2222
2223fn create_invisible_cursor(
2224    connection: &XCBConnection,
2225) -> anyhow::Result<crate::platform::linux::x11::client::xproto::Cursor> {
2226    let empty_pixmap = connection.generate_id()?;
2227    let root = connection.setup().roots[0].root;
2228    connection.create_pixmap(1, empty_pixmap, root, 1, 1)?;
2229
2230    let cursor = connection.generate_id()?;
2231    connection.create_cursor(cursor, empty_pixmap, empty_pixmap, 0, 0, 0, 0, 0, 0, 0, 0)?;
2232
2233    connection.free_pixmap(empty_pixmap)?;
2234
2235    xcb_flush(connection);
2236    Ok(cursor)
2237}
2238
2239enum DpiMode {
2240    Randr,
2241    Scale(f32),
2242    NotSet,
2243}
2244
2245fn get_scale_factor(
2246    connection: &XCBConnection,
2247    resource_database: &Database,
2248    screen_index: usize,
2249) -> f32 {
2250    let env_dpi = std::env::var(GPUI_X11_SCALE_FACTOR_ENV)
2251        .ok()
2252        .map(|var| {
2253            if var.to_lowercase() == "randr" {
2254                DpiMode::Randr
2255            } else if let Ok(scale) = var.parse::<f32>() {
2256                if valid_scale_factor(scale) {
2257                    DpiMode::Scale(scale)
2258                } else {
2259                    panic!(
2260                        "`{}` must be a positive normal number or `randr`. Got `{}`",
2261                        GPUI_X11_SCALE_FACTOR_ENV, var
2262                    );
2263                }
2264            } else if var.is_empty() {
2265                DpiMode::NotSet
2266            } else {
2267                panic!(
2268                    "`{}` must be a positive number or `randr`. Got `{}`",
2269                    GPUI_X11_SCALE_FACTOR_ENV, var
2270                );
2271            }
2272        })
2273        .unwrap_or(DpiMode::NotSet);
2274
2275    match env_dpi {
2276        DpiMode::Scale(scale) => {
2277            log::info!(
2278                "Using scale factor from {}: {}",
2279                GPUI_X11_SCALE_FACTOR_ENV,
2280                scale
2281            );
2282            return scale;
2283        }
2284        DpiMode::Randr => {
2285            if let Some(scale) = get_randr_scale_factor(connection, screen_index) {
2286                log::info!(
2287                    "Using RandR scale factor from {}=randr: {}",
2288                    GPUI_X11_SCALE_FACTOR_ENV,
2289                    scale
2290                );
2291                return scale;
2292            }
2293            log::warn!("Failed to calculate RandR scale factor, falling back to default");
2294            return 1.0;
2295        }
2296        DpiMode::NotSet => {}
2297    }
2298
2299    // TODO: Use scale factor from XSettings here
2300
2301    if let Some(dpi) = resource_database
2302        .get_value::<f32>("Xft.dpi", "Xft.dpi")
2303        .ok()
2304        .flatten()
2305    {
2306        let scale = dpi / 96.0; // base dpi
2307        log::info!("Using scale factor from Xft.dpi: {}", scale);
2308        return scale;
2309    }
2310
2311    if let Some(scale) = get_randr_scale_factor(connection, screen_index) {
2312        log::info!("Using RandR scale factor: {}", scale);
2313        return scale;
2314    }
2315
2316    log::info!("Using default scale factor: 1.0");
2317    1.0
2318}
2319
2320fn get_randr_scale_factor(connection: &XCBConnection, screen_index: usize) -> Option<f32> {
2321    let root = connection.setup().roots.get(screen_index)?.root;
2322
2323    let version_cookie = connection.randr_query_version(1, 6).ok()?;
2324    let version_reply = version_cookie.reply().ok()?;
2325    if version_reply.major_version < 1
2326        || (version_reply.major_version == 1 && version_reply.minor_version < 5)
2327    {
2328        return legacy_get_randr_scale_factor(connection, root); // for randr <1.5
2329    }
2330
2331    let monitors_cookie = connection.randr_get_monitors(root, true).ok()?; // true for active only
2332    let monitors_reply = monitors_cookie.reply().ok()?;
2333
2334    let mut fallback_scale: Option<f32> = None;
2335    for monitor in monitors_reply.monitors {
2336        if monitor.width_in_millimeters == 0 || monitor.height_in_millimeters == 0 {
2337            continue;
2338        }
2339        let scale_factor = get_dpi_factor(
2340            (monitor.width as u32, monitor.height as u32),
2341            (
2342                monitor.width_in_millimeters as u64,
2343                monitor.height_in_millimeters as u64,
2344            ),
2345        );
2346        if monitor.primary {
2347            return Some(scale_factor);
2348        } else if fallback_scale.is_none() {
2349            fallback_scale = Some(scale_factor);
2350        }
2351    }
2352
2353    fallback_scale
2354}
2355
2356fn legacy_get_randr_scale_factor(connection: &XCBConnection, root: u32) -> Option<f32> {
2357    let primary_cookie = connection.randr_get_output_primary(root).ok()?;
2358    let primary_reply = primary_cookie.reply().ok()?;
2359    let primary_output = primary_reply.output;
2360
2361    let primary_output_cookie = connection
2362        .randr_get_output_info(primary_output, x11rb::CURRENT_TIME)
2363        .ok()?;
2364    let primary_output_info = primary_output_cookie.reply().ok()?;
2365
2366    // try primary
2367    if primary_output_info.connection == randr::Connection::CONNECTED
2368        && primary_output_info.mm_width > 0
2369        && primary_output_info.mm_height > 0
2370        && primary_output_info.crtc != 0
2371    {
2372        let crtc_cookie = connection
2373            .randr_get_crtc_info(primary_output_info.crtc, x11rb::CURRENT_TIME)
2374            .ok()?;
2375        let crtc_info = crtc_cookie.reply().ok()?;
2376
2377        if crtc_info.width > 0 && crtc_info.height > 0 {
2378            let scale_factor = get_dpi_factor(
2379                (crtc_info.width as u32, crtc_info.height as u32),
2380                (
2381                    primary_output_info.mm_width as u64,
2382                    primary_output_info.mm_height as u64,
2383                ),
2384            );
2385            return Some(scale_factor);
2386        }
2387    }
2388
2389    // fallback: full scan
2390    let resources_cookie = connection.randr_get_screen_resources_current(root).ok()?;
2391    let screen_resources = resources_cookie.reply().ok()?;
2392
2393    let mut crtc_cookies = Vec::with_capacity(screen_resources.crtcs.len());
2394    for &crtc in &screen_resources.crtcs {
2395        if let Ok(cookie) = connection.randr_get_crtc_info(crtc, x11rb::CURRENT_TIME) {
2396            crtc_cookies.push((crtc, cookie));
2397        }
2398    }
2399
2400    let mut crtc_infos: HashMap<randr::Crtc, randr::GetCrtcInfoReply> = HashMap::default();
2401    let mut valid_outputs: HashSet<randr::Output> = HashSet::new();
2402    for (crtc, cookie) in crtc_cookies {
2403        if let Ok(reply) = cookie.reply() {
2404            if reply.width > 0 && reply.height > 0 && !reply.outputs.is_empty() {
2405                crtc_infos.insert(crtc, reply.clone());
2406                valid_outputs.extend(&reply.outputs);
2407            }
2408        }
2409    }
2410
2411    if valid_outputs.is_empty() {
2412        return None;
2413    }
2414
2415    let mut output_cookies = Vec::with_capacity(valid_outputs.len());
2416    for &output in &valid_outputs {
2417        if let Ok(cookie) = connection.randr_get_output_info(output, x11rb::CURRENT_TIME) {
2418            output_cookies.push((output, cookie));
2419        }
2420    }
2421    let mut output_infos: HashMap<randr::Output, randr::GetOutputInfoReply> = HashMap::default();
2422    for (output, cookie) in output_cookies {
2423        if let Ok(reply) = cookie.reply() {
2424            output_infos.insert(output, reply);
2425        }
2426    }
2427
2428    let mut fallback_scale: Option<f32> = None;
2429    for crtc_info in crtc_infos.values() {
2430        for &output in &crtc_info.outputs {
2431            if let Some(output_info) = output_infos.get(&output) {
2432                if output_info.connection != randr::Connection::CONNECTED {
2433                    continue;
2434                }
2435
2436                if output_info.mm_width == 0 || output_info.mm_height == 0 {
2437                    continue;
2438                }
2439
2440                let scale_factor = get_dpi_factor(
2441                    (crtc_info.width as u32, crtc_info.height as u32),
2442                    (output_info.mm_width as u64, output_info.mm_height as u64),
2443                );
2444
2445                if output != primary_output && fallback_scale.is_none() {
2446                    fallback_scale = Some(scale_factor);
2447                }
2448            }
2449        }
2450    }
2451
2452    fallback_scale
2453}
2454
2455fn get_dpi_factor((width_px, height_px): (u32, u32), (width_mm, height_mm): (u64, u64)) -> f32 {
2456    let ppmm = ((width_px as f64 * height_px as f64) / (width_mm as f64 * height_mm as f64)).sqrt(); // pixels per mm
2457
2458    const MM_PER_INCH: f64 = 25.4;
2459    const BASE_DPI: f64 = 96.0;
2460    const QUANTIZE_STEP: f64 = 12.0; // e.g. 1.25 = 15/12, 1.5 = 18/12, 1.75 = 21/12, 2.0 = 24/12
2461    const MIN_SCALE: f64 = 1.0;
2462    const MAX_SCALE: f64 = 20.0;
2463
2464    let dpi_factor =
2465        ((ppmm * (QUANTIZE_STEP * MM_PER_INCH / BASE_DPI)).round() / QUANTIZE_STEP).max(MIN_SCALE);
2466
2467    let validated_factor = if dpi_factor <= MAX_SCALE {
2468        dpi_factor
2469    } else {
2470        MIN_SCALE
2471    };
2472
2473    if valid_scale_factor(validated_factor as f32) {
2474        validated_factor as f32
2475    } else {
2476        log::warn!(
2477            "Calculated DPI factor {} is invalid, using 1.0",
2478            validated_factor
2479        );
2480        1.0
2481    }
2482}
2483
2484#[inline]
2485fn valid_scale_factor(scale_factor: f32) -> bool {
2486    scale_factor.is_sign_positive() && scale_factor.is_normal()
2487}