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