Skip to repository content

tenant.openagents/omega

No repository description is available.

OpenAgents Git authority 2026-07-28T03:59:28.710Z Public web read
NIP-34 coordinate30617:7649603503856e5148d571eac2766b288a8ff1e9e35d380337a1d2b0015b4f92:omega
MaintainersHidden in public view
References2 branches · 1 tag
Read-only clonegit clone https://openagents.com/git/tenant.openagents/omega.git
Browse files

client.rs

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