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