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 KeycodeSource,
82 platform::{PlatformWindow, blade::BladeContext},
83};
84use crate::{
85 SharedString,
86 platform::linux::{
87 LinuxClient, get_xkb_compose_state, is_within_click_distance, open_uri_internal, read_fd,
88 reveal_path_internal,
89 wayland::{
90 clipboard::{Clipboard, DataOffer, FILE_LIST_MIME_TYPE, TEXT_MIME_TYPES},
91 cursor::Cursor,
92 serial::{SerialKind, SerialTracker},
93 window::WaylandWindow,
94 },
95 xdg_desktop_portal::{Event as XDPEvent, XDPEventSource},
96 },
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 keymap_state: Option<xkb::State>,
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 keymap_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.keymap_state = Some(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 keymap_state = state.keymap_state.as_mut().unwrap();
1258 let old_layout =
1259 keymap_state.serialize_layout(xkbcommon::xkb::STATE_LAYOUT_EFFECTIVE);
1260 keymap_state.update_mask(mods_depressed, mods_latched, mods_locked, 0, 0, group);
1261 state.modifiers = Modifiers::from_xkb(keymap_state);
1262 let keymap_state = state.keymap_state.as_mut().unwrap();
1263 state.capslock = Capslock::from_xkb(keymap_state);
1264
1265 let input = PlatformInput::ModifiersChanged(ModifiersChangedEvent {
1266 modifiers: state.modifiers,
1267 capslock: state.capslock,
1268 });
1269 drop(state);
1270
1271 if let Some(focused_window) = focused_window {
1272 focused_window.handle_input(input);
1273 }
1274
1275 if group != old_layout {
1276 this.handle_keyboard_layout_change();
1277 }
1278 }
1279 wl_keyboard::Event::Key {
1280 serial,
1281 key,
1282 state: WEnum::Value(key_state),
1283 ..
1284 } => {
1285 state.serial_tracker.update(SerialKind::KeyPress, serial);
1286
1287 let focused_window = state.keyboard_focused_window.clone();
1288 let Some(focused_window) = focused_window else {
1289 return;
1290 };
1291 let focused_window = focused_window.clone();
1292
1293 let keymap_state = state.keymap_state.as_ref().unwrap();
1294 let keycode = Keycode::from(key + MIN_KEYCODE);
1295 let keysym = keymap_state.key_get_one_sym(keycode);
1296
1297 match key_state {
1298 wl_keyboard::KeyState::Pressed if !keysym.is_modifier_key() => {
1299 let mut keystroke = Keystroke::from_xkb(
1300 &keymap_state,
1301 state.modifiers,
1302 keycode,
1303 KeycodeSource::Wayland,
1304 );
1305 if let Some(mut compose) = state.compose_state.take() {
1306 compose.feed(keysym);
1307 match compose.status() {
1308 xkb::Status::Composing => {
1309 keystroke.key_char = None;
1310 state.pre_edit_text =
1311 compose.utf8().or(Keystroke::underlying_dead_key(keysym));
1312 let pre_edit =
1313 state.pre_edit_text.clone().unwrap_or(String::default());
1314 drop(state);
1315 focused_window.handle_ime(ImeInput::SetMarkedText(pre_edit));
1316 state = client.borrow_mut();
1317 }
1318
1319 xkb::Status::Composed => {
1320 state.pre_edit_text.take();
1321 keystroke.key_char = compose.utf8();
1322 if let Some(keysym) = compose.keysym() {
1323 keystroke.key = xkb::keysym_get_name(keysym);
1324 }
1325 }
1326 xkb::Status::Cancelled => {
1327 let pre_edit = state.pre_edit_text.take();
1328 let new_pre_edit = Keystroke::underlying_dead_key(keysym);
1329 state.pre_edit_text = new_pre_edit.clone();
1330 drop(state);
1331 if let Some(pre_edit) = pre_edit {
1332 focused_window.handle_ime(ImeInput::InsertText(pre_edit));
1333 }
1334 if let Some(current_key) = new_pre_edit {
1335 focused_window
1336 .handle_ime(ImeInput::SetMarkedText(current_key));
1337 }
1338 compose.feed(keysym);
1339 state = client.borrow_mut();
1340 }
1341 _ => {}
1342 }
1343 state.compose_state = Some(compose);
1344 }
1345 let input = PlatformInput::KeyDown(KeyDownEvent {
1346 keystroke: keystroke.clone(),
1347 is_held: false,
1348 });
1349
1350 state.repeat.current_id += 1;
1351 state.repeat.current_keycode = Some(keycode);
1352
1353 let rate = state.repeat.characters_per_second;
1354 let id = state.repeat.current_id;
1355 state
1356 .loop_handle
1357 .insert_source(Timer::from_duration(state.repeat.delay), {
1358 let input = PlatformInput::KeyDown(KeyDownEvent {
1359 keystroke,
1360 is_held: true,
1361 });
1362 move |_event, _metadata, this| {
1363 let mut client = this.get_client();
1364 let mut state = client.borrow_mut();
1365 let is_repeating = id == state.repeat.current_id
1366 && state.repeat.current_keycode.is_some()
1367 && state.keyboard_focused_window.is_some();
1368
1369 if !is_repeating || rate == 0 {
1370 return TimeoutAction::Drop;
1371 }
1372
1373 let focused_window =
1374 state.keyboard_focused_window.as_ref().unwrap().clone();
1375
1376 drop(state);
1377 focused_window.handle_input(input.clone());
1378
1379 TimeoutAction::ToDuration(Duration::from_secs(1) / rate)
1380 }
1381 })
1382 .unwrap();
1383
1384 drop(state);
1385 focused_window.handle_input(input);
1386 }
1387 wl_keyboard::KeyState::Released if !keysym.is_modifier_key() => {
1388 let input = PlatformInput::KeyUp(KeyUpEvent {
1389 keystroke: Keystroke::from_xkb(
1390 keymap_state,
1391 state.modifiers,
1392 keycode,
1393 KeycodeSource::Wayland,
1394 ),
1395 });
1396
1397 if state.repeat.current_keycode == Some(keycode) {
1398 state.repeat.current_keycode = None;
1399 }
1400
1401 drop(state);
1402 focused_window.handle_input(input);
1403 }
1404 _ => {}
1405 }
1406 }
1407 _ => {}
1408 }
1409 }
1410}
1411
1412impl Dispatch<zwp_text_input_v3::ZwpTextInputV3, ()> for WaylandClientStatePtr {
1413 fn event(
1414 this: &mut Self,
1415 text_input: &zwp_text_input_v3::ZwpTextInputV3,
1416 event: <zwp_text_input_v3::ZwpTextInputV3 as Proxy>::Event,
1417 _: &(),
1418 _: &Connection,
1419 _: &QueueHandle<Self>,
1420 ) {
1421 let client = this.get_client();
1422 let mut state = client.borrow_mut();
1423 match event {
1424 zwp_text_input_v3::Event::Enter { .. } => {
1425 drop(state);
1426 this.enable_ime();
1427 }
1428 zwp_text_input_v3::Event::Leave { .. } => {
1429 drop(state);
1430 this.disable_ime();
1431 }
1432 zwp_text_input_v3::Event::CommitString { text } => {
1433 state.composing = false;
1434 let Some(window) = state.keyboard_focused_window.clone() else {
1435 return;
1436 };
1437
1438 if let Some(commit_text) = text {
1439 drop(state);
1440 // IBus Intercepts keys like `a`, `b`, but those keys are needed for vim mode.
1441 // We should only send ASCII characters to Zed, otherwise a user could remap a letter like `か` or `相`.
1442 if commit_text.len() == 1 {
1443 window.handle_input(PlatformInput::KeyDown(KeyDownEvent {
1444 keystroke: Keystroke {
1445 modifiers: Modifiers::default(),
1446 key: commit_text.clone(),
1447 key_char: Some(commit_text),
1448 },
1449 is_held: false,
1450 }));
1451 } else {
1452 window.handle_ime(ImeInput::InsertText(commit_text));
1453 }
1454 }
1455 }
1456 zwp_text_input_v3::Event::PreeditString { text, .. } => {
1457 state.composing = true;
1458 state.ime_pre_edit = text;
1459 }
1460 zwp_text_input_v3::Event::Done { serial } => {
1461 let last_serial = state.serial_tracker.get(SerialKind::InputMethod);
1462 state.serial_tracker.update(SerialKind::InputMethod, serial);
1463 let Some(window) = state.keyboard_focused_window.clone() else {
1464 return;
1465 };
1466
1467 if let Some(text) = state.ime_pre_edit.take() {
1468 drop(state);
1469 window.handle_ime(ImeInput::SetMarkedText(text));
1470 if let Some(area) = window.get_ime_area() {
1471 text_input.set_cursor_rectangle(
1472 area.origin.x.0 as i32,
1473 area.origin.y.0 as i32,
1474 area.size.width.0 as i32,
1475 area.size.height.0 as i32,
1476 );
1477 if last_serial == serial {
1478 text_input.commit();
1479 }
1480 }
1481 } else {
1482 state.composing = false;
1483 drop(state);
1484 window.handle_ime(ImeInput::DeleteText);
1485 }
1486 }
1487 _ => {}
1488 }
1489 }
1490}
1491
1492fn linux_button_to_gpui(button: u32) -> Option<MouseButton> {
1493 // These values are coming from <linux/input-event-codes.h>.
1494 const BTN_LEFT: u32 = 0x110;
1495 const BTN_RIGHT: u32 = 0x111;
1496 const BTN_MIDDLE: u32 = 0x112;
1497 const BTN_SIDE: u32 = 0x113;
1498 const BTN_EXTRA: u32 = 0x114;
1499 const BTN_FORWARD: u32 = 0x115;
1500 const BTN_BACK: u32 = 0x116;
1501
1502 Some(match button {
1503 BTN_LEFT => MouseButton::Left,
1504 BTN_RIGHT => MouseButton::Right,
1505 BTN_MIDDLE => MouseButton::Middle,
1506 BTN_BACK | BTN_SIDE => MouseButton::Navigate(NavigationDirection::Back),
1507 BTN_FORWARD | BTN_EXTRA => MouseButton::Navigate(NavigationDirection::Forward),
1508 _ => return None,
1509 })
1510}
1511
1512impl Dispatch<wl_pointer::WlPointer, ()> for WaylandClientStatePtr {
1513 fn event(
1514 this: &mut Self,
1515 wl_pointer: &wl_pointer::WlPointer,
1516 event: wl_pointer::Event,
1517 _: &(),
1518 _: &Connection,
1519 _: &QueueHandle<Self>,
1520 ) {
1521 let mut client = this.get_client();
1522 let mut state = client.borrow_mut();
1523
1524 match event {
1525 wl_pointer::Event::Enter {
1526 serial,
1527 surface,
1528 surface_x,
1529 surface_y,
1530 ..
1531 } => {
1532 state.serial_tracker.update(SerialKind::MouseEnter, serial);
1533 state.mouse_location = Some(point(px(surface_x as f32), px(surface_y as f32)));
1534 state.button_pressed = None;
1535
1536 if let Some(window) = get_window(&mut state, &surface.id()) {
1537 state.mouse_focused_window = Some(window.clone());
1538
1539 if state.enter_token.is_some() {
1540 state.enter_token = None;
1541 }
1542 if let Some(style) = state.cursor_style {
1543 if let CursorStyle::None = style {
1544 let wl_pointer = state
1545 .wl_pointer
1546 .clone()
1547 .expect("window is focused by pointer");
1548 wl_pointer.set_cursor(serial, None, 0, 0);
1549 } else if let Some(cursor_shape_device) = &state.cursor_shape_device {
1550 cursor_shape_device.set_shape(serial, style.to_shape());
1551 } else {
1552 let scale = window.primary_output_scale();
1553 state.cursor.set_icon(
1554 &wl_pointer,
1555 serial,
1556 style.to_icon_names(),
1557 scale,
1558 );
1559 }
1560 }
1561 drop(state);
1562 window.set_hovered(true);
1563 }
1564 }
1565 wl_pointer::Event::Leave { .. } => {
1566 if let Some(focused_window) = state.mouse_focused_window.clone() {
1567 let input = PlatformInput::MouseExited(MouseExitEvent {
1568 position: state.mouse_location.unwrap(),
1569 pressed_button: state.button_pressed,
1570 modifiers: state.modifiers,
1571 });
1572 state.mouse_focused_window = None;
1573 state.mouse_location = None;
1574 state.button_pressed = None;
1575
1576 drop(state);
1577 focused_window.handle_input(input);
1578 focused_window.set_hovered(false);
1579 }
1580 }
1581 wl_pointer::Event::Motion {
1582 surface_x,
1583 surface_y,
1584 ..
1585 } => {
1586 if state.mouse_focused_window.is_none() {
1587 return;
1588 }
1589 state.mouse_location = Some(point(px(surface_x as f32), px(surface_y as f32)));
1590
1591 if let Some(window) = state.mouse_focused_window.clone() {
1592 if state
1593 .keyboard_focused_window
1594 .as_ref()
1595 .map_or(false, |keyboard_window| window.ptr_eq(&keyboard_window))
1596 {
1597 state.enter_token = None;
1598 }
1599 let input = PlatformInput::MouseMove(MouseMoveEvent {
1600 position: state.mouse_location.unwrap(),
1601 pressed_button: state.button_pressed,
1602 modifiers: state.modifiers,
1603 });
1604 drop(state);
1605 window.handle_input(input);
1606 }
1607 }
1608 wl_pointer::Event::Button {
1609 serial,
1610 button,
1611 state: WEnum::Value(button_state),
1612 ..
1613 } => {
1614 state.serial_tracker.update(SerialKind::MousePress, serial);
1615 let button = linux_button_to_gpui(button);
1616 let Some(button) = button else { return };
1617 if state.mouse_focused_window.is_none() {
1618 return;
1619 }
1620 match button_state {
1621 wl_pointer::ButtonState::Pressed => {
1622 if let Some(window) = state.keyboard_focused_window.clone() {
1623 if state.composing && state.text_input.is_some() {
1624 drop(state);
1625 // text_input_v3 don't have something like a reset function
1626 this.disable_ime();
1627 this.enable_ime();
1628 window.handle_ime(ImeInput::UnmarkText);
1629 state = client.borrow_mut();
1630 } else if let (Some(text), Some(compose)) =
1631 (state.pre_edit_text.take(), state.compose_state.as_mut())
1632 {
1633 compose.reset();
1634 drop(state);
1635 window.handle_ime(ImeInput::InsertText(text));
1636 state = client.borrow_mut();
1637 }
1638 }
1639 let click_elapsed = state.click.last_click.elapsed();
1640
1641 if click_elapsed < DOUBLE_CLICK_INTERVAL
1642 && state
1643 .click
1644 .last_mouse_button
1645 .is_some_and(|prev_button| prev_button == button)
1646 && is_within_click_distance(
1647 state.click.last_location,
1648 state.mouse_location.unwrap(),
1649 )
1650 {
1651 state.click.current_count += 1;
1652 } else {
1653 state.click.current_count = 1;
1654 }
1655
1656 state.click.last_click = Instant::now();
1657 state.click.last_mouse_button = Some(button);
1658 state.click.last_location = state.mouse_location.unwrap();
1659
1660 state.button_pressed = Some(button);
1661
1662 if let Some(window) = state.mouse_focused_window.clone() {
1663 let input = PlatformInput::MouseDown(MouseDownEvent {
1664 button,
1665 position: state.mouse_location.unwrap(),
1666 modifiers: state.modifiers,
1667 click_count: state.click.current_count,
1668 first_mouse: state.enter_token.take().is_some(),
1669 });
1670 drop(state);
1671 window.handle_input(input);
1672 }
1673 }
1674 wl_pointer::ButtonState::Released => {
1675 state.button_pressed = None;
1676
1677 if let Some(window) = state.mouse_focused_window.clone() {
1678 let input = PlatformInput::MouseUp(MouseUpEvent {
1679 button,
1680 position: state.mouse_location.unwrap(),
1681 modifiers: state.modifiers,
1682 click_count: state.click.current_count,
1683 });
1684 drop(state);
1685 window.handle_input(input);
1686 }
1687 }
1688 _ => {}
1689 }
1690 }
1691
1692 // Axis Events
1693 wl_pointer::Event::AxisSource {
1694 axis_source: WEnum::Value(axis_source),
1695 } => {
1696 state.axis_source = axis_source;
1697 }
1698 wl_pointer::Event::Axis {
1699 axis: WEnum::Value(axis),
1700 value,
1701 ..
1702 } => {
1703 if state.axis_source == AxisSource::Wheel {
1704 return;
1705 }
1706 let axis = if state.modifiers.shift {
1707 wl_pointer::Axis::HorizontalScroll
1708 } else {
1709 axis
1710 };
1711 let axis_modifier = match axis {
1712 wl_pointer::Axis::VerticalScroll => state.vertical_modifier,
1713 wl_pointer::Axis::HorizontalScroll => state.horizontal_modifier,
1714 _ => 1.0,
1715 };
1716 state.scroll_event_received = true;
1717 let scroll_delta = state
1718 .continuous_scroll_delta
1719 .get_or_insert(point(px(0.0), px(0.0)));
1720 let modifier = 3.0;
1721 match axis {
1722 wl_pointer::Axis::VerticalScroll => {
1723 scroll_delta.y += px(value as f32 * modifier * axis_modifier);
1724 }
1725 wl_pointer::Axis::HorizontalScroll => {
1726 scroll_delta.x += px(value as f32 * modifier * axis_modifier);
1727 }
1728 _ => unreachable!(),
1729 }
1730 }
1731 wl_pointer::Event::AxisDiscrete {
1732 axis: WEnum::Value(axis),
1733 discrete,
1734 } => {
1735 state.scroll_event_received = true;
1736 let axis = if state.modifiers.shift {
1737 wl_pointer::Axis::HorizontalScroll
1738 } else {
1739 axis
1740 };
1741 let axis_modifier = match axis {
1742 wl_pointer::Axis::VerticalScroll => state.vertical_modifier,
1743 wl_pointer::Axis::HorizontalScroll => state.horizontal_modifier,
1744 _ => 1.0,
1745 };
1746
1747 let scroll_delta = state.discrete_scroll_delta.get_or_insert(point(0.0, 0.0));
1748 match axis {
1749 wl_pointer::Axis::VerticalScroll => {
1750 scroll_delta.y += discrete as f32 * axis_modifier * SCROLL_LINES;
1751 }
1752 wl_pointer::Axis::HorizontalScroll => {
1753 scroll_delta.x += discrete as f32 * axis_modifier * SCROLL_LINES;
1754 }
1755 _ => unreachable!(),
1756 }
1757 }
1758 wl_pointer::Event::AxisValue120 {
1759 axis: WEnum::Value(axis),
1760 value120,
1761 } => {
1762 state.scroll_event_received = true;
1763 let axis = if state.modifiers.shift {
1764 wl_pointer::Axis::HorizontalScroll
1765 } else {
1766 axis
1767 };
1768 let axis_modifier = match axis {
1769 wl_pointer::Axis::VerticalScroll => state.vertical_modifier,
1770 wl_pointer::Axis::HorizontalScroll => state.horizontal_modifier,
1771 _ => unreachable!(),
1772 };
1773
1774 let scroll_delta = state.discrete_scroll_delta.get_or_insert(point(0.0, 0.0));
1775 let wheel_percent = value120 as f32 / 120.0;
1776 match axis {
1777 wl_pointer::Axis::VerticalScroll => {
1778 scroll_delta.y += wheel_percent * axis_modifier * SCROLL_LINES;
1779 }
1780 wl_pointer::Axis::HorizontalScroll => {
1781 scroll_delta.x += wheel_percent * axis_modifier * SCROLL_LINES;
1782 }
1783 _ => unreachable!(),
1784 }
1785 }
1786 wl_pointer::Event::Frame => {
1787 if state.scroll_event_received {
1788 state.scroll_event_received = false;
1789 let continuous = state.continuous_scroll_delta.take();
1790 let discrete = state.discrete_scroll_delta.take();
1791 if let Some(continuous) = continuous {
1792 if let Some(window) = state.mouse_focused_window.clone() {
1793 let input = PlatformInput::ScrollWheel(ScrollWheelEvent {
1794 position: state.mouse_location.unwrap(),
1795 delta: ScrollDelta::Pixels(continuous),
1796 modifiers: state.modifiers,
1797 touch_phase: TouchPhase::Moved,
1798 });
1799 drop(state);
1800 window.handle_input(input);
1801 }
1802 } else if let Some(discrete) = discrete {
1803 if let Some(window) = state.mouse_focused_window.clone() {
1804 let input = PlatformInput::ScrollWheel(ScrollWheelEvent {
1805 position: state.mouse_location.unwrap(),
1806 delta: ScrollDelta::Lines(discrete),
1807 modifiers: state.modifiers,
1808 touch_phase: TouchPhase::Moved,
1809 });
1810 drop(state);
1811 window.handle_input(input);
1812 }
1813 }
1814 }
1815 }
1816 _ => {}
1817 }
1818 }
1819}
1820
1821impl Dispatch<wp_fractional_scale_v1::WpFractionalScaleV1, ObjectId> for WaylandClientStatePtr {
1822 fn event(
1823 this: &mut Self,
1824 _: &wp_fractional_scale_v1::WpFractionalScaleV1,
1825 event: <wp_fractional_scale_v1::WpFractionalScaleV1 as Proxy>::Event,
1826 surface_id: &ObjectId,
1827 _: &Connection,
1828 _: &QueueHandle<Self>,
1829 ) {
1830 let client = this.get_client();
1831 let mut state = client.borrow_mut();
1832
1833 let Some(window) = get_window(&mut state, surface_id) else {
1834 return;
1835 };
1836
1837 drop(state);
1838 window.handle_fractional_scale_event(event);
1839 }
1840}
1841
1842impl Dispatch<zxdg_toplevel_decoration_v1::ZxdgToplevelDecorationV1, ObjectId>
1843 for WaylandClientStatePtr
1844{
1845 fn event(
1846 this: &mut Self,
1847 _: &zxdg_toplevel_decoration_v1::ZxdgToplevelDecorationV1,
1848 event: zxdg_toplevel_decoration_v1::Event,
1849 surface_id: &ObjectId,
1850 _: &Connection,
1851 _: &QueueHandle<Self>,
1852 ) {
1853 let client = this.get_client();
1854 let mut state = client.borrow_mut();
1855 let Some(window) = get_window(&mut state, surface_id) else {
1856 return;
1857 };
1858
1859 drop(state);
1860 window.handle_toplevel_decoration_event(event);
1861 }
1862}
1863
1864impl Dispatch<wl_data_device::WlDataDevice, ()> for WaylandClientStatePtr {
1865 fn event(
1866 this: &mut Self,
1867 _: &wl_data_device::WlDataDevice,
1868 event: wl_data_device::Event,
1869 _: &(),
1870 _: &Connection,
1871 _: &QueueHandle<Self>,
1872 ) {
1873 let client = this.get_client();
1874 let mut state = client.borrow_mut();
1875
1876 match event {
1877 // Clipboard
1878 wl_data_device::Event::DataOffer { id: data_offer } => {
1879 state.data_offers.push(DataOffer::new(data_offer));
1880 if state.data_offers.len() > 2 {
1881 // At most we store a clipboard offer and a drag and drop offer.
1882 state.data_offers.remove(0).inner.destroy();
1883 }
1884 }
1885 wl_data_device::Event::Selection { id: data_offer } => {
1886 if let Some(offer) = data_offer {
1887 let offer = state
1888 .data_offers
1889 .iter()
1890 .find(|wrapper| wrapper.inner.id() == offer.id());
1891 let offer = offer.cloned();
1892 state.clipboard.set_offer(offer);
1893 } else {
1894 state.clipboard.set_offer(None);
1895 }
1896 }
1897
1898 // Drag and drop
1899 wl_data_device::Event::Enter {
1900 serial,
1901 surface,
1902 x,
1903 y,
1904 id: data_offer,
1905 } => {
1906 state.serial_tracker.update(SerialKind::DataDevice, serial);
1907 if let Some(data_offer) = data_offer {
1908 let Some(drag_window) = get_window(&mut state, &surface.id()) else {
1909 return;
1910 };
1911
1912 const ACTIONS: DndAction = DndAction::Copy;
1913 data_offer.set_actions(ACTIONS, ACTIONS);
1914
1915 let pipe = Pipe::new().unwrap();
1916 data_offer.receive(FILE_LIST_MIME_TYPE.to_string(), unsafe {
1917 BorrowedFd::borrow_raw(pipe.write.as_raw_fd())
1918 });
1919 let fd = pipe.read;
1920 drop(pipe.write);
1921
1922 let read_task = state.common.background_executor.spawn(async {
1923 let buffer = unsafe { read_fd(fd)? };
1924 let text = String::from_utf8(buffer)?;
1925 anyhow::Ok(text)
1926 });
1927
1928 let this = this.clone();
1929 state
1930 .common
1931 .foreground_executor
1932 .spawn(async move {
1933 let file_list = match read_task.await {
1934 Ok(list) => list,
1935 Err(err) => {
1936 log::error!("error reading drag and drop pipe: {err:?}");
1937 return;
1938 }
1939 };
1940
1941 let paths: SmallVec<[_; 2]> = file_list
1942 .lines()
1943 .filter_map(|path| Url::parse(path).log_err())
1944 .filter_map(|url| url.to_file_path().log_err())
1945 .collect();
1946 let position = Point::new(x.into(), y.into());
1947
1948 // Prevent dropping text from other programs.
1949 if paths.is_empty() {
1950 data_offer.destroy();
1951 return;
1952 }
1953
1954 let input = PlatformInput::FileDrop(FileDropEvent::Entered {
1955 position,
1956 paths: crate::ExternalPaths(paths),
1957 });
1958
1959 let client = this.get_client();
1960 let mut state = client.borrow_mut();
1961 state.drag.data_offer = Some(data_offer);
1962 state.drag.window = Some(drag_window.clone());
1963 state.drag.position = position;
1964
1965 drop(state);
1966 drag_window.handle_input(input);
1967 })
1968 .detach();
1969 }
1970 }
1971 wl_data_device::Event::Motion { x, y, .. } => {
1972 let Some(drag_window) = state.drag.window.clone() else {
1973 return;
1974 };
1975 let position = Point::new(x.into(), y.into());
1976 state.drag.position = position;
1977
1978 let input = PlatformInput::FileDrop(FileDropEvent::Pending { position });
1979 drop(state);
1980 drag_window.handle_input(input);
1981 }
1982 wl_data_device::Event::Leave => {
1983 let Some(drag_window) = state.drag.window.clone() else {
1984 return;
1985 };
1986 let data_offer = state.drag.data_offer.clone().unwrap();
1987 data_offer.destroy();
1988
1989 state.drag.data_offer = None;
1990 state.drag.window = None;
1991
1992 let input = PlatformInput::FileDrop(FileDropEvent::Exited {});
1993 drop(state);
1994 drag_window.handle_input(input);
1995 }
1996 wl_data_device::Event::Drop => {
1997 let Some(drag_window) = state.drag.window.clone() else {
1998 return;
1999 };
2000 let data_offer = state.drag.data_offer.clone().unwrap();
2001 data_offer.finish();
2002 data_offer.destroy();
2003
2004 state.drag.data_offer = None;
2005 state.drag.window = None;
2006
2007 let input = PlatformInput::FileDrop(FileDropEvent::Submit {
2008 position: state.drag.position,
2009 });
2010 drop(state);
2011 drag_window.handle_input(input);
2012 }
2013 _ => {}
2014 }
2015 }
2016
2017 event_created_child!(WaylandClientStatePtr, wl_data_device::WlDataDevice, [
2018 wl_data_device::EVT_DATA_OFFER_OPCODE => (wl_data_offer::WlDataOffer, ()),
2019 ]);
2020}
2021
2022impl Dispatch<wl_data_offer::WlDataOffer, ()> for WaylandClientStatePtr {
2023 fn event(
2024 this: &mut Self,
2025 data_offer: &wl_data_offer::WlDataOffer,
2026 event: wl_data_offer::Event,
2027 _: &(),
2028 _: &Connection,
2029 _: &QueueHandle<Self>,
2030 ) {
2031 let client = this.get_client();
2032 let mut state = client.borrow_mut();
2033
2034 match event {
2035 wl_data_offer::Event::Offer { mime_type } => {
2036 // Drag and drop
2037 if mime_type == FILE_LIST_MIME_TYPE {
2038 let serial = state.serial_tracker.get(SerialKind::DataDevice);
2039 let mime_type = mime_type.clone();
2040 data_offer.accept(serial, Some(mime_type));
2041 }
2042
2043 // Clipboard
2044 if let Some(offer) = state
2045 .data_offers
2046 .iter_mut()
2047 .find(|wrapper| wrapper.inner.id() == data_offer.id())
2048 {
2049 offer.add_mime_type(mime_type);
2050 }
2051 }
2052 _ => {}
2053 }
2054 }
2055}
2056
2057impl Dispatch<wl_data_source::WlDataSource, ()> for WaylandClientStatePtr {
2058 fn event(
2059 this: &mut Self,
2060 data_source: &wl_data_source::WlDataSource,
2061 event: wl_data_source::Event,
2062 _: &(),
2063 _: &Connection,
2064 _: &QueueHandle<Self>,
2065 ) {
2066 let client = this.get_client();
2067 let mut state = client.borrow_mut();
2068
2069 match event {
2070 wl_data_source::Event::Send { mime_type, fd } => {
2071 state.clipboard.send(mime_type, fd);
2072 }
2073 wl_data_source::Event::Cancelled => {
2074 data_source.destroy();
2075 }
2076 _ => {}
2077 }
2078 }
2079}
2080
2081impl Dispatch<zwp_primary_selection_device_v1::ZwpPrimarySelectionDeviceV1, ()>
2082 for WaylandClientStatePtr
2083{
2084 fn event(
2085 this: &mut Self,
2086 _: &zwp_primary_selection_device_v1::ZwpPrimarySelectionDeviceV1,
2087 event: zwp_primary_selection_device_v1::Event,
2088 _: &(),
2089 _: &Connection,
2090 _: &QueueHandle<Self>,
2091 ) {
2092 let client = this.get_client();
2093 let mut state = client.borrow_mut();
2094
2095 match event {
2096 zwp_primary_selection_device_v1::Event::DataOffer { offer } => {
2097 let old_offer = state.primary_data_offer.replace(DataOffer::new(offer));
2098 if let Some(old_offer) = old_offer {
2099 old_offer.inner.destroy();
2100 }
2101 }
2102 zwp_primary_selection_device_v1::Event::Selection { id: data_offer } => {
2103 if data_offer.is_some() {
2104 let offer = state.primary_data_offer.clone();
2105 state.clipboard.set_primary_offer(offer);
2106 } else {
2107 state.clipboard.set_primary_offer(None);
2108 }
2109 }
2110 _ => {}
2111 }
2112 }
2113
2114 event_created_child!(WaylandClientStatePtr, zwp_primary_selection_device_v1::ZwpPrimarySelectionDeviceV1, [
2115 zwp_primary_selection_device_v1::EVT_DATA_OFFER_OPCODE => (zwp_primary_selection_offer_v1::ZwpPrimarySelectionOfferV1, ()),
2116 ]);
2117}
2118
2119impl Dispatch<zwp_primary_selection_offer_v1::ZwpPrimarySelectionOfferV1, ()>
2120 for WaylandClientStatePtr
2121{
2122 fn event(
2123 this: &mut Self,
2124 _data_offer: &zwp_primary_selection_offer_v1::ZwpPrimarySelectionOfferV1,
2125 event: zwp_primary_selection_offer_v1::Event,
2126 _: &(),
2127 _: &Connection,
2128 _: &QueueHandle<Self>,
2129 ) {
2130 let client = this.get_client();
2131 let mut state = client.borrow_mut();
2132
2133 match event {
2134 zwp_primary_selection_offer_v1::Event::Offer { mime_type } => {
2135 if let Some(offer) = state.primary_data_offer.as_mut() {
2136 offer.add_mime_type(mime_type);
2137 }
2138 }
2139 _ => {}
2140 }
2141 }
2142}
2143
2144impl Dispatch<zwp_primary_selection_source_v1::ZwpPrimarySelectionSourceV1, ()>
2145 for WaylandClientStatePtr
2146{
2147 fn event(
2148 this: &mut Self,
2149 selection_source: &zwp_primary_selection_source_v1::ZwpPrimarySelectionSourceV1,
2150 event: zwp_primary_selection_source_v1::Event,
2151 _: &(),
2152 _: &Connection,
2153 _: &QueueHandle<Self>,
2154 ) {
2155 let client = this.get_client();
2156 let mut state = client.borrow_mut();
2157
2158 match event {
2159 zwp_primary_selection_source_v1::Event::Send { mime_type, fd } => {
2160 state.clipboard.send_primary(mime_type, fd);
2161 }
2162 zwp_primary_selection_source_v1::Event::Cancelled => {
2163 selection_source.destroy();
2164 }
2165 _ => {}
2166 }
2167 }
2168}