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