client.rs

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