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.serial_tracker.get(SerialKind::KeyPress);
879 let data_source = primary_selection_manager.create_source(&state.globals.qh, ());
880 for mime_type in TEXT_MIME_TYPES {
881 data_source.offer(mime_type.to_string());
882 }
883 data_source.offer(state.clipboard.self_mime());
884 primary_selection.set_selection(Some(&data_source), serial);
885 }
886 }
887
888 fn write_to_clipboard(&self, item: gpui::ClipboardItem) {
889 let mut state = self.0.borrow_mut();
890 let (Some(data_device_manager), Some(data_device)) = (
891 state.globals.data_device_manager.clone(),
892 state.data_device.clone(),
893 ) else {
894 return;
895 };
896 if state.mouse_focused_window.is_some() || state.keyboard_focused_window.is_some() {
897 state.clipboard.set(item);
898 let serial = state.serial_tracker.get(SerialKind::KeyPress);
899 let data_source = data_device_manager.create_data_source(&state.globals.qh, ());
900 for mime_type in TEXT_MIME_TYPES {
901 data_source.offer(mime_type.to_string());
902 }
903 data_source.offer(state.clipboard.self_mime());
904 data_device.set_selection(Some(&data_source), serial);
905 }
906 }
907
908 fn read_from_primary(&self) -> Option<gpui::ClipboardItem> {
909 self.0.borrow_mut().clipboard.read_primary()
910 }
911
912 fn read_from_clipboard(&self) -> Option<gpui::ClipboardItem> {
913 self.0.borrow_mut().clipboard.read()
914 }
915
916 fn active_window(&self) -> Option<AnyWindowHandle> {
917 self.0
918 .borrow_mut()
919 .keyboard_focused_window
920 .as_ref()
921 .map(|window| window.handle())
922 }
923
924 fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
925 None
926 }
927
928 fn compositor_name(&self) -> &'static str {
929 "Wayland"
930 }
931
932 fn window_identifier(&self) -> impl Future<Output = Option<WindowIdentifier>> + Send + 'static {
933 async fn inner(surface: Option<wl_surface::WlSurface>) -> Option<WindowIdentifier> {
934 if let Some(surface) = surface {
935 ashpd::WindowIdentifier::from_wayland(&surface).await
936 } else {
937 None
938 }
939 }
940
941 let client_state = self.0.borrow();
942 let active_window = client_state.keyboard_focused_window.as_ref();
943 inner(active_window.map(|aw| aw.surface()))
944 }
945}
946
947struct DmabufProbeState {
948 device: Option<u64>,
949}
950
951impl Dispatch<wl_registry::WlRegistry, GlobalListContents> for DmabufProbeState {
952 fn event(
953 _: &mut Self,
954 _: &wl_registry::WlRegistry,
955 _: wl_registry::Event,
956 _: &GlobalListContents,
957 _: &Connection,
958 _: &QueueHandle<Self>,
959 ) {
960 }
961}
962
963impl Dispatch<zwp_linux_dmabuf_v1::ZwpLinuxDmabufV1, ()> for DmabufProbeState {
964 fn event(
965 _: &mut Self,
966 _: &zwp_linux_dmabuf_v1::ZwpLinuxDmabufV1,
967 _: zwp_linux_dmabuf_v1::Event,
968 _: &(),
969 _: &Connection,
970 _: &QueueHandle<Self>,
971 ) {
972 }
973}
974
975impl Dispatch<zwp_linux_dmabuf_feedback_v1::ZwpLinuxDmabufFeedbackV1, ()> for DmabufProbeState {
976 fn event(
977 state: &mut Self,
978 _: &zwp_linux_dmabuf_feedback_v1::ZwpLinuxDmabufFeedbackV1,
979 event: zwp_linux_dmabuf_feedback_v1::Event,
980 _: &(),
981 _: &Connection,
982 _: &QueueHandle<Self>,
983 ) {
984 if let zwp_linux_dmabuf_feedback_v1::Event::MainDevice { device } = event {
985 if let Ok(bytes) = <[u8; 8]>::try_from(device.as_slice()) {
986 state.device = Some(u64::from_ne_bytes(bytes));
987 }
988 }
989 }
990}
991
992fn detect_compositor_gpu() -> Option<CompositorGpuHint> {
993 let connection = Connection::connect_to_env().ok()?;
994 let (globals, mut event_queue) = registry_queue_init::<DmabufProbeState>(&connection).ok()?;
995 let queue_handle = event_queue.handle();
996
997 let dmabuf: zwp_linux_dmabuf_v1::ZwpLinuxDmabufV1 =
998 globals.bind(&queue_handle, 4..=4, ()).ok()?;
999 let feedback = dmabuf.get_default_feedback(&queue_handle, ());
1000
1001 let mut state = DmabufProbeState { device: None };
1002
1003 event_queue.roundtrip(&mut state).ok()?;
1004
1005 feedback.destroy();
1006 dmabuf.destroy();
1007
1008 crate::linux::compositor_gpu_hint_from_dev_t(state.device?)
1009}
1010
1011impl Dispatch<wl_registry::WlRegistry, GlobalListContents> for WaylandClientStatePtr {
1012 fn event(
1013 this: &mut Self,
1014 registry: &wl_registry::WlRegistry,
1015 event: wl_registry::Event,
1016 _: &GlobalListContents,
1017 _: &Connection,
1018 qh: &QueueHandle<Self>,
1019 ) {
1020 let client = this.get_client();
1021 let mut state = client.borrow_mut();
1022
1023 match event {
1024 wl_registry::Event::Global {
1025 name,
1026 interface,
1027 version,
1028 } => match &interface[..] {
1029 "wl_seat" => {
1030 if let Some(wl_pointer) = state.wl_pointer.take() {
1031 wl_pointer.release();
1032 }
1033 if let Some(wl_keyboard) = state.wl_keyboard.take() {
1034 wl_keyboard.release();
1035 }
1036 state.wl_seat.release();
1037 state.wl_seat = registry.bind::<wl_seat::WlSeat, _, _>(
1038 name,
1039 wl_seat_version(version),
1040 qh,
1041 (),
1042 );
1043 }
1044 "wl_output" => {
1045 let output = registry.bind::<wl_output::WlOutput, _, _>(
1046 name,
1047 wl_output_version(version),
1048 qh,
1049 (),
1050 );
1051
1052 state
1053 .in_progress_outputs
1054 .insert(output.id(), InProgressOutput::default());
1055 state.wl_outputs.insert(output.id(), output);
1056 }
1057 _ => {}
1058 },
1059 wl_registry::Event::GlobalRemove { name: _ } => {
1060 // TODO: handle global removal
1061 }
1062 _ => {}
1063 }
1064 }
1065}
1066
1067delegate_noop!(WaylandClientStatePtr: ignore xdg_activation_v1::XdgActivationV1);
1068delegate_noop!(WaylandClientStatePtr: ignore wl_compositor::WlCompositor);
1069delegate_noop!(WaylandClientStatePtr: ignore wp_cursor_shape_device_v1::WpCursorShapeDeviceV1);
1070delegate_noop!(WaylandClientStatePtr: ignore wp_cursor_shape_manager_v1::WpCursorShapeManagerV1);
1071delegate_noop!(WaylandClientStatePtr: ignore wl_data_device_manager::WlDataDeviceManager);
1072delegate_noop!(WaylandClientStatePtr: ignore zwp_primary_selection_device_manager_v1::ZwpPrimarySelectionDeviceManagerV1);
1073delegate_noop!(WaylandClientStatePtr: ignore wl_shm::WlShm);
1074delegate_noop!(WaylandClientStatePtr: ignore wl_shm_pool::WlShmPool);
1075delegate_noop!(WaylandClientStatePtr: ignore wl_buffer::WlBuffer);
1076delegate_noop!(WaylandClientStatePtr: ignore wl_region::WlRegion);
1077delegate_noop!(WaylandClientStatePtr: ignore wp_fractional_scale_manager_v1::WpFractionalScaleManagerV1);
1078delegate_noop!(WaylandClientStatePtr: ignore zxdg_decoration_manager_v1::ZxdgDecorationManagerV1);
1079delegate_noop!(WaylandClientStatePtr: ignore zwlr_layer_shell_v1::ZwlrLayerShellV1);
1080delegate_noop!(WaylandClientStatePtr: ignore org_kde_kwin_blur_manager::OrgKdeKwinBlurManager);
1081delegate_noop!(WaylandClientStatePtr: ignore zwp_text_input_manager_v3::ZwpTextInputManagerV3);
1082delegate_noop!(WaylandClientStatePtr: ignore org_kde_kwin_blur::OrgKdeKwinBlur);
1083delegate_noop!(WaylandClientStatePtr: ignore wp_viewporter::WpViewporter);
1084delegate_noop!(WaylandClientStatePtr: ignore wp_viewport::WpViewport);
1085
1086impl Dispatch<WlCallback, ObjectId> for WaylandClientStatePtr {
1087 fn event(
1088 state: &mut WaylandClientStatePtr,
1089 _: &wl_callback::WlCallback,
1090 event: wl_callback::Event,
1091 surface_id: &ObjectId,
1092 _: &Connection,
1093 _: &QueueHandle<Self>,
1094 ) {
1095 let client = state.get_client();
1096 let mut state = client.borrow_mut();
1097 let Some(window) = get_window(&mut state, surface_id) else {
1098 return;
1099 };
1100 drop(state);
1101
1102 if let wl_callback::Event::Done { .. } = event {
1103 window.frame();
1104 }
1105 }
1106}
1107
1108pub(crate) fn get_window(
1109 state: &mut RefMut<WaylandClientState>,
1110 surface_id: &ObjectId,
1111) -> Option<WaylandWindowStatePtr> {
1112 state.windows.get(surface_id).cloned()
1113}
1114
1115impl Dispatch<wl_surface::WlSurface, ()> for WaylandClientStatePtr {
1116 fn event(
1117 this: &mut Self,
1118 surface: &wl_surface::WlSurface,
1119 event: <wl_surface::WlSurface as Proxy>::Event,
1120 _: &(),
1121 _: &Connection,
1122 _: &QueueHandle<Self>,
1123 ) {
1124 let client = this.get_client();
1125 let mut state = client.borrow_mut();
1126
1127 let Some(window) = get_window(&mut state, &surface.id()) else {
1128 return;
1129 };
1130 #[allow(clippy::mutable_key_type)]
1131 let outputs = state.outputs.clone();
1132 drop(state);
1133
1134 window.handle_surface_event(event, outputs);
1135 }
1136}
1137
1138impl Dispatch<wl_output::WlOutput, ()> for WaylandClientStatePtr {
1139 fn event(
1140 this: &mut Self,
1141 output: &wl_output::WlOutput,
1142 event: <wl_output::WlOutput as Proxy>::Event,
1143 _: &(),
1144 _: &Connection,
1145 _: &QueueHandle<Self>,
1146 ) {
1147 let client = this.get_client();
1148 let mut state = client.borrow_mut();
1149
1150 let Some(in_progress_output) = state.in_progress_outputs.get_mut(&output.id()) else {
1151 return;
1152 };
1153
1154 match event {
1155 wl_output::Event::Name { name } => {
1156 in_progress_output.name = Some(name);
1157 }
1158 wl_output::Event::Scale { factor } => {
1159 in_progress_output.scale = Some(factor);
1160 }
1161 wl_output::Event::Geometry { x, y, .. } => {
1162 in_progress_output.position = Some(point(DevicePixels(x), DevicePixels(y)))
1163 }
1164 wl_output::Event::Mode { width, height, .. } => {
1165 in_progress_output.size = Some(size(DevicePixels(width), DevicePixels(height)))
1166 }
1167 wl_output::Event::Done => {
1168 if let Some(complete) = in_progress_output.complete() {
1169 state.outputs.insert(output.id(), complete);
1170 }
1171 state.in_progress_outputs.remove(&output.id());
1172 }
1173 _ => {}
1174 }
1175 }
1176}
1177
1178impl Dispatch<xdg_surface::XdgSurface, ObjectId> for WaylandClientStatePtr {
1179 fn event(
1180 state: &mut Self,
1181 _: &xdg_surface::XdgSurface,
1182 event: xdg_surface::Event,
1183 surface_id: &ObjectId,
1184 _: &Connection,
1185 _: &QueueHandle<Self>,
1186 ) {
1187 let client = state.get_client();
1188 let mut state = client.borrow_mut();
1189 let Some(window) = get_window(&mut state, surface_id) else {
1190 return;
1191 };
1192 drop(state);
1193 window.handle_xdg_surface_event(event);
1194 }
1195}
1196
1197impl Dispatch<xdg_toplevel::XdgToplevel, ObjectId> for WaylandClientStatePtr {
1198 fn event(
1199 this: &mut Self,
1200 _: &xdg_toplevel::XdgToplevel,
1201 event: <xdg_toplevel::XdgToplevel as Proxy>::Event,
1202 surface_id: &ObjectId,
1203 _: &Connection,
1204 _: &QueueHandle<Self>,
1205 ) {
1206 let client = this.get_client();
1207 let mut state = client.borrow_mut();
1208 let Some(window) = get_window(&mut state, surface_id) else {
1209 return;
1210 };
1211
1212 drop(state);
1213 let should_close = window.handle_toplevel_event(event);
1214
1215 if should_close {
1216 // The close logic will be handled in drop_window()
1217 window.close();
1218 }
1219 }
1220}
1221
1222impl Dispatch<zwlr_layer_surface_v1::ZwlrLayerSurfaceV1, ObjectId> for WaylandClientStatePtr {
1223 fn event(
1224 this: &mut Self,
1225 _: &zwlr_layer_surface_v1::ZwlrLayerSurfaceV1,
1226 event: <zwlr_layer_surface_v1::ZwlrLayerSurfaceV1 as Proxy>::Event,
1227 surface_id: &ObjectId,
1228 _: &Connection,
1229 _: &QueueHandle<Self>,
1230 ) {
1231 let client = this.get_client();
1232 let mut state = client.borrow_mut();
1233 let Some(window) = get_window(&mut state, surface_id) else {
1234 return;
1235 };
1236
1237 drop(state);
1238 let should_close = window.handle_layersurface_event(event);
1239
1240 if should_close {
1241 // The close logic will be handled in drop_window()
1242 window.close();
1243 }
1244 }
1245}
1246
1247impl Dispatch<xdg_wm_base::XdgWmBase, ()> for WaylandClientStatePtr {
1248 fn event(
1249 _: &mut Self,
1250 wm_base: &xdg_wm_base::XdgWmBase,
1251 event: <xdg_wm_base::XdgWmBase as Proxy>::Event,
1252 _: &(),
1253 _: &Connection,
1254 _: &QueueHandle<Self>,
1255 ) {
1256 if let xdg_wm_base::Event::Ping { serial } = event {
1257 wm_base.pong(serial);
1258 }
1259 }
1260}
1261
1262impl Dispatch<xdg_activation_token_v1::XdgActivationTokenV1, ()> for WaylandClientStatePtr {
1263 fn event(
1264 this: &mut Self,
1265 token: &xdg_activation_token_v1::XdgActivationTokenV1,
1266 event: <xdg_activation_token_v1::XdgActivationTokenV1 as Proxy>::Event,
1267 _: &(),
1268 _: &Connection,
1269 _: &QueueHandle<Self>,
1270 ) {
1271 let client = this.get_client();
1272 let mut state = client.borrow_mut();
1273
1274 if let xdg_activation_token_v1::Event::Done { token } = event {
1275 let executor = state.common.background_executor.clone();
1276 match state.pending_activation.take() {
1277 Some(PendingActivation::Uri(uri)) => open_uri_internal(executor, &uri, Some(token)),
1278 Some(PendingActivation::Path(path)) => {
1279 reveal_path_internal(executor, path, Some(token))
1280 }
1281 Some(PendingActivation::Window(window)) => {
1282 let Some(window) = get_window(&mut state, &window) else {
1283 return;
1284 };
1285 let activation = state.globals.activation.as_ref().unwrap();
1286 activation.activate(token, &window.surface());
1287 }
1288 None => log::error!("activation token received with no pending activation"),
1289 }
1290 }
1291
1292 token.destroy();
1293 }
1294}
1295
1296impl Dispatch<wl_seat::WlSeat, ()> for WaylandClientStatePtr {
1297 fn event(
1298 state: &mut Self,
1299 seat: &wl_seat::WlSeat,
1300 event: wl_seat::Event,
1301 _: &(),
1302 _: &Connection,
1303 qh: &QueueHandle<Self>,
1304 ) {
1305 if let wl_seat::Event::Capabilities {
1306 capabilities: WEnum::Value(capabilities),
1307 } = event
1308 {
1309 let client = state.get_client();
1310 let mut state = client.borrow_mut();
1311 if capabilities.contains(wl_seat::Capability::Keyboard) {
1312 let keyboard = seat.get_keyboard(qh, ());
1313
1314 if let Some(text_input) = state.text_input.take() {
1315 text_input.destroy();
1316 state.ime_pre_edit = None;
1317 state.composing = false;
1318 }
1319
1320 state.text_input = state
1321 .globals
1322 .text_input_manager
1323 .as_ref()
1324 .map(|text_input_manager| text_input_manager.get_text_input(seat, qh, ()));
1325
1326 if let Some(wl_keyboard) = &state.wl_keyboard {
1327 wl_keyboard.release();
1328 }
1329
1330 state.wl_keyboard = Some(keyboard);
1331 }
1332 if capabilities.contains(wl_seat::Capability::Pointer) {
1333 let pointer = seat.get_pointer(qh, ());
1334
1335 if let Some(cursor_shape_device) = state.cursor_shape_device.take() {
1336 cursor_shape_device.destroy();
1337 }
1338
1339 state.cursor_shape_device = state
1340 .globals
1341 .cursor_shape_manager
1342 .as_ref()
1343 .map(|cursor_shape_manager| cursor_shape_manager.get_pointer(&pointer, qh, ()));
1344
1345 state.pinch_gesture = state.globals.gesture_manager.as_ref().map(
1346 |gesture_manager: &zwp_pointer_gestures_v1::ZwpPointerGesturesV1| {
1347 gesture_manager.get_pinch_gesture(&pointer, qh, ())
1348 },
1349 );
1350
1351 if let Some(wl_pointer) = &state.wl_pointer {
1352 wl_pointer.release();
1353 }
1354
1355 state.wl_pointer = Some(pointer);
1356 }
1357 }
1358 }
1359}
1360
1361impl Dispatch<wl_keyboard::WlKeyboard, ()> for WaylandClientStatePtr {
1362 fn event(
1363 this: &mut Self,
1364 _: &wl_keyboard::WlKeyboard,
1365 event: wl_keyboard::Event,
1366 _: &(),
1367 _: &Connection,
1368 _: &QueueHandle<Self>,
1369 ) {
1370 let client = this.get_client();
1371 let mut state = client.borrow_mut();
1372 match event {
1373 wl_keyboard::Event::RepeatInfo { rate, delay } => {
1374 state.repeat.characters_per_second = rate as u32;
1375 state.repeat.delay = Duration::from_millis(delay as u64);
1376 }
1377 wl_keyboard::Event::Keymap {
1378 format: WEnum::Value(format),
1379 fd,
1380 size,
1381 ..
1382 } => {
1383 if format != wl_keyboard::KeymapFormat::XkbV1 {
1384 log::error!("Received keymap format {:?}, expected XkbV1", format);
1385 return;
1386 }
1387 let xkb_context = xkb::Context::new(xkb::CONTEXT_NO_FLAGS);
1388 let keymap = unsafe {
1389 xkb::Keymap::new_from_fd(
1390 &xkb_context,
1391 fd,
1392 size as usize,
1393 XKB_KEYMAP_FORMAT_TEXT_V1,
1394 KEYMAP_COMPILE_NO_FLAGS,
1395 )
1396 .log_err()
1397 .flatten()
1398 .expect("Failed to create keymap")
1399 };
1400 state.keymap_state = Some(xkb::State::new(&keymap));
1401 state.compose_state = get_xkb_compose_state(&xkb_context);
1402 drop(state);
1403
1404 this.handle_keyboard_layout_change();
1405 }
1406 wl_keyboard::Event::Enter { surface, .. } => {
1407 state.keyboard_focused_window = get_window(&mut state, &surface.id());
1408 state.enter_token = Some(());
1409
1410 if let Some(window) = state.keyboard_focused_window.clone() {
1411 drop(state);
1412 window.set_focused(true);
1413 }
1414 }
1415 wl_keyboard::Event::Leave { surface, .. } => {
1416 let keyboard_focused_window = get_window(&mut state, &surface.id());
1417 state.keyboard_focused_window = None;
1418 state.enter_token.take();
1419 // Prevent keyboard events from repeating after opening e.g. a file chooser and closing it quickly
1420 state.repeat.current_id += 1;
1421
1422 if let Some(window) = keyboard_focused_window {
1423 if let Some(ref mut compose) = state.compose_state {
1424 compose.reset();
1425 }
1426 state.pre_edit_text.take();
1427 drop(state);
1428 window.handle_ime(ImeInput::DeleteText);
1429 window.set_focused(false);
1430 }
1431 }
1432 wl_keyboard::Event::Modifiers {
1433 mods_depressed,
1434 mods_latched,
1435 mods_locked,
1436 group,
1437 ..
1438 } => {
1439 let focused_window = state.keyboard_focused_window.clone();
1440
1441 let keymap_state = state.keymap_state.as_mut().unwrap();
1442 let old_layout =
1443 keymap_state.serialize_layout(xkbcommon::xkb::STATE_LAYOUT_EFFECTIVE);
1444 keymap_state.update_mask(mods_depressed, mods_latched, mods_locked, 0, 0, group);
1445 state.modifiers = modifiers_from_xkb(keymap_state);
1446 let keymap_state = state.keymap_state.as_mut().unwrap();
1447 state.capslock = capslock_from_xkb(keymap_state);
1448
1449 let input = PlatformInput::ModifiersChanged(ModifiersChangedEvent {
1450 modifiers: state.modifiers,
1451 capslock: state.capslock,
1452 });
1453 drop(state);
1454
1455 if let Some(focused_window) = focused_window {
1456 focused_window.handle_input(input);
1457 }
1458
1459 if group != old_layout {
1460 this.handle_keyboard_layout_change();
1461 }
1462 }
1463 wl_keyboard::Event::Key {
1464 serial,
1465 key,
1466 state: WEnum::Value(key_state),
1467 ..
1468 } => {
1469 state.serial_tracker.update(SerialKind::KeyPress, serial);
1470
1471 let focused_window = state.keyboard_focused_window.clone();
1472 let Some(focused_window) = focused_window else {
1473 return;
1474 };
1475
1476 let keymap_state = state.keymap_state.as_ref().unwrap();
1477 let keycode = Keycode::from(key + MIN_KEYCODE);
1478 let keysym = keymap_state.key_get_one_sym(keycode);
1479
1480 match key_state {
1481 wl_keyboard::KeyState::Pressed if !keysym.is_modifier_key() => {
1482 let mut keystroke =
1483 keystroke_from_xkb(keymap_state, state.modifiers, keycode);
1484 if let Some(mut compose) = state.compose_state.take() {
1485 compose.feed(keysym);
1486 match compose.status() {
1487 xkb::Status::Composing => {
1488 keystroke.key_char = None;
1489 state.pre_edit_text =
1490 compose.utf8().or(keystroke_underlying_dead_key(keysym));
1491 let pre_edit =
1492 state.pre_edit_text.clone().unwrap_or(String::default());
1493 drop(state);
1494 focused_window.handle_ime(ImeInput::SetMarkedText(pre_edit));
1495 state = client.borrow_mut();
1496 }
1497
1498 xkb::Status::Composed => {
1499 state.pre_edit_text.take();
1500 keystroke.key_char = compose.utf8();
1501 if let Some(keysym) = compose.keysym() {
1502 keystroke.key = xkb::keysym_get_name(keysym);
1503 }
1504 }
1505 xkb::Status::Cancelled => {
1506 let pre_edit = state.pre_edit_text.take();
1507 let new_pre_edit = keystroke_underlying_dead_key(keysym);
1508 state.pre_edit_text = new_pre_edit.clone();
1509 drop(state);
1510 if let Some(pre_edit) = pre_edit {
1511 focused_window.handle_ime(ImeInput::InsertText(pre_edit));
1512 }
1513 if let Some(current_key) = new_pre_edit {
1514 focused_window
1515 .handle_ime(ImeInput::SetMarkedText(current_key));
1516 }
1517 compose.feed(keysym);
1518 state = client.borrow_mut();
1519 }
1520 _ => {}
1521 }
1522 state.compose_state = Some(compose);
1523 }
1524 let input = PlatformInput::KeyDown(KeyDownEvent {
1525 keystroke: keystroke.clone(),
1526 is_held: false,
1527 prefer_character_input: false,
1528 });
1529
1530 state.repeat.current_id += 1;
1531 state.repeat.current_keycode = Some(keycode);
1532
1533 let rate = state.repeat.characters_per_second;
1534 let repeat_interval = Duration::from_secs(1) / rate.max(1);
1535 let id = state.repeat.current_id;
1536 state
1537 .loop_handle
1538 .insert_source(Timer::from_duration(state.repeat.delay), {
1539 let input = PlatformInput::KeyDown(KeyDownEvent {
1540 keystroke,
1541 is_held: true,
1542 prefer_character_input: false,
1543 });
1544 move |event_timestamp, _metadata, this| {
1545 let client = this.get_client();
1546 let state = client.borrow();
1547 let is_repeating = id == state.repeat.current_id
1548 && state.repeat.current_keycode.is_some()
1549 && state.keyboard_focused_window.is_some();
1550
1551 if !is_repeating || rate == 0 {
1552 return TimeoutAction::Drop;
1553 }
1554
1555 let focused_window =
1556 state.keyboard_focused_window.as_ref().unwrap().clone();
1557
1558 drop(state);
1559 focused_window.handle_input(input.clone());
1560
1561 // If the new scheduled time is in the past the event will repeat as soon as possible
1562 TimeoutAction::ToInstant(event_timestamp + repeat_interval)
1563 }
1564 })
1565 .unwrap();
1566
1567 drop(state);
1568 focused_window.handle_input(input);
1569 }
1570 wl_keyboard::KeyState::Released if !keysym.is_modifier_key() => {
1571 let input = PlatformInput::KeyUp(KeyUpEvent {
1572 keystroke: keystroke_from_xkb(keymap_state, state.modifiers, keycode),
1573 });
1574
1575 if state.repeat.current_keycode == Some(keycode) {
1576 state.repeat.current_keycode = None;
1577 }
1578
1579 drop(state);
1580 focused_window.handle_input(input);
1581 }
1582 _ => {}
1583 }
1584 }
1585 _ => {}
1586 }
1587 }
1588}
1589
1590impl Dispatch<zwp_text_input_v3::ZwpTextInputV3, ()> for WaylandClientStatePtr {
1591 fn event(
1592 this: &mut Self,
1593 text_input: &zwp_text_input_v3::ZwpTextInputV3,
1594 event: <zwp_text_input_v3::ZwpTextInputV3 as Proxy>::Event,
1595 _: &(),
1596 _: &Connection,
1597 _: &QueueHandle<Self>,
1598 ) {
1599 let client = this.get_client();
1600 let mut state = client.borrow_mut();
1601 match event {
1602 zwp_text_input_v3::Event::Enter { .. } => {
1603 drop(state);
1604 this.enable_ime();
1605 }
1606 zwp_text_input_v3::Event::Leave { .. } => {
1607 drop(state);
1608 this.disable_ime();
1609 }
1610 zwp_text_input_v3::Event::CommitString { text } => {
1611 state.composing = false;
1612 let Some(window) = state.keyboard_focused_window.clone() else {
1613 return;
1614 };
1615
1616 if let Some(commit_text) = text {
1617 drop(state);
1618 // IBus Intercepts keys like `a`, `b`, but those keys are needed for vim mode.
1619 // We should only send ASCII characters to Zed, otherwise a user could remap a letter like `か` or `相`.
1620 if commit_text.len() == 1 {
1621 window.handle_input(PlatformInput::KeyDown(KeyDownEvent {
1622 keystroke: Keystroke {
1623 modifiers: Modifiers::default(),
1624 key: commit_text.clone(),
1625 key_char: Some(commit_text),
1626 },
1627 is_held: false,
1628 prefer_character_input: false,
1629 }));
1630 } else {
1631 window.handle_ime(ImeInput::InsertText(commit_text));
1632 }
1633 }
1634 }
1635 zwp_text_input_v3::Event::PreeditString { text, .. } => {
1636 state.composing = true;
1637 state.ime_pre_edit = text;
1638 }
1639 zwp_text_input_v3::Event::Done { serial } => {
1640 let last_serial = state.serial_tracker.get(SerialKind::InputMethod);
1641 state.serial_tracker.update(SerialKind::InputMethod, serial);
1642 let Some(window) = state.keyboard_focused_window.clone() else {
1643 return;
1644 };
1645
1646 if let Some(text) = state.ime_pre_edit.take() {
1647 drop(state);
1648 window.handle_ime(ImeInput::SetMarkedText(text));
1649 if let Some(area) = window.get_ime_area() {
1650 text_input.set_cursor_rectangle(
1651 f32::from(area.origin.x) as i32,
1652 f32::from(area.origin.y) as i32,
1653 f32::from(area.size.width) as i32,
1654 f32::from(area.size.height) as i32,
1655 );
1656 if last_serial == serial {
1657 text_input.commit();
1658 }
1659 }
1660 } else {
1661 state.composing = false;
1662 drop(state);
1663 window.handle_ime(ImeInput::DeleteText);
1664 }
1665 }
1666 _ => {}
1667 }
1668 }
1669}
1670
1671fn linux_button_to_gpui(button: u32) -> Option<MouseButton> {
1672 // These values are coming from <linux/input-event-codes.h>.
1673 const BTN_LEFT: u32 = 0x110;
1674 const BTN_RIGHT: u32 = 0x111;
1675 const BTN_MIDDLE: u32 = 0x112;
1676 const BTN_SIDE: u32 = 0x113;
1677 const BTN_EXTRA: u32 = 0x114;
1678 const BTN_FORWARD: u32 = 0x115;
1679 const BTN_BACK: u32 = 0x116;
1680
1681 Some(match button {
1682 BTN_LEFT => MouseButton::Left,
1683 BTN_RIGHT => MouseButton::Right,
1684 BTN_MIDDLE => MouseButton::Middle,
1685 BTN_BACK | BTN_SIDE => MouseButton::Navigate(NavigationDirection::Back),
1686 BTN_FORWARD | BTN_EXTRA => MouseButton::Navigate(NavigationDirection::Forward),
1687 _ => return None,
1688 })
1689}
1690
1691impl Dispatch<wl_pointer::WlPointer, ()> for WaylandClientStatePtr {
1692 fn event(
1693 this: &mut Self,
1694 wl_pointer: &wl_pointer::WlPointer,
1695 event: wl_pointer::Event,
1696 _: &(),
1697 _: &Connection,
1698 _: &QueueHandle<Self>,
1699 ) {
1700 let client = this.get_client();
1701 let mut state = client.borrow_mut();
1702
1703 match event {
1704 wl_pointer::Event::Enter {
1705 serial,
1706 surface,
1707 surface_x,
1708 surface_y,
1709 ..
1710 } => {
1711 state.serial_tracker.update(SerialKind::MouseEnter, serial);
1712 state.mouse_location = Some(point(px(surface_x as f32), px(surface_y as f32)));
1713 state.button_pressed = None;
1714
1715 if let Some(window) = get_window(&mut state, &surface.id()) {
1716 state.mouse_focused_window = Some(window.clone());
1717
1718 if state.enter_token.is_some() {
1719 state.enter_token = None;
1720 }
1721 if let Some(style) = state.cursor_style {
1722 if let CursorStyle::None = style {
1723 let wl_pointer = state
1724 .wl_pointer
1725 .clone()
1726 .expect("window is focused by pointer");
1727 wl_pointer.set_cursor(serial, None, 0, 0);
1728 } else if let Some(cursor_shape_device) = &state.cursor_shape_device {
1729 cursor_shape_device.set_shape(serial, to_shape(style));
1730 } else {
1731 let scale = window.primary_output_scale();
1732 state.cursor.set_icon(
1733 wl_pointer,
1734 serial,
1735 cursor_style_to_icon_names(style),
1736 scale,
1737 );
1738 }
1739 }
1740 drop(state);
1741 window.set_hovered(true);
1742 }
1743 }
1744 wl_pointer::Event::Leave { .. } => {
1745 if let Some(focused_window) = state.mouse_focused_window.clone() {
1746 let input = PlatformInput::MouseExited(MouseExitEvent {
1747 position: state.mouse_location.unwrap(),
1748 pressed_button: state.button_pressed,
1749 modifiers: state.modifiers,
1750 });
1751 state.mouse_focused_window = None;
1752 state.mouse_location = None;
1753 state.button_pressed = None;
1754
1755 drop(state);
1756 focused_window.handle_input(input);
1757 focused_window.set_hovered(false);
1758 }
1759 }
1760 wl_pointer::Event::Motion {
1761 surface_x,
1762 surface_y,
1763 ..
1764 } => {
1765 if state.mouse_focused_window.is_none() {
1766 return;
1767 }
1768 state.mouse_location = Some(point(px(surface_x as f32), px(surface_y as f32)));
1769
1770 if let Some(window) = state.mouse_focused_window.clone() {
1771 if window.is_blocked() {
1772 let default_style = CursorStyle::Arrow;
1773 if state.cursor_style != Some(default_style) {
1774 let serial = state.serial_tracker.get(SerialKind::MouseEnter);
1775 state.cursor_style = Some(default_style);
1776
1777 if let Some(cursor_shape_device) = &state.cursor_shape_device {
1778 cursor_shape_device.set_shape(serial, to_shape(default_style));
1779 } else {
1780 // cursor-shape-v1 isn't supported, set the cursor using a surface.
1781 let wl_pointer = state
1782 .wl_pointer
1783 .clone()
1784 .expect("window is focused by pointer");
1785 let scale = window.primary_output_scale();
1786 state.cursor.set_icon(
1787 &wl_pointer,
1788 serial,
1789 cursor_style_to_icon_names(default_style),
1790 scale,
1791 );
1792 }
1793 }
1794 }
1795 if state
1796 .keyboard_focused_window
1797 .as_ref()
1798 .is_some_and(|keyboard_window| window.ptr_eq(keyboard_window))
1799 {
1800 state.enter_token = None;
1801 }
1802 let input = PlatformInput::MouseMove(MouseMoveEvent {
1803 position: state.mouse_location.unwrap(),
1804 pressed_button: state.button_pressed,
1805 modifiers: state.modifiers,
1806 });
1807 drop(state);
1808 window.handle_input(input);
1809 }
1810 }
1811 wl_pointer::Event::Button {
1812 serial,
1813 button,
1814 state: WEnum::Value(button_state),
1815 ..
1816 } => {
1817 state.serial_tracker.update(SerialKind::MousePress, serial);
1818 let button = linux_button_to_gpui(button);
1819 let Some(button) = button else { return };
1820 if state.mouse_focused_window.is_none() {
1821 return;
1822 }
1823 match button_state {
1824 wl_pointer::ButtonState::Pressed => {
1825 if let Some(window) = state.keyboard_focused_window.clone() {
1826 if state.composing && state.text_input.is_some() {
1827 drop(state);
1828 // text_input_v3 don't have something like a reset function
1829 this.disable_ime();
1830 this.enable_ime();
1831 window.handle_ime(ImeInput::UnmarkText);
1832 state = client.borrow_mut();
1833 } else if let (Some(text), Some(compose)) =
1834 (state.pre_edit_text.take(), state.compose_state.as_mut())
1835 {
1836 compose.reset();
1837 drop(state);
1838 window.handle_ime(ImeInput::InsertText(text));
1839 state = client.borrow_mut();
1840 }
1841 }
1842 let click_elapsed = state.click.last_click.elapsed();
1843
1844 if click_elapsed < DOUBLE_CLICK_INTERVAL
1845 && state
1846 .click
1847 .last_mouse_button
1848 .is_some_and(|prev_button| prev_button == button)
1849 && is_within_click_distance(
1850 state.click.last_location,
1851 state.mouse_location.unwrap(),
1852 )
1853 {
1854 state.click.current_count += 1;
1855 } else {
1856 state.click.current_count = 1;
1857 }
1858
1859 state.click.last_click = Instant::now();
1860 state.click.last_mouse_button = Some(button);
1861 state.click.last_location = state.mouse_location.unwrap();
1862
1863 state.button_pressed = Some(button);
1864
1865 if let Some(window) = state.mouse_focused_window.clone() {
1866 let input = PlatformInput::MouseDown(MouseDownEvent {
1867 button,
1868 position: state.mouse_location.unwrap(),
1869 modifiers: state.modifiers,
1870 click_count: state.click.current_count,
1871 first_mouse: state.enter_token.take().is_some(),
1872 });
1873 drop(state);
1874 window.handle_input(input);
1875 }
1876 }
1877 wl_pointer::ButtonState::Released => {
1878 state.button_pressed = None;
1879
1880 if let Some(window) = state.mouse_focused_window.clone() {
1881 let input = PlatformInput::MouseUp(MouseUpEvent {
1882 button,
1883 position: state.mouse_location.unwrap(),
1884 modifiers: state.modifiers,
1885 click_count: state.click.current_count,
1886 });
1887 drop(state);
1888 window.handle_input(input);
1889 }
1890 }
1891 _ => {}
1892 }
1893 }
1894
1895 // Axis Events
1896 wl_pointer::Event::AxisSource {
1897 axis_source: WEnum::Value(axis_source),
1898 } => {
1899 state.axis_source = axis_source;
1900 }
1901 wl_pointer::Event::Axis {
1902 axis: WEnum::Value(axis),
1903 value,
1904 ..
1905 } => {
1906 if state.axis_source == AxisSource::Wheel {
1907 return;
1908 }
1909 let axis = if state.modifiers.shift {
1910 wl_pointer::Axis::HorizontalScroll
1911 } else {
1912 axis
1913 };
1914 let axis_modifier = match axis {
1915 wl_pointer::Axis::VerticalScroll => state.vertical_modifier,
1916 wl_pointer::Axis::HorizontalScroll => state.horizontal_modifier,
1917 _ => 1.0,
1918 };
1919 state.scroll_event_received = true;
1920 let scroll_delta = state
1921 .continuous_scroll_delta
1922 .get_or_insert(point(px(0.0), px(0.0)));
1923 let modifier = 3.0;
1924 match axis {
1925 wl_pointer::Axis::VerticalScroll => {
1926 scroll_delta.y += px(value as f32 * modifier * axis_modifier);
1927 }
1928 wl_pointer::Axis::HorizontalScroll => {
1929 scroll_delta.x += px(value as f32 * modifier * axis_modifier);
1930 }
1931 _ => unreachable!(),
1932 }
1933 }
1934 wl_pointer::Event::AxisDiscrete {
1935 axis: WEnum::Value(axis),
1936 discrete,
1937 } => {
1938 state.scroll_event_received = true;
1939 let axis = if state.modifiers.shift {
1940 wl_pointer::Axis::HorizontalScroll
1941 } else {
1942 axis
1943 };
1944 let axis_modifier = match axis {
1945 wl_pointer::Axis::VerticalScroll => state.vertical_modifier,
1946 wl_pointer::Axis::HorizontalScroll => state.horizontal_modifier,
1947 _ => 1.0,
1948 };
1949
1950 let scroll_delta = state.discrete_scroll_delta.get_or_insert(point(0.0, 0.0));
1951 match axis {
1952 wl_pointer::Axis::VerticalScroll => {
1953 scroll_delta.y += discrete as f32 * axis_modifier * SCROLL_LINES;
1954 }
1955 wl_pointer::Axis::HorizontalScroll => {
1956 scroll_delta.x += discrete as f32 * axis_modifier * SCROLL_LINES;
1957 }
1958 _ => unreachable!(),
1959 }
1960 }
1961 wl_pointer::Event::AxisValue120 {
1962 axis: WEnum::Value(axis),
1963 value120,
1964 } => {
1965 state.scroll_event_received = true;
1966 let axis = if state.modifiers.shift {
1967 wl_pointer::Axis::HorizontalScroll
1968 } else {
1969 axis
1970 };
1971 let axis_modifier = match axis {
1972 wl_pointer::Axis::VerticalScroll => state.vertical_modifier,
1973 wl_pointer::Axis::HorizontalScroll => state.horizontal_modifier,
1974 _ => unreachable!(),
1975 };
1976
1977 let scroll_delta = state.discrete_scroll_delta.get_or_insert(point(0.0, 0.0));
1978 let wheel_percent = value120 as f32 / 120.0;
1979 match axis {
1980 wl_pointer::Axis::VerticalScroll => {
1981 scroll_delta.y += wheel_percent * axis_modifier * SCROLL_LINES;
1982 }
1983 wl_pointer::Axis::HorizontalScroll => {
1984 scroll_delta.x += wheel_percent * axis_modifier * SCROLL_LINES;
1985 }
1986 _ => unreachable!(),
1987 }
1988 }
1989 wl_pointer::Event::Frame => {
1990 if state.scroll_event_received {
1991 state.scroll_event_received = false;
1992 let continuous = state.continuous_scroll_delta.take();
1993 let discrete = state.discrete_scroll_delta.take();
1994 if let Some(continuous) = continuous {
1995 if let Some(window) = state.mouse_focused_window.clone() {
1996 let input = PlatformInput::ScrollWheel(ScrollWheelEvent {
1997 position: state.mouse_location.unwrap(),
1998 delta: ScrollDelta::Pixels(continuous),
1999 modifiers: state.modifiers,
2000 touch_phase: TouchPhase::Moved,
2001 });
2002 drop(state);
2003 window.handle_input(input);
2004 }
2005 } else if let Some(discrete) = discrete
2006 && let Some(window) = state.mouse_focused_window.clone()
2007 {
2008 let input = PlatformInput::ScrollWheel(ScrollWheelEvent {
2009 position: state.mouse_location.unwrap(),
2010 delta: ScrollDelta::Lines(discrete),
2011 modifiers: state.modifiers,
2012 touch_phase: TouchPhase::Moved,
2013 });
2014 drop(state);
2015 window.handle_input(input);
2016 }
2017 }
2018 }
2019 _ => {}
2020 }
2021 }
2022}
2023
2024impl Dispatch<zwp_pointer_gestures_v1::ZwpPointerGesturesV1, ()> for WaylandClientStatePtr {
2025 fn event(
2026 _this: &mut Self,
2027 _: &zwp_pointer_gestures_v1::ZwpPointerGesturesV1,
2028 _: <zwp_pointer_gestures_v1::ZwpPointerGesturesV1 as Proxy>::Event,
2029 _: &(),
2030 _: &Connection,
2031 _: &QueueHandle<Self>,
2032 ) {
2033 // The gesture manager doesn't generate events
2034 }
2035}
2036
2037impl Dispatch<zwp_pointer_gesture_pinch_v1::ZwpPointerGesturePinchV1, ()>
2038 for WaylandClientStatePtr
2039{
2040 fn event(
2041 this: &mut Self,
2042 _: &zwp_pointer_gesture_pinch_v1::ZwpPointerGesturePinchV1,
2043 event: <zwp_pointer_gesture_pinch_v1::ZwpPointerGesturePinchV1 as Proxy>::Event,
2044 _: &(),
2045 _: &Connection,
2046 _: &QueueHandle<Self>,
2047 ) {
2048 use gpui::PinchEvent;
2049
2050 let client = this.get_client();
2051 let mut state = client.borrow_mut();
2052
2053 let Some(window) = state.mouse_focused_window.clone() else {
2054 return;
2055 };
2056
2057 match event {
2058 zwp_pointer_gesture_pinch_v1::Event::Begin {
2059 serial: _,
2060 time: _,
2061 surface: _,
2062 fingers: _,
2063 } => {
2064 state.pinch_scale = 1.0;
2065 let input = PlatformInput::Pinch(PinchEvent {
2066 position: state.mouse_location.unwrap_or(point(px(0.0), px(0.0))),
2067 delta: 0.0,
2068 modifiers: state.modifiers,
2069 phase: TouchPhase::Started,
2070 });
2071 drop(state);
2072 window.handle_input(input);
2073 }
2074 zwp_pointer_gesture_pinch_v1::Event::Update { time: _, scale, .. } => {
2075 let new_absolute_scale = scale as f32;
2076 let previous_scale = state.pinch_scale;
2077 let zoom_delta = new_absolute_scale - previous_scale;
2078 state.pinch_scale = new_absolute_scale;
2079
2080 let input = PlatformInput::Pinch(PinchEvent {
2081 position: state.mouse_location.unwrap_or(point(px(0.0), px(0.0))),
2082 delta: zoom_delta,
2083 modifiers: state.modifiers,
2084 phase: TouchPhase::Moved,
2085 });
2086 drop(state);
2087 window.handle_input(input);
2088 }
2089 zwp_pointer_gesture_pinch_v1::Event::End {
2090 serial: _,
2091 time: _,
2092 cancelled: _,
2093 } => {
2094 state.pinch_scale = 1.0;
2095 let input = PlatformInput::Pinch(PinchEvent {
2096 position: state.mouse_location.unwrap_or(point(px(0.0), px(0.0))),
2097 delta: 0.0,
2098 modifiers: state.modifiers,
2099 phase: TouchPhase::Ended,
2100 });
2101 drop(state);
2102 window.handle_input(input);
2103 }
2104 _ => {}
2105 }
2106 }
2107}
2108
2109impl Dispatch<wp_fractional_scale_v1::WpFractionalScaleV1, ObjectId> for WaylandClientStatePtr {
2110 fn event(
2111 this: &mut Self,
2112 _: &wp_fractional_scale_v1::WpFractionalScaleV1,
2113 event: <wp_fractional_scale_v1::WpFractionalScaleV1 as Proxy>::Event,
2114 surface_id: &ObjectId,
2115 _: &Connection,
2116 _: &QueueHandle<Self>,
2117 ) {
2118 let client = this.get_client();
2119 let mut state = client.borrow_mut();
2120
2121 let Some(window) = get_window(&mut state, surface_id) else {
2122 return;
2123 };
2124
2125 drop(state);
2126 window.handle_fractional_scale_event(event);
2127 }
2128}
2129
2130impl Dispatch<zxdg_toplevel_decoration_v1::ZxdgToplevelDecorationV1, ObjectId>
2131 for WaylandClientStatePtr
2132{
2133 fn event(
2134 this: &mut Self,
2135 _: &zxdg_toplevel_decoration_v1::ZxdgToplevelDecorationV1,
2136 event: zxdg_toplevel_decoration_v1::Event,
2137 surface_id: &ObjectId,
2138 _: &Connection,
2139 _: &QueueHandle<Self>,
2140 ) {
2141 let client = this.get_client();
2142 let mut state = client.borrow_mut();
2143 let Some(window) = get_window(&mut state, surface_id) else {
2144 return;
2145 };
2146
2147 drop(state);
2148 window.handle_toplevel_decoration_event(event);
2149 }
2150}
2151
2152impl Dispatch<wl_data_device::WlDataDevice, ()> for WaylandClientStatePtr {
2153 fn event(
2154 this: &mut Self,
2155 _: &wl_data_device::WlDataDevice,
2156 event: wl_data_device::Event,
2157 _: &(),
2158 _: &Connection,
2159 _: &QueueHandle<Self>,
2160 ) {
2161 let client = this.get_client();
2162 let mut state = client.borrow_mut();
2163
2164 match event {
2165 // Clipboard
2166 wl_data_device::Event::DataOffer { id: data_offer } => {
2167 state.data_offers.push(DataOffer::new(data_offer));
2168 if state.data_offers.len() > 2 {
2169 // At most we store a clipboard offer and a drag and drop offer.
2170 state.data_offers.remove(0).inner.destroy();
2171 }
2172 }
2173 wl_data_device::Event::Selection { id: data_offer } => {
2174 if let Some(offer) = data_offer {
2175 let offer = state
2176 .data_offers
2177 .iter()
2178 .find(|wrapper| wrapper.inner.id() == offer.id());
2179 let offer = offer.cloned();
2180 state.clipboard.set_offer(offer);
2181 } else {
2182 state.clipboard.set_offer(None);
2183 }
2184 }
2185
2186 // Drag and drop
2187 wl_data_device::Event::Enter {
2188 serial,
2189 surface,
2190 x,
2191 y,
2192 id: data_offer,
2193 } => {
2194 state.serial_tracker.update(SerialKind::DataDevice, serial);
2195 if let Some(data_offer) = data_offer {
2196 let Some(drag_window) = get_window(&mut state, &surface.id()) else {
2197 return;
2198 };
2199
2200 const ACTIONS: DndAction = DndAction::Copy;
2201 data_offer.set_actions(ACTIONS, ACTIONS);
2202
2203 let pipe = Pipe::new().unwrap();
2204 data_offer.receive(FILE_LIST_MIME_TYPE.to_string(), unsafe {
2205 BorrowedFd::borrow_raw(pipe.write.as_raw_fd())
2206 });
2207 let fd = pipe.read;
2208 drop(pipe.write);
2209
2210 let read_task = state.common.background_executor.spawn(async {
2211 let buffer = unsafe { read_fd(fd)? };
2212 let text = String::from_utf8(buffer)?;
2213 anyhow::Ok(text)
2214 });
2215
2216 let this = this.clone();
2217 state
2218 .common
2219 .foreground_executor
2220 .spawn(async move {
2221 let file_list = match read_task.await {
2222 Ok(list) => list,
2223 Err(err) => {
2224 log::error!("error reading drag and drop pipe: {err:?}");
2225 return;
2226 }
2227 };
2228
2229 let paths: SmallVec<[_; 2]> = file_list
2230 .lines()
2231 .filter_map(|path| Url::parse(path).log_err())
2232 .filter_map(|url| url.to_file_path().log_err())
2233 .collect();
2234 let position = Point::new(x.into(), y.into());
2235
2236 // Prevent dropping text from other programs.
2237 if paths.is_empty() {
2238 data_offer.destroy();
2239 return;
2240 }
2241
2242 let input = PlatformInput::FileDrop(FileDropEvent::Entered {
2243 position,
2244 paths: gpui::ExternalPaths(paths),
2245 });
2246
2247 let client = this.get_client();
2248 let mut state = client.borrow_mut();
2249 state.drag.data_offer = Some(data_offer);
2250 state.drag.window = Some(drag_window.clone());
2251 state.drag.position = position;
2252
2253 drop(state);
2254 drag_window.handle_input(input);
2255 })
2256 .detach();
2257 }
2258 }
2259 wl_data_device::Event::Motion { x, y, .. } => {
2260 let Some(drag_window) = state.drag.window.clone() else {
2261 return;
2262 };
2263 let position = Point::new(x.into(), y.into());
2264 state.drag.position = position;
2265
2266 let input = PlatformInput::FileDrop(FileDropEvent::Pending { position });
2267 drop(state);
2268 drag_window.handle_input(input);
2269 }
2270 wl_data_device::Event::Leave => {
2271 let Some(drag_window) = state.drag.window.clone() else {
2272 return;
2273 };
2274 let data_offer = state.drag.data_offer.clone().unwrap();
2275 data_offer.destroy();
2276
2277 state.drag.data_offer = None;
2278 state.drag.window = None;
2279
2280 let input = PlatformInput::FileDrop(FileDropEvent::Exited {});
2281 drop(state);
2282 drag_window.handle_input(input);
2283 }
2284 wl_data_device::Event::Drop => {
2285 let Some(drag_window) = state.drag.window.clone() else {
2286 return;
2287 };
2288 let data_offer = state.drag.data_offer.clone().unwrap();
2289 data_offer.finish();
2290 data_offer.destroy();
2291
2292 state.drag.data_offer = None;
2293 state.drag.window = None;
2294
2295 let input = PlatformInput::FileDrop(FileDropEvent::Submit {
2296 position: state.drag.position,
2297 });
2298 drop(state);
2299 drag_window.handle_input(input);
2300 }
2301 _ => {}
2302 }
2303 }
2304
2305 event_created_child!(WaylandClientStatePtr, wl_data_device::WlDataDevice, [
2306 wl_data_device::EVT_DATA_OFFER_OPCODE => (wl_data_offer::WlDataOffer, ()),
2307 ]);
2308}
2309
2310impl Dispatch<wl_data_offer::WlDataOffer, ()> for WaylandClientStatePtr {
2311 fn event(
2312 this: &mut Self,
2313 data_offer: &wl_data_offer::WlDataOffer,
2314 event: wl_data_offer::Event,
2315 _: &(),
2316 _: &Connection,
2317 _: &QueueHandle<Self>,
2318 ) {
2319 let client = this.get_client();
2320 let mut state = client.borrow_mut();
2321
2322 if let wl_data_offer::Event::Offer { mime_type } = event {
2323 // Drag and drop
2324 if mime_type == FILE_LIST_MIME_TYPE {
2325 let serial = state.serial_tracker.get(SerialKind::DataDevice);
2326 let mime_type = mime_type.clone();
2327 data_offer.accept(serial, Some(mime_type));
2328 }
2329
2330 // Clipboard
2331 if let Some(offer) = state
2332 .data_offers
2333 .iter_mut()
2334 .find(|wrapper| wrapper.inner.id() == data_offer.id())
2335 {
2336 offer.add_mime_type(mime_type);
2337 }
2338 }
2339 }
2340}
2341
2342impl Dispatch<wl_data_source::WlDataSource, ()> for WaylandClientStatePtr {
2343 fn event(
2344 this: &mut Self,
2345 data_source: &wl_data_source::WlDataSource,
2346 event: wl_data_source::Event,
2347 _: &(),
2348 _: &Connection,
2349 _: &QueueHandle<Self>,
2350 ) {
2351 let client = this.get_client();
2352 let state = client.borrow_mut();
2353
2354 match event {
2355 wl_data_source::Event::Send { mime_type, fd } => {
2356 state.clipboard.send(mime_type, fd);
2357 }
2358 wl_data_source::Event::Cancelled => {
2359 data_source.destroy();
2360 }
2361 _ => {}
2362 }
2363 }
2364}
2365
2366impl Dispatch<zwp_primary_selection_device_v1::ZwpPrimarySelectionDeviceV1, ()>
2367 for WaylandClientStatePtr
2368{
2369 fn event(
2370 this: &mut Self,
2371 _: &zwp_primary_selection_device_v1::ZwpPrimarySelectionDeviceV1,
2372 event: zwp_primary_selection_device_v1::Event,
2373 _: &(),
2374 _: &Connection,
2375 _: &QueueHandle<Self>,
2376 ) {
2377 let client = this.get_client();
2378 let mut state = client.borrow_mut();
2379
2380 match event {
2381 zwp_primary_selection_device_v1::Event::DataOffer { offer } => {
2382 let old_offer = state.primary_data_offer.replace(DataOffer::new(offer));
2383 if let Some(old_offer) = old_offer {
2384 old_offer.inner.destroy();
2385 }
2386 }
2387 zwp_primary_selection_device_v1::Event::Selection { id: data_offer } => {
2388 if data_offer.is_some() {
2389 let offer = state.primary_data_offer.clone();
2390 state.clipboard.set_primary_offer(offer);
2391 } else {
2392 state.clipboard.set_primary_offer(None);
2393 }
2394 }
2395 _ => {}
2396 }
2397 }
2398
2399 event_created_child!(WaylandClientStatePtr, zwp_primary_selection_device_v1::ZwpPrimarySelectionDeviceV1, [
2400 zwp_primary_selection_device_v1::EVT_DATA_OFFER_OPCODE => (zwp_primary_selection_offer_v1::ZwpPrimarySelectionOfferV1, ()),
2401 ]);
2402}
2403
2404impl Dispatch<zwp_primary_selection_offer_v1::ZwpPrimarySelectionOfferV1, ()>
2405 for WaylandClientStatePtr
2406{
2407 fn event(
2408 this: &mut Self,
2409 _data_offer: &zwp_primary_selection_offer_v1::ZwpPrimarySelectionOfferV1,
2410 event: zwp_primary_selection_offer_v1::Event,
2411 _: &(),
2412 _: &Connection,
2413 _: &QueueHandle<Self>,
2414 ) {
2415 let client = this.get_client();
2416 let mut state = client.borrow_mut();
2417
2418 if let zwp_primary_selection_offer_v1::Event::Offer { mime_type } = event
2419 && let Some(offer) = state.primary_data_offer.as_mut()
2420 {
2421 offer.add_mime_type(mime_type);
2422 }
2423 }
2424}
2425
2426impl Dispatch<zwp_primary_selection_source_v1::ZwpPrimarySelectionSourceV1, ()>
2427 for WaylandClientStatePtr
2428{
2429 fn event(
2430 this: &mut Self,
2431 selection_source: &zwp_primary_selection_source_v1::ZwpPrimarySelectionSourceV1,
2432 event: zwp_primary_selection_source_v1::Event,
2433 _: &(),
2434 _: &Connection,
2435 _: &QueueHandle<Self>,
2436 ) {
2437 let client = this.get_client();
2438 let state = client.borrow_mut();
2439
2440 match event {
2441 zwp_primary_selection_source_v1::Event::Send { mime_type, fd } => {
2442 state.clipboard.send_primary(mime_type, fd);
2443 }
2444 zwp_primary_selection_source_v1::Event::Cancelled => {
2445 selection_source.destroy();
2446 }
2447 _ => {}
2448 }
2449 }
2450}
2451
2452impl Dispatch<XdgWmDialogV1, ()> for WaylandClientStatePtr {
2453 fn event(
2454 _: &mut Self,
2455 _: &XdgWmDialogV1,
2456 _: <XdgWmDialogV1 as Proxy>::Event,
2457 _: &(),
2458 _: &Connection,
2459 _: &QueueHandle<Self>,
2460 ) {
2461 }
2462}
2463
2464impl Dispatch<XdgDialogV1, ()> for WaylandClientStatePtr {
2465 fn event(
2466 _state: &mut Self,
2467 _proxy: &XdgDialogV1,
2468 _event: <XdgDialogV1 as Proxy>::Event,
2469 _data: &(),
2470 _conn: &Connection,
2471 _qhandle: &QueueHandle<Self>,
2472 ) {
2473 }
2474}