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