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