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