1use std::{
2 cell::{RefCell, RefMut},
3 hash::Hash,
4 os::fd::{AsRawFd, BorrowedFd},
5 path::PathBuf,
6 rc::{Rc, Weak},
7 time::{Duration, Instant},
8};
9
10use ashpd::WindowIdentifier;
11use calloop::{
12 EventLoop, LoopHandle,
13 timer::{TimeoutAction, Timer},
14};
15use calloop_wayland_source::WaylandSource;
16use collections::HashMap;
17use filedescriptor::Pipe;
18use http_client::Url;
19use smallvec::SmallVec;
20use util::ResultExt as _;
21use wayland_backend::client::ObjectId;
22use wayland_backend::protocol::WEnum;
23use wayland_client::event_created_child;
24use wayland_client::globals::{GlobalList, GlobalListContents, registry_queue_init};
25use wayland_client::protocol::wl_callback::{self, WlCallback};
26use wayland_client::protocol::wl_data_device_manager::DndAction;
27use wayland_client::protocol::wl_data_offer::WlDataOffer;
28use wayland_client::protocol::wl_pointer::AxisSource;
29use wayland_client::protocol::{
30 wl_data_device, wl_data_device_manager, wl_data_offer, wl_data_source, wl_output, wl_region,
31};
32use wayland_client::{
33 Connection, Dispatch, Proxy, QueueHandle, delegate_noop,
34 protocol::{
35 wl_buffer, wl_compositor, wl_keyboard, wl_pointer, wl_registry, wl_seat, wl_shm,
36 wl_shm_pool, wl_surface,
37 },
38};
39use wayland_protocols::wp::pointer_gestures::zv1::client::{
40 zwp_pointer_gesture_pinch_v1, zwp_pointer_gestures_v1,
41};
42use wayland_protocols::wp::primary_selection::zv1::client::zwp_primary_selection_offer_v1::{
43 self, ZwpPrimarySelectionOfferV1,
44};
45use wayland_protocols::wp::primary_selection::zv1::client::{
46 zwp_primary_selection_device_manager_v1, zwp_primary_selection_device_v1,
47 zwp_primary_selection_source_v1,
48};
49use wayland_protocols::wp::text_input::zv3::client::zwp_text_input_v3::{
50 ContentHint, ContentPurpose,
51};
52use wayland_protocols::wp::text_input::zv3::client::{
53 zwp_text_input_manager_v3, zwp_text_input_v3,
54};
55use wayland_protocols::wp::viewporter::client::{wp_viewport, wp_viewporter};
56use wayland_protocols::xdg::activation::v1::client::{xdg_activation_token_v1, xdg_activation_v1};
57use wayland_protocols::xdg::decoration::zv1::client::{
58 zxdg_decoration_manager_v1, zxdg_toplevel_decoration_v1,
59};
60use wayland_protocols::xdg::shell::client::{xdg_surface, xdg_toplevel, xdg_wm_base};
61use wayland_protocols::{
62 wp::cursor_shape::v1::client::{wp_cursor_shape_device_v1, wp_cursor_shape_manager_v1},
63 xdg::dialog::v1::client::xdg_wm_dialog_v1::{self, XdgWmDialogV1},
64};
65use wayland_protocols::{
66 wp::fractional_scale::v1::client::{wp_fractional_scale_manager_v1, wp_fractional_scale_v1},
67 xdg::dialog::v1::client::xdg_dialog_v1::XdgDialogV1,
68};
69use wayland_protocols_plasma::blur::client::{org_kde_kwin_blur, org_kde_kwin_blur_manager};
70use wayland_protocols_wlr::layer_shell::v1::client::{zwlr_layer_shell_v1, zwlr_layer_surface_v1};
71use xkbcommon::xkb::ffi::XKB_KEYMAP_FORMAT_TEXT_V1;
72use xkbcommon::xkb::{self, KEYMAP_COMPILE_NO_FLAGS, Keycode};
73
74use super::{
75 display::WaylandDisplay,
76 window::{ImeInput, WaylandWindowStatePtr},
77};
78
79use crate::linux::{
80 DOUBLE_CLICK_INTERVAL, LinuxClient, LinuxCommon, LinuxKeyboardLayout, SCROLL_LINES,
81 capslock_from_xkb, cursor_style_to_icon_names, get_xkb_compose_state, is_within_click_distance,
82 keystroke_from_xkb, keystroke_underlying_dead_key, modifiers_from_xkb, open_uri_internal,
83 read_fd, reveal_path_internal,
84 wayland::{
85 clipboard::{Clipboard, DataOffer, FILE_LIST_MIME_TYPE, TEXT_MIME_TYPES},
86 cursor::Cursor,
87 serial::{SerialKind, SerialTracker},
88 to_shape,
89 window::WaylandWindow,
90 },
91 xdg_desktop_portal::{Event as XDPEvent, XDPEventSource},
92};
93use gpui::{
94 AnyWindowHandle, Bounds, Capslock, CursorStyle, DevicePixels, DisplayId, FileDropEvent,
95 ForegroundExecutor, KeyDownEvent, KeyUpEvent, Keystroke, Modifiers, ModifiersChangedEvent,
96 MouseButton, MouseDownEvent, MouseExitEvent, MouseMoveEvent, MouseUpEvent, NavigationDirection,
97 Pixels, PlatformDisplay, PlatformInput, PlatformKeyboardLayout, PlatformWindow, Point,
98 ScrollDelta, ScrollWheelEvent, SharedString, Size, TaskTiming, TouchPhase, WindowButtonLayout,
99 WindowParams, point, profiler, px, size,
100};
101use gpui_wgpu::{CompositorGpuHint, GpuContext};
102use wayland_protocols::wp::linux_dmabuf::zv1::client::{
103 zwp_linux_dmabuf_feedback_v1, zwp_linux_dmabuf_v1,
104};
105
106/// Used to convert evdev scancode to xkb scancode
107const MIN_KEYCODE: u32 = 8;
108
109const UNKNOWN_KEYBOARD_LAYOUT_NAME: SharedString = SharedString::new_static("unknown");
110
111#[derive(Clone)]
112pub struct Globals {
113 pub qh: QueueHandle<WaylandClientStatePtr>,
114 pub activation: Option<xdg_activation_v1::XdgActivationV1>,
115 pub compositor: wl_compositor::WlCompositor,
116 pub cursor_shape_manager: Option<wp_cursor_shape_manager_v1::WpCursorShapeManagerV1>,
117 pub data_device_manager: Option<wl_data_device_manager::WlDataDeviceManager>,
118 pub primary_selection_manager:
119 Option<zwp_primary_selection_device_manager_v1::ZwpPrimarySelectionDeviceManagerV1>,
120 pub wm_base: xdg_wm_base::XdgWmBase,
121 pub shm: wl_shm::WlShm,
122 pub seat: wl_seat::WlSeat,
123 pub viewporter: Option<wp_viewporter::WpViewporter>,
124 pub fractional_scale_manager:
125 Option<wp_fractional_scale_manager_v1::WpFractionalScaleManagerV1>,
126 pub decoration_manager: Option<zxdg_decoration_manager_v1::ZxdgDecorationManagerV1>,
127 pub layer_shell: Option<zwlr_layer_shell_v1::ZwlrLayerShellV1>,
128 pub blur_manager: Option<org_kde_kwin_blur_manager::OrgKdeKwinBlurManager>,
129 pub text_input_manager: Option<zwp_text_input_manager_v3::ZwpTextInputManagerV3>,
130 pub gesture_manager: Option<zwp_pointer_gestures_v1::ZwpPointerGesturesV1>,
131 pub dialog: Option<xdg_wm_dialog_v1::XdgWmDialogV1>,
132 pub executor: ForegroundExecutor,
133}
134
135impl Globals {
136 fn new(
137 globals: GlobalList,
138 executor: ForegroundExecutor,
139 qh: QueueHandle<WaylandClientStatePtr>,
140 seat: wl_seat::WlSeat,
141 ) -> Self {
142 let dialog_v = XdgWmDialogV1::interface().version;
143 Globals {
144 activation: globals.bind(&qh, 1..=1, ()).ok(),
145 compositor: globals
146 .bind(
147 &qh,
148 wl_surface::REQ_SET_BUFFER_SCALE_SINCE
149 ..=wl_surface::EVT_PREFERRED_BUFFER_SCALE_SINCE,
150 (),
151 )
152 .unwrap(),
153 cursor_shape_manager: globals.bind(&qh, 1..=1, ()).ok(),
154 data_device_manager: globals
155 .bind(
156 &qh,
157 WL_DATA_DEVICE_MANAGER_VERSION..=WL_DATA_DEVICE_MANAGER_VERSION,
158 (),
159 )
160 .ok(),
161 primary_selection_manager: globals.bind(&qh, 1..=1, ()).ok(),
162 shm: globals.bind(&qh, 1..=1, ()).unwrap(),
163 seat,
164 wm_base: globals.bind(&qh, 1..=5, ()).unwrap(),
165 viewporter: globals.bind(&qh, 1..=1, ()).ok(),
166 fractional_scale_manager: globals.bind(&qh, 1..=1, ()).ok(),
167 decoration_manager: globals.bind(&qh, 1..=1, ()).ok(),
168 layer_shell: globals.bind(&qh, 1..=5, ()).ok(),
169 blur_manager: globals.bind(&qh, 1..=1, ()).ok(),
170 text_input_manager: globals.bind(&qh, 1..=1, ()).ok(),
171 gesture_manager: globals.bind(&qh, 1..=3, ()).ok(),
172 dialog: globals.bind(&qh, dialog_v..=dialog_v, ()).ok(),
173 executor,
174 qh,
175 }
176 }
177}
178
179#[derive(Default, Debug, Clone, PartialEq, Eq, Hash)]
180pub struct InProgressOutput {
181 name: Option<String>,
182 scale: Option<i32>,
183 position: Option<Point<DevicePixels>>,
184 size: Option<Size<DevicePixels>>,
185}
186
187impl InProgressOutput {
188 fn complete(&self) -> Option<Output> {
189 if let Some((position, size)) = self.position.zip(self.size) {
190 let scale = self.scale.unwrap_or(1);
191 Some(Output {
192 name: self.name.clone(),
193 scale,
194 bounds: Bounds::new(position, size),
195 })
196 } else {
197 None
198 }
199 }
200}
201
202#[derive(Debug, Clone, Eq, PartialEq, Hash)]
203pub struct Output {
204 pub name: Option<String>,
205 pub scale: i32,
206 pub bounds: Bounds<DevicePixels>,
207}
208
209pub(crate) struct WaylandClientState {
210 serial_tracker: SerialTracker,
211 globals: Globals,
212 pub gpu_context: GpuContext,
213 pub compositor_gpu: Option<CompositorGpuHint>,
214 wl_seat: wl_seat::WlSeat, // TODO: Multi seat support
215 wl_pointer: Option<wl_pointer::WlPointer>,
216 pinch_gesture: Option<zwp_pointer_gesture_pinch_v1::ZwpPointerGesturePinchV1>,
217 pinch_scale: f32,
218 wl_keyboard: Option<wl_keyboard::WlKeyboard>,
219 cursor_shape_device: Option<wp_cursor_shape_device_v1::WpCursorShapeDeviceV1>,
220 data_device: Option<wl_data_device::WlDataDevice>,
221 primary_selection: Option<zwp_primary_selection_device_v1::ZwpPrimarySelectionDeviceV1>,
222 text_input: Option<zwp_text_input_v3::ZwpTextInputV3>,
223 pre_edit_text: Option<String>,
224 ime_pre_edit: Option<String>,
225 composing: bool,
226 // Surface to Window mapping
227 windows: HashMap<ObjectId, WaylandWindowStatePtr>,
228 // Output to scale mapping
229 outputs: HashMap<ObjectId, Output>,
230 in_progress_outputs: HashMap<ObjectId, InProgressOutput>,
231 wl_outputs: HashMap<ObjectId, wl_output::WlOutput>,
232 keyboard_layout: LinuxKeyboardLayout,
233 keymap_state: Option<xkb::State>,
234 compose_state: Option<xkb::compose::State>,
235 drag: DragState,
236 click: ClickState,
237 repeat: KeyRepeat,
238 pub modifiers: Modifiers,
239 pub capslock: Capslock,
240 axis_source: AxisSource,
241 pub mouse_location: Option<Point<Pixels>>,
242 continuous_scroll_delta: Option<Point<Pixels>>,
243 discrete_scroll_delta: Option<Point<f32>>,
244 vertical_modifier: f32,
245 horizontal_modifier: f32,
246 scroll_event_received: bool,
247 enter_token: Option<()>,
248 button_pressed: Option<MouseButton>,
249 mouse_focused_window: Option<WaylandWindowStatePtr>,
250 keyboard_focused_window: Option<WaylandWindowStatePtr>,
251 loop_handle: LoopHandle<'static, WaylandClientStatePtr>,
252 cursor_style: Option<CursorStyle>,
253 clipboard: Clipboard,
254 data_offers: Vec<DataOffer<WlDataOffer>>,
255 primary_data_offer: Option<DataOffer<ZwpPrimarySelectionOfferV1>>,
256 cursor: Cursor,
257 pending_activation: Option<PendingActivation>,
258 event_loop: Option<EventLoop<'static, WaylandClientStatePtr>>,
259 pub common: LinuxCommon,
260}
261
262pub struct DragState {
263 data_offer: Option<wl_data_offer::WlDataOffer>,
264 window: Option<WaylandWindowStatePtr>,
265 position: Point<Pixels>,
266}
267
268pub struct ClickState {
269 last_mouse_button: Option<MouseButton>,
270 last_click: Instant,
271 last_location: Point<Pixels>,
272 current_count: usize,
273}
274
275pub(crate) struct KeyRepeat {
276 characters_per_second: u32,
277 delay: Duration,
278 current_id: u64,
279 current_keycode: Option<xkb::Keycode>,
280}
281
282pub(crate) enum PendingActivation {
283 /// URI to open in the web browser.
284 Uri(String),
285 /// Path to open in the file explorer.
286 Path(PathBuf),
287 /// A window from ourselves to raise.
288 Window(ObjectId),
289}
290
291/// This struct is required to conform to Rust's orphan rules, so we can dispatch on the state but hand the
292/// window to GPUI.
293#[derive(Clone)]
294pub struct WaylandClientStatePtr(Weak<RefCell<WaylandClientState>>);
295
296impl WaylandClientStatePtr {
297 pub fn get_client(&self) -> Rc<RefCell<WaylandClientState>> {
298 self.0
299 .upgrade()
300 .expect("The pointer should always be valid when dispatching in wayland")
301 }
302
303 pub fn get_serial(&self, kind: SerialKind) -> u32 {
304 self.0.upgrade().unwrap().borrow().serial_tracker.get(kind)
305 }
306
307 pub fn set_pending_activation(&self, window: ObjectId) {
308 self.0.upgrade().unwrap().borrow_mut().pending_activation =
309 Some(PendingActivation::Window(window));
310 }
311
312 pub fn enable_ime(&self) {
313 let client = self.get_client();
314 let mut state = client.borrow_mut();
315 let Some(text_input) = state.text_input.take() else {
316 return;
317 };
318
319 text_input.enable();
320 text_input.set_content_type(ContentHint::None, ContentPurpose::Normal);
321 if let Some(window) = state.keyboard_focused_window.clone() {
322 drop(state);
323 if let Some(area) = window.get_ime_area() {
324 text_input.set_cursor_rectangle(
325 f32::from(area.origin.x) as i32,
326 f32::from(area.origin.y) as i32,
327 f32::from(area.size.width) as i32,
328 f32::from(area.size.height) as i32,
329 );
330 }
331 state = client.borrow_mut();
332 }
333 text_input.commit();
334 state.text_input = Some(text_input);
335 }
336
337 pub fn disable_ime(&self) {
338 let client = self.get_client();
339 let mut state = client.borrow_mut();
340 state.composing = false;
341 if let Some(text_input) = &state.text_input {
342 text_input.disable();
343 text_input.commit();
344 }
345 }
346
347 pub fn update_ime_position(&self, bounds: Bounds<Pixels>) {
348 let client = self.get_client();
349 let state = client.borrow_mut();
350 if state.composing || state.text_input.is_none() || state.pre_edit_text.is_some() {
351 return;
352 }
353
354 let text_input = state.text_input.as_ref().unwrap();
355 text_input.set_cursor_rectangle(
356 bounds.origin.x.as_f32() as i32,
357 bounds.origin.y.as_f32() as i32,
358 bounds.size.width.as_f32() as i32,
359 bounds.size.height.as_f32() as i32,
360 );
361 text_input.commit();
362 }
363
364 pub fn handle_keyboard_layout_change(&self) {
365 let client = self.get_client();
366 let mut state = client.borrow_mut();
367 let changed = if let Some(keymap_state) = &state.keymap_state {
368 let layout_idx = keymap_state.serialize_layout(xkbcommon::xkb::STATE_LAYOUT_EFFECTIVE);
369 let keymap = keymap_state.get_keymap();
370 let layout_name = keymap.layout_get_name(layout_idx);
371 let changed = layout_name != state.keyboard_layout.name();
372 if changed {
373 state.keyboard_layout = LinuxKeyboardLayout::new(layout_name.to_string().into());
374 }
375 changed
376 } else {
377 let changed = &UNKNOWN_KEYBOARD_LAYOUT_NAME != state.keyboard_layout.name();
378 if changed {
379 state.keyboard_layout = LinuxKeyboardLayout::new(UNKNOWN_KEYBOARD_LAYOUT_NAME);
380 }
381 changed
382 };
383
384 if changed && let Some(mut callback) = state.common.callbacks.keyboard_layout_change.take()
385 {
386 drop(state);
387 callback();
388 state = client.borrow_mut();
389 state.common.callbacks.keyboard_layout_change = Some(callback);
390 }
391 }
392
393 pub fn drop_window(&self, surface_id: &ObjectId) {
394 let client = self.get_client();
395 let mut state = client.borrow_mut();
396 let closed_window = state.windows.remove(surface_id).unwrap();
397 if let Some(window) = state.mouse_focused_window.take()
398 && !window.ptr_eq(&closed_window)
399 {
400 state.mouse_focused_window = Some(window);
401 }
402 if let Some(window) = state.keyboard_focused_window.take()
403 && !window.ptr_eq(&closed_window)
404 {
405 state.keyboard_focused_window = Some(window);
406 }
407 }
408}
409
410#[derive(Clone)]
411pub struct WaylandClient(Rc<RefCell<WaylandClientState>>);
412
413impl Drop for WaylandClient {
414 fn drop(&mut self) {
415 let mut state = self.0.borrow_mut();
416 state.windows.clear();
417
418 if let Some(wl_pointer) = &state.wl_pointer {
419 wl_pointer.release();
420 }
421 if let Some(cursor_shape_device) = &state.cursor_shape_device {
422 cursor_shape_device.destroy();
423 }
424 if let Some(data_device) = &state.data_device {
425 data_device.release();
426 }
427 if let Some(text_input) = &state.text_input {
428 text_input.destroy();
429 }
430 }
431}
432
433const WL_DATA_DEVICE_MANAGER_VERSION: u32 = 3;
434
435fn wl_seat_version(version: u32) -> u32 {
436 // We rely on the wl_pointer.frame event
437 const WL_SEAT_MIN_VERSION: u32 = 5;
438 const WL_SEAT_MAX_VERSION: u32 = 9;
439
440 if version < WL_SEAT_MIN_VERSION {
441 panic!(
442 "wl_seat below required version: {} < {}",
443 version, WL_SEAT_MIN_VERSION
444 );
445 }
446
447 version.clamp(WL_SEAT_MIN_VERSION, WL_SEAT_MAX_VERSION)
448}
449
450fn wl_output_version(version: u32) -> u32 {
451 const WL_OUTPUT_MIN_VERSION: u32 = 2;
452 const WL_OUTPUT_MAX_VERSION: u32 = 4;
453
454 if version < WL_OUTPUT_MIN_VERSION {
455 panic!(
456 "wl_output below required version: {} < {}",
457 version, WL_OUTPUT_MIN_VERSION
458 );
459 }
460
461 version.clamp(WL_OUTPUT_MIN_VERSION, WL_OUTPUT_MAX_VERSION)
462}
463
464impl WaylandClient {
465 pub(crate) fn new() -> Self {
466 let conn = Connection::connect_to_env().unwrap();
467
468 let (globals, event_queue) = registry_queue_init::<WaylandClientStatePtr>(&conn).unwrap();
469 let qh = event_queue.handle();
470
471 let mut seat: Option<wl_seat::WlSeat> = None;
472 #[allow(clippy::mutable_key_type)]
473 let mut in_progress_outputs = HashMap::default();
474 #[allow(clippy::mutable_key_type)]
475 let mut wl_outputs: HashMap<ObjectId, wl_output::WlOutput> = HashMap::default();
476 globals.contents().with_list(|list| {
477 for global in list {
478 match &global.interface[..] {
479 "wl_seat" => {
480 seat = Some(globals.registry().bind::<wl_seat::WlSeat, _, _>(
481 global.name,
482 wl_seat_version(global.version),
483 &qh,
484 (),
485 ));
486 }
487 "wl_output" => {
488 let output = globals.registry().bind::<wl_output::WlOutput, _, _>(
489 global.name,
490 wl_output_version(global.version),
491 &qh,
492 (),
493 );
494 in_progress_outputs.insert(output.id(), InProgressOutput::default());
495 wl_outputs.insert(output.id(), output);
496 }
497 _ => {}
498 }
499 }
500 });
501
502 let event_loop = EventLoop::<WaylandClientStatePtr>::try_new().unwrap();
503
504 let (common, main_receiver) = LinuxCommon::new(event_loop.get_signal());
505
506 let handle = event_loop.handle();
507 handle
508 .insert_source(main_receiver, {
509 let handle = handle.clone();
510 move |event, _, _: &mut WaylandClientStatePtr| {
511 if let calloop::channel::Event::Msg(runnable) = event {
512 handle.insert_idle(|_| {
513 let start = Instant::now();
514 let location = runnable.metadata().location;
515 let mut timing = TaskTiming {
516 location,
517 start,
518 end: None,
519 };
520 profiler::add_task_timing(timing);
521
522 runnable.run();
523
524 let end = Instant::now();
525 timing.end = Some(end);
526 profiler::add_task_timing(timing);
527 });
528 }
529 }
530 })
531 .unwrap();
532
533 let compositor_gpu = detect_compositor_gpu();
534 let gpu_context = Rc::new(RefCell::new(None));
535
536 let seat = seat.unwrap();
537 let globals = Globals::new(
538 globals,
539 common.foreground_executor.clone(),
540 qh.clone(),
541 seat.clone(),
542 );
543
544 let data_device = globals
545 .data_device_manager
546 .as_ref()
547 .map(|data_device_manager| data_device_manager.get_data_device(&seat, &qh, ()));
548
549 let primary_selection = globals
550 .primary_selection_manager
551 .as_ref()
552 .map(|primary_selection_manager| primary_selection_manager.get_device(&seat, &qh, ()));
553
554 let cursor = Cursor::new(&conn, &globals, 24);
555
556 handle
557 .insert_source(XDPEventSource::new(&common.background_executor), {
558 move |event, _, client| match event {
559 XDPEvent::WindowAppearance(appearance) => {
560 if let Some(client) = client.0.upgrade() {
561 let mut client = client.borrow_mut();
562
563 client.common.appearance = appearance;
564
565 for window in client.windows.values_mut() {
566 window.set_appearance(appearance);
567 }
568 }
569 }
570 XDPEvent::ButtonLayout(layout_str) => {
571 if let Some(client) = client.0.upgrade() {
572 let layout = WindowButtonLayout::parse(&layout_str)
573 .log_err()
574 .unwrap_or_else(WindowButtonLayout::linux_default);
575 let mut client = client.borrow_mut();
576 client.common.button_layout = layout;
577
578 for window in client.windows.values_mut() {
579 window.set_button_layout();
580 }
581 }
582 }
583 XDPEvent::CursorTheme(theme) => {
584 if let Some(client) = client.0.upgrade() {
585 let mut client = client.borrow_mut();
586 client.cursor.set_theme(theme);
587 }
588 }
589 XDPEvent::CursorSize(size) => {
590 if let Some(client) = client.0.upgrade() {
591 let mut client = client.borrow_mut();
592 client.cursor.set_size(size);
593 }
594 }
595 }
596 })
597 .unwrap();
598
599 let state = Rc::new(RefCell::new(WaylandClientState {
600 serial_tracker: SerialTracker::new(),
601 globals,
602 gpu_context,
603 compositor_gpu,
604 wl_seat: seat,
605 wl_pointer: None,
606 wl_keyboard: None,
607 pinch_gesture: None,
608 pinch_scale: 1.0,
609 cursor_shape_device: None,
610 data_device,
611 primary_selection,
612 text_input: None,
613 pre_edit_text: None,
614 ime_pre_edit: None,
615 composing: false,
616 outputs: HashMap::default(),
617 in_progress_outputs,
618 wl_outputs,
619 windows: HashMap::default(),
620 common,
621 keyboard_layout: LinuxKeyboardLayout::new(UNKNOWN_KEYBOARD_LAYOUT_NAME),
622 keymap_state: None,
623 compose_state: None,
624 drag: DragState {
625 data_offer: None,
626 window: None,
627 position: Point::default(),
628 },
629 click: ClickState {
630 last_click: Instant::now(),
631 last_mouse_button: None,
632 last_location: Point::default(),
633 current_count: 0,
634 },
635 repeat: KeyRepeat {
636 characters_per_second: 16,
637 delay: Duration::from_millis(500),
638 current_id: 0,
639 current_keycode: None,
640 },
641 modifiers: Modifiers {
642 shift: false,
643 control: false,
644 alt: false,
645 function: false,
646 platform: false,
647 },
648 capslock: Capslock { on: false },
649 scroll_event_received: false,
650 axis_source: AxisSource::Wheel,
651 mouse_location: None,
652 continuous_scroll_delta: None,
653 discrete_scroll_delta: None,
654 vertical_modifier: -1.0,
655 horizontal_modifier: -1.0,
656 button_pressed: None,
657 mouse_focused_window: None,
658 keyboard_focused_window: None,
659 loop_handle: handle.clone(),
660 enter_token: None,
661 cursor_style: None,
662 clipboard: Clipboard::new(conn.clone(), handle.clone()),
663 data_offers: Vec::new(),
664 primary_data_offer: None,
665 cursor,
666 pending_activation: None,
667 event_loop: Some(event_loop),
668 }));
669
670 WaylandSource::new(conn, event_queue)
671 .insert(handle)
672 .unwrap();
673
674 Self(state)
675 }
676}
677
678impl LinuxClient for WaylandClient {
679 fn keyboard_layout(&self) -> Box<dyn PlatformKeyboardLayout> {
680 Box::new(self.0.borrow().keyboard_layout.clone())
681 }
682
683 fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
684 self.0
685 .borrow()
686 .outputs
687 .iter()
688 .map(|(id, output)| {
689 Rc::new(WaylandDisplay {
690 id: id.clone(),
691 name: output.name.clone(),
692 bounds: output.bounds.to_pixels(output.scale as f32),
693 }) as Rc<dyn PlatformDisplay>
694 })
695 .collect()
696 }
697
698 fn display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>> {
699 self.0
700 .borrow()
701 .outputs
702 .iter()
703 .find_map(|(object_id, output)| {
704 (object_id.protocol_id() == u32::from(id)).then(|| {
705 Rc::new(WaylandDisplay {
706 id: object_id.clone(),
707 name: output.name.clone(),
708 bounds: output.bounds.to_pixels(output.scale as f32),
709 }) as Rc<dyn PlatformDisplay>
710 })
711 })
712 }
713
714 fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
715 None
716 }
717
718 #[cfg(feature = "screen-capture")]
719 fn screen_capture_sources(
720 &self,
721 ) -> futures::channel::oneshot::Receiver<anyhow::Result<Vec<Rc<dyn gpui::ScreenCaptureSource>>>>
722 {
723 // TODO: Get screen capture working on wayland. Be sure to try window resizing as that may
724 // be tricky.
725 //
726 // start_scap_default_target_source()
727 let (sources_tx, sources_rx) = futures::channel::oneshot::channel();
728 sources_tx
729 .send(Err(anyhow::anyhow!(
730 "Wayland screen capture not yet implemented."
731 )))
732 .ok();
733 sources_rx
734 }
735
736 fn open_window(
737 &self,
738 handle: AnyWindowHandle,
739 params: WindowParams,
740 ) -> anyhow::Result<Box<dyn PlatformWindow>> {
741 let mut state = self.0.borrow_mut();
742
743 let parent = state.keyboard_focused_window.clone();
744
745 let target_output = params.display_id.and_then(|display_id| {
746 let target_protocol_id: u32 = display_id.into();
747 state
748 .wl_outputs
749 .iter()
750 .find(|(id, _)| id.protocol_id() == target_protocol_id)
751 .map(|(_, output)| output.clone())
752 });
753
754 let appearance = state.common.appearance;
755 let compositor_gpu = state.compositor_gpu.take();
756 let (window, surface_id) = WaylandWindow::new(
757 handle,
758 state.globals.clone(),
759 state.gpu_context.clone(),
760 compositor_gpu,
761 WaylandClientStatePtr(Rc::downgrade(&self.0)),
762 params,
763 appearance,
764 parent,
765 target_output,
766 )?;
767 state.windows.insert(surface_id, window.0.clone());
768
769 Ok(Box::new(window))
770 }
771
772 fn set_cursor_style(&self, style: CursorStyle) {
773 let mut state = self.0.borrow_mut();
774
775 let need_update = state.cursor_style != Some(style)
776 && (state.mouse_focused_window.is_none()
777 || state
778 .mouse_focused_window
779 .as_ref()
780 .is_some_and(|w| !w.is_blocked()));
781
782 if need_update {
783 let serial = state.serial_tracker.get(SerialKind::MouseEnter);
784 state.cursor_style = Some(style);
785
786 if let CursorStyle::None = style {
787 let wl_pointer = state
788 .wl_pointer
789 .clone()
790 .expect("window is focused by pointer");
791 wl_pointer.set_cursor(serial, None, 0, 0);
792 } else if let Some(cursor_shape_device) = &state.cursor_shape_device {
793 cursor_shape_device.set_shape(serial, to_shape(style));
794 } else if let Some(focused_window) = &state.mouse_focused_window {
795 // cursor-shape-v1 isn't supported, set the cursor using a surface.
796 let wl_pointer = state
797 .wl_pointer
798 .clone()
799 .expect("window is focused by pointer");
800 let scale = focused_window.primary_output_scale();
801 state.cursor.set_icon(
802 &wl_pointer,
803 serial,
804 cursor_style_to_icon_names(style),
805 scale,
806 );
807 }
808 }
809 }
810
811 fn open_uri(&self, uri: &str) {
812 let mut state = self.0.borrow_mut();
813 if let (Some(activation), Some(window)) = (
814 state.globals.activation.clone(),
815 state.mouse_focused_window.clone(),
816 ) {
817 state.pending_activation = Some(PendingActivation::Uri(uri.to_string()));
818 let token = activation.get_activation_token(&state.globals.qh, ());
819 let serial = state.serial_tracker.get(SerialKind::MousePress);
820 token.set_serial(serial, &state.wl_seat);
821 token.set_surface(&window.surface());
822 token.commit();
823 } else {
824 let executor = state.common.background_executor.clone();
825 open_uri_internal(executor, uri, None);
826 }
827 }
828
829 fn reveal_path(&self, path: PathBuf) {
830 let mut state = self.0.borrow_mut();
831 if let (Some(activation), Some(window)) = (
832 state.globals.activation.clone(),
833 state.mouse_focused_window.clone(),
834 ) {
835 state.pending_activation = Some(PendingActivation::Path(path));
836 let token = activation.get_activation_token(&state.globals.qh, ());
837 let serial = state.serial_tracker.get(SerialKind::MousePress);
838 token.set_serial(serial, &state.wl_seat);
839 token.set_surface(&window.surface());
840 token.commit();
841 } else {
842 let executor = state.common.background_executor.clone();
843 reveal_path_internal(executor, path, None);
844 }
845 }
846
847 fn with_common<R>(&self, f: impl FnOnce(&mut LinuxCommon) -> R) -> R {
848 f(&mut self.0.borrow_mut().common)
849 }
850
851 fn run(&self) {
852 let mut event_loop = self
853 .0
854 .borrow_mut()
855 .event_loop
856 .take()
857 .expect("App is already running");
858
859 event_loop
860 .run(
861 None,
862 &mut WaylandClientStatePtr(Rc::downgrade(&self.0)),
863 |_| {},
864 )
865 .log_err();
866 }
867
868 fn write_to_primary(&self, item: gpui::ClipboardItem) {
869 let mut state = self.0.borrow_mut();
870 let (Some(primary_selection_manager), Some(primary_selection)) = (
871 state.globals.primary_selection_manager.clone(),
872 state.primary_selection.clone(),
873 ) else {
874 return;
875 };
876 if state.mouse_focused_window.is_some() || state.keyboard_focused_window.is_some() {
877 state.clipboard.set_primary(item);
878 let serial = state
879 .serial_tracker
880 .latest_of(&[SerialKind::KeyPress, SerialKind::MousePress]);
881 let data_source = primary_selection_manager.create_source(&state.globals.qh, ());
882 for mime_type in TEXT_MIME_TYPES {
883 data_source.offer(mime_type.to_string());
884 }
885 data_source.offer(state.clipboard.self_mime());
886 primary_selection.set_selection(Some(&data_source), serial);
887 }
888 }
889
890 fn write_to_clipboard(&self, item: gpui::ClipboardItem) {
891 let mut state = self.0.borrow_mut();
892 let (Some(data_device_manager), Some(data_device)) = (
893 state.globals.data_device_manager.clone(),
894 state.data_device.clone(),
895 ) else {
896 return;
897 };
898 if state.mouse_focused_window.is_some() || state.keyboard_focused_window.is_some() {
899 state.clipboard.set(item);
900 let serial = state
901 .serial_tracker
902 .latest_of(&[SerialKind::KeyPress, SerialKind::MousePress]);
903 let data_source = data_device_manager.create_data_source(&state.globals.qh, ());
904 for mime_type in TEXT_MIME_TYPES {
905 data_source.offer(mime_type.to_string());
906 }
907 data_source.offer(state.clipboard.self_mime());
908 data_device.set_selection(Some(&data_source), serial);
909 }
910 }
911
912 fn read_from_primary(&self) -> Option<gpui::ClipboardItem> {
913 self.0.borrow_mut().clipboard.read_primary()
914 }
915
916 fn read_from_clipboard(&self) -> Option<gpui::ClipboardItem> {
917 self.0.borrow_mut().clipboard.read()
918 }
919
920 fn active_window(&self) -> Option<AnyWindowHandle> {
921 self.0
922 .borrow_mut()
923 .keyboard_focused_window
924 .as_ref()
925 .map(|window| window.handle())
926 }
927
928 fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
929 None
930 }
931
932 fn compositor_name(&self) -> &'static str {
933 "Wayland"
934 }
935
936 fn window_identifier(&self) -> impl Future<Output = Option<WindowIdentifier>> + Send + 'static {
937 async fn inner(surface: Option<wl_surface::WlSurface>) -> Option<WindowIdentifier> {
938 if let Some(surface) = surface {
939 ashpd::WindowIdentifier::from_wayland(&surface).await
940 } else {
941 None
942 }
943 }
944
945 let client_state = self.0.borrow();
946 let active_window = client_state.keyboard_focused_window.as_ref();
947 inner(active_window.map(|aw| aw.surface()))
948 }
949}
950
951struct DmabufProbeState {
952 device: Option<u64>,
953}
954
955impl Dispatch<wl_registry::WlRegistry, GlobalListContents> for DmabufProbeState {
956 fn event(
957 _: &mut Self,
958 _: &wl_registry::WlRegistry,
959 _: wl_registry::Event,
960 _: &GlobalListContents,
961 _: &Connection,
962 _: &QueueHandle<Self>,
963 ) {
964 }
965}
966
967impl Dispatch<zwp_linux_dmabuf_v1::ZwpLinuxDmabufV1, ()> for DmabufProbeState {
968 fn event(
969 _: &mut Self,
970 _: &zwp_linux_dmabuf_v1::ZwpLinuxDmabufV1,
971 _: zwp_linux_dmabuf_v1::Event,
972 _: &(),
973 _: &Connection,
974 _: &QueueHandle<Self>,
975 ) {
976 }
977}
978
979impl Dispatch<zwp_linux_dmabuf_feedback_v1::ZwpLinuxDmabufFeedbackV1, ()> for DmabufProbeState {
980 fn event(
981 state: &mut Self,
982 _: &zwp_linux_dmabuf_feedback_v1::ZwpLinuxDmabufFeedbackV1,
983 event: zwp_linux_dmabuf_feedback_v1::Event,
984 _: &(),
985 _: &Connection,
986 _: &QueueHandle<Self>,
987 ) {
988 if let zwp_linux_dmabuf_feedback_v1::Event::MainDevice { device } = event {
989 if let Ok(bytes) = <[u8; 8]>::try_from(device.as_slice()) {
990 state.device = Some(u64::from_ne_bytes(bytes));
991 }
992 }
993 }
994}
995
996fn detect_compositor_gpu() -> Option<CompositorGpuHint> {
997 let connection = Connection::connect_to_env().ok()?;
998 let (globals, mut event_queue) = registry_queue_init::<DmabufProbeState>(&connection).ok()?;
999 let queue_handle = event_queue.handle();
1000
1001 let dmabuf: zwp_linux_dmabuf_v1::ZwpLinuxDmabufV1 =
1002 globals.bind(&queue_handle, 4..=4, ()).ok()?;
1003 let feedback = dmabuf.get_default_feedback(&queue_handle, ());
1004
1005 let mut state = DmabufProbeState { device: None };
1006
1007 event_queue.roundtrip(&mut state).ok()?;
1008
1009 feedback.destroy();
1010 dmabuf.destroy();
1011
1012 crate::linux::compositor_gpu_hint_from_dev_t(state.device?)
1013}
1014
1015impl Dispatch<wl_registry::WlRegistry, GlobalListContents> for WaylandClientStatePtr {
1016 fn event(
1017 this: &mut Self,
1018 registry: &wl_registry::WlRegistry,
1019 event: wl_registry::Event,
1020 _: &GlobalListContents,
1021 _: &Connection,
1022 qh: &QueueHandle<Self>,
1023 ) {
1024 let client = this.get_client();
1025 let mut state = client.borrow_mut();
1026
1027 match event {
1028 wl_registry::Event::Global {
1029 name,
1030 interface,
1031 version,
1032 } => match &interface[..] {
1033 "wl_seat" => {
1034 if let Some(wl_pointer) = state.wl_pointer.take() {
1035 wl_pointer.release();
1036 }
1037 if let Some(wl_keyboard) = state.wl_keyboard.take() {
1038 wl_keyboard.release();
1039 }
1040 state.wl_seat.release();
1041 state.wl_seat = registry.bind::<wl_seat::WlSeat, _, _>(
1042 name,
1043 wl_seat_version(version),
1044 qh,
1045 (),
1046 );
1047 }
1048 "wl_output" => {
1049 let output = registry.bind::<wl_output::WlOutput, _, _>(
1050 name,
1051 wl_output_version(version),
1052 qh,
1053 (),
1054 );
1055
1056 state
1057 .in_progress_outputs
1058 .insert(output.id(), InProgressOutput::default());
1059 state.wl_outputs.insert(output.id(), output);
1060 }
1061 _ => {}
1062 },
1063 wl_registry::Event::GlobalRemove { name: _ } => {
1064 // TODO: handle global removal
1065 }
1066 _ => {}
1067 }
1068 }
1069}
1070
1071delegate_noop!(WaylandClientStatePtr: ignore xdg_activation_v1::XdgActivationV1);
1072delegate_noop!(WaylandClientStatePtr: ignore wl_compositor::WlCompositor);
1073delegate_noop!(WaylandClientStatePtr: ignore wp_cursor_shape_device_v1::WpCursorShapeDeviceV1);
1074delegate_noop!(WaylandClientStatePtr: ignore wp_cursor_shape_manager_v1::WpCursorShapeManagerV1);
1075delegate_noop!(WaylandClientStatePtr: ignore wl_data_device_manager::WlDataDeviceManager);
1076delegate_noop!(WaylandClientStatePtr: ignore zwp_primary_selection_device_manager_v1::ZwpPrimarySelectionDeviceManagerV1);
1077delegate_noop!(WaylandClientStatePtr: ignore wl_shm::WlShm);
1078delegate_noop!(WaylandClientStatePtr: ignore wl_shm_pool::WlShmPool);
1079delegate_noop!(WaylandClientStatePtr: ignore wl_buffer::WlBuffer);
1080delegate_noop!(WaylandClientStatePtr: ignore wl_region::WlRegion);
1081delegate_noop!(WaylandClientStatePtr: ignore wp_fractional_scale_manager_v1::WpFractionalScaleManagerV1);
1082delegate_noop!(WaylandClientStatePtr: ignore zxdg_decoration_manager_v1::ZxdgDecorationManagerV1);
1083delegate_noop!(WaylandClientStatePtr: ignore zwlr_layer_shell_v1::ZwlrLayerShellV1);
1084delegate_noop!(WaylandClientStatePtr: ignore org_kde_kwin_blur_manager::OrgKdeKwinBlurManager);
1085delegate_noop!(WaylandClientStatePtr: ignore zwp_text_input_manager_v3::ZwpTextInputManagerV3);
1086delegate_noop!(WaylandClientStatePtr: ignore org_kde_kwin_blur::OrgKdeKwinBlur);
1087delegate_noop!(WaylandClientStatePtr: ignore wp_viewporter::WpViewporter);
1088delegate_noop!(WaylandClientStatePtr: ignore wp_viewport::WpViewport);
1089
1090impl Dispatch<WlCallback, ObjectId> for WaylandClientStatePtr {
1091 fn event(
1092 state: &mut WaylandClientStatePtr,
1093 _: &wl_callback::WlCallback,
1094 event: wl_callback::Event,
1095 surface_id: &ObjectId,
1096 _: &Connection,
1097 _: &QueueHandle<Self>,
1098 ) {
1099 let client = state.get_client();
1100 let mut state = client.borrow_mut();
1101 let Some(window) = get_window(&mut state, surface_id) else {
1102 return;
1103 };
1104 drop(state);
1105
1106 if let wl_callback::Event::Done { .. } = event {
1107 window.frame();
1108 }
1109 }
1110}
1111
1112pub(crate) fn get_window(
1113 state: &mut RefMut<WaylandClientState>,
1114 surface_id: &ObjectId,
1115) -> Option<WaylandWindowStatePtr> {
1116 state.windows.get(surface_id).cloned()
1117}
1118
1119impl Dispatch<wl_surface::WlSurface, ()> for WaylandClientStatePtr {
1120 fn event(
1121 this: &mut Self,
1122 surface: &wl_surface::WlSurface,
1123 event: <wl_surface::WlSurface as Proxy>::Event,
1124 _: &(),
1125 _: &Connection,
1126 _: &QueueHandle<Self>,
1127 ) {
1128 let client = this.get_client();
1129 let mut state = client.borrow_mut();
1130
1131 let Some(window) = get_window(&mut state, &surface.id()) else {
1132 return;
1133 };
1134 #[allow(clippy::mutable_key_type)]
1135 let outputs = state.outputs.clone();
1136 drop(state);
1137
1138 window.handle_surface_event(event, outputs);
1139 }
1140}
1141
1142impl Dispatch<wl_output::WlOutput, ()> for WaylandClientStatePtr {
1143 fn event(
1144 this: &mut Self,
1145 output: &wl_output::WlOutput,
1146 event: <wl_output::WlOutput as Proxy>::Event,
1147 _: &(),
1148 _: &Connection,
1149 _: &QueueHandle<Self>,
1150 ) {
1151 let client = this.get_client();
1152 let mut state = client.borrow_mut();
1153
1154 let Some(in_progress_output) = state.in_progress_outputs.get_mut(&output.id()) else {
1155 return;
1156 };
1157
1158 match event {
1159 wl_output::Event::Name { name } => {
1160 in_progress_output.name = Some(name);
1161 }
1162 wl_output::Event::Scale { factor } => {
1163 in_progress_output.scale = Some(factor);
1164 }
1165 wl_output::Event::Geometry { x, y, .. } => {
1166 in_progress_output.position = Some(point(DevicePixels(x), DevicePixels(y)))
1167 }
1168 wl_output::Event::Mode { width, height, .. } => {
1169 in_progress_output.size = Some(size(DevicePixels(width), DevicePixels(height)))
1170 }
1171 wl_output::Event::Done => {
1172 if let Some(complete) = in_progress_output.complete() {
1173 state.outputs.insert(output.id(), complete);
1174 }
1175 state.in_progress_outputs.remove(&output.id());
1176 }
1177 _ => {}
1178 }
1179 }
1180}
1181
1182impl Dispatch<xdg_surface::XdgSurface, ObjectId> for WaylandClientStatePtr {
1183 fn event(
1184 state: &mut Self,
1185 _: &xdg_surface::XdgSurface,
1186 event: xdg_surface::Event,
1187 surface_id: &ObjectId,
1188 _: &Connection,
1189 _: &QueueHandle<Self>,
1190 ) {
1191 let client = state.get_client();
1192 let mut state = client.borrow_mut();
1193 let Some(window) = get_window(&mut state, surface_id) else {
1194 return;
1195 };
1196 drop(state);
1197 window.handle_xdg_surface_event(event);
1198 }
1199}
1200
1201impl Dispatch<xdg_toplevel::XdgToplevel, ObjectId> for WaylandClientStatePtr {
1202 fn event(
1203 this: &mut Self,
1204 _: &xdg_toplevel::XdgToplevel,
1205 event: <xdg_toplevel::XdgToplevel as Proxy>::Event,
1206 surface_id: &ObjectId,
1207 _: &Connection,
1208 _: &QueueHandle<Self>,
1209 ) {
1210 let client = this.get_client();
1211 let mut state = client.borrow_mut();
1212 let Some(window) = get_window(&mut state, surface_id) else {
1213 return;
1214 };
1215
1216 drop(state);
1217 let should_close = window.handle_toplevel_event(event);
1218
1219 if should_close {
1220 // The close logic will be handled in drop_window()
1221 window.close();
1222 }
1223 }
1224}
1225
1226impl Dispatch<zwlr_layer_surface_v1::ZwlrLayerSurfaceV1, ObjectId> for WaylandClientStatePtr {
1227 fn event(
1228 this: &mut Self,
1229 _: &zwlr_layer_surface_v1::ZwlrLayerSurfaceV1,
1230 event: <zwlr_layer_surface_v1::ZwlrLayerSurfaceV1 as Proxy>::Event,
1231 surface_id: &ObjectId,
1232 _: &Connection,
1233 _: &QueueHandle<Self>,
1234 ) {
1235 let client = this.get_client();
1236 let mut state = client.borrow_mut();
1237 let Some(window) = get_window(&mut state, surface_id) else {
1238 return;
1239 };
1240
1241 drop(state);
1242 let should_close = window.handle_layersurface_event(event);
1243
1244 if should_close {
1245 // The close logic will be handled in drop_window()
1246 window.close();
1247 }
1248 }
1249}
1250
1251impl Dispatch<xdg_wm_base::XdgWmBase, ()> for WaylandClientStatePtr {
1252 fn event(
1253 _: &mut Self,
1254 wm_base: &xdg_wm_base::XdgWmBase,
1255 event: <xdg_wm_base::XdgWmBase as Proxy>::Event,
1256 _: &(),
1257 _: &Connection,
1258 _: &QueueHandle<Self>,
1259 ) {
1260 if let xdg_wm_base::Event::Ping { serial } = event {
1261 wm_base.pong(serial);
1262 }
1263 }
1264}
1265
1266impl Dispatch<xdg_activation_token_v1::XdgActivationTokenV1, ()> for WaylandClientStatePtr {
1267 fn event(
1268 this: &mut Self,
1269 token: &xdg_activation_token_v1::XdgActivationTokenV1,
1270 event: <xdg_activation_token_v1::XdgActivationTokenV1 as Proxy>::Event,
1271 _: &(),
1272 _: &Connection,
1273 _: &QueueHandle<Self>,
1274 ) {
1275 let client = this.get_client();
1276 let mut state = client.borrow_mut();
1277
1278 if let xdg_activation_token_v1::Event::Done { token } = event {
1279 let executor = state.common.background_executor.clone();
1280 match state.pending_activation.take() {
1281 Some(PendingActivation::Uri(uri)) => open_uri_internal(executor, &uri, Some(token)),
1282 Some(PendingActivation::Path(path)) => {
1283 reveal_path_internal(executor, path, Some(token))
1284 }
1285 Some(PendingActivation::Window(window)) => {
1286 let Some(window) = get_window(&mut state, &window) else {
1287 return;
1288 };
1289 let activation = state.globals.activation.as_ref().unwrap();
1290 activation.activate(token, &window.surface());
1291 }
1292 None => log::error!("activation token received with no pending activation"),
1293 }
1294 }
1295
1296 token.destroy();
1297 }
1298}
1299
1300impl Dispatch<wl_seat::WlSeat, ()> for WaylandClientStatePtr {
1301 fn event(
1302 state: &mut Self,
1303 seat: &wl_seat::WlSeat,
1304 event: wl_seat::Event,
1305 _: &(),
1306 _: &Connection,
1307 qh: &QueueHandle<Self>,
1308 ) {
1309 if let wl_seat::Event::Capabilities {
1310 capabilities: WEnum::Value(capabilities),
1311 } = event
1312 {
1313 let client = state.get_client();
1314 let mut state = client.borrow_mut();
1315 if capabilities.contains(wl_seat::Capability::Keyboard) {
1316 let keyboard = seat.get_keyboard(qh, ());
1317
1318 if let Some(text_input) = state.text_input.take() {
1319 text_input.destroy();
1320 state.ime_pre_edit = None;
1321 state.composing = false;
1322 }
1323
1324 state.text_input = state
1325 .globals
1326 .text_input_manager
1327 .as_ref()
1328 .map(|text_input_manager| text_input_manager.get_text_input(seat, qh, ()));
1329
1330 if let Some(wl_keyboard) = &state.wl_keyboard {
1331 wl_keyboard.release();
1332 }
1333
1334 state.wl_keyboard = Some(keyboard);
1335 }
1336 if capabilities.contains(wl_seat::Capability::Pointer) {
1337 let pointer = seat.get_pointer(qh, ());
1338
1339 if let Some(cursor_shape_device) = state.cursor_shape_device.take() {
1340 cursor_shape_device.destroy();
1341 }
1342
1343 state.cursor_shape_device = state
1344 .globals
1345 .cursor_shape_manager
1346 .as_ref()
1347 .map(|cursor_shape_manager| cursor_shape_manager.get_pointer(&pointer, qh, ()));
1348
1349 state.pinch_gesture = state.globals.gesture_manager.as_ref().map(
1350 |gesture_manager: &zwp_pointer_gestures_v1::ZwpPointerGesturesV1| {
1351 gesture_manager.get_pinch_gesture(&pointer, qh, ())
1352 },
1353 );
1354
1355 if let Some(wl_pointer) = &state.wl_pointer {
1356 wl_pointer.release();
1357 }
1358
1359 state.wl_pointer = Some(pointer);
1360 }
1361 }
1362 }
1363}
1364
1365impl Dispatch<wl_keyboard::WlKeyboard, ()> for WaylandClientStatePtr {
1366 fn event(
1367 this: &mut Self,
1368 _: &wl_keyboard::WlKeyboard,
1369 event: wl_keyboard::Event,
1370 _: &(),
1371 _: &Connection,
1372 _: &QueueHandle<Self>,
1373 ) {
1374 let client = this.get_client();
1375 let mut state = client.borrow_mut();
1376 match event {
1377 wl_keyboard::Event::RepeatInfo { rate, delay } => {
1378 state.repeat.characters_per_second = rate as u32;
1379 state.repeat.delay = Duration::from_millis(delay as u64);
1380 }
1381 wl_keyboard::Event::Keymap {
1382 format: WEnum::Value(format),
1383 fd,
1384 size,
1385 ..
1386 } => {
1387 if format != wl_keyboard::KeymapFormat::XkbV1 {
1388 log::error!("Received keymap format {:?}, expected XkbV1", format);
1389 return;
1390 }
1391 let xkb_context = xkb::Context::new(xkb::CONTEXT_NO_FLAGS);
1392 let keymap = unsafe {
1393 xkb::Keymap::new_from_fd(
1394 &xkb_context,
1395 fd,
1396 size as usize,
1397 XKB_KEYMAP_FORMAT_TEXT_V1,
1398 KEYMAP_COMPILE_NO_FLAGS,
1399 )
1400 .log_err()
1401 .flatten()
1402 .expect("Failed to create keymap")
1403 };
1404 state.keymap_state = Some(xkb::State::new(&keymap));
1405 state.compose_state = get_xkb_compose_state(&xkb_context);
1406 drop(state);
1407
1408 this.handle_keyboard_layout_change();
1409 }
1410 wl_keyboard::Event::Enter { surface, .. } => {
1411 state.keyboard_focused_window = get_window(&mut state, &surface.id());
1412 state.enter_token = Some(());
1413
1414 if let Some(window) = state.keyboard_focused_window.clone() {
1415 drop(state);
1416 window.set_focused(true);
1417 }
1418 }
1419 wl_keyboard::Event::Leave { surface, .. } => {
1420 let keyboard_focused_window = get_window(&mut state, &surface.id());
1421 state.keyboard_focused_window = None;
1422 state.enter_token.take();
1423 // Prevent keyboard events from repeating after opening e.g. a file chooser and closing it quickly
1424 state.repeat.current_id += 1;
1425
1426 if let Some(window) = keyboard_focused_window {
1427 if let Some(ref mut compose) = state.compose_state {
1428 compose.reset();
1429 }
1430 state.pre_edit_text.take();
1431 drop(state);
1432 window.handle_ime(ImeInput::DeleteText);
1433 window.set_focused(false);
1434 }
1435 }
1436 wl_keyboard::Event::Modifiers {
1437 mods_depressed,
1438 mods_latched,
1439 mods_locked,
1440 group,
1441 ..
1442 } => {
1443 let focused_window = state.keyboard_focused_window.clone();
1444
1445 let keymap_state = state.keymap_state.as_mut().unwrap();
1446 let old_layout =
1447 keymap_state.serialize_layout(xkbcommon::xkb::STATE_LAYOUT_EFFECTIVE);
1448 keymap_state.update_mask(mods_depressed, mods_latched, mods_locked, 0, 0, group);
1449 state.modifiers = modifiers_from_xkb(keymap_state);
1450 let keymap_state = state.keymap_state.as_mut().unwrap();
1451 state.capslock = capslock_from_xkb(keymap_state);
1452
1453 let input = PlatformInput::ModifiersChanged(ModifiersChangedEvent {
1454 modifiers: state.modifiers,
1455 capslock: state.capslock,
1456 });
1457 drop(state);
1458
1459 if let Some(focused_window) = focused_window {
1460 focused_window.handle_input(input);
1461 }
1462
1463 if group != old_layout {
1464 this.handle_keyboard_layout_change();
1465 }
1466 }
1467 wl_keyboard::Event::Key {
1468 serial,
1469 key,
1470 state: WEnum::Value(key_state),
1471 ..
1472 } => {
1473 state.serial_tracker.update(SerialKind::KeyPress, serial);
1474
1475 let focused_window = state.keyboard_focused_window.clone();
1476 let Some(focused_window) = focused_window else {
1477 return;
1478 };
1479
1480 let keymap_state = state.keymap_state.as_ref().unwrap();
1481 let keycode = Keycode::from(key + MIN_KEYCODE);
1482 let keysym = keymap_state.key_get_one_sym(keycode);
1483
1484 match key_state {
1485 wl_keyboard::KeyState::Pressed if !keysym.is_modifier_key() => {
1486 let mut keystroke =
1487 keystroke_from_xkb(keymap_state, state.modifiers, keycode);
1488 if let Some(mut compose) = state.compose_state.take() {
1489 compose.feed(keysym);
1490 match compose.status() {
1491 xkb::Status::Composing => {
1492 keystroke.key_char = None;
1493 state.pre_edit_text =
1494 compose.utf8().or(keystroke_underlying_dead_key(keysym));
1495 let pre_edit =
1496 state.pre_edit_text.clone().unwrap_or(String::default());
1497 drop(state);
1498 focused_window.handle_ime(ImeInput::SetMarkedText(pre_edit));
1499 state = client.borrow_mut();
1500 }
1501
1502 xkb::Status::Composed => {
1503 state.pre_edit_text.take();
1504 keystroke.key_char = compose.utf8();
1505 if let Some(keysym) = compose.keysym() {
1506 keystroke.key = xkb::keysym_get_name(keysym);
1507 }
1508 }
1509 xkb::Status::Cancelled => {
1510 let pre_edit = state.pre_edit_text.take();
1511 let new_pre_edit = keystroke_underlying_dead_key(keysym);
1512 state.pre_edit_text = new_pre_edit.clone();
1513 drop(state);
1514 if let Some(pre_edit) = pre_edit {
1515 focused_window.handle_ime(ImeInput::InsertText(pre_edit));
1516 }
1517 if let Some(current_key) = new_pre_edit {
1518 focused_window
1519 .handle_ime(ImeInput::SetMarkedText(current_key));
1520 }
1521 compose.feed(keysym);
1522 state = client.borrow_mut();
1523 }
1524 _ => {}
1525 }
1526 state.compose_state = Some(compose);
1527 }
1528 let input = PlatformInput::KeyDown(KeyDownEvent {
1529 keystroke: keystroke.clone(),
1530 is_held: false,
1531 prefer_character_input: false,
1532 });
1533
1534 state.repeat.current_id += 1;
1535 state.repeat.current_keycode = Some(keycode);
1536
1537 let rate = state.repeat.characters_per_second;
1538 let repeat_interval = Duration::from_secs(1) / rate.max(1);
1539 let id = state.repeat.current_id;
1540 state
1541 .loop_handle
1542 .insert_source(Timer::from_duration(state.repeat.delay), {
1543 let input = PlatformInput::KeyDown(KeyDownEvent {
1544 keystroke,
1545 is_held: true,
1546 prefer_character_input: false,
1547 });
1548 move |event_timestamp, _metadata, this| {
1549 let client = this.get_client();
1550 let state = client.borrow();
1551 let is_repeating = id == state.repeat.current_id
1552 && state.repeat.current_keycode.is_some()
1553 && state.keyboard_focused_window.is_some();
1554
1555 if !is_repeating || rate == 0 {
1556 return TimeoutAction::Drop;
1557 }
1558
1559 let focused_window =
1560 state.keyboard_focused_window.as_ref().unwrap().clone();
1561
1562 drop(state);
1563 focused_window.handle_input(input.clone());
1564
1565 // If the new scheduled time is in the past the event will repeat as soon as possible
1566 TimeoutAction::ToInstant(event_timestamp + repeat_interval)
1567 }
1568 })
1569 .unwrap();
1570
1571 drop(state);
1572 focused_window.handle_input(input);
1573 }
1574 wl_keyboard::KeyState::Released if !keysym.is_modifier_key() => {
1575 let input = PlatformInput::KeyUp(KeyUpEvent {
1576 keystroke: keystroke_from_xkb(keymap_state, state.modifiers, keycode),
1577 });
1578
1579 if state.repeat.current_keycode == Some(keycode) {
1580 state.repeat.current_keycode = None;
1581 }
1582
1583 drop(state);
1584 focused_window.handle_input(input);
1585 }
1586 _ => {}
1587 }
1588 }
1589 _ => {}
1590 }
1591 }
1592}
1593
1594impl Dispatch<zwp_text_input_v3::ZwpTextInputV3, ()> for WaylandClientStatePtr {
1595 fn event(
1596 this: &mut Self,
1597 text_input: &zwp_text_input_v3::ZwpTextInputV3,
1598 event: <zwp_text_input_v3::ZwpTextInputV3 as Proxy>::Event,
1599 _: &(),
1600 _: &Connection,
1601 _: &QueueHandle<Self>,
1602 ) {
1603 let client = this.get_client();
1604 let mut state = client.borrow_mut();
1605 match event {
1606 zwp_text_input_v3::Event::Enter { .. } => {
1607 drop(state);
1608 this.enable_ime();
1609 }
1610 zwp_text_input_v3::Event::Leave { .. } => {
1611 drop(state);
1612 this.disable_ime();
1613 }
1614 zwp_text_input_v3::Event::CommitString { text } => {
1615 state.composing = false;
1616 let Some(window) = state.keyboard_focused_window.clone() else {
1617 return;
1618 };
1619
1620 if let Some(commit_text) = text {
1621 drop(state);
1622 // IBus Intercepts keys like `a`, `b`, but those keys are needed for vim mode.
1623 // We should only send ASCII characters to Zed, otherwise a user could remap a letter like `か` or `相`.
1624 if commit_text.len() == 1 {
1625 window.handle_input(PlatformInput::KeyDown(KeyDownEvent {
1626 keystroke: Keystroke {
1627 modifiers: Modifiers::default(),
1628 key: commit_text.clone(),
1629 key_char: Some(commit_text),
1630 },
1631 is_held: false,
1632 prefer_character_input: false,
1633 }));
1634 } else {
1635 window.handle_ime(ImeInput::InsertText(commit_text));
1636 }
1637 }
1638 }
1639 zwp_text_input_v3::Event::PreeditString { text, .. } => {
1640 state.composing = true;
1641 state.ime_pre_edit = text;
1642 }
1643 zwp_text_input_v3::Event::Done { serial } => {
1644 let last_serial = state.serial_tracker.get(SerialKind::InputMethod);
1645 state.serial_tracker.update(SerialKind::InputMethod, serial);
1646 let Some(window) = state.keyboard_focused_window.clone() else {
1647 return;
1648 };
1649
1650 if let Some(text) = state.ime_pre_edit.take() {
1651 drop(state);
1652 window.handle_ime(ImeInput::SetMarkedText(text));
1653 if let Some(area) = window.get_ime_area() {
1654 text_input.set_cursor_rectangle(
1655 f32::from(area.origin.x) as i32,
1656 f32::from(area.origin.y) as i32,
1657 f32::from(area.size.width) as i32,
1658 f32::from(area.size.height) as i32,
1659 );
1660 if last_serial == serial {
1661 text_input.commit();
1662 }
1663 }
1664 } else {
1665 state.composing = false;
1666 drop(state);
1667 window.handle_ime(ImeInput::DeleteText);
1668 }
1669 }
1670 _ => {}
1671 }
1672 }
1673}
1674
1675fn linux_button_to_gpui(button: u32) -> Option<MouseButton> {
1676 // These values are coming from <linux/input-event-codes.h>.
1677 const BTN_LEFT: u32 = 0x110;
1678 const BTN_RIGHT: u32 = 0x111;
1679 const BTN_MIDDLE: u32 = 0x112;
1680 const BTN_SIDE: u32 = 0x113;
1681 const BTN_EXTRA: u32 = 0x114;
1682 const BTN_FORWARD: u32 = 0x115;
1683 const BTN_BACK: u32 = 0x116;
1684
1685 Some(match button {
1686 BTN_LEFT => MouseButton::Left,
1687 BTN_RIGHT => MouseButton::Right,
1688 BTN_MIDDLE => MouseButton::Middle,
1689 BTN_BACK | BTN_SIDE => MouseButton::Navigate(NavigationDirection::Back),
1690 BTN_FORWARD | BTN_EXTRA => MouseButton::Navigate(NavigationDirection::Forward),
1691 _ => return None,
1692 })
1693}
1694
1695impl Dispatch<wl_pointer::WlPointer, ()> for WaylandClientStatePtr {
1696 fn event(
1697 this: &mut Self,
1698 wl_pointer: &wl_pointer::WlPointer,
1699 event: wl_pointer::Event,
1700 _: &(),
1701 _: &Connection,
1702 _: &QueueHandle<Self>,
1703 ) {
1704 let client = this.get_client();
1705 let mut state = client.borrow_mut();
1706
1707 match event {
1708 wl_pointer::Event::Enter {
1709 serial,
1710 surface,
1711 surface_x,
1712 surface_y,
1713 ..
1714 } => {
1715 state.serial_tracker.update(SerialKind::MouseEnter, serial);
1716 state.mouse_location = Some(point(px(surface_x as f32), px(surface_y as f32)));
1717 state.button_pressed = None;
1718
1719 if let Some(window) = get_window(&mut state, &surface.id()) {
1720 state.mouse_focused_window = Some(window.clone());
1721
1722 if state.enter_token.is_some() {
1723 state.enter_token = None;
1724 }
1725 if let Some(style) = state.cursor_style {
1726 if let CursorStyle::None = style {
1727 let wl_pointer = state
1728 .wl_pointer
1729 .clone()
1730 .expect("window is focused by pointer");
1731 wl_pointer.set_cursor(serial, None, 0, 0);
1732 } else if let Some(cursor_shape_device) = &state.cursor_shape_device {
1733 cursor_shape_device.set_shape(serial, to_shape(style));
1734 } else {
1735 let scale = window.primary_output_scale();
1736 state.cursor.set_icon(
1737 wl_pointer,
1738 serial,
1739 cursor_style_to_icon_names(style),
1740 scale,
1741 );
1742 }
1743 }
1744 drop(state);
1745 window.set_hovered(true);
1746 }
1747 }
1748 wl_pointer::Event::Leave { .. } => {
1749 if let Some(focused_window) = state.mouse_focused_window.clone() {
1750 let input = PlatformInput::MouseExited(MouseExitEvent {
1751 position: state.mouse_location.unwrap(),
1752 pressed_button: state.button_pressed,
1753 modifiers: state.modifiers,
1754 });
1755 state.mouse_focused_window = None;
1756 state.mouse_location = None;
1757 state.button_pressed = None;
1758
1759 drop(state);
1760 focused_window.handle_input(input);
1761 focused_window.set_hovered(false);
1762 }
1763 }
1764 wl_pointer::Event::Motion {
1765 surface_x,
1766 surface_y,
1767 ..
1768 } => {
1769 if state.mouse_focused_window.is_none() {
1770 return;
1771 }
1772 state.mouse_location = Some(point(px(surface_x as f32), px(surface_y as f32)));
1773
1774 if let Some(window) = state.mouse_focused_window.clone() {
1775 if window.is_blocked() {
1776 let default_style = CursorStyle::Arrow;
1777 if state.cursor_style != Some(default_style) {
1778 let serial = state.serial_tracker.get(SerialKind::MouseEnter);
1779 state.cursor_style = Some(default_style);
1780
1781 if let Some(cursor_shape_device) = &state.cursor_shape_device {
1782 cursor_shape_device.set_shape(serial, to_shape(default_style));
1783 } else {
1784 // cursor-shape-v1 isn't supported, set the cursor using a surface.
1785 let wl_pointer = state
1786 .wl_pointer
1787 .clone()
1788 .expect("window is focused by pointer");
1789 let scale = window.primary_output_scale();
1790 state.cursor.set_icon(
1791 &wl_pointer,
1792 serial,
1793 cursor_style_to_icon_names(default_style),
1794 scale,
1795 );
1796 }
1797 }
1798 }
1799 if state
1800 .keyboard_focused_window
1801 .as_ref()
1802 .is_some_and(|keyboard_window| window.ptr_eq(keyboard_window))
1803 {
1804 state.enter_token = None;
1805 }
1806 let input = PlatformInput::MouseMove(MouseMoveEvent {
1807 position: state.mouse_location.unwrap(),
1808 pressed_button: state.button_pressed,
1809 modifiers: state.modifiers,
1810 });
1811 drop(state);
1812 window.handle_input(input);
1813 }
1814 }
1815 wl_pointer::Event::Button {
1816 serial,
1817 button,
1818 state: WEnum::Value(button_state),
1819 ..
1820 } => {
1821 state.serial_tracker.update(SerialKind::MousePress, serial);
1822 let button = linux_button_to_gpui(button);
1823 let Some(button) = button else { return };
1824 if state.mouse_focused_window.is_none() {
1825 return;
1826 }
1827 match button_state {
1828 wl_pointer::ButtonState::Pressed => {
1829 if let Some(window) = state.keyboard_focused_window.clone() {
1830 if state.composing && state.text_input.is_some() {
1831 drop(state);
1832 // text_input_v3 don't have something like a reset function
1833 this.disable_ime();
1834 this.enable_ime();
1835 window.handle_ime(ImeInput::UnmarkText);
1836 state = client.borrow_mut();
1837 } else if let (Some(text), Some(compose)) =
1838 (state.pre_edit_text.take(), state.compose_state.as_mut())
1839 {
1840 compose.reset();
1841 drop(state);
1842 window.handle_ime(ImeInput::InsertText(text));
1843 state = client.borrow_mut();
1844 }
1845 }
1846 let click_elapsed = state.click.last_click.elapsed();
1847
1848 if click_elapsed < DOUBLE_CLICK_INTERVAL
1849 && state
1850 .click
1851 .last_mouse_button
1852 .is_some_and(|prev_button| prev_button == button)
1853 && is_within_click_distance(
1854 state.click.last_location,
1855 state.mouse_location.unwrap(),
1856 )
1857 {
1858 state.click.current_count += 1;
1859 } else {
1860 state.click.current_count = 1;
1861 }
1862
1863 state.click.last_click = Instant::now();
1864 state.click.last_mouse_button = Some(button);
1865 state.click.last_location = state.mouse_location.unwrap();
1866
1867 state.button_pressed = Some(button);
1868
1869 if let Some(window) = state.mouse_focused_window.clone() {
1870 let input = PlatformInput::MouseDown(MouseDownEvent {
1871 button,
1872 position: state.mouse_location.unwrap(),
1873 modifiers: state.modifiers,
1874 click_count: state.click.current_count,
1875 first_mouse: state.enter_token.take().is_some(),
1876 });
1877 drop(state);
1878 window.handle_input(input);
1879 }
1880 }
1881 wl_pointer::ButtonState::Released => {
1882 state.button_pressed = None;
1883
1884 if let Some(window) = state.mouse_focused_window.clone() {
1885 let input = PlatformInput::MouseUp(MouseUpEvent {
1886 button,
1887 position: state.mouse_location.unwrap(),
1888 modifiers: state.modifiers,
1889 click_count: state.click.current_count,
1890 });
1891 drop(state);
1892 window.handle_input(input);
1893 }
1894 }
1895 _ => {}
1896 }
1897 }
1898
1899 // Axis Events
1900 wl_pointer::Event::AxisSource {
1901 axis_source: WEnum::Value(axis_source),
1902 } => {
1903 state.axis_source = axis_source;
1904 }
1905 wl_pointer::Event::Axis {
1906 axis: WEnum::Value(axis),
1907 value,
1908 ..
1909 } => {
1910 if state.axis_source == AxisSource::Wheel {
1911 return;
1912 }
1913 let axis = if state.modifiers.shift {
1914 wl_pointer::Axis::HorizontalScroll
1915 } else {
1916 axis
1917 };
1918 let axis_modifier = match axis {
1919 wl_pointer::Axis::VerticalScroll => state.vertical_modifier,
1920 wl_pointer::Axis::HorizontalScroll => state.horizontal_modifier,
1921 _ => 1.0,
1922 };
1923 state.scroll_event_received = true;
1924 let scroll_delta = state
1925 .continuous_scroll_delta
1926 .get_or_insert(point(px(0.0), px(0.0)));
1927 let modifier = 3.0;
1928 match axis {
1929 wl_pointer::Axis::VerticalScroll => {
1930 scroll_delta.y += px(value as f32 * modifier * axis_modifier);
1931 }
1932 wl_pointer::Axis::HorizontalScroll => {
1933 scroll_delta.x += px(value as f32 * modifier * axis_modifier);
1934 }
1935 _ => unreachable!(),
1936 }
1937 }
1938 wl_pointer::Event::AxisDiscrete {
1939 axis: WEnum::Value(axis),
1940 discrete,
1941 } => {
1942 state.scroll_event_received = true;
1943 let axis = if state.modifiers.shift {
1944 wl_pointer::Axis::HorizontalScroll
1945 } else {
1946 axis
1947 };
1948 let axis_modifier = match axis {
1949 wl_pointer::Axis::VerticalScroll => state.vertical_modifier,
1950 wl_pointer::Axis::HorizontalScroll => state.horizontal_modifier,
1951 _ => 1.0,
1952 };
1953
1954 let scroll_delta = state.discrete_scroll_delta.get_or_insert(point(0.0, 0.0));
1955 match axis {
1956 wl_pointer::Axis::VerticalScroll => {
1957 scroll_delta.y += discrete as f32 * axis_modifier * SCROLL_LINES;
1958 }
1959 wl_pointer::Axis::HorizontalScroll => {
1960 scroll_delta.x += discrete as f32 * axis_modifier * SCROLL_LINES;
1961 }
1962 _ => unreachable!(),
1963 }
1964 }
1965 wl_pointer::Event::AxisValue120 {
1966 axis: WEnum::Value(axis),
1967 value120,
1968 } => {
1969 state.scroll_event_received = true;
1970 let axis = if state.modifiers.shift {
1971 wl_pointer::Axis::HorizontalScroll
1972 } else {
1973 axis
1974 };
1975 let axis_modifier = match axis {
1976 wl_pointer::Axis::VerticalScroll => state.vertical_modifier,
1977 wl_pointer::Axis::HorizontalScroll => state.horizontal_modifier,
1978 _ => unreachable!(),
1979 };
1980
1981 let scroll_delta = state.discrete_scroll_delta.get_or_insert(point(0.0, 0.0));
1982 let wheel_percent = value120 as f32 / 120.0;
1983 match axis {
1984 wl_pointer::Axis::VerticalScroll => {
1985 scroll_delta.y += wheel_percent * axis_modifier * SCROLL_LINES;
1986 }
1987 wl_pointer::Axis::HorizontalScroll => {
1988 scroll_delta.x += wheel_percent * axis_modifier * SCROLL_LINES;
1989 }
1990 _ => unreachable!(),
1991 }
1992 }
1993 wl_pointer::Event::Frame => {
1994 if state.scroll_event_received {
1995 state.scroll_event_received = false;
1996 let continuous = state.continuous_scroll_delta.take();
1997 let discrete = state.discrete_scroll_delta.take();
1998 if let Some(continuous) = continuous {
1999 if let Some(window) = state.mouse_focused_window.clone() {
2000 let input = PlatformInput::ScrollWheel(ScrollWheelEvent {
2001 position: state.mouse_location.unwrap(),
2002 delta: ScrollDelta::Pixels(continuous),
2003 modifiers: state.modifiers,
2004 touch_phase: TouchPhase::Moved,
2005 });
2006 drop(state);
2007 window.handle_input(input);
2008 }
2009 } else if let Some(discrete) = discrete
2010 && let Some(window) = state.mouse_focused_window.clone()
2011 {
2012 let input = PlatformInput::ScrollWheel(ScrollWheelEvent {
2013 position: state.mouse_location.unwrap(),
2014 delta: ScrollDelta::Lines(discrete),
2015 modifiers: state.modifiers,
2016 touch_phase: TouchPhase::Moved,
2017 });
2018 drop(state);
2019 window.handle_input(input);
2020 }
2021 }
2022 }
2023 _ => {}
2024 }
2025 }
2026}
2027
2028impl Dispatch<zwp_pointer_gestures_v1::ZwpPointerGesturesV1, ()> for WaylandClientStatePtr {
2029 fn event(
2030 _this: &mut Self,
2031 _: &zwp_pointer_gestures_v1::ZwpPointerGesturesV1,
2032 _: <zwp_pointer_gestures_v1::ZwpPointerGesturesV1 as Proxy>::Event,
2033 _: &(),
2034 _: &Connection,
2035 _: &QueueHandle<Self>,
2036 ) {
2037 // The gesture manager doesn't generate events
2038 }
2039}
2040
2041impl Dispatch<zwp_pointer_gesture_pinch_v1::ZwpPointerGesturePinchV1, ()>
2042 for WaylandClientStatePtr
2043{
2044 fn event(
2045 this: &mut Self,
2046 _: &zwp_pointer_gesture_pinch_v1::ZwpPointerGesturePinchV1,
2047 event: <zwp_pointer_gesture_pinch_v1::ZwpPointerGesturePinchV1 as Proxy>::Event,
2048 _: &(),
2049 _: &Connection,
2050 _: &QueueHandle<Self>,
2051 ) {
2052 use gpui::PinchEvent;
2053
2054 let client = this.get_client();
2055 let mut state = client.borrow_mut();
2056
2057 let Some(window) = state.mouse_focused_window.clone() else {
2058 return;
2059 };
2060
2061 match event {
2062 zwp_pointer_gesture_pinch_v1::Event::Begin {
2063 serial: _,
2064 time: _,
2065 surface: _,
2066 fingers: _,
2067 } => {
2068 state.pinch_scale = 1.0;
2069 let input = PlatformInput::Pinch(PinchEvent {
2070 position: state.mouse_location.unwrap_or(point(px(0.0), px(0.0))),
2071 delta: 0.0,
2072 modifiers: state.modifiers,
2073 phase: TouchPhase::Started,
2074 });
2075 drop(state);
2076 window.handle_input(input);
2077 }
2078 zwp_pointer_gesture_pinch_v1::Event::Update { time: _, scale, .. } => {
2079 let new_absolute_scale = scale as f32;
2080 let previous_scale = state.pinch_scale;
2081 let zoom_delta = new_absolute_scale - previous_scale;
2082 state.pinch_scale = new_absolute_scale;
2083
2084 let input = PlatformInput::Pinch(PinchEvent {
2085 position: state.mouse_location.unwrap_or(point(px(0.0), px(0.0))),
2086 delta: zoom_delta,
2087 modifiers: state.modifiers,
2088 phase: TouchPhase::Moved,
2089 });
2090 drop(state);
2091 window.handle_input(input);
2092 }
2093 zwp_pointer_gesture_pinch_v1::Event::End {
2094 serial: _,
2095 time: _,
2096 cancelled: _,
2097 } => {
2098 state.pinch_scale = 1.0;
2099 let input = PlatformInput::Pinch(PinchEvent {
2100 position: state.mouse_location.unwrap_or(point(px(0.0), px(0.0))),
2101 delta: 0.0,
2102 modifiers: state.modifiers,
2103 phase: TouchPhase::Ended,
2104 });
2105 drop(state);
2106 window.handle_input(input);
2107 }
2108 _ => {}
2109 }
2110 }
2111}
2112
2113impl Dispatch<wp_fractional_scale_v1::WpFractionalScaleV1, ObjectId> for WaylandClientStatePtr {
2114 fn event(
2115 this: &mut Self,
2116 _: &wp_fractional_scale_v1::WpFractionalScaleV1,
2117 event: <wp_fractional_scale_v1::WpFractionalScaleV1 as Proxy>::Event,
2118 surface_id: &ObjectId,
2119 _: &Connection,
2120 _: &QueueHandle<Self>,
2121 ) {
2122 let client = this.get_client();
2123 let mut state = client.borrow_mut();
2124
2125 let Some(window) = get_window(&mut state, surface_id) else {
2126 return;
2127 };
2128
2129 drop(state);
2130 window.handle_fractional_scale_event(event);
2131 }
2132}
2133
2134impl Dispatch<zxdg_toplevel_decoration_v1::ZxdgToplevelDecorationV1, ObjectId>
2135 for WaylandClientStatePtr
2136{
2137 fn event(
2138 this: &mut Self,
2139 _: &zxdg_toplevel_decoration_v1::ZxdgToplevelDecorationV1,
2140 event: zxdg_toplevel_decoration_v1::Event,
2141 surface_id: &ObjectId,
2142 _: &Connection,
2143 _: &QueueHandle<Self>,
2144 ) {
2145 let client = this.get_client();
2146 let mut state = client.borrow_mut();
2147 let Some(window) = get_window(&mut state, surface_id) else {
2148 return;
2149 };
2150
2151 drop(state);
2152 window.handle_toplevel_decoration_event(event);
2153 }
2154}
2155
2156impl Dispatch<wl_data_device::WlDataDevice, ()> for WaylandClientStatePtr {
2157 fn event(
2158 this: &mut Self,
2159 _: &wl_data_device::WlDataDevice,
2160 event: wl_data_device::Event,
2161 _: &(),
2162 _: &Connection,
2163 _: &QueueHandle<Self>,
2164 ) {
2165 let client = this.get_client();
2166 let mut state = client.borrow_mut();
2167
2168 match event {
2169 // Clipboard
2170 wl_data_device::Event::DataOffer { id: data_offer } => {
2171 state.data_offers.push(DataOffer::new(data_offer));
2172 if state.data_offers.len() > 2 {
2173 // At most we store a clipboard offer and a drag and drop offer.
2174 state.data_offers.remove(0).inner.destroy();
2175 }
2176 }
2177 wl_data_device::Event::Selection { id: data_offer } => {
2178 if let Some(offer) = data_offer {
2179 let offer = state
2180 .data_offers
2181 .iter()
2182 .find(|wrapper| wrapper.inner.id() == offer.id());
2183 let offer = offer.cloned();
2184 state.clipboard.set_offer(offer);
2185 } else {
2186 state.clipboard.set_offer(None);
2187 }
2188 }
2189
2190 // Drag and drop
2191 wl_data_device::Event::Enter {
2192 serial,
2193 surface,
2194 x,
2195 y,
2196 id: data_offer,
2197 } => {
2198 state.serial_tracker.update(SerialKind::DataDevice, serial);
2199 if let Some(data_offer) = data_offer {
2200 let Some(drag_window) = get_window(&mut state, &surface.id()) else {
2201 return;
2202 };
2203
2204 const ACTIONS: DndAction = DndAction::Copy;
2205 data_offer.set_actions(ACTIONS, ACTIONS);
2206
2207 let pipe = Pipe::new().unwrap();
2208 data_offer.receive(FILE_LIST_MIME_TYPE.to_string(), unsafe {
2209 BorrowedFd::borrow_raw(pipe.write.as_raw_fd())
2210 });
2211 let fd = pipe.read;
2212 drop(pipe.write);
2213
2214 let read_task = state.common.background_executor.spawn(async {
2215 let buffer = unsafe { read_fd(fd)? };
2216 let text = String::from_utf8(buffer)?;
2217 anyhow::Ok(text)
2218 });
2219
2220 let this = this.clone();
2221 state
2222 .common
2223 .foreground_executor
2224 .spawn(async move {
2225 let file_list = match read_task.await {
2226 Ok(list) => list,
2227 Err(err) => {
2228 log::error!("error reading drag and drop pipe: {err:?}");
2229 return;
2230 }
2231 };
2232
2233 let paths: SmallVec<[_; 2]> = file_list
2234 .lines()
2235 .filter_map(|path| Url::parse(path).log_err())
2236 .filter_map(|url| url.to_file_path().log_err())
2237 .collect();
2238 let position = Point::new(x.into(), y.into());
2239
2240 // Prevent dropping text from other programs.
2241 if paths.is_empty() {
2242 data_offer.destroy();
2243 return;
2244 }
2245
2246 let input = PlatformInput::FileDrop(FileDropEvent::Entered {
2247 position,
2248 paths: gpui::ExternalPaths(paths),
2249 });
2250
2251 let client = this.get_client();
2252 let mut state = client.borrow_mut();
2253 state.drag.data_offer = Some(data_offer);
2254 state.drag.window = Some(drag_window.clone());
2255 state.drag.position = position;
2256
2257 drop(state);
2258 drag_window.handle_input(input);
2259 })
2260 .detach();
2261 }
2262 }
2263 wl_data_device::Event::Motion { x, y, .. } => {
2264 let Some(drag_window) = state.drag.window.clone() else {
2265 return;
2266 };
2267 let position = Point::new(x.into(), y.into());
2268 state.drag.position = position;
2269
2270 let input = PlatformInput::FileDrop(FileDropEvent::Pending { position });
2271 drop(state);
2272 drag_window.handle_input(input);
2273 }
2274 wl_data_device::Event::Leave => {
2275 let Some(drag_window) = state.drag.window.clone() else {
2276 return;
2277 };
2278 let data_offer = state.drag.data_offer.clone().unwrap();
2279 data_offer.destroy();
2280
2281 state.drag.data_offer = None;
2282 state.drag.window = None;
2283
2284 let input = PlatformInput::FileDrop(FileDropEvent::Exited {});
2285 drop(state);
2286 drag_window.handle_input(input);
2287 }
2288 wl_data_device::Event::Drop => {
2289 let Some(drag_window) = state.drag.window.clone() else {
2290 return;
2291 };
2292 let data_offer = state.drag.data_offer.clone().unwrap();
2293 data_offer.finish();
2294 data_offer.destroy();
2295
2296 state.drag.data_offer = None;
2297 state.drag.window = None;
2298
2299 let input = PlatformInput::FileDrop(FileDropEvent::Submit {
2300 position: state.drag.position,
2301 });
2302 drop(state);
2303 drag_window.handle_input(input);
2304 }
2305 _ => {}
2306 }
2307 }
2308
2309 event_created_child!(WaylandClientStatePtr, wl_data_device::WlDataDevice, [
2310 wl_data_device::EVT_DATA_OFFER_OPCODE => (wl_data_offer::WlDataOffer, ()),
2311 ]);
2312}
2313
2314impl Dispatch<wl_data_offer::WlDataOffer, ()> for WaylandClientStatePtr {
2315 fn event(
2316 this: &mut Self,
2317 data_offer: &wl_data_offer::WlDataOffer,
2318 event: wl_data_offer::Event,
2319 _: &(),
2320 _: &Connection,
2321 _: &QueueHandle<Self>,
2322 ) {
2323 let client = this.get_client();
2324 let mut state = client.borrow_mut();
2325
2326 if let wl_data_offer::Event::Offer { mime_type } = event {
2327 // Drag and drop
2328 if mime_type == FILE_LIST_MIME_TYPE {
2329 let serial = state.serial_tracker.get(SerialKind::DataDevice);
2330 let mime_type = mime_type.clone();
2331 data_offer.accept(serial, Some(mime_type));
2332 }
2333
2334 // Clipboard
2335 if let Some(offer) = state
2336 .data_offers
2337 .iter_mut()
2338 .find(|wrapper| wrapper.inner.id() == data_offer.id())
2339 {
2340 offer.add_mime_type(mime_type);
2341 }
2342 }
2343 }
2344}
2345
2346impl Dispatch<wl_data_source::WlDataSource, ()> for WaylandClientStatePtr {
2347 fn event(
2348 this: &mut Self,
2349 data_source: &wl_data_source::WlDataSource,
2350 event: wl_data_source::Event,
2351 _: &(),
2352 _: &Connection,
2353 _: &QueueHandle<Self>,
2354 ) {
2355 let client = this.get_client();
2356 let state = client.borrow_mut();
2357
2358 match event {
2359 wl_data_source::Event::Send { mime_type, fd } => {
2360 state.clipboard.send(mime_type, fd);
2361 }
2362 wl_data_source::Event::Cancelled => {
2363 data_source.destroy();
2364 }
2365 _ => {}
2366 }
2367 }
2368}
2369
2370impl Dispatch<zwp_primary_selection_device_v1::ZwpPrimarySelectionDeviceV1, ()>
2371 for WaylandClientStatePtr
2372{
2373 fn event(
2374 this: &mut Self,
2375 _: &zwp_primary_selection_device_v1::ZwpPrimarySelectionDeviceV1,
2376 event: zwp_primary_selection_device_v1::Event,
2377 _: &(),
2378 _: &Connection,
2379 _: &QueueHandle<Self>,
2380 ) {
2381 let client = this.get_client();
2382 let mut state = client.borrow_mut();
2383
2384 match event {
2385 zwp_primary_selection_device_v1::Event::DataOffer { offer } => {
2386 let old_offer = state.primary_data_offer.replace(DataOffer::new(offer));
2387 if let Some(old_offer) = old_offer {
2388 old_offer.inner.destroy();
2389 }
2390 }
2391 zwp_primary_selection_device_v1::Event::Selection { id: data_offer } => {
2392 if data_offer.is_some() {
2393 let offer = state.primary_data_offer.clone();
2394 state.clipboard.set_primary_offer(offer);
2395 } else {
2396 state.clipboard.set_primary_offer(None);
2397 }
2398 }
2399 _ => {}
2400 }
2401 }
2402
2403 event_created_child!(WaylandClientStatePtr, zwp_primary_selection_device_v1::ZwpPrimarySelectionDeviceV1, [
2404 zwp_primary_selection_device_v1::EVT_DATA_OFFER_OPCODE => (zwp_primary_selection_offer_v1::ZwpPrimarySelectionOfferV1, ()),
2405 ]);
2406}
2407
2408impl Dispatch<zwp_primary_selection_offer_v1::ZwpPrimarySelectionOfferV1, ()>
2409 for WaylandClientStatePtr
2410{
2411 fn event(
2412 this: &mut Self,
2413 _data_offer: &zwp_primary_selection_offer_v1::ZwpPrimarySelectionOfferV1,
2414 event: zwp_primary_selection_offer_v1::Event,
2415 _: &(),
2416 _: &Connection,
2417 _: &QueueHandle<Self>,
2418 ) {
2419 let client = this.get_client();
2420 let mut state = client.borrow_mut();
2421
2422 if let zwp_primary_selection_offer_v1::Event::Offer { mime_type } = event
2423 && let Some(offer) = state.primary_data_offer.as_mut()
2424 {
2425 offer.add_mime_type(mime_type);
2426 }
2427 }
2428}
2429
2430impl Dispatch<zwp_primary_selection_source_v1::ZwpPrimarySelectionSourceV1, ()>
2431 for WaylandClientStatePtr
2432{
2433 fn event(
2434 this: &mut Self,
2435 selection_source: &zwp_primary_selection_source_v1::ZwpPrimarySelectionSourceV1,
2436 event: zwp_primary_selection_source_v1::Event,
2437 _: &(),
2438 _: &Connection,
2439 _: &QueueHandle<Self>,
2440 ) {
2441 let client = this.get_client();
2442 let state = client.borrow_mut();
2443
2444 match event {
2445 zwp_primary_selection_source_v1::Event::Send { mime_type, fd } => {
2446 state.clipboard.send_primary(mime_type, fd);
2447 }
2448 zwp_primary_selection_source_v1::Event::Cancelled => {
2449 selection_source.destroy();
2450 }
2451 _ => {}
2452 }
2453 }
2454}
2455
2456impl Dispatch<XdgWmDialogV1, ()> for WaylandClientStatePtr {
2457 fn event(
2458 _: &mut Self,
2459 _: &XdgWmDialogV1,
2460 _: <XdgWmDialogV1 as Proxy>::Event,
2461 _: &(),
2462 _: &Connection,
2463 _: &QueueHandle<Self>,
2464 ) {
2465 }
2466}
2467
2468impl Dispatch<XdgDialogV1, ()> for WaylandClientStatePtr {
2469 fn event(
2470 _state: &mut Self,
2471 _proxy: &XdgDialogV1,
2472 _event: <XdgDialogV1 as Proxy>::Event,
2473 _data: &(),
2474 _conn: &Connection,
2475 _qhandle: &QueueHandle<Self>,
2476 ) {
2477 }
2478}