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