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