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