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