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 @ ConnectionError::IoError(..)) => {
606 return Err(EventHandlerError::from(err));
607 }
608 Err(err) => {
609 let err = handle_connection_error(err);
610 log::warn!("error while polling for X11 events: {err:?}");
611 break;
612 }
613 }
614 }
615
616 if let Some(release_event) = last_key_release.take() {
617 events.push(release_event);
618 }
619 if let Some(keymap_change_event) = last_keymap_change_event.take() {
620 events.push(keymap_change_event);
621 }
622
623 if events.is_empty() && windows_to_refresh.is_empty() {
624 break;
625 }
626
627 for window in windows_to_refresh.into_iter() {
628 let mut state = self.0.borrow_mut();
629 if let Some(window) = state.windows.get_mut(&window) {
630 window.expose_event_received = true;
631 }
632 }
633
634 for event in events.into_iter() {
635 let mut state = self.0.borrow_mut();
636 if !state.has_xim() {
637 drop(state);
638 self.handle_event(event);
639 continue;
640 }
641
642 let Some((mut ximc, mut xim_handler)) = state.take_xim() else {
643 continue;
644 };
645 let xim_connected = xim_handler.connected;
646 drop(state);
647
648 let xim_filtered = ximc.filter_event(&event, &mut xim_handler);
649 let xim_callback_event = xim_handler.last_callback_event.take();
650
651 let mut state = self.0.borrow_mut();
652 state.restore_xim(ximc, xim_handler);
653 drop(state);
654
655 if let Some(event) = xim_callback_event {
656 self.handle_xim_callback_event(event);
657 }
658
659 match xim_filtered {
660 Ok(handled) => {
661 if handled {
662 continue;
663 }
664 if xim_connected {
665 self.xim_handle_event(event);
666 } else {
667 self.handle_event(event);
668 }
669 }
670 Err(err) => {
671 // this might happen when xim server crashes on one of the events
672 // we do lose 1-2 keys when crash happens since there is no reliable way to get that info
673 // luckily, x11 sends us window not found error when xim server crashes upon further key press
674 // hence we fall back to handle_event
675 log::error!("XIMClientError: {}", err);
676 let mut state = self.0.borrow_mut();
677 state.take_xim();
678 drop(state);
679 self.handle_event(event);
680 }
681 }
682 }
683 }
684 Ok(())
685 }
686
687 pub fn enable_ime(&self) {
688 let mut state = self.0.borrow_mut();
689 if !state.has_xim() {
690 return;
691 }
692
693 let Some((mut ximc, xim_handler)) = state.take_xim() else {
694 return;
695 };
696 let mut ic_attributes = ximc
697 .build_ic_attributes()
698 .push(AttributeName::InputStyle, InputStyle::PREEDIT_CALLBACKS)
699 .push(AttributeName::ClientWindow, xim_handler.window)
700 .push(AttributeName::FocusWindow, xim_handler.window);
701
702 let window_id = state.keyboard_focused_window;
703 drop(state);
704 if let Some(window_id) = window_id {
705 let Some(window) = self.get_window(window_id) else {
706 log::error!("Failed to get window for IME positioning");
707 let mut state = self.0.borrow_mut();
708 state.ximc = Some(ximc);
709 state.xim_handler = Some(xim_handler);
710 return;
711 };
712 if let Some(scaled_area) = window.get_ime_area() {
713 ic_attributes =
714 ic_attributes.nested_list(xim::AttributeName::PreeditAttributes, |b| {
715 b.push(
716 xim::AttributeName::SpotLocation,
717 xim::Point {
718 x: u32::from(scaled_area.origin.x + scaled_area.size.width) as i16,
719 y: u32::from(scaled_area.origin.y + scaled_area.size.height) as i16,
720 },
721 );
722 });
723 }
724 }
725 ximc.create_ic(xim_handler.im_id, ic_attributes.build())
726 .ok();
727 let mut state = self.0.borrow_mut();
728 state.restore_xim(ximc, xim_handler);
729 }
730
731 pub fn reset_ime(&self) {
732 let mut state = self.0.borrow_mut();
733 state.composing = false;
734 if let Some(mut ximc) = state.ximc.take() {
735 if let Some(xim_handler) = state.xim_handler.as_ref() {
736 ximc.reset_ic(xim_handler.im_id, xim_handler.ic_id).ok();
737 } else {
738 log::error!("bug: xim handler not set in reset_ime");
739 }
740 state.ximc = Some(ximc);
741 }
742 }
743
744 pub(crate) fn get_window(&self, win: xproto::Window) -> Option<X11WindowStatePtr> {
745 let state = self.0.borrow();
746 state
747 .windows
748 .get(&win)
749 .filter(|window_reference| !window_reference.window.state.borrow().destroyed)
750 .map(|window_reference| window_reference.window.clone())
751 }
752
753 fn handle_event(&self, event: Event) -> Option<()> {
754 match event {
755 Event::UnmapNotify(event) => {
756 let mut state = self.0.borrow_mut();
757 if let Some(window_ref) = state.windows.get_mut(&event.window) {
758 window_ref.is_mapped = false;
759 }
760 state.update_refresh_loop(event.window);
761 }
762 Event::MapNotify(event) => {
763 let mut state = self.0.borrow_mut();
764 if let Some(window_ref) = state.windows.get_mut(&event.window) {
765 window_ref.is_mapped = true;
766 }
767 state.update_refresh_loop(event.window);
768 }
769 Event::VisibilityNotify(event) => {
770 let mut state = self.0.borrow_mut();
771 if let Some(window_ref) = state.windows.get_mut(&event.window) {
772 window_ref.last_visibility = event.state;
773 }
774 state.update_refresh_loop(event.window);
775 }
776 Event::ClientMessage(event) => {
777 let window = self.get_window(event.window)?;
778 let [atom, arg1, arg2, arg3, arg4] = event.data.as_data32();
779 let mut state = self.0.borrow_mut();
780
781 if atom == state.atoms.WM_DELETE_WINDOW && window.should_close() {
782 // window "x" button clicked by user
783 // Rest of the close logic is handled in drop_window()
784 drop(state);
785 window.close();
786 state = self.0.borrow_mut();
787 } else if atom == state.atoms._NET_WM_SYNC_REQUEST {
788 window.state.borrow_mut().last_sync_counter =
789 Some(x11rb::protocol::sync::Int64 {
790 lo: arg2,
791 hi: arg3 as i32,
792 })
793 }
794
795 if event.type_ == state.atoms.XdndEnter {
796 state.xdnd_state.other_window = atom;
797 if (arg1 & 0x1) == 0x1 {
798 state.xdnd_state.drag_type = xdnd_get_supported_atom(
799 &state.xcb_connection,
800 &state.atoms,
801 state.xdnd_state.other_window,
802 );
803 } else {
804 if let Some(atom) = [arg2, arg3, arg4]
805 .into_iter()
806 .find(|atom| xdnd_is_atom_supported(*atom, &state.atoms))
807 {
808 state.xdnd_state.drag_type = atom;
809 }
810 }
811 } else if event.type_ == state.atoms.XdndLeave {
812 let position = state.xdnd_state.position;
813 drop(state);
814 window
815 .handle_input(PlatformInput::FileDrop(FileDropEvent::Pending { position }));
816 window.handle_input(PlatformInput::FileDrop(FileDropEvent::Exited {}));
817 self.0.borrow_mut().xdnd_state = Xdnd::default();
818 } else if event.type_ == state.atoms.XdndPosition {
819 if let Ok(pos) = get_reply(
820 || "Failed to query pointer position",
821 state.xcb_connection.query_pointer(event.window),
822 ) {
823 state.xdnd_state.position =
824 Point::new(px(pos.win_x as f32), px(pos.win_y as f32));
825 }
826 if !state.xdnd_state.retrieved {
827 check_reply(
828 || "Failed to convert selection for drag and drop",
829 state.xcb_connection.convert_selection(
830 event.window,
831 state.atoms.XdndSelection,
832 state.xdnd_state.drag_type,
833 state.atoms.XDND_DATA,
834 arg3,
835 ),
836 )
837 .log_err();
838 }
839 xdnd_send_status(
840 &state.xcb_connection,
841 &state.atoms,
842 event.window,
843 state.xdnd_state.other_window,
844 arg4,
845 );
846 let position = state.xdnd_state.position;
847 drop(state);
848 window
849 .handle_input(PlatformInput::FileDrop(FileDropEvent::Pending { position }));
850 } else if event.type_ == state.atoms.XdndDrop {
851 xdnd_send_finished(
852 &state.xcb_connection,
853 &state.atoms,
854 event.window,
855 state.xdnd_state.other_window,
856 );
857 let position = state.xdnd_state.position;
858 drop(state);
859 window
860 .handle_input(PlatformInput::FileDrop(FileDropEvent::Submit { position }));
861 self.0.borrow_mut().xdnd_state = Xdnd::default();
862 }
863 }
864 Event::SelectionNotify(event) => {
865 let window = self.get_window(event.requestor)?;
866 let state = self.0.borrow_mut();
867 let reply = get_reply(
868 || "Failed to get XDND_DATA",
869 state.xcb_connection.get_property(
870 false,
871 event.requestor,
872 state.atoms.XDND_DATA,
873 AtomEnum::ANY,
874 0,
875 1024,
876 ),
877 )
878 .log_err();
879 let Some(reply) = reply else {
880 return Some(());
881 };
882 if let Ok(file_list) = str::from_utf8(&reply.value) {
883 let paths: SmallVec<[_; 2]> = file_list
884 .lines()
885 .filter_map(|path| Url::parse(path).log_err())
886 .filter_map(|url| url.to_file_path().log_err())
887 .collect();
888 let input = PlatformInput::FileDrop(FileDropEvent::Entered {
889 position: state.xdnd_state.position,
890 paths: gpui::ExternalPaths(paths),
891 });
892 drop(state);
893 window.handle_input(input);
894 self.0.borrow_mut().xdnd_state.retrieved = true;
895 }
896 }
897 Event::ConfigureNotify(event) => {
898 let bounds = Bounds {
899 origin: Point {
900 x: event.x.into(),
901 y: event.y.into(),
902 },
903 size: Size {
904 width: event.width.into(),
905 height: event.height.into(),
906 },
907 };
908 let window = self.get_window(event.window)?;
909 window
910 .set_bounds(bounds)
911 .context("X11: Failed to set window bounds")
912 .log_err();
913 }
914 Event::PropertyNotify(event) => {
915 let window = self.get_window(event.window)?;
916 window
917 .property_notify(event)
918 .context("X11: Failed to handle property notify")
919 .log_err();
920 }
921 Event::FocusIn(event) => {
922 let window = self.get_window(event.event)?;
923 window.set_active(true);
924 let mut state = self.0.borrow_mut();
925 state.keyboard_focused_window = Some(event.event);
926 if let Some(handler) = state.xim_handler.as_mut() {
927 handler.window = event.event;
928 }
929 drop(state);
930 self.enable_ime();
931 }
932 Event::FocusOut(event) => {
933 let window = self.get_window(event.event)?;
934 window.set_active(false);
935 let mut state = self.0.borrow_mut();
936 // 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)
937 reset_all_pointer_device_scroll_positions(&mut state.pointer_device_states);
938 state.keyboard_focused_window = None;
939 if let Some(compose_state) = state.compose_state.as_mut() {
940 compose_state.reset();
941 }
942 state.pre_edit_text.take();
943 drop(state);
944 self.reset_ime();
945 window.handle_ime_delete();
946 }
947 Event::XkbNewKeyboardNotify(_) | Event::XkbMapNotify(_) => {
948 let mut state = self.0.borrow_mut();
949 let xkb_state = {
950 let xkb_keymap = xkbc::x11::keymap_new_from_device(
951 &state.xkb_context,
952 &state.xcb_connection,
953 state.xkb_device_id,
954 xkbc::KEYMAP_COMPILE_NO_FLAGS,
955 );
956 xkbc::x11::state_new_from_device(
957 &xkb_keymap,
958 &state.xcb_connection,
959 state.xkb_device_id,
960 )
961 };
962 state.xkb = xkb_state;
963 drop(state);
964 self.handle_keyboard_layout_change();
965 }
966 Event::XkbStateNotify(event) => {
967 let mut state = self.0.borrow_mut();
968 let old_layout = state.xkb.serialize_layout(STATE_LAYOUT_EFFECTIVE);
969 let new_layout = u32::from(event.group);
970 state.xkb.update_mask(
971 event.base_mods.into(),
972 event.latched_mods.into(),
973 event.locked_mods.into(),
974 event.base_group as u32,
975 event.latched_group as u32,
976 event.locked_group.into(),
977 );
978 let modifiers = modifiers_from_xkb(&state.xkb);
979 let capslock = capslock_from_xkb(&state.xkb);
980 if state.last_modifiers_changed_event == modifiers
981 && state.last_capslock_changed_event == capslock
982 {
983 drop(state);
984 } else {
985 let focused_window_id = state.keyboard_focused_window?;
986 state.modifiers = modifiers;
987 state.last_modifiers_changed_event = modifiers;
988 state.capslock = capslock;
989 state.last_capslock_changed_event = capslock;
990 drop(state);
991
992 let focused_window = self.get_window(focused_window_id)?;
993 focused_window.handle_input(PlatformInput::ModifiersChanged(
994 ModifiersChangedEvent {
995 modifiers,
996 capslock,
997 },
998 ));
999 }
1000
1001 if new_layout != old_layout {
1002 self.handle_keyboard_layout_change();
1003 }
1004 }
1005 Event::KeyPress(event) => {
1006 let window = self.get_window(event.event)?;
1007 let mut state = self.0.borrow_mut();
1008
1009 let modifiers = modifiers_from_state(event.state);
1010 state.modifiers = modifiers;
1011 state.pre_key_char_down.take();
1012
1013 // Macros containing modifiers might result in
1014 // the modifiers missing from the event.
1015 // We therefore update the mask from the global state.
1016 update_xkb_mask_from_event_state(&mut state.xkb, event.state);
1017
1018 let keystroke = {
1019 let code = event.detail.into();
1020 let mut keystroke = keystroke_from_xkb(&state.xkb, modifiers, code);
1021 let keysym = state.xkb.key_get_one_sym(code);
1022
1023 if keysym.is_modifier_key() {
1024 return Some(());
1025 }
1026
1027 // should be called after key_get_one_sym
1028 state.xkb.update_key(code, xkbc::KeyDirection::Down);
1029
1030 if let Some(mut compose_state) = state.compose_state.take() {
1031 compose_state.feed(keysym);
1032 match compose_state.status() {
1033 xkbc::Status::Composed => {
1034 state.pre_edit_text.take();
1035 keystroke.key_char = compose_state.utf8();
1036 if let Some(keysym) = compose_state.keysym() {
1037 keystroke.key = xkbc::keysym_get_name(keysym);
1038 }
1039 }
1040 xkbc::Status::Composing => {
1041 keystroke.key_char = None;
1042 state.pre_edit_text = compose_state
1043 .utf8()
1044 .or(keystroke_underlying_dead_key(keysym));
1045 let pre_edit =
1046 state.pre_edit_text.clone().unwrap_or(String::default());
1047 drop(state);
1048 window.handle_ime_preedit(pre_edit);
1049 state = self.0.borrow_mut();
1050 }
1051 xkbc::Status::Cancelled => {
1052 let pre_edit = state.pre_edit_text.take();
1053 drop(state);
1054 if let Some(pre_edit) = pre_edit {
1055 window.handle_ime_commit(pre_edit);
1056 }
1057 if let Some(current_key) = keystroke_underlying_dead_key(keysym) {
1058 window.handle_ime_preedit(current_key);
1059 }
1060 state = self.0.borrow_mut();
1061 compose_state.feed(keysym);
1062 }
1063 _ => {}
1064 }
1065 state.compose_state = Some(compose_state);
1066 }
1067 keystroke
1068 };
1069 drop(state);
1070 window.handle_input(PlatformInput::KeyDown(gpui::KeyDownEvent {
1071 keystroke,
1072 is_held: false,
1073 prefer_character_input: false,
1074 }));
1075 }
1076 Event::KeyRelease(event) => {
1077 let window = self.get_window(event.event)?;
1078 let mut state = self.0.borrow_mut();
1079
1080 let modifiers = modifiers_from_state(event.state);
1081 state.modifiers = modifiers;
1082
1083 // Macros containing modifiers might result in
1084 // the modifiers missing from the event.
1085 // We therefore update the mask from the global state.
1086 update_xkb_mask_from_event_state(&mut state.xkb, event.state);
1087
1088 let keystroke = {
1089 let code = event.detail.into();
1090 let keystroke = keystroke_from_xkb(&state.xkb, modifiers, code);
1091 let keysym = state.xkb.key_get_one_sym(code);
1092
1093 if keysym.is_modifier_key() {
1094 return Some(());
1095 }
1096
1097 // should be called after key_get_one_sym
1098 state.xkb.update_key(code, xkbc::KeyDirection::Up);
1099
1100 keystroke
1101 };
1102 drop(state);
1103 window.handle_input(PlatformInput::KeyUp(gpui::KeyUpEvent { keystroke }));
1104 }
1105 Event::XinputButtonPress(event) => {
1106 let window = self.get_window(event.event)?;
1107 let mut state = self.0.borrow_mut();
1108
1109 let modifiers = modifiers_from_xinput_info(event.mods);
1110 state.modifiers = modifiers;
1111
1112 let position = point(
1113 px(event.event_x as f32 / u16::MAX as f32 / state.scale_factor),
1114 px(event.event_y as f32 / u16::MAX as f32 / state.scale_factor),
1115 );
1116
1117 if state.composing && state.ximc.is_some() {
1118 drop(state);
1119 self.reset_ime();
1120 window.handle_ime_unmark();
1121 state = self.0.borrow_mut();
1122 } else if let Some(text) = state.pre_edit_text.take() {
1123 if let Some(compose_state) = state.compose_state.as_mut() {
1124 compose_state.reset();
1125 }
1126 drop(state);
1127 window.handle_ime_commit(text);
1128 state = self.0.borrow_mut();
1129 }
1130 match button_or_scroll_from_event_detail(event.detail) {
1131 Some(ButtonOrScroll::Button(button)) => {
1132 let click_elapsed = state.last_click.elapsed();
1133 if click_elapsed < DOUBLE_CLICK_INTERVAL
1134 && state
1135 .last_mouse_button
1136 .is_some_and(|prev_button| prev_button == button)
1137 && is_within_click_distance(state.last_location, position)
1138 {
1139 state.current_count += 1;
1140 } else {
1141 state.current_count = 1;
1142 }
1143
1144 state.last_click = Instant::now();
1145 state.last_mouse_button = Some(button);
1146 state.last_location = position;
1147 let current_count = state.current_count;
1148
1149 drop(state);
1150 window.handle_input(PlatformInput::MouseDown(gpui::MouseDownEvent {
1151 button,
1152 position,
1153 modifiers,
1154 click_count: current_count,
1155 first_mouse: false,
1156 }));
1157 }
1158 Some(ButtonOrScroll::Scroll(direction)) => {
1159 drop(state);
1160 // Emulated scroll button presses are sent simultaneously with smooth scrolling XinputMotion events.
1161 // Since handling those events does the scrolling, they are skipped here.
1162 if !event
1163 .flags
1164 .contains(xinput::PointerEventFlags::POINTER_EMULATED)
1165 {
1166 let scroll_delta = match direction {
1167 ScrollDirection::Up => Point::new(0.0, SCROLL_LINES),
1168 ScrollDirection::Down => Point::new(0.0, -SCROLL_LINES),
1169 ScrollDirection::Left => Point::new(SCROLL_LINES, 0.0),
1170 ScrollDirection::Right => Point::new(-SCROLL_LINES, 0.0),
1171 };
1172 window.handle_input(PlatformInput::ScrollWheel(
1173 make_scroll_wheel_event(position, scroll_delta, modifiers),
1174 ));
1175 }
1176 }
1177 None => {
1178 log::error!("Unknown x11 button: {}", event.detail);
1179 }
1180 }
1181 }
1182 Event::XinputButtonRelease(event) => {
1183 let window = self.get_window(event.event)?;
1184 let mut state = self.0.borrow_mut();
1185 let modifiers = modifiers_from_xinput_info(event.mods);
1186 state.modifiers = modifiers;
1187
1188 let position = point(
1189 px(event.event_x as f32 / u16::MAX as f32 / state.scale_factor),
1190 px(event.event_y as f32 / u16::MAX as f32 / state.scale_factor),
1191 );
1192 match button_or_scroll_from_event_detail(event.detail) {
1193 Some(ButtonOrScroll::Button(button)) => {
1194 let click_count = state.current_count;
1195 drop(state);
1196 window.handle_input(PlatformInput::MouseUp(gpui::MouseUpEvent {
1197 button,
1198 position,
1199 modifiers,
1200 click_count,
1201 }));
1202 }
1203 Some(ButtonOrScroll::Scroll(_)) => {}
1204 None => {}
1205 }
1206 }
1207 Event::XinputMotion(event) => {
1208 let window = self.get_window(event.event)?;
1209 let mut state = self.0.borrow_mut();
1210 if window.is_blocked() {
1211 // We want to set the cursor to the default arrow
1212 // when the window is blocked
1213 let style = CursorStyle::Arrow;
1214
1215 let current_style = state
1216 .cursor_styles
1217 .get(&window.x_window)
1218 .unwrap_or(&CursorStyle::Arrow);
1219 if *current_style != style
1220 && let Some(cursor) = state.get_cursor_icon(style)
1221 {
1222 state.cursor_styles.insert(window.x_window, style);
1223 check_reply(
1224 || "Failed to set cursor style",
1225 state.xcb_connection.change_window_attributes(
1226 window.x_window,
1227 &ChangeWindowAttributesAux {
1228 cursor: Some(cursor),
1229 ..Default::default()
1230 },
1231 ),
1232 )
1233 .log_err();
1234 state.xcb_connection.flush().log_err();
1235 };
1236 }
1237 let pressed_button = pressed_button_from_mask(event.button_mask[0]);
1238 let position = point(
1239 px(event.event_x as f32 / u16::MAX as f32 / state.scale_factor),
1240 px(event.event_y as f32 / u16::MAX as f32 / state.scale_factor),
1241 );
1242 let modifiers = modifiers_from_xinput_info(event.mods);
1243 state.modifiers = modifiers;
1244 drop(state);
1245
1246 if event.valuator_mask[0] & 3 != 0 {
1247 window.handle_input(PlatformInput::MouseMove(gpui::MouseMoveEvent {
1248 position,
1249 pressed_button,
1250 modifiers,
1251 }));
1252 }
1253
1254 state = self.0.borrow_mut();
1255 if let Some(pointer) = state.pointer_device_states.get_mut(&event.sourceid) {
1256 let scroll_delta = get_scroll_delta_and_update_state(pointer, &event);
1257 drop(state);
1258 if let Some(scroll_delta) = scroll_delta {
1259 window.handle_input(PlatformInput::ScrollWheel(make_scroll_wheel_event(
1260 position,
1261 scroll_delta,
1262 modifiers,
1263 )));
1264 }
1265 }
1266 }
1267 Event::XinputEnter(event) if event.mode == xinput::NotifyMode::NORMAL => {
1268 let window = self.get_window(event.event)?;
1269 window.set_hovered(true);
1270 let mut state = self.0.borrow_mut();
1271 state.mouse_focused_window = Some(event.event);
1272 }
1273 Event::XinputLeave(event) if event.mode == xinput::NotifyMode::NORMAL => {
1274 let mut state = self.0.borrow_mut();
1275
1276 // 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)
1277 reset_all_pointer_device_scroll_positions(&mut state.pointer_device_states);
1278 state.mouse_focused_window = None;
1279 let pressed_button = pressed_button_from_mask(event.buttons[0]);
1280 let position = point(
1281 px(event.event_x as f32 / u16::MAX as f32 / state.scale_factor),
1282 px(event.event_y as f32 / u16::MAX as f32 / state.scale_factor),
1283 );
1284 let modifiers = modifiers_from_xinput_info(event.mods);
1285 state.modifiers = modifiers;
1286 drop(state);
1287
1288 let window = self.get_window(event.event)?;
1289 window.handle_input(PlatformInput::MouseExited(gpui::MouseExitEvent {
1290 pressed_button,
1291 position,
1292 modifiers,
1293 }));
1294 window.set_hovered(false);
1295 }
1296 Event::XinputHierarchy(event) => {
1297 let mut state = self.0.borrow_mut();
1298 // Temporarily use `state.pointer_device_states` to only store pointers that still have valid scroll values.
1299 // Any change to a device invalidates its scroll values.
1300 for info in event.infos {
1301 if is_pointer_device(info.type_) {
1302 state.pointer_device_states.remove(&info.deviceid);
1303 }
1304 }
1305 if let Some(pointer_device_states) = current_pointer_device_states(
1306 &state.xcb_connection,
1307 &state.pointer_device_states,
1308 ) {
1309 state.pointer_device_states = pointer_device_states;
1310 }
1311 }
1312 Event::XinputDeviceChanged(event) => {
1313 let mut state = self.0.borrow_mut();
1314 if let Some(pointer) = state.pointer_device_states.get_mut(&event.sourceid) {
1315 reset_pointer_device_scroll_positions(pointer);
1316 }
1317 }
1318 _ => {}
1319 };
1320
1321 Some(())
1322 }
1323
1324 fn handle_xim_callback_event(&self, event: XimCallbackEvent) {
1325 match event {
1326 XimCallbackEvent::XimXEvent(event) => {
1327 self.handle_event(event);
1328 }
1329 XimCallbackEvent::XimCommitEvent(window, text) => {
1330 self.xim_handle_commit(window, text);
1331 }
1332 XimCallbackEvent::XimPreeditEvent(window, text) => {
1333 self.xim_handle_preedit(window, text);
1334 }
1335 };
1336 }
1337
1338 fn xim_handle_event(&self, event: Event) -> Option<()> {
1339 match event {
1340 Event::KeyPress(event) | Event::KeyRelease(event) => {
1341 let mut state = self.0.borrow_mut();
1342 state.pre_key_char_down = Some(keystroke_from_xkb(
1343 &state.xkb,
1344 state.modifiers,
1345 event.detail.into(),
1346 ));
1347 let (mut ximc, mut xim_handler) = state.take_xim()?;
1348 drop(state);
1349 xim_handler.window = event.event;
1350 ximc.forward_event(
1351 xim_handler.im_id,
1352 xim_handler.ic_id,
1353 xim::ForwardEventFlag::empty(),
1354 &event,
1355 )
1356 .context("X11: Failed to forward XIM event")
1357 .log_err();
1358 let mut state = self.0.borrow_mut();
1359 state.restore_xim(ximc, xim_handler);
1360 drop(state);
1361 }
1362 event => {
1363 self.handle_event(event);
1364 }
1365 }
1366 Some(())
1367 }
1368
1369 fn xim_handle_commit(&self, window: xproto::Window, text: String) -> Option<()> {
1370 let Some(window) = self.get_window(window) else {
1371 log::error!("bug: Failed to get window for XIM commit");
1372 return None;
1373 };
1374 let mut state = self.0.borrow_mut();
1375 state.composing = false;
1376 drop(state);
1377 window.handle_ime_commit(text);
1378 Some(())
1379 }
1380
1381 fn xim_handle_preedit(&self, window: xproto::Window, text: String) -> Option<()> {
1382 let Some(window) = self.get_window(window) else {
1383 log::error!("bug: Failed to get window for XIM preedit");
1384 return None;
1385 };
1386
1387 let mut state = self.0.borrow_mut();
1388 let (mut ximc, xim_handler) = state.take_xim()?;
1389 state.composing = !text.is_empty();
1390 drop(state);
1391 window.handle_ime_preedit(text);
1392
1393 if let Some(scaled_area) = window.get_ime_area() {
1394 let ic_attributes = ximc
1395 .build_ic_attributes()
1396 .push(
1397 xim::AttributeName::InputStyle,
1398 xim::InputStyle::PREEDIT_CALLBACKS,
1399 )
1400 .push(xim::AttributeName::ClientWindow, xim_handler.window)
1401 .push(xim::AttributeName::FocusWindow, xim_handler.window)
1402 .nested_list(xim::AttributeName::PreeditAttributes, |b| {
1403 b.push(
1404 xim::AttributeName::SpotLocation,
1405 xim::Point {
1406 x: u32::from(scaled_area.origin.x + scaled_area.size.width) as i16,
1407 y: u32::from(scaled_area.origin.y + scaled_area.size.height) as i16,
1408 },
1409 );
1410 })
1411 .build();
1412 ximc.set_ic_values(xim_handler.im_id, xim_handler.ic_id, ic_attributes)
1413 .ok();
1414 }
1415 let mut state = self.0.borrow_mut();
1416 state.restore_xim(ximc, xim_handler);
1417 drop(state);
1418 Some(())
1419 }
1420
1421 fn handle_keyboard_layout_change(&self) {
1422 let mut state = self.0.borrow_mut();
1423 let layout_idx = state.xkb.serialize_layout(STATE_LAYOUT_EFFECTIVE);
1424 let keymap = state.xkb.get_keymap();
1425 let layout_name = keymap.layout_get_name(layout_idx);
1426 if layout_name != state.keyboard_layout.name() {
1427 state.keyboard_layout = LinuxKeyboardLayout::new(layout_name.to_string().into());
1428 if let Some(mut callback) = state.common.callbacks.keyboard_layout_change.take() {
1429 drop(state);
1430 callback();
1431 state = self.0.borrow_mut();
1432 state.common.callbacks.keyboard_layout_change = Some(callback);
1433 }
1434 }
1435 }
1436}
1437
1438impl LinuxClient for X11Client {
1439 fn compositor_name(&self) -> &'static str {
1440 "X11"
1441 }
1442
1443 fn with_common<R>(&self, f: impl FnOnce(&mut LinuxCommon) -> R) -> R {
1444 f(&mut self.0.borrow_mut().common)
1445 }
1446
1447 fn keyboard_layout(&self) -> Box<dyn PlatformKeyboardLayout> {
1448 let state = self.0.borrow();
1449 Box::new(state.keyboard_layout.clone())
1450 }
1451
1452 fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
1453 let state = self.0.borrow();
1454 let setup = state.xcb_connection.setup();
1455 setup
1456 .roots
1457 .iter()
1458 .enumerate()
1459 .filter_map(|(root_id, _)| {
1460 Some(Rc::new(
1461 X11Display::new(&state.xcb_connection, state.scale_factor, root_id).ok()?,
1462 ) as Rc<dyn PlatformDisplay>)
1463 })
1464 .collect()
1465 }
1466
1467 fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
1468 let state = self.0.borrow();
1469 X11Display::new(
1470 &state.xcb_connection,
1471 state.scale_factor,
1472 state.x_root_index,
1473 )
1474 .log_err()
1475 .map(|display| Rc::new(display) as Rc<dyn PlatformDisplay>)
1476 }
1477
1478 fn display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>> {
1479 let state = self.0.borrow();
1480
1481 Some(Rc::new(
1482 X11Display::new(
1483 &state.xcb_connection,
1484 state.scale_factor,
1485 u32::from(id) as usize,
1486 )
1487 .ok()?,
1488 ))
1489 }
1490
1491 #[cfg(feature = "screen-capture")]
1492 fn is_screen_capture_supported(&self) -> bool {
1493 true
1494 }
1495
1496 #[cfg(feature = "screen-capture")]
1497 fn screen_capture_sources(
1498 &self,
1499 ) -> futures::channel::oneshot::Receiver<anyhow::Result<Vec<Rc<dyn gpui::ScreenCaptureSource>>>>
1500 {
1501 gpui::scap_screen_capture::scap_screen_sources(&self.0.borrow().common.foreground_executor)
1502 }
1503
1504 fn open_window(
1505 &self,
1506 handle: AnyWindowHandle,
1507 params: WindowParams,
1508 ) -> anyhow::Result<Box<dyn PlatformWindow>> {
1509 let mut state = self.0.borrow_mut();
1510 let parent_window = state
1511 .keyboard_focused_window
1512 .and_then(|focused_window| state.windows.get(&focused_window))
1513 .map(|w| w.window.clone());
1514 let x_window = state
1515 .xcb_connection
1516 .generate_id()
1517 .context("X11: Failed to generate window ID")?;
1518
1519 let xcb_connection = state.xcb_connection.clone();
1520 let client_side_decorations_supported = state.client_side_decorations_supported;
1521 let x_root_index = state.x_root_index;
1522 let atoms = state.atoms;
1523 let scale_factor = state.scale_factor;
1524 let appearance = state.common.appearance;
1525 let compositor_gpu = state.compositor_gpu.take();
1526 let window = X11Window::new(
1527 handle,
1528 X11ClientStatePtr(Rc::downgrade(&self.0)),
1529 state.common.foreground_executor.clone(),
1530 state.gpu_context.clone(),
1531 compositor_gpu,
1532 params,
1533 &xcb_connection,
1534 client_side_decorations_supported,
1535 x_root_index,
1536 x_window,
1537 &atoms,
1538 scale_factor,
1539 appearance,
1540 parent_window,
1541 )?;
1542 check_reply(
1543 || "Failed to set XdndAware property",
1544 state.xcb_connection.change_property32(
1545 xproto::PropMode::REPLACE,
1546 x_window,
1547 state.atoms.XdndAware,
1548 state.atoms.XA_ATOM,
1549 &[5],
1550 ),
1551 )
1552 .log_err();
1553 xcb_flush(&state.xcb_connection);
1554
1555 let window_ref = WindowRef {
1556 window: window.0.clone(),
1557 refresh_state: None,
1558 expose_event_received: false,
1559 last_visibility: Visibility::UNOBSCURED,
1560 is_mapped: false,
1561 };
1562
1563 state.windows.insert(x_window, window_ref);
1564 Ok(Box::new(window))
1565 }
1566
1567 fn set_cursor_style(&self, style: CursorStyle) {
1568 let mut state = self.0.borrow_mut();
1569 let Some(focused_window) = state.mouse_focused_window else {
1570 return;
1571 };
1572 let current_style = state
1573 .cursor_styles
1574 .get(&focused_window)
1575 .unwrap_or(&CursorStyle::Arrow);
1576
1577 let window = state
1578 .mouse_focused_window
1579 .and_then(|w| state.windows.get(&w));
1580
1581 let should_change = *current_style != style
1582 && (window.is_none() || window.is_some_and(|w| !w.is_blocked()));
1583
1584 if !should_change {
1585 return;
1586 }
1587
1588 let Some(cursor) = state.get_cursor_icon(style) else {
1589 return;
1590 };
1591
1592 state.cursor_styles.insert(focused_window, style);
1593 check_reply(
1594 || "Failed to set cursor style",
1595 state.xcb_connection.change_window_attributes(
1596 focused_window,
1597 &ChangeWindowAttributesAux {
1598 cursor: Some(cursor),
1599 ..Default::default()
1600 },
1601 ),
1602 )
1603 .log_err();
1604 state.xcb_connection.flush().log_err();
1605 }
1606
1607 fn open_uri(&self, uri: &str) {
1608 #[cfg(any(feature = "wayland", feature = "x11"))]
1609 open_uri_internal(
1610 self.with_common(|c| c.background_executor.clone()),
1611 uri,
1612 None,
1613 );
1614 }
1615
1616 fn reveal_path(&self, path: PathBuf) {
1617 #[cfg(any(feature = "x11", feature = "wayland"))]
1618 reveal_path_internal(
1619 self.with_common(|c| c.background_executor.clone()),
1620 path,
1621 None,
1622 );
1623 }
1624
1625 fn write_to_primary(&self, item: gpui::ClipboardItem) {
1626 let state = self.0.borrow_mut();
1627 state
1628 .clipboard
1629 .set_text(
1630 std::borrow::Cow::Owned(item.text().unwrap_or_default()),
1631 clipboard::ClipboardKind::Primary,
1632 clipboard::WaitConfig::None,
1633 )
1634 .context("X11 Failed to write to clipboard (primary)")
1635 .log_with_level(log::Level::Debug);
1636 }
1637
1638 fn write_to_clipboard(&self, item: gpui::ClipboardItem) {
1639 let mut state = self.0.borrow_mut();
1640 state
1641 .clipboard
1642 .set_text(
1643 std::borrow::Cow::Owned(item.text().unwrap_or_default()),
1644 clipboard::ClipboardKind::Clipboard,
1645 clipboard::WaitConfig::None,
1646 )
1647 .context("X11: Failed to write to clipboard (clipboard)")
1648 .log_with_level(log::Level::Debug);
1649 state.clipboard_item.replace(item);
1650 }
1651
1652 fn read_from_primary(&self) -> Option<gpui::ClipboardItem> {
1653 let state = self.0.borrow_mut();
1654 state
1655 .clipboard
1656 .get_any(clipboard::ClipboardKind::Primary)
1657 .context("X11: Failed to read from clipboard (primary)")
1658 .log_with_level(log::Level::Debug)
1659 }
1660
1661 fn read_from_clipboard(&self) -> Option<gpui::ClipboardItem> {
1662 let state = self.0.borrow_mut();
1663 // if the last copy was from this app, return our cached item
1664 // which has metadata attached.
1665 if state
1666 .clipboard
1667 .is_owner(clipboard::ClipboardKind::Clipboard)
1668 {
1669 return state.clipboard_item.clone();
1670 }
1671 state
1672 .clipboard
1673 .get_any(clipboard::ClipboardKind::Clipboard)
1674 .context("X11: Failed to read from clipboard (clipboard)")
1675 .log_with_level(log::Level::Debug)
1676 }
1677
1678 fn run(&self) {
1679 let Some(mut event_loop) = self
1680 .0
1681 .borrow_mut()
1682 .event_loop
1683 .take()
1684 .context("X11Client::run called but it's already running")
1685 .log_err()
1686 else {
1687 return;
1688 };
1689
1690 event_loop.run(None, &mut self.clone(), |_| {}).log_err();
1691 }
1692
1693 fn active_window(&self) -> Option<AnyWindowHandle> {
1694 let state = self.0.borrow();
1695 state.keyboard_focused_window.and_then(|focused_window| {
1696 state
1697 .windows
1698 .get(&focused_window)
1699 .map(|window| window.handle())
1700 })
1701 }
1702
1703 fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
1704 let state = self.0.borrow();
1705 let root = state.xcb_connection.setup().roots[state.x_root_index].root;
1706
1707 let reply = state
1708 .xcb_connection
1709 .get_property(
1710 false,
1711 root,
1712 state.atoms._NET_CLIENT_LIST_STACKING,
1713 xproto::AtomEnum::WINDOW,
1714 0,
1715 u32::MAX,
1716 )
1717 .ok()?
1718 .reply()
1719 .ok()?;
1720
1721 let window_ids = reply
1722 .value
1723 .chunks_exact(4)
1724 .filter_map(|chunk| chunk.try_into().ok().map(u32::from_ne_bytes))
1725 .collect::<Vec<xproto::Window>>();
1726
1727 let mut handles = Vec::new();
1728
1729 // We need to reverse, since _NET_CLIENT_LIST_STACKING has
1730 // a back-to-front order.
1731 // See: https://specifications.freedesktop.org/wm-spec/1.3/ar01s03.html
1732 for window_ref in window_ids
1733 .iter()
1734 .rev()
1735 .filter_map(|&win| state.windows.get(&win))
1736 {
1737 if !window_ref.window.state.borrow().destroyed {
1738 handles.push(window_ref.handle());
1739 }
1740 }
1741
1742 Some(handles)
1743 }
1744
1745 fn window_identifier(&self) -> impl Future<Output = Option<WindowIdentifier>> + Send + 'static {
1746 let state = self.0.borrow();
1747 state
1748 .keyboard_focused_window
1749 .and_then(|focused_window| state.windows.get(&focused_window))
1750 .map(|window| window.window.x_window as u64)
1751 .map(|x_window| std::future::ready(Some(WindowIdentifier::from_xid(x_window))))
1752 .unwrap_or(std::future::ready(None))
1753 }
1754}
1755
1756impl X11ClientState {
1757 fn has_xim(&self) -> bool {
1758 self.ximc.is_some() && self.xim_handler.is_some()
1759 }
1760
1761 fn take_xim(&mut self) -> Option<(X11rbClient<Rc<XCBConnection>>, XimHandler)> {
1762 let ximc = self
1763 .ximc
1764 .take()
1765 .ok_or(anyhow!("bug: XIM connection not set"))
1766 .log_err()?;
1767 if let Some(xim_handler) = self.xim_handler.take() {
1768 Some((ximc, xim_handler))
1769 } else {
1770 self.ximc = Some(ximc);
1771 log::error!("bug: XIM handler not set");
1772 None
1773 }
1774 }
1775
1776 fn restore_xim(&mut self, ximc: X11rbClient<Rc<XCBConnection>>, xim_handler: XimHandler) {
1777 self.ximc = Some(ximc);
1778 self.xim_handler = Some(xim_handler);
1779 }
1780
1781 fn update_refresh_loop(&mut self, x_window: xproto::Window) {
1782 let Some(window_ref) = self.windows.get_mut(&x_window) else {
1783 return;
1784 };
1785 let is_visible = window_ref.is_mapped
1786 && !matches!(window_ref.last_visibility, Visibility::FULLY_OBSCURED);
1787 match (is_visible, window_ref.refresh_state.take()) {
1788 (false, refresh_state @ Some(RefreshState::Hidden { .. }))
1789 | (false, refresh_state @ None)
1790 | (true, refresh_state @ Some(RefreshState::PeriodicRefresh { .. })) => {
1791 window_ref.refresh_state = refresh_state;
1792 }
1793 (
1794 false,
1795 Some(RefreshState::PeriodicRefresh {
1796 refresh_rate,
1797 event_loop_token,
1798 }),
1799 ) => {
1800 self.loop_handle.remove(event_loop_token);
1801 window_ref.refresh_state = Some(RefreshState::Hidden { refresh_rate });
1802 }
1803 (true, Some(RefreshState::Hidden { refresh_rate })) => {
1804 let event_loop_token = self.start_refresh_loop(x_window, refresh_rate);
1805 let Some(window_ref) = self.windows.get_mut(&x_window) else {
1806 return;
1807 };
1808 window_ref.refresh_state = Some(RefreshState::PeriodicRefresh {
1809 refresh_rate,
1810 event_loop_token,
1811 });
1812 }
1813 (true, None) => {
1814 let Some(screen_resources) = get_reply(
1815 || "Failed to get screen resources",
1816 self.xcb_connection
1817 .randr_get_screen_resources_current(x_window),
1818 )
1819 .log_err() else {
1820 return;
1821 };
1822
1823 // Ideally this would be re-queried when the window changes screens, but there
1824 // doesn't seem to be an efficient / straightforward way to do this. Should also be
1825 // updated when screen configurations change.
1826 let mode_info = screen_resources.crtcs.iter().find_map(|crtc| {
1827 let crtc_info = self
1828 .xcb_connection
1829 .randr_get_crtc_info(*crtc, x11rb::CURRENT_TIME)
1830 .ok()?
1831 .reply()
1832 .ok()?;
1833
1834 screen_resources
1835 .modes
1836 .iter()
1837 .find(|m| m.id == crtc_info.mode)
1838 });
1839 let refresh_rate = match mode_info {
1840 Some(mode_info) => mode_refresh_rate(mode_info),
1841 None => {
1842 log::error!(
1843 "Failed to get screen mode info from xrandr, \
1844 defaulting to 60hz refresh rate."
1845 );
1846 Duration::from_micros(1_000_000 / 60)
1847 }
1848 };
1849
1850 let event_loop_token = self.start_refresh_loop(x_window, refresh_rate);
1851 let Some(window_ref) = self.windows.get_mut(&x_window) else {
1852 return;
1853 };
1854 window_ref.refresh_state = Some(RefreshState::PeriodicRefresh {
1855 refresh_rate,
1856 event_loop_token,
1857 });
1858 }
1859 }
1860 }
1861
1862 #[must_use]
1863 fn start_refresh_loop(
1864 &self,
1865 x_window: xproto::Window,
1866 refresh_rate: Duration,
1867 ) -> RegistrationToken {
1868 self.loop_handle
1869 .insert_source(calloop::timer::Timer::immediate(), {
1870 move |mut instant, (), client| {
1871 let xcb_connection = {
1872 let mut state = client.0.borrow_mut();
1873 let xcb_connection = state.xcb_connection.clone();
1874 if let Some(window) = state.windows.get_mut(&x_window) {
1875 let expose_event_received = window.expose_event_received;
1876 window.expose_event_received = false;
1877 let window = window.window.clone();
1878 drop(state);
1879 window.refresh(RequestFrameOptions {
1880 require_presentation: expose_event_received,
1881 force_render: false,
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}