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