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