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 Some(cursor_shape_device) = &state.cursor_shape_device {
671 cursor_shape_device.set_shape(serial, style.to_shape());
672 } else if let Some(focused_window) = &state.mouse_focused_window {
673 // cursor-shape-v1 isn't supported, set the cursor using a surface.
674 let wl_pointer = state
675 .wl_pointer
676 .clone()
677 .expect("window is focused by pointer");
678 let scale = focused_window.primary_output_scale();
679 state
680 .cursor
681 .set_icon(&wl_pointer, serial, &style.to_icon_name(), scale);
682 }
683 }
684 }
685
686 fn open_uri(&self, uri: &str) {
687 let mut state = self.0.borrow_mut();
688 if let (Some(activation), Some(window)) = (
689 state.globals.activation.clone(),
690 state.mouse_focused_window.clone(),
691 ) {
692 state.pending_activation = Some(PendingActivation::Uri(uri.to_string()));
693 let token = activation.get_activation_token(&state.globals.qh, ());
694 let serial = state.serial_tracker.get(SerialKind::MousePress);
695 token.set_serial(serial, &state.wl_seat);
696 token.set_surface(&window.surface());
697 token.commit();
698 } else {
699 let executor = state.common.background_executor.clone();
700 open_uri_internal(executor, uri, None);
701 }
702 }
703
704 fn reveal_path(&self, path: PathBuf) {
705 let mut state = self.0.borrow_mut();
706 if let (Some(activation), Some(window)) = (
707 state.globals.activation.clone(),
708 state.mouse_focused_window.clone(),
709 ) {
710 state.pending_activation = Some(PendingActivation::Path(path));
711 let token = activation.get_activation_token(&state.globals.qh, ());
712 let serial = state.serial_tracker.get(SerialKind::MousePress);
713 token.set_serial(serial, &state.wl_seat);
714 token.set_surface(&window.surface());
715 token.commit();
716 } else {
717 let executor = state.common.background_executor.clone();
718 reveal_path_internal(executor, path, None);
719 }
720 }
721
722 fn with_common<R>(&self, f: impl FnOnce(&mut LinuxCommon) -> R) -> R {
723 f(&mut self.0.borrow_mut().common)
724 }
725
726 fn run(&self) {
727 let mut event_loop = self
728 .0
729 .borrow_mut()
730 .event_loop
731 .take()
732 .expect("App is already running");
733
734 event_loop
735 .run(
736 None,
737 &mut WaylandClientStatePtr(Rc::downgrade(&self.0)),
738 |_| {},
739 )
740 .log_err();
741 }
742
743 fn write_to_primary(&self, item: crate::ClipboardItem) {
744 let mut state = self.0.borrow_mut();
745 let (Some(primary_selection_manager), Some(primary_selection)) = (
746 state.globals.primary_selection_manager.clone(),
747 state.primary_selection.clone(),
748 ) else {
749 return;
750 };
751 if state.mouse_focused_window.is_some() || state.keyboard_focused_window.is_some() {
752 state.clipboard.set_primary(item);
753 let serial = state.serial_tracker.get(SerialKind::KeyPress);
754 let data_source = primary_selection_manager.create_source(&state.globals.qh, ());
755 data_source.offer(state.clipboard.self_mime());
756 data_source.offer(TEXT_MIME_TYPE.to_string());
757 primary_selection.set_selection(Some(&data_source), serial);
758 }
759 }
760
761 fn write_to_clipboard(&self, item: crate::ClipboardItem) {
762 let mut state = self.0.borrow_mut();
763 let (Some(data_device_manager), Some(data_device)) = (
764 state.globals.data_device_manager.clone(),
765 state.data_device.clone(),
766 ) else {
767 return;
768 };
769 if state.mouse_focused_window.is_some() || state.keyboard_focused_window.is_some() {
770 state.clipboard.set(item);
771 let serial = state.serial_tracker.get(SerialKind::KeyPress);
772 let data_source = data_device_manager.create_data_source(&state.globals.qh, ());
773 data_source.offer(state.clipboard.self_mime());
774 data_source.offer(TEXT_MIME_TYPE.to_string());
775 data_device.set_selection(Some(&data_source), serial);
776 }
777 }
778
779 fn read_from_primary(&self) -> Option<crate::ClipboardItem> {
780 self.0.borrow_mut().clipboard.read_primary()
781 }
782
783 fn read_from_clipboard(&self) -> Option<crate::ClipboardItem> {
784 self.0.borrow_mut().clipboard.read()
785 }
786
787 fn active_window(&self) -> Option<AnyWindowHandle> {
788 self.0
789 .borrow_mut()
790 .keyboard_focused_window
791 .as_ref()
792 .map(|window| window.handle())
793 }
794
795 fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
796 None
797 }
798
799 fn compositor_name(&self) -> &'static str {
800 "Wayland"
801 }
802}
803
804impl Dispatch<wl_registry::WlRegistry, GlobalListContents> for WaylandClientStatePtr {
805 fn event(
806 this: &mut Self,
807 registry: &wl_registry::WlRegistry,
808 event: wl_registry::Event,
809 _: &GlobalListContents,
810 _: &Connection,
811 qh: &QueueHandle<Self>,
812 ) {
813 let mut client = this.get_client();
814 let mut state = client.borrow_mut();
815
816 match event {
817 wl_registry::Event::Global {
818 name,
819 interface,
820 version,
821 } => match &interface[..] {
822 "wl_seat" => {
823 if let Some(wl_pointer) = state.wl_pointer.take() {
824 wl_pointer.release();
825 }
826 if let Some(wl_keyboard) = state.wl_keyboard.take() {
827 wl_keyboard.release();
828 }
829 state.wl_seat.release();
830 state.wl_seat = registry.bind::<wl_seat::WlSeat, _, _>(
831 name,
832 wl_seat_version(version),
833 qh,
834 (),
835 );
836 }
837 "wl_output" => {
838 let output = registry.bind::<wl_output::WlOutput, _, _>(
839 name,
840 wl_output_version(version),
841 qh,
842 (),
843 );
844
845 state
846 .in_progress_outputs
847 .insert(output.id(), InProgressOutput::default());
848 }
849 _ => {}
850 },
851 wl_registry::Event::GlobalRemove { name: _ } => {
852 // TODO: handle global removal
853 }
854 _ => {}
855 }
856 }
857}
858
859delegate_noop!(WaylandClientStatePtr: ignore xdg_activation_v1::XdgActivationV1);
860delegate_noop!(WaylandClientStatePtr: ignore wl_compositor::WlCompositor);
861delegate_noop!(WaylandClientStatePtr: ignore wp_cursor_shape_device_v1::WpCursorShapeDeviceV1);
862delegate_noop!(WaylandClientStatePtr: ignore wp_cursor_shape_manager_v1::WpCursorShapeManagerV1);
863delegate_noop!(WaylandClientStatePtr: ignore wl_data_device_manager::WlDataDeviceManager);
864delegate_noop!(WaylandClientStatePtr: ignore zwp_primary_selection_device_manager_v1::ZwpPrimarySelectionDeviceManagerV1);
865delegate_noop!(WaylandClientStatePtr: ignore wl_shm::WlShm);
866delegate_noop!(WaylandClientStatePtr: ignore wl_shm_pool::WlShmPool);
867delegate_noop!(WaylandClientStatePtr: ignore wl_buffer::WlBuffer);
868delegate_noop!(WaylandClientStatePtr: ignore wl_region::WlRegion);
869delegate_noop!(WaylandClientStatePtr: ignore wp_fractional_scale_manager_v1::WpFractionalScaleManagerV1);
870delegate_noop!(WaylandClientStatePtr: ignore zxdg_decoration_manager_v1::ZxdgDecorationManagerV1);
871delegate_noop!(WaylandClientStatePtr: ignore org_kde_kwin_blur_manager::OrgKdeKwinBlurManager);
872delegate_noop!(WaylandClientStatePtr: ignore zwp_text_input_manager_v3::ZwpTextInputManagerV3);
873delegate_noop!(WaylandClientStatePtr: ignore org_kde_kwin_blur::OrgKdeKwinBlur);
874delegate_noop!(WaylandClientStatePtr: ignore wp_viewporter::WpViewporter);
875delegate_noop!(WaylandClientStatePtr: ignore wp_viewport::WpViewport);
876
877impl Dispatch<WlCallback, ObjectId> for WaylandClientStatePtr {
878 fn event(
879 state: &mut WaylandClientStatePtr,
880 _: &wl_callback::WlCallback,
881 event: wl_callback::Event,
882 surface_id: &ObjectId,
883 _: &Connection,
884 _: &QueueHandle<Self>,
885 ) {
886 let client = state.get_client();
887 let mut state = client.borrow_mut();
888 let Some(window) = get_window(&mut state, surface_id) else {
889 return;
890 };
891 drop(state);
892
893 match event {
894 wl_callback::Event::Done { .. } => {
895 window.frame();
896 }
897 _ => {}
898 }
899 }
900}
901
902fn get_window(
903 mut state: &mut RefMut<WaylandClientState>,
904 surface_id: &ObjectId,
905) -> Option<WaylandWindowStatePtr> {
906 state.windows.get(surface_id).cloned()
907}
908
909impl Dispatch<wl_surface::WlSurface, ()> for WaylandClientStatePtr {
910 fn event(
911 this: &mut Self,
912 surface: &wl_surface::WlSurface,
913 event: <wl_surface::WlSurface as Proxy>::Event,
914 _: &(),
915 _: &Connection,
916 _: &QueueHandle<Self>,
917 ) {
918 let mut client = this.get_client();
919 let mut state = client.borrow_mut();
920
921 let Some(window) = get_window(&mut state, &surface.id()) else {
922 return;
923 };
924 #[allow(clippy::mutable_key_type)]
925 let outputs = state.outputs.clone();
926 drop(state);
927
928 window.handle_surface_event(event, outputs);
929 }
930}
931
932impl Dispatch<wl_output::WlOutput, ()> for WaylandClientStatePtr {
933 fn event(
934 this: &mut Self,
935 output: &wl_output::WlOutput,
936 event: <wl_output::WlOutput as Proxy>::Event,
937 _: &(),
938 _: &Connection,
939 _: &QueueHandle<Self>,
940 ) {
941 let mut client = this.get_client();
942 let mut state = client.borrow_mut();
943
944 let Some(mut in_progress_output) = state.in_progress_outputs.get_mut(&output.id()) else {
945 return;
946 };
947
948 match event {
949 wl_output::Event::Name { name } => {
950 in_progress_output.name = Some(name);
951 }
952 wl_output::Event::Scale { factor } => {
953 in_progress_output.scale = Some(factor);
954 }
955 wl_output::Event::Geometry { x, y, .. } => {
956 in_progress_output.position = Some(point(DevicePixels(x), DevicePixels(y)))
957 }
958 wl_output::Event::Mode { width, height, .. } => {
959 in_progress_output.size = Some(size(DevicePixels(width), DevicePixels(height)))
960 }
961 wl_output::Event::Done => {
962 if let Some(complete) = in_progress_output.complete() {
963 state.outputs.insert(output.id(), complete);
964 }
965 state.in_progress_outputs.remove(&output.id());
966 }
967 _ => {}
968 }
969 }
970}
971
972impl Dispatch<xdg_surface::XdgSurface, ObjectId> for WaylandClientStatePtr {
973 fn event(
974 state: &mut Self,
975 _: &xdg_surface::XdgSurface,
976 event: xdg_surface::Event,
977 surface_id: &ObjectId,
978 _: &Connection,
979 _: &QueueHandle<Self>,
980 ) {
981 let client = state.get_client();
982 let mut state = client.borrow_mut();
983 let Some(window) = get_window(&mut state, surface_id) else {
984 return;
985 };
986 drop(state);
987 window.handle_xdg_surface_event(event);
988 }
989}
990
991impl Dispatch<xdg_toplevel::XdgToplevel, ObjectId> for WaylandClientStatePtr {
992 fn event(
993 this: &mut Self,
994 _: &xdg_toplevel::XdgToplevel,
995 event: <xdg_toplevel::XdgToplevel as Proxy>::Event,
996 surface_id: &ObjectId,
997 _: &Connection,
998 _: &QueueHandle<Self>,
999 ) {
1000 let client = this.get_client();
1001 let mut state = client.borrow_mut();
1002 let Some(window) = get_window(&mut state, surface_id) else {
1003 return;
1004 };
1005
1006 drop(state);
1007 let should_close = window.handle_toplevel_event(event);
1008
1009 if should_close {
1010 // The close logic will be handled in drop_window()
1011 window.close();
1012 }
1013 }
1014}
1015
1016impl Dispatch<xdg_wm_base::XdgWmBase, ()> for WaylandClientStatePtr {
1017 fn event(
1018 _: &mut Self,
1019 wm_base: &xdg_wm_base::XdgWmBase,
1020 event: <xdg_wm_base::XdgWmBase as Proxy>::Event,
1021 _: &(),
1022 _: &Connection,
1023 _: &QueueHandle<Self>,
1024 ) {
1025 if let xdg_wm_base::Event::Ping { serial } = event {
1026 wm_base.pong(serial);
1027 }
1028 }
1029}
1030
1031impl Dispatch<xdg_activation_token_v1::XdgActivationTokenV1, ()> for WaylandClientStatePtr {
1032 fn event(
1033 this: &mut Self,
1034 token: &xdg_activation_token_v1::XdgActivationTokenV1,
1035 event: <xdg_activation_token_v1::XdgActivationTokenV1 as Proxy>::Event,
1036 _: &(),
1037 _: &Connection,
1038 _: &QueueHandle<Self>,
1039 ) {
1040 let client = this.get_client();
1041 let mut state = client.borrow_mut();
1042
1043 if let xdg_activation_token_v1::Event::Done { token } = event {
1044 let executor = state.common.background_executor.clone();
1045 match state.pending_activation.take() {
1046 Some(PendingActivation::Uri(uri)) => open_uri_internal(executor, &uri, Some(token)),
1047 Some(PendingActivation::Path(path)) => {
1048 reveal_path_internal(executor, path, Some(token))
1049 }
1050 Some(PendingActivation::Window(window)) => {
1051 let Some(window) = get_window(&mut state, &window) else {
1052 return;
1053 };
1054 let activation = state.globals.activation.as_ref().unwrap();
1055 activation.activate(token, &window.surface());
1056 }
1057 None => log::error!("activation token received with no pending activation"),
1058 }
1059 }
1060
1061 token.destroy();
1062 }
1063}
1064
1065impl Dispatch<wl_seat::WlSeat, ()> for WaylandClientStatePtr {
1066 fn event(
1067 state: &mut Self,
1068 seat: &wl_seat::WlSeat,
1069 event: wl_seat::Event,
1070 _: &(),
1071 _: &Connection,
1072 qh: &QueueHandle<Self>,
1073 ) {
1074 if let wl_seat::Event::Capabilities {
1075 capabilities: WEnum::Value(capabilities),
1076 } = event
1077 {
1078 let client = state.get_client();
1079 let mut state = client.borrow_mut();
1080 if capabilities.contains(wl_seat::Capability::Keyboard) {
1081 let keyboard = seat.get_keyboard(qh, ());
1082
1083 state.text_input = state
1084 .globals
1085 .text_input_manager
1086 .as_ref()
1087 .map(|text_input_manager| text_input_manager.get_text_input(&seat, qh, ()));
1088
1089 if let Some(wl_keyboard) = &state.wl_keyboard {
1090 wl_keyboard.release();
1091 }
1092
1093 state.wl_keyboard = Some(keyboard);
1094 }
1095 if capabilities.contains(wl_seat::Capability::Pointer) {
1096 let pointer = seat.get_pointer(qh, ());
1097 state.cursor_shape_device = state
1098 .globals
1099 .cursor_shape_manager
1100 .as_ref()
1101 .map(|cursor_shape_manager| cursor_shape_manager.get_pointer(&pointer, qh, ()));
1102
1103 if let Some(wl_pointer) = &state.wl_pointer {
1104 wl_pointer.release();
1105 }
1106
1107 state.wl_pointer = Some(pointer);
1108 }
1109 }
1110 }
1111}
1112
1113impl Dispatch<wl_keyboard::WlKeyboard, ()> for WaylandClientStatePtr {
1114 fn event(
1115 this: &mut Self,
1116 _: &wl_keyboard::WlKeyboard,
1117 event: wl_keyboard::Event,
1118 _: &(),
1119 _: &Connection,
1120 _: &QueueHandle<Self>,
1121 ) {
1122 let mut client = this.get_client();
1123 let mut state = client.borrow_mut();
1124 match event {
1125 wl_keyboard::Event::RepeatInfo { rate, delay } => {
1126 state.repeat.characters_per_second = rate as u32;
1127 state.repeat.delay = Duration::from_millis(delay as u64);
1128 }
1129 wl_keyboard::Event::Keymap {
1130 format: WEnum::Value(format),
1131 fd,
1132 size,
1133 ..
1134 } => {
1135 assert_eq!(
1136 format,
1137 wl_keyboard::KeymapFormat::XkbV1,
1138 "Unsupported keymap format"
1139 );
1140 let xkb_context = xkb::Context::new(xkb::CONTEXT_NO_FLAGS);
1141 let keymap = unsafe {
1142 xkb::Keymap::new_from_fd(
1143 &xkb_context,
1144 fd,
1145 size as usize,
1146 XKB_KEYMAP_FORMAT_TEXT_V1,
1147 KEYMAP_COMPILE_NO_FLAGS,
1148 )
1149 .log_err()
1150 .flatten()
1151 .expect("Failed to create keymap")
1152 };
1153 state.keymap_state = Some(xkb::State::new(&keymap));
1154 state.compose_state = get_xkb_compose_state(&xkb_context);
1155
1156 if let Some(mut callback) = state.common.callbacks.keyboard_layout_change.take() {
1157 drop(state);
1158 callback();
1159 state = client.borrow_mut();
1160 state.common.callbacks.keyboard_layout_change = Some(callback);
1161 }
1162 }
1163 wl_keyboard::Event::Enter { surface, .. } => {
1164 state.keyboard_focused_window = get_window(&mut state, &surface.id());
1165 state.enter_token = Some(());
1166
1167 if let Some(window) = state.keyboard_focused_window.clone() {
1168 drop(state);
1169 window.set_focused(true);
1170 }
1171 }
1172 wl_keyboard::Event::Leave { surface, .. } => {
1173 let keyboard_focused_window = get_window(&mut state, &surface.id());
1174 state.keyboard_focused_window = None;
1175 state.enter_token.take();
1176 // Prevent keyboard events from repeating after opening e.g. a file chooser and closing it quickly
1177 state.repeat.current_id += 1;
1178
1179 if let Some(window) = keyboard_focused_window {
1180 if let Some(ref mut compose) = state.compose_state {
1181 compose.reset();
1182 }
1183 state.pre_edit_text.take();
1184 drop(state);
1185 window.handle_ime(ImeInput::DeleteText);
1186 window.set_focused(false);
1187 }
1188 }
1189 wl_keyboard::Event::Modifiers {
1190 mods_depressed,
1191 mods_latched,
1192 mods_locked,
1193 group,
1194 ..
1195 } => {
1196 let focused_window = state.keyboard_focused_window.clone();
1197
1198 let keymap_state = state.keymap_state.as_mut().unwrap();
1199 let old_layout =
1200 keymap_state.serialize_layout(xkbcommon::xkb::STATE_LAYOUT_EFFECTIVE);
1201 keymap_state.update_mask(mods_depressed, mods_latched, mods_locked, 0, 0, group);
1202 state.modifiers = Modifiers::from_xkb(keymap_state);
1203
1204 if group != old_layout {
1205 if let Some(mut callback) = state.common.callbacks.keyboard_layout_change.take()
1206 {
1207 drop(state);
1208 callback();
1209 state = client.borrow_mut();
1210 state.common.callbacks.keyboard_layout_change = Some(callback);
1211 }
1212 }
1213
1214 let Some(focused_window) = focused_window else {
1215 return;
1216 };
1217
1218 let input = PlatformInput::ModifiersChanged(ModifiersChangedEvent {
1219 modifiers: state.modifiers,
1220 });
1221
1222 drop(state);
1223 focused_window.handle_input(input);
1224 }
1225 wl_keyboard::Event::Key {
1226 serial,
1227 key,
1228 state: WEnum::Value(key_state),
1229 ..
1230 } => {
1231 state.serial_tracker.update(SerialKind::KeyPress, serial);
1232
1233 let focused_window = state.keyboard_focused_window.clone();
1234 let Some(focused_window) = focused_window else {
1235 return;
1236 };
1237 let focused_window = focused_window.clone();
1238
1239 let keymap_state = state.keymap_state.as_ref().unwrap();
1240 let keycode = Keycode::from(key + MIN_KEYCODE);
1241 let keysym = keymap_state.key_get_one_sym(keycode);
1242
1243 match key_state {
1244 wl_keyboard::KeyState::Pressed if !keysym.is_modifier_key() => {
1245 let mut keystroke =
1246 Keystroke::from_xkb(&keymap_state, state.modifiers, keycode);
1247 if let Some(mut compose) = state.compose_state.take() {
1248 compose.feed(keysym);
1249 match compose.status() {
1250 xkb::Status::Composing => {
1251 keystroke.key_char = None;
1252 state.pre_edit_text =
1253 compose.utf8().or(Keystroke::underlying_dead_key(keysym));
1254 let pre_edit =
1255 state.pre_edit_text.clone().unwrap_or(String::default());
1256 drop(state);
1257 focused_window.handle_ime(ImeInput::SetMarkedText(pre_edit));
1258 state = client.borrow_mut();
1259 }
1260
1261 xkb::Status::Composed => {
1262 state.pre_edit_text.take();
1263 keystroke.key_char = compose.utf8();
1264 if let Some(keysym) = compose.keysym() {
1265 keystroke.key = xkb::keysym_get_name(keysym);
1266 }
1267 }
1268 xkb::Status::Cancelled => {
1269 let pre_edit = state.pre_edit_text.take();
1270 let new_pre_edit = Keystroke::underlying_dead_key(keysym);
1271 state.pre_edit_text = new_pre_edit.clone();
1272 drop(state);
1273 if let Some(pre_edit) = pre_edit {
1274 focused_window.handle_ime(ImeInput::InsertText(pre_edit));
1275 }
1276 if let Some(current_key) = new_pre_edit {
1277 focused_window
1278 .handle_ime(ImeInput::SetMarkedText(current_key));
1279 }
1280 compose.feed(keysym);
1281 state = client.borrow_mut();
1282 }
1283 _ => {}
1284 }
1285 state.compose_state = Some(compose);
1286 }
1287 let input = PlatformInput::KeyDown(KeyDownEvent {
1288 keystroke: keystroke.clone(),
1289 is_held: false,
1290 });
1291
1292 state.repeat.current_id += 1;
1293 state.repeat.current_keycode = Some(keycode);
1294
1295 let rate = state.repeat.characters_per_second;
1296 let id = state.repeat.current_id;
1297 state
1298 .loop_handle
1299 .insert_source(Timer::from_duration(state.repeat.delay), {
1300 let input = PlatformInput::KeyDown(KeyDownEvent {
1301 keystroke,
1302 is_held: true,
1303 });
1304 move |_event, _metadata, this| {
1305 let mut client = this.get_client();
1306 let mut state = client.borrow_mut();
1307 let is_repeating = id == state.repeat.current_id
1308 && state.repeat.current_keycode.is_some()
1309 && state.keyboard_focused_window.is_some();
1310
1311 if !is_repeating || rate == 0 {
1312 return TimeoutAction::Drop;
1313 }
1314
1315 let focused_window =
1316 state.keyboard_focused_window.as_ref().unwrap().clone();
1317
1318 drop(state);
1319 focused_window.handle_input(input.clone());
1320
1321 TimeoutAction::ToDuration(Duration::from_secs(1) / rate)
1322 }
1323 })
1324 .unwrap();
1325
1326 drop(state);
1327 focused_window.handle_input(input);
1328 }
1329 wl_keyboard::KeyState::Released if !keysym.is_modifier_key() => {
1330 let input = PlatformInput::KeyUp(KeyUpEvent {
1331 keystroke: Keystroke::from_xkb(keymap_state, state.modifiers, keycode),
1332 });
1333
1334 if state.repeat.current_keycode == Some(keycode) {
1335 state.repeat.current_keycode = None;
1336 }
1337
1338 drop(state);
1339 focused_window.handle_input(input);
1340 }
1341 _ => {}
1342 }
1343 }
1344 _ => {}
1345 }
1346 }
1347}
1348impl Dispatch<zwp_text_input_v3::ZwpTextInputV3, ()> for WaylandClientStatePtr {
1349 fn event(
1350 this: &mut Self,
1351 text_input: &zwp_text_input_v3::ZwpTextInputV3,
1352 event: <zwp_text_input_v3::ZwpTextInputV3 as Proxy>::Event,
1353 _: &(),
1354 _: &Connection,
1355 _: &QueueHandle<Self>,
1356 ) {
1357 let client = this.get_client();
1358 let mut state = client.borrow_mut();
1359 match event {
1360 zwp_text_input_v3::Event::Enter { .. } => {
1361 drop(state);
1362 this.enable_ime();
1363 }
1364 zwp_text_input_v3::Event::Leave { .. } => {
1365 drop(state);
1366 this.disable_ime();
1367 }
1368 zwp_text_input_v3::Event::CommitString { text } => {
1369 state.composing = false;
1370 let Some(window) = state.keyboard_focused_window.clone() else {
1371 return;
1372 };
1373
1374 if let Some(commit_text) = text {
1375 drop(state);
1376 // IBus Intercepts keys like `a`, `b`, but those keys are needed for vim mode.
1377 // We should only send ASCII characters to Zed, otherwise a user could remap a letter like `か` or `相`.
1378 if commit_text.len() == 1 {
1379 window.handle_input(PlatformInput::KeyDown(KeyDownEvent {
1380 keystroke: Keystroke {
1381 modifiers: Modifiers::default(),
1382 key: commit_text.clone(),
1383 key_char: Some(commit_text),
1384 },
1385 is_held: false,
1386 }));
1387 } else {
1388 window.handle_ime(ImeInput::InsertText(commit_text));
1389 }
1390 }
1391 }
1392 zwp_text_input_v3::Event::PreeditString { text, .. } => {
1393 state.composing = true;
1394 state.ime_pre_edit = text;
1395 }
1396 zwp_text_input_v3::Event::Done { serial } => {
1397 let last_serial = state.serial_tracker.get(SerialKind::InputMethod);
1398 state.serial_tracker.update(SerialKind::InputMethod, serial);
1399 let Some(window) = state.keyboard_focused_window.clone() else {
1400 return;
1401 };
1402
1403 if let Some(text) = state.ime_pre_edit.take() {
1404 drop(state);
1405 window.handle_ime(ImeInput::SetMarkedText(text));
1406 if let Some(area) = window.get_ime_area() {
1407 text_input.set_cursor_rectangle(
1408 area.origin.x.0 as i32,
1409 area.origin.y.0 as i32,
1410 area.size.width.0 as i32,
1411 area.size.height.0 as i32,
1412 );
1413 if last_serial == serial {
1414 text_input.commit();
1415 }
1416 }
1417 } else {
1418 state.composing = false;
1419 drop(state);
1420 window.handle_ime(ImeInput::DeleteText);
1421 }
1422 }
1423 _ => {}
1424 }
1425 }
1426}
1427
1428fn linux_button_to_gpui(button: u32) -> Option<MouseButton> {
1429 // These values are coming from <linux/input-event-codes.h>.
1430 const BTN_LEFT: u32 = 0x110;
1431 const BTN_RIGHT: u32 = 0x111;
1432 const BTN_MIDDLE: u32 = 0x112;
1433 const BTN_SIDE: u32 = 0x113;
1434 const BTN_EXTRA: u32 = 0x114;
1435 const BTN_FORWARD: u32 = 0x115;
1436 const BTN_BACK: u32 = 0x116;
1437
1438 Some(match button {
1439 BTN_LEFT => MouseButton::Left,
1440 BTN_RIGHT => MouseButton::Right,
1441 BTN_MIDDLE => MouseButton::Middle,
1442 BTN_BACK | BTN_SIDE => MouseButton::Navigate(NavigationDirection::Back),
1443 BTN_FORWARD | BTN_EXTRA => MouseButton::Navigate(NavigationDirection::Forward),
1444 _ => return None,
1445 })
1446}
1447
1448impl Dispatch<wl_pointer::WlPointer, ()> for WaylandClientStatePtr {
1449 fn event(
1450 this: &mut Self,
1451 wl_pointer: &wl_pointer::WlPointer,
1452 event: wl_pointer::Event,
1453 _: &(),
1454 _: &Connection,
1455 _: &QueueHandle<Self>,
1456 ) {
1457 let mut client = this.get_client();
1458 let mut state = client.borrow_mut();
1459
1460 match event {
1461 wl_pointer::Event::Enter {
1462 serial,
1463 surface,
1464 surface_x,
1465 surface_y,
1466 ..
1467 } => {
1468 state.serial_tracker.update(SerialKind::MouseEnter, serial);
1469 state.mouse_location = Some(point(px(surface_x as f32), px(surface_y as f32)));
1470 state.button_pressed = None;
1471
1472 if let Some(window) = get_window(&mut state, &surface.id()) {
1473 state.mouse_focused_window = Some(window.clone());
1474
1475 if state.enter_token.is_some() {
1476 state.enter_token = None;
1477 }
1478 if let Some(style) = state.cursor_style {
1479 if let Some(cursor_shape_device) = &state.cursor_shape_device {
1480 cursor_shape_device.set_shape(serial, style.to_shape());
1481 } else {
1482 let scale = window.primary_output_scale();
1483 state.cursor.set_icon(
1484 &wl_pointer,
1485 serial,
1486 &style.to_icon_name(),
1487 scale,
1488 );
1489 }
1490 }
1491 drop(state);
1492 window.set_hovered(true);
1493 }
1494 }
1495 wl_pointer::Event::Leave { .. } => {
1496 if let Some(focused_window) = state.mouse_focused_window.clone() {
1497 let input = PlatformInput::MouseExited(MouseExitEvent {
1498 position: state.mouse_location.unwrap(),
1499 pressed_button: state.button_pressed,
1500 modifiers: state.modifiers,
1501 });
1502 state.mouse_focused_window = None;
1503 state.mouse_location = None;
1504 state.button_pressed = None;
1505
1506 drop(state);
1507 focused_window.handle_input(input);
1508 focused_window.set_hovered(false);
1509 }
1510 }
1511 wl_pointer::Event::Motion {
1512 surface_x,
1513 surface_y,
1514 ..
1515 } => {
1516 if state.mouse_focused_window.is_none() {
1517 return;
1518 }
1519 state.mouse_location = Some(point(px(surface_x as f32), px(surface_y as f32)));
1520
1521 if let Some(window) = state.mouse_focused_window.clone() {
1522 if state
1523 .keyboard_focused_window
1524 .as_ref()
1525 .map_or(false, |keyboard_window| window.ptr_eq(&keyboard_window))
1526 {
1527 state.enter_token = None;
1528 }
1529 let input = PlatformInput::MouseMove(MouseMoveEvent {
1530 position: state.mouse_location.unwrap(),
1531 pressed_button: state.button_pressed,
1532 modifiers: state.modifiers,
1533 });
1534 drop(state);
1535 window.handle_input(input);
1536 }
1537 }
1538 wl_pointer::Event::Button {
1539 serial,
1540 button,
1541 state: WEnum::Value(button_state),
1542 ..
1543 } => {
1544 state.serial_tracker.update(SerialKind::MousePress, serial);
1545 let button = linux_button_to_gpui(button);
1546 let Some(button) = button else { return };
1547 if state.mouse_focused_window.is_none() {
1548 return;
1549 }
1550 match button_state {
1551 wl_pointer::ButtonState::Pressed => {
1552 if let Some(window) = state.keyboard_focused_window.clone() {
1553 if state.composing && state.text_input.is_some() {
1554 drop(state);
1555 // text_input_v3 don't have something like a reset function
1556 this.disable_ime();
1557 this.enable_ime();
1558 window.handle_ime(ImeInput::UnmarkText);
1559 state = client.borrow_mut();
1560 } else if let (Some(text), Some(compose)) =
1561 (state.pre_edit_text.take(), state.compose_state.as_mut())
1562 {
1563 compose.reset();
1564 drop(state);
1565 window.handle_ime(ImeInput::InsertText(text));
1566 state = client.borrow_mut();
1567 }
1568 }
1569 let click_elapsed = state.click.last_click.elapsed();
1570
1571 if click_elapsed < DOUBLE_CLICK_INTERVAL
1572 && state
1573 .click
1574 .last_mouse_button
1575 .is_some_and(|prev_button| prev_button == button)
1576 && is_within_click_distance(
1577 state.click.last_location,
1578 state.mouse_location.unwrap(),
1579 )
1580 {
1581 state.click.current_count += 1;
1582 } else {
1583 state.click.current_count = 1;
1584 }
1585
1586 state.click.last_click = Instant::now();
1587 state.click.last_mouse_button = Some(button);
1588 state.click.last_location = state.mouse_location.unwrap();
1589
1590 state.button_pressed = Some(button);
1591
1592 if let Some(window) = state.mouse_focused_window.clone() {
1593 let input = PlatformInput::MouseDown(MouseDownEvent {
1594 button,
1595 position: state.mouse_location.unwrap(),
1596 modifiers: state.modifiers,
1597 click_count: state.click.current_count,
1598 first_mouse: state.enter_token.take().is_some(),
1599 });
1600 drop(state);
1601 window.handle_input(input);
1602 }
1603 }
1604 wl_pointer::ButtonState::Released => {
1605 state.button_pressed = None;
1606
1607 if let Some(window) = state.mouse_focused_window.clone() {
1608 let input = PlatformInput::MouseUp(MouseUpEvent {
1609 button,
1610 position: state.mouse_location.unwrap(),
1611 modifiers: state.modifiers,
1612 click_count: state.click.current_count,
1613 });
1614 drop(state);
1615 window.handle_input(input);
1616 }
1617 }
1618 _ => {}
1619 }
1620 }
1621
1622 // Axis Events
1623 wl_pointer::Event::AxisSource {
1624 axis_source: WEnum::Value(axis_source),
1625 } => {
1626 state.axis_source = axis_source;
1627 }
1628 wl_pointer::Event::Axis {
1629 axis: WEnum::Value(axis),
1630 value,
1631 ..
1632 } => {
1633 if state.axis_source == AxisSource::Wheel {
1634 return;
1635 }
1636 let axis = if state.modifiers.shift {
1637 wl_pointer::Axis::HorizontalScroll
1638 } else {
1639 axis
1640 };
1641 let axis_modifier = match axis {
1642 wl_pointer::Axis::VerticalScroll => state.vertical_modifier,
1643 wl_pointer::Axis::HorizontalScroll => state.horizontal_modifier,
1644 _ => 1.0,
1645 };
1646 state.scroll_event_received = true;
1647 let scroll_delta = state
1648 .continuous_scroll_delta
1649 .get_or_insert(point(px(0.0), px(0.0)));
1650 let modifier = 3.0;
1651 match axis {
1652 wl_pointer::Axis::VerticalScroll => {
1653 scroll_delta.y += px(value as f32 * modifier * axis_modifier);
1654 }
1655 wl_pointer::Axis::HorizontalScroll => {
1656 scroll_delta.x += px(value as f32 * modifier * axis_modifier);
1657 }
1658 _ => unreachable!(),
1659 }
1660 }
1661 wl_pointer::Event::AxisDiscrete {
1662 axis: WEnum::Value(axis),
1663 discrete,
1664 } => {
1665 state.scroll_event_received = true;
1666 let axis = if state.modifiers.shift {
1667 wl_pointer::Axis::HorizontalScroll
1668 } else {
1669 axis
1670 };
1671 let axis_modifier = match axis {
1672 wl_pointer::Axis::VerticalScroll => state.vertical_modifier,
1673 wl_pointer::Axis::HorizontalScroll => state.horizontal_modifier,
1674 _ => 1.0,
1675 };
1676
1677 let scroll_delta = state.discrete_scroll_delta.get_or_insert(point(0.0, 0.0));
1678 match axis {
1679 wl_pointer::Axis::VerticalScroll => {
1680 scroll_delta.y += discrete as f32 * axis_modifier * SCROLL_LINES;
1681 }
1682 wl_pointer::Axis::HorizontalScroll => {
1683 scroll_delta.x += discrete as f32 * axis_modifier * SCROLL_LINES;
1684 }
1685 _ => unreachable!(),
1686 }
1687 }
1688 wl_pointer::Event::AxisValue120 {
1689 axis: WEnum::Value(axis),
1690 value120,
1691 } => {
1692 state.scroll_event_received = true;
1693 let axis = if state.modifiers.shift {
1694 wl_pointer::Axis::HorizontalScroll
1695 } else {
1696 axis
1697 };
1698 let axis_modifier = match axis {
1699 wl_pointer::Axis::VerticalScroll => state.vertical_modifier,
1700 wl_pointer::Axis::HorizontalScroll => state.horizontal_modifier,
1701 _ => unreachable!(),
1702 };
1703
1704 let scroll_delta = state.discrete_scroll_delta.get_or_insert(point(0.0, 0.0));
1705 let wheel_percent = value120 as f32 / 120.0;
1706 match axis {
1707 wl_pointer::Axis::VerticalScroll => {
1708 scroll_delta.y += wheel_percent * axis_modifier * SCROLL_LINES;
1709 }
1710 wl_pointer::Axis::HorizontalScroll => {
1711 scroll_delta.x += wheel_percent * axis_modifier * SCROLL_LINES;
1712 }
1713 _ => unreachable!(),
1714 }
1715 }
1716 wl_pointer::Event::Frame => {
1717 if state.scroll_event_received {
1718 state.scroll_event_received = false;
1719 let continuous = state.continuous_scroll_delta.take();
1720 let discrete = state.discrete_scroll_delta.take();
1721 if let Some(continuous) = continuous {
1722 if let Some(window) = state.mouse_focused_window.clone() {
1723 let input = PlatformInput::ScrollWheel(ScrollWheelEvent {
1724 position: state.mouse_location.unwrap(),
1725 delta: ScrollDelta::Pixels(continuous),
1726 modifiers: state.modifiers,
1727 touch_phase: TouchPhase::Moved,
1728 });
1729 drop(state);
1730 window.handle_input(input);
1731 }
1732 } else if let Some(discrete) = discrete {
1733 if let Some(window) = state.mouse_focused_window.clone() {
1734 let input = PlatformInput::ScrollWheel(ScrollWheelEvent {
1735 position: state.mouse_location.unwrap(),
1736 delta: ScrollDelta::Lines(discrete),
1737 modifiers: state.modifiers,
1738 touch_phase: TouchPhase::Moved,
1739 });
1740 drop(state);
1741 window.handle_input(input);
1742 }
1743 }
1744 }
1745 }
1746 _ => {}
1747 }
1748 }
1749}
1750
1751impl Dispatch<wp_fractional_scale_v1::WpFractionalScaleV1, ObjectId> for WaylandClientStatePtr {
1752 fn event(
1753 this: &mut Self,
1754 _: &wp_fractional_scale_v1::WpFractionalScaleV1,
1755 event: <wp_fractional_scale_v1::WpFractionalScaleV1 as Proxy>::Event,
1756 surface_id: &ObjectId,
1757 _: &Connection,
1758 _: &QueueHandle<Self>,
1759 ) {
1760 let client = this.get_client();
1761 let mut state = client.borrow_mut();
1762
1763 let Some(window) = get_window(&mut state, surface_id) else {
1764 return;
1765 };
1766
1767 drop(state);
1768 window.handle_fractional_scale_event(event);
1769 }
1770}
1771
1772impl Dispatch<zxdg_toplevel_decoration_v1::ZxdgToplevelDecorationV1, ObjectId>
1773 for WaylandClientStatePtr
1774{
1775 fn event(
1776 this: &mut Self,
1777 _: &zxdg_toplevel_decoration_v1::ZxdgToplevelDecorationV1,
1778 event: zxdg_toplevel_decoration_v1::Event,
1779 surface_id: &ObjectId,
1780 _: &Connection,
1781 _: &QueueHandle<Self>,
1782 ) {
1783 let client = this.get_client();
1784 let mut state = client.borrow_mut();
1785 let Some(window) = get_window(&mut state, surface_id) else {
1786 return;
1787 };
1788
1789 drop(state);
1790 window.handle_toplevel_decoration_event(event);
1791 }
1792}
1793
1794impl Dispatch<wl_data_device::WlDataDevice, ()> for WaylandClientStatePtr {
1795 fn event(
1796 this: &mut Self,
1797 _: &wl_data_device::WlDataDevice,
1798 event: wl_data_device::Event,
1799 _: &(),
1800 _: &Connection,
1801 _: &QueueHandle<Self>,
1802 ) {
1803 let client = this.get_client();
1804 let mut state = client.borrow_mut();
1805
1806 match event {
1807 // Clipboard
1808 wl_data_device::Event::DataOffer { id: data_offer } => {
1809 state.data_offers.push(DataOffer::new(data_offer));
1810 if state.data_offers.len() > 2 {
1811 // At most we store a clipboard offer and a drag and drop offer.
1812 state.data_offers.remove(0).inner.destroy();
1813 }
1814 }
1815 wl_data_device::Event::Selection { id: data_offer } => {
1816 if let Some(offer) = data_offer {
1817 let offer = state
1818 .data_offers
1819 .iter()
1820 .find(|wrapper| wrapper.inner.id() == offer.id());
1821 let offer = offer.cloned();
1822 state.clipboard.set_offer(offer);
1823 } else {
1824 state.clipboard.set_offer(None);
1825 }
1826 }
1827
1828 // Drag and drop
1829 wl_data_device::Event::Enter {
1830 serial,
1831 surface,
1832 x,
1833 y,
1834 id: data_offer,
1835 } => {
1836 state.serial_tracker.update(SerialKind::DataDevice, serial);
1837 if let Some(data_offer) = data_offer {
1838 let Some(drag_window) = get_window(&mut state, &surface.id()) else {
1839 return;
1840 };
1841
1842 const ACTIONS: DndAction = DndAction::Copy;
1843 data_offer.set_actions(ACTIONS, ACTIONS);
1844
1845 let pipe = Pipe::new().unwrap();
1846 data_offer.receive(FILE_LIST_MIME_TYPE.to_string(), unsafe {
1847 BorrowedFd::borrow_raw(pipe.write.as_raw_fd())
1848 });
1849 let fd = pipe.read;
1850 drop(pipe.write);
1851
1852 let read_task = state.common.background_executor.spawn(async {
1853 let buffer = unsafe { read_fd(fd)? };
1854 let text = String::from_utf8(buffer)?;
1855 anyhow::Ok(text)
1856 });
1857
1858 let this = this.clone();
1859 state
1860 .common
1861 .foreground_executor
1862 .spawn(async move {
1863 let file_list = match read_task.await {
1864 Ok(list) => list,
1865 Err(err) => {
1866 log::error!("error reading drag and drop pipe: {err:?}");
1867 return;
1868 }
1869 };
1870
1871 let paths: SmallVec<[_; 2]> = file_list
1872 .lines()
1873 .filter_map(|path| Url::parse(path).log_err())
1874 .filter_map(|url| url.to_file_path().log_err())
1875 .collect();
1876 let position = Point::new(x.into(), y.into());
1877
1878 // Prevent dropping text from other programs.
1879 if paths.is_empty() {
1880 data_offer.destroy();
1881 return;
1882 }
1883
1884 let input = PlatformInput::FileDrop(FileDropEvent::Entered {
1885 position,
1886 paths: crate::ExternalPaths(paths),
1887 });
1888
1889 let client = this.get_client();
1890 let mut state = client.borrow_mut();
1891 state.drag.data_offer = Some(data_offer);
1892 state.drag.window = Some(drag_window.clone());
1893 state.drag.position = position;
1894
1895 drop(state);
1896 drag_window.handle_input(input);
1897 })
1898 .detach();
1899 }
1900 }
1901 wl_data_device::Event::Motion { x, y, .. } => {
1902 let Some(drag_window) = state.drag.window.clone() else {
1903 return;
1904 };
1905 let position = Point::new(x.into(), y.into());
1906 state.drag.position = position;
1907
1908 let input = PlatformInput::FileDrop(FileDropEvent::Pending { position });
1909 drop(state);
1910 drag_window.handle_input(input);
1911 }
1912 wl_data_device::Event::Leave => {
1913 let Some(drag_window) = state.drag.window.clone() else {
1914 return;
1915 };
1916 let data_offer = state.drag.data_offer.clone().unwrap();
1917 data_offer.destroy();
1918
1919 state.drag.data_offer = None;
1920 state.drag.window = None;
1921
1922 let input = PlatformInput::FileDrop(FileDropEvent::Exited {});
1923 drop(state);
1924 drag_window.handle_input(input);
1925 }
1926 wl_data_device::Event::Drop => {
1927 let Some(drag_window) = state.drag.window.clone() else {
1928 return;
1929 };
1930 let data_offer = state.drag.data_offer.clone().unwrap();
1931 data_offer.finish();
1932 data_offer.destroy();
1933
1934 state.drag.data_offer = None;
1935 state.drag.window = None;
1936
1937 let input = PlatformInput::FileDrop(FileDropEvent::Submit {
1938 position: state.drag.position,
1939 });
1940 drop(state);
1941 drag_window.handle_input(input);
1942 }
1943 _ => {}
1944 }
1945 }
1946
1947 event_created_child!(WaylandClientStatePtr, wl_data_device::WlDataDevice, [
1948 wl_data_device::EVT_DATA_OFFER_OPCODE => (wl_data_offer::WlDataOffer, ()),
1949 ]);
1950}
1951
1952impl Dispatch<wl_data_offer::WlDataOffer, ()> for WaylandClientStatePtr {
1953 fn event(
1954 this: &mut Self,
1955 data_offer: &wl_data_offer::WlDataOffer,
1956 event: wl_data_offer::Event,
1957 _: &(),
1958 _: &Connection,
1959 _: &QueueHandle<Self>,
1960 ) {
1961 let client = this.get_client();
1962 let mut state = client.borrow_mut();
1963
1964 match event {
1965 wl_data_offer::Event::Offer { mime_type } => {
1966 // Drag and drop
1967 if mime_type == FILE_LIST_MIME_TYPE {
1968 let serial = state.serial_tracker.get(SerialKind::DataDevice);
1969 let mime_type = mime_type.clone();
1970 data_offer.accept(serial, Some(mime_type));
1971 }
1972
1973 // Clipboard
1974 if let Some(offer) = state
1975 .data_offers
1976 .iter_mut()
1977 .find(|wrapper| wrapper.inner.id() == data_offer.id())
1978 {
1979 offer.add_mime_type(mime_type);
1980 }
1981 }
1982 _ => {}
1983 }
1984 }
1985}
1986
1987impl Dispatch<wl_data_source::WlDataSource, ()> for WaylandClientStatePtr {
1988 fn event(
1989 this: &mut Self,
1990 data_source: &wl_data_source::WlDataSource,
1991 event: wl_data_source::Event,
1992 _: &(),
1993 _: &Connection,
1994 _: &QueueHandle<Self>,
1995 ) {
1996 let client = this.get_client();
1997 let mut state = client.borrow_mut();
1998
1999 match event {
2000 wl_data_source::Event::Send { mime_type, fd } => {
2001 state.clipboard.send(mime_type, fd);
2002 }
2003 wl_data_source::Event::Cancelled => {
2004 data_source.destroy();
2005 }
2006 _ => {}
2007 }
2008 }
2009}
2010
2011impl Dispatch<zwp_primary_selection_device_v1::ZwpPrimarySelectionDeviceV1, ()>
2012 for WaylandClientStatePtr
2013{
2014 fn event(
2015 this: &mut Self,
2016 _: &zwp_primary_selection_device_v1::ZwpPrimarySelectionDeviceV1,
2017 event: zwp_primary_selection_device_v1::Event,
2018 _: &(),
2019 _: &Connection,
2020 _: &QueueHandle<Self>,
2021 ) {
2022 let client = this.get_client();
2023 let mut state = client.borrow_mut();
2024
2025 match event {
2026 zwp_primary_selection_device_v1::Event::DataOffer { offer } => {
2027 let old_offer = state.primary_data_offer.replace(DataOffer::new(offer));
2028 if let Some(old_offer) = old_offer {
2029 old_offer.inner.destroy();
2030 }
2031 }
2032 zwp_primary_selection_device_v1::Event::Selection { id: data_offer } => {
2033 if data_offer.is_some() {
2034 let offer = state.primary_data_offer.clone();
2035 state.clipboard.set_primary_offer(offer);
2036 } else {
2037 state.clipboard.set_primary_offer(None);
2038 }
2039 }
2040 _ => {}
2041 }
2042 }
2043
2044 event_created_child!(WaylandClientStatePtr, zwp_primary_selection_device_v1::ZwpPrimarySelectionDeviceV1, [
2045 zwp_primary_selection_device_v1::EVT_DATA_OFFER_OPCODE => (zwp_primary_selection_offer_v1::ZwpPrimarySelectionOfferV1, ()),
2046 ]);
2047}
2048
2049impl Dispatch<zwp_primary_selection_offer_v1::ZwpPrimarySelectionOfferV1, ()>
2050 for WaylandClientStatePtr
2051{
2052 fn event(
2053 this: &mut Self,
2054 _data_offer: &zwp_primary_selection_offer_v1::ZwpPrimarySelectionOfferV1,
2055 event: zwp_primary_selection_offer_v1::Event,
2056 _: &(),
2057 _: &Connection,
2058 _: &QueueHandle<Self>,
2059 ) {
2060 let client = this.get_client();
2061 let mut state = client.borrow_mut();
2062
2063 match event {
2064 zwp_primary_selection_offer_v1::Event::Offer { mime_type } => {
2065 if let Some(offer) = state.primary_data_offer.as_mut() {
2066 offer.add_mime_type(mime_type);
2067 }
2068 }
2069 _ => {}
2070 }
2071 }
2072}
2073
2074impl Dispatch<zwp_primary_selection_source_v1::ZwpPrimarySelectionSourceV1, ()>
2075 for WaylandClientStatePtr
2076{
2077 fn event(
2078 this: &mut Self,
2079 selection_source: &zwp_primary_selection_source_v1::ZwpPrimarySelectionSourceV1,
2080 event: zwp_primary_selection_source_v1::Event,
2081 _: &(),
2082 _: &Connection,
2083 _: &QueueHandle<Self>,
2084 ) {
2085 let client = this.get_client();
2086 let mut state = client.borrow_mut();
2087
2088 match event {
2089 zwp_primary_selection_source_v1::Event::Send { mime_type, fd } => {
2090 state.clipboard.send_primary(mime_type, fd);
2091 }
2092 zwp_primary_selection_source_v1::Event::Cancelled => {
2093 selection_source.destroy();
2094 }
2095 _ => {}
2096 }
2097 }
2098}