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