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