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