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