client.rs

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