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