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